Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
384,700 | def _expectation(p, mean, none, kern, feat, nghp=None):
return tf.matrix_transpose(expectation(p, (kern, feat), mean)) | Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,} :: Linear kernel
or the equivalent for MarkovGaussian
:return: NxDxM |
384,701 | def load(self, typedef, value, **kwargs):
try:
bound_type = self.bound_types[typedef]
except KeyError:
raise DeclareException(
"Cant need to try/catch since load/dump are bound together
return bound_type["load"](value, **kwargs) | Return the result of the bound load method for a typedef
Looks up the load function that was bound to the engine for a typedef,
and return the result of passing the given `value` and any `context`
to that function.
Parameters
----------
typedef : :class:`~TypeDefinition... |
384,702 | def dispatch(self, *args, **kwargs):
return super(GenList, self).dispatch(*args, **kwargs) | Entry point for this class, here we decide basic stuff |
384,703 | def get(self):
self.log.info()
from operator import itemgetter
results = list(self.squareResults)
results = sorted(
results, key=itemgetter(), reverse=True)
headers = ["sdss_name", "type", "ra", "dec", "specz", "specz_err", "photoz",
... | *get the cone_search object*
**Return:**
- ``results`` -- the results of the conesearch |
384,704 | def __find_index(alig_file_pth, idx_extensions):
if idx_extensions is None:
return None
base, _ = os.path.splitext(alig_file_pth)
for idx_ext in idx_extensions:
candidate = base + os.extsep + idx_ext
if os.path.isfile(candidate):
return candidate
return None | Find an index file for a genome alignment file in the same directory.
:param alig_file_path: path to the alignment file.
:param idx_extensions: check for index files with these extensions
:return: path to first index file that matches the name of the alignment file
and has one of the specified extensi... |
384,705 | def tabulate(self, restricted_predicted_column_indices = [], restricted_predicted_column_names = [], dataset_name = None):
self._analyze()
data_series = self.get_series_names(column_indices = restricted_predicted_column_indices, column_names = restricted_predicted_column_names)
... | Returns summary analysis from the dataframe as a DataTable object.
DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful for combining multiple analyses.
DataTables can be printed to terminal as a tabular string using their representation functio... |
384,706 | def validate_config(config):
fields = [f for f in get_fields(config)]
if len(fields) != len(set(fields)):
raise InvalidConfigException(
"Invalid configuration file - %d duplicate field names" % len(fields) - len(set(fields))
)
return True | Validates the extractor configuration file. Ensures that there are no duplicate field names, etc.
:param config: The configuration file that contains the specification of the extractor
:return: True if config is valid, else raises a exception that specifies the correction to be made |
384,707 | def run_download_media(filename=None):
if not filename:
filename = settings.MEDIA_DUMP_FILENAME
if env.key_filename:
ssh = settings.PROJECT_NAME
else:
ssh = .format(env.user, env.host_string)
local(.format(
ssh, settings.FAB_SETTING(), filename)) | Downloads the media dump from the server into your local machine.
In order to import the downloaded media dump, run ``fab import_media``
Usage::
fab prod run_download_media
fab prod run_download_media:filename=foobar.tar.gz |
384,708 | def parse(self,tolerance=0,downsample=None,evidence=2,use_gene_names=False):
g = Graph()
nodes = [Node(x) for x in self._transcripts]
for n in nodes: g.add_node(n)
for i in range(0,len(nodes)):
for j in range(0,len(nodes)):
if i == j: continue
jov = nodes[... | Divide out the transcripts. allow junction tolerance if wanted |
384,709 | def compute_bin_edges(features, num_bins, edge_range, trim_outliers, trim_percentile, use_orig_distr=False):
"Compute the edges for the histogram bins to keep it the same for all nodes."
if use_orig_distr:
print()
edges=None
return edges
if edge_range is None:
if trim_outli... | Compute the edges for the histogram bins to keep it the same for all nodes. |
384,710 | def iter_prio_dict(prio_dict):
for _prio, objs in sorted(prio_dict.items(), key=lambda x: x[0]):
for obj in objs:
yield obj | Iterate over a priority dictionary. A priority dictionary is a
dictionary keyed by integer priority, with the values being lists
of objects. This generator will iterate over the dictionary in
priority order (from lowest integer value to highest integer
value), yielding each object in the lists in turn... |
384,711 | def save(self, filething=None, padding=None):
try:
self.tags._inject(filething.fileobj, padding)
except (IOError, error) as e:
reraise(self._Error, e, sys.exc_info()[2])
except EOFError:
raise self._Error("no appropriate stream found") | save(filething=None, padding=None)
Save a tag to a file.
If no filename is given, the one most recently loaded is used.
Args:
filething (filething)
padding (:obj:`mutagen.PaddingFunction`)
Raises:
mutagen.MutagenError |
384,712 | def features_node_edge_graph(obj):
points = {}
features = obj[]
for feature in tqdm(obj[]):
for (lon, lat) in geojson.utils.coords(feature):
points.setdefault((lon, lat), 0)
points[(lon, lat)] += 1
points = [p for (p, c) in points.items() if c > 1]
features = [ge... | Transform the features into a more graph-like structure by
appropriately splitting LineString features into two-point
"edges" that connect Point "nodes". |
384,713 | def most_by_mask(self, mask, y, mult):
idxs = np.where(mask)[0]
cnt = min(4, len(idxs))
return idxs[np.argsort(mult * self.probs[idxs,y])[:cnt]] | Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False every... |
384,714 | def get_form(self, request, obj=None, **kwargs):
parent_id = request.GET.get(, None)
if not parent_id:
parent_id = request.POST.get(, None)
if parent_id:
return AddFolderPopupForm
else:
folder_form = super(FolderAdmin, self).get_form(
... | Returns a Form class for use in the admin add view. This is used by
add_view and change_view. |
384,715 | def reset(self):
self.solved = False
self.niter = 0
self.iter_mis = []
self.F = None
self.system.dae.factorize = True | Reset all internal storage to initial status
Returns
-------
None |
384,716 | def gfrepi(window, begmss, endmss):
begmss = stypes.stringToCharP(begmss)
endmss = stypes.stringToCharP(endmss)
if not isinstance(window, ctypes.POINTER(stypes.SpiceCell)):
assert isinstance(window, stypes.SpiceCell)
assert window.is_double()
window = ctypes.byref(window)
... | This entry point initializes a search progress report.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrepi_c.html
:param window: A window over which a job is to be performed.
:type window: spiceypy.utils.support_types.SpiceCell
:param begmss: Beginning of the text portion of the output mess... |
384,717 | def parse_value(named_reg_value):
name, value, value_type = named_reg_value
value_class = REG_VALUE_TYPE_MAP[value_type]
return name, value_class(value) | Convert the value returned from EnumValue to a (name, value) tuple using the value classes. |
384,718 | def _getModelPosterior(self,min):
Sigma = self._getLaplaceCovar(min)
n_params = self.vd.getNumberScales()
ModCompl = 0.5*n_params*sp.log(2*sp.pi)+0.5*sp.log(sp.linalg.det(Sigma))
RV = min[]+ModCompl
return RV | USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR |
384,719 | def row_wise_rescale(matrix):
if matrix.shape[0] <= matrix.shape[1]:
raise ValueError(
)
min_ = matrix.min(axis=1)
range_ = matrix.ptp(axis=1)
min_tile = np.tile(min_, (matrix.shape[1], 1)).T
range_tile = np.tile(range_, (matrix.shape[1], 1)).T
range_t... | Row-wise rescale of a given matrix.
For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time.
Parameters
----------
matrix : ndarray
Input rectangular matrix, typically a carpet of size num_voxels x num_4th_dim, 4th_dim could be time points or g... |
384,720 | def batch_insert(self, records, typecast=False):
return self._batch_request(self.insert, records) | Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
To change the rate limit use ``airtable.API_LIMIT = 0.2``
(5 per second)
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> airtable.batch_insert(records)
Args:
records(``list``): Rec... |
384,721 | def to_graph_decomposition(H):
if not isinstance(H, UndirectedHypergraph):
raise TypeError("Transformation only applicable to \
undirected Hs")
G = UndirectedHypergraph()
nodes = [(node, H.get_node_attributes(node_attributes))
for node in G.node_iterator()... | Returns an UndirectedHypergraph object that has the same nodes (and
corresponding attributes) as the given H, except that for all
hyperedges in the given H, each node in the hyperedge is pairwise
connected to every other node also in that hyperedge in the new H.
Said another way, each of the original hy... |
384,722 | def saved(name,
source=,
user=None,
group=None,
mode=None,
attrs=None,
makedirs=False,
dir_mode=None,
replace=True,
backup=,
show_changes=True,
create=True,
tmp_dir=,
tmp_ext=,
enc... | .. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
name
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
source: ``running``
The configur... |
384,723 | def CI_calc(mean, SE, CV=1.96):
try:
CI_down = mean - CV * SE
CI_up = mean + CV * SE
return (CI_down, CI_up)
except Exception:
return ("None", "None") | Calculate confidence interval.
:param mean: mean of data
:type mean : float
:param SE: standard error of data
:type SE : float
:param CV: critical value
:type CV:float
:return: confidence interval as tuple |
384,724 | def initSchd_1_to_4(self):
self.m_schd_1_to_4["reserved_40"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_schd_1_to_4["Schedule_1_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
self.m_schd_1_to_4["Schedule_1_Period_1_Min"] = [2, FieldType.Int, S... | Initialize first tariff schedule :class:`~ekmmeters.SerialBlock`. |
384,725 | def get_current_future_chain(self, continuous_future, dt):
rf = self._roll_finders[continuous_future.roll_style]
session = self.trading_calendar.minute_to_session_label(dt)
contract_center = rf.get_contract_center(
continuous_future.root_symbol, session,
continuo... | Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the first index is the current
contract specified by the continuous future ... |
384,726 | def line(x_fn, y_fn, *, options={}, **interact_params):
fig = options.get(, False) or _create_fig(options=options)
[line] = (_create_marks(fig=fig, marks=[bq.Lines], options=options))
_add_marks(fig, [line])
def wrapped(**interact_params):
x_data = util.maybe_call(x_fn, interact_params, pr... | Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and... |
384,727 | def _apply_theme(self):
self.theme.apply_axs(self.axs)
self.theme.apply_figure(self.figure) | Apply theme attributes to Matplotlib objects |
384,728 | def unblock_username(username, pipe=None):
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if username:
pipe.delete(get_username_attempt_cache_key(username))
pipe.delete(get_username_blocked_cache_key(username))
if do_commit:
... | unblock the given Username |
384,729 | def sources_remove(source_uri, ruby=None, runas=None, gem_bin=None):
*
return _gem([, , source_uri],
ruby,
gem_bin=gem_bin,
runas=runas) | Remove a gem source.
:param source_uri: string
The source URI to remove.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
:... |
384,730 | def map_lazy(
self,
target: Callable,
map_iter: Sequence[Any] = None,
*,
map_args: Sequence[Sequence[Any]] = None,
args: Sequence = None,
map_kwargs: Sequence[Mapping[str, Any]] = None,
kwargs: Mapping = None,
pass_state: bool = False,
num_... | r"""
Functional equivalent of ``map()`` in-built function,
but executed in a parallel fashion.
Distributes the iterables,
provided in the ``map_*`` arguments to ``num_chunks`` no of worker nodes.
The idea is to:
1. Split the the iterables provided in the ``map_*`` a... |
384,731 | def bin(args):
p = OptionParser(bin.__doc__)
p.add_option("--dtype", choices=("float32", "int32"),
help="dtype of the matrix")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
tsvfile, = args
dtype = opts.dtype
if dtype is None: ... | %prog bin data.tsv
Conver tsv to binary format. |
384,732 | def remove_bucket(self, bucket_name):
is_valid_bucket_name(bucket_name)
self._url_open(, bucket_name=bucket_name)
self._delete_bucket_region(bucket_name) | Remove a bucket.
:param bucket_name: Bucket to remove |
384,733 | def raise_301(instance, location):
_set_location(instance, location)
instance.response.status = 301
raise ResponseException(instance.response) | Abort the current request with a 301 (Moved Permanently) response code.
Sets the Location header correctly. If the location does not start with a
slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.... |
384,734 | def startup_config_content(self, startup_config):
try:
startup_config_path = os.path.join(self.working_dir, "startup-config.cfg")
if startup_config is None:
startup_config =
if len(startup_config) == 0 and os.path.exists(startup_confi... | Update the startup config
:param startup_config: content of the startup configuration file |
384,735 | def querytime(self, value):
self._querytime = value
self.query.querytime = value | Sets self._querytime as well as self.query.querytime.
:param value: None or datetime
:return: |
384,736 | def weighted_axioms(self, x, y, xg):
scope_pairs = [
(, , 0.0, 0.0, 3.0,-0.8),
(, , 0.0, 0.0, 2.5,-0.5),
(, , -1.0, 1.0, 0.0, 0.0),
(, , 1.0,-1.0, 0.0, 0.0),
(, , 0.0, 0.0, 0.0, 0.0),
... | return a tuple (sub,sup,equiv,other) indicating estimated prior probabilities for an interpretation of a mapping
between x and y.
See kboom paper |
384,737 | def obfn_fvar(self, i):
r
return self.X[..., i] if self.opt[] else self.Y | r"""Variable to be evaluated in computing :math:`f_i(\cdot)`,
depending on the ``fEvalX`` option value. |
384,738 | def set_node_as_int(self, dst, src):
dst.value = self.value(src)
return True | Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
] |
384,739 | def citation_count(doi, url = "http://www.crossref.org/openurl/",
key = "cboettig@ropensci.org", **kwargs):
args = {"id": "doi:" + doi, "pid": key, "noredirect": True}
args = dict((k, v) for k, v in args.items() if v)
res = requests.get(url, params = args, headers = make_ua(), **kwargs)
xmldoc ... | Get a citation count with a DOI
:param doi: [String] DOI, digital object identifier
:param url: [String] the API url for the function (should be left to default)
:param keyc: [String] your API key
See http://labs.crossref.org/openurl/ for more info on this Crossref API service.
Usage::
f... |
384,740 | def readline(self, size=-1):
"Ignore the `size` since a complete line must be processed."
while True:
try:
record = next(self.reader)
except StopIteration:
break
if checks.record_is_valid(record):
if self.u... | Ignore the `size` since a complete line must be processed. |
384,741 | def inline(args):
trusted = args.trusted
args = load_config(args)
print("Args:")
pprint.pprint(args)
ret_code = 0
url = args.url
if args.repo_slug:
owner = args.repo_slug.split("/")[0]
repo = args.repo_slug.split("/")[1]
else:
owner = args.owner
... | Parse input file with the specified parser and post messages based on lint output
:param args: Contains the following
interface: How are we going to post comments?
owner: Username of repo owner
repo: Repository name
pr: Pull request ID
token: Authentication for repository
... |
384,742 | def _run_pre_command(self, pre_cmd):
logger.debug(, pre_cmd)
try:
pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True)
except OSError as err:
if err.errno == errno.ENOENT:
logger.debug(, pre_cmd)
return
stdout, std... | Run a pre command to get external args for a command |
384,743 | def list(self, log=values.unset, message_date_before=values.unset,
message_date=values.unset, message_date_after=values.unset, limit=None,
page_size=None):
return list(self.stream(
log=log,
message_date_before=message_date_before,
message_da... | Lists NotificationInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode log: Filter by log level
:param date message_date_before: Filter by date
:param date message_date: Filte... |
384,744 | def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(, , required=True,
action=, help=)
arg_parser.add_argument(, , required=True,
dest=, action=, help=)
arg_parser.add_argument(, , dest=,
... | main routine |
384,745 | def list(self, request, *args, **kwargs):
return super(SshKeyViewSet, self).list(request, *args, **kwargs) | To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user.
A new SSH key can be created by any active users. Example of a valid request:
.. code-block:: http
POST /api/keys/ HTTP/1.1
Content-Type: application/json
Accept: application/json
... |
384,746 | def moderate_model(ParentModel, publication_date_field=None, enable_comments_field=None):
attrs = {
: publication_date_field,
: publication_date_field,
: enable_comments_field,
}
ModerationClass = type(ParentModel.__name__ + , (FluentCommentsModerator,), attrs)
moderator.reg... | Register a parent model (e.g. ``Blog`` or ``Article``) that should receive comment moderation.
:param ParentModel: The parent model, e.g. a ``Blog`` or ``Article`` model.
:param publication_date_field: The field name of a :class:`~django.db.models.DateTimeField` in the parent model which stores the publication... |
384,747 | def sign(self, msg, key):
if not isinstance(key, rsa.RSAPrivateKey):
raise TypeError(
"The key must be an instance of rsa.RSAPrivateKey")
sig = key.sign(msg, self.padding, self.hash)
return sig | Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes |
384,748 | def ngettext(*args, **kwargs):
is_plural = args[2] > 1
if not is_plural:
key = args[0]
key_match = TRANSLATION_KEY_RE.match(key)
else:
key = args[1]
key_match = PLURAL_TRANSLATION_KEY_RE.match(key)
translation = _ngettext(*args, **kwargs)
if not key_match or tra... | Like :func:`gettext`, except it supports pluralization. |
384,749 | def _get_module_filename(module):
module = module.split()
package = .join(module[:-1])
module = module[-1]
try:
if not package:
module = __import__(module)
else:
package = __import__(package, fromlist=[module])
... | Return the filename of `module` if it can be imported.
If `module` is a package, its directory will be returned.
If it cannot be imported ``None`` is returned.
If the ``__file__`` attribute is missing, or the module or package is a
compiled egg, then an :class:`Unparseable` instance is returned, sinc... |
384,750 | def mask_plane(data, wcs, region, negate=False):
indexes = np.empty((data.shape[0]*data.shape[1], 2), dtype=int)
idx = np.array([(j, 0) for j in range(data.shape[1])])
j = data.shape[1]
for i in range(data.shape[0]):
idx[:, 1] = i
indexes[i*j:(i+1)*j] = idx
... | Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`
A region within which the image pixels will be maske... |
384,751 | def _dimension_keys(self):
return [tuple(zip([d.name for d in self.kdims], [k] if self.ndims == 1 else k))
for k in self.keys()] | Helper for __mul__ that returns the list of keys together with
the dimension labels. |
384,752 | def validate_query_params(self, strict=True):
if not (self.api_key or default_api_key):
raise ValueError()
if strict and self.query_params_mode not in (None, , ):
raise ValueError()
if not self.person.is_searchable:
raise ValueError()
... | Check if the request is valid and can be sent, raise ValueError if
not.
`strict` is a boolean argument that defaults to True which means an
exception is raised on every invalid query parameter, if set to False
an exception is raised only when the search request cannot be ... |
384,753 | def prepare_state_m_for_insert_as(state_m_to_insert, previous_state_size):
if isinstance(state_m_to_insert, AbstractStateModel) and \
not gui_helper_meta_data.model_has_empty_meta(state_m_to_insert):
if isinstance(state_m_to_insert, ContainerStateModel):
... | Prepares and scales the meta data to fit into actual size of the state. |
384,754 | def from_xdr_object(cls, op_xdr_object):
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
, op_xdr_object.sourceAccount[0].ed25519).decode()
destination = encode_check(
,
op_xdr_object.body.pa... | Creates a :class:`Payment` object from an XDR Operation
object. |
384,755 | def _unrecognised(achr):
if options[] == UNRECOGNISED_ECHO:
return achr
elif options[] == UNRECOGNISED_SUBSTITUTE:
return options[]
else:
raise KeyError(achr) | Handle unrecognised characters. |
384,756 | def execute_pool_txns(self, three_pc_batch) -> List:
committed_txns = self.default_executer(three_pc_batch)
for txn in committed_txns:
self.poolManager.onPoolMembershipChange(txn)
return committed_txns | Execute a transaction that involves consensus pool management, like
adding a node, client or a steward.
:param ppTime: PrePrepare request time
:param reqs_keys: requests keys to be committed |
384,757 | def _get_app_auth_headers(self):
now = datetime.now(timezone.utc)
expiry = now + timedelta(minutes=5)
data = {"iat": now, "exp": expiry, "iss": self.app_id}
app_token = jwt.encode(data, self.app_key, algorithm="RS256").decode("utf-8")
headers = {
"Accept": ... | Set the correct auth headers to authenticate against GitHub. |
384,758 | def _resolve_model(obj):
if isinstance(obj, six.string_types) and len(obj.split()) == 2:
app_name, model_name = obj.split()
resolved_model = apps.get_model(app_name, model_name)
if resolved_model is None:
msg = "Django did not return a model for {0}.{1}"
raise Im... | Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key definition.
String representations... |
384,759 | def delete(self, using=None):
if self.is_alone:
self.topic.delete()
else:
super(AbstractPost, self).delete(using)
self.topic.update_trackers() | Deletes the post instance. |
384,760 | def dir(self, filetype, **kwargs):
full = kwargs.get(, None)
if not full:
full = self.full(filetype, **kwargs)
return os.path.dirname(full) | Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file. |
384,761 | def get_objective(self, objective_id=None):
if objective_id is None:
raise NullArgument()
url_path = construct_url(, obj_id=objective_id)
return objects.Objective(self._get_request(url_path)) | Gets the Objective specified by its Id.
In plenary mode, the exact Id is found or a NotFound results.
Otherwise, the returned Objective may have a different Id than
requested, such as the case where a duplicate Id was assigned to
an Objective and retained for compatibility.
arg: ... |
384,762 | def cast_to_subclass(self):
self.import_lib()
self.load_requirements()
try:
self.commit()
b = clz(self._dataset, self._library, self._source_url, self._build_url)
b.limited_run = self.limited_run
b.capture_exceptions = self.capture_exceptions
... | Load the bundle file from the database to get the derived bundle class,
then return a new bundle built on that class
:return: |
384,763 | def cloud_front_origin_access_identity_exists(Id, region=None, key=None, keyid=None, profile=None):
authargs = {: region, : key, : keyid, : profile}
oais = list_cloud_front_origin_access_identities(**authargs) or []
return bool([i[] for i in oais if i[] == Id]) | Return True if a CloudFront origin access identity exists with the given Resource ID or False
otherwise.
Id
Resource ID of the CloudFront origin access identity.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict... |
384,764 | def makeFigFromFile(filename,*args,**kwargs):
import matplotlib.pyplot as plt
img = plt.imread(filename)
fig,ax = plt.subplots(*args,**kwargs)
ax.axis()
ax.imshow(img)
return fig | Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots |
384,765 | def t_ID(self, t):
r
t.type = self.reserved.get(t.value, )
if t.type == :
t.value = node.Id(t.value, self.lineno, self.filename)
return t | r'[a-z][a-zA-Z0-9_]* |
384,766 | def resource(resource_id):
resource_obj = app.db.resource(resource_id)
if in request.args:
return send_from_directory(os.path.dirname(resource_obj.path),
os.path.basename(resource_obj.path))
return render_template(, resource=resource_obj) | Show a resource. |
384,767 | def global_set_option(self, opt, value):
self._all_options[opt].set_option(opt, value) | set option on the correct option provider |
384,768 | def get_urls(self):
not_clone_url = [url(r,
admin.site.admin_view(self.will_not_clone))]
restore_url = [
url(r, admin.site.admin_view(self.restore))]
return not_clone_url + restore_url + super(VersionedAdmin,
... | Appends the custom will_not_clone url to the admin site |
384,769 | def get_color_label(self):
if self.args.norm:
return .format(self.args.norm)
if len(self.units) == 1 and self.usetex:
return r.format(
self.units[0].to_string().strip())
elif len(self.units) == 1:
return .format(self.units[0].to_string... | Text for colorbar label |
384,770 | def load_plug_in(self, name):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
plug_in_name = self._call("loadPlugIn",
in_p=[name])
return plug_in_name | Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in. |
384,771 | def represent_datetime(self, d):
fixed_format = self.get()
if fixed_format:
rep = string_decode(d.strftime(fixed_format), )
else:
format_hook = self.get_hook()
if format_hook:
rep = string_decode(format_hook(d), )
else:
... | turns a given datetime obj into a string representation.
This will:
1) look if a fixed 'timestamp_format' is given in the config
2) check if a 'timestamp_format' hook is defined
3) use :func:`~alot.helper.pretty_datetime` as fallback |
384,772 | def _command(self, event, command, *args, **kwargs):
self._assert_transition(event)
self.trigger( % event, **kwargs)
self._execute_command(command, *args)
self.trigger( % event, **kwargs) | Context state controller.
Check whether the transition is possible or not, it executes it and
triggers the Hooks with the pre_* and post_* events.
@param event: (str) event generated by the command.
@param command: (virDomain.method) state transition to impose.
@raise: RuntimeE... |
384,773 | def encipher(self,string):
string = self.remove_punctuation(string,filter=+self.key+)
ctext = ""
for c in string:
ctext += .join([str(i) for i in L2IND[c]])
return ctext | Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The ciphertext will be 3 times the length of the p... |
384,774 | def _do_connection(self, wgt, sig, func):
if hasattr(self, wgt):
wgtobj = getattr(self, wgt)
if hasattr(wgtobj, sig):
sigobj = getattr(wgtobj, sig)
if isinstance(sigobj, Signal):
sigobj.conn... | Make a connection between a GUI widget and a callable.
wgt and sig are strings with widget and signal name
func is a callable for that signal |
384,775 | def set_child_value(self, name, value):
return XMLElement(lib.lsl_set_child_value(self.e,
str.encode(name),
str.encode(value))) | Set the text value of the (nameless) plain-text child of a named
child node. |
384,776 | def predict(self, X):
K = pairwise_kernels(self.X, X, metric=self.kernel, gamma=self.gamma)
return (K * self.y[:, None]).sum(axis=0) / K.sum(axis=0) | Predict target values for X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted target value. |
384,777 | def put(self, key):
self.client.write(self._key_path(key[]), **key)
return self._key_path(key[]) | Put and return the only unique identifier possible, its path |
384,778 | def vtrees(self):
self.connection._check_login()
response = self.connection._do_get("{}/{}".format(self.connection._api_url, "types/VTree/instances")).json()
all_vtrees = []
for vtree in response:
all_vtrees.append(
SIO_Vtree.from_dict(vtree)
... | Get list of VTrees from ScaleIO cluster
:return: List of VTree objects - Can be empty of no VTrees exist
:rtype: VTree object |
384,779 | def nodes(self):
return np.column_stack((self.points,
self.points)).reshape(
-1)[1:-1].reshape((-1, 2)) | Returns an (n,2) list of nodes, or vertices on the path.
Note that this generic class function assumes that all of the
reference points are on the path which is true for lines and
three point arcs.
If you were to define another class where that wasn't the case
(for example, the ... |
384,780 | def line_segment(X0, X1):
r
X0 = sp.around(X0).astype(int)
X1 = sp.around(X1).astype(int)
if len(X0) == 3:
L = sp.amax(sp.absolute([[X1[0]-X0[0]], [X1[1]-X0[1]], [X1[2]-X0[2]]])) + 1
x = sp.rint(sp.linspace(X0[0], X1[0], L)).astype(int)
y = sp.rint(sp.linspace(X0[1], X1[1], L)).a... | r"""
Calculate the voxel coordinates of a straight line between the two given
end points
Parameters
----------
X0 and X1 : array_like
The [x, y] or [x, y, z] coordinates of the start and end points of
the line.
Returns
-------
coords : list of lists
A list of li... |
384,781 | def selenol_params(**kwargs):
def params_decorator(func):
def service_function_wrapper(service, message):
params = {k: f(service, message) for k, f in kwargs.items()}
return func(service, **params)
return service_function_wrapper
return params_d... | Decorate request parameters to transform them into Selenol objects. |
384,782 | def load_grammar(self, path):
if not os.path.exists(path):
raise Exception("path does not exist: {!r}".format(path))
grammar_path = os.path.dirname(path)
if grammar_path not in... | Load a grammar file (python file containing grammar definitions) by
file path. When loaded, the global variable ``GRAMFUZZER`` will be set
within the module. This is not always needed, but can be useful.
:param str path: The path to the grammar file |
384,783 | def get_text(node, strategy):
textEquivs = node.get_TextEquiv()
if not textEquivs:
log.debug("No text results on %s %s", node, node.id)
return
else:
if len(textEquivs) > 1:
index1 = [x for x in textEquivs if x.index == 1]
if index1:
... | Get the most confident text results, either those with @index = 1 or the first text results or empty string. |
384,784 | def get_file_to_path(self, share_name, directory_name, file_name, file_path,
open_mode=, start_range=None, end_range=None,
range_get_content_md5=None, progress_callback=None,
max_connections=1, max_retries=5, retry_wait=1.0, timeout=None):
... | Downloads a file to a file path, with automatic chunking and progress
notifications. Returns an instance of File with properties and metadata.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_nam... |
384,785 | def do_prune(self):
if self.prune_table and self.prune_column and self.prune_date:
return True
elif self.prune_table or self.prune_column or self.prune_date:
raise Exception()
else:
return False | Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in. |
384,786 | async def get_source_list(self, scheme: str = "") -> List[Source]:
res = await self.services["avContent"]["getSourceList"](scheme=scheme)
return [Source.make(**x) for x in res] | Return available sources for playback. |
384,787 | def normalize_docroot(app, root):
srcdir = app.env.srcdir
default_version = app.config.javalink_default_version
if isinstance(root, basestring):
(url, base) = _parse_docroot_str(srcdir, root)
return {: url, : base, : default_version}
else:
normalized = {}
normalize... | Creates a package-list URL and a link base from a docroot element.
Args:
app: the global app object
root: the docroot element [string or dictionary] |
384,788 | def lock(self):
if self.cache.get(self.lock_name):
return False
else:
self.cache.set(self.lock_name, timezone.now(), self.timeout)
return True | This method sets a cache variable to mark current job as "already running". |
384,789 | def _eval_target_jumptable(state, ip, limit):
if ip.symbolic is False:
return [ (claripy.ast.bool.true, ip) ]
cond_and_targets = [ ]
ip_ = ip
outer_reverse = False
if ip_.op == "Reverse":
ip_ = ip_.args[0]
oute... | A *very* fast method to evaluate symbolic jump targets if they are a) concrete targets, or b) targets coming
from jump tables.
:param state: A SimState instance.
:param ip: The AST of the instruction pointer to evaluate.
:param limit: The maximum number of concrete IPs.
... |
384,790 | def hook_point(self, hook_name, handle=None):
full_hook_name = + hook_name
for module in self.modules_manager.instances:
_ts = time.time()
if not hasattr(module, full_hook_name):
continue
fun = getattr(module, full_hook_name)
try... | Used to call module function that may define a hook function for hook_name
Available hook points:
- `tick`, called on each daemon loop turn
- `save_retention`; called by the scheduler when live state
saving is to be done
- `load_retention`; called by the scheduler when live ... |
384,791 | def eval(self, code, mode=):
if isinstance(code, str):
if isinstance(code, str):
code = UTF8_COOKIE + code.encode()
code = compile(code, , mode)
if mode != :
return eval(code, self.globals, self.locals)
exec(code, self.globals, self.lo... | Evaluate code in the context of the frame. |
384,792 | def imported_targets(self):
libs = []
for spec in self.imported_target_specs(payload=self.payload):
resolved_target = self._build_graph.get_target_from_spec(spec,
relative_to=self.address.spec_path)
if not resolved_target:
r... | :returns: target instances for specs referenced by imported_target_specs.
:rtype: list of Target |
384,793 | def add_fields(self, field_dict):
for key, field in field_dict.items():
self.add_field(key, field) | Add a mapping of field names to PayloadField instances.
:API: public |
384,794 | def opens_platforms(self, tag=None, fromdate=None, todate=None):
return self.call("GET", "/stats/outbound/opens/platforms", tag=tag, fromdate=fromdate, todate=todate) | Gets an overview of the platforms used to open your emails.
This is only recorded when open tracking is enabled for that email. |
384,795 | def ps_ball(radius):
r
rad = int(sp.ceil(radius))
other = sp.ones((2 * rad + 1, 2 * rad + 1, 2 * rad + 1), dtype=bool)
other[rad, rad, rad] = False
ball = spim.distance_transform_edt(other) < radius
return ball | r"""
Creates spherical ball structuring element for morphological operations
Parameters
----------
radius : float or int
The desired radius of the structuring element
Returns
-------
strel : 3D-array
A 3D numpy array of the structuring element |
384,796 | def global_config(cls, key, *args):
if args:
cls.settings[key] = args[0]
else:
return cls.settings[key] | This reads or sets the global settings stored in class.settings. |
384,797 | def decode_base64(data):
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b * (4 - missing_padding)
return base64.b64decode(data) | Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes |
384,798 | def get_teams():
LOGGER.debug("TeamService.get_teams")
args = {: , : }
response = TeamService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
for team in response.response_content[]:
ret.append(Team.json_2_team(team))... | :return: all knows teams |
384,799 | def CountFlowLogEntries(self, client_id, flow_id):
return len(self.ReadFlowLogEntries(client_id, flow_id, 0, sys.maxsize)) | Returns number of flow log entries of a given flow. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.