Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
342,600 | def buildschema(_cls=None, **kwargs):
if _cls is None:
return lambda _cls: buildschema(_cls=_cls, **kwargs)
result = build(_cls, **kwargs)
return result | Class decorator used to build a schema from the decorate class.
:param type _cls: class to decorate.
:param kwargs: schema attributes to set.
:rtype: type
:return: schema class. |
342,601 | def searches(self):
return self._get_object(
regex=re.compile(
r, re.UNICODE),
objectType="searchBlock",
content=None
) | *The search-block (if any) associated with this document*
**Usage:**
.. code-block:: python
# DOCUMENT SEARCHES
docSearchBlock = doc.searches |
342,602 | def store(self, key, expiry, data):
self.cache.set(key, (expiry, data), self.cache_ttl)
if getattr(settings, , True):
__, cached_data = self.cache.get(key, (None, None))
if data is not None and cached_data is None:
... | Add a result to the cache
:key: Cache key to use
:expiry: The expiry timestamp after which the result is stale
:data: The data to cache |
342,603 | def startup(name):
ret = {: name,
: {},
: None,
: }
if __opts__[]:
ret[] =
return ret
__salt__[]()
ret[] = True
ret[] =
return ret | Start Traffic Server on the local node.
.. code-block:: yaml
startup_ats:
trafficserver.startup |
342,604 | def extract_message_to_dict(filename):
message_dict = {}
if os.path.isfile(filename):
with open(filename,) as wfile:
key = ""
val = ""
startMess = False
while 1:
each_line = wfile.readline()
if not each_lin... | Read in a text file that java messages to be ignored and generate a dictionary structure out of
it with key and value pairs. The keys are test names and the values are lists of java message
strings associated with that test name where we are either going to add to the existing java messages
to ignore or re... |
342,605 | def driver(self, package=None, attach=True, activity=None, process=None):
app = self._d.current_app()
capabilities = {
: {
: self._d.serial,
: package or app.package,
: attach,
: process or app.package,
... | Args:
- package(string): default current running app
- attach(bool): default true, Attach to an already-running app instead of launching the app with a clear data directory
- activity(string): Name of the Activity hosting the WebView.
- process(string): Process name o... |
342,606 | def restart(self, restart_data, run_async=False):
assert isinstance(restart_data, dict)
if (not self.restart_matches(restart_data.get(),
restart_data.get(),
( in restart_data))):
return (False, "restart condi... | conditional and unconditional restart |
342,607 | def add_organization(session, name):
if name is None:
raise ValueError(" cannot be None")
if name == :
raise ValueError(" cannot be an empty string")
organization = Organization(name=name)
session.add(organization)
return organization | Add an organization to the session.
This function adds a new organization to the session,
using the given `name` as an identifier. Name cannot be
empty or `None`.
It returns a new `Organization` object.
:param session: database session
:param name: name of the organization
:return: a new... |
342,608 | def to_pod(self):
orderers = {}
packages = {}
for fam, orderer in self.order_dict.iteritems():
k = id(orderer)
orderers[k] = orderer
packages.setdefault(k, set()).add(fam)
orderlist = []
for k, fams in packages.iteritems():
... | Example (in yaml):
type: per_family
orderers:
- packages: ['foo', 'bah']
type: version_split
first_version: '4.0.5'
- packages: ['python']
type: sorted
descending: false
default_order:
type... |
342,609 | def rank_member_if_in(
self,
leaderboard_name,
rank_conditional,
member,
score,
member_data=None):
reverse
current_score = self.redis_connection.zscore(leaderboard_name, member)
if current_score is not None:
curr... | Rank a member in the named leaderboard based on execution of the +rank_conditional+.
The +rank_conditional+ is passed the following parameters:
member: Member name.
current_score: Current score for the member in the leaderboard.
score: Member score.
member_data: Optional... |
342,610 | def lease(self, items):
self._manager.leaser.add(items)
self._manager.maybe_pause_consumer() | Add the given messages to lease management.
Args:
items(Sequence[LeaseRequest]): The items to lease. |
342,611 | def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
where = dict(where, **kwargs).items()
sql, args = makeSQL("SELECT", table, cols, where, group, order, limit)
return execute(sql, args) | Convenience wrapper for database SELECT. |
342,612 | def save(self, *args, **kwargs):
if self.user:
self.from_name = self.user.get_full_name()
self.from_email = self.user.email
if int(self.status) < 1:
self.send()
if INWARD_LOG:
super(Inward, self).s... | Custom save method |
342,613 | def remove(self, branch, turn, tick):
time_entity, parents, branches, keys, settings, presettings, remove_keycache, send = self._remove_stuff
parent, entity, key = time_entity[branch, turn, tick]
branchkey = parent + (entity, key)
keykey = parent + (entity,)
if parent in... | Delete all data from a specific tick |
342,614 | def print_diff(self, style=no_style()):
if self.options[]:
self.print_diff_sql(style)
else:
self.print_diff_text(style) | Print differences to stdout |
342,615 | def add_bcc(
self,
bcc_email,
global_substitutions=None,
is_multiple=False,
p=0):
if isinstance(bcc_email, str):
bcc_email = Bcc(bcc_email, None)
if isinstance(bcc_email, tuple):
bcc_email = Bcc(bcc_email[0], bc... | Adds a Bcc object to the Personalization object
:param to_emails: An Bcc object
:type to_emails: Bcc
:param global_substitutions: A dict of substitutions for all recipients
:type global_substitutions: dict
:param is_multiple: Create a new personilization for each recipient
... |
342,616 | def hardware_connector_sfp_breakout(self, **kwargs):
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
connector = ET.SubElement(hardware, "connector")
name_key = ET.SubElement(connector, "name")
nam... | Auto Generated Code |
342,617 | def fsto(self):
a = float(self.tmpopslist.pop())
var = self.opslist.pop()
if isinstance(var, basestring):
self.variables.update({var: a})
return a
else:
print("Can only sto into a variable.")
return | sto operation. |
342,618 | def periodogram_auto(self, oversampling=5, nyquist_factor=3,
return_periods=True):
N = len(self.t)
T = np.max(self.t) - np.min(self.t)
df = 1. / T / oversampling
f0 = df
Nf = int(0.5 * oversampling * nyquist_factor * N)
freq = f0 + df * n... | Compute the periodogram on an automatically-determined grid
This function uses heuristic arguments to choose a suitable frequency
grid for the data. Note that depending on the data window function,
the model may be sensitive to periodicity at higher frequencies than
this function return... |
342,619 | def load_json(cls, data, default_rule=None, raise_error=False):
rules = {k: _parser.parse_rule(v, raise_error)
for k, v in json.loads(data).items()}
return cls(rules, default_rule) | Allow loading of JSON rule data. |
342,620 | def from_query_string(cls, schema, qs=None):
dct = load_query_string_data(schema, qs)
return cls.from_dict(dct) | Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted) |
342,621 | def _extract_all_responses(self, resources, api_endpoint, api_name):
all_responses, resources = self._bulk_cache_lookup(api_name, resources)
resource_chunks = self._prepare_resource_chunks(resources)
response_chunks = self._request_reports("resource", resource_chunks, api_endpoint)
... | Aux function to extract all the API endpoint responses.
Args:
resources: list of string hashes.
api_endpoint: endpoint path
api_name: endpoint name
Returns:
A dict with the hash as key and the VT report as value. |
342,622 | def _check_diff_result(row, matches, tokenize, join):
ngram_tokens = tokenize(row[constants.NGRAM_FIELDNAME])
sub_ngram1 = join(ngram_tokens[:-1])
sub_ngram2 = join(ngram_tokens[1:])
count = constants.COUNT_FIELDNAME
discard = False
status1 = ma... | Returns `row`, possibly with its count changed to 0, depending on
the status of the n-grams that compose it.
The n-gram represented in `row` can be decomposed into two
(n-1)-grams. If neither sub-n-gram is present in `matches`, do
not change the count since this is a new difference.
... |
342,623 | def kind(self):
if "kind" not in self.attrs.keys():
self.attrs["kind"] = "None"
value = self.attrs["kind"]
return value if not value == "None" else None | Kind. |
342,624 | def format_label(self, field, counter):
return % (
counter, field.field.required and , field.label) | Format the label for each field |
342,625 | def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
if is_rgb: has_components = True
ndim = data.ndim
if has_components:
ndim -= 1
dtype = data.dtype.name
ptype = _npy_to_itk_map[dtype]
data = np.array(data)
if origin is None: ... | Internal function for creating an ANTsImage |
342,626 | def convert_string_to_type(string_value):
if string_value in [, type(None).__name__]:
return type(None)
if isinstance(string_value, type) or isclass(string_value):
return string_value
if sys.version_info >= (3,):
import builtins as builtins23
else:
im... | Converts a string into a type or class
:param string_value: the string to be converted, e.g. "int"
:return: The type derived from string_value, e.g. int |
342,627 | def insert(self, payload):
response = self.session.post(self._get_table_url(), data=json.dumps(payload))
return self._get_content(response) | Inserts a new record with the payload passed as an argument
:param payload: The record to create (dict)
:return:
- Created record |
342,628 | def download_device(headers, cookies, temp_target_disk,
device_url, lease_updater,
total_bytes_written, total_bytes_to_write):
with open(temp_target_disk, ) as handle:
response = requests.get(device_url, stream=True,
headers=header... | Download disk device of HttpNfcLease.info.deviceUrl
list of devices
:param headers: Request headers
:type cookies: dict
:param cookies: Request cookies (session)
:type cookies: dict
:param temp_target_disk: file name to write
:type temp_target_disk: str
:param device_url: deviceUrl.url
... |
342,629 | def _register_custom_contracts(contract_name, contract_exceptions):
global _CUSTOM_CONTRACTS
if not isinstance(contract_name, str):
raise TypeError("Argument `contract_name` is of the wrong type")
if (
(not isinstance(contract_exceptions, list))
and (not... | Homogenize custom contract exception definition. |
342,630 | def add_post(self, *args, **kwargs):
return self.add_route(hdrs.METH_POST, *args, **kwargs) | Shortcut for add_route with method POST |
342,631 | def has_intercept(estimator):
if hasattr(estimator, ):
return estimator.fit_intercept
if hasattr(estimator, ):
if estimator.intercept_ is None:
return False
return np.any(estimator.intercept_)
return False | Return True if an estimator has intercept fit. |
342,632 | def get_dom(self) -> str:
if self.is_running:
return self.dumps()
if self.dom is not None:
return self.dom
dom = self.dumps()
self.dom = dom
return dom | Retrieves the current value of the DOM for the step |
342,633 | def ekdelr(handle, segno, recno):
handle = ctypes.c_int(handle)
segno = ctypes.c_int(segno)
recno = ctypes.c_int(recno)
libspice.ekdelr_c(handle, segno, recno) | Delete a specified record from a specified E-kernel segment.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekdelr_c.html
:param handle: File handle.
:type handle: int
:param segno: Segment number.
:type segno: int
:param recno: Record number.
:type recno: int |
342,634 | def simplex_index(x, m, n):
r
if m == 1:
return 0
decumsum = np.cumsum(x[-1:0:-1])[::-1]
idx = num_compositions(m, n) - 1
for i in range(m-1):
if decumsum[i] == 0:
break
idx -= num_compositions(m-i, decumsum[i]-1)
return idx | r"""
Return the index of the point x in the lexicographic order of the
integer points of the (m-1)-dimensional simplex :math:`\{x \mid x_0
+ \cdots + x_{m-1} = n\}`.
Parameters
----------
x : array_like(int, ndim=1)
Integer point in the simplex, i.e., an array of m nonnegative
i... |
342,635 | def get_plugin_modules(plugins):
if not plugins:
raise MissingPluginNames("input plugin names are required")
modules = []
for plugin in plugins:
short_name = PLUGIN_MAPPING.get(plugin.lower(), plugin.lower())
full_path = % (module_prefix, short_name)
modules.append(im... | Get plugin modules from input strings
:param tuple plugins: a tuple of plugin names in str |
342,636 | def check(self):
self._check_tx_inout_count()
self._check_txs_out()
self._check_txs_in()
self._check_size_limit() | Basic checks that don't depend on any context.
Adapted from Bicoin Code: main.cpp |
342,637 | def load(cls, path, encoding="utf-8", format_=None, fps=None, **kwargs):
with open(path, encoding=encoding) as fp:
return cls.from_file(fp, format_, fps=fps, **kwargs) | Load subtitle file from given path.
Arguments:
path (str): Path to subtitle file.
encoding (str): Character encoding of input file.
Defaults to UTF-8, you may need to change this.
format_ (str): Optional, forces use of specific parser
(eg. `"s... |
342,638 | def _slug_strip(value, separator=):
separator = separator or
if separator == or not separator:
re_sep =
else:
re_sep = % re.escape(separator)
if separator != re_sep:
value = re.sub( % re_sep, separator, value)
if separator:
if separator != :
... | Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator. |
342,639 | def extract_suffix(self, name):
if len(name.strip().split()) > 2:
name, suffix = self.extract_matching_portion(r.format(SUFFIX_RE), name)
suffix, degree = self.extract_matching_portion(DEGREE_RE, suffix or )
return name, suffix or None
return name, ... | Returns a tuple of (name, suffix), or (name, None) if no suffix could be found.
As the method name indicates, the name is returned without the suffix.
Suffixes deemed to be degrees are discarded. |
342,640 | def add_metric(self, labels, count_value, sum_value, timestamp=None):
self.samples.append(Sample(self.name + , dict(zip(self._labelnames, labels)), count_value, timestamp))
self.samples.append(Sample(self.name + , dict(zip(self._labelnames, labels)), sum_value, timestamp)) | Add a metric to the metric family.
Args:
labels: A list of label values
count_value: The count value of the metric.
sum_value: The sum value of the metric. |
342,641 | def applySettings(self, axisMin=None, axisMax=None, axisLimit=None):
if axisMin is not None and not math.isnan(axisMin):
self.minValueSource =
self.minValue = self.checkFinite(axisMin, )
if axisMax == :
self.maxValueSource =
elif axisMax is not Non... | Apply the specified settings to this axis.
Set self.minValue, self.minValueSource, self.maxValue,
self.maxValueSource, and self.axisLimit reasonably based on the
parameters provided.
Arguments:
axisMin -- a finite number, or None to choose a round minimum
limit tha... |
342,642 | def multihead_attention(queries,
keys,
scope="multihead_attention",
num_units=None,
num_heads=4,
dropout_rate=0,
is_training=True,
causality=False):
... | Applies multihead attention.
Args:
queries: A 3d tensor with shape of [N, T_q, C_q].
keys: A 3d tensor with shape of [N, T_k, C_k].
num_units: A cdscalar. Attention size.
dropout_rate: A floating point number.
is_training: Boolean. Controller of mechanism for dropout.
causality:... |
342,643 | def _fetch_json(self, url, payload):
params = {
: json.dumps(payload),
: {: },
: {: self.sma_sid} if self.sma_sid else None,
}
for _ in range(3):
try:
with async_timeout.timeout(3):
res = yield from self... | Fetch json data for requests. |
342,644 | def get_parcellation(atlas, parcel_param):
"Placeholder to insert your own function to return parcellation in reference space."
parc_path = os.path.join(atlas, .format(parcel_param))
parcel = nibabel.freesurfer.io.read_geometry(parc_path)
return parcel | Placeholder to insert your own function to return parcellation in reference space. |
342,645 | def pending_exists(self, hash):
hash = self._process_value(hash, )
payload = {"hash": hash}
resp = self.call(, payload)
return resp[] == | Check whether block is pending by **hash**
.. version 8.0 required
:param hash: Hash of block to check if pending
:type hash: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.pending_exists(
hash="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3... |
342,646 | def error(f, *args, **kwargs):
kwargs.update({: logging.ERROR})
return _stump(f, *args, **kwargs) | Automatically log progress on function entry and exit. Default logging
value: error.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. Each '{varname}' will be replaced by the v... |
342,647 | def on_message(self, headers, body):
self.__sysout()
if in headers:
content = base64.b64decode(body.encode())
if os.path.exists(headers[]):
fname = % (headers[], int(time.time()))
else:
fname = headers[]
with open... | See :py:meth:`ConnectionListener.on_message`
Special case: if the header 'filename' is present, the content is written out
as a file |
342,648 | def parse_args():
parser = argparse.ArgumentParser(
description=)
parser.add_argument(, nargs=, type=str,
help=)
parser.add_argument(, , default=, type=str,
help=)
parser.add_argument(, , default=, type=str,
help=)
... | Define and parse command line arguments |
342,649 | def get_bbl(arxiv_id):
tar_file = get_sources(arxiv_id)
bbl_files = [i for i in tar_file.getmembers() if i.name.endswith(".bbl")]
bbl_files = [tar_file.extractfile(member).read().decode(tarfile.ENCODING)
for member in bbl_files]
return bbl_files | Get the .bbl files (if any) of a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``) in \
a canoni... |
342,650 | def on_exit(self, info):
if self.prompt_on_exit:
retval = confirm(parent = info.ui.control,
message = "Exit Godot?",
title = "Confirm exit",
default = YES)
if retval == YES:
... | Handles the user attempting to exit Godot. |
342,651 | def get_attribute_option(self, attribute, option_name):
self.__validate_attribute_option_name(option_name)
attribute_key = self.__make_key(attribute)
return self.__attribute_options[attribute_key].get(option_name) | Returns the value of the given attribute option for the specified
attribute. |
342,652 | def log_player_trades_with_other_player(self, player, to_other, other, to_player):
self._log(.format(player.color))
self._log()
for i, (num, res) in enumerate(to_other):
if i > 0:
self._log()
self._log(.format(num, res.value))
se... | :param player: catan.game.Player
:param to_other: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
:param other: catan.board.Player
:param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] |
342,653 | def dl_pb_file(inputs):
basefile, subdir, db, dl_dir, keep_subdirs, overwrite = inputs
url = posixpath.join(config.db_index_url, db, subdir, basefile)
remote_file_size = _remote_file_size(url)
if keep_subdirs:
dldir = os.path.join(dl_dir, subdir)
else:
dldir =... | Download a file from physiobank.
The input args are to be unpacked for the use of multiprocessing
map, because python2 doesn't have starmap... |
342,654 | def convolutional_layer_series(initial_size, layer_sequence):
size = initial_size
for filter_size, padding, stride in layer_sequence:
size = convolution_size_equation(size, filter_size, padding, stride)
return size | Execute a series of convolutional layer transformations to the size number |
342,655 | def run(self):
user_params = None
build_json = get_build_json()
git_url = os.environ[]
git_ref = os.environ.get(, None)
image = os.environ[]
self.target_registry = os.environ.get(, None)
self.reactor_env = None
git_commit_depth = None
git... | each plugin has to implement this method -- it is used to run the plugin actually
response from plugin is kept and used in json result response |
342,656 | def calculate(self, T, method):
r
if method == RACKETT:
Vm = Rackett(T, self.Tc, self.Pc, self.Zc)
elif method == YAMADA_GUNN:
Vm = Yamada_Gunn(T, self.Tc, self.Pc, self.omega)
elif method == BHIRUD_NORMAL:
Vm = Bhirud_normal(T, self.Tc, self.Pc, self.... | r'''Method to calculate low-pressure liquid molar volume at tempearture
`T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Temperature at which to calculate molar volume, [K]
... |
342,657 | def batch_get_archive(self, archive_names, default_versions=None):
archive_names = map(
lambda arch: self._normalize_archive_name(arch)[1],
archive_names)
responses = self.manager.batch_get_archive(archive_names)
archives = {}
if default_vers... | Batch version of :py:meth:`~DataAPI.get_archive`
Parameters
----------
archive_names: list
Iterable of archive names to retrieve
default_versions: str, object, or dict
Default versions to assign to each returned archive. May be a dict
with archive... |
342,658 | def moresane_by_scale(self, start_scale=1, stop_scale=20, subregion=None, sigma_level=4, loop_gain=0.1,
tolerance=0.75, accuracy=1e-6, major_loop_miter=100, minor_loop_miter=30, all_on_gpu=False,
decom_mode="ser", core_count=1, conv_device=, conv_mode=, extraction_mod... | Extension of the MORESANE algorithm. This takes a scale-by-scale approach, attempting to remove all sources
at the lower scales before moving onto the higher ones. At each step the algorithm may return to previous
scales to remove the sources uncovered by the deconvolution.
INPUTS:
star... |
342,659 | def forms(self):
forms = FormsDict()
for name, item in self.POST.allitems():
if not hasattr(item, ):
forms[name] = item
return forms | Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is retuned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. |
342,660 | def _retrieve_grains_cache(proxy=None):
global GRAINS_CACHE
if not GRAINS_CACHE:
if proxy and salt.utils.napalm.is_proxy(__opts__):
GRAINS_CACHE = proxy[]()
elif not proxy and salt.utils.napalm.is_minion(__opts__):
GRAINS_CACHE = salt.utils.... | Retrieves the grains from the network device if not cached already. |
342,661 | def load(self, instance, xblock):
if djpyfs:
return djpyfs.get_filesystem(scope_key(instance, xblock))
else:
raise NotImplementedError("djpyfs not available") | Get the filesystem for the field specified in 'instance' and the
xblock in 'xblock' It is locally scoped. |
342,662 | def leave_chat(self, *args, **kwargs):
return leave_chat(*args, **self._merge_overrides(**kwargs)).run() | See :func:`leave_chat_member` |
342,663 | def all_subclasses(cls):
subclasses = cls.__subclasses__()
return subclasses + [g for s in subclasses for g in all_subclasses(s)] | Given a class `cls`, this recursive function returns a list with
all subclasses, subclasses of subclasses, and so on. |
342,664 | def flip_y(self, center=None):
if center is None:
self.poly.flop()
else:
self.poly.flop(center[1])
return self | Flip the shape in the y direction, in-place.
Parameters
----------
center : array-like, optional
Point about which to flip.
If not passed, the center of the shape will be used. |
342,665 | def getCountry(value):
if not helpers.has_len(value):
return False
return COUNTRIES.get(str(value).lower(), False) | returns the country name from country code
@return string |
342,666 | def _prohibited(from_op, to_op):
"Determines if from_op is allowed to be mutated to to_op."
if from_op is UnaryOperators.Not:
if to_op is not UnaryOperators.Nothing:
return True
if from_op is UnaryOperators.UAdd:
if to_op is UnaryOperators.Nothing:
ret... | Determines if from_op is allowed to be mutated to to_op. |
342,667 | def _req(self):
sentinel =
field_names = [field[] for field in self.fields]
req = []
for template_ord, template in enumerate(self.templates):
field_values = {field: sentinel for field in field_names}
required_fields = []
for field_ord, field in enumerate(field_names):
fv... | List of required fields for each template. Format is [tmpl_idx, "all"|"any", [req_field_1, req_field_2, ...]].
Partial reimplementation of req computing logic from Anki. We use pystache instead of Anki's custom mustache
implementation.
The goal is to figure out which fields are "required", i.e. if they ar... |
342,668 | def get_versions(default=DEFAULT, verbose=False):
assert versionfile_source is not None, "please set versioneer.versionfile_source"
assert tag_prefix is not None, "please set versioneer.tag_prefix"
assert parentdir_prefix is not None, "please set versioneer.parentdir_prefix"
assert VCS is no... | This variation of get_versions() will be used in versioneer.py . |
342,669 | def get_headers(self):
headers = {
"User-Agent": "kFlame 1.0"
}
password_url = self._get_password_url()
if password_url and password_url in self._settings["authorizations"]:
headers["Authorization"] = self._settings["authorizations"][password_url]
... | Get headers.
Returns:
tuple: Headers |
342,670 | def _StackSummary_extract(frame_gen, limit=None, lookup_lines=True, capture_locals=False):
result = StackSummary()
for f, lineno in frame_gen:
co = f.f_code
filename = co.co_filename
name = co.co_name
result.append(ExtendedFrameSummary(
frame=f, filename=filename... | Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is why we overwrite it.
Additionally, we also capture the frame.
This is a bit hacky and also not... |
342,671 | def _convertNonZeroToFailure(self, res):
"utility method to handle the result of getProcessOutputAndValue"
(stdout, stderr, code) = res
if code != 0:
raise EnvironmentError(
% (code, stderr))
return (stdout, stderr, code) | utility method to handle the result of getProcessOutputAndValue |
342,672 | def timestamp(args):
p = OptionParser(timestamp.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
path, = args
for root, dirs, files in os.walk(path):
for f in files:
filename = op.join(root, f)
atime, mtime = get_... | %prog timestamp path > timestamp.info
Record the timestamps for all files in the current folder.
filename atime mtime
This file can be used later to recover previous timestamps through touch(). |
342,673 | def get_replies_to(self, msg):
mid = msg.get_message_id()
msg_hash = self.get_messages()
for m in msg_hash.keys():
if m.get_message_id() == mid:
return msg_hash[m]
return None | returns all replies to the given message contained in this thread.
:param msg: parent message to look up
:type msg: :class:`~alot.db.message.Message`
:returns: list of :class:`~alot.db.message.Message` or `None` |
342,674 | def get_loaded_rules(rules_paths):
for path in rules_paths:
if path.name != :
rule = Rule.from_path(path)
if rule.is_enabled:
yield rule | Yields all available rules.
:type rules_paths: [Path]
:rtype: Iterable[Rule] |
342,675 | def put_file(self, filename, index, doc_type, id=None, name=None):
if id is None:
request_method =
else:
request_method =
path = make_path(index, doc_type, id)
doc = file_to_attachment(filename)
if name:
doc["_name"] = name
r... | Store a file in a index |
342,676 | def resolve_pointer(self, document, pointer):
parts = re.split(r"(?<!\^)/", unquote(pointer.lstrip("/"))) if pointer else []
for part in parts:
replacements = {r"^/": r"/", r"^^": r"^"}
part = re.sub(
"|".join(re.escape(key) for key... | Resolve a json pointer ``pointer`` within the referenced ``document``.
:argument document: the referent document
:argument str pointer: a json pointer URI fragment to resolve within it |
342,677 | def set_default_decoder_parameters():
ARGTYPES = [ctypes.POINTER(DecompressionParametersType)]
OPENJP2.opj_set_default_decoder_parameters.argtypes = ARGTYPES
OPENJP2.opj_set_default_decoder_parameters.restype = ctypes.c_void_p
dparams = DecompressionParametersType()
OPENJP2.opj_set_default_dec... | Wraps openjp2 library function opj_set_default_decoder_parameters.
Sets decoding parameters to default values.
Returns
-------
dparam : DecompressionParametersType
Decompression parameters. |
342,678 | def alter_database_user(self, username, password=None, permissions=None):
url = "db/{0}/users/{1}".format(self._database, username)
if not password and not permissions:
raise ValueError("Nothing to alter for user {0}.".format(username))
data = {}
if password:
... | Alter a database user and/or their permissions.
:param permissions: A ``(readFrom, writeTo)`` tuple
:raise TypeError: if permissions cannot be read.
:raise ValueError: if neither password nor permissions provided. |
342,679 | def get_action_methods(self):
return [(name, getattr(self, name))
for name, _ in Action.get_command_types()] | return a list of methods on this class for executing actions.
methods are return as a list of (name, func) tuples |
342,680 | def iter_predict(self, X, include_init=False):
for probas in self.iter_predict_proba(X, include_init=include_init):
yield self.encoder_.inverse_transform(np.argmax(probas, axis=1)) | Returns the predicted classes for ``X`` at every stage of the boosting procedure.
Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.
include_init (bool... |
342,681 | def to_sky(self, wcs, mode=):
sky_params = self._to_sky_params(wcs, mode=mode)
return SkyCircularAperture(**sky_params) | Convert the aperture to a `SkyCircularAperture` object defined
in celestial coordinates.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformat... |
342,682 | def construct(path, name=None):
"Selects an appropriate CGroup subclass for the given CGroup path."
name = name if name else path.split("/")[4]
classes = {"memory": Memory,
"cpu": CPU,
"cpuacct": CPUAcct}
constructor = classes.get(name, CGroup)
log.debug("Chose %s for: ... | Selects an appropriate CGroup subclass for the given CGroup path. |
342,683 | def hardware_flexport_flexport_type_type(self, **kwargs):
config = ET.Element("config")
hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware")
flexport = ET.SubElement(hardware, "flexport")
id_key = ET.SubElement(flexport, "id")
id_ke... | Auto Generated Code |
342,684 | def expand_details(df, detailCol=):
df = copy.deepcopy(df)
df[] = df[detailCol]
dicts = [sportsref.nfl.pbp.parse_play_details(detail) for detail in df[].values]
cols = {c for d in dicts if d for c in d.keys()}
blankEntry = {c: np.nan for c in cols}
newDicts = [d if d else blankEntry fo... | Expands the details column of the given dataframe and returns the
resulting DataFrame.
:df: The input DataFrame.
:detailCol: The detail column name.
:returns: Returns DataFrame with new columns from pbp parsing. |
342,685 | def _encrypt(cipher, key, data, iv, padding):
if not isinstance(key, byte_cls):
raise TypeError(pretty_message(
,
type_name(key)
))
if not isinstance(data, byte_cls):
raise TypeError(pretty_message(
,
type_name(data)
))
... | Encrypts plaintext
:param cipher:
A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key",
"rc2", "rc4"
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The plaintext - a byte string
:param iv:
The initialization vector ... |
342,686 | def exists(self):
api = self._instance._client.database_admin_api
metadata = _metadata_with_prefix(self.name)
try:
api.get_database_ddl(self.name, metadata=metadata)
except NotFound:
return False
return True | Test whether this database exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDDL
:rtype: bool
:returns: True if the database exists, else false. |
342,687 | def deregister_listener(self, member_uuid, listener):
self._casts[str(member_uuid)][].remove(listener) | Deregister listener for audio group changes of cast uuid. |
342,688 | def _single_site(self):
if settings.FLUENTCMS_EMAILTEMPLATES_FILTER_SITE_ID and self._parent_site is None:
return self.parent_site(settings.SITE_ID)
else:
return self | Make sure the queryset is filtered on a parent site, if that didn't happen already. |
342,689 | def send(self, local, remote, makedirs=False):
if makedirs:
self.exec_cmd(.format(os.path.dirname(remote)))
host = self.host
if in host:
host = .format(host)
cmd = .format(local, host, remote)
cmd = self._cmd_str(cmd, ssh=)
lo... | scp a file or files to a remote system |
342,690 | def token_required(scopes=, new=False):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if request.method == :
if request.POST.get("_add", False):
logger.... | Decorator for views which supplies a single, user-selected token for the view to process.
Same parameters as tokens_required. |
342,691 | def is_causal_central(graph: BELGraph, node: BaseEntity) -> bool:
return has_causal_in_edges(graph, node) and has_causal_out_edges(graph, node) | Return true if the node is neither a causal sink nor a causal source.
- Does have causal in edges(s)
- Does have causal out edge(s) |
342,692 | def stratKP2iS(f, G, y0, tspan, Jmethod=Jkpw, gam=None, al1=None, al2=None,
rtol=1e-4, dW=None, J=None):
try:
from scipy.optimize import fsolve
except ImportError:
raise Error()
(d, m, f, G, y0, tspan, dW, J) = _check_args(f, G, y0, tspan, dW, J)
if not callable(G):
... | Use the Kloeden and Platen two-step implicit order 1.0 strong algorithm
to integrate a Stratonovich equation dy = f(y,t)dt + G(y,t)\circ dW(t)
This semi-implicit algorithm may be useful for stiff systems. The noise
does not need to be scalar, diagonal, or commutative.
This algorithm is defined in Kloe... |
342,693 | def fetch_by_code(self, code):
code_data = self.read(code)
if code_data is None:
raise AuthCodeNotFound
return AuthorizationCode(**code_data) | Returns data belonging to an authorization code from redis or
``None`` if no data was found.
See :class:`oauth2.store.AuthCodeStore`. |
342,694 | def RunValidationOutputFromOptions(feed, options):
if options.output.upper() == "CONSOLE":
return RunValidationOutputToConsole(feed, options)
else:
return RunValidationOutputToFilename(feed, options, options.output) | Validate feed, output results per options and return an exit code. |
342,695 | def decode(self, check_trailer=False):
try:
kind = self.data[self.offset]
except IndexError:
raise BencodeError("Unexpected end of data at offset %d/%d" % (
self.offset, len(self.data),
))
if kind.isdigit():
... | Decode data in C{self.data} and return deserialized object.
@param check_trailer: Raise error if trailing junk is found in data?
@raise BencodeError: Invalid data. |
342,696 | def get_counter(self, counter_name, default=0):
self.__update_state()
return self._state.counters_map.get(counter_name, default) | Get the value of the named counter from this job.
When a job is running, counter values won't be very accurate.
Args:
counter_name: name of the counter in string.
default: default value if the counter doesn't exist.
Returns:
Value in int of the named counter. |
342,697 | def normalized_mutual_info_score(self, reference_clusters):
return normalized_mutual_info_score(self.get_labels(self), self.get_labels(reference_clusters)) | Calculates the normalized mutual information w.r.t. the reference clusters (explicit evaluation)
:param reference_clusters: Clusters that are to be used as reference
:return: The resulting normalized mutual information score. |
342,698 | async def connect(self):
requester = AiohttpRequester()
factory = UpnpFactory(requester)
device = await factory.async_create_device(self.url)
self.service = device.service()
if not self.service:
_LOGGER.error("Unable to find group service!")
return False
... | Available actions
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetDeviceInfo)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetState)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetStateM)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupNam... |
342,699 | def binned_pixelrange(self, waverange, **kwargs):
x = units.validate_quantity(
waverange, self._internal_wave_unit, equivalencies=u.spectral())
return binning.pixel_range(self.binset.value, x.value, **kwargs) | Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the desired wavelength range.
If not a Quantity, assumed to be in Angst... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.