text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def append(self, child):
"""
Append the given child
:class:`Element <hl7apy.core.Element>`
:param child: an instance of an :class:`Element <hl7apy.core.Element>` subclass
"""
if self._can_add_child(child):
if self.element == child.parent:
self... | [
"def",
"append",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"_can_add_child",
"(",
"child",
")",
":",
"if",
"self",
".",
"element",
"==",
"child",
".",
"parent",
":",
"self",
".",
"_remove_from_traversal_index",
"(",
"child",
")",
"self",
... | 39.5 | 14.9 |
def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str,
password: str) -> Membership:
"""
Get a Membership document
:param membership_type: "IN" to ask for membership or "OUT" to cancel membership
:param current_block: Current bl... | [
"def",
"get_membership_document",
"(",
"membership_type",
":",
"str",
",",
"current_block",
":",
"dict",
",",
"identity",
":",
"Identity",
",",
"salt",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"Membership",
":",
"# get current block BlockStamp",
"time... | 28.972222 | 19.194444 |
def getDetail(self, row, detail_field):
"""Gets the value of the detail *detail_field* of paramter
at index *row* from its selected components `auto_details`.
All of the selected components value for *detail_field* must
match
:param row: the ith parameter number
:type ro... | [
"def",
"getDetail",
"(",
"self",
",",
"row",
",",
"detail_field",
")",
":",
"param",
"=",
"self",
".",
"_parameters",
"[",
"row",
"]",
"param_type",
"=",
"param",
"[",
"'parameter'",
"]",
"components",
"=",
"param",
"[",
"'selection'",
"]",
"if",
"len",
... | 40.9375 | 12.59375 |
def expose_attribute(self, local_name, attribute_type, remote_name=None, display_name=None, is_required=False, is_readonly=False, max_length=None, min_length=None, is_identifier=False, choices=None, is_unique=False, is_email=False, is_login=False, is_editable=True, is_password=False, can_order=False, can_search=False, ... | [
"def",
"expose_attribute",
"(",
"self",
",",
"local_name",
",",
"attribute_type",
",",
"remote_name",
"=",
"None",
",",
"display_name",
"=",
"None",
",",
"is_required",
"=",
"False",
",",
"is_readonly",
"=",
"False",
",",
"max_length",
"=",
"None",
",",
"min... | 46.060606 | 22.393939 |
def _eq(self, T, P):
"""Procedure for calculate the composition in saturation state
Parameters
----------
T : float
Temperature [K]
P : float
Pressure [MPa]
Returns
-------
Asat : float
Saturation mass fraction of dry ... | [
"def",
"_eq",
"(",
"self",
",",
"T",
",",
"P",
")",
":",
"if",
"T",
"<=",
"273.16",
":",
"ice",
"=",
"_Ice",
"(",
"T",
",",
"P",
")",
"gw",
"=",
"ice",
"[",
"\"g\"",
"]",
"else",
":",
"water",
"=",
"IAPWS95",
"(",
"T",
"=",
"T",
",",
"P",... | 24.939394 | 19.272727 |
def restore_app_connection(self, port=None):
"""Restores the sl4a after device got disconnected.
Instead of creating new instance of the client:
- Uses the given port (or find a new available host_port if none is
given).
- Tries to connect to remote server with selected ... | [
"def",
"restore_app_connection",
"(",
"self",
",",
"port",
"=",
"None",
")",
":",
"self",
".",
"host_port",
"=",
"port",
"or",
"utils",
".",
"get_available_host_port",
"(",
")",
"self",
".",
"_retry_connect",
"(",
")",
"self",
".",
"ed",
"=",
"self",
"."... | 39.421053 | 23.631579 |
def exit(exit_code=0):
"""
Exits the Application.
:param exit_code: Exit code.
:type exit_code: int
"""
for line in SESSION_FOOTER_TEXT:
LOGGER.info(line)
foundations.verbose.remove_logging_handler(RuntimeGlobals.logging_console_handler)
RuntimeGlobals.application.exit(exit_c... | [
"def",
"exit",
"(",
"exit_code",
"=",
"0",
")",
":",
"for",
"line",
"in",
"SESSION_FOOTER_TEXT",
":",
"LOGGER",
".",
"info",
"(",
"line",
")",
"foundations",
".",
"verbose",
".",
"remove_logging_handler",
"(",
"RuntimeGlobals",
".",
"logging_console_handler",
... | 22.214286 | 20.5 |
def finish_async_rpc(self, address, rpc_id, response):
"""Finish a previous asynchronous RPC.
This method should be called by a peripheral tile that previously
had an RPC called on it and chose to response asynchronously by
raising ``AsynchronousRPCResponse`` in the RPC handler itself.
... | [
"def",
"finish_async_rpc",
"(",
"self",
",",
"address",
",",
"rpc_id",
",",
"response",
")",
":",
"pending",
"=",
"self",
".",
"_pending_rpcs",
".",
"get",
"(",
"address",
")",
"if",
"pending",
"is",
"None",
":",
"raise",
"ArgumentError",
"(",
"\"No asynch... | 38.969697 | 25.969697 |
def hashtags(self, quantity: int = 4) -> Union[str, list]:
"""Generate a list of hashtags.
:param quantity: The quantity of hashtags.
:return: The list of hashtags.
:raises NonEnumerableError: if category is not in Hashtag.
:Example:
['#love', '#sky', '#nice']
... | [
"def",
"hashtags",
"(",
"self",
",",
"quantity",
":",
"int",
"=",
"4",
")",
"->",
"Union",
"[",
"str",
",",
"list",
"]",
":",
"tags",
"=",
"[",
"'#'",
"+",
"self",
".",
"random",
".",
"choice",
"(",
"HASHTAGS",
")",
"for",
"_",
"in",
"range",
"... | 28.411765 | 17.470588 |
def authenticate(self, username=None, password=None, **kwargs):
"""The authenticate method takes credentials as keyword arguments,
usually username/email and password.
Returns a user model if the Stormpath authentication was successful or
None otherwise. It expects three variable to be ... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"username",
"is",
"None",
":",
"UserModel",
"=",
"get_user_model",
"(",
")",
"username",
"=",
"kwargs",
".",
"get",... | 40 | 17.571429 |
def Decrypt(self, data):
"""A convenience method which pads and decrypts at once."""
decryptor = self.GetDecryptor()
try:
padded_data = decryptor.update(data) + decryptor.finalize()
return self.UnPad(padded_data)
except ValueError as e:
raise CipherError(e) | [
"def",
"Decrypt",
"(",
"self",
",",
"data",
")",
":",
"decryptor",
"=",
"self",
".",
"GetDecryptor",
"(",
")",
"try",
":",
"padded_data",
"=",
"decryptor",
".",
"update",
"(",
"data",
")",
"+",
"decryptor",
".",
"finalize",
"(",
")",
"return",
"self",
... | 31.555556 | 16.555556 |
def cos_r(self, N=None): # percent=0.9
"""Return the squared cosines for each row."""
if not hasattr(self, 'F') or self.F.shape[1] < self.rank:
self.fs_r(N=self.rank) # generate F
self.dr = norm(self.F, axis=1)**2
# cheaper than diag(self.F.dot(self.F.T))?
return apply_along_axis(lambda _: _/self.dr, 0... | [
"def",
"cos_r",
"(",
"self",
",",
"N",
"=",
"None",
")",
":",
"# percent=0.9",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'F'",
")",
"or",
"self",
".",
"F",
".",
"shape",
"[",
"1",
"]",
"<",
"self",
".",
"rank",
":",
"self",
".",
"fs_r",
"(",
... | 36.777778 | 15.222222 |
def list_endpoints(self):
"""Lists the known object storage endpoints."""
_filter = {
'hubNetworkStorage': {'vendorName': {'operation': 'Swift'}},
}
endpoints = []
network_storage = self.client.call('Account',
'getHubNetworkS... | [
"def",
"list_endpoints",
"(",
"self",
")",
":",
"_filter",
"=",
"{",
"'hubNetworkStorage'",
":",
"{",
"'vendorName'",
":",
"{",
"'operation'",
":",
"'Swift'",
"}",
"}",
",",
"}",
"endpoints",
"=",
"[",
"]",
"network_storage",
"=",
"self",
".",
"client",
... | 40.8 | 18.25 |
def fetch_git_sha(path, head=None):
"""
>>> fetch_git_sha(os.path.dirname(__file__))
"""
if not head:
head_path = os.path.join(path, '.git', 'HEAD')
if not os.path.exists(head_path):
raise InvalidGitRepository(
'Cannot identify HEAD for git repository at %s' %... | [
"def",
"fetch_git_sha",
"(",
"path",
",",
"head",
"=",
"None",
")",
":",
"if",
"not",
"head",
":",
"head_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.git'",
",",
"'HEAD'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(... | 37.166667 | 16.333333 |
def prepare_roomMap(roomMap):
""" Prepares the roomMap to be JSONified. That is: convert the non
JSON serializable objects such as set() """
ret = {}
for room in roomMap:
ret[room] = [roomMap[room].name, list(roomMap[room].pcs)]
return ret | [
"def",
"prepare_roomMap",
"(",
"roomMap",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"room",
"in",
"roomMap",
":",
"ret",
"[",
"room",
"]",
"=",
"[",
"roomMap",
"[",
"room",
"]",
".",
"name",
",",
"list",
"(",
"roomMap",
"[",
"room",
"]",
".",
"pcs",... | 37.857143 | 15.142857 |
def columns(self, model=None):
"""
Returns a generator that loops through the columns that are associated with this query.
:return <generator>(orb.Column)
"""
column = self.column(model=model)
if column:
yield column
check = self.__value
... | [
"def",
"columns",
"(",
"self",
",",
"model",
"=",
"None",
")",
":",
"column",
"=",
"self",
".",
"column",
"(",
"model",
"=",
"model",
")",
"if",
"column",
":",
"yield",
"column",
"check",
"=",
"self",
".",
"__value",
"if",
"not",
"isinstance",
"(",
... | 30.277778 | 16.833333 |
def validate(path, format='json',
approved_applications=None,
determined=True,
listed=True,
expectation=PACKAGE_ANY,
for_appversions=None,
overrides=None,
timeout=-1,
compat_test=False,
**kw):
"""
... | [
"def",
"validate",
"(",
"path",
",",
"format",
"=",
"'json'",
",",
"approved_applications",
"=",
"None",
",",
"determined",
"=",
"True",
",",
"listed",
"=",
"True",
",",
"expectation",
"=",
"PACKAGE_ANY",
",",
"for_appversions",
"=",
"None",
",",
"overrides"... | 38.842857 | 20.1 |
def nest_values(self, levels, level=0, metric=None, dims=()):
"""
Nest values at each level on the back-end with
access and setting, instead of summing from the bottom.
"""
if not level:
return [{
'name': m,
'val': levels[0][m],
... | [
"def",
"nest_values",
"(",
"self",
",",
"levels",
",",
"level",
"=",
"0",
",",
"metric",
"=",
"None",
",",
"dims",
"=",
"(",
")",
")",
":",
"if",
"not",
"level",
":",
"return",
"[",
"{",
"'name'",
":",
"m",
",",
"'val'",
":",
"levels",
"[",
"0"... | 36.038462 | 13.807692 |
def log_scalar(self, name, value, step=None):
"""
Add a new measurement.
The measurement will be processed by the MongoDB* observer
during a heartbeat event.
Other observers are not yet supported.
:param name: The name of the metric, e.g. training.loss
:param va... | [
"def",
"log_scalar",
"(",
"self",
",",
"name",
",",
"value",
",",
"step",
"=",
"None",
")",
":",
"# Method added in change https://github.com/chovanecm/sacred/issues/4",
"# The same as Run.log_scalar",
"return",
"self",
".",
"current_run",
".",
"log_scalar",
"(",
"name"... | 41.941176 | 17.235294 |
def lstsq(a, b, rcond=None, weighted=False, extrainfo=False):
""" Least-squares solution ``x`` to ``a @ x = b`` for |GVar|\s.
Here ``x`` is defined to be the solution that minimizes ``||b - a @ x||``.
If ``b`` has a covariance matrix, another option is to weight the
norm with the inverse covariance mat... | [
"def",
"lstsq",
"(",
"a",
",",
"b",
",",
"rcond",
"=",
"None",
",",
"weighted",
"=",
"False",
",",
"extrainfo",
"=",
"False",
")",
":",
"a",
"=",
"numpy",
".",
"asarray",
"(",
"a",
")",
"b",
"=",
"numpy",
".",
"asarray",
"(",
"b",
")",
"if",
... | 42.432836 | 21.447761 |
def create_networks(self, ids, id_vlan):
"""Set column 'active = 1' in tables redeipv4 and redeipv6]
:param ids: ID for NetworkIPv4 and/or NetworkIPv6
:return: Nothing
"""
network_map = dict()
network_map['ids'] = ids
network_map['id_vlan'] = id_vlan
c... | [
"def",
"create_networks",
"(",
"self",
",",
"ids",
",",
"id_vlan",
")",
":",
"network_map",
"=",
"dict",
"(",
")",
"network_map",
"[",
"'ids'",
"]",
"=",
"ids",
"network_map",
"[",
"'id_vlan'",
"]",
"=",
"id_vlan",
"code",
",",
"xml",
"=",
"self",
".",... | 27.0625 | 17.8125 |
def delete_model(self, model_id, erase=False):
"""Delete the model with given identifier in the database. Returns the
handle for the deleted model or None if object identifier is unknown.
Parameters
----------
model_id : string
Unique model identifier
erase :... | [
"def",
"delete_model",
"(",
"self",
",",
"model_id",
",",
"erase",
"=",
"False",
")",
":",
"return",
"self",
".",
"delete_object",
"(",
"model_id",
",",
"erase",
"=",
"erase",
")"
] | 35.411765 | 21.117647 |
def decompress(obj, return_type="bytes"):
"""
De-compress it to it's original.
:param obj: Compressed object, could be bytes or str.
:param return_type: if bytes, then return bytes; if str, then use
base64.b64decode; if obj, then use pickle.loads return an object.
"""
if isinstance(obj,... | [
"def",
"decompress",
"(",
"obj",
",",
"return_type",
"=",
"\"bytes\"",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":",
"b",
"=",
"zlib",
".",
"decompress",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"string_types",
... | 34.208333 | 17.458333 |
def get_account(self, account_id, **kwargs):
"""Retrieves a CDN account with the specified account ID.
:param account_id int: the numeric ID associated with the CDN account.
:param dict \\*\\*kwargs: additional arguments to include in the object
mask.
"""... | [
"def",
"get_account",
"(",
"self",
",",
"account_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"'status'",
"return",
"self",
".",
"account",
".",
"getObject",
"(",
"id",
"=",
"a... | 37.083333 | 19.75 |
def get_id(self):
"""Returns unique id of an alignment. """
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) | [
"def",
"get_id",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"str",
"(",
"self",
".",
"title",
")",
"+",
"str",
"(",
"self",
".",
"best_score",
"(",
")",
")",
"+",
"str",
"(",
"self",
".",
"hit_def",
")",
")"
] | 49.333333 | 21.333333 |
def iterativeFetch(query, batchSize=default_batch_size):
"""
Returns rows of a sql fetch query on demand
"""
while True:
rows = query.fetchmany(batchSize)
if not rows:
break
rowDicts = sqliteRowsToDicts(rows)
for rowDict in rowDicts:
yield rowDict | [
"def",
"iterativeFetch",
"(",
"query",
",",
"batchSize",
"=",
"default_batch_size",
")",
":",
"while",
"True",
":",
"rows",
"=",
"query",
".",
"fetchmany",
"(",
"batchSize",
")",
"if",
"not",
"rows",
":",
"break",
"rowDicts",
"=",
"sqliteRowsToDicts",
"(",
... | 28.090909 | 10.636364 |
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
self.latest_newline = t.lexpos | [
"def",
"t_newline",
"(",
"self",
",",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"len",
"(",
"t",
".",
"value",
")",
"self",
".",
"latest_newline",
"=",
"t",
".",
"lexpos"
] | 28.25 | 11.75 |
def insert_list_of_dictionaries_into_database_tables(
dbConn,
log,
dictList,
dbTableName,
uniqueKeyList=[],
dateModified=False,
dateCreated=True,
batchSize=2500,
replace=False,
dbSettings=False):
"""insert list of dictionaries into data... | [
"def",
"insert_list_of_dictionaries_into_database_tables",
"(",
"dbConn",
",",
"log",
",",
"dictList",
",",
"dbTableName",
",",
"uniqueKeyList",
"=",
"[",
"]",
",",
"dateModified",
"=",
"False",
",",
"dateCreated",
"=",
"True",
",",
"batchSize",
"=",
"2500",
","... | 31.412698 | 22.539683 |
def remove_certain_leaves(tr, to_remove=lambda node: False):
"""
Removes all the branches leading to leaves identified positively by to_remove function.
:param tr: the tree of interest (ete3 Tree)
:param to_remove: a method to check is a leaf should be removed.
:return: void, modifies the initial tr... | [
"def",
"remove_certain_leaves",
"(",
"tr",
",",
"to_remove",
"=",
"lambda",
"node",
":",
"False",
")",
":",
"tips",
"=",
"[",
"tip",
"for",
"tip",
"in",
"tr",
"if",
"to_remove",
"(",
"tip",
")",
"]",
"for",
"node",
"in",
"tips",
":",
"if",
"node",
... | 36 | 13.538462 |
def _enable_rpcs(self, conn, services, timeout=1.0):
"""Prepare this device to receive RPCs
"""
#FIXME: Check for characteristic existence in a try/catch and return failure if not found
success, result = self._set_notification(conn, services[TileBusService]['characteristics'][TileBusRe... | [
"def",
"_enable_rpcs",
"(",
"self",
",",
"conn",
",",
"services",
",",
"timeout",
"=",
"1.0",
")",
":",
"#FIXME: Check for characteristic existence in a try/catch and return failure if not found",
"success",
",",
"result",
"=",
"self",
".",
"_set_notification",
"(",
"co... | 50.272727 | 38.363636 |
def appendQKeyEvent(self, keyEvent: QtGui.QKeyEvent):
"""
Append another key to the key sequence represented by this object.
|Args|
* ``keyEvent`` (**QKeyEvent**): the key to add.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one ... | [
"def",
"appendQKeyEvent",
"(",
"self",
",",
"keyEvent",
":",
"QtGui",
".",
"QKeyEvent",
")",
":",
"# Store the QKeyEvent.",
"self",
".",
"keylistKeyEvent",
".",
"append",
"(",
"keyEvent",
")",
"# Convenience shortcuts.",
"mod",
"=",
"keyEvent",
".",
"modifiers",
... | 28.892857 | 23.464286 |
def get_by_id(self, id_code: str) -> Currency or None:
""" Get currency by ID
:param id_code: set, like "R01305"
:return: currency or None.
"""
try:
return [_ for _ in self.currencies if _.id == id_code][0]
except IndexError:
return None | [
"def",
"get_by_id",
"(",
"self",
",",
"id_code",
":",
"str",
")",
"->",
"Currency",
"or",
"None",
":",
"try",
":",
"return",
"[",
"_",
"for",
"_",
"in",
"self",
".",
"currencies",
"if",
"_",
".",
"id",
"==",
"id_code",
"]",
"[",
"0",
"]",
"except... | 30.1 | 15 |
def get_chromosome_priority(chrom, chrom_dict={}):
"""
Return the chromosome priority
Arguments:
chrom (str): The cromosome name from the vcf
chrom_dict (dict): A map of chromosome names and theis priority
Return:
priority (str): The priority for this chromosom
"""
... | [
"def",
"get_chromosome_priority",
"(",
"chrom",
",",
"chrom_dict",
"=",
"{",
"}",
")",
":",
"priority",
"=",
"0",
"chrom",
"=",
"str",
"(",
"chrom",
")",
".",
"lstrip",
"(",
"'chr'",
")",
"if",
"chrom_dict",
":",
"priority",
"=",
"chrom_dict",
".",
"ge... | 24.212121 | 18.090909 |
def _extract_ld_data(data, data_format=None, **kwargs):
"""Extract the given :attr:`data` into a
:class:`~.ExtractedLinkedDataResult` with the resulting data
stripped of any Linked Data specifics. Any missing Linked Data
properties are returned as ``None`` in the resulting
:class:`~.ExtractLinkedDat... | [
"def",
"_extract_ld_data",
"(",
"data",
",",
"data_format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"data_format",
":",
"data_format",
"=",
"_get_format_from_data",
"(",
"data",
")",
"extract_ld_data_fn",
"=",
"_data_format_resolver",
"(",
... | 38.388889 | 14.666667 |
def add(self, key, value,
description='',
history_max_size=None):
"""Add an new item (key, value) to the current history."""
if key not in self.stats_history:
self.stats_history[key] = GlancesAttribute(key,
descri... | [
"def",
"add",
"(",
"self",
",",
"key",
",",
"value",
",",
"description",
"=",
"''",
",",
"history_max_size",
"=",
"None",
")",
":",
"if",
"key",
"not",
"in",
"self",
".",
"stats_history",
":",
"self",
".",
"stats_history",
"[",
"key",
"]",
"=",
"Glan... | 51.777778 | 16.222222 |
def update_machine_state(self, machine_state):
"""Updates the machine state in the VM process.
Must be called only in certain cases
(see the method implementation).
in machine_state of type :class:`MachineState`
raises :class:`VBoxErrorInvalidVmState`
Session state ... | [
"def",
"update_machine_state",
"(",
"self",
",",
"machine_state",
")",
":",
"if",
"not",
"isinstance",
"(",
"machine_state",
",",
"MachineState",
")",
":",
"raise",
"TypeError",
"(",
"\"machine_state can only be an instance of type MachineState\"",
")",
"self",
".",
"... | 37.722222 | 14.5 |
def supports_gzip(self, context):
"""
Looks at the RequestContext object and determines if the client
supports gzip encoded content. If the client does, we will send them
to the gzipped version of files that are allowed to be compressed.
Clients without gzip support will be serve... | [
"def",
"supports_gzip",
"(",
"self",
",",
"context",
")",
":",
"if",
"'request'",
"in",
"context",
"and",
"client",
".",
"supports_gzip",
"(",
")",
":",
"enc",
"=",
"context",
"[",
"'request'",
"]",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT_ENCODING'",
... | 51 | 21.181818 |
def makeindex_runs(self, gloss_files):
'''
Check for each glossary if it has to be regenerated
with "makeindex".
@return: True if "makeindex" was called.
'''
gloss_changed = False
for gloss in self.glossaries:
make_gloss = False
ext_i, ext... | [
"def",
"makeindex_runs",
"(",
"self",
",",
"gloss_files",
")",
":",
"gloss_changed",
"=",
"False",
"for",
"gloss",
"in",
"self",
".",
"glossaries",
":",
"make_gloss",
"=",
"False",
"ext_i",
",",
"ext_o",
"=",
"self",
".",
"glossaries",
"[",
"gloss",
"]",
... | 37.641026 | 15.282051 |
def main(argv=None):
"""ben-umb entry point"""
arguments = cli_common(__doc__, argv=argv)
driver = CampaignDriver(arguments['CAMPAIGN-DIR'], expandcampvars=False)
driver(no_exec=True)
if argv is not None:
return driver | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"arguments",
"=",
"cli_common",
"(",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"driver",
"=",
"CampaignDriver",
"(",
"arguments",
"[",
"'CAMPAIGN-DIR'",
"]",
",",
"expandcampvars",
"=",
"False",
")",
"dr... | 34.285714 | 16.142857 |
def apply_attributes(self, nc, table, prefix=''):
"""
apply fixed attributes, or look up attributes needed and apply them
"""
for name, value in sorted(table.items()):
if name in nc.ncattrs():
LOG.debug('already have a value for %s' % name)
con... | [
"def",
"apply_attributes",
"(",
"self",
",",
"nc",
",",
"table",
",",
"prefix",
"=",
"''",
")",
":",
"for",
"name",
",",
"value",
"in",
"sorted",
"(",
"table",
".",
"items",
"(",
")",
")",
":",
"if",
"name",
"in",
"nc",
".",
"ncattrs",
"(",
")",
... | 40.894737 | 12.263158 |
def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes):
"""
map all read sets against all fasta files
"""
if cluster is True:
threads = '48'
btc = []
for fa in fas:
btd = bowtiedb(fa, keepDB)
F, R, U = reads
if F is not False:
if... | [
"def",
"crossmap",
"(",
"fas",
",",
"reads",
",",
"options",
",",
"no_shrink",
",",
"keepDB",
",",
"threads",
",",
"cluster",
",",
"nodes",
")",
":",
"if",
"cluster",
"is",
"True",
":",
"threads",
"=",
"'48'",
"btc",
"=",
"[",
"]",
"for",
"fa",
"in... | 37.952381 | 18.333333 |
def _kill_all_kids(self, sig):
"""
Kill all subprocesses (and its subprocesses) that executor started.
This function tries to kill all leftovers in process tree that current
executor may have left. It uses environment variable to recognise if
process have origin in this Executor... | [
"def",
"_kill_all_kids",
"(",
"self",
",",
"sig",
")",
":",
"pids",
"=",
"processes_with_env",
"(",
"ENV_UUID",
",",
"self",
".",
"_uuid",
")",
"for",
"pid",
"in",
"pids",
":",
"log",
".",
"debug",
"(",
"\"Killing process %d ...\"",
",",
"pid",
")",
"try... | 39.692308 | 20 |
def set_user_timer(self, value, index):
"""Set the current value of a user timer."""
err = self.clock_manager.set_tick(index, value)
return [err] | [
"def",
"set_user_timer",
"(",
"self",
",",
"value",
",",
"index",
")",
":",
"err",
"=",
"self",
".",
"clock_manager",
".",
"set_tick",
"(",
"index",
",",
"value",
")",
"return",
"[",
"err",
"]"
] | 33.2 | 15.2 |
def register_metas(self):
"""register metas"""
# concatenate some attributes to global lists:
aggregated = {'build': [], 'watch': []}
for attribute, values in aggregated.items():
for info in self.info['analyses'] + [self.info]:
if attribute in info:
... | [
"def",
"register_metas",
"(",
"self",
")",
":",
"# concatenate some attributes to global lists:",
"aggregated",
"=",
"{",
"'build'",
":",
"[",
"]",
",",
"'watch'",
":",
"[",
"]",
"}",
"for",
"attribute",
",",
"values",
"in",
"aggregated",
".",
"items",
"(",
... | 39.97619 | 20.357143 |
def copy(self):
""" Creates a copy of the TT-matrix """
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | [
"def",
"copy",
"(",
"self",
")",
":",
"c",
"=",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"self",
".",
"tt",
".",
"copy",
"(",
")",
"c",
".",
"n",
"=",
"self",
".",
"n",
".",
"copy",
"(",
")",
"c",
".",
"m",
"=",
"self",
".",
"m",
".",
... | 25.857143 | 15.142857 |
def add_result(self, content_id, content, **kwargs):
""""Add a result to the list of results."""
result_object = self.ResultClass(content_id, self.name, self.version,
formats.JSON, content, **kwargs)
self.results.append(result_object)
return | [
"def",
"add_result",
"(",
"self",
",",
"content_id",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"result_object",
"=",
"self",
".",
"ResultClass",
"(",
"content_id",
",",
"self",
".",
"name",
",",
"self",
".",
"version",
",",
"formats",
".",
"JS... | 51.5 | 18.333333 |
def match_main(self, text, pattern, loc):
"""Locate the best instance of 'pattern' in 'text' near 'loc'.
Args:
text: The text to search.
pattern: The pattern to search for.
loc: The location to search around.
Returns:
Best match index or -1.
"""
# Check for null inputs.
... | [
"def",
"match_main",
"(",
"self",
",",
"text",
",",
"pattern",
",",
"loc",
")",
":",
"# Check for null inputs.",
"if",
"text",
"==",
"None",
"or",
"pattern",
"==",
"None",
":",
"raise",
"ValueError",
"(",
"\"Null inputs. (match_main)\"",
")",
"loc",
"=",
"ma... | 28.724138 | 17.241379 |
def _validate_label(cls, name, value):
"""Raise ValueError if the label is invalid."""
# Rules for labels are described in:
# https://cloud.google.com/compute/docs/labeling-resources#restrictions
# * Keys and values cannot be longer than 63 characters each.
# * Keys and values can only contain low... | [
"def",
"_validate_label",
"(",
"cls",
",",
"name",
",",
"value",
")",
":",
"# Rules for labels are described in:",
"# https://cloud.google.com/compute/docs/labeling-resources#restrictions",
"# * Keys and values cannot be longer than 63 characters each.",
"# * Keys and values can only cont... | 46 | 18.052632 |
def fn_signature(callable,
argument_transform=(lambda name: name),
default_transform=(lambda name, value: "%s=%s" %
(name, repr(value))),
vararg_transform=(lambda name: "*" + name),
kwargs_trans... | [
"def",
"fn_signature",
"(",
"callable",
",",
"argument_transform",
"=",
"(",
"lambda",
"name",
":",
"name",
")",
",",
"default_transform",
"=",
"(",
"lambda",
"name",
",",
"value",
":",
"\"%s=%s\"",
"%",
"(",
"name",
",",
"repr",
"(",
"value",
")",
")",
... | 41.407407 | 17.962963 |
def labels(self, pores=[], throats=[], element=None, mode='union'):
r"""
Returns a list of labels present on the object
Additionally, this function can return labels applied to a specified
set of pores or throats
Parameters
----------
element : string
... | [
"def",
"labels",
"(",
"self",
",",
"pores",
"=",
"[",
"]",
",",
"throats",
"=",
"[",
"]",
",",
"element",
"=",
"None",
",",
"mode",
"=",
"'union'",
")",
":",
"# Short-circuit query when no pores or throats are given",
"if",
"(",
"sp",
".",
"size",
"(",
"... | 37.447368 | 24.802632 |
def get_state(self, key):
"""
Get the state connected to a given key.
:param key: Key into the state database
:return: A :py:class:´oidcservice.state_interface.State` instance
"""
_data = self.state_db.get(key)
if not _data:
raise KeyError(key)
... | [
"def",
"get_state",
"(",
"self",
",",
"key",
")",
":",
"_data",
"=",
"self",
".",
"state_db",
".",
"get",
"(",
"key",
")",
"if",
"not",
"_data",
":",
"raise",
"KeyError",
"(",
"key",
")",
"else",
":",
"return",
"State",
"(",
")",
".",
"from_json",
... | 30 | 13.5 |
def off(self, event, handler=None):
"""Remove an event or a handler from it."""
if handler:
self.events[event].off(handler)
else:
del self.events[event]
delattr(self, event) | [
"def",
"off",
"(",
"self",
",",
"event",
",",
"handler",
"=",
"None",
")",
":",
"if",
"handler",
":",
"self",
".",
"events",
"[",
"event",
"]",
".",
"off",
"(",
"handler",
")",
"else",
":",
"del",
"self",
".",
"events",
"[",
"event",
"]",
"delatt... | 32.428571 | 10 |
def ignore_nan_inf(kde_method):
"""Ignores nans and infs from the input data
Invalid positions in the resulting density are set to nan.
"""
def new_kde_method(events_x, events_y, xout=None, yout=None,
*args, **kwargs):
bad_in = get_bad_vals(events_x, events_y)
if ... | [
"def",
"ignore_nan_inf",
"(",
"kde_method",
")",
":",
"def",
"new_kde_method",
"(",
"events_x",
",",
"events_y",
",",
"xout",
"=",
"None",
",",
"yout",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"bad_in",
"=",
"get_bad_vals",
"("... | 35.21875 | 15.1875 |
def _ProduceContent(self, mods, showprivate=False, showinh=False):
"""An internal helper to create pages for several modules that do not have nested modules.
This will automatically generate the needed RSF to document each module module
and save the module to its own page appropriately.
... | [
"def",
"_ProduceContent",
"(",
"self",
",",
"mods",
",",
"showprivate",
"=",
"False",
",",
"showinh",
"=",
"False",
")",
":",
"result",
"=",
"''",
"nestedresult",
"=",
"''",
"# For each module",
"for",
"mod",
"in",
"mods",
":",
"# Test to see if module to docu... | 42.214286 | 24.25 |
def main():
"""Parse parameters and run ms bot framework"""
args = parser.parse_args()
run_ms_bot_framework_server(agent_generator=make_agent,
app_id=args.ms_id,
app_secret=args.ms_secret,
stateful=True) | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"run_ms_bot_framework_server",
"(",
"agent_generator",
"=",
"make_agent",
",",
"app_id",
"=",
"args",
".",
"ms_id",
",",
"app_secret",
"=",
"args",
".",
"ms_secret",
",",
"st... | 38.125 | 16.5 |
def set_geometry(self, crect):
"""Set geometry for floating panels.
Normally you don't need to override this method, you should override
`geometry` instead.
"""
x0, y0, width, height = self.geometry()
if width is None:
width = crect.width()
if height... | [
"def",
"set_geometry",
"(",
"self",
",",
"crect",
")",
":",
"x0",
",",
"y0",
",",
"width",
",",
"height",
"=",
"self",
".",
"geometry",
"(",
")",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"crect",
".",
"width",
"(",
")",
"if",
"height",
"is... | 38.363636 | 19.863636 |
def json_int_dttm_ser(obj):
"""json serializer that deals with dates"""
val = base_json_conv(obj)
if val is not None:
return val
if isinstance(obj, (datetime, pd.Timestamp)):
obj = datetime_to_epoch(obj)
elif isinstance(obj, date):
obj = (obj - EPOCH.date()).total_seconds() *... | [
"def",
"json_int_dttm_ser",
"(",
"obj",
")",
":",
"val",
"=",
"base_json_conv",
"(",
"obj",
")",
"if",
"val",
"is",
"not",
"None",
":",
"return",
"val",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"datetime",
",",
"pd",
".",
"Timestamp",
")",
")",
":",... | 33.615385 | 16 |
def available_configuration_files(self):
"""A list of strings with the absolute pathnames of the available configuration files."""
known_files = [GLOBAL_CONFIG, LOCAL_CONFIG, self.environment.get('PIP_ACCEL_CONFIG')]
absolute_paths = [parse_path(pathname) for pathname in known_files if pathname]... | [
"def",
"available_configuration_files",
"(",
"self",
")",
":",
"known_files",
"=",
"[",
"GLOBAL_CONFIG",
",",
"LOCAL_CONFIG",
",",
"self",
".",
"environment",
".",
"get",
"(",
"'PIP_ACCEL_CONFIG'",
")",
"]",
"absolute_paths",
"=",
"[",
"parse_path",
"(",
"pathna... | 80.2 | 28.8 |
def user_auth(
self,
cloudflare_email=None,
cloudflare_pass=None,
unique_id=None
):
"""
Get user_key based on either his email and password or unique_id.
:param cloudflare_email: email associated with user
:type cloudflare_email: str
... | [
"def",
"user_auth",
"(",
"self",
",",
"cloudflare_email",
"=",
"None",
",",
"cloudflare_pass",
"=",
"None",
",",
"unique_id",
"=",
"None",
")",
":",
"if",
"not",
"(",
"cloudflare_email",
"and",
"cloudflare_pass",
")",
"and",
"not",
"unique_id",
":",
"raise",... | 34.9 | 18.3 |
def populate_from_local(self, sa, container, path, mode, cache_control):
# type: (StorageEntity, blobxfer.operations.azure.StorageAccount
# str, str, blobxfer.models.azure.StorageModes, str) -> None
"""Populate properties from local
:param StorageEntity self: this
:param b... | [
"def",
"populate_from_local",
"(",
"self",
",",
"sa",
",",
"container",
",",
"path",
",",
"mode",
",",
"cache_control",
")",
":",
"# type: (StorageEntity, blobxfer.operations.azure.StorageAccount",
"# str, str, blobxfer.models.azure.StorageModes, str) -> None",
"self",
"... | 45.151515 | 10.666667 |
def FromBinary(cls, record_data, record_count=1):
"""Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a SendRPCRecord.
Args:
record_data (bytearray): Th... | [
"def",
"FromBinary",
"(",
"cls",
",",
"record_data",
",",
"record_count",
"=",
"1",
")",
":",
"cmd",
",",
"address",
",",
"resp_length",
",",
"payload",
"=",
"cls",
".",
"_parse_rpc_info",
"(",
"record_data",
")",
"# The first bit is 1 if we do not have a fixed le... | 39.481481 | 27.481481 |
def get_glance_url(url_base, tenant_id, user, password, region):
"""It get the glance url
:param url_base: keystone url
:param tenand_id: the id of the tenant
:param user: the user
:param paassword: the password
"""
get_url(url_base, tenant_id, user, password, 'image', region) | [
"def",
"get_glance_url",
"(",
"url_base",
",",
"tenant_id",
",",
"user",
",",
"password",
",",
"region",
")",
":",
"get_url",
"(",
"url_base",
",",
"tenant_id",
",",
"user",
",",
"password",
",",
"'image'",
",",
"region",
")"
] | 37.25 | 9.875 |
def read_to_file(library, session, filename, count):
"""Read data synchronously, and store the transferred data in a file.
Corresponds to viReadToFile function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param fi... | [
"def",
"read_to_file",
"(",
"library",
",",
"session",
",",
"filename",
",",
"count",
")",
":",
"return_count",
"=",
"ViUInt32",
"(",
")",
"ret",
"=",
"library",
".",
"viReadToFile",
"(",
"session",
",",
"filename",
",",
"count",
",",
"return_count",
")",
... | 45.333333 | 19.066667 |
def set_option(name, option):
"""
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
"""
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name),
_encode_strin... | [
"def",
"set_option",
"(",
"name",
",",
"option",
")",
":",
"ffi",
".",
"lib",
".",
"LLVMPY_SetCommandLine",
"(",
"_encode_string",
"(",
"name",
")",
",",
"_encode_string",
"(",
"option",
")",
")"
] | 35.777778 | 14.444444 |
def find_elb_dns_zone_id(name='', env='dev', region='us-east-1'):
"""Get an application's AWS elb dns zone id.
Args:
name (str): ELB name
env (str): Environment/account of ELB
region (str): AWS Region
Returns:
str: elb DNS zone ID
"""
LOG.info('Find %s ELB DNS Zone... | [
"def",
"find_elb_dns_zone_id",
"(",
"name",
"=",
"''",
",",
"env",
"=",
"'dev'",
",",
"region",
"=",
"'us-east-1'",
")",
":",
"LOG",
".",
"info",
"(",
"'Find %s ELB DNS Zone ID in %s [%s].'",
",",
"name",
",",
"env",
",",
"region",
")",
"client",
"=",
"bot... | 35.25 | 23.1875 |
def _parseCounters(self, data):
"""Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-value pair in each line.
@return: Dictionary of stats.
"""
info_dict = util.NestedDict()
for line in data.splitlines():
... | [
"def",
"_parseCounters",
"(",
"self",
",",
"data",
")",
":",
"info_dict",
"=",
"util",
".",
"NestedDict",
"(",
")",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
":",
"mobj",
"=",
"re",
".",
"match",
"(",
"'^\\s*([\\w\\.]+)\\s*=\\s*(\\S.*)$'",
... | 37.266667 | 13.133333 |
def get_gallery_profile(self):
"""Return the users gallery profile."""
url = (self._imgur._base_url + "/3/account/{0}/"
"gallery_profile".format(self.name))
return self._imgur._send_request(url) | [
"def",
"get_gallery_profile",
"(",
"self",
")",
":",
"url",
"=",
"(",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/account/{0}/\"",
"\"gallery_profile\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"self",
".",
"_imgur",
".",
"_sen... | 45.8 | 8.4 |
def parse_auth_headers(self, authorization):
"""Parses the authorization headers from the authorization header taken from a request.
Returns a dict that is accepted by all other API functions which expect authorization headers in a dict format.
Keyword arguments:
authorization -- The au... | [
"def",
"parse_auth_headers",
"(",
"self",
",",
"authorization",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"r'^(?i)Acquia\\s+(.*?):(.+)$'",
",",
"authorization",
")",
"if",
"m",
"is",
"not",
"None",
":",
"return",
"{",
"\"id\"",
":",
"m",
".",
"group",
... | 53.272727 | 27.636364 |
def _set_action(self, v, load=False):
"""
Setter method for action, mapped from YANG variable /rule/action (rule-action)
If this variable is read-only (config: false) in the
source YANG file, then _set_action is considered as a private
method. Backends looking to populate this variable should
do... | [
"def",
"_set_action",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 86.227273 | 40.318182 |
def rights(self, form, load):
'''
Determine what type of authentication is being requested and pass
authorization
Note: this will check that the user has at least one right that will let
the user execute "load", this does not deal with conflicting rules
'''
adat... | [
"def",
"rights",
"(",
"self",
",",
"form",
",",
"load",
")",
":",
"adata",
"=",
"self",
".",
"auth_data",
"good",
"=",
"False",
"if",
"load",
".",
"get",
"(",
"'token'",
",",
"False",
")",
":",
"for",
"sub_auth",
"in",
"self",
".",
"token",
"(",
... | 37.421053 | 17.368421 |
def _extractAssociation(self, assoc_response, assoc_session):
"""Attempt to extract an association from the response, given
the association response message and the established
association session.
@param assoc_response: The association response message from
the server
... | [
"def",
"_extractAssociation",
"(",
"self",
",",
"assoc_response",
",",
"assoc_session",
")",
":",
"# Extract the common fields from the response, raising an",
"# exception if they are not found",
"assoc_type",
"=",
"assoc_response",
".",
"getArg",
"(",
"OPENID_NS",
",",
"'ass... | 44.597403 | 20.519481 |
def get_text_stream(stream="stdout", encoding=None):
"""Retrieve a unicode stream wrapper around **sys.stdout** or **sys.stderr**.
:param str stream: The name of the stream to wrap from the :mod:`sys` module.
:param str encoding: An optional encoding to use.
:return: A new :class:`~vistir.misc.StreamWr... | [
"def",
"get_text_stream",
"(",
"stream",
"=",
"\"stdout\"",
",",
"encoding",
"=",
"None",
")",
":",
"stream_map",
"=",
"{",
"\"stdin\"",
":",
"sys",
".",
"stdin",
",",
"\"stdout\"",
":",
"sys",
".",
"stdout",
",",
"\"stderr\"",
":",
"sys",
".",
"stderr",... | 43.041667 | 21.291667 |
def swap_time_and_batch_axes(inputs):
"""Swaps time and batch axis (the first two axis)."""
transposed_axes = tf.concat([[1, 0], tf.range(2, tf.rank(inputs))], axis=0)
return tf.transpose(inputs, transposed_axes) | [
"def",
"swap_time_and_batch_axes",
"(",
"inputs",
")",
":",
"transposed_axes",
"=",
"tf",
".",
"concat",
"(",
"[",
"[",
"1",
",",
"0",
"]",
",",
"tf",
".",
"range",
"(",
"2",
",",
"tf",
".",
"rank",
"(",
"inputs",
")",
")",
"]",
",",
"axis",
"=",... | 53.75 | 11.5 |
def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... | [
"def",
"filter_python_files",
"(",
"files",
")",
":",
"py_files",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"# If we end in .py, or if we don't have an extension and file says that",
"# we are a python script, then add us to the list",
"extension",
"=",
"os",
".",
"pat... | 34.529412 | 18.647059 |
def load_module(self, module):
"""
Load a rules module
:param module:
:type module:
:return:
:rtype:
"""
# pylint: disable=unused-variable
for name, obj in inspect.getmembers(module,
lambda member: hasat... | [
"def",
"load_module",
"(",
"self",
",",
"module",
")",
":",
"# pylint: disable=unused-variable",
"for",
"name",
",",
"obj",
"in",
"inspect",
".",
"getmembers",
"(",
"module",
",",
"lambda",
"member",
":",
"hasattr",
"(",
"member",
",",
"'__module__'",
")",
"... | 34.266667 | 19.066667 |
def do_translate(parser, token):
"""
This will mark a string for translation and will
translate the string for the current language.
Usage::
{% trans "this is a test" %}
This will mark the string for translation so it will
be pulled out by mark-messages.py into the .po files
and will... | [
"def",
"do_translate",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one argument\"",
"%",
"bits",
"[",
... | 40.320513 | 18.961538 |
def efficiency(self):
"""Calculate :ref:`pysynphot-formula-qtlam`.
Returns
-------
ans : float
Bandpass dimensionless efficiency.
"""
mywaveunits = self.waveunits.name
self.convert('angstroms')
wave = self.wave
thru = self.throughput... | [
"def",
"efficiency",
"(",
"self",
")",
":",
"mywaveunits",
"=",
"self",
".",
"waveunits",
".",
"name",
"self",
".",
"convert",
"(",
"'angstroms'",
")",
"wave",
"=",
"self",
".",
"wave",
"thru",
"=",
"self",
".",
"throughput",
"self",
".",
"convert",
"(... | 23 | 18.611111 |
def search(
self,
token: dict = None,
query: str = "",
bbox: list = None,
poly: str = None,
georel: str = None,
order_by: str = "_created",
order_dir: str = "desc",
page_size: int = 100,
offset: int = 0,
share: str = None,
s... | [
"def",
"search",
"(",
"self",
",",
"token",
":",
"dict",
"=",
"None",
",",
"query",
":",
"str",
"=",
"\"\"",
",",
"bbox",
":",
"list",
"=",
"None",
",",
"poly",
":",
"str",
"=",
"None",
",",
"georel",
":",
"str",
"=",
"None",
",",
"order_by",
"... | 35.418079 | 18.672316 |
def compose_MDAL_dic(self, site, point_type,
start, end, var, agg, window, aligned, points=None, return_names=False):
""" Create dictionary for MDAL request.
Parameters
----------
site : str
Building name.
start : str
... | [
"def",
"compose_MDAL_dic",
"(",
"self",
",",
"site",
",",
"point_type",
",",
"start",
",",
"end",
",",
"var",
",",
"agg",
",",
"window",
",",
"aligned",
",",
"points",
"=",
"None",
",",
"return_names",
"=",
"False",
")",
":",
"# Convert time to UTC",
"st... | 37.41791 | 22.58209 |
def get(self, *args, **kwargs):
"""
The base activation logic; subclasses should leave this method
alone and implement activate(), which is called from this
method.
"""
extra_context = {}
try:
activated_user = self.activate(*args, **kwargs)
ex... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"extra_context",
"=",
"{",
"}",
"try",
":",
"activated_user",
"=",
"self",
".",
"activate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"ActivationError",
... | 32.3 | 13.7 |
def add(self, cell):
"""Append a cell into the stack.
Parameters
----------
cell : BaseRNNCell
The cell to be appended. During unroll, previous cell's output (or raw inputs if
no previous cell) is used as the input to this cell.
"""
self._cells.ap... | [
"def",
"add",
"(",
"self",
",",
"cell",
")",
":",
"self",
".",
"_cells",
".",
"append",
"(",
"cell",
")",
"if",
"self",
".",
"_override_cell_params",
":",
"assert",
"cell",
".",
"_own_params",
",",
"\"Either specify params for SequentialRNNCell \"",
"\"or child ... | 38.625 | 16.6875 |
def get_hosts_info(self):
"""
Returns a list of dicts with information about the known hosts.
The dict-keys are: 'ip', 'name', 'mac', 'status'
"""
result = []
index = 0
while index < self.host_numbers:
host = self.get_generic_host_entry(index)
... | [
"def",
"get_hosts_info",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"index",
"=",
"0",
"while",
"index",
"<",
"self",
".",
"host_numbers",
":",
"host",
"=",
"self",
".",
"get_generic_host_entry",
"(",
"index",
")",
"result",
".",
"append",
"(",
"{... | 34.375 | 11.625 |
def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear... | [
"def",
"DecimalField",
"(",
"default",
"=",
"NOTHING",
",",
"required",
"=",
"True",
",",
"repr",
"=",
"True",
",",
"cmp",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"default",
"=",
"_init_fields",
".",
"init_default",
"(",
"required",
",",
"defau... | 47.875 | 19 |
def trap_http_exception(self, e):
"""Checks if an HTTP exception should be trapped or not. By default
this will return `False` for all exceptions except for a bad request
key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It
also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is se... | [
"def",
"trap_http_exception",
"(",
"self",
",",
"e",
")",
":",
"if",
"self",
".",
"config",
"[",
"'TRAP_HTTP_EXCEPTIONS'",
"]",
":",
"return",
"True",
"if",
"self",
".",
"config",
"[",
"'TRAP_BAD_REQUEST_ERRORS'",
"]",
":",
"return",
"isinstance",
"(",
"e",
... | 45.473684 | 21.526316 |
def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
"""Execute a search against one or more indices to get the resultset.
`query` must be a Search object, a Query object, or a custom
dictionary of search parameters using the query DSL to ... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"indices",
"=",
"None",
",",
"doc_types",
"=",
"None",
",",
"model",
"=",
"None",
",",
"scan",
"=",
"False",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"query_params",
")",
":",
"if",
"isinstance",
... | 44.6 | 25.9 |
def conf(self, conf):
""" 设置当前 WechatConf 实例 """
self.__conf = conf
self.__request = WechatRequest(conf=self.__conf) | [
"def",
"conf",
"(",
"self",
",",
"conf",
")",
":",
"self",
".",
"__conf",
"=",
"conf",
"self",
".",
"__request",
"=",
"WechatRequest",
"(",
"conf",
"=",
"self",
".",
"__conf",
")"
] | 34.5 | 12.25 |
def delete_contacts(
self,
ids: List[int]
):
"""Use this method to delete contacts from your Telegram address book.
Args:
ids (List of ``int``):
A list of unique identifiers for the target users.
Can be an ID (int), a username (string) or ... | [
"def",
"delete_contacts",
"(",
"self",
",",
"ids",
":",
"List",
"[",
"int",
"]",
")",
":",
"contacts",
"=",
"[",
"]",
"for",
"i",
"in",
"ids",
":",
"try",
":",
"input_user",
"=",
"self",
".",
"resolve_peer",
"(",
"i",
")",
"except",
"PeerIdInvalid",
... | 27.151515 | 22.454545 |
def main():
"""The command line interface for the ``pip-accel`` program."""
arguments = sys.argv[1:]
# If no arguments are given, the help text of pip-accel is printed.
if not arguments:
usage()
sys.exit(0)
# If no install subcommand is given we pass the command line straight
# t... | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"# If no arguments are given, the help text of pip-accel is printed.",
"if",
"not",
"arguments",
":",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"# If no install... | 39.666667 | 17.435897 |
def get_event_exchange(service_name):
""" Get an exchange for ``service_name`` events.
"""
exchange_name = "{}.events".format(service_name)
exchange = Exchange(
exchange_name, type='topic', durable=True, delivery_mode=PERSISTENT
)
return exchange | [
"def",
"get_event_exchange",
"(",
"service_name",
")",
":",
"exchange_name",
"=",
"\"{}.events\"",
".",
"format",
"(",
"service_name",
")",
"exchange",
"=",
"Exchange",
"(",
"exchange_name",
",",
"type",
"=",
"'topic'",
",",
"durable",
"=",
"True",
",",
"deliv... | 30.111111 | 18 |
def get_response_form(self, assessment_section_id, item_id):
"""Gets the response form for submitting an answer.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return: (osid.assessment.... | [
"def",
"get_response_form",
"(",
"self",
",",
"assessment_section_id",
",",
"item_id",
")",
":",
"if",
"not",
"isinstance",
"(",
"item_id",
",",
"ABCId",
")",
":",
"raise",
"errors",
".",
"InvalidArgument",
"(",
"'argument is not a valid OSID Id'",
")",
"# This is... | 48 | 20.612903 |
def update(self, campaign_id, schedule, nick=None):
'''xxxxx.xxxxx.campaign.schedule.update
===================================
更新一个推广计划的分时折扣设置'''
request = TOPRequest('xxxxx.xxxxx.campaign.schedule.update')
request['campaign_id'] = campaign_id
request['schedule'] = sched... | [
"def",
"update",
"(",
"self",
",",
"campaign_id",
",",
"schedule",
",",
"nick",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'xxxxx.xxxxx.campaign.schedule.update'",
")",
"request",
"[",
"'campaign_id'",
"]",
"=",
"campaign_id",
"request",
"[",
"... | 53.6 | 19.6 |
def _fill_empty_sessions(self, fill_subjects, fill_visits):
"""
Fill in tree with additional empty subjects and/or visits to
allow the study to pull its inputs from external repositories
"""
if fill_subjects is None:
fill_subjects = [s.id for s in self.subjects]
... | [
"def",
"_fill_empty_sessions",
"(",
"self",
",",
"fill_subjects",
",",
"fill_visits",
")",
":",
"if",
"fill_subjects",
"is",
"None",
":",
"fill_subjects",
"=",
"[",
"s",
".",
"id",
"for",
"s",
"in",
"self",
".",
"subjects",
"]",
"if",
"fill_visits",
"is",
... | 44.592593 | 12.814815 |
def get_args(cls, dist, header=None):
"""
Yield write_script() argument tuples for a distribution's
console_scripts and gui_scripts entry points.
"""
if header is None:
header = cls.get_header()
spec = str(dist.as_requirement())
for type_ in 'console',... | [
"def",
"get_args",
"(",
"cls",
",",
"dist",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"cls",
".",
"get_header",
"(",
")",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"for",
... | 40.8125 | 9.8125 |
def load_json(data=None, path=None, name='NT'):
""" Map namedtuples with json data. """
if data and not path:
return mapper(json.loads(data), _nt_name=name)
if path and not data:
return mapper(json.load(path), _nt_name=name)
if data and path:
raise ValueError('expected one source... | [
"def",
"load_json",
"(",
"data",
"=",
"None",
",",
"path",
"=",
"None",
",",
"name",
"=",
"'NT'",
")",
":",
"if",
"data",
"and",
"not",
"path",
":",
"return",
"mapper",
"(",
"json",
".",
"loads",
"(",
"data",
")",
",",
"_nt_name",
"=",
"name",
")... | 41.5 | 13.375 |
def delete_access_key(self, access_key_id, user_name=None):
"""
Delete an access key associated with a user.
If the user_name is not specified, it is determined implicitly based
on the AWS Access Key ID used to sign the request.
:type access_key_id: string
:param access... | [
"def",
"delete_access_key",
"(",
"self",
",",
"access_key_id",
",",
"user_name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'AccessKeyId'",
":",
"access_key_id",
"}",
"if",
"user_name",
":",
"params",
"[",
"'UserName'",
"]",
"=",
"user_name",
"return",
"sel... | 34.555556 | 19.222222 |
def _zip_request_params(self, urls, query_params, data):
"""Massages inputs and returns a list of 3-tuples zipping them up.
This is all the smarts behind deciding how many requests to issue.
It's fine for an input to have 0, 1, or a list of values.
If there are two inputs each with a li... | [
"def",
"_zip_request_params",
"(",
"self",
",",
"urls",
",",
"query_params",
",",
"data",
")",
":",
"# Everybody gets to be a list",
"if",
"not",
"isinstance",
"(",
"urls",
",",
"list",
")",
":",
"urls",
"=",
"[",
"urls",
"]",
"if",
"not",
"isinstance",
"(... | 36.568627 | 19.607843 |
def set_alarm_state(self, state):
"""
:param state: a boolean of ture (on) or false ('off')
:return: nothing
"""
values = {"desired_state": {"alarm_enabled": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_respon... | [
"def",
"set_alarm_state",
"(",
"self",
",",
"state",
")",
":",
"values",
"=",
"{",
"\"desired_state\"",
":",
"{",
"\"alarm_enabled\"",
":",
"state",
"}",
"}",
"response",
"=",
"self",
".",
"api_interface",
".",
"set_device_state",
"(",
"self",
",",
"values",... | 40.625 | 12.875 |
def cohort_queryplan(plan):
"""
Input:
{
'source': 'kronos', # Name of data source from settings
'cohort':
{'stream': CohortTest.EMAIL_STREAM, # Kronos stream to define cohort from.
'transform': lambda x: x, # Transformations on the kstream.
'start': date.now(), # The da... | [
"def",
"cohort_queryplan",
"(",
"plan",
")",
":",
"cohort",
"=",
"plan",
"[",
"'cohort'",
"]",
"action",
"=",
"plan",
"[",
"'action'",
"]",
"source",
"=",
"plan",
"[",
"'source'",
"]",
"# Calculate the start and end dates, in Kronos time, of the",
"# beginning and e... | 45.266667 | 25.622222 |
def exposure_plot(self, places=-1, c_poly='default', c_holes='default',
s_sop=25, extra_height=0.1):
"""
Plots the exposure of the sensible points in a space to the data
and the Sun positions. It is required to previously compute the
shadowing.
... | [
"def",
"exposure_plot",
"(",
"self",
",",
"places",
"=",
"-",
"1",
",",
"c_poly",
"=",
"'default'",
",",
"c_holes",
"=",
"'default'",
",",
"s_sop",
"=",
"25",
",",
"extra_height",
"=",
"0.1",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt"... | 41.306818 | 17.511364 |
def delete_note(self, note_id,
url='https://api.shanbay.com/bdc/note/{note_id}/'):
"""删除笔记"""
url = url.format(note_id=note_id)
return self._request(url, method='delete').json() | [
"def",
"delete_note",
"(",
"self",
",",
"note_id",
",",
"url",
"=",
"'https://api.shanbay.com/bdc/note/{note_id}/'",
")",
":",
"url",
"=",
"url",
".",
"format",
"(",
"note_id",
"=",
"note_id",
")",
"return",
"self",
".",
"_request",
"(",
"url",
",",
"method"... | 43.4 | 11.8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.