code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def set_contents_from_file(self, fp, headers=None, replace=True, cb=None, num_cb=10, policy=None, md5=None): """ Store an object in a file using the name of the Key object as the key in file URI and the contents of the file pointed to by 'fp' as the content...
Store an object in a file using the name of the Key object as the key in file URI and the contents of the file pointed to by 'fp' as the contents. :type fp: file :param fp: the file whose contents to upload :type headers: dict :param headers: ignored in this subclass. ...
def parse(item): r""" >>> Tag.parse('x') == {'key': 'x', 'value': None} True >>> Tag.parse('x=yes') == {'key': 'x', 'value': 'yes'} True >>> Tag.parse('x=3')['value'] '3' >>> Tag.parse('x=red fox\\:green eggs')['value'] 'red fox;green eggs' ...
r""" >>> Tag.parse('x') == {'key': 'x', 'value': None} True >>> Tag.parse('x=yes') == {'key': 'x', 'value': 'yes'} True >>> Tag.parse('x=3')['value'] '3' >>> Tag.parse('x=red fox\\:green eggs')['value'] 'red fox;green eggs' >>> Tag.parse('x=red...
def list_regions(self): """获得账号可见的区域的信息 列出当前用户所有可使用的区域。 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回区域列表,失败返回None - ResponseInfo 请求的Response信息 """ url = '{0}/v3/regions'.format(self.host) return http....
获得账号可见的区域的信息 列出当前用户所有可使用的区域。 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回区域列表,失败返回None - ResponseInfo 请求的Response信息
def listen(self, addr=None): """Wait for a connection/reconnection from a DCC peer. Returns the DCCConnection object. The local IP address and port are available as self.localaddress and self.localport. After connection from a peer, the peer address and port are available as ...
Wait for a connection/reconnection from a DCC peer. Returns the DCCConnection object. The local IP address and port are available as self.localaddress and self.localport. After connection from a peer, the peer address and port are available as self.peeraddress and self.peerpor...
def _color_dialog_changed(self, n, top, c): """ Updates the color of the slider. """ self._button_save.setEnabled(True) cp = self._colorpoint_list[n] # if they're linked, set both if self._checkboxes[n].isChecked(): self.modify_colorpoint(n, cp[0], [...
Updates the color of the slider.
def save_params_to_file(self, fname: str): """ Saves model parameters to file. :param fname: Path to save parameters to. """ if self.aux_params is not None: utils.save_params(self.params.copy(), fname, self.aux_params.copy()) else: utils.save_para...
Saves model parameters to file. :param fname: Path to save parameters to.
def estimateAnomalyLikelihoods(anomalyScores, averagingWindow=10, skipRecords=0, verbosity=0): """ Given a series of anomaly scores, compute the likelihood for each score. This function should be called once on a bunch of...
Given a series of anomaly scores, compute the likelihood for each score. This function should be called once on a bunch of historical anomaly scores for an initial estimate of the distribution. It should be called again every so often (say every 50 records) to update the estimate. :param anomalyScores: a list ...
def fit(self, X, y=None): """Fit distance-based AD. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Returns ------- self : object ...
Fit distance-based AD. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Returns ------- self : object Returns self.
def extract_stack(f=None, limit=None): """equivalent to traceback.extract_stack(), but also works with psyco """ if f is not None: raise RuntimeError("Timba.utils.extract_stack: f has to be None, don't ask why") # normally we can just use the traceback.extract_stack() function and # cut out ...
equivalent to traceback.extract_stack(), but also works with psyco
def course_run_detail(self, request, pk, course_id): # pylint: disable=invalid-name,unused-argument """ Return the metadata for the specified course run. The course run needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoi...
Return the metadata for the specified course run. The course run needs to be included in the specified EnterpriseCustomerCatalog in order for metadata to be returned from this endpoint.
async def acquire_lease_async(self, lease): """ Acquire the lease on the desired partition for this EventProcessorHost. Note that it is legal to acquire a lease that is already owned by another host. Lease-stealing is how partitions are redistributed when additional hosts are started. ...
Acquire the lease on the desired partition for this EventProcessorHost. Note that it is legal to acquire a lease that is already owned by another host. Lease-stealing is how partitions are redistributed when additional hosts are started. :param lease: The stored lease to be acquired. :t...
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None, ...
Formula for computing the current backoff :rtype: float
def showMenu(self, point): """ Displays the menu for this filter widget. """ menu = QMenu(self) acts = {} acts['edit'] = menu.addAction('Edit quick filter...') trigger = menu.exec_(self.mapToGlobal(point)) if trigger == acts['ed...
Displays the menu for this filter widget.
def open_unknown_proxy(self, proxy, fullurl, data=None): """Overridable interface to open unknown URL type.""" type, url = splittype(fullurl) raise IOError('url error', 'invalid proxy for %s' % type, proxy)
Overridable interface to open unknown URL type.
def get_type_string(self, data, type_string): """ Gets type string. Finds the type string for 'data' contained in ``python_type_strings`` using its ``type``. Non-``None`` 'type_string` overrides whatever type string is looked up. The override makes it easier for subclasses to co...
Gets type string. Finds the type string for 'data' contained in ``python_type_strings`` using its ``type``. Non-``None`` 'type_string` overrides whatever type string is looked up. The override makes it easier for subclasses to convert something that the parent marshaller can wri...
def to_int(argument): """ Converts the ``str`` argument to an integer: >>> from py_register_machine2.engine_tools.conversions import * >>> to_int("0x04") 4 >>> to_int("'a'") 97 """ if(argument.startswith("0b")): return int(argument[2:], 2) elif(argument.startswith("0x")): return int(argument[2:], 16) e...
Converts the ``str`` argument to an integer: >>> from py_register_machine2.engine_tools.conversions import * >>> to_int("0x04") 4 >>> to_int("'a'") 97
def _nginx_http_spec(port_spec, bridge_ip): """This will output the nginx HTTP config string for specific port spec """ server_string_spec = "\t server {\n" server_string_spec += "\t \t {}\n".format(_nginx_max_file_size_string()) server_string_spec += "\t \t {}\n".format(_nginx_listen_string(port_spec))...
This will output the nginx HTTP config string for specific port spec
def in6_getha(prefix): """ Return the anycast address associated with all home agents on a given subnet. """ r = in6_and(inet_pton(socket.AF_INET6, prefix), in6_cidr2mask(64)) r = in6_or(r, inet_pton(socket.AF_INET6, '::fdff:ffff:ffff:fffe')) return inet_ntop(socket.AF_INET6, r)
Return the anycast address associated with all home agents on a given subnet.
def update_host_password(host, username, password, new_password, protocol=None, port=None): ''' Update the password for a given host. .. note:: Currently only works with connections to ESXi hosts. Does not work with vCenter servers. host The location of the ESXi host. username The...
Update the password for a given host. .. note:: Currently only works with connections to ESXi hosts. Does not work with vCenter servers. host The location of the ESXi host. username The username used to login to the ESXi host, such as ``root``. password The password used to l...
def _search_files(self): """Retrieve the file paths stored under the base path.""" for root, _, files in os.walk(self.dirpath): for filename in files: location = os.path.join(root, filename) yield location
Retrieve the file paths stored under the base path.
def sweFixedStar(star, jd): """ Returns a fixed star from the Ephemeris. """ sweList = swisseph.fixstar_ut(star, jd) mag = swisseph.fixstar_mag(star) return { 'id': star, 'mag': mag, 'lon': sweList[0], 'lat': sweList[1] }
Returns a fixed star from the Ephemeris.
def dag(self) -> Tuple[Dict, Dict]: """Construct the DAG of this pipeline run based on the its operation runs and their downstream. """ from pipelines import dags operation_runs = self.operation_runs.all().prefetch_related('downstream_runs') def get_downstream(op_run): ...
Construct the DAG of this pipeline run based on the its operation runs and their downstream.
def search(cls, term=None, page=0, **criteria): """ Search a list of the model If you use "term": - Returns a collection of people that have a name matching the term passed in through the URL. If you use "criteria": - returns people who match your search criteria. ...
Search a list of the model If you use "term": - Returns a collection of people that have a name matching the term passed in through the URL. If you use "criteria": - returns people who match your search criteria. Search by any criteria you can on the Contacts tab, including cust...
def opt_grid_parallel(params, func, limits, ftol=0.01, disp=0, compute_errors=True): """ parallelized version of :func:`opt_grid` """ import multiprocessing def spawn(f): def fun(q_in,q_out): while True: i,x = q_in.get() if i == None: break q_out.put((i,f(x))) return fun ...
parallelized version of :func:`opt_grid`
def save_linked_hdds_info(self): """ Save linked cloned hard disks information. :returns: disk table information """ hdd_table = [] if self.linked_clone: if os.path.exists(self.working_dir): hdd_files = yield from self._get_all_hdd_files() ...
Save linked cloned hard disks information. :returns: disk table information
def reset(self): """ Reset the Quantum Abstract Machine to its initial state, which is particularly useful when it has gotten into an unwanted state. This can happen, for example, if the QAM is interrupted in the middle of a run. """ self._variables_shim = {} self...
Reset the Quantum Abstract Machine to its initial state, which is particularly useful when it has gotten into an unwanted state. This can happen, for example, if the QAM is interrupted in the middle of a run.
def get_new_client(self, public=True): """ Returns a new instance of the client for this endpoint. """ return self._get_client(public=public, cached=False)
Returns a new instance of the client for this endpoint.
def generate_host_keys(hostname: str) -> Iterator[str]: """Yield Chrome/Chromium keys for `hostname`, from least to most specific. Given a hostname like foo.example.com, this yields the key sequence: example.com .example.com foo.example.com .foo.example.com """ labels = hostname.split...
Yield Chrome/Chromium keys for `hostname`, from least to most specific. Given a hostname like foo.example.com, this yields the key sequence: example.com .example.com foo.example.com .foo.example.com
def vectored_io_from_metadata(md): # type: (dict) -> collections.namedtuple """Convert vectored io metadata in json metadata :param dict md: metadata dictionary :rtype: VectoredStripe or None :return: vectored io metadata """ try: mdattr = json.loads( md[JSON_KEY_BLOBXFER...
Convert vectored io metadata in json metadata :param dict md: metadata dictionary :rtype: VectoredStripe or None :return: vectored io metadata
def get_functions_overridden_by(self, function): ''' Return the list of functions overriden by the function Args: (core.Function) Returns: list(core.Function) ''' candidates = [c.functions_not_inherited for c in self.inheritance] candi...
Return the list of functions overriden by the function Args: (core.Function) Returns: list(core.Function)
def _intermediary_to_markdown(tables, relationships): """ Returns the er markup source in a string. """ t = '\n'.join(t.to_markdown() for t in tables) r = '\n'.join(r.to_markdown() for r in relationships) return '{}\n{}'.format(t, r)
Returns the er markup source in a string.
async def flush(self) -> None: """ Give the writer a chance to flush the pending data out of the internal buffer. """ async with self._flush_lock: if self.finished(): if self._exc: raise self._exc return ...
Give the writer a chance to flush the pending data out of the internal buffer.
def cudnn_stacked_bi_gru(units, n_hidden, seq_lengths=None, n_stacks=2, keep_prob=1.0, concat_stacked_outputs=False, trainable_initial_states=False, ...
Fast CuDNN Stacked Bi-GRU implementation Args: units: tf.Tensor with dimensions [B x T x F], where B - batch size T - number of tokens F - features n_hidden: dimensionality of hidden state seq_lengths: number of tokens in each sample in the batch ...
def get_minibam_bed(bamfile, bedfile, minibam=None): """ samtools view -L could do the work, but it is NOT random access. Here we are processing multiple regions sequentially. See also: https://www.biostars.org/p/49306/ """ pf = op.basename(bedfile).split(".")[0] minibamfile = minibam or op.bas...
samtools view -L could do the work, but it is NOT random access. Here we are processing multiple regions sequentially. See also: https://www.biostars.org/p/49306/
def get_data_home(data_home=None): """Return the path of the arviz data dir. This folder is used by some dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'arviz_data' in the user home folder. Alternatively, it can be set by the 'ARV...
Return the path of the arviz data dir. This folder is used by some dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'arviz_data' in the user home folder. Alternatively, it can be set by the 'ARVIZ_DATA' environment variable or progr...
def directive(apply_globally=False, api=None): """A decorator that registers a single hug directive""" def decorator(directive_method): if apply_globally: hug.defaults.directives[underscore(directive_method.__name__)] = directive_method else: apply_to_api = hug.API(api) i...
A decorator that registers a single hug directive
def verify_token(self, token, expiration_in_seconds=None): """ Verify token signature, verify token expiration, and decrypt token. | Returns None if token is expired or invalid. | Returns a list of strings and integers on success. Implemented as:: concatenated_str = self.d...
Verify token signature, verify token expiration, and decrypt token. | Returns None if token is expired or invalid. | Returns a list of strings and integers on success. Implemented as:: concatenated_str = self.decrypt_string(token, expiration_in_seconds) data_items = se...
def copytree(src, dst, symlinks=False, ignore=None): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree resu...
Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is f...
def apply(self, args, kwargs): """ Replicate a call to the encapsulated function. Unlike func(*args, **kwargs) the call is deterministic in the order kwargs are being checked by python. In other words, it behaves exactly the same as if typed into the repl prompt. This i...
Replicate a call to the encapsulated function. Unlike func(*args, **kwargs) the call is deterministic in the order kwargs are being checked by python. In other words, it behaves exactly the same as if typed into the repl prompt. This is usually only a problem when a function is given t...
def ssh_accept_sec_context(self, hostname, username, recv_token): """ Accept a SSPI context (server mode). :param str hostname: The servers FQDN :param str username: The name of the user who attempts to login :param str recv_token: The SSPI Token received from the server, ...
Accept a SSPI context (server mode). :param str hostname: The servers FQDN :param str username: The name of the user who attempts to login :param str recv_token: The SSPI Token received from the server, if it's not the initial call. :return: A ``String`` i...
def get_metrics(thing, extra=''): """Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active back...
Return MetricsInterface instance with specified name. The name is used as the prefix for all keys generated with this :py:class:`markus.main.MetricsInterface`. The :py:class:`markus.main.MetricsInterface` is not tied to metrics backends. The list of active backends are globally configured. This allows...
def do_commit(self, subcmd, opts, *args): """Send changes from your working copy to the repository. usage: commit [PATH...] A log message must be provided, but it can be empty. If it is not given by a --message or --file option, an editor will be started. ...
Send changes from your working copy to the repository. usage: commit [PATH...] A log message must be provided, but it can be empty. If it is not given by a --message or --file option, an editor will be started. ${cmd_option_list}
def getMaxDelay(inferences): """ Returns the maximum delay for the InferenceElements in the inference dictionary Parameters: ----------------------------------------------------------------------- inferences: A dictionary where the keys are InferenceElements """ maxDelay = 0 for i...
Returns the maximum delay for the InferenceElements in the inference dictionary Parameters: ----------------------------------------------------------------------- inferences: A dictionary where the keys are InferenceElements
def get_operator_statistic(self, name): """|coro| Gets the operator unique statistic from the operator definitions dict Returns ------- str the name of the operator unique statistic""" opdefs = yield from self.get_operator_definitions() name = name....
|coro| Gets the operator unique statistic from the operator definitions dict Returns ------- str the name of the operator unique statistic
def get_cancel_operation_by_id(cls, cancel_operation_id, **kwargs): """Find CancelOperation Return single instance of CancelOperation by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api...
Find CancelOperation Return single instance of CancelOperation by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_cancel_operation_by_id(cancel_operation_id, async=True) >>> result...
def strip_suffix(string, suffix, regex=False): """Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression.""" if not isinstance(string, six.string_types) or not isinstance(suffix, six.string_types): msg = 'Arguments to strip_suffix must be string type...
Strip the suffix from the string. If 'regex' is specified, suffix is understood as a regular expression.
def _get_rdfclass(self, class_type, **kwargs): """ returns the instanticated class from the class list args: class_type: dictionary with rdf_types """ def select_class(class_name): """ finds the class in the rdfclass Module""" try: ...
returns the instanticated class from the class list args: class_type: dictionary with rdf_types
def _populate_cparams(self, img_array, mct=None, cratios=None, psnr=None, cinema2k=None, cinema4k=None, irreversible=None, cbsize=None, eph=None, grid_offset=None, modesw=None, numres=None, prog=None, psizes=None, sop=None, ...
Directs processing of write method arguments. Parameters ---------- img_array : ndarray Image data to be written to file. kwargs : dictionary Non-image keyword inputs provided to write method.
def select_upstream(self, device: devicetools.Device) -> 'Selection': """Restrict the current selection to the network upstream of the given starting point, including the starting point itself. See the documentation on method |Selection.search_upstream| for additional information. ...
Restrict the current selection to the network upstream of the given starting point, including the starting point itself. See the documentation on method |Selection.search_upstream| for additional information.
def make_method_names(self): """Create tokens for setting __testname__ on functions""" lst = [] for group in self.all_groups: for single in group.singles: name, english = single.name, single.english if english[1:-1] != name.replace('_', ' '): ...
Create tokens for setting __testname__ on functions
def allele_support_df(loci, sources): """ Returns a DataFrame of allele counts for all given loci in the read sources """ return pandas.DataFrame( allele_support_rows(loci, sources), columns=EXPECTED_COLUMNS)
Returns a DataFrame of allele counts for all given loci in the read sources
def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) ...
Return a matching (possibly munged) command, if found in rule.
def build_casc(ObsData, hourly=True,level=9, months=None, avg_stats=True, percentile=50): '''Builds the cascade statistics of observed data for disaggregation Parameters ----------- ObsData : pd.Series hourly=True -> hourly obs data else -> 5...
Builds the cascade statistics of observed data for disaggregation Parameters ----------- ObsData : pd.Series hourly=True -> hourly obs data else -> 5min data (disaggregation level=9 (default), 10, 11) months : numpy array of ints Months for each seasons to be used for stati...
def create(self, path, data, **kwargs): """Create a file at the given path. :param data: ``bytes`` or a ``file``-like object to upload :param overwrite: If a file already exists, should it be overwritten? :type overwrite: bool :param blocksize: The block size of a file. ...
Create a file at the given path. :param data: ``bytes`` or a ``file``-like object to upload :param overwrite: If a file already exists, should it be overwritten? :type overwrite: bool :param blocksize: The block size of a file. :type blocksize: long :param replication: T...
def _analyze_read_write(self): """ Compute variables read/written/... """ write_var = [x.variables_written_as_expression for x in self.nodes] write_var = [x for x in write_var if x] write_var = [item for sublist in write_var for item in sublist] write_var = list(set(writ...
Compute variables read/written/...
def value(self): """ returns the object instead of instance """ if self._wrapped is not self.Null: return self._wrapped else: return self.obj
returns the object instead of instance
def CEscape(text, as_utf8): """Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it encodes unprintable characters using two-digit hex escapes whereas our C++ unescaping function allows hex escapes to be any length. So, "\0011".enco...
Escape a bytes string for use in an ascii protocol buffer. text.encode('string_escape') does not seem to satisfy our needs as it encodes unprintable characters using two-digit hex escapes whereas our C++ unescaping function allows hex escapes to be any length. So, "\0011".encode('string_escape') ends up being...
def deprecated(will_be=None, on_version=None, name=None): """ Function decorator that warns about deprecation upon function invocation. :param will_be: str representing the target action on the deprecated function :param on_version: tuple representing a SW version :param name: name of the entity to ...
Function decorator that warns about deprecation upon function invocation. :param will_be: str representing the target action on the deprecated function :param on_version: tuple representing a SW version :param name: name of the entity to be deprecated (useful when decorating __init__ methods so you can ...
def flags2text(self): """ parse the `self.flags` field and create a list of `CKF_*` strings corresponding to bits set in flags :return: a list of strings :rtype: list """ r = [] for v in self.flags_dict.keys(): if self.flags & v: ...
parse the `self.flags` field and create a list of `CKF_*` strings corresponding to bits set in flags :return: a list of strings :rtype: list
def setUp(self, tp): '''tp -- complexType/simpleContent/[Exention,Restriction] ''' self._item = tp assert tp.isComplex() is True and tp.content.isSimple() is True,\ 'expecting complexType/simpleContent not: %s' %tp.content.getItemTrace() simple = tp.content ...
tp -- complexType/simpleContent/[Exention,Restriction]
def git_merge(base, head, no_ff=False): # type: (str, str, bool) -> None """ Merge *head* into *base*. Args: base (str): The base branch. *head* will be merged into this branch. head (str): The branch that will be merged into *base*. no_ff (bool): ...
Merge *head* into *base*. Args: base (str): The base branch. *head* will be merged into this branch. head (str): The branch that will be merged into *base*. no_ff (bool): If set to **True** it will force git to create merge commit. If set to *...
def _linux_os_release(): """Try to determine the name of a Linux distribution. This function checks for the /etc/os-release file. It takes the name from the 'NAME' field and the version from 'VERSION_ID'. An empty string is returned if the above values cannot be determined. """ pretty_name = ''...
Try to determine the name of a Linux distribution. This function checks for the /etc/os-release file. It takes the name from the 'NAME' field and the version from 'VERSION_ID'. An empty string is returned if the above values cannot be determined.
def sampleCellsWithinColumns(numCellPairs, cellsPerColumn, numColumns, seed=42): """ Generate indices of cell pairs, each pair of cells are from the same column @return cellPairs (list) list of cell pairs """ np.random.seed(seed) cellPairs = [] for i in range(numCellPairs): randCol = np.random.randint...
Generate indices of cell pairs, each pair of cells are from the same column @return cellPairs (list) list of cell pairs
def add_node(self, node_or_ID, **kwds): """ Adds a node to the graph. """ if not isinstance(node_or_ID, Node): nodeID = str( node_or_ID ) if nodeID in self.nodes: node = self.nodes[ self.nodes.index(nodeID) ] else: if self.defau...
Adds a node to the graph.
def _copy_deploy_scripts_for_hosts(self, domains): """ Copy the deploy scripts for all the domains into the prefix scripts dir Args: domains(dict): spec with the domains info as when loaded from the initfile Returns: None """ with...
Copy the deploy scripts for all the domains into the prefix scripts dir Args: domains(dict): spec with the domains info as when loaded from the initfile Returns: None
def check_my_users(user): """Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords """ user_data = my_users.get(user['username']) if not user_data: return False # <--- invalid credentials elif user_data.get('passw...
Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords
def reset_permission_factories(self): """Remove cached permission factories.""" for key in ('read', 'create', 'update', 'delete'): full_key = '{0}_permission_factory'.format(key) if full_key in self.__dict__: del self.__dict__[full_key]
Remove cached permission factories.
def main(self, standalone=False): """Create interactive browser window. keyword arguments standalone -- Set to true, if the browser is not attached to other windows """ window = _Tkinter.Tk() sc = _TreeWidget.ScrolledCanvas(window, bg="white",\ ...
Create interactive browser window. keyword arguments standalone -- Set to true, if the browser is not attached to other windows
def prune_unspecified_categories(modules, categories): """ Removes unspecified module categories. Mutates dictionary and returns it. """ res = {} for mod_name, mod_info in modules.items(): mod_categories = mod_info.get("categories", all_categories) for category in categories: ...
Removes unspecified module categories. Mutates dictionary and returns it.
def get_location(self, location, columns=None, as_dict=False, index=True): """ For an index location and either (1) list of columns return a DataFrame or dictionary of the values or (2) single column name and return the value of that cell. This is optimized for speed because it does not need ...
For an index location and either (1) list of columns return a DataFrame or dictionary of the values or (2) single column name and return the value of that cell. This is optimized for speed because it does not need to lookup the index location with a search. Also can accept relative indexing from the end...
def create_widget(self): """ Create the toolkit widget for the proxy object. """ d = self.declaration button_type = UIButton.UIButtonTypeSystem if d.flat else UIButton.UIButtonTypeRoundedRect self.widget = UIButton(buttonWithType=button_type)
Create the toolkit widget for the proxy object.
def _from_dict_dict(cls, dic): """Takes a dict {id : dict_attributes} """ return cls({_convert_id(i): v for i, v in dic.items()})
Takes a dict {id : dict_attributes}
def beam_best_first(problem, beam_size=100, iterations_limit=0, viewer=None): ''' Beam search best first. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than th...
Beam search best first. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, SearchProblem.result, and SearchPr...
def get_artist_hotttnesss(self, cache=True): """Get our numerical description of how hottt a song's artist currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. ...
Get our numerical description of how hottt a song's artist currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing hotttnesss. ...
def has_parent_logs(self, log_id): """Tests if the ``Log`` has any parents. arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the log has parents, ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument -...
Tests if the ``Log`` has any parents. arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the log has parents, ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: Operat...
def setup_venv(self): """Setup virtualenv if necessary.""" venv = self.opts.venv if not venv: venv = os.environ.get('CRONY_VENV') if not venv and self.config['crony']: venv = self.config['crony'].get('venv') if venv: if not venv.endswit...
Setup virtualenv if necessary.
def csw_global_dispatch(request, url=None, catalog_id=None): """pycsw wrapper""" if request.user.is_authenticated(): # turn on CSW-T settings.REGISTRY_PYCSW['manager']['transactions'] = 'true' env = request.META.copy() # TODO: remove this workaround # HH should be able to pass env['wsgi....
pycsw wrapper
def check_backup_count_and_state(self, site): """Look up basebackups from the object store, prune any extra backups and return the datetime of the latest backup.""" basebackups = self.get_remote_basebackups_info(site) self.log.debug("Found %r basebackups", basebackups) if baseba...
Look up basebackups from the object store, prune any extra backups and return the datetime of the latest backup.
def distance_to_edge(self, skydir): """Return the angular distance from the given direction and the edge of the projection.""" xpix, ypix = skydir.to_pixel(self.wcs, origin=0) deltax = np.array((xpix - self._pix_center[0]) * self._pix_size[0], ndmin=1) ...
Return the angular distance from the given direction and the edge of the projection.
async def set_analog_latch(self, pin, threshold_type, threshold_value, cb=None, cb_type=None): """ This method "arms" an analog pin for its data to be latched and saved in the latching table If a callback method is provided, when latching criteria is achiev...
This method "arms" an analog pin for its data to be latched and saved in the latching table If a callback method is provided, when latching criteria is achieved, the callback function is called with latching data notification. Data returned in the callback list has the pin number as the...
def _ReadLine(self, file_object): """Reads a line from the file object. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the file-like object. """ if len(self._buffer) < self._buffer_size: content = file_object.read(self._buffer_size) content...
Reads a line from the file object. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the file-like object.
def encrypt_dynamodb_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Encrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item >>> plaintext_item = { ... 'some': {'S': 'data'}, ... 'more': {'N':...
Encrypt a DynamoDB item. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_dynamodb_item >>> plaintext_item = { ... 'some': {'S': 'data'}, ... 'more': {'N': '5'} ... } >>> encrypted_item = encrypt_dynamodb_item( ... item=plaintext_item, ... crypto_config=my_...
def _get_server(vm_, volumes, nics): ''' Construct server instance from cloud profile config ''' # Apply component overrides to the size from the cloud profile config vm_size = _override_size(vm_) # Set the server availability zone from the cloud profile config availability_zone = config.ge...
Construct server instance from cloud profile config
def same_disks(self, count=2): """ filter self to the required number of disks with same size and type Select the disks with the same type and same size. If not enough disks available, set self to empty. :param count: number of disks to retrieve :return: disk list """ ...
filter self to the required number of disks with same size and type Select the disks with the same type and same size. If not enough disks available, set self to empty. :param count: number of disks to retrieve :return: disk list
def _shutdown(self): """Gracefully shut down the consumer and exit.""" if self._channel: _log.info("Halting %r consumer sessions", self._channel.consumer_tags) self._running = False if self._connection and self._connection.is_open: self._connection.close() ...
Gracefully shut down the consumer and exit.
def decrypt(self, k, a, iv, e, t): """ Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication T...
Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication Tag Returns plaintext or raises an erro...
def linOriginRegression(points): """ computes a linear regression starting at zero """ j = sum([ i[0] for i in points ]) k = sum([ i[1] for i in points ]) if j != 0: return k/j, j, k return 1, j, k
computes a linear regression starting at zero
def update_params_for_auth(self, headers, querys, auth_settings): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication sett...
Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list.
def search_task_views(self, user, search_string): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :return: JSON response """ magic = self._magic_json( action=TouchWorksMagicConstants.ACTION_SEARCH_TASK_VIEWS, parameter1=us...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :return: JSON response
def solar_elevation(self, dateandtime, latitude, longitude): """Calculate the elevation angle of the sun. :param dateandtime: The date and time for which to calculate the angle. :type dateandtime: :class:`~datetime.datetime` :param latitude: Latitude - Nor...
Calculate the elevation angle of the sun. :param dateandtime: The date and time for which to calculate the angle. :type dateandtime: :class:`~datetime.datetime` :param latitude: Latitude - Northern latitudes should be positive :type latitude: float ...
def _LeaseFlowProcessingReqests(self, cursor=None): """Leases a number of flow processing requests.""" now = rdfvalue.RDFDatetime.Now() expiry = now + rdfvalue.Duration("10m") query = """ UPDATE flow_processing_requests SET leased_until=FROM_UNIXTIME(%(expiry)s), leased_by=%(id)s WHER...
Leases a number of flow processing requests.
def default_validity_start(): """ Sets validity_start field to 1 day before the current date (avoids "certificate not valid yet" edge case). In some cases, because of timezone differences, when certificates were just created they were considered valid in a timezone (eg: Europe) but not yet vali...
Sets validity_start field to 1 day before the current date (avoids "certificate not valid yet" edge case). In some cases, because of timezone differences, when certificates were just created they were considered valid in a timezone (eg: Europe) but not yet valid in another timezone (eg: US). This ...
def dvhat(s1): """ Find the unit vector corresponding to a state vector and the derivative of the unit vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvhat_c.html :param s1: State to be normalized. :type s1: 6-Element Array of floats :return: Unit vector s1 / abs(s1), and ...
Find the unit vector corresponding to a state vector and the derivative of the unit vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvhat_c.html :param s1: State to be normalized. :type s1: 6-Element Array of floats :return: Unit vector s1 / abs(s1), and its time derivative. :r...
def iscan(self, *, match=None, count=None): """Incrementally iterate the keys space using async for. Usage example: >>> async for key in redis.iscan(match='something*'): ... print('Matched:', key) """ return _ScanIter(lambda cur: self.scan(cur, ...
Incrementally iterate the keys space using async for. Usage example: >>> async for key in redis.iscan(match='something*'): ... print('Matched:', key)
def download_docs(client, output_filename=None, expanded=False): """ Given a LuminosoClient pointing to a project and a filename to write to, retrieve all its documents in batches, and write them to a JSON lines (.jsons) file with one document per line. """ if output_filename is None: # ...
Given a LuminosoClient pointing to a project and a filename to write to, retrieve all its documents in batches, and write them to a JSON lines (.jsons) file with one document per line.
def format_search_results(self, search_results): """Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in. """ formatted_lines = [] for search_result ...
Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in.
def _access_control(self, access_control, my_media_group=None): """ Prepares the extension element for access control Extension element is the optional parameter for the YouTubeVideoEntry We use extension element to modify access control settings Returns: tuple of ex...
Prepares the extension element for access control Extension element is the optional parameter for the YouTubeVideoEntry We use extension element to modify access control settings Returns: tuple of extension elements
def get_patches_ignore_regex(self): """Returns a string representing a regex for filtering out patches This string is parsed from a comment in the specfile that contains the word filter-out followed by an equal sign. For example, a comment as such: # patches_ignore=(regex) ...
Returns a string representing a regex for filtering out patches This string is parsed from a comment in the specfile that contains the word filter-out followed by an equal sign. For example, a comment as such: # patches_ignore=(regex) would mean this method returns the str...
def get_changes(self, commit_id, repository_id, project=None, top=None, skip=None): """GetChanges. Retrieve changes for a particular commit. :param str commit_id: The id of the commit. :param str repository_id: The id or friendly name of the repository. To use the friendly name, projectI...
GetChanges. Retrieve changes for a particular commit. :param str commit_id: The id of the commit. :param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified. :param str project: Project ID or project name :param...
def create(self, doc_details): ''' a method to create a new document in the collection :param doc_details: dictionary with document details and user id value :return: dictionary with document details and _id and _rev values ''' # https://developer.couchbase...
a method to create a new document in the collection :param doc_details: dictionary with document details and user id value :return: dictionary with document details and _id and _rev values