text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def preloop(self):
''' Executed before the command loop starts. '''
script_dir = os.path.dirname(os.path.realpath(__file__))
help_dir = os.path.join(script_dir, HELP_DIR_NAME)
self.load_forth_commands(help_dir)
self.load_shell_commands(help_dir) | [
"def",
"preloop",
"(",
"self",
")",
":",
"script_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"help_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"script_dir",
",",
"HELP_DIR_NAME... | 46.666667 | 14 |
def find_TPs_and_DUPs(self, percent=5., makefig=False):
"""
Function which finds TPs and uses the calc_DUP_parameter
function. To calculate DUP parameter evolution dependent of
the star or core mass.
Parameters
----------
fig : integer
Figure number ... | [
"def",
"find_TPs_and_DUPs",
"(",
"self",
",",
"percent",
"=",
"5.",
",",
"makefig",
"=",
"False",
")",
":",
"t0_model",
"=",
"self",
".",
"find_first_TP",
"(",
")",
"t0_idx",
"=",
"(",
"t0_model",
"-",
"self",
".",
"get",
"(",
"\"model_number\"",
")",
... | 37.149533 | 18.738318 |
def orchestration_restore(self, saved_artifact_info, custom_params=None):
"""Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters
"""
if saved_artifact_info is None or saved_... | [
"def",
"orchestration_restore",
"(",
"self",
",",
"saved_artifact_info",
",",
"custom_params",
"=",
"None",
")",
":",
"if",
"saved_artifact_info",
"is",
"None",
"or",
"saved_artifact_info",
"==",
"''",
":",
"raise",
"Exception",
"(",
"'ConfigurationOperations'",
","... | 50.622222 | 32.6 |
def to_xml(self):
'''
Returns a DOM representation of the line.
@return: Element
'''
for n, v in {"name": self.name, "quantity": self.quantity,
"unit_price": self.unit_price}.items():
if is_empty_or_none(v):
raise LineError("'%s' a... | [
"def",
"to_xml",
"(",
"self",
")",
":",
"for",
"n",
",",
"v",
"in",
"{",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"quantity\"",
":",
"self",
".",
"quantity",
",",
"\"unit_price\"",
":",
"self",
".",
"unit_price",
"}",
".",
"items",
"(",
")",
":... | 45.391304 | 19.782609 |
def dp_from_p(p, ps, p_top=0., p_bot=1.1e5):
"""Get level thickness of pressure data, incorporating surface pressure.
Level edges are defined as halfway between the levels, as well as the user-
specified uppermost and lowermost values. The dp of levels whose bottom
pressure is less than the surface pr... | [
"def",
"dp_from_p",
"(",
"p",
",",
"ps",
",",
"p_top",
"=",
"0.",
",",
"p_bot",
"=",
"1.1e5",
")",
":",
"p_str",
"=",
"get_dim_name",
"(",
"p",
",",
"(",
"internal_names",
".",
"PLEVEL_STR",
",",
"'plev'",
")",
")",
"p_vals",
"=",
"to_pascal",
"(",
... | 46.709677 | 19.951613 |
async def close(self, event):
"""Close the PLM device connection and don't try to reconnect."""
_LOGGER.info('Closing connection to Insteon Modem')
self._closing = True
self._auto_reconnect = False
await self.protocol.close()
if self.protocol.transport:
self.p... | [
"async",
"def",
"close",
"(",
"self",
",",
"event",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Closing connection to Insteon Modem'",
")",
"self",
".",
"_closing",
"=",
"True",
"self",
".",
"_auto_reconnect",
"=",
"False",
"await",
"self",
".",
"protocol",
"."... | 44 | 8.1 |
def limit_value_string_length(value):
"""This method limits the string representation of the value to MAX_VALUE_LABEL_TEXT_LENGTH + 3 characters.
:param value: Value to limit string representation
:return: String holding the value with a maximum length of MAX_VALUE_LABEL_TEXT_LENGTH + 3
"""
if isin... | [
"def",
"limit_value_string_length",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"string_types",
")",
"and",
"len",
"(",
"value",
")",
">",
"constants",
".",
"MAX_VALUE_LABEL_TEXT_LENGTH",
":",
"value",
"=",
"value",
"[",
":",
"constants",
... | 50.5 | 24.5 |
def listed(self):
"""Print blacklist packages
"""
print("\nPackages in the blacklist:\n")
for black in self.get_black():
if black:
print("{0}{1}{2}".format(self.meta.color["GREEN"], black,
self.meta.color["ENDC"]))
... | [
"def",
"listed",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nPackages in the blacklist:\\n\"",
")",
"for",
"black",
"in",
"self",
".",
"get_black",
"(",
")",
":",
"if",
"black",
":",
"print",
"(",
"\"{0}{1}{2}\"",
".",
"format",
"(",
"self",
".",
"meta",
... | 34.727273 | 14.181818 |
def to_dictionary(self):
"""Serialize an object into dictionary form. Useful if you have to
serialize an array of objects into JSON. Otherwise, if you call the
:meth:`to_json` method on each object in the list and then try to
dump the array, you end up with an array with one string."""... | [
"def",
"to_dictionary",
"(",
"self",
")",
":",
"j",
"=",
"{",
"}",
"for",
"p",
"in",
"self",
".",
"properties",
":",
"j",
"[",
"p",
"]",
"=",
"getattr",
"(",
"self",
",",
"p",
")",
"return",
"j"
] | 37.636364 | 20.636364 |
def _parse(self, source, name, filename):
"""Internal parsing function used by `parse` and `compile`."""
return Parser(self, source, name, _encode_filename(filename)).parse() | [
"def",
"_parse",
"(",
"self",
",",
"source",
",",
"name",
",",
"filename",
")",
":",
"return",
"Parser",
"(",
"self",
",",
"source",
",",
"name",
",",
"_encode_filename",
"(",
"filename",
")",
")",
".",
"parse",
"(",
")"
] | 62.666667 | 12.666667 |
def append_rows(self, rows, between, refresh_presision):
"""Transform the rows of data to Measurements.
Keyword arguments:
rows -- an array of arrays [datetime, integral_measurement]
between -- time between integral_measurements in seconds
refresh_presision -- time between sensor values that compose the ... | [
"def",
"append_rows",
"(",
"self",
",",
"rows",
",",
"between",
",",
"refresh_presision",
")",
":",
"for",
"r",
"in",
"rows",
":",
"Measurement",
".",
"register_or_check",
"(",
"finish",
"=",
"r",
"[",
"0",
"]",
",",
"mean",
"=",
"r",
"[",
"1",
"]",
... | 49.5 | 28.7 |
def migrate(action):
" Migration utils [create, run, undo, redo]. "
from flaskext.evolution import Evolution
from flask import current_app
evolution = Evolution(current_app)
evolution.manager(action) | [
"def",
"migrate",
"(",
"action",
")",
":",
"from",
"flaskext",
".",
"evolution",
"import",
"Evolution",
"from",
"flask",
"import",
"current_app",
"evolution",
"=",
"Evolution",
"(",
"current_app",
")",
"evolution",
".",
"manager",
"(",
"action",
")"
] | 35.666667 | 9 |
def cmd_delete(args):
"""Deletes a node"""
major = args.get(0)
minor = args.get(1)
if major is not None:
if major in penStore.data:
if minor is None:
if len(penStore.data[major]) > 0:
if raw_input("are you sure (y/n)? ") not in ['y', 'Y', 'yes', 'Y... | [
"def",
"cmd_delete",
"(",
"args",
")",
":",
"major",
"=",
"args",
".",
"get",
"(",
"0",
")",
"minor",
"=",
"args",
".",
"get",
"(",
"1",
")",
"if",
"major",
"is",
"not",
"None",
":",
"if",
"major",
"in",
"penStore",
".",
"data",
":",
"if",
"min... | 35.961538 | 15.346154 |
def total_sparse_pixels_from_mask(mask, unmasked_sparse_grid_pixel_centres):
"""Given the full (i.e. without removing pixels which are outside the regular-masks) pixelization grid's pixel centers
and the regular-masks, compute the total number of pixels which are within the regular-masks and thus used by the
... | [
"def",
"total_sparse_pixels_from_mask",
"(",
"mask",
",",
"unmasked_sparse_grid_pixel_centres",
")",
":",
"total_sparse_pixels",
"=",
"0",
"for",
"unmasked_sparse_pixel_index",
"in",
"range",
"(",
"unmasked_sparse_grid_pixel_centres",
".",
"shape",
"[",
"0",
"]",
")",
"... | 39.333333 | 27.791667 |
def get_pushes(self, project, **params):
"""
Gets pushes from project, filtered by parameters
By default this method will just return the latest 10 pushes (if they exist)
:param project: project (repository name) to query data for
:param params: keyword arguments to filter resu... | [
"def",
"get_pushes",
"(",
"self",
",",
"project",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"_get_json_list",
"(",
"self",
".",
"PUSH_ENDPOINT",
",",
"project",
",",
"*",
"*",
"params",
")"
] | 40 | 21.8 |
def submarine(space, smooth=True, taper=20.0):
"""Return a 'submarine' phantom consisting in an ellipsoid and a box.
Parameters
----------
space : `DiscreteLp`
Discretized space in which the phantom is supposed to be created.
smooth : bool, optional
If ``True``, the boundaries are s... | [
"def",
"submarine",
"(",
"space",
",",
"smooth",
"=",
"True",
",",
"taper",
"=",
"20.0",
")",
":",
"if",
"space",
".",
"ndim",
"==",
"2",
":",
"if",
"smooth",
":",
"return",
"_submarine_2d_smooth",
"(",
"space",
",",
"taper",
")",
"else",
":",
"retur... | 34.222222 | 19.259259 |
def run(self, args):
"""
Process command line arguments and run the given command command
(start, stop, restart).
"""
prog = args[0]
if len(args) < 2:
self.usage(prog)
return 1
command = args[1]
if command == "start":
s... | [
"def",
"run",
"(",
"self",
",",
"args",
")",
":",
"prog",
"=",
"args",
"[",
"0",
"]",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"self",
".",
"usage",
"(",
"prog",
")",
"return",
"1",
"command",
"=",
"args",
"[",
"1",
"]",
"if",
"command",... | 24.136364 | 16.136364 |
def from_xml(self,xmlnode):
"""Initialize Delay object from an XML node.
:Parameters:
- `xmlnode`: the jabber:x:delay XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`"""
if xmlnode.type!="element":
raise ValueError("XML node is not a jabber:x:delay... | [
"def",
"from_xml",
"(",
"self",
",",
"xmlnode",
")",
":",
"if",
"xmlnode",
".",
"type",
"!=",
"\"element\"",
":",
"raise",
"ValueError",
"(",
"\"XML node is not a jabber:x:delay element (not an element)\"",
")",
"ns",
"=",
"get_node_ns_uri",
"(",
"xmlnode",
")",
"... | 39.46875 | 17.5 |
def _bprop_wrap(name, reqtype, doc):
"""
Helper function to generate properties
:param name: The name of the subfield in the JSON dictionary
:param reqtype: The compound query type the query
list should be coerced into
:param doc: Documentation for the field
:return: the property.
""... | [
"def",
"_bprop_wrap",
"(",
"name",
",",
"reqtype",
",",
"doc",
")",
":",
"def",
"fget",
"(",
"self",
")",
":",
"return",
"self",
".",
"_subqueries",
".",
"get",
"(",
"name",
")",
"def",
"fset",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
... | 31.108108 | 13.594595 |
def _loadThreePartSource(self, sourceFName, sourceLines):
"""is a helper for _loadOneSource.
"""
lineno = 1
for ln in sourceLines:
lineno += 1
try:
stem, pubType, source = ln.split("\t", 2)
stem = stem.strip()[-9:]
s... | [
"def",
"_loadThreePartSource",
"(",
"self",
",",
"sourceFName",
",",
"sourceLines",
")",
":",
"lineno",
"=",
"1",
"for",
"ln",
"in",
"sourceLines",
":",
"lineno",
"+=",
"1",
"try",
":",
"stem",
",",
"pubType",
",",
"source",
"=",
"ln",
".",
"split",
"(... | 39.571429 | 14.5 |
def latrec(radius, longitude, latitude):
"""
Convert from latitudinal coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latrec_c.html
:param radius: Distance of a point from the origin.
:type radius: float
:param longitude: Longitude of point in ra... | [
"def",
"latrec",
"(",
"radius",
",",
"longitude",
",",
"latitude",
")",
":",
"radius",
"=",
"ctypes",
".",
"c_double",
"(",
"radius",
")",
"longitude",
"=",
"ctypes",
".",
"c_double",
"(",
"longitude",
")",
"latitude",
"=",
"ctypes",
".",
"c_double",
"("... | 36.666667 | 12.47619 |
def generate(self, num_to_generate, starting_place):
"""Generate data based on some initial position."""
res = []
activ = starting_place[None, :]
index = activ.__getattribute__(self.argfunc)(1)
item = self.weights[index]
for x in range(num_to_generate):
activ ... | [
"def",
"generate",
"(",
"self",
",",
"num_to_generate",
",",
"starting_place",
")",
":",
"res",
"=",
"[",
"]",
"activ",
"=",
"starting_place",
"[",
"None",
",",
":",
"]",
"index",
"=",
"activ",
".",
"__getattribute__",
"(",
"self",
".",
"argfunc",
")",
... | 38.692308 | 13.538462 |
def get_xdg_env(env_name, fallback):
""" Used for XDG_* env variables to return fallback if unset *or* empty """
env = os.environ.get(env_name)
return env if env else fallback | [
"def",
"get_xdg_env",
"(",
"env_name",
",",
"fallback",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_name",
")",
"return",
"env",
"if",
"env",
"else",
"fallback"
] | 46 | 3.75 |
def execute(self):
"""Execute Main Loop"""
try:
logging.debug("Entering IOLoop")
self.loop.start()
logging.debug("Leaving IOLoop")
except KeyboardInterrupt:
logging.debug("Leaving IOLoop by KeyboardInterrupt")
finally:
self.hw_c... | [
"def",
"execute",
"(",
"self",
")",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"\"Entering IOLoop\"",
")",
"self",
".",
"loop",
".",
"start",
"(",
")",
"logging",
".",
"debug",
"(",
"\"Leaving IOLoop\"",
")",
"except",
"KeyboardInterrupt",
":",
"loggin... | 33.6 | 12.9 |
def tabulate(tabular_data, headers=(), tablefmt="simple",
floatfmt=_DEFAULT_FLOATFMT, numalign="decimal", stralign="left",
missingval=_DEFAULT_MISSINGVAL, showindex="default",
disable_numparse=False):
"""Format a fixed width table for pretty printing.
"""
if tabular_da... | [
"def",
"tabulate",
"(",
"tabular_data",
",",
"headers",
"=",
"(",
")",
",",
"tablefmt",
"=",
"\"simple\"",
",",
"floatfmt",
"=",
"_DEFAULT_FLOATFMT",
",",
"numalign",
"=",
"\"decimal\"",
",",
"stralign",
"=",
"\"left\"",
",",
"missingval",
"=",
"_DEFAULT_MISSI... | 45.594937 | 20.949367 |
def consume(self, routingKey, msg):
"""
Consumer for this (CaptureData) class. Gets the data sent from yieldMetricsValue and
sends it to the storage backends.
"""
build_data = msg['build_data']
builder_info = yield self.master.data.get(("builders", build_data['builderid']... | [
"def",
"consume",
"(",
"self",
",",
"routingKey",
",",
"msg",
")",
":",
"build_data",
"=",
"msg",
"[",
"'build_data'",
"]",
"builder_info",
"=",
"yield",
"self",
".",
"master",
".",
"data",
".",
"get",
"(",
"(",
"\"builders\"",
",",
"build_data",
"[",
... | 54.85 | 26.35 |
def setup(self, port):
"""Connects to an Arduino UNO on serial port `port`.
@throw RuntimeError can't connect to Arduino
"""
port = str(port)
# timeout is used by all I/O operations
self._serial = serial.Serial(port, 115200, timeout=2)
time.sleep(2) # time to Ar... | [
"def",
"setup",
"(",
"self",
",",
"port",
")",
":",
"port",
"=",
"str",
"(",
"port",
")",
"# timeout is used by all I/O operations",
"self",
".",
"_serial",
"=",
"serial",
".",
"Serial",
"(",
"port",
",",
"115200",
",",
"timeout",
"=",
"2",
")",
"time",
... | 34.47619 | 19.761905 |
def certificateOptionsFromPEMs(pemObjects, **kw):
# type: (List[AbstractPEMObject], **Any) -> ssl.CerticateOptions
"""
Load a CertificateOptions from the given collection of PEM objects
(already-loaded private keys and certificates).
In those PEM objects, identify one private key and its correspond... | [
"def",
"certificateOptionsFromPEMs",
"(",
"pemObjects",
",",
"*",
"*",
"kw",
")",
":",
"# type: (List[AbstractPEMObject], **Any) -> ssl.CerticateOptions",
"keys",
"=",
"[",
"key",
"for",
"key",
"in",
"pemObjects",
"if",
"isinstance",
"(",
"key",
",",
"Key",
")",
"... | 36 | 24.277778 |
def calc_effective_diffusivity(self, inlets=None, outlets=None,
domain_area=None, domain_length=None):
r"""
This calculates the effective diffusivity in this linear transport
algorithm.
Parameters
----------
inlets : array_like
... | [
"def",
"calc_effective_diffusivity",
"(",
"self",
",",
"inlets",
"=",
"None",
",",
"outlets",
"=",
"None",
",",
"domain_area",
"=",
"None",
",",
"domain_length",
"=",
"None",
")",
":",
"return",
"self",
".",
"_calc_eff_prop",
"(",
"inlets",
"=",
"inlets",
... | 42.135135 | 25.189189 |
def _ip_route_linux():
'''
Return ip routing information for Linux distros
(netstat is deprecated and may not be available)
'''
# table main closest to old netstat inet output
ret = []
cmd = 'ip -4 route show table main'
out = __salt__['cmd.run'](cmd, python_shell=True)
for line in o... | [
"def",
"_ip_route_linux",
"(",
")",
":",
"# table main closest to old netstat inet output",
"ret",
"=",
"[",
"]",
"cmd",
"=",
"'ip -4 route show table main'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"True",
")",
"for",
... | 30.893617 | 13.170213 |
def parse_json(target, json, create_sections = False, create_options = False):
"""Given a confmanager object and a dictionary object, import the values from the dictionary into the object, optionally adding sections and options as it goes."""
is_dict = isinstance(json, dict)
for o in json:
if is_dict:
sect... | [
"def",
"parse_json",
"(",
"target",
",",
"json",
",",
"create_sections",
"=",
"False",
",",
"create_options",
"=",
"False",
")",
":",
"is_dict",
"=",
"isinstance",
"(",
"json",
",",
"dict",
")",
"for",
"o",
"in",
"json",
":",
"if",
"is_dict",
":",
"sec... | 38.529412 | 20.117647 |
def strace_data_store_event(self, operation, address, address_range=0):
"""Sets an event to trigger trace logic when data write access is made.
Args:
self (JLink): the ``JLink`` instance.
operation (int): one of the operations in ``JLinkStraceOperation``.
address (int): th... | [
"def",
"strace_data_store_event",
"(",
"self",
",",
"operation",
",",
"address",
",",
"address_range",
"=",
"0",
")",
":",
"cmd",
"=",
"enums",
".",
"JLinkStraceCommand",
".",
"TRACE_EVENT_SET",
"event_info",
"=",
"structs",
".",
"JLinkStraceEventInfo",
"(",
")"... | 40.481481 | 21.37037 |
def __get_doc_block_lines(self):
"""
Returns the start and end line of the DOcBlock of the stored routine code.
"""
line1 = None
line2 = None
i = 0
for line in self._routine_source_code_lines:
if re.match(r'\s*/\*\*', line):
line1 = i
... | [
"def",
"__get_doc_block_lines",
"(",
"self",
")",
":",
"line1",
"=",
"None",
"line2",
"=",
"None",
"i",
"=",
"0",
"for",
"line",
"in",
"self",
".",
"_routine_source_code_lines",
":",
"if",
"re",
".",
"match",
"(",
"r'\\s*/\\*\\*'",
",",
"line",
")",
":",... | 23.571429 | 20.52381 |
def get_strain_state_dict(strains, stresses, eq_stress=None,
tol=1e-10, add_eq=True, sort=True):
"""
Creates a dictionary of voigt-notation stress-strain sets
keyed by "strain state", i. e. a tuple corresponding to
the non-zero entries in ratios to the lowest nonzero value,
... | [
"def",
"get_strain_state_dict",
"(",
"strains",
",",
"stresses",
",",
"eq_stress",
"=",
"None",
",",
"tol",
"=",
"1e-10",
",",
"add_eq",
"=",
"True",
",",
"sort",
"=",
"True",
")",
":",
"# Recast stress/strains",
"vstrains",
"=",
"np",
".",
"array",
"(",
... | 44.377049 | 17.819672 |
def update_policy(self, id, policy):
""" Create policy.
https://www.nomadproject.io/api/acl-policies.html
arguments:
- name
- policy
returns: request.Response
raises:
- nomad.api.exceptions.BaseNomadException
... | [
"def",
"update_policy",
"(",
"self",
",",
"id",
",",
"policy",
")",
":",
"return",
"self",
".",
"request",
"(",
"\"policy\"",
",",
"id",
",",
"json",
"=",
"policy",
",",
"method",
"=",
"\"post\"",
")"
] | 29.6 | 19.133333 |
def to_array(self):
"""
Serializes this InvoiceMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InvoiceMessage, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"InvoiceMessage",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'title'",
"]",
"=",
"u",
"(",
"self",
".",
"title",
")",
"# py2: type unicode, py3: type str",
"array",
"[... | 50.1 | 29.014286 |
def m2i(self, pkt, s):
"""
ASN1F_SEQUENCE behaves transparently, with nested ASN1_objects being
dissected one by one. Because we use obj.dissect (see loop below)
instead of obj.m2i (as we trust dissect to do the appropriate set_vals)
we do not directly retrieve the list of nested... | [
"def",
"m2i",
"(",
"self",
",",
"pkt",
",",
"s",
")",
":",
"diff_tag",
",",
"s",
"=",
"BER_tagging_dec",
"(",
"s",
",",
"hidden_tag",
"=",
"self",
".",
"ASN1_tag",
",",
"implicit_tag",
"=",
"self",
".",
"implicit_tag",
",",
"explicit_tag",
"=",
"self",... | 45.59375 | 16.90625 |
def from_dict(cls, data, read_only=False):
'''Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
i... | [
"def",
"from_dict",
"(",
"cls",
",",
"data",
",",
"read_only",
"=",
"False",
")",
":",
"fc",
"=",
"cls",
"(",
"read_only",
"=",
"read_only",
")",
"fc",
".",
"_features",
"=",
"{",
"}",
"fc",
".",
"_from_dict_update",
"(",
"data",
")",
"return",
"fc"
... | 37.384615 | 21.384615 |
def get_tracks(self):
"""Returns the list of Tracks on this album."""
return _extract_tracks(
self._request(self.ws_prefix + ".getInfo", cacheable=True), self.network
) | [
"def",
"get_tracks",
"(",
"self",
")",
":",
"return",
"_extract_tracks",
"(",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getInfo\"",
",",
"cacheable",
"=",
"True",
")",
",",
"self",
".",
"network",
")"
] | 33.333333 | 23.833333 |
def snapshot(domain, name=None, suffix=None, **kwargs):
'''
Create a snapshot of a VM.
:param domain: domain name
:param name: Name of the snapshot. If the name is omitted, then will be used original domain
name with ISO 8601 time as a suffix.
:param suffix: Add suffix for the new... | [
"def",
"snapshot",
"(",
"domain",
",",
"name",
"=",
"None",
",",
"suffix",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"and",
"name",
".",
"lower",
"(",
")",
"==",
"domain",
".",
"lower",
"(",
")",
":",
"raise",
"CommandExecutionE... | 32.8125 | 27.229167 |
def parse_color(v, color_range=1):
'''Receives a colour definition and returns a (r,g,b,a) tuple.
Accepts:
- v
- (v)
- (v,a)
- (r,g,b)
- (r,g,b,a)
- #RRGGBB
- RRGGBB
- #RRGGBBAA
- RRGGBBAA
Returns a (red, green, blue, alpha) tuple, with values ranging from
0 to 1.
... | [
"def",
"parse_color",
"(",
"v",
",",
"color_range",
"=",
"1",
")",
":",
"# unpack one-element tuples, they show up sometimes",
"while",
"isinstance",
"(",
"v",
",",
"(",
"tuple",
",",
"list",
")",
")",
"and",
"len",
"(",
"v",
")",
"==",
"1",
":",
"v",
"=... | 27.802817 | 18.619718 |
def point_to_line(point, segment_start, segment_end):
"""Given a point and a line segment, return the vector from the point to
the closest point on the segment.
"""
# TODO: Needs unittests.
segment_vec = segment_end - segment_start
# t is distance along line
t = -(segment_start - point).dot... | [
"def",
"point_to_line",
"(",
"point",
",",
"segment_start",
",",
"segment_end",
")",
":",
"# TODO: Needs unittests.",
"segment_vec",
"=",
"segment_end",
"-",
"segment_start",
"# t is distance along line",
"t",
"=",
"-",
"(",
"segment_start",
"-",
"point",
")",
".",
... | 35.384615 | 12.692308 |
def _iter_frequencies(self):
"""Iterate over the frequencies of this `QPlane`
"""
# work out how many frequencies we need
minf, maxf = self.frange
fcum_mismatch = log(maxf / minf) * (2 + self.q**2)**(1/2.) / 2.
nfreq = int(max(1, ceil(fcum_mismatch / self.deltam)))
... | [
"def",
"_iter_frequencies",
"(",
"self",
")",
":",
"# work out how many frequencies we need",
"minf",
",",
"maxf",
"=",
"self",
".",
"frange",
"fcum_mismatch",
"=",
"log",
"(",
"maxf",
"/",
"minf",
")",
"*",
"(",
"2",
"+",
"self",
".",
"q",
"**",
"2",
")... | 42.214286 | 10.571429 |
def get_side_length_of_resize_handle(view, item):
"""Calculate the side length of a resize handle
:param rafcon.gui.mygaphas.view.ExtendedGtkView view: View
:param rafcon.gui.mygaphas.items.state.StateView item: StateView
:return: side length
:rtype: float
"""
from rafcon.gui.mygaphas.items... | [
"def",
"get_side_length_of_resize_handle",
"(",
"view",
",",
"item",
")",
":",
"from",
"rafcon",
".",
"gui",
".",
"mygaphas",
".",
"items",
".",
"state",
"import",
"StateView",
",",
"NameView",
"if",
"isinstance",
"(",
"item",
",",
"StateView",
")",
":",
"... | 40.071429 | 18.214286 |
def annual_event_counts(kind='all'):
"""
Returns a QuerySet of dicts, each one with these keys:
* year - a date object representing the year
* total - the number of events of `kind` that year
kind - The Event `kind`, or 'all' for all kinds (default).
"""
qs = Event.objects
if ... | [
"def",
"annual_event_counts",
"(",
"kind",
"=",
"'all'",
")",
":",
"qs",
"=",
"Event",
".",
"objects",
"if",
"kind",
"!=",
"'all'",
":",
"qs",
"=",
"qs",
".",
"filter",
"(",
"kind",
"=",
"kind",
")",
"qs",
"=",
"qs",
".",
"annotate",
"(",
"year",
... | 25.75 | 18.75 |
async def kick(self, user_id: base.Integer,
until_date: typing.Union[base.Integer, None] = None):
"""
Use this method to kick a user from a group, a supergroup or a channel.
In the case of supergroups and channels, the user will not be able to return to the group
on th... | [
"async",
"def",
"kick",
"(",
"self",
",",
"user_id",
":",
"base",
".",
"Integer",
",",
"until_date",
":",
"typing",
".",
"Union",
"[",
"base",
".",
"Integer",
",",
"None",
"]",
"=",
"None",
")",
":",
"return",
"await",
"self",
".",
"bot",
".",
"kic... | 53.304348 | 30.608696 |
def _GenerateNonImplementedMethod(self, method):
"""Generates and returns a method that can be set for a service methods.
Args:
method: Descriptor of the service method for which a method is to be
generated.
Returns:
A method that can be added to the service class.
"""
return l... | [
"def",
"_GenerateNonImplementedMethod",
"(",
"self",
",",
"method",
")",
":",
"return",
"lambda",
"inst",
",",
"rpc_controller",
",",
"request",
",",
"callback",
":",
"(",
"self",
".",
"_NonImplementedMethod",
"(",
"method",
".",
"name",
",",
"rpc_controller",
... | 36 | 22.583333 |
def num_cols(x):
"""Returns number of cols in a given `Tensor`."""
if tf.compat.dimension_value(x.shape[-1]) is not None:
return tf.compat.dimension_value(x.shape[-1])
return tf.shape(input=x)[-1] | [
"def",
"num_cols",
"(",
"x",
")",
":",
"if",
"tf",
".",
"compat",
".",
"dimension_value",
"(",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
")",
"is",
"not",
"None",
":",
"return",
"tf",
".",
"compat",
".",
"dimension_value",
"(",
"x",
".",
"shape",
"[... | 40.4 | 11.8 |
def denoise(data, pon, work_dir):
"""Normalize read counts using panel of normal background or GC/mappability
"""
std_file = os.path.join(work_dir, "%s-crstandardized.tsv" % dd.get_sample_name(data))
denoise_file = os.path.join(work_dir, "%s-crdenoised.tsv" % dd.get_sample_name(data))
if not utils.f... | [
"def",
"denoise",
"(",
"data",
",",
"pon",
",",
"work_dir",
")",
":",
"std_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-crstandardized.tsv\"",
"%",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
")",
"denoise_file",
"=",
"os",... | 57.941176 | 23.705882 |
def setSparseOutput(outputs, name, value):
"""
Set region sparse output value.
The region output memory is owned by the c++ caller and cannot be changed
directly from python. Use this method to update the sparse output fields in
the "outputs" array so it can be resized from the c++ code.
:... | [
"def",
"setSparseOutput",
"(",
"outputs",
",",
"name",
",",
"value",
")",
":",
"# The region output memory is owned by the c++ and cannot be changed from",
"# python. We use a special attribule named \"__{name}_len__\" to pass",
"# the sparse array length back to c++",
"lenAttr",
"=",
... | 44.137931 | 20.827586 |
def merge_dict(to_update: dict, other_dict: dict):
""" merges b into a """
for key, value in other_dict.items():
has_map = (
isinstance(value, collections.Mapping) and
isinstance(to_update.get(key, None), collections.Mapping)
)
if has_map:
merge_dict(... | [
"def",
"merge_dict",
"(",
"to_update",
":",
"dict",
",",
"other_dict",
":",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"other_dict",
".",
"items",
"(",
")",
":",
"has_map",
"=",
"(",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Mappin... | 31.666667 | 17.083333 |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the ProtocolVersion struct and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"ProtocolVersion",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_version",
... | 38.772727 | 23.545455 |
def get_all(self, include_archived=False):
"""Get all the conversations.
Args:
include_archived (bool): (optional) Whether to include archived
conversations. Defaults to ``False``.
Returns:
List of all :class:`.Conversation` objects.
"""
... | [
"def",
"get_all",
"(",
"self",
",",
"include_archived",
"=",
"False",
")",
":",
"return",
"[",
"conv",
"for",
"conv",
"in",
"self",
".",
"_conv_dict",
".",
"values",
"(",
")",
"if",
"not",
"conv",
".",
"is_archived",
"or",
"include_archived",
"]"
] | 34.916667 | 19.416667 |
def pprint(self, index=False, delimiter='-'):
"""Pretty-print the binary tree.
:param index: If set to True (default: False), display level-order_
indexes using the format: ``{index}{delimiter}{value}``.
:type index: bool
:param delimiter: Delimiter character between the nod... | [
"def",
"pprint",
"(",
"self",
",",
"index",
"=",
"False",
",",
"delimiter",
"=",
"'-'",
")",
":",
"lines",
"=",
"_build_tree_string",
"(",
"self",
",",
"0",
",",
"index",
",",
"delimiter",
")",
"[",
"0",
"]",
"print",
"(",
"'\\n'",
"+",
"'\\n'",
".... | 33 | 21.957447 |
def inv_slots_preferred(self):
"""
List of all available inventory slots in the preferred search order.
Does not include the additional slots from the open window.
1. active slot
2. remainder of the hotbar
3. remainder of the persistent inventory
"""
slot... | [
"def",
"inv_slots_preferred",
"(",
"self",
")",
":",
"slots",
"=",
"[",
"self",
".",
"active_slot",
"]",
"slots",
".",
"extend",
"(",
"slot",
"for",
"slot",
"in",
"self",
".",
"window",
".",
"hotbar_slots",
"if",
"slot",
"!=",
"self",
".",
"active_slot",... | 36.642857 | 15.071429 |
def log_analyzer(path):
"""This procedure replaces every line which can't be parsed
with special object MalformedLogEntry.
"""
with handle(MalformedLogEntryError,
lambda (c):
invoke_restart('use_value',
MalformedLogEntry(c.text... | [
"def",
"log_analyzer",
"(",
"path",
")",
":",
"with",
"handle",
"(",
"MalformedLogEntryError",
",",
"lambda",
"(",
"c",
")",
":",
"invoke_restart",
"(",
"'use_value'",
",",
"MalformedLogEntry",
"(",
"c",
".",
"text",
")",
")",
")",
":",
"for",
"filename",
... | 39.4 | 7.6 |
def sample_indexes(segyfile, t0=0.0, dt_override=None):
"""
Creates a list of values representing the samples in a trace at depth or time.
The list starts at *t0* and is incremented with am*dt* for the number of samples.
If a *dt_override* is not provided it will try to find a *dt* in the file.
Pa... | [
"def",
"sample_indexes",
"(",
"segyfile",
",",
"t0",
"=",
"0.0",
",",
"dt_override",
"=",
"None",
")",
":",
"if",
"dt_override",
"is",
"None",
":",
"dt_override",
"=",
"dt",
"(",
"segyfile",
")",
"return",
"[",
"t0",
"+",
"t",
"*",
"dt_override",
"for"... | 24.821429 | 25.535714 |
def files_write(self, path, file, offset=0, create=False, truncate=False,
count=None, **kwargs):
"""Writes to a mutable file in the MFS.
.. code-block:: python
>>> c.files_write("/test/file", io.BytesIO(b"hi"), create=True)
b''
Parameters
--... | [
"def",
"files_write",
"(",
"self",
",",
"path",
",",
"file",
",",
"offset",
"=",
"0",
",",
"create",
"=",
"False",
",",
"truncate",
"=",
"False",
",",
"count",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"opts",
"=",
"{",
"\"offset\"",
":",
"... | 35.545455 | 20.030303 |
def reconfigure_log_level(self):
"""
Returns a new standard logger instance
"""
if Global.LOGGER:
Global.LOGGER.debug('reconfiguring logger level')
stream_handlers = filter(lambda x: type(x) is logging.StreamHandler,
self._logger_insta... | [
"def",
"reconfigure_log_level",
"(",
"self",
")",
":",
"if",
"Global",
".",
"LOGGER",
":",
"Global",
".",
"LOGGER",
".",
"debug",
"(",
"'reconfiguring logger level'",
")",
"stream_handlers",
"=",
"filter",
"(",
"lambda",
"x",
":",
"type",
"(",
"x",
")",
"i... | 34.153846 | 16.769231 |
def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width | [
"def",
"_set_tab_width",
"(",
"self",
",",
"tab_width",
")",
":",
"font_metrics",
"=",
"QtGui",
".",
"QFontMetrics",
"(",
"self",
".",
"font",
")",
"self",
".",
"_control",
".",
"setTabStopWidth",
"(",
"tab_width",
"*",
"font_metrics",
".",
"width",
"(",
"... | 40.714286 | 13.571429 |
def limit(self, limit):
"""
Sets the limit of this ListEmployeeWagesRequest.
Maximum number of Employee Wages to return per page. Can range between 1 and 200. The default is the maximum at 200.
:param limit: The limit of this ListEmployeeWagesRequest.
:type: int
"""
... | [
"def",
"limit",
"(",
"self",
",",
"limit",
")",
":",
"if",
"limit",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `limit`, must not be `None`\"",
")",
"if",
"limit",
">",
"200",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `limit`, m... | 40.352941 | 30 |
def config_control(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument
'''
Will check if the configuration was changed.
If differences found, will try to commit.
In case commit unsuccessful, will try to rollback.
:return: A tuple with a boolean that specifies if the config wa... | [
"def",
"config_control",
"(",
"inherit_napalm_device",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"result",
"=",
"True",
"comment",
"=",
"''",
"changed",
",",
"not_changed_rsn",
"=",
"config_changed",
"(",
"inherit_napalm_de... | 32.564103 | 26.153846 |
def library(repo):
"""Load packages from slpkg library and from local
"""
pkg_list, packages = [], ""
if repo == "sbo":
if (os.path.isfile(
_meta_.lib_path + "{0}_repo/SLACKBUILDS.TXT".format(repo))):
packages = Utils().read_file(_meta_.lib_path + "{0}_repo/"
... | [
"def",
"library",
"(",
"repo",
")",
":",
"pkg_list",
",",
"packages",
"=",
"[",
"]",
",",
"\"\"",
"if",
"repo",
"==",
"\"sbo\"",
":",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"_meta_",
".",
"lib_path",
"+",
"\"{0}_repo/SLACKBUILDS.TXT\"",
".",... | 42.291667 | 17.166667 |
def deltafmt(delta, decimals = None):
"""
Returns a human readable representation of a time with the format:
[[[Ih]Jm]K[.L]s
For example: 6h5m23s
If "decimals" is specified, the seconds will be output with that many decimal places.
If not, there will be two places for times less than 1 minute, one place for ... | [
"def",
"deltafmt",
"(",
"delta",
",",
"decimals",
"=",
"None",
")",
":",
"try",
":",
"delta",
"=",
"float",
"(",
"delta",
")",
"except",
":",
"return",
"'(bad delta: %s)'",
"%",
"(",
"str",
"(",
"delta",
")",
",",
")",
"if",
"delta",
"<",
"60",
":"... | 30.147059 | 20.970588 |
def transfer_session_cookies_to_driver(self, domain=None):
"""Copies the Session's cookies into the webdriver
Using the 'domain' parameter we choose the cookies we wish to transfer, we only
transfer the cookies which belong to that domain. The domain defaults to our last visited
site if... | [
"def",
"transfer_session_cookies_to_driver",
"(",
"self",
",",
"domain",
"=",
"None",
")",
":",
"if",
"not",
"domain",
"and",
"self",
".",
"_last_requests_url",
":",
"domain",
"=",
"tldextract",
".",
"extract",
"(",
"self",
".",
"_last_requests_url",
")",
".",... | 57.705882 | 30.705882 |
def update_stats_history(self):
"""Update stats history."""
# If the plugin data is a dict, the dict's key should be used
if self.get_key() is None:
item_name = ''
else:
item_name = self.get_key()
# Build the history
if self.get_export() and self.h... | [
"def",
"update_stats_history",
"(",
"self",
")",
":",
"# If the plugin data is a dict, the dict's key should be used",
"if",
"self",
".",
"get_key",
"(",
")",
"is",
"None",
":",
"item_name",
"=",
"''",
"else",
":",
"item_name",
"=",
"self",
".",
"get_key",
"(",
... | 49.962963 | 17.407407 |
def index():
""" Display productpage with normal user and test user buttons"""
global productpage
table = json2html.convert(json = json.dumps(productpage),
table_attributes="class=\"table table-condensed table-bordered table-hover\"")
return render_template('index.html', ... | [
"def",
"index",
"(",
")",
":",
"global",
"productpage",
"table",
"=",
"json2html",
".",
"convert",
"(",
"json",
"=",
"json",
".",
"dumps",
"(",
"productpage",
")",
",",
"table_attributes",
"=",
"\"class=\\\"table table-condensed table-bordered table-hover\\\"\"",
")... | 41.5 | 29.375 |
def CompileReport(self, mediator):
"""Compiles an analysis report.
Args:
mediator (AnalysisMediator): mediates interactions between
analysis plugins and other components, such as storage and dfvfs.
Returns:
AnalysisReport: analysis report.
"""
report_text = [
'Session... | [
"def",
"CompileReport",
"(",
"self",
",",
"mediator",
")",
":",
"report_text",
"=",
"[",
"'Sessionize plugin identified {0:d} sessions and '",
"'applied {1:d} tags.'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_events_per_session",
")",
",",
"self",
".",
"_numbe... | 38.789474 | 19.631579 |
def current_iteration(self):
"""Get the index of the current iteration.
Returns
-------
cur_iter : int
The index of the current iteration.
"""
out_cur_iter = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetCurrentIteration(
self.handle,
... | [
"def",
"current_iteration",
"(",
"self",
")",
":",
"out_cur_iter",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"_safe_call",
"(",
"_LIB",
".",
"LGBM_BoosterGetCurrentIteration",
"(",
"self",
".",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"out_cur_iter",
")... | 29.153846 | 12.923077 |
def write_h5ad(
self,
filename: Optional[PathLike] = None,
compression: Optional[str] = None,
compression_opts: Union[int, Any] = None,
force_dense: Optional[bool] = None
):
"""Write ``.h5ad``-formatted hdf5 file.
.. note::
Setting compression to... | [
"def",
"write_h5ad",
"(",
"self",
",",
"filename",
":",
"Optional",
"[",
"PathLike",
"]",
"=",
"None",
",",
"compression",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"compression_opts",
":",
"Union",
"[",
"int",
",",
"Any",
"]",
"=",
"None",
... | 35.469388 | 20.326531 |
def create_new_account(data_dir, password, **geth_kwargs):
"""Creates a new Ethereum account on geth.
This is useful for testing when you want to stress
interaction (transfers) between Ethereum accounts.
This command communicates with ``geth`` command over
terminal interaction. It creates keystore... | [
"def",
"create_new_account",
"(",
"data_dir",
",",
"password",
",",
"*",
"*",
"geth_kwargs",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"password",
")",
":",
"geth_kwargs",
"[",
"'password'",
"]",
"=",
"password",
"command",
",",
"proc",
"=",... | 31.722222 | 22.222222 |
def owner_search_fields(self):
"""
Returns all the fields that are CharFields except for password from the
User model. For the built-in User model, that means username,
first_name, last_name, and email.
"""
try:
from django.contrib.auth import get_user_model
... | [
"def",
"owner_search_fields",
"(",
"self",
")",
":",
"try",
":",
"from",
"django",
".",
"contrib",
".",
"auth",
"import",
"get_user_model",
"except",
"ImportError",
":",
"# Django < 1.5",
"from",
"django",
".",
"contrib",
".",
"auth",
".",
"models",
"import",
... | 38.4375 | 17.6875 |
def filter(self, scored_list):
'''
Filtering with top-n ranking.
Args:
scored_list: The list of scoring.
Retruns:
The list of filtered result.
'''
top_n_key = -1 * self.top_n
top_n_list = sorted(scored_list, key=lambda x: x[1])[top_n_... | [
"def",
"filter",
"(",
"self",
",",
"scored_list",
")",
":",
"top_n_key",
"=",
"-",
"1",
"*",
"self",
".",
"top_n",
"top_n_list",
"=",
"sorted",
"(",
"scored_list",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
")",
"[",
"top_n_key",
":",... | 26.6 | 21.4 |
def state_id_generator(size=STATE_ID_LENGTH, chars=string.ascii_uppercase, used_state_ids=None):
""" Create a new and unique state id
Generates an id for a state. It randomly samples from random ascii uppercase letters size times
and concatenates them. If the id already exists it draws a new one.
:par... | [
"def",
"state_id_generator",
"(",
"size",
"=",
"STATE_ID_LENGTH",
",",
"chars",
"=",
"string",
".",
"ascii_uppercase",
",",
"used_state_ids",
"=",
"None",
")",
":",
"new_state_id",
"=",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"chars",
")",
"f... | 47.6875 | 26.875 |
def build_attrs(self, *args, **kwargs):
"""Add select2's tag attributes."""
self.attrs.setdefault('data-minimum-input-length', 1)
self.attrs.setdefault('data-tags', 'true')
self.attrs.setdefault('data-token-separators', '[",", " "]')
return super(Select2TagMixin, self).build_attr... | [
"def",
"build_attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"attrs",
".",
"setdefault",
"(",
"'data-minimum-input-length'",
",",
"1",
")",
"self",
".",
"attrs",
".",
"setdefault",
"(",
"'data-tags'",
",",
"'true'"... | 55.5 | 15.333333 |
def multi_packages(self, logins=None, platform=None, package_type=None,
type_=None, access=None):
"""Return the private packages for a given set of usernames/logins."""
logger.debug('')
method = self._multi_packages
new_client = True
try:
# Onl... | [
"def",
"multi_packages",
"(",
"self",
",",
"logins",
"=",
"None",
",",
"platform",
"=",
"None",
",",
"package_type",
"=",
"None",
",",
"type_",
"=",
"None",
",",
"access",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"''",
")",
"method",
"=",
... | 43.333333 | 19.777778 |
async def get_eventhub_info_async(self):
"""
Get details on the specified EventHub async.
:rtype: dict
"""
alt_creds = {
"username": self._auth_config.get("iot_username"),
"password":self._auth_config.get("iot_password")}
try:
mgmt_aut... | [
"async",
"def",
"get_eventhub_info_async",
"(",
"self",
")",
":",
"alt_creds",
"=",
"{",
"\"username\"",
":",
"self",
".",
"_auth_config",
".",
"get",
"(",
"\"iot_username\"",
")",
",",
"\"password\"",
":",
"self",
".",
"_auth_config",
".",
"get",
"(",
"\"io... | 45.548387 | 20 |
def camelcase_to_lowercase(camelcase_input, python_input=None):
'''
a function to recursively convert data with camelcase key names into lowercase keys
:param camelcase_input: list or dictionary with camelcase keys
:param python_input: [optional] list or dictionary with default lower... | [
"def",
"camelcase_to_lowercase",
"(",
"camelcase_input",
",",
"python_input",
"=",
"None",
")",
":",
"if",
"python_input",
":",
"if",
"camelcase_input",
".",
"__class__",
"!=",
"python_input",
".",
"__class__",
":",
"raise",
"ValueError",
"(",
"'python_input type %s... | 46.263158 | 30.578947 |
def cluster(self, algorithm=None):
"""Cluster the codebook. The clusters of the data instances can be
assigned based on the BMUs. The method populates the class variable
Somoclu.clusters. If viewing methods are called after clustering, but
without colors for best matching units, colors w... | [
"def",
"cluster",
"(",
"self",
",",
"algorithm",
"=",
"None",
")",
":",
"import",
"sklearn",
".",
"base",
"if",
"algorithm",
"is",
"None",
":",
"import",
"sklearn",
".",
"cluster",
"algorithm",
"=",
"sklearn",
".",
"cluster",
".",
"KMeans",
"(",
")",
"... | 51.115385 | 19.846154 |
def move_into(self, destination_folder):
# type: (Folder) -> None
"""Move the Folder into a different folder.
This makes the Folder provided a child folder of the destination_folder.
Raises:
AuthError: Raised if Outlook returns a 401, generally caused by an invalid or expir... | [
"def",
"move_into",
"(",
"self",
",",
"destination_folder",
")",
":",
"# type: (Folder) -> None",
"headers",
"=",
"self",
".",
"headers",
"endpoint",
"=",
"'https://outlook.office.com/api/v2.0/me/MailFolders/'",
"+",
"self",
".",
"id",
"+",
"'/move'",
"payload",
"=",
... | 38.153846 | 28.769231 |
def list(payment):
"""
List all the refunds for a payment.
:param payment: The payment object or the payment id
:type payment: resources.Payment|string
:return: A collection of refunds
:rtype resources.APIResourceCollection
"""
if isinstance(payment, res... | [
"def",
"list",
"(",
"payment",
")",
":",
"if",
"isinstance",
"(",
"payment",
",",
"resources",
".",
"Payment",
")",
":",
"payment",
"=",
"payment",
".",
"id",
"http_client",
"=",
"HttpClient",
"(",
")",
"response",
",",
"_",
"=",
"http_client",
".",
"g... | 35.0625 | 18.1875 |
def _ep_need_close(self):
"""Peer has closed its end of the session."""
LOG.debug("Session %s close requested - closing...",
self._name)
links = self._links.copy() # may modify _links
for link in links:
link._session_closed() | [
"def",
"_ep_need_close",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Session %s close requested - closing...\"",
",",
"self",
".",
"_name",
")",
"links",
"=",
"self",
".",
"_links",
".",
"copy",
"(",
")",
"# may modify _links",
"for",
"link",
"in",
"... | 40.285714 | 11.571429 |
def save(self, content):
"""
Save any given content to the instance file.
:param content: (str or bytes)
:return: (None)
"""
# backup existing file if needed
if os.path.exists(self.file_path) and not self.assume_yes:
message = "Overwrite existing {}? (... | [
"def",
"save",
"(",
"self",
",",
"content",
")",
":",
"# backup existing file if needed",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file_path",
")",
"and",
"not",
"self",
".",
"assume_yes",
":",
"message",
"=",
"\"Overwrite existing {}? (y/n) ... | 35.631579 | 11.947368 |
def _outliers(self,x):
"""
Compute number of outliers
"""
outliers = self._tukey(x, threshold = 1.5)
return np.size(outliers) | [
"def",
"_outliers",
"(",
"self",
",",
"x",
")",
":",
"outliers",
"=",
"self",
".",
"_tukey",
"(",
"x",
",",
"threshold",
"=",
"1.5",
")",
"return",
"np",
".",
"size",
"(",
"outliers",
")"
] | 26.666667 | 7 |
def mtf_bitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_bitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.encoder_layers = [
"self_att", "local_self_att", "moe_1d", "moe_... | [
"def",
"mtf_bitransformer_all_layers_tiny",
"(",
")",
":",
"hparams",
"=",
"mtf_bitransformer_tiny",
"(",
")",
"hparams",
".",
"moe_num_experts",
"=",
"4",
"hparams",
".",
"moe_expert_x",
"=",
"4",
"hparams",
".",
"moe_expert_y",
"=",
"4",
"hparams",
".",
"moe_h... | 36.666667 | 12.916667 |
def rvalues(self):
"""
in reversed order
"""
tmp = self
while tmp is not None:
yield tmp.data
tmp = tmp.prev | [
"def",
"rvalues",
"(",
"self",
")",
":",
"tmp",
"=",
"self",
"while",
"tmp",
"is",
"not",
"None",
":",
"yield",
"tmp",
".",
"data",
"tmp",
"=",
"tmp",
".",
"prev"
] | 20.75 | 12.125 |
def read_cache(self):
"""Reads the cached contents into memory.
"""
if os.path.exists(self._cache_file):
self._cache = _read_cache_file(self._cache_file)
else:
self._cache = {} | [
"def",
"read_cache",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_file",
")",
":",
"self",
".",
"_cache",
"=",
"_read_cache_file",
"(",
"self",
".",
"_cache_file",
")",
"else",
":",
"self",
".",
"_cache",
"... | 32.285714 | 11.714286 |
def reweight(self, weight, edges=None, copy=False):
'''Replaces existing edge weights. weight may be a scalar or 1d array.
edges is a mask or index array that specifies a subset of edges to modify'''
if not self.is_weighted():
warnings.warn('Cannot supply weights for unweighted graph; '
... | [
"def",
"reweight",
"(",
"self",
",",
"weight",
",",
"edges",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"is_weighted",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"'Cannot supply weights for unweighted graph; '",
"'ignoring ... | 49.727273 | 20.272727 |
def add_library(self, name):
"""Add a library to the database
This method is for adding a library by name (eg: "BuiltIn")
rather than by a file.
"""
libdoc = LibraryDocumentation(name)
if len(libdoc.keywords) > 0:
# FIXME: figure out the path to the library f... | [
"def",
"add_library",
"(",
"self",
",",
"name",
")",
":",
"libdoc",
"=",
"LibraryDocumentation",
"(",
"name",
")",
"if",
"len",
"(",
"libdoc",
".",
"keywords",
")",
">",
"0",
":",
"# FIXME: figure out the path to the library file",
"collection_id",
"=",
"self",
... | 48.285714 | 19.785714 |
def intersection(self, other):
""" Calculates the intersection of the two underlying bitarrays and returns
a new bloom filter object."""
if self.capacity != other.capacity or \
self.error_rate != other.error_rate:
raise ValueError("Intersecting filters requires both filte... | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"capacity",
"!=",
"other",
".",
"capacity",
"or",
"self",
".",
"error_rate",
"!=",
"other",
".",
"error_rate",
":",
"raise",
"ValueError",
"(",
"\"Intersecting filters requires both... | 47.7 | 11.5 |
def get_agents(self, addr=True, agent_cls=None, as_coro=False):
"""Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
de... | [
"def",
"get_agents",
"(",
"self",
",",
"addr",
"=",
"True",
",",
"agent_cls",
"=",
"None",
",",
"as_coro",
"=",
"False",
")",
":",
"return",
"self",
".",
"env",
".",
"get_agents",
"(",
"addr",
"=",
"addr",
",",
"agent_cls",
"=",
"agent_cls",
")"
] | 44 | 20.444444 |
def encode_offset_fetch_request(cls, group, payloads, from_kafka=False):
"""
Encode an OffsetFetchRequest struct. The request is encoded using
version 0 if from_kafka is false, indicating a request for Zookeeper
offsets. It is encoded using version 1 otherwise, indicating a request
... | [
"def",
"encode_offset_fetch_request",
"(",
"cls",
",",
"group",
",",
"payloads",
",",
"from_kafka",
"=",
"False",
")",
":",
"version",
"=",
"1",
"if",
"from_kafka",
"else",
"0",
"return",
"kafka",
".",
"protocol",
".",
"commit",
".",
"OffsetFetchRequest",
"[... | 47.157895 | 22.842105 |
def _save(self):
""" save a JSON file representation of Tetrad Class for checkpoint"""
## save each attribute as dict
fulldict = copy.deepcopy(self.__dict__)
for i, j in fulldict.items():
if isinstance(j, Params):
fulldict[i] = j.__dict__
fulldumps = ... | [
"def",
"_save",
"(",
"self",
")",
":",
"## save each attribute as dict",
"fulldict",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"__dict__",
")",
"for",
"i",
",",
"j",
"in",
"fulldict",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"j",
","... | 35.37931 | 13.137931 |
def AddKeys(self, key_list):
"""Mark additional columns as being part of the superkey.
Supplements the Keys already extracted from the FSM template.
Useful when adding new columns to existing tables.
Note: This will impact attempts to further 'extend' the table as the
superkey must be common bet... | [
"def",
"AddKeys",
"(",
"self",
",",
"key_list",
")",
":",
"for",
"keyname",
"in",
"key_list",
":",
"if",
"keyname",
"not",
"in",
"self",
".",
"header",
":",
"raise",
"KeyError",
"(",
"\"'%s'\"",
"%",
"keyname",
")",
"self",
".",
"_keys",
"=",
"self",
... | 40.470588 | 19.764706 |
def rectwidth(self):
"""Calculate :ref:`pysynphot-formula-rectw`.
Returns
-------
ans : float
Bandpass rectangular width.
"""
mywaveunits = self.waveunits.name
self.convert('angstroms')
wave = self.wave
thru = self.throughput
... | [
"def",
"rectwidth",
"(",
"self",
")",
":",
"mywaveunits",
"=",
"self",
".",
"waveunits",
".",
"name",
"self",
".",
"convert",
"(",
"'angstroms'",
")",
"wave",
"=",
"self",
".",
"wave",
"thru",
"=",
"self",
".",
"throughput",
"self",
".",
"convert",
"("... | 21.608696 | 18.695652 |
def _send(key, value, metric_type):
"""Send the specified value to the statsd daemon via UDP without a
direct socket connection.
:param str value: The properly formatted statsd counter value
"""
if STATSD_PREFIX:
key = '.'.join([STATSD_PREFIX, key])
try:
STATSD_SOCKET.sendto('{... | [
"def",
"_send",
"(",
"key",
",",
"value",
",",
"metric_type",
")",
":",
"if",
"STATSD_PREFIX",
":",
"key",
"=",
"'.'",
".",
"join",
"(",
"[",
"STATSD_PREFIX",
",",
"key",
"]",
")",
"try",
":",
"STATSD_SOCKET",
".",
"sendto",
"(",
"'{0}:{1}|{2}'",
".",
... | 35.25 | 16.0625 |
def save_data(self, filename=None):
"""Save data"""
if filename is None:
filename = self.filename
if filename is None:
filename = getcwd_or_home()
filename, _selfilter = getsavefilename(self, _("Save data"),
... | [
"def",
"save_data",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"getcwd_or_home",
"(",
")",
"filename",
",",
"... | 45.030303 | 16.666667 |
def get_image_tags(self):
"""
Fetches image labels (repository / tags) from Docker.
:return: A dictionary, with image name and tags as the key and the image id as value.
:rtype: dict
"""
current_images = self.images()
tags = {tag: i['Id'] for i in current_images ... | [
"def",
"get_image_tags",
"(",
"self",
")",
":",
"current_images",
"=",
"self",
".",
"images",
"(",
")",
"tags",
"=",
"{",
"tag",
":",
"i",
"[",
"'Id'",
"]",
"for",
"i",
"in",
"current_images",
"for",
"tag",
"in",
"i",
"[",
"'RepoTags'",
"]",
"}",
"... | 35.6 | 21 |
def blow_out(self, location=None):
"""
Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
Parameters... | [
"def",
"blow_out",
"(",
"self",
",",
"location",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"tip_attached",
":",
"log",
".",
"warning",
"(",
"\"Cannot 'blow out' without a tip attached.\"",
")",
"self",
".",
"move_to",
"(",
"location",
")",
"self",
"."... | 32.52381 | 22.761905 |
def aes_b64_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | [
"def",
"aes_b64_encrypt",
"(",
"value",
",",
"secret",
",",
"block_size",
"=",
"AES",
".",
"block_size",
")",
":",
"# iv = randstr(block_size * 2, rng=random)",
"iv",
"=",
"randstr",
"(",
"block_size",
"*",
"2",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"s... | 41.045455 | 17.318182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.