text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def attr(prev, attr_name):
"""attr pipe can extract attribute value of object.
:param prev: The previous iterator of pipe.
:type prev: Pipe
:param attr_name: The name of attribute
:type attr_name: str
:returns: generator
"""
for obj in prev:
if hasattr(obj, attr_name):
... | [
"def",
"attr",
"(",
"prev",
",",
"attr_name",
")",
":",
"for",
"obj",
"in",
"prev",
":",
"if",
"hasattr",
"(",
"obj",
",",
"attr_name",
")",
":",
"yield",
"getattr",
"(",
"obj",
",",
"attr_name",
")"
] | 28.416667 | 11.916667 |
def updateTable(self, networkId, tableType, body, class_, verbose=None):
"""
Updates the table specified by the `tableType` and `networkId` parameters. New columns will be created if they do not exist in the target table.
Current limitations:
* Numbers are handled as Double
... | [
"def",
"updateTable",
"(",
"self",
",",
"networkId",
",",
"tableType",
",",
"body",
",",
"class_",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'networks/'",
"+",
"str",
"(",
"networkId",
... | 43.263158 | 26.210526 |
def get_public_network_ip(ips, public_subnet):
"""
Given a public subnet, chose the one IP from the remote host that exists
within the subnet range.
"""
for ip in ips:
if net.ip_in_subnet(ip, public_subnet):
return ip
msg = "IPs (%s) are not valid for any of subnet specified ... | [
"def",
"get_public_network_ip",
"(",
"ips",
",",
"public_subnet",
")",
":",
"for",
"ip",
"in",
"ips",
":",
"if",
"net",
".",
"ip_in_subnet",
"(",
"ip",
",",
"public_subnet",
")",
":",
"return",
"ip",
"msg",
"=",
"\"IPs (%s) are not valid for any of subnet specif... | 37.5 | 17.3 |
def _parse_mibs(iLOIP, snmp_credentials):
"""Parses the MIBs.
:param iLOIP: IP address of the server on which SNMP discovery
has to be executed.
:param snmp_credentials: a Dictionary of SNMP credentials.
auth_user: SNMP user
auth_protocol: Auth Protocol
au... | [
"def",
"_parse_mibs",
"(",
"iLOIP",
",",
"snmp_credentials",
")",
":",
"result",
"=",
"{",
"}",
"usm_user_obj",
"=",
"_create_usm_user_obj",
"(",
"snmp_credentials",
")",
"try",
":",
"for",
"(",
"errorIndication",
",",
"errorStatus",
",",
"errorIndex",
",",
"v... | 44 | 15.890411 |
def set_journal_comment(self, comment=None):
"""Sets a comment.
arg: comment (string): the new comment
raise: InvalidArgument - comment is invalid
raise: NoAccess - metadata.is_readonly() is true
raise: NullArgument - comment is null
compliance: mandatory - This me... | [
"def",
"set_journal_comment",
"(",
"self",
",",
"comment",
"=",
"None",
")",
":",
"if",
"comment",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"metadata",
"=",
"Metadata",
"(",
"*",
"*",
"settings",
".",
"METADATA",
"[",
"'comment'",
"]",
")",
... | 36.947368 | 15 |
def setLogEntries(self, entries, save=True, update_policies=True):
"""Sets list of log entries. If save=True, saves the log. If update_policies=True, also updates default policies based
on these entries"""
prev = None; # "previous" valid entry for "Prev" link
uplink = os.path.join("..",... | [
"def",
"setLogEntries",
"(",
"self",
",",
"entries",
",",
"save",
"=",
"True",
",",
"update_policies",
"=",
"True",
")",
":",
"prev",
"=",
"None",
"# \"previous\" valid entry for \"Prev\" link",
"uplink",
"=",
"os",
".",
"path",
".",
"join",
"(",
"\"..\"",
"... | 47.263158 | 14.789474 |
def clone(self):
"""Create a complete copy of the package.
:returns: A new MaterialPackage object."""
result = copy.copy(self)
result._compound_masses = copy.deepcopy(self._compound_masses)
return result | [
"def",
"clone",
"(",
"self",
")",
":",
"result",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"result",
".",
"_compound_masses",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_compound_masses",
")",
"return",
"result"
] | 29.75 | 20.125 |
def contextMenuEvent(self, event):
"""
Add menu action:
* 'Show line numbers'
* 'Save to file'
"""
menu = QtWidgets.QTextEdit.createStandardContextMenu(self)
# create max.lines spin box:
w = QtWidgets.QWidget()
l = QtWidgets.QHBoxLayout()
... | [
"def",
"contextMenuEvent",
"(",
"self",
",",
"event",
")",
":",
"menu",
"=",
"QtWidgets",
".",
"QTextEdit",
".",
"createStandardContextMenu",
"(",
"self",
")",
"# create max.lines spin box:",
"w",
"=",
"QtWidgets",
".",
"QWidget",
"(",
")",
"l",
"=",
"QtWidget... | 28.68 | 14.28 |
def filter_spouts(table, header):
""" filter to keep spouts """
spouts_info = []
for row in table:
if row[0] == 'spout':
spouts_info.append(row)
return spouts_info, header | [
"def",
"filter_spouts",
"(",
"table",
",",
"header",
")",
":",
"spouts_info",
"=",
"[",
"]",
"for",
"row",
"in",
"table",
":",
"if",
"row",
"[",
"0",
"]",
"==",
"'spout'",
":",
"spouts_info",
".",
"append",
"(",
"row",
")",
"return",
"spouts_info",
"... | 26.142857 | 12.571429 |
def targets_for_class(self, target, classname):
"""Search which targets from `target`'s transitive dependencies contain `classname`."""
targets_with_class = set()
for target in target.closure():
for one_class in self._target_classes(target):
if classname in one_class:
targets_with_cl... | [
"def",
"targets_for_class",
"(",
"self",
",",
"target",
",",
"classname",
")",
":",
"targets_with_class",
"=",
"set",
"(",
")",
"for",
"target",
"in",
"target",
".",
"closure",
"(",
")",
":",
"for",
"one_class",
"in",
"self",
".",
"_target_classes",
"(",
... | 37.3 | 11.6 |
def push(self, new_scope=None):
"""Create a new scope
:returns: TODO
"""
if new_scope is None:
new_scope = {
"types": {},
"vars": {}
}
self._curr_scope = new_scope
self._dlog("pushing new scope, scope level = {}".fo... | [
"def",
"push",
"(",
"self",
",",
"new_scope",
"=",
"None",
")",
":",
"if",
"new_scope",
"is",
"None",
":",
"new_scope",
"=",
"{",
"\"types\"",
":",
"{",
"}",
",",
"\"vars\"",
":",
"{",
"}",
"}",
"self",
".",
"_curr_scope",
"=",
"new_scope",
"self",
... | 29.076923 | 15.230769 |
def grant_revoke(grant,
database,
user,
host='localhost',
grant_option=False,
escape=True,
**connection_args):
'''
Removes a grant from the MySQL server.
CLI Example:
.. code-block:: bash
sal... | [
"def",
"grant_revoke",
"(",
"grant",
",",
"database",
",",
"user",
",",
"host",
"=",
"'localhost'",
",",
"grant_option",
"=",
"False",
",",
"escape",
"=",
"True",
",",
"*",
"*",
"connection_args",
")",
":",
"dbc",
"=",
"_connect",
"(",
"*",
"*",
"conne... | 28.64 | 19.12 |
def send_extpos(self, pos):
"""
Send the current Crazyflie X, Y, Z position. This is going to be
forwarded to the Crazyflie's position estimator.
"""
pk = CRTPPacket()
pk.port = CRTPPort.LOCALIZATION
pk.channel = self.POSITION_CH
pk.data = struct.pack('<f... | [
"def",
"send_extpos",
"(",
"self",
",",
"pos",
")",
":",
"pk",
"=",
"CRTPPacket",
"(",
")",
"pk",
".",
"port",
"=",
"CRTPPort",
".",
"LOCALIZATION",
"pk",
".",
"channel",
"=",
"self",
".",
"POSITION_CH",
"pk",
".",
"data",
"=",
"struct",
".",
"pack",... | 33.727273 | 13.545455 |
def _send_user_message(self, data):
"""
send a message, but block if we're in key negotiation. this is used
for user-initiated requests.
"""
start = time.time()
while True:
self.clear_to_send.wait(0.1)
if not self.active:
self._log... | [
"def",
"_send_user_message",
"(",
"self",
",",
"data",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"self",
".",
"clear_to_send",
".",
"wait",
"(",
"0.1",
")",
"if",
"not",
"self",
".",
"active",
":",
"self",
".",
"_... | 38.285714 | 14.857143 |
def parse_bangrc():
"""
Parses ``$HOME/.bangrc`` for global settings and deployer credentials. The
``.bangrc`` file is expected to be a YAML file whose outermost structure is
a key-value map.
Note that even though ``.bangrc`` is just a YAML file in which a user could
store any top-level keys, ... | [
"def",
"parse_bangrc",
"(",
")",
":",
"raw",
"=",
"read_raw_bangrc",
"(",
")",
"return",
"dict",
"(",
"(",
"k",
",",
"raw",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"raw",
"if",
"k",
"in",
"RC_KEYS",
")"
] | 34.777778 | 25.444444 |
def density(self, r, rho0, gamma):
"""
computes the density
:param x:
:param y:
:param rho0:
:param a:
:param s:
:return:
"""
rho = rho0 / r**gamma
return rho | [
"def",
"density",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"gamma",
")",
":",
"rho",
"=",
"rho0",
"/",
"r",
"**",
"gamma",
"return",
"rho"
] | 19.583333 | 15.583333 |
def fit_transform(self, raw_documents, y=None):
""" Learn the vocabulary dictionary and return term-document matrix.
This is equivalent to fit followed by transform, but more efficiently
implemented.
Parameters
----------
raw_documents : iterable
An iterable ... | [
"def",
"fit_transform",
"(",
"self",
",",
"raw_documents",
",",
"y",
"=",
"None",
")",
":",
"documents",
"=",
"super",
"(",
"CountVectorizer",
",",
"self",
")",
".",
"fit_transform",
"(",
"raw_documents",
"=",
"raw_documents",
",",
"y",
"=",
"y",
")",
"s... | 34.086957 | 17.173913 |
def max_heapify(arr, end, simulation, iteration):
""" Max heapify helper for max_heap_sort
"""
last_parent = (end - 1) // 2
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
whi... | [
"def",
"max_heapify",
"(",
"arr",
",",
"end",
",",
"simulation",
",",
"iteration",
")",
":",
"last_parent",
"=",
"(",
"end",
"-",
"1",
")",
"//",
"2",
"# Iterate from last parent to first",
"for",
"parent",
"in",
"range",
"(",
"last_parent",
",",
"-",
"1",... | 37.071429 | 13.821429 |
def _convert_indirect_jump_targets_to_states(job, indirect_jump_targets):
"""
Convert each concrete indirect jump target into a SimState.
:param job: The CFGJob instance.
:param indirect_jump_targets: A collection of concrete jump targets resolved from a indirect j... | [
"def",
"_convert_indirect_jump_targets_to_states",
"(",
"job",
",",
"indirect_jump_targets",
")",
":",
"successors",
"=",
"[",
"]",
"for",
"t",
"in",
"indirect_jump_targets",
":",
"# Insert new successors",
"a",
"=",
"job",
".",
"sim_successors",
".",
"all_successors"... | 39.294118 | 19.764706 |
def write(self, outfile):
"""
Save the likelihood results as a sparse HEALPix map.
"""
data = odict()
data['PIXEL']=self.roi.pixels_target
# Full data output (too large for survey)
if self.config['scan']['full_pdf']:
data['LOG_LIKELIHOOD']=self.log_lik... | [
"def",
"write",
"(",
"self",
",",
"outfile",
")",
":",
"data",
"=",
"odict",
"(",
")",
"data",
"[",
"'PIXEL'",
"]",
"=",
"self",
".",
"roi",
".",
"pixels_target",
"# Full data output (too large for survey)",
"if",
"self",
".",
"config",
"[",
"'scan'",
"]",... | 49.392857 | 21.464286 |
def _sanity_check_every_location_is_marked(ir_blocks):
"""Ensure that every new location is marked with a MarkLocation block."""
# Exactly one MarkLocation block is found between any block that starts an interval of blocks
# that all affect the same query position, and the first subsequent block that affect... | [
"def",
"_sanity_check_every_location_is_marked",
"(",
"ir_blocks",
")",
":",
"# Exactly one MarkLocation block is found between any block that starts an interval of blocks",
"# that all affect the same query position, and the first subsequent block that affects a",
"# different position in the query... | 51.344828 | 22.206897 |
def check_type(self, value):
"""Hook for type-checking, invoked during assignment.
raises TypeError if neither value nor self.dtype are None and they
do not match.
will not raise an exception if either value or self.dtype is None
"""
if self.__dict__['dtype'] is None:
... | [
"def",
"check_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"__dict__",
"[",
"'dtype'",
"]",
"is",
"None",
":",
"return",
"elif",
"value",
"is",
"None",
":",
"return",
"elif",
"isinstance",
"(",
"value",
",",
"self",
".",
"__dict__",
... | 34.176471 | 18.411765 |
def iter_all_repos(self, number=-1, since=None, etag=None, per_page=None):
"""Iterate over every repository in the order they were created.
:param int number: (optional), number of repositories to return.
Default: -1, returns all of them
:param int since: (optional), last repository... | [
"def",
"iter_all_repos",
"(",
"self",
",",
"number",
"=",
"-",
"1",
",",
"since",
"=",
"None",
",",
"etag",
"=",
"None",
",",
"per_page",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'repositories'",
")",
"return",
"self",
".",... | 50.352941 | 20.411765 |
def _base_placeholder(self):
"""
Return the notes master placeholder this notes slide placeholder
inherits from, or |None| if no placeholder of the matching type is
present.
"""
notes_master = self.part.notes_master
ph_type = self.element.ph_type
return no... | [
"def",
"_base_placeholder",
"(",
"self",
")",
":",
"notes_master",
"=",
"self",
".",
"part",
".",
"notes_master",
"ph_type",
"=",
"self",
".",
"element",
".",
"ph_type",
"return",
"notes_master",
".",
"placeholders",
".",
"get",
"(",
"ph_type",
"=",
"ph_type... | 39.555556 | 14.444444 |
def converter(input_string, block_size=2):
"""
The cli tool as a built-in function.
:param input_string: A string that should be converted to a set of facts.
:type input_string: str.
:param blocks_size: Optional block size of sentences (Default: 2).
:type block_size: int.
"""
sentences... | [
"def",
"converter",
"(",
"input_string",
",",
"block_size",
"=",
"2",
")",
":",
"sentences",
"=",
"textprocessing",
".",
"getSentences",
"(",
"input_string",
")",
"blocks",
"=",
"textprocessing",
".",
"getBlocks",
"(",
"sentences",
",",
"block_size",
")",
"par... | 34.384615 | 16.846154 |
def calculate_checksum_on_bytes(
b, algorithm=d1_common.const.DEFAULT_CHECKSUM_ALGORITHM
):
"""Calculate the checksum of ``bytes``.
Warning: This method requires the entire object to be buffered in (virtual) memory,
which should normally be avoided in production code.
Args:
b: bytes
... | [
"def",
"calculate_checksum_on_bytes",
"(",
"b",
",",
"algorithm",
"=",
"d1_common",
".",
"const",
".",
"DEFAULT_CHECKSUM_ALGORITHM",
")",
":",
"checksum_calc",
"=",
"get_checksum_calculator_by_dataone_designator",
"(",
"algorithm",
")",
"checksum_calc",
".",
"update",
"... | 29.090909 | 26 |
def get_string(self, significant_figures=6):
"""
Returns the string representation of simulation box in LAMMPS
data file format.
Args:
significant_figures (int): No. of significant figures to
output for box settings. Default to 6.
Returns:
... | [
"def",
"get_string",
"(",
"self",
",",
"significant_figures",
"=",
"6",
")",
":",
"ph",
"=",
"\"{:.%df}\"",
"%",
"significant_figures",
"lines",
"=",
"[",
"]",
"for",
"bound",
",",
"d",
"in",
"zip",
"(",
"self",
".",
"bounds",
",",
"\"xyz\"",
")",
":",... | 33.73913 | 17.652174 |
def reset(self):
"""
Reset the state of the sandbox.
http://docs.fiesta.cc/sandbox.html#post--reset
"""
path = 'reset'
request_data = {} # Need to put data into the request to force urllib2 to make it a POST request
response_data = self.request(path, request_dat... | [
"def",
"reset",
"(",
"self",
")",
":",
"path",
"=",
"'reset'",
"request_data",
"=",
"{",
"}",
"# Need to put data into the request to force urllib2 to make it a POST request",
"response_data",
"=",
"self",
".",
"request",
"(",
"path",
",",
"request_data",
")",
"succes... | 39.5 | 17.5 |
def normalize_example_nlp(task, example, is_infer, vocab_type, vocab_offset,
max_input_length, max_target_length,
fixed_train_length):
"""Normalize the examples from different tasks so they can be merged.
This function is specific to NLP tasks and normalizes them... | [
"def",
"normalize_example_nlp",
"(",
"task",
",",
"example",
",",
"is_infer",
",",
"vocab_type",
",",
"vocab_offset",
",",
"max_input_length",
",",
"max_target_length",
",",
"fixed_train_length",
")",
":",
"if",
"task",
".",
"has_inputs",
":",
"example",
"[",
"\... | 43.352113 | 21.014085 |
def exec_output(cls, command, shell=True, encoding='utf-8'):
""" Return execution output
:param encoding: charset used to decode the stdout
:type encoding: str
:return: the return of the command
:rtype: unicode string
"""
proc = Popen(command, shell=shell, stdou... | [
"def",
"exec_output",
"(",
"cls",
",",
"command",
",",
"shell",
"=",
"True",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"proc",
"=",
"Popen",
"(",
"command",
",",
"shell",
"=",
"shell",
",",
"stdout",
"=",
"PIPE",
")",
"stdout",
",",
"_stderr",
"=",
... | 30.2 | 15.666667 |
def setup_menu_actions(self):
"""Setup and update the menu actions."""
self.recent_project_menu.clear()
self.recent_projects_actions = []
if self.recent_projects:
for project in self.recent_projects:
if self.is_valid_project(project):
... | [
"def",
"setup_menu_actions",
"(",
"self",
")",
":",
"self",
".",
"recent_project_menu",
".",
"clear",
"(",
")",
"self",
".",
"recent_projects_actions",
"=",
"[",
"]",
"if",
"self",
".",
"recent_projects",
":",
"for",
"project",
"in",
"self",
".",
"recent_pro... | 47.125 | 15.25 |
def _split_covariance_into_marginals(covariance, block_sizes):
"""Split a covariance matrix into block-diagonal marginals of given sizes."""
start_dim = 0
marginals = []
for size in block_sizes:
end_dim = start_dim + size
marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim])
start_... | [
"def",
"_split_covariance_into_marginals",
"(",
"covariance",
",",
"block_sizes",
")",
":",
"start_dim",
"=",
"0",
"marginals",
"=",
"[",
"]",
"for",
"size",
"in",
"block_sizes",
":",
"end_dim",
"=",
"start_dim",
"+",
"size",
"marginals",
".",
"append",
"(",
... | 38.222222 | 18.777778 |
def set_quiet(mres, parent, global_options):
"""
Sets the 'quiet' property on the MultiResult
"""
quiet = global_options.get('quiet')
if quiet is not None:
mres._quiet = quiet
else:
mres._quiet = parent.quiet | [
"def",
"set_quiet",
"(",
"mres",
",",
"parent",
",",
"global_options",
")",
":",
"quiet",
"=",
"global_options",
".",
"get",
"(",
"'quiet'",
")",
"if",
"quiet",
"is",
"not",
"None",
":",
"mres",
".",
"_quiet",
"=",
"quiet",
"else",
":",
"mres",
".",
... | 26.666667 | 8.666667 |
def search_url(obj, url_data, pageno, seen_objs):
"""Recurse through a PDF object, searching for URLs."""
if isinstance(obj, PDFObjRef):
if obj.objid in seen_objs:
# prevent recursive loops
return
seen_objs.add(obj.objid)
obj = obj.resolve()
if isinstance(obj,... | [
"def",
"search_url",
"(",
"obj",
",",
"url_data",
",",
"pageno",
",",
"seen_objs",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"PDFObjRef",
")",
":",
"if",
"obj",
".",
"objid",
"in",
"seen_objs",
":",
"# prevent recursive loops",
"return",
"seen_objs",
... | 42.521739 | 13.434783 |
def insert(
self,
table_name,
obj=None,
database=None,
overwrite=False,
partition=None,
values=None,
validate=True,
):
"""
Insert into existing table.
See ImpalaTable.insert for other parameters.
Parameters
---... | [
"def",
"insert",
"(",
"self",
",",
"table_name",
",",
"obj",
"=",
"None",
",",
"database",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"partition",
"=",
"None",
",",
"values",
"=",
"None",
",",
"validate",
"=",
"True",
",",
")",
":",
"table",
... | 23.805556 | 19.194444 |
def _merge_single_runs(self, other_trajectory, used_runs):
""" Updates the `run_information` of the current trajectory."""
count = len(self) # Variable to count the increasing new run indices and create
# new run names
run_indices = range(len(other_trajectory))
run_name_dict ... | [
"def",
"_merge_single_runs",
"(",
"self",
",",
"other_trajectory",
",",
"used_runs",
")",
":",
"count",
"=",
"len",
"(",
"self",
")",
"# Variable to count the increasing new run indices and create",
"# new run names",
"run_indices",
"=",
"range",
"(",
"len",
"(",
"oth... | 41.538462 | 20.461538 |
def getProjectionRaw(self, eEye):
"""
The components necessary to build your own projection matrix in case your
application is doing something fancy like infinite Z
"""
fn = self.function_table.getProjectionRaw
pfLeft = c_float()
pfRight = c_float()
pfTop... | [
"def",
"getProjectionRaw",
"(",
"self",
",",
"eEye",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getProjectionRaw",
"pfLeft",
"=",
"c_float",
"(",
")",
"pfRight",
"=",
"c_float",
"(",
")",
"pfTop",
"=",
"c_float",
"(",
")",
"pfBottom",
"=",... | 38.461538 | 18.461538 |
def vec(self):
""":obj:`numpy.ndarray` : Vector representation for this camera.
"""
return np.r_[self.fx, self.fy, self.cx, self.cy, self.skew, self.height, self.width] | [
"def",
"vec",
"(",
"self",
")",
":",
"return",
"np",
".",
"r_",
"[",
"self",
".",
"fx",
",",
"self",
".",
"fy",
",",
"self",
".",
"cx",
",",
"self",
".",
"cy",
",",
"self",
".",
"skew",
",",
"self",
".",
"height",
",",
"self",
".",
"width",
... | 47.25 | 19.5 |
def parse_stations(html):
"""
Strips JS code, loads JSON
"""
html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '')
html = json.loads(html)
return html['suggestions'] | [
"def",
"parse_stations",
"(",
"html",
")",
":",
"html",
"=",
"html",
".",
"replace",
"(",
"'SLs.sls='",
",",
"''",
")",
".",
"replace",
"(",
"';SLs.showSuggestion();'",
",",
"''",
")",
"html",
"=",
"json",
".",
"loads",
"(",
"html",
")",
"return",
"htm... | 29.571429 | 11.571429 |
def gesture(self, start1, start2, *args, **kwargs):
'''
perform two point gesture.
Usage:
d().gesture(startPoint1, startPoint2).to(endPoint1, endPoint2, steps)
d().gesture(startPoint1, startPoint2, endPoint1, endPoint2, steps)
'''
def to(obj_self, end1, end2, step... | [
"def",
"gesture",
"(",
"self",
",",
"start1",
",",
"start2",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"to",
"(",
"obj_self",
",",
"end1",
",",
"end2",
",",
"steps",
"=",
"100",
")",
":",
"ctp",
"=",
"lambda",
"pt",
":",
"poin... | 52.846154 | 26.692308 |
def exclude_current_instance(self, queryset):
"""
If an instance is being updated, then do not include
that instance itself as a uniqueness conflict.
"""
if self.instance is not None:
return queryset.exclude(pk=self.instance.pk)
return queryset | [
"def",
"exclude_current_instance",
"(",
"self",
",",
"queryset",
")",
":",
"if",
"self",
".",
"instance",
"is",
"not",
"None",
":",
"return",
"queryset",
".",
"exclude",
"(",
"pk",
"=",
"self",
".",
"instance",
".",
"pk",
")",
"return",
"queryset"
] | 37.125 | 9.375 |
def to_camel_case(snake_case_string):
"""
Convert a string from snake case to camel case. For example, "some_var" would become "someVar".
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string.
"""
parts = snake_case_string.lstr... | [
"def",
"to_camel_case",
"(",
"snake_case_string",
")",
":",
"parts",
"=",
"snake_case_string",
".",
"lstrip",
"(",
"'_'",
")",
".",
"split",
"(",
"'_'",
")",
"return",
"parts",
"[",
"0",
"]",
"+",
"''",
".",
"join",
"(",
"[",
"i",
".",
"title",
"(",
... | 43.555556 | 20.444444 |
def trigger_event(name,
event,
value1=None,
value2=None,
value3=None
):
'''
Trigger an event in IFTTT
.. code-block:: yaml
ifttt-event:
ifttt.trigger_event:
- event: TestEvent
... | [
"def",
"trigger_event",
"(",
"name",
",",
"event",
",",
"value1",
"=",
"None",
",",
"value2",
"=",
"None",
",",
"value3",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",... | 23.918033 | 22.934426 |
def _poll_task(task_id, server_config, poll_rate=None, timeout=None):
"""Implement :meth:`nailgun.entities.ForemanTask.poll`.
See :meth:`nailgun.entities.ForemanTask.poll` for a full description of how
this method acts. Other methods may also call this method, such as
:meth:`nailgun.entity_mixins.Entit... | [
"def",
"_poll_task",
"(",
"task_id",
",",
"server_config",
",",
"poll_rate",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"poll_rate",
"is",
"None",
":",
"poll_rate",
"=",
"TASK_POLL_RATE",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
... | 38.818182 | 20.254545 |
def coalesce(*fields, **kwargs):
"""
Return a function which accepts a row and returns the first non-missing
value from the specified fields. Intended for use with
:func:`petl.transform.basics.addfield`.
"""
missing = kwargs.get('missing', None)
default = kwargs.get('default', None)
de... | [
"def",
"coalesce",
"(",
"*",
"fields",
",",
"*",
"*",
"kwargs",
")",
":",
"missing",
"=",
"kwargs",
".",
"get",
"(",
"'missing'",
",",
"None",
")",
"default",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"None",
")",
"def",
"_coalesce",
"(",
"... | 26.166667 | 16.611111 |
def buffer(self, buffer, buffer_format: str, attribute_names, per_instance=False):
"""
Register a buffer/vbo for the VAO. This can be called multiple times.
adding multiple buffers (interleaved or not)
Args:
buffer: The buffer data. Can be ``numpy.array``, ``moderngl.Buffer`... | [
"def",
"buffer",
"(",
"self",
",",
"buffer",
",",
"buffer_format",
":",
"str",
",",
"attribute_names",
",",
"per_instance",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"attribute_names",
",",
"list",
")",
":",
"attribute_names",
"=",
"[",
"attr... | 42.146341 | 29.853659 |
def bond_task(
perc_graph_result, seeds, ps, convolution_factors_tasks_iterator
):
"""
Perform a number of runs
The number of runs is the number of seeds
convolution_factors_tasks_iterator needs to be an iterator
We shield the convolution factors tasks from jug value/result mechanism
by s... | [
"def",
"bond_task",
"(",
"perc_graph_result",
",",
"seeds",
",",
"ps",
",",
"convolution_factors_tasks_iterator",
")",
":",
"# restore the list of convolution factors tasks",
"convolution_factors_tasks",
"=",
"list",
"(",
"convolution_factors_tasks_iterator",
")",
"return",
"... | 32.758621 | 25.793103 |
def country_code(self, fmt: Optional[CountryCode] = CountryCode.A2) -> str:
"""Get a random code of country.
Default format is :attr:`~enums.CountryCode.A2` (ISO 3166-1-alpha2),
you can change it by passing parameter ``fmt`` with enum object
:class:`~enums.CountryCode`.
:param ... | [
"def",
"country_code",
"(",
"self",
",",
"fmt",
":",
"Optional",
"[",
"CountryCode",
"]",
"=",
"CountryCode",
".",
"A2",
")",
"->",
"str",
":",
"key",
"=",
"self",
".",
"_validate_enum",
"(",
"fmt",
",",
"CountryCode",
")",
"return",
"self",
".",
"rand... | 42.769231 | 17.923077 |
def _consume_rpc_request(self, arguments, consumer_tag, exclusive, no_ack,
no_local, queue):
"""Create a Consume Frame and execute a RPC request.
:param str queue: Queue name
:param str consumer_tag: Consumer tag
:param bool no_local: Do not deliver own mess... | [
"def",
"_consume_rpc_request",
"(",
"self",
",",
"arguments",
",",
"consumer_tag",
",",
"exclusive",
",",
"no_ack",
",",
"no_local",
",",
"queue",
")",
":",
"consume_frame",
"=",
"specification",
".",
"Basic",
".",
"Consume",
"(",
"queue",
"=",
"queue",
",",... | 49.6 | 20.45 |
def do_enable():
"""
Uncomment any lines that start with #import in the .pth file
"""
try:
_lines = []
with open(vext_pth, mode='r') as f:
for line in f.readlines():
if line.startswith('#') and line[1:].lstrip().startswith('import '):
_line... | [
"def",
"do_enable",
"(",
")",
":",
"try",
":",
"_lines",
"=",
"[",
"]",
"with",
"open",
"(",
"vext_pth",
",",
"mode",
"=",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"... | 27.125 | 18.5625 |
def _is_valid_options_weights_list(value):
'''Check whether ``values`` is a valid argument for ``weighted_choice``.'''
return ((isinstance(value, list)) and
len(value) > 1 and
(all(isinstance(opt, tuple) and
len(opt) == 2 and
isinstance(opt[1], (int, flo... | [
"def",
"_is_valid_options_weights_list",
"(",
"value",
")",
":",
"return",
"(",
"(",
"isinstance",
"(",
"value",
",",
"list",
")",
")",
"and",
"len",
"(",
"value",
")",
">",
"1",
"and",
"(",
"all",
"(",
"isinstance",
"(",
"opt",
",",
"tuple",
")",
"a... | 44.25 | 9.25 |
def download(self, replace=False):
"""
Download the dataset from the hosted Yellowbrick data store and save
it to the location specified by ``get_data_home``. The downloader
verifies the download completed successfully and safely by comparing
the expected signature with the SHA 2... | [
"def",
"download",
"(",
"self",
",",
"replace",
"=",
"False",
")",
":",
"download_data",
"(",
"self",
".",
"url",
",",
"self",
".",
"signature",
",",
"data_home",
"=",
"self",
".",
"data_home",
",",
"replace",
"=",
"replace",
",",
"extract",
"=",
"True... | 40.555556 | 21.555556 |
def put(self, file):
""" Create a new file on github
:param file: File to create
:return: File or self.ProxyError
"""
input_ = {
"message": file.logs,
"author": file.author.dict(),
"content": file.base64,
"branch": file.branch
... | [
"def",
"put",
"(",
"self",
",",
"file",
")",
":",
"input_",
"=",
"{",
"\"message\"",
":",
"file",
".",
"logs",
",",
"\"author\"",
":",
"file",
".",
"author",
".",
"dict",
"(",
")",
",",
"\"content\"",
":",
"file",
".",
"base64",
",",
"\"branch\"",
... | 29.83871 | 14.354839 |
def generate_match_query(field, value, with_operator_and):
"""Helper for generating a match query.
Args:
field (six.text_type): The ES field to be queried.
value (six.text_type/bool): The value of the query (bool for the case of type-code query ["core: true"]).
with_operator_and (bool):... | [
"def",
"generate_match_query",
"(",
"field",
",",
"value",
",",
"with_operator_and",
")",
":",
"parsed_value",
"=",
"None",
"try",
":",
"parsed_value",
"=",
"json",
".",
"loads",
"(",
"value",
".",
"lower",
"(",
")",
")",
"except",
"(",
"ValueError",
",",
... | 34.638889 | 24.027778 |
def _init_taxids(taxid, taxids):
"""Return taxid set"""
ret = set()
if taxids is not None:
if taxids is True:
return True
if isinstance(taxids, int):
ret.add(taxids)
else:
ret.update(taxids)
if taxid is n... | [
"def",
"_init_taxids",
"(",
"taxid",
",",
"taxids",
")",
":",
"ret",
"=",
"set",
"(",
")",
"if",
"taxids",
"is",
"not",
"None",
":",
"if",
"taxids",
"is",
"True",
":",
"return",
"True",
"if",
"isinstance",
"(",
"taxids",
",",
"int",
")",
":",
"ret"... | 31.411765 | 13.647059 |
def run_idle(self):
"""Run one of the idle callbacks.
Returns:
True if one was called, False if no idle callback was called.
"""
if not self.idlers or self.inactive >= len(self.idlers):
return False
idler = self.idlers.popleft()
callback, args, kwds = idler
_logging_debug('idler... | [
"def",
"run_idle",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"idlers",
"or",
"self",
".",
"inactive",
">=",
"len",
"(",
"self",
".",
"idlers",
")",
":",
"return",
"False",
"idler",
"=",
"self",
".",
"idlers",
".",
"popleft",
"(",
")",
"callb... | 29.363636 | 18.272727 |
def execute(self, run):
"""
This function executes the tool with a sourcefile with options.
It also calls functions for output before and after the run.
"""
self.output_handler.output_before_run(run)
benchmark = self.benchmark
memlimit = benchmark.rlimits.get(MEM... | [
"def",
"execute",
"(",
"self",
",",
"run",
")",
":",
"self",
".",
"output_handler",
".",
"output_before_run",
"(",
"run",
")",
"benchmark",
"=",
"self",
".",
"benchmark",
"memlimit",
"=",
"benchmark",
".",
"rlimits",
".",
"get",
"(",
"MEMLIMIT",
")",
"ar... | 39.5625 | 17.8125 |
def _send_ffe(self, pid, app_id, app_flags, fr):
"""Send a flood-fill end packet.
The cores and regions that the application should be loaded to will
have been specified by a stream of flood-fill core select packets
(FFCS).
"""
arg1 = (NNCommands.flood_fill_end << 24) | ... | [
"def",
"_send_ffe",
"(",
"self",
",",
"pid",
",",
"app_id",
",",
"app_flags",
",",
"fr",
")",
":",
"arg1",
"=",
"(",
"NNCommands",
".",
"flood_fill_end",
"<<",
"24",
")",
"|",
"pid",
"arg2",
"=",
"(",
"app_id",
"<<",
"24",
")",
"|",
"(",
"app_flags... | 43.272727 | 18.090909 |
def _forward_outbound(self, channel):
""" Forward outbound traffic (ssh -> websockets) """
try:
while True:
wait_read(channel.fileno())
data = channel.recv(1024)
if not len(data):
return
self._websocket.send(... | [
"def",
"_forward_outbound",
"(",
"self",
",",
"channel",
")",
":",
"try",
":",
"while",
"True",
":",
"wait_read",
"(",
"channel",
".",
"fileno",
"(",
")",
")",
"data",
"=",
"channel",
".",
"recv",
"(",
"1024",
")",
"if",
"not",
"len",
"(",
"data",
... | 34.454545 | 12.454545 |
def get_tornado_apps(context, debug=False):
"""
Create Tornado's application for all interfaces which are defined
in the configuration. *context* is instance of the
:class:`shelter.core.context.Context`. If *debug* is :const:`True`,
server will be run in **DEBUG** mode. Return :class:`list` of the
... | [
"def",
"get_tornado_apps",
"(",
"context",
",",
"debug",
"=",
"False",
")",
":",
"if",
"context",
".",
"config",
".",
"app_settings_handler",
":",
"app_settings_handler",
"=",
"import_object",
"(",
"context",
".",
"config",
".",
"app_settings_handler",
")",
"set... | 34.777778 | 16.111111 |
def launchQueryForMode(self, query=None, mode=None):
"""
Method that launches an i3Browser to collect data.
Args:
-----
query: The query to be performed
mode: The mode to be used to build the query.
Return:
-------
A string containing... | [
"def",
"launchQueryForMode",
"(",
"self",
",",
"query",
"=",
"None",
",",
"mode",
"=",
"None",
")",
":",
"# Creating the query URL for that mode",
"qURL",
"=",
"self",
".",
"createURL",
"(",
"word",
"=",
"query",
",",
"mode",
"=",
"mode",
")",
"i3Browser",
... | 32.566667 | 19.5 |
def combination_step(self):
"""Update auxiliary state by a smart combination of previous
updates in the frequency domain (standard FISTA
:cite:`beck-2009-fast`).
"""
# Update t step
tprv = self.t
self.t = 0.5 * float(1. + np.sqrt(1. + 4. * tprv**2))
# Up... | [
"def",
"combination_step",
"(",
"self",
")",
":",
"# Update t step",
"tprv",
"=",
"self",
".",
"t",
"self",
".",
"t",
"=",
"0.5",
"*",
"float",
"(",
"1.",
"+",
"np",
".",
"sqrt",
"(",
"1.",
"+",
"4.",
"*",
"tprv",
"**",
"2",
")",
")",
"# Update Y... | 33.357143 | 16.714286 |
def run(self, plugin_manager=None):
"""Run the haas test runner.
This will load and configure the selected plugins, set up the
environment and begin test discovery, loading and running.
Parameters
----------
plugin_manager : haas.plugin_manager.PluginManager
... | [
"def",
"run",
"(",
"self",
",",
"plugin_manager",
"=",
"None",
")",
":",
"if",
"plugin_manager",
"is",
"None",
":",
"plugin_manager",
"=",
"PluginManager",
"(",
")",
"plugin_manager",
".",
"add_plugin_arguments",
"(",
"self",
".",
"parser",
")",
"args",
"=",... | 36.960784 | 18.980392 |
def parseFloat(self, words):
"""Convert a floating-point number described in words to a double.
Supports two kinds of descriptions: those with a 'point' (e.g.,
"one point two five") and those with a fraction (e.g., "one and
a quarter").
Args:
words (str): Descriptio... | [
"def",
"parseFloat",
"(",
"self",
",",
"words",
")",
":",
"def",
"pointFloat",
"(",
"words",
")",
":",
"m",
"=",
"re",
".",
"search",
"(",
"r'(.*) point (.*)'",
",",
"words",
")",
"if",
"m",
":",
"whole",
"=",
"m",
".",
"group",
"(",
"1",
")",
"f... | 32.376812 | 18.942029 |
def _rc_rpoplpush(self, src, dst):
"""
RPOP a value off of the ``src`` list and LPUSH it
on to the ``dst`` list. Returns the value.
"""
rpop = self.rpop(src)
if rpop is not None:
self.lpush(dst, rpop)
return rpop
return None | [
"def",
"_rc_rpoplpush",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"rpop",
"=",
"self",
".",
"rpop",
"(",
"src",
")",
"if",
"rpop",
"is",
"not",
"None",
":",
"self",
".",
"lpush",
"(",
"dst",
",",
"rpop",
")",
"return",
"rpop",
"return",
"Non... | 29.6 | 10.2 |
def log(wave):
r"""
Return the natural logarithm of a waveform's dependent variable vector.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentati... | [
"def",
"log",
"(",
"wave",
")",
":",
"pexdoc",
".",
"exh",
".",
"addex",
"(",
"ValueError",
",",
"\"Math domain error\"",
",",
"bool",
"(",
"(",
"min",
"(",
"wave",
".",
"_dep_vector",
")",
"<=",
"0",
")",
")",
")",
"return",
"_operation",
"(",
"wave... | 26.565217 | 23.304348 |
def _copy_from(self, rhs):
"""Copy all data from rhs into this instance, handles usage count"""
self._manager = rhs._manager
self._rlist = type(rhs._rlist)(rhs._rlist)
self._region = rhs._region
self._ofs = rhs._ofs
self._size = rhs._size
for region in self._rlis... | [
"def",
"_copy_from",
"(",
"self",
",",
"rhs",
")",
":",
"self",
".",
"_manager",
"=",
"rhs",
".",
"_manager",
"self",
".",
"_rlist",
"=",
"type",
"(",
"rhs",
".",
"_rlist",
")",
"(",
"rhs",
".",
"_rlist",
")",
"self",
".",
"_region",
"=",
"rhs",
... | 34 | 12.153846 |
def auth(self, request):
"""
let's auth the user to the Service
:param request: request object
:return: callback url
:rtype: string that contains the url to redirect after auth
"""
service = UserService.objects.get(user=request.user, name='Service... | [
"def",
"auth",
"(",
"self",
",",
"request",
")",
":",
"service",
"=",
"UserService",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
",",
"name",
"=",
"'ServiceWallabag'",
")",
"callback_url",
"=",
"'%s://%s%s'",
"%",
"(",
"request"... | 45.352941 | 17.705882 |
def _next_iter_line(self, row_num):
"""
Wrapper around iterating through `self.data` (CSV source).
When a CSV error is raised, we check for specific
error messages that allow us to customize the
error message displayed to the user.
Parameters
----------
... | [
"def",
"_next_iter_line",
"(",
"self",
",",
"row_num",
")",
":",
"try",
":",
"return",
"next",
"(",
"self",
".",
"data",
")",
"except",
"csv",
".",
"Error",
"as",
"e",
":",
"if",
"self",
".",
"warn_bad_lines",
"or",
"self",
".",
"error_bad_lines",
":",... | 37.142857 | 19.657143 |
def autoargs(include=None, # type: Union[str, Tuple[str]]
exclude=None, # type: Union[str, Tuple[str]]
f=DECORATED
):
"""
Defines a decorator with parameters, to automatically assign the inputs of a function to self PRIOR to executing
the function. In other words:
... | [
"def",
"autoargs",
"(",
"include",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"exclude",
"=",
"None",
",",
"# type: Union[str, Tuple[str]]",
"f",
"=",
"DECORATED",
")",
":",
"return",
"autoargs_decorate",
"(",
"f",
",",
"include",
"=",
"include",
",",
"... | 33.4 | 31.666667 |
def ipa_chars(self, value):
"""
Set the list of IPAChar objects composing the IPA string
:param list value: list of IPAChar objects
"""
if value is None:
self.__ipa_chars = []
else:
if is_list_of_ipachars(value):
self.__ipa_chars =... | [
"def",
"ipa_chars",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"self",
".",
"__ipa_chars",
"=",
"[",
"]",
"else",
":",
"if",
"is_list_of_ipachars",
"(",
"value",
")",
":",
"self",
".",
"__ipa_chars",
"=",
"value",
"else",
... | 32 | 15.692308 |
def _value_format(self, value):
"""Format value for dual value display."""
return super(VerticalPyramid, self)._value_format(value and abs(value)) | [
"def",
"_value_format",
"(",
"self",
",",
"value",
")",
":",
"return",
"super",
"(",
"VerticalPyramid",
",",
"self",
")",
".",
"_value_format",
"(",
"value",
"and",
"abs",
"(",
"value",
")",
")"
] | 53.333333 | 16 |
def getheaders(self, name):
"""Get all values for a header.
This returns a list of values for headers given more than once; each
value in the result list is stripped in the same way as the result of
getheader(). If the header is not given, return an empty list.
"""
resu... | [
"def",
"getheaders",
"(",
"self",
",",
"name",
")",
":",
"result",
"=",
"[",
"]",
"current",
"=",
"''",
"have_header",
"=",
"0",
"for",
"s",
"in",
"self",
".",
"getallmatchingheaders",
"(",
"name",
")",
":",
"if",
"s",
"[",
"0",
"]",
".",
"isspace"... | 35.166667 | 16.166667 |
async def read(self) -> bytes:
"""Read request body if present.
Returns bytes object with full request content.
"""
if self._read_bytes is None:
body = bytearray()
while True:
chunk = await self._payload.readany()
body.extend(chunk... | [
"async",
"def",
"read",
"(",
"self",
")",
"->",
"bytes",
":",
"if",
"self",
".",
"_read_bytes",
"is",
"None",
":",
"body",
"=",
"bytearray",
"(",
")",
"while",
"True",
":",
"chunk",
"=",
"await",
"self",
".",
"_payload",
".",
"readany",
"(",
")",
"... | 36.571429 | 11 |
def get_representative_json(file_input=None,
formatted=False, annotate_is_json=False,
sampling_substitution_regex=('(.+)', '\\1_sample'),
do_not_sample=('sqlite_stat1', ),
sampling_limits=None):
"""
:... | [
"def",
"get_representative_json",
"(",
"file_input",
"=",
"None",
",",
"formatted",
"=",
"False",
",",
"annotate_is_json",
"=",
"False",
",",
"sampling_substitution_regex",
"=",
"(",
"'(.+)'",
",",
"'\\\\1_sample'",
")",
",",
"do_not_sample",
"=",
"(",
"'sqlite_st... | 36.368421 | 21.815789 |
def register_plugins():
"""find any installed plugins and register them."""
if pkg_resources: # pragma: no cover
for ep in pkg_resources.iter_entry_points('slam_plugins'):
plugin = ep.load()
# add any init options to the main init command
if hasattr(plugin, 'init') ... | [
"def",
"register_plugins",
"(",
")",
":",
"if",
"pkg_resources",
":",
"# pragma: no cover",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'slam_plugins'",
")",
":",
"plugin",
"=",
"ep",
".",
"load",
"(",
")",
"# add any init options to the ma... | 43.857143 | 18.5 |
def _render_headers(self):
"""
Write the headers row
"""
headers = getattr(self, 'headers', ())
for index, col in enumerate(headers):
# We write the headers
cell = self.worksheet.cell(row=1, column=index + 1)
cell.value = col['label']
... | [
"def",
"_render_headers",
"(",
"self",
")",
":",
"headers",
"=",
"getattr",
"(",
"self",
",",
"'headers'",
",",
"(",
")",
")",
"for",
"index",
",",
"col",
"in",
"enumerate",
"(",
"headers",
")",
":",
"# We write the headers",
"cell",
"=",
"self",
".",
... | 34.0625 | 15.0625 |
def connect(config_file=qcs.default_filename, section='info', remember_me=False, remember_me_always=False):
""" Return a QGAPIConnect object for v1 API pulling settings from config
file.
"""
# Retrieve login credentials.
conf = qcconf.QualysConnectConfig(filename=config_file, section=section, rememb... | [
"def",
"connect",
"(",
"config_file",
"=",
"qcs",
".",
"default_filename",
",",
"section",
"=",
"'info'",
",",
"remember_me",
"=",
"False",
",",
"remember_me_always",
"=",
"False",
")",
":",
"# Retrieve login credentials.",
"conf",
"=",
"qcconf",
".",
"QualysCon... | 51.692308 | 20.692308 |
def balanceSheetDF(symbol, token='', version=''):
'''Pulls balance sheet data. Available quarterly (4 quarters) and annually (4 years)
https://iexcloud.io/docs/api/#balance-sheet
Updates at 8am, 9am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
... | [
"def",
"balanceSheetDF",
"(",
"symbol",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"val",
"=",
"balanceSheet",
"(",
"symbol",
",",
"token",
",",
"version",
")",
"df",
"=",
"pd",
".",
"io",
".",
"json",
".",
"json_normalize",
"(",
... | 27.9 | 21.8 |
def runs(self):
"""Instance depends on the API version:
* 2018-09-01: :class:`RunsOperations<azure.mgmt.containerregistry.v2018_09_01.operations.RunsOperations>`
"""
api_version = self._get_api_version('runs')
if api_version == '2018-09-01':
from .v2018_09_01.oper... | [
"def",
"runs",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'runs'",
")",
"if",
"api_version",
"==",
"'2018-09-01'",
":",
"from",
".",
"v2018_09_01",
".",
"operations",
"import",
"RunsOperations",
"as",
"OperationClass",
"e... | 55.363636 | 34.272727 |
def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search):
"""Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resou... | [
"def",
"get_sequence_rule_enablers_by_search",
"(",
"self",
",",
"sequence_rule_enabler_query",
",",
"sequence_rule_enabler_search",
")",
":",
"# Implemented from azosid template for -",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"if",
"not",
"self",
".",... | 77.714286 | 30.571429 |
def stop(self):
"""
Stop ZMQ tools.
:return: self
"""
LOGGER.debug("zeromq.Driver.stop")
for publisher in self.publishers_registry:
publisher.stop()
self.publishers_registry.clear()
for subscriber in self.subscribers_registry:
if su... | [
"def",
"stop",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"zeromq.Driver.stop\"",
")",
"for",
"publisher",
"in",
"self",
".",
"publishers_registry",
":",
"publisher",
".",
"stop",
"(",
")",
"self",
".",
"publishers_registry",
".",
"clear",
"(",
... | 30.866667 | 8.6 |
def graph_png(self):
"""
Export a graph of the data in png format using graphviz/dot.
"""
if not self.out_file:
ui.error(c.MESSAGES["png_missing_out"])
sys.exit(1)
cli_flags = "-Gsize='{0}' -Gdpi='{1}' {2} ".format(self.size, self.dpi,
... | [
"def",
"graph_png",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"out_file",
":",
"ui",
".",
"error",
"(",
"c",
".",
"MESSAGES",
"[",
"\"png_missing_out\"",
"]",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"cli_flags",
"=",
"\"-Gsize='{0}' -Gdpi='{1}' {2... | 32.666667 | 20 |
def buscar_por_id(self, id_ambiente):
"""Obtém um ambiente a partir da chave primária (identificador).
:param id_ambiente: Identificador do ambiente.
:return: Dicionário com a seguinte estrutura:
::
{'ambiente': {'id': < id_ambiente >,
'link': < link >,
... | [
"def",
"buscar_por_id",
"(",
"self",
",",
"id_ambiente",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_ambiente",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'O identificador do ambiente é inválido ou não foi informado.')",
"",
"url",
"=",
"'environment/id/... | 38.842105 | 18.184211 |
def security_rule_create_or_update(name, access, direction, priority, protocol, security_group, resource_group,
source_address_prefix=None, destination_address_prefix=None, source_port_range=None,
destination_port_range=None, source_address_prefixes=... | [
"def",
"security_rule_create_or_update",
"(",
"name",
",",
"access",
",",
"direction",
",",
"priority",
",",
"protocol",
",",
"security_group",
",",
"resource_group",
",",
"source_address_prefix",
"=",
"None",
",",
"destination_address_prefix",
"=",
"None",
",",
"so... | 40.266667 | 26.666667 |
def filter_filenames_by_info(self, filename_items):
"""Filter out file using metadata from the filenames.
This sorts out the different lon and lat datasets depending on TC is
desired or not.
"""
filename_items = list(filename_items)
geo_keep = []
geo_del = []
... | [
"def",
"filter_filenames_by_info",
"(",
"self",
",",
"filename_items",
")",
":",
"filename_items",
"=",
"list",
"(",
"filename_items",
")",
"geo_keep",
"=",
"[",
"]",
"geo_del",
"=",
"[",
"]",
"for",
"filename",
",",
"filename_info",
"in",
"filename_items",
":... | 43.742857 | 15.057143 |
def interpret_header(self):
"""
Read pertinent information from the image headers,
especially location and radius of the Sun to calculate the default thematic map
:return: setes self.date, self.cy, self.cx, and self.sun_radius_pixel
"""
# handle special cases since date-... | [
"def",
"interpret_header",
"(",
"self",
")",
":",
"# handle special cases since date-obs field changed names",
"if",
"'DATE_OBS'",
"in",
"self",
".",
"header",
":",
"self",
".",
"date",
"=",
"self",
".",
"header",
"[",
"'DATE_OBS'",
"]",
"elif",
"'DATE-OBS'",
"in"... | 49.444444 | 22 |
def get_revision_sha(self, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev t... | [
"def",
"get_revision_sha",
"(",
"self",
",",
"dest",
",",
"rev",
")",
":",
"# Pass rev to pre-filter the list.",
"output",
"=",
"self",
".",
"run_command",
"(",
"[",
"'show-ref'",
",",
"rev",
"]",
",",
"cwd",
"=",
"dest",
",",
"show_stdout",
"=",
"False",
... | 33.121212 | 19 |
def fromProfile(cls, profile):
"""Return an `Origin` from a given configuration profile.
:see: `ProfileStore`.
"""
session = bones.SessionAPI.fromProfile(profile)
return cls(session) | [
"def",
"fromProfile",
"(",
"cls",
",",
"profile",
")",
":",
"session",
"=",
"bones",
".",
"SessionAPI",
".",
"fromProfile",
"(",
"profile",
")",
"return",
"cls",
"(",
"session",
")"
] | 31 | 12.714286 |
def update_stock_codes():
"""获取所有股票 ID 到 all_stock_code 目录下"""
all_stock_codes_url = "http://www.shdjt.com/js/lib/astock.js"
grep_stock_codes = re.compile(r"~(\d+)`")
response = requests.get(all_stock_codes_url)
all_stock_codes = grep_stock_codes.findall(response.text)
with open(stock_code_path(... | [
"def",
"update_stock_codes",
"(",
")",
":",
"all_stock_codes_url",
"=",
"\"http://www.shdjt.com/js/lib/astock.js\"",
"grep_stock_codes",
"=",
"re",
".",
"compile",
"(",
"r\"~(\\d+)`\"",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"all_stock_codes_url",
")",
"al... | 47.875 | 11.625 |
def update(self, *args, **kwargs):
"""
Reimplements the :meth:`Dict.update` method.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
"""
dict.update(self, *args, **kwargs)
self.__dict__.upda... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dict",
".",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"__dict__",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"k... | 27.333333 | 12 |
def _forward_mode(self, *args):
"""Forward mode differentiation for a constant"""
# Evaluate inner function self.f
X: np.ndarray
dX: np.ndarray
X, dX = self.f._forward_mode(*args)
# The function value
val = self.func(X)
# The derivative
diff = self... | [
"def",
"_forward_mode",
"(",
"self",
",",
"*",
"args",
")",
":",
"# Evaluate inner function self.f",
"X",
":",
"np",
".",
"ndarray",
"dX",
":",
"np",
".",
"ndarray",
"X",
",",
"dX",
"=",
"self",
".",
"f",
".",
"_forward_mode",
"(",
"*",
"args",
")",
... | 31.909091 | 10.181818 |
def formatted_str(self, format):
"""Return formatted str.
:param format: one of 'json', 'csv' are supported
"""
assert(format in ('json', 'csv'))
ret_str_list = []
for rec in self._records:
if format == 'json':
ret_str_list.append('{')
... | [
"def",
"formatted_str",
"(",
"self",
",",
"format",
")",
":",
"assert",
"(",
"format",
"in",
"(",
"'json'",
",",
"'csv'",
")",
")",
"ret_str_list",
"=",
"[",
"]",
"for",
"rec",
"in",
"self",
".",
"_records",
":",
"if",
"format",
"==",
"'json'",
":",
... | 41.846154 | 13.115385 |
def get_instance(self, payload):
"""
Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance
... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"RecordingInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"call_sid",
"=",
"self",
".",
"_so... | 33.733333 | 18.933333 |
def _get_comments(group_tasks):
"""
Get the human readable comments and quantities for the task types.
"""
comments = {}
for status, human in _COMMENTS:
num_tasks = _get_number_of_tasks_for(status, group_tasks)
if num_tasks:
space = " " if status in _PENDING_SUB_STATUS... | [
"def",
"_get_comments",
"(",
"group_tasks",
")",
":",
"comments",
"=",
"{",
"}",
"for",
"status",
",",
"human",
"in",
"_COMMENTS",
":",
"num_tasks",
"=",
"_get_number_of_tasks_for",
"(",
"status",
",",
"group_tasks",
")",
"if",
"num_tasks",
":",
"space",
"="... | 36.071429 | 15.785714 |
def push(self, url, title=''):
"""
Pushes the url into the history stack at the current index.
:param url | <str>
:return <bool> | changed
"""
# ignore refreshes of the top level
if self.currentUrl() == url or self._blockStack:
... | [
"def",
"push",
"(",
"self",
",",
"url",
",",
"title",
"=",
"''",
")",
":",
"# ignore refreshes of the top level",
"if",
"self",
".",
"currentUrl",
"(",
")",
"==",
"url",
"or",
"self",
".",
"_blockStack",
":",
"return",
"False",
"self",
".",
"_blockStack",
... | 30.357143 | 17.142857 |
def getattr(self, obj, attribute):
"""Get an item or attribute of an object but prefer the attribute.
Unlike :meth:`getitem` the attribute *must* be a bytestring.
"""
try:
return getattr(obj, attribute)
except AttributeError:
pass
try:
... | [
"def",
"getattr",
"(",
"self",
",",
"obj",
",",
"attribute",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"obj",
",",
"attribute",
")",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"return",
"obj",
"[",
"attribute",
"]",
"except",
"(",
"Type... | 37.166667 | 13.916667 |
def normalize(pw):
""" Lower case, and change the symbols to closest characters"""
pw_lower = pw.lower()
return ''.join(helper.L33T.get(c, c) for c in pw_lower) | [
"def",
"normalize",
"(",
"pw",
")",
":",
"pw_lower",
"=",
"pw",
".",
"lower",
"(",
")",
"return",
"''",
".",
"join",
"(",
"helper",
".",
"L33T",
".",
"get",
"(",
"c",
",",
"c",
")",
"for",
"c",
"in",
"pw_lower",
")"
] | 42.25 | 14 |
def parse_site(sample, convention, Z):
"""
parse the site name from the sample name using the specified convention
"""
convention = str(convention)
site = sample # default is that site = sample
#
#
# Sample is final letter on site designation eg: TG001a (used by SIO lab
# in San Diego)
if conv... | [
"def",
"parse_site",
"(",
"sample",
",",
"convention",
",",
"Z",
")",
":",
"convention",
"=",
"str",
"(",
"convention",
")",
"site",
"=",
"sample",
"# default is that site = sample",
"#",
"#",
"# Sample is final letter on site designation eg: TG001a (used by SIO lab",
... | 27.897959 | 23.244898 |
def _has_expired(self):
""" Has this HIT expired yet? """
expired = False
if hasattr(self, 'Expiration'):
now = datetime.datetime.utcnow()
expiration = datetime.datetime.strptime(self.Expiration, '%Y-%m-%dT%H:%M:%SZ')
expired = (now >= expiration)
else... | [
"def",
"_has_expired",
"(",
"self",
")",
":",
"expired",
"=",
"False",
"if",
"hasattr",
"(",
"self",
",",
"'Expiration'",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"expiration",
"=",
"datetime",
".",
"datetime",
".",
"... | 43 | 18.9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.