Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
357,100 | def deleteJID(self, bare_jid):
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, None)
self.__devices_cache.pop(bare_jid, None)
self.__trust_cache.pop(bare_jid, None)
yield self._storage.deleteJID(bare_jid) | Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys. |
357,101 | def tree_type_checker(*ref):
ref = tuple(ref)
if NeuriteType.all in ref:
def check_tree_type(_):
return True
else:
def check_tree_type(tree):
return tree.type in ref
return check_tree_type | Tree type checker functor
Returns:
Functor that takes a tree, and returns true if that tree matches any of
NeuriteTypes in ref
Ex:
>>> from neurom.core.types import NeuriteType, tree_type_checker
>>> tree_filter = tree_type_checker(NeuriteType.axon, NeuriteType.basal_dendrite)
... |
357,102 | def _expression(expression):
if isinstance(expression, QuilParser.ParenthesisExpContext):
return _expression(expression.expression())
elif isinstance(expression, QuilParser.PowerExpContext):
if expression.POWER():
return _binary_exp(expression, operator.pow)
elif isinst... | NB: Order of operations is already dealt with by the grammar. Here we can simply match on the type. |
357,103 | def _get_resource(self, label: str, source: dict, resource_type: str):
try:
return source[label]
except KeyError:
raise ValueError("Cannot find {0} with label .\nExisting {0} labels: {2}".format(
resource_type, label, list(source.keys()))) | Generic resoure fetcher handling errors.
Args:
label (str): The label to fetch
source (dict): The dictionary to look up the label
resource_type str: The display name of the resource type (used in errors) |
357,104 | def parse_single_results(data, sample, res1):
sample.stats_dfs.s2["trim_adapter_bp_read1"] = 0
sample.stats_dfs.s2["trim_quality_bp_read1"] = 0
sample.stats_dfs.s2["reads_filtered_by_Ns"] = 0
sample.stats_dfs.s2["reads_filtered_by_minlen"] = 0
sample.stats_dfs.s2["reads_passed_filter... | parse results from cutadapt into sample data |
357,105 | def _is_expired_response(self, response):
if response.status_code != 401:
return False
challenge = response.headers.get(, )
return in challenge | Check if the response failed because of an expired access token. |
357,106 | def open(self):
segments = []
files = config.get(, , fallback=[])
if not files:
raise JplConfigError("No JPL file defined")
for filepath in files:
filepath = Path(filepath)
if filepath.suffix.lower() != ".bsp":
co... | Open the files |
357,107 | def json_unicode_to_utf8(data):
if isinstance(data, unicode):
return data.encode()
elif isinstance(data, dict):
newdict = {}
for key in data:
newdict[json_unicode_to_utf8(
key)] = json_unicode_to_utf8(data[key])
return newdict
elif isinstance(... | Change all strings in a JSON structure to UTF-8. |
357,108 | def parse(self, rrstr):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
(su_len, su_entry_version_unused) = struct.unpack_from(, rrstr[:4], 2)
self._initialized = True | Parse a Rock Ridge System Terminator record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing. |
357,109 | def slice_after(predicate, iterable):
record = []
for i, item in enumerate(iterable):
record.append(item)
if predicate(item):
yield tuple(record)
record = []
if record:
yield tuple(record) | Returns groups of elements from iterable,
slicing just after predicate(elem) is True |
357,110 | def _build_ftp_processor(cls, session: AppSession):
ftp_client = session.factory[]
fetch_params = session.factory.new(
,
remove_listing=session.args.remove_listing,
retr_symlinks=session.args.retr_symlinks,
preserve_permissions=session.args.prese... | Build FTPProcessor. |
357,111 | def options(self, context, module_options):
scripts = {: get_script(),
: get_script()}
self.script_choice =
if in module_options:
self.script_choice = module_options[].upper()
if self.script_choice not in scripts.keys():
con... | SCRIPT Script version to execute (choices: bash, python) (default: bash) |
357,112 | def compute_Kij(self, Xi, Xj, ni, nj, noise=False, hyper_deriv=None, k=None):
r
if k is None:
if not noise:
k = self.k
else:
k = self.noise_k
if Xj is None:
symmetric = True
Xj = Xi
nj = ni
... | r"""Compute covariance matrix between datasets `Xi` and `Xj`.
Specify the orders of derivatives at each location with the `ni`, `nj`
arrays. The `include_noise` flag is passed to the covariance kernel to
indicate whether noise is to be included (i.e., for evaluation of
:math:`K+... |
357,113 | def createAction(self, parent=None, name=):
action = super(UiLoader, self).createAction(parent, name)
if not action.parent():
action.setParent(self._baseinstance)
setattr(self._baseinstance, name, action)
return action | Overloads teh create action method to handle the proper base
instance information, similar to the PyQt4 loading system.
:param parent | <QWidget> || None
name | <str> |
357,114 | def parse_params(self,
y=None,
y_target=None,
beta=1e-2,
decision_rule=,
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
max_i... | :param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
:param beta: Trades off L2... |
357,115 | def get_storage_account_keys(self, service_name):
_validate_not_none(, service_name)
return self._perform_get(
self._get_storage_service_path(service_name) + ,
StorageService) | Returns the primary and secondary access keys for the specified
storage account.
service_name:
Name of the storage service account. |
357,116 | def last_modified(self):
resource_list = self.traffic_incident()
last_modified = namedtuple(, )
if len(resource_list) == 1 and resource_list[0] is None:
return None
else:
try:
return [last_modified(resource[])
for r... | Retrieves the last modified time stamp of the incident/incidents
from the output response
Returns:
last_modified(namedtuple): List of named tuples of last modified
time stamp of the incident/incidents |
357,117 | def _multiplexed_buffer_helper(self, response):
buf = self._result(response, binary=True)
buf_length = len(buf)
walker = 0
while True:
if buf_length - walker < STREAM_HEADER_SIZE_BYTES:
break
header = buf[walker:walker + STREAM_HEADER_SIZE... | A generator of multiplexed data blocks read from a buffered
response. |
357,118 | def BatchConvert(self, metadata_value_pairs, token=None):
msg_dict = {}
for metadata, msg in metadata_value_pairs:
msg_dict.setdefault(msg.source, []).append((metadata, msg))
metadata_objects = []
metadata_to_fetch = []
for client_urn in msg_dict:
try:
metadata_... | Converts a batch of GrrMessages into a set of RDFValues at once.
Args:
metadata_value_pairs: a list or a generator of tuples (metadata, value),
where metadata is ExportedMetadata to be used for conversion and value
is a GrrMessage to be converted.
token: Security token.
Returns:
... |
357,119 | def load(self):
self.path = self.find_scene(self.meta.path)
if not self.path:
raise ValueError("Scene not found".format(self.meta.path))
self.scene = Scene(self.path)
if self.path.suffix == :
self.load_gltf()
if self.path.suf... | Deferred loading of the scene
:param scene: The scene object
:param file: Resolved path if changed by finder |
357,120 | def convert_lines_to_block(lines, block_map, link_stack, source_path, block_name=ALL_BLOCK_NAME):
found_closing_block = False
segments = []
while lines:
line = lines.pop(0)
close_tag_match = BLOCK_CLOSE_REGEX.match(line)
if close_tag_match:
if clos... | Converts the specified block content lines (list of strings) into a Block object.
Nested blocks are recursively converted into strings and cached in the block_map. Include tags
are processed as well. The resulting block string is also added to the block_map, along with any
nested blocks.
PARAMETERS:
... |
357,121 | def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=[, ]):
with zipfile.ZipFile(filename, , compression=zipfile.ZIP_DEFLATED) as zip_file:
root_len = len(os.path.abspath(directory))
out("Creating archive: " + str(filename))
for root, dirs, f... | Creates an archive from a directory and returns
the file that was created. |
357,122 | def json(
self,
dirPath=None):
if dirPath:
p = self._file_prefix()
jsonSources = self.sourceResults.json(
filepath=dirPath + "/" + p + "sources.json")
jsonPhot = self.photResults.json(
filepath=dirPath + "/" + ... | *Render the results in json format*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `jsonSources` -- the top-level transient data
- `jsonPhot` -- all photometry associated with the transient... |
357,123 | def address_to_ip(address):
address_parts = address.split(":")
ip_address = socket.gethostbyname(address_parts[0])
if ip_address == "127.0.0.1":
ip_address = get_node_ip_address()
return ":".join([ip_address] + address_parts[1:]) | Convert a hostname to a numerical IP addresses in an address.
This should be a no-op if address already contains an actual numerical IP
address.
Args:
address: This can be either a string containing a hostname (or an IP
address) and a port or it can be just an IP address.
Returns:... |
357,124 | def url_map(self, for_user=None, **kwargs):
class Home:
title = _("Home")
home = Home()
setattr(home, "get_absolute_url", home_slug)
items = {home.get_absolute_url(): home}
for model in apps.get_models():
if issubclass(model, self.model):
... | Returns a dictionary of urls mapped to Displayable subclass
instances, including a fake homepage instance if none exists.
Used in ``yacms.core.sitemaps``. |
357,125 | def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer,
indices: List[int]) -> None:
probs, unitaries = zip(*protocols.mixture(op))
index = np.random.choice(range(len(unitaries)), p=probs)
shape = (2,) * (2 * len(indices))
uni... | Simulate an op that is a mixtures of unitaries. |
357,126 | def get(self, tag=None, **kwargs):
if tag is None: tag = dom_tag
attrs = [(dom_tag.clean_attribute(attr), value)
for attr, value in kwargs.items()]
results = []
for child in self.children:
if (isinstance(tag, basestring) and type(child).__name__ == tag) or \
(not isinst... | Recursively searches children for tags of a certain
type with matching attributes. |
357,127 | def do_interact(self, arg):
ns = self.curframe.f_globals.copy()
ns.update(self.curframe_locals)
code.interact("*interactive*", local=ns) | interact
Start an interative interpreter whose global namespace
contains all the names found in the current scope. |
357,128 | def write(self, filename, content, overwrite=False):
if not self.overwrite and not overwrite and self.backend.exists(filename):
raise FileExists()
return self.backend.write(filename, content) | Write content to a file.
:param str filename: The storage root-relative filename
:param content: The content to write in the file
:param bool overwrite: Whether to wllow overwrite or not
:raises FileExists: If the file exists and `overwrite` is `False` |
357,129 | def bottleneck_layer(inputs,
hparams,
name="discrete_bottleneck"):
[
latents_dense,
latents_discrete,
extra_loss,
embed_fn,
_,
] = hparams.bottleneck(inputs=inputs,
filter_size=hparams.compress_filter_size,
... | Computes latents given inputs (typically, compressed targets). |
357,130 | def invert(a, b):
if HAVE_GMP:
s = int(gmpy2.invert(a, b))
if s == 0:
raise ZeroDivisionError()
return s
else:
r, s, _ = extended_euclidean_algorithm(a, b)
if r != 1:
raise ZeroDivisionError()
return s % b | The multiplicitive inverse of a in the integers modulo b.
:return int: x, where a * x == 1 mod b |
357,131 | def quit(self):
self.script.LOG.warn("Abort due to user choice!")
sys.exit(self.QUIT_RC) | Exit the program due to user's choices. |
357,132 | def json_register(self):
code1234code12
post_data = self.get_post_data()
user_create_status = self.__check_valid(post_data)
if not user_create_status[]:
return json.dump(user_create_status, self)
form = SumForm(self.request.arguments)
if form.valida... | The first char of 'code' stands for the different field.
'1' for user_name
'2' for user_email
'3' for user_pass
'4' for user_role
The seconde char of 'code' stands for different status.
'1' for invalide
'2' for already exists. |
357,133 | async def insert(self, values_lst: Iterable[SQLValuesToWrite], returning=False) -> Union[int, List[DataRecord]]:
raise NotImplementedError() | :param values_lst:
:param returning:
:return: return count if returning is False, otherwise records |
357,134 | def post(self, request, **kwargs):
serializer = CreateSubscriptionSerializer(data=request.data)
if serializer.is_valid():
try:
customer, _created = Customer.get_or_create(
subscriber=subscriber_request_callback(self.request)
)
customer.add_card(serializer.data["stripe_token"])
charge_imm... | Create a new current subscription for the user.
Returns with status code 201. |
357,135 | def run_containers(command, parser, cl_args, unknown_args):
cluster, role, env = cl_args[], cl_args[], cl_args[]
topology = cl_args[]
container_id = cl_args[]
try:
result = tracker_access.get_topology_info(cluster, env, topology, role)
except:
Log.error("Fail to connect to tracker: \", cl_args["tra... | run containers subcommand |
357,136 | def summary(self):
out = {}
for bench in self.runner.runned:
key = self.key(bench)
runs = {}
for method, results in bench.results.items():
mean = results.total / bench.times
name = bench.label_for(method)
runs[m... | Compute the execution summary |
357,137 | def _link_variables_on_expr(self, variable_manager, block, stmt_idx, stmt, expr):
if type(expr) is ailment.Expr.Register:
reg_vars = variable_manager.find_variables_by_atom(block.addr, stmt_idx, expr)
if len(reg_vars) == 1:
reg_var, off... | Link atoms (AIL expressions) in the given expression to corresponding variables identified previously.
:param variable_manager: Variable manager of the function.
:param ailment.Block block: AIL block.
:param int stmt_idx: ID of the statement.
:param stmt: The AI... |
357,138 | def create_task(self, subject, desc):
task = zobjects.Task()
task_creator = task.to_creator(subject, desc)
resp = self.request(, task_creator)
task_id = resp[]
return task_id | Create a task
:param subject: the task's subject
:param desc: the task's content in plain-text
:returns: the task's id |
357,139 | def h2i(self, pkt, x):
if isinstance(x, str) and x.startswith("v") and len(x) <= 8:
major = int(x.split(".")[0][1:])
minor = int(x.split(".")[1])
return (major << 8) | minor
elif isinstance(x, int) and 0 <= x <= 65535:
return x
else:
... | The field accepts string values like v12.1, v1.1 or integer values.
String values have to start with a "v" folled by a floating point number.
Valid numbers are between 0 and 255. |
357,140 | def get_uuid_string(low=None, high=None, **x):
if low is None or high is None:
return None
x = .join([parse_part(low), parse_part(high)])
return .join([x[:8], x[8:12], x[12:16], x[16:20], x[20:32]]) | This method parses a UUID protobuf message type from its component
'high' and 'low' longs into a standard formatted UUID string
Args:
x (dict): containing keys, 'low' and 'high' corresponding to the UUID
protobuf message type
Returns:
str: UUID formatted string |
357,141 | def classify_nearest(self, partial_labels):
labels = np.array(partial_labels, copy=True)
unlabeled = labels == -1
D_unlabeled = self.shortest_path(weighted=True)[unlabeled]
D_unlabeled[:,unlabeled] = np.inf
idx = D_unlabeled.argmin(axis=1)
labels[unlabeled] = labels[idx]... | Simple semi-supervised classification, by assigning unlabeled vertices
the label of nearest labeled vertex.
partial_labels: (n,) array of integer labels, -1 for unlabeled. |
357,142 | def export_to_html(
table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs
):
serialized_table = serialize(table, *args, **kwargs)
fields = next(serialized_table)
result = ["<table>\n\n"]
if caption and table.name:
result.extend([" <caption>", table.name, "</ca... | Export and return rows.Table data to HTML file. |
357,143 | def change(self, ident, rank=None):
self.ident = ident
if rank:
self.rank = rank
self.level = self._getLevel(rank, self.taxonomy)
self.counter += 1 | Change ident |
357,144 | def source(self, source):
if isinstance(source, list):
source = source[0] if len(source) > 0 else None
self._source = source | When the source gets updated, update the select widget |
357,145 | def gte(min_value):
def validate(value):
if value < min_value:
return e("{} is not greater than or equal to {}", value, min_value)
return validate | Validates that a field value is greater than or equal to the
value given to this validator. |
357,146 | def post_install_postgresql():
from django.conf import settings as s
with settings(warn_only=True):
sudo()
sudo(% env.password, user=)
sudo("psql -f /usr/share/postgresql/8.4/contrib/adminpack.sql", user=)
if s.DATABASES[][]==:
sudo(% (s.DATABASES[][],s.DATABASES... | example default hook for installing postgresql |
357,147 | def associate_address(self, instance_id, public_ip=None, allocation_id=None):
params = { : instance_id }
if public_ip is not None:
params[] = public_ip
elif allocation_id is not None:
params[] = allocation_id
return self.get_status(, params, verb=) | Associate an Elastic IP address with a currently running instance.
This requires one of ``public_ip`` or ``allocation_id`` depending
on if you're associating a VPC address or a plain EC2 address.
:type instance_id: string
:param instance_id: The ID of the instance
:type public_... |
357,148 | def _get_config_file(user, config):
s ssh_config.
user.infoUser \ does not existhome']
config = _expand_authorized_keys_path(config, user, home)
if not os.path.isabs(config):
config = os.path.join(home, config)
return config | Get absolute path to a user's ssh_config. |
357,149 | def log_wrapper(self):
log = logging.getLogger()
try:
debug = self.params["debug"]
log.setLevel(logging.DEBUG)
except KeyError:
log.setLevel(logging.INFO)
stream = logging.StreamHandler()
logformat = logging.Formatt... | Wrapper to set logging parameters for output |
357,150 | def telemetry_client(self, value: BotTelemetryClient) -> None:
if value is None:
self._telemetry_client = NullTelemetryClient()
else:
self._telemetry_client = value | Sets the telemetry client for logging events. |
357,151 | def tree(obj):
from .objects import Object
if isinstance(obj, (bool, int, float, str, bytes)):
return obj
elif isinstance(obj, (datetime.date, datetime.time)):
return obj.isoformat()
elif isinstance(obj, dict):
return {k: tree(v) for k, v in obj.items()}
elif isinstance(... | Convert object to a tree of lists, dicts and simple values.
The result can be serialized to JSON. |
357,152 | def boolean(input):
try:
input = input.strip().lower()
except AttributeError:
return bool(input)
if input in (, , , , , ):
return True
if input in (, , , , , ):
return False
raise ValueError("Unable to convert {0!r} to a boolean value.".format... | Convert the given input to a boolean value.
Intelligently handles boolean and non-string values, returning
as-is and passing to the bool builtin respectively.
This process is case-insensitive.
Acceptable values:
True
* yes
* y
* on
* true
*... |
357,153 | def post(fqdn, package, result, entry, bound, ekey, *argl, **argd):
global _atdepth_call, _cstack_call
_cstack_call.pop()
if len(_cstack_call) == 0:
_atdepth_call = False
r = _post_call(_atdepth_call, package, fqdn, result,
entry, bound, ekey, argl, argd)
return r | Adds logging for the post-call result of calling the method externally.
Args:
fqdn (str): fully-qualified domain name of the function being logged.
package (str): name of the package we are logging for. Usually the first
element of `fqdn.split('.')`.
result: returned from calling ... |
357,154 | def get_prop(self, key, default_val=None):
if self.props.has_key(key):
return self.props[key]
else:
return default_val | Returns a property set on the context.
:Parameters:
key
String key to lookup in the context props dict
default_val
Value to return if key is not set on the context props |
357,155 | def to_dict(self):
return {
: self.definition,
: self.term_id,
: self.image.to_dict(),
: self.rank,
: self.term
} | Convert Term into raw dictionary data. |
357,156 | def hex_to_rgb(h):
h = h.lstrip()
return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4)) | Returns 0 to 1 rgb from a hex list or tuple |
357,157 | def _validated_locations(self, locations):
valid_locations = set(self.__location_map__.keys())
given = set(locations)
invalid_locations = given - valid_locations
if len(invalid_locations):
msg = "Invalid locations arguments: {0}".format(list(invalid... | Ensure that the given locations argument is valid.
:raises: ValueError if a given locations includes an invalid location. |
357,158 | def get_most_salient_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
return _words_by_salience_score(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n) | Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from most to least salient. Optionally only
return the `n` most salient words.
J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models" |
357,159 | def from_instance(class_, instance, namespace=None, host=None,
strict=False):
keybindings = NocaseDict()
for prop in class_.properties:
if in class_.properties[prop].qualifiers:
pname = class_.properties[prop].name
if prop i... | Return a new :class:`~pywbem.CIMInstanceName` object from the key
property values in a CIM instance and the key property definitions in a
CIM class.
If the `strict` parameter is `False`, and a property value does not
exist in the `instance` that entry is not included in the constructed
... |
357,160 | def _check(self):
super(Photometry, self)._check()
err_str = None
has_flux = self._KEYS.FLUX in self
has_flux_dens = self._KEYS.FLUX_DENSITY in self
has_u_flux = self._KEYS.U_FLUX in self
has_u_flux_dens = self._KEYS.U_FLUX_DENSITY in self
has_... | Check that entry attributes are legal. |
357,161 | def getIncEdgesMap(self):
incEdgesMap = dict()
for cand1 in self.wmgMap.keys():
incEdgesSum = 0
for cand2 in self.wmgMap[cand1].keys():
if self.wmgMap[cand1][cand2] > 0:
incEdgesSum += self.wmgMap[cand1][cand2]
... | Returns a dictionary that associates numbers of incoming edges in the weighted majority
graph with the candidates that have that number of incoming edges. |
357,162 | def build(self) -> type:
def _get_property_mappings(encoder: MappingJSONEncoder) -> List[JsonPropertyMapping]:
return _get_all_property_mappings(encoder, self.mappings, self.superclasses)
def get_serializable_cls(encoder: MappingJSONEncoder) -> type:
return self.target_... | Build a subclass of `MappingJSONEncoder`.
:return: the built subclass |
357,163 | def main(args, options, parser):
from spython.main.parse import ( DockerRecipe, SingularityRecipe )
if not args.files:
parser.print_help()
sys.exit(1)
outfile = None
if len(args.files) > 1:
outfile = args.files[1]
parser = SingularityRecipe
if ... | This function serves as a wrapper around the DockerRecipe and
SingularityRecipe converters. We can either save to file if
args.outfile is defined, or print to the console if not. |
357,164 | def _match_one_or_many(self, models, results, relation, type_):
dictionary = self._build_dictionary(results)
for model in models:
key = model.get_attribute(self._local_key)
if key in dictionary:
value = Result(
self._get_relation_val... | Match the eargerly loaded resuls to their single parents.
:param models: The parents
:type models: list
:param results: The results collection
:type results: Collection
:param relation: The relation
:type relation: str
:param type_: The match type
:typ... |
357,165 | def write(self, string):
bytes_ = string.encode(self._encoding)
self._file.write(bytes_) | Write a string to the file. |
357,166 | def _repr_html_(self):
r = .join([, , , ])
rows = .format(r)
for i, w in enumerate(self.__list):
rows += .format(i)
rows += .format(w.uwi)
rows += .format(len(w.data))
rows += .format(.join(w.data.keys()))
html =... | Jupyter Notebook magic repr function. |
357,167 | def ReadFlowRequestsReadyForProcessing(self,
client_id,
flow_id,
next_needed_request=None):
request_dict = self.flow_requests.get((client_id, flow_id), {})
response_dict = self.flow_re... | Reads all requests for a flow that can be processed by the worker. |
357,168 | def parse_date(value: Union[date, StrIntFloat]) -> date:
if isinstance(value, date):
if isinstance(value, datetime):
return value.date()
else:
return value
number = get_numeric(value)
if number is not None:
return from_unix_seconds(number).date()
ma... | Parse a date/int/float/string and return a datetime.date.
Raise ValueError if the input is well formatted but not a valid date.
Raise ValueError if the input isn't well formatted. |
357,169 | def _item_to_database(self, iterator, database_pb):
return Database.from_pb(database_pb, self, pool=BurstyPool()) | Convert a database protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type database_pb: :class:`~google.spanner.admin.database.v1.Database`
:param database_pb: A database returned from... |
357,170 | def ParseVideoRow(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = KodiVideoEventData()
event_data.filename = self._GetRowValue(query_hash, row, )
event_data.play_count = self._GetRowValue(query_hash, row, )
event_data.query = query
timestamp = se... | Parses a Video row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. |
357,171 | def _summary_csv_by_researcher(summary_yaml, researcher, descrs, data):
out_file = os.path.join(utils.safe_makedir(os.path.join(data["dirs"]["work"], "researcher")),
"%s-summary.tsv" % run_info.clean_name(researcher))
metrics = ["Total_reads", "Mapped_reads", "Mapped_reads_pct",... | Generate a CSV file with summary information for a researcher on this project. |
357,172 | def generate_version_py(packagename=None, version=None, release=None, debug=None,
uses_git=None, srcdir=):
if packagename is not None:
warnings.warn(
, AstropyDeprecationWarning)
if version is not None:
warnings.warn(
... | Generate a version.py file in the package with version information, and
update developer version strings.
This function should normally be called without any arguments. In this case
the package name and version is read in from the ``setup.cfg`` file (from
the ``name`` or ``package_name`` entry and the ... |
357,173 | def repay_loan(self, order_id, amount):
params = {: order_id, : amount}
path = f
def _wrapper(_func):
@wraps(_func)
def handle():
_func(api_key_post(params, path))
return handle
return _wrapper | 归还借贷
:param order_id:
:param amount:
:return: |
357,174 | def id(self, value):
if value == self._defaults[] and in self._values:
del self._values[]
else:
self._values[] = value | The id property.
Args:
value (string). the property value. |
357,175 | def clean(self, *args, **kwargs):
for key in list(self.store.keys()):
self.unset(key) | Clean all loaded values to reload when switching envs |
357,176 | def fun_residuals(params, xnor, ynor, w, bbox, k, ext):
spl = LSQUnivariateSpline(
x=xnor,
y=ynor,
t=[item.value for item in params.values()],
w=w,
bbox=bbox,
k=k,
ext=ext,
check_finite=False
)
return spl.get_residual() | Compute fit residuals |
357,177 | def do_default(value, default_value=u, boolean=False):
if (boolean and not value) or isinstance(value, Undefined):
return default_value
return value | If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defi... |
357,178 | def get_resampled_top_edge(self, angle_var=0.1):
mesh = self.mesh
top_edge = [Point(mesh.lons[0][0], mesh.lats[0][0], mesh.depths[0][0])]
for i in range(len(mesh.triangulate()[1][0]) - 1):
v1 = numpy.asarray(mesh.triangulate()[1][0][i])
v2 = numpy.asarray(mesh.t... | This methods computes a simplified representation of a fault top edge
by removing the points that are not describing a change of direction,
provided a certain tolerance angle.
:param float angle_var:
Number representing the maximum deviation (in degrees) admitted
without... |
357,179 | def create_service(resource_root, name, service_type,
cluster_name="default"):
apiservice = ApiService(resource_root, name, service_type)
return call(resource_root.post,
SERVICES_PATH % (cluster_name,),
ApiService, True, data=[apiservice])[0] | Create a service
@param resource_root: The root Resource object.
@param name: Service name
@param service_type: Service type
@param cluster_name: Cluster name
@return: An ApiService object |
357,180 | def ancestor(self, value):
if not isinstance(value, Key):
raise TypeError("Ancestor must be a Key")
self._ancestor = value | Set the ancestor for the query
:type value: :class:`~google.cloud.datastore.key.Key`
:param value: the new ancestor key |
357,181 | def configureAndBuild(self, nocompressjs=False):
jsb = self.createCleanJsbConfig()
self.buildFromJsbString(jsb, nocompressjs) | Run :meth:`createCleanJsbConfig` and :meth:`build`. |
357,182 | def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False):
min_mel = hz_to_mel(fmin, htk=htk)
max_mel = hz_to_mel(fmax, htk=htk)
mels = np.linspace(min_mel, max_mel, n_mels)
return mel_to_hz(mels, htk=htk) | Compute an array of acoustic frequencies tuned to the mel scale.
The mel scale is a quasi-logarithmic function of acoustic frequency
designed such that perceptually similar pitch intervals (e.g. octaves)
appear equal in width over the full hearing range.
Because the definition of the mel scale is cond... |
357,183 | def _set_interface_flooding_up_threshold(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {:... | Setter method for interface_flooding_up_threshold, mapped from YANG variable /mpls_state/rsvp/interfaces/interface_flooding_up_threshold (feature-config-source)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_flooding_up_threshold is considered as a private
method.... |
357,184 | def get_outlier_info(pronac):
df = data.planilha_captacao
raised_funds_averages = data.segment_raised_funds_average.to_dict()
segment_id = df[df[] == pronac][].iloc[0]
mean = raised_funds_averages[segment_id][]
std = raised_funds_averages[segment_id][]
project_raised_funds = get_project_... | Return if a project with the given
pronac is an outlier based on raised funds. |
357,185 | def parse_from_file(filename, nodata=False):
header = None
with open(filename, "rb") as file:
header = read_machine_header(file)
meta_raw = file.read(header[])
meta = __parse_meta(meta_raw, header)
data = b
if not nodata:
data = __decompress(meta, file.re... | Parse df message from file.
@filename - path to file
@nodata - do not load data
@return - [binary header, metadata, binary data] |
357,186 | def drop(self, labels, dim=None):
if utils.is_scalar(labels):
labels = [labels]
if dim is None:
return self._drop_vars(labels)
else:
try:
index = self.indexes[dim]
except KeyError:
raise ValueError(
... | Drop variables or index labels from this dataset.
Parameters
----------
labels : scalar or list of scalars
Name(s) of variables or index labels to drop.
dim : None or str, optional
Dimension along which to drop index labels. By default (if
``dim is No... |
357,187 | def value(self):
result = sum(led.value for led in self)
if self[0].value < self[-1].value:
result = -result
return result / len(self) | The value of the LED bar graph. When no LEDs are lit, the value is 0.
When all LEDs are lit, the value is 1. Values between 0 and 1
light LEDs linearly from first to last. Values between 0 and -1
light LEDs linearly from last to first.
To light a particular number of LEDs, simply divide... |
357,188 | def data_mod(self, *args, **kwargs):
for instrument in self.instruments:
instrument.custom.add(*args, **kwargs) | Register a function to modify data of member Instruments.
The function is not partially applied to modify member data.
When the Constellation receives a function call to register a function for data modification,
it passes the call to each instrument and registers it in the instrument's pysat.... |
357,189 | def retrieve(self, id) :
_, _, deal = self.http_client.get("/deals/{id}".format(id=id))
deal["value"] = Coercion.to_decimal(deal["value"])
return deal | Retrieve a single deal
Returns a single deal available to the user, according to the unique deal ID provided
If the specified deal does not exist, the request will return an error
:calls: ``get /deals/{id}``
:param int id: Unique identifier of a Deal.
:return: Dictionary that s... |
357,190 | def __normalized_name(self, message_type):
name = message_type.definition_name()
split_name = re.split(r, name)
normalized = .join(
part[0].upper() + part[1:] for part in split_name if part)
previous = self.__normalized_names.get(normalized)
if previous:
if previous !=... | Normalized schema name.
Generate a normalized schema name, taking the class name and stripping out
everything but alphanumerics, and camel casing the remaining words.
A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]*
Args:
message_type: protorpc.message.Message class being par... |
357,191 | def _check_targets(self):
if self.outputs:
targets = self.outputs.copy()
def check_targets(node_id):
try:
targets.remove(node_id)
return not targets
except KeyError:
... | Returns a function to terminate the ArciDispatch algorithm when all
targets have been visited.
:return:
A function to terminate the ArciDispatch algorithm.
:rtype: (str) -> bool |
357,192 | def dropped(self, component, event):
if isinstance(component, AbstractStimulusComponent):
row, col = self.splitAt(event.pos())
index = self.model().createIndex(row, col, component)
self.model().insertComponent(index, component)
if isinstance... | Adds the dropped *component* into the model.
:meth:`Re-implemented<sparkle.gui.abstract_drag_view.AbstractDragView.dropped>` |
357,193 | def authenticate_direct_bind(self, username, password):
bind_user = .format(
rdn=self.config.get(),
username=username,
user_search_dn=self.full_user_search_dn,
)
connection = self._make_connection(
bind_user=bind_user,
bind_p... | Performs a direct bind. We can do this since the RDN is the same
as the login attribute. Hence we just string together a dn to find
this user with.
Args:
username (str): Username of the user to bind (the field specified
as LDAP_BIND_RDN_ATTR)
password (st... |
357,194 | def month(self):
url = "/stats/month"
result = self._get(url)
return StatModel.parse(result) | Get the overall Unsplash stats for the past 30 days.
:return [Stat]: The Unsplash Stat. |
357,195 | def param_names(self):
pn = CombinedBounds(self.k.param_names, self.noise_k.param_names)
if self.mu is not None:
pn = CombinedBounds(pn, self.mu.param_names)
return pn | Combined names for the hyperparameters for the kernel, noise kernel and (if present) mean function. |
357,196 | def run_restore(self, snapshot: Dict[Union[str, Key], Any]) -> :
try:
for name, snap in snapshot.items():
if isinstance(name, Key):
self._nested_items[name.group].run_restore(snap)
else:
self._nested_items[name].run_re... | Restores the state of a collection from a snapshot |
357,197 | def _init_c2ps(self, go_sources, traverse_child):
if not traverse_child:
return {}
c2ps = defaultdict(set)
goids_seen = set()
go2obj = self.go2obj
for goid_src in go_sources:
goobj_src = go2obj[goid_src]
if goid_src not in goids_seen:
... | Traverse up children. |
357,198 | def pressure(self):
pressure = self._libinput.libinput_event_tablet_tool_get_pressure(
self._handle)
changed = self._libinput. \
libinput_event_tablet_tool_pressure_has_changed(self._handle)
return pressure, changed | The current pressure being applied on the tool in use,
normalized to the range [0, 1] and whether it has changed in this event.
If this axis does not exist on the current tool, this property is
(0, :obj:`False`).
Returns:
(float, bool): The current value of the the axis and whether it has
changed. |
357,199 | async def pin_chat_message(self, chat_id: typing.Union[base.Integer, base.String], message_id: base.Integer,
disable_notification: typing.Union[base.Boolean, None] = None) -> base.Boolean:
payload = generate_payload(**locals())
result = await self.request(api.Met... | Use this method to pin a message in a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#pinchatmessage
:param chat_id: Unique identifier for the target chat or username of the target ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.