text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def max(self, axis=None, keepdims=False):
"""
Return the maximum of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boo... | [
"def",
"max",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"from",
"numpy",
"import",
"maximum",
"return",
"self",
".",
"_stat",
"(",
"axis",
",",
"func",
"=",
"maximum",
",",
"keepdims",
"=",
"keepdims",
")"
] | 33.8 | 15.4 |
def install(self, package):
'''Install a python package using pip'''
logger.debug('Installing ' + package)
shell.run(self.pip_path, 'install', package) | [
"def",
"install",
"(",
"self",
",",
"package",
")",
":",
"logger",
".",
"debug",
"(",
"'Installing '",
"+",
"package",
")",
"shell",
".",
"run",
"(",
"self",
".",
"pip_path",
",",
"'install'",
",",
"package",
")"
] | 34.6 | 15.8 |
def ParseOptions(cls, options, output_module):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
SetCredentials ... | [
"def",
"ParseOptions",
"(",
"cls",
",",
"options",
",",
"output_module",
")",
":",
"if",
"not",
"hasattr",
"(",
"output_module",
",",
"'SetCredentials'",
")",
":",
"raise",
"errors",
".",
"BadConfigObject",
"(",
"'Unable to set username information.'",
")",
"if",
... | 40.037037 | 21.481481 |
def describe_availability_zones(self, xml_bytes):
"""Parse the XML returned by the C{DescribeAvailibilityZones} function.
@param xml_bytes: XML bytes with a C{DescribeAvailibilityZonesResponse}
root element.
@return: a C{list} of L{AvailabilityZone}.
TODO: regionName, messa... | [
"def",
"describe_availability_zones",
"(",
"self",
",",
"xml_bytes",
")",
":",
"results",
"=",
"[",
"]",
"root",
"=",
"XML",
"(",
"xml_bytes",
")",
"for",
"zone_data",
"in",
"root",
".",
"find",
"(",
"\"availabilityZoneInfo\"",
")",
":",
"zone_name",
"=",
... | 40.125 | 18 |
def add_missing_price_information_message(request, item):
"""
Add a message to the Django messages store indicating that we failed to retrieve price information about an item.
:param request: The current request.
:param item: The item for which price information is missing. Example: a program title, or... | [
"def",
"add_missing_price_information_message",
"(",
"request",
",",
"item",
")",
":",
"messages",
".",
"warning",
"(",
"request",
",",
"_",
"(",
"'{strong_start}We could not gather price information for {em_start}{item}{em_end}.{strong_end} '",
"'{span_start}If you continue to hav... | 42.75 | 27.178571 |
def get_trend(self):
"""
Get the trend for the last two metric values using the interval defined in the metric
:return: a tuple with the metric value for the last interval and the
trend percentage between the last two intervals
"""
""" """
# TODO: We j... | [
"def",
"get_trend",
"(",
"self",
")",
":",
"\"\"\" \"\"\"",
"# TODO: We just need the last two periods, not the full ts",
"ts",
"=",
"self",
".",
"get_ts",
"(",
")",
"last",
"=",
"ts",
"[",
"'value'",
"]",
"[",
"len",
"(",
"ts",
"[",
"'value'",
"]",
")",
"-... | 31.28 | 19.12 |
async def get_contents(self, uri) -> List[Content]:
"""Request content listing recursively for the given URI.
:param uri: URI for the source.
:return: List of Content objects.
"""
contents = [
Content.make(**x)
for x in await self.services["avContent"]["g... | [
"async",
"def",
"get_contents",
"(",
"self",
",",
"uri",
")",
"->",
"List",
"[",
"Content",
"]",
":",
"contents",
"=",
"[",
"Content",
".",
"make",
"(",
"*",
"*",
"x",
")",
"for",
"x",
"in",
"await",
"self",
".",
"services",
"[",
"\"avContent\"",
"... | 36.666667 | 16.380952 |
def p_lvalue_partselect(self, p):
'lvalue : lpartselect'
p[0] = Lvalue(p[1], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_lvalue_partselect",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Lvalue",
"(",
"p",
"[",
"1",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
... | 36.5 | 7 |
def start_adc(self, channel, gain=1, data_rate=None):
"""Start continuous ADC conversions on the specified channel (0-3). Will
return an initial conversion result, then call the get_last_result()
function to read the most recent conversion result. Call stop_adc() to
stop conversions.
... | [
"def",
"start_adc",
"(",
"self",
",",
"channel",
",",
"gain",
"=",
"1",
",",
"data_rate",
"=",
"None",
")",
":",
"assert",
"0",
"<=",
"channel",
"<=",
"3",
",",
"'Channel must be a value within 0-3!'",
"# Start continuous reads and set the mux value to the channel plu... | 59.6 | 21.9 |
def qtable(columns, data, **meta):
'''Creates a QTable out of given column names and data, and initialises the
meta data.
:class:`.QTable` is represented internally by `numpy.core.records.recarray`.
Data for each column is converted to :class:`.QList` via :func:`.qlist`
function. If qtype ind... | [
"def",
"qtable",
"(",
"columns",
",",
"data",
",",
"*",
"*",
"meta",
")",
":",
"if",
"len",
"(",
"columns",
")",
"!=",
"len",
"(",
"data",
")",
":",
"raise",
"ValueError",
"(",
"'Number of columns doesn`t match the data layout. %s vs %s'",
"%",
"(",
"len",
... | 50.151163 | 33.662791 |
def explain_prediction_lightgbm(
lgb, doc,
vec=None,
top=None,
top_targets=None,
target_names=None,
targets=None,
feature_names=None,
feature_re=None,
feature_filter=None,
vectorized=False,
):
""" Return an explanation of LightG... | [
"def",
"explain_prediction_lightgbm",
"(",
"lgb",
",",
"doc",
",",
"vec",
"=",
"None",
",",
"top",
"=",
"None",
",",
"top_targets",
"=",
"None",
",",
"target_names",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"feature_names",
"=",
"None",
",",
"featu... | 36.621951 | 18.146341 |
def kmc(forward_in, database_name, min_occurrences=1, reverse_in='NA', k=31, cleanup=True,
returncmd=False, tmpdir='tmp', **kwargs):
"""
Runs kmc to count kmers.
:param forward_in: Forward input reads. Assumed to be fastq.
:param database_name: Name for output kmc database.
:param min_occurr... | [
"def",
"kmc",
"(",
"forward_in",
",",
"database_name",
",",
"min_occurrences",
"=",
"1",
",",
"reverse_in",
"=",
"'NA'",
",",
"k",
"=",
"31",
",",
"cleanup",
"=",
"True",
",",
"returncmd",
"=",
"False",
",",
"tmpdir",
"=",
"'tmp'",
",",
"*",
"*",
"kw... | 49.926829 | 21.878049 |
def parse_public(data):
"""
Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
EC public keys. For RSA keys, both the old RSAPublicKey and
SubjectPublicKeyInfo structures are supported. Also allows extracting a
public key from an X.509 certificate.
:param data:
A... | [
"def",
"parse_public",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"pretty_message",
"(",
"'''\n data must be a byte string, not %s\n '''",
",",
"type_name",
"(",
"data",
... | 33.042254 | 21.71831 |
def graph_to_dot(graph, node_renderer=None, edge_renderer=None):
"""Produces a DOT specification string from the provided graph."""
node_pairs = list(graph.nodes.items())
edge_pairs = list(graph.edges.items())
if node_renderer is None:
node_renderer_wrapper = lambda nid: ''
else:
no... | [
"def",
"graph_to_dot",
"(",
"graph",
",",
"node_renderer",
"=",
"None",
",",
"edge_renderer",
"=",
"None",
")",
":",
"node_pairs",
"=",
"list",
"(",
"graph",
".",
"nodes",
".",
"items",
"(",
")",
")",
"edge_pairs",
"=",
"list",
"(",
"graph",
".",
"edge... | 32.344828 | 18.965517 |
def _get_geneid2nt(nts):
"""Get geneid2nt given a list of namedtuples."""
geneid2nt = {}
for ntd in nts:
geneid = ntd.GeneID
if geneid not in geneid2nt:
geneid2nt[geneid] = ntd
else:
print("DUPLICATE GeneID FOUND {N:9} {SYM}".fo... | [
"def",
"_get_geneid2nt",
"(",
"nts",
")",
":",
"geneid2nt",
"=",
"{",
"}",
"for",
"ntd",
"in",
"nts",
":",
"geneid",
"=",
"ntd",
".",
"GeneID",
"if",
"geneid",
"not",
"in",
"geneid2nt",
":",
"geneid2nt",
"[",
"geneid",
"]",
"=",
"ntd",
"else",
":",
... | 36.7 | 15.3 |
def pair_is_consistent(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> Optional[str]:
"""Return if the edges between the given nodes are consistent, meaning they all have the same relation.
:return: If the edges aren't consistent, return false, otherwise return the relation type
"""
relations = {data... | [
"def",
"pair_is_consistent",
"(",
"graph",
":",
"BELGraph",
",",
"u",
":",
"BaseEntity",
",",
"v",
":",
"BaseEntity",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"relations",
"=",
"{",
"data",
"[",
"RELATION",
"]",
"for",
"data",
"in",
"graph",
"[",
... | 39 | 26.818182 |
def _get_api_params(api_url=None,
page_id=None,
api_key=None,
api_version=None):
'''
Retrieve the API params from the config file.
'''
statuspage_cfg = __salt__['config.get']('statuspage')
if not statuspage_cfg:
statuspage_cfg = {}
... | [
"def",
"_get_api_params",
"(",
"api_url",
"=",
"None",
",",
"page_id",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"api_version",
"=",
"None",
")",
":",
"statuspage_cfg",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'statuspage'",
")",
"if",
"not",
... | 40.6875 | 23.0625 |
def AnalizarAutorizarCertificadoResp(self, ret):
"Metodo interno para extraer datos de la Respuesta de Certificación"
aut = ret.get('autorizacion')
if aut:
self.PtoEmision = aut['ptoEmision']
self.NroOrden = aut['nroOrden']
self.FechaCertificacion = str(aut.ge... | [
"def",
"AnalizarAutorizarCertificadoResp",
"(",
"self",
",",
"ret",
")",
":",
"aut",
"=",
"ret",
".",
"get",
"(",
"'autorizacion'",
")",
"if",
"aut",
":",
"self",
".",
"PtoEmision",
"=",
"aut",
"[",
"'ptoEmision'",
"]",
"self",
".",
"NroOrden",
"=",
"aut... | 63.689922 | 28.356589 |
def close(self):
"""
Stop the server.
"""
logger.info("Stop server")
self.stopped.set()
for event in self.to_be_stopped:
event.set()
self._socket.close() | [
"def",
"close",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Stop server\"",
")",
"self",
".",
"stopped",
".",
"set",
"(",
")",
"for",
"event",
"in",
"self",
".",
"to_be_stopped",
":",
"event",
".",
"set",
"(",
")",
"self",
".",
"_socket",
... | 21.3 | 12.9 |
def get_submission_archive(self, submissions, sub_folders, aggregations, archive_file=None):
"""
:param submissions: a list of submissions
:param sub_folders: possible values:
[]: put all submissions in /
['taskid']: put all submissions for each task in a different direct... | [
"def",
"get_submission_archive",
"(",
"self",
",",
"submissions",
",",
"sub_folders",
",",
"aggregations",
",",
"archive_file",
"=",
"None",
")",
":",
"tmpfile",
"=",
"archive_file",
"if",
"archive_file",
"is",
"not",
"None",
"else",
"tempfile",
".",
"TemporaryF... | 54.206186 | 29.649485 |
def _check_for_more_pages(self):
"""
Check for more pages. The last item will be sliced off.
"""
self._has_more = len(self._items) > self.per_page
self._items = self._items[0 : self.per_page] | [
"def",
"_check_for_more_pages",
"(",
"self",
")",
":",
"self",
".",
"_has_more",
"=",
"len",
"(",
"self",
".",
"_items",
")",
">",
"self",
".",
"per_page",
"self",
".",
"_items",
"=",
"self",
".",
"_items",
"[",
"0",
":",
"self",
".",
"per_page",
"]"... | 32.285714 | 14.285714 |
def collapse_nodes_with_same_names(graph: BELGraph) -> None:
"""Collapse all nodes with the same name, merging namespaces by picking first alphabetical one."""
survivor_mapping = defaultdict(set) # Collapse mapping dict
victims = set() # Things already mapped while iterating
it = tqdm(itt.combinations(... | [
"def",
"collapse_nodes_with_same_names",
"(",
"graph",
":",
"BELGraph",
")",
"->",
"None",
":",
"survivor_mapping",
"=",
"defaultdict",
"(",
"set",
")",
"# Collapse mapping dict",
"victims",
"=",
"set",
"(",
")",
"# Things already mapped while iterating",
"it",
"=",
... | 38.444444 | 24.074074 |
def get(self, resource, **params):
"""
Generic TeleSign REST API GET handler.
:param resource: The partial resource URI to perform the request against, as a string.
:param params: Body params to perform the GET request with, as a dictionary.
:return: The RestClient Response obje... | [
"def",
"get",
"(",
"self",
",",
"resource",
",",
"*",
"*",
"params",
")",
":",
"return",
"self",
".",
"_execute",
"(",
"self",
".",
"session",
".",
"get",
",",
"'GET'",
",",
"resource",
",",
"*",
"*",
"params",
")"
] | 44.555556 | 21.222222 |
async def select_page(self, info: SQLQueryInfo, size=1, page=1) -> Tuple[Tuple[DataRecord, ...], int]:
"""
Select from database
:param info:
:param size: -1 means infinite
:param page:
:param need_count: if True, get count as second return value, otherwise -1
:ret... | [
"async",
"def",
"select_page",
"(",
"self",
",",
"info",
":",
"SQLQueryInfo",
",",
"size",
"=",
"1",
",",
"page",
"=",
"1",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"DataRecord",
",",
"...",
"]",
",",
"int",
"]",
":",
"raise",
"NotImplementedError",
"(... | 37.8 | 17.2 |
def _ofind(self, oname, namespaces=None):
"""Find an object in the available namespaces.
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
Has special code to detect magic functions.
"""
oname = oname.strip()
#print '1- oname: <%r>' % oname # dbg
i... | [
"def",
"_ofind",
"(",
"self",
",",
"oname",
",",
"namespaces",
"=",
"None",
")",
":",
"oname",
"=",
"oname",
".",
"strip",
"(",
")",
"#print '1- oname: <%r>' % oname # dbg",
"if",
"not",
"oname",
".",
"startswith",
"(",
"ESC_MAGIC",
")",
"and",
"not",
"on... | 42.585106 | 18.021277 |
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
from_email = email_message.from_email
recipients = email_message.recipients()
try:
self.connection.messages.create(
to=recipients,
from_=from_email,
body=email_... | [
"def",
"_send",
"(",
"self",
",",
"email_message",
")",
":",
"if",
"not",
"email_message",
".",
"recipients",
"(",
")",
":",
"return",
"False",
"from_email",
"=",
"email_message",
".",
"from_email",
"recipients",
"=",
"email_message",
".",
"recipients",
"(",
... | 24.176471 | 16.705882 |
def load(self):
"""Read the store dict from file"""
with open(self.store_file_path, 'r') as fh:
self.store = json.loads(fh.read()) | [
"def",
"load",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"store_file_path",
",",
"'r'",
")",
"as",
"fh",
":",
"self",
".",
"store",
"=",
"json",
".",
"loads",
"(",
"fh",
".",
"read",
"(",
")",
")"
] | 31 | 16.4 |
def status(gandi, service):
"""Display current status from status.gandi.net."""
if not service:
global_status = gandi.status.status()
if global_status['status'] == 'FOGGY':
# something is going on but not affecting services
filters = {
'category': 'Incide... | [
"def",
"status",
"(",
"gandi",
",",
"service",
")",
":",
"if",
"not",
"service",
":",
"global_status",
"=",
"gandi",
".",
"status",
".",
"status",
"(",
")",
"if",
"global_status",
"[",
"'status'",
"]",
"==",
"'FOGGY'",
":",
"# something is going on but not a... | 34.636364 | 16.522727 |
def body(self, frame):
""" Creates the dialog body. Returns the widget that should have
initial focus.
"""
master = Frame(self)
master.pack(padx=5, pady=0, expand=1, fill=BOTH)
title = Label(master, text="Buses")
title.pack(side=TOP)
bus_lb = self.bu... | [
"def",
"body",
"(",
"self",
",",
"frame",
")",
":",
"master",
"=",
"Frame",
"(",
"self",
")",
"master",
".",
"pack",
"(",
"padx",
"=",
"5",
",",
"pady",
"=",
"0",
",",
"expand",
"=",
"1",
",",
"fill",
"=",
"BOTH",
")",
"title",
"=",
"Label",
... | 27.952381 | 19.238095 |
def p_subind_TO(p):
""" substr : LP TO RP
"""
p[0] = (make_typecast(TYPE.uinteger,
make_number(0, lineno=p.lineno(2)),
p.lineno(1)),
make_typecast(TYPE.uinteger,
make_number(gl.MAX_STRSLICE_IDX, lineno=p.lineno(3)),
... | [
"def",
"p_subind_TO",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"make_typecast",
"(",
"TYPE",
".",
"uinteger",
",",
"make_number",
"(",
"0",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"2",
")",
")",
",",
"p",
".",
"lineno",
"(",
"1",
... | 38.777778 | 9.222222 |
def __x_google_quota_descriptor(self, metric_costs):
"""Describes the metric costs for a call.
Args:
metric_costs: Dict of metric definitions to the integer cost value against
that metric.
Returns:
A dict descriptor describing the Quota limits for the endpoint.
"""
return {
... | [
"def",
"__x_google_quota_descriptor",
"(",
"self",
",",
"metric_costs",
")",
":",
"return",
"{",
"'metricCosts'",
":",
"{",
"metric",
":",
"cost",
"for",
"(",
"metric",
",",
"cost",
")",
"in",
"metric_costs",
".",
"items",
"(",
")",
"}",
"}",
"if",
"metr... | 29.133333 | 23.4 |
def tags(self, where, archiver="", timeout=DEFAULT_TIMEOUT):
"""
Retrieves tags for all streams matching the given WHERE clause
Arguments:
[where]: the where clause (e.g. 'path like "keti"', 'SourceName = "TED Main"')
[archiver]: if specified, this is the archiver to use. Else, ... | [
"def",
"tags",
"(",
"self",
",",
"where",
",",
"archiver",
"=",
"\"\"",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"return",
"self",
".",
"query",
"(",
"\"select * where {0}\"",
".",
"format",
"(",
"where",
")",
",",
"archiver",
",",
"timeout",
")... | 54 | 30.545455 |
def pwarning(*args, **kwargs):
"""print formatted output to stderr with indentation control"""
if should_msg(kwargs.get("groups", ["warning"])):
# initialize colorama only if uninitialized
global colorama_init
if not colorama_init:
colorama_init = True
colorama.i... | [
"def",
"pwarning",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"should_msg",
"(",
"kwargs",
".",
"get",
"(",
"\"groups\"",
",",
"[",
"\"warning\"",
"]",
")",
")",
":",
"# initialize colorama only if uninitialized",
"global",
"colorama_init",
"... | 32.058824 | 14 |
def add_element(self, name, ns_uri=None, attributes=None,
text=None, before_this_element=False):
"""
Add a new child element to this element, with an optional namespace
definition. If no namespace is provided the child will be assigned
to the default namespace.
:para... | [
"def",
"add_element",
"(",
"self",
",",
"name",
",",
"ns_uri",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"text",
"=",
"None",
",",
"before_this_element",
"=",
"False",
")",
":",
"# Determine local name, namespace and prefix info from tag name",
"prefix",
"... | 49.736111 | 19.708333 |
def str2int(self, str_value):
"""Conversion class name string => integer."""
str_value = tf.compat.as_text(str_value)
if self._str2int:
return self._str2int[str_value]
# No names provided, try to integerize
failed_parse = False
try:
int_value = int(str_value)
except ValueError:
... | [
"def",
"str2int",
"(",
"self",
",",
"str_value",
")",
":",
"str_value",
"=",
"tf",
".",
"compat",
".",
"as_text",
"(",
"str_value",
")",
"if",
"self",
".",
"_str2int",
":",
"return",
"self",
".",
"_str2int",
"[",
"str_value",
"]",
"# No names provided, try... | 32.2 | 15.8 |
def UpdateHuntOutputPluginState(self, hunt_id, state_index, update_fn):
"""Updates hunt output plugin state for a given output plugin."""
if hunt_id not in self.hunts:
raise db.UnknownHuntError(hunt_id)
try:
state = rdf_flow_runner.OutputPluginState.FromSerializedString(
self.hunt_ou... | [
"def",
"UpdateHuntOutputPluginState",
"(",
"self",
",",
"hunt_id",
",",
"state_index",
",",
"update_fn",
")",
":",
"if",
"hunt_id",
"not",
"in",
"self",
".",
"hunts",
":",
"raise",
"db",
".",
"UnknownHuntError",
"(",
"hunt_id",
")",
"try",
":",
"state",
"=... | 34.166667 | 22.555556 |
def _build_brokers(self, brokers):
"""Build broker objects using broker-ids."""
for broker_id, metadata in six.iteritems(brokers):
self.brokers[broker_id] = self._create_broker(broker_id, metadata) | [
"def",
"_build_brokers",
"(",
"self",
",",
"brokers",
")",
":",
"for",
"broker_id",
",",
"metadata",
"in",
"six",
".",
"iteritems",
"(",
"brokers",
")",
":",
"self",
".",
"brokers",
"[",
"broker_id",
"]",
"=",
"self",
".",
"_create_broker",
"(",
"broker_... | 55.5 | 15.5 |
def form_invalid(self, form, prefix=None):
""" If form invalid return error list in JSON response """
response = super(FormAjaxMixin, self).form_invalid(form)
if self.request.is_ajax():
data = {
"errors_list": self.add_prefix(form.errors, prefix),
}
... | [
"def",
"form_invalid",
"(",
"self",
",",
"form",
",",
"prefix",
"=",
"None",
")",
":",
"response",
"=",
"super",
"(",
"FormAjaxMixin",
",",
"self",
")",
".",
"form_invalid",
"(",
"form",
")",
"if",
"self",
".",
"request",
".",
"is_ajax",
"(",
")",
":... | 47.6 | 19 |
def pack_int(v):
""" Returns <v> as packed string. """
if v == 0:
return "\0"
ret = ''
while v > 0:
c = v & 127
v >>= 7
if v != 0:
c = c | 128
ret += chr(c)
return ret | [
"def",
"pack_int",
"(",
"v",
")",
":",
"if",
"v",
"==",
"0",
":",
"return",
"\"\\0\"",
"ret",
"=",
"''",
"while",
"v",
">",
"0",
":",
"c",
"=",
"v",
"&",
"127",
"v",
">>=",
"7",
"if",
"v",
"!=",
"0",
":",
"c",
"=",
"c",
"|",
"128",
"ret",... | 19 | 21.083333 |
def handler(self):
'Handler function'
from feedjack import filters # shouldn't be imported globally, as they may depend on models
proc_func = getattr(filters, self.handler_name or self.name, None)
if proc_func is None:
if '.' not in self.handler_name:
raise ImportError('Processing function not available:... | [
"def",
"handler",
"(",
"self",
")",
":",
"from",
"feedjack",
"import",
"filters",
"# shouldn't be imported globally, as they may depend on models",
"proc_func",
"=",
"getattr",
"(",
"filters",
",",
"self",
".",
"handler_name",
"or",
"self",
".",
"name",
",",
"None",... | 51.8 | 29 |
def filter_aliases(alias_table):
"""
Filter aliases that does not have a command field in the configuration file.
Args:
alias_table: The alias table.
Yield:
A tuple with [0] being the first word of the alias and
[1] being the command that the alias points to.
"""
for al... | [
"def",
"filter_aliases",
"(",
"alias_table",
")",
":",
"for",
"alias",
"in",
"alias_table",
".",
"sections",
"(",
")",
":",
"if",
"alias_table",
".",
"has_option",
"(",
"alias",
",",
"'command'",
")",
":",
"yield",
"(",
"alias",
".",
"split",
"(",
")",
... | 35.071429 | 21.5 |
def check_node(self, tup_tree, nodename, required_attrs=None,
optional_attrs=None, allowed_children=None,
allow_pcdata=False):
# pylint: disable=too-many-branches
"""
Check static local constraints on a tuple tree node.
The node must have the given ... | [
"def",
"check_node",
"(",
"self",
",",
"tup_tree",
",",
"nodename",
",",
"required_attrs",
"=",
"None",
",",
"optional_attrs",
"=",
"None",
",",
"allowed_children",
"=",
"None",
",",
"allow_pcdata",
"=",
"False",
")",
":",
"# pylint: disable=too-many-branches",
... | 42.588235 | 19.576471 |
def beta(returns, factor_returns, risk_free=0.0, out=None):
"""Calculates beta.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in :func:`~empyrical.stats.cum_returns`.
factor_returns : pd.Series
Daily noncumula... | [
"def",
"beta",
"(",
"returns",
",",
"factor_returns",
",",
"risk_free",
"=",
"0.0",
",",
"out",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"returns",
",",
"np",
".",
"ndarray",
")",
"and",
"isinstance",
"(",
"factor_returns",
",",
"np"... | 32.545455 | 19.818182 |
def after_retract(analysis):
"""Function triggered after a 'retract' transition for the analysis passed
in is performed. The analysis transitions to "retracted" state and a new
copy of the analysis is created. The copy initial state is "unassigned",
unless the the retracted analysis was assigned to a wo... | [
"def",
"after_retract",
"(",
"analysis",
")",
":",
"# Retract our dependents (analyses that depend on this analysis)",
"cascade_to_dependents",
"(",
"analysis",
",",
"\"retract\"",
")",
"# Retract our dependencies (analyses this analysis depends on)",
"promote_to_dependencies",
"(",
... | 43.232558 | 19.906977 |
def system_add_keyspace(self, ks_def):
"""
adds a keyspace and any column families that are part of it. returns the new schema id.
Parameters:
- ks_def
"""
self._seqid += 1
d = self._reqs[self._seqid] = defer.Deferred()
self.send_system_add_keyspace(ks_def)
return d | [
"def",
"system_add_keyspace",
"(",
"self",
",",
"ks_def",
")",
":",
"self",
".",
"_seqid",
"+=",
"1",
"d",
"=",
"self",
".",
"_reqs",
"[",
"self",
".",
"_seqid",
"]",
"=",
"defer",
".",
"Deferred",
"(",
")",
"self",
".",
"send_system_add_keyspace",
"("... | 26.727273 | 18.545455 |
def secret_absent(name, namespace='default', **kwargs):
'''
Ensures that the named secret is absent from the given namespace.
name
The name of the secret
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
... | [
"def",
"secret_absent",
"(",
"name",
",",
"namespace",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"s... | 28.076923 | 23.512821 |
def blueprint(blueprint_name):
"""
create and register a blueprint
"""
app = os.getcwd().split('/')[-1]
if app != 'app':
logger.warning('''\033[31m{Warning}\033[0m
==> your current path is \033[32m%s\033[0m\n
==> please create your blueprint under app folder!''' % os.getcwd())
exit(1... | [
"def",
"blueprint",
"(",
"blueprint_name",
")",
":",
"app",
"=",
"os",
".",
"getcwd",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"app",
"!=",
"'app'",
":",
"logger",
".",
"warning",
"(",
"'''\\033[31m{Warning}\\033[0m\n==> your cu... | 30.735849 | 16.849057 |
def stop(self):
"""Stop the name server.
"""
self.listener.setsockopt(LINGER, 1)
self.loop = False
with nslock:
self.listener.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"listener",
".",
"setsockopt",
"(",
"LINGER",
",",
"1",
")",
"self",
".",
"loop",
"=",
"False",
"with",
"nslock",
":",
"self",
".",
"listener",
".",
"close",
"(",
")"
] | 25.571429 | 10 |
def runSearchVariantAnnotations(self, request):
"""
Runs the specified SearchVariantAnnotationsRequest.
"""
return self.runSearchRequest(
request, protocol.SearchVariantAnnotationsRequest,
protocol.SearchVariantAnnotationsResponse,
self.variantAnnotati... | [
"def",
"runSearchVariantAnnotations",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"runSearchRequest",
"(",
"request",
",",
"protocol",
".",
"SearchVariantAnnotationsRequest",
",",
"protocol",
".",
"SearchVariantAnnotationsResponse",
",",
"self",
".",... | 40.75 | 8.75 |
def variable_declaration(self):
"""
variable_declaration: 'let' assignment ';'
"""
self._process(Nature.LET)
node = VariableDeclaration(assignment=self.assignment())
self._process(Nature.SEMI)
return node | [
"def",
"variable_declaration",
"(",
"self",
")",
":",
"self",
".",
"_process",
"(",
"Nature",
".",
"LET",
")",
"node",
"=",
"VariableDeclaration",
"(",
"assignment",
"=",
"self",
".",
"assignment",
"(",
")",
")",
"self",
".",
"_process",
"(",
"Nature",
"... | 31.625 | 9.625 |
def calculate_oobatake_dS(seq, temp):
"""Get dS using Oobatake method in units cal/mol.
Args:
seq (str, Seq, SeqRecord): Amino acid sequence
temp (float): Temperature in degrees C
Returns:
float: dS in units cal/mol
"""
seq = ssbio.protein.sequence.utils.cast_to_str(seq)
... | [
"def",
"calculate_oobatake_dS",
"(",
"seq",
",",
"temp",
")",
":",
"seq",
"=",
"ssbio",
".",
"protein",
".",
"sequence",
".",
"utils",
".",
"cast_to_str",
"(",
"seq",
")",
"dS",
"=",
"0",
"temp",
"+=",
"273.15",
"T0",
"=",
"298.15",
"dCp_sum",
"=",
"... | 22.772727 | 20.136364 |
def _get_separated_values(self, secondary=False):
"""Separate values between odd and even series stacked"""
series = self.secondary_series if secondary else self.series
positive_vals = map(
sum,
zip(
*[
serie.safe_values for index, seri... | [
"def",
"_get_separated_values",
"(",
"self",
",",
"secondary",
"=",
"False",
")",
":",
"series",
"=",
"self",
".",
"secondary_series",
"if",
"secondary",
"else",
"self",
".",
"series",
"positive_vals",
"=",
"map",
"(",
"sum",
",",
"zip",
"(",
"*",
"[",
"... | 31.318182 | 20.909091 |
def read_byte(self, do_ord=True) -> int:
"""
Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred.
"""
try:
if do_ord... | [
"def",
"read_byte",
"(",
"self",
",",
"do_ord",
"=",
"True",
")",
"->",
"int",
":",
"try",
":",
"if",
"do_ord",
":",
"return",
"ord",
"(",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
")",
"else",
":",
"return",
"self",
".",
"stream",
".",
... | 34.4 | 17.333333 |
def use_comparative_assessment_taken_view(self):
"""Pass through to provider AssessmentTakenLookupSession.use_comparative_assessment_taken_view"""
self._object_views['assessment_taken'] = COMPARATIVE
# self._get_provider_session('assessment_taken_lookup_session') # To make sure the session is tr... | [
"def",
"use_comparative_assessment_taken_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'assessment_taken'",
"]",
"=",
"COMPARATIVE",
"# self._get_provider_session('assessment_taken_lookup_session') # To make sure the session is tracked",
"for",
"session",
"in",
... | 56.444444 | 20.333333 |
def add_error(cls, queue_name, job, error, when=None, trace=None,
**additional_fields):
"""
Add a new error in redis.
`job` is a job which generated the error
`queue_name` is the name of the queue where the error arrived
`er... | [
"def",
"add_error",
"(",
"cls",
",",
"queue_name",
",",
"job",
",",
"error",
",",
"when",
"=",
"None",
",",
"trace",
"=",
"None",
",",
"*",
"*",
"additional_fields",
")",
":",
"if",
"when",
"is",
"None",
":",
"when",
"=",
"datetime",
".",
"utcnow",
... | 34.212766 | 19.531915 |
def _pre_process_call(self, name="Unknown", endpoint_params=None):
"""
This is called by the method_decorator within the Endpoint.
The point is to capture a slot for the endpoint.method to put
it's final _calls.
It also allows for some special new arguments that will be extracted... | [
"def",
"_pre_process_call",
"(",
"self",
",",
"name",
"=",
"\"Unknown\"",
",",
"endpoint_params",
"=",
"None",
")",
":",
"call_temps",
"=",
"self",
".",
"_call_temps",
".",
"get",
"(",
"self",
".",
"_get_thread_id",
"(",
")",
",",
"None",
")",
"call_params... | 41.25 | 18.557692 |
def execute_policy(self, policy):
"""
Executes the specified policy for this scaling group.
"""
return self.manager.execute_policy(scaling_group=self, policy=policy) | [
"def",
"execute_policy",
"(",
"self",
",",
"policy",
")",
":",
"return",
"self",
".",
"manager",
".",
"execute_policy",
"(",
"scaling_group",
"=",
"self",
",",
"policy",
"=",
"policy",
")"
] | 38.6 | 13 |
def get_max_length(self):
"""
Return the maximum length of the pianorolls along the time axis (in
time step).
Returns
-------
max_length : int
The maximum length of the pianorolls along the time axis (in time
step).
"""
max_length... | [
"def",
"get_max_length",
"(",
"self",
")",
":",
"max_length",
"=",
"0",
"for",
"track",
"in",
"self",
".",
"tracks",
":",
"if",
"max_length",
"<",
"track",
".",
"pianoroll",
".",
"shape",
"[",
"0",
"]",
":",
"max_length",
"=",
"track",
".",
"pianoroll"... | 28 | 20.117647 |
def _buildTemplates(self):
"""
OVERRIDING THIS METHOD from Factory
"""
c_mydict = build_class_json(self.ontospy_graph.all_classes)
JSON_DATA_CLASSES = json.dumps(c_mydict)
extra_context = {
"ontograph": self.ontospy_graph,
'JSON_DATA_CL... | [
"def",
"_buildTemplates",
"(",
"self",
")",
":",
"c_mydict",
"=",
"build_class_json",
"(",
"self",
".",
"ontospy_graph",
".",
"all_classes",
")",
"JSON_DATA_CLASSES",
"=",
"json",
".",
"dumps",
"(",
"c_mydict",
")",
"extra_context",
"=",
"{",
"\"ontograph\"",
... | 30.35 | 21.15 |
def create_new_migration_record(self):
"""
Create a new migration record for this migration set
"""
migration_record = self.migration_model(
name=self.name,
version=self.latest_migration)
self.session.add(migration_record)
self.session.commit() | [
"def",
"create_new_migration_record",
"(",
"self",
")",
":",
"migration_record",
"=",
"self",
".",
"migration_model",
"(",
"name",
"=",
"self",
".",
"name",
",",
"version",
"=",
"self",
".",
"latest_migration",
")",
"self",
".",
"session",
".",
"add",
"(",
... | 34.222222 | 6.444444 |
def reset(self):
"""Deletes all entries in the cache area"""
if self.collname not in self.current_kv_names():
return # nothing to do
# we'll simply delete the entire collection and then re-create it.
r = self.request('delete',
self.url+"storage/collec... | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"collname",
"not",
"in",
"self",
".",
"current_kv_names",
"(",
")",
":",
"return",
"# nothing to do",
"# we'll simply delete the entire collection and then re-create it.",
"r",
"=",
"self",
".",
"request",
... | 43.777778 | 16.555556 |
def complete_session_endpoint(self, cmd_param_text, full_cmd, *rest):
""" TODO: the hosts lists can be retrieved from self.zk.hosts """
complete_hosts = partial(complete_values, ["127.0.0.1:2181"])
completers = [self._complete_path, complete_hosts, complete_labeled_boolean("reverse")]
re... | [
"def",
"complete_session_endpoint",
"(",
"self",
",",
"cmd_param_text",
",",
"full_cmd",
",",
"*",
"rest",
")",
":",
"complete_hosts",
"=",
"partial",
"(",
"complete_values",
",",
"[",
"\"127.0.0.1:2181\"",
"]",
")",
"completers",
"=",
"[",
"self",
".",
"_comp... | 74.8 | 28.2 |
def welcome(self):
"""Personalized welcome page"""
if not g.user or not g.user.get_id():
return redirect(appbuilder.get_url_for_login)
welcome_dashboard_id = (
db.session
.query(UserAttribute.welcome_dashboard_id)
.filter_by(user_id=g.user.get_id(... | [
"def",
"welcome",
"(",
"self",
")",
":",
"if",
"not",
"g",
".",
"user",
"or",
"not",
"g",
".",
"user",
".",
"get_id",
"(",
")",
":",
"return",
"redirect",
"(",
"appbuilder",
".",
"get_url_for_login",
")",
"welcome_dashboard_id",
"=",
"(",
"db",
".",
... | 31 | 18.4 |
def coordinates(self, x, y):
'''return coordinates of a pixel in the map'''
state = self.state
return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, state.ground_width) | [
"def",
"coordinates",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"state",
"=",
"self",
".",
"state",
"return",
"state",
".",
"mt",
".",
"coord_from_area",
"(",
"x",
",",
"y",
",",
"state",
".",
"lat",
",",
"state",
".",
"lon",
",",
"state",
".",
... | 52 | 25 |
def match(self, version):
"""Check whether a Version satisfies the Spec."""
return all(spec.match(version) for spec in self.specs) | [
"def",
"match",
"(",
"self",
",",
"version",
")",
":",
"return",
"all",
"(",
"spec",
".",
"match",
"(",
"version",
")",
"for",
"spec",
"in",
"self",
".",
"specs",
")"
] | 48 | 12.333333 |
def additionalProperties(self):
"""Schema for all additional properties, or False."""
value = self._schema.get("additionalProperties", {})
if not isinstance(value, dict) and value is not False:
raise SchemaError(
"additionalProperties value {0!r} is neither false nor"... | [
"def",
"additionalProperties",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_schema",
".",
"get",
"(",
"\"additionalProperties\"",
",",
"{",
"}",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"value",
"is",
"not",
"False",
... | 47.25 | 14.375 |
def _values_of_same_type(self, val1, val2):
"""Checks if two values agree in type.
Raises a TypeError if both values are not supported by the parameter.
Returns false if only one of the two values is supported by the parameter.
Example usage:
>>>param._values_of_same_type(42,4... | [
"def",
"_values_of_same_type",
"(",
"self",
",",
"val1",
",",
"val2",
")",
":",
"if",
"self",
".",
"f_supports",
"(",
"val1",
")",
"!=",
"self",
".",
"f_supports",
"(",
"val2",
")",
":",
"return",
"False",
"if",
"not",
"self",
".",
"f_supports",
"(",
... | 33.285714 | 25.214286 |
def get_file(self, file_hash, save_file_at, timeout=None):
""" Get the scan results for a file.
Even if you do not have a Private Mass API key that you can use, you can still download files from the
VirusTotal storage making use of your VirusTotal Intelligence quota, i.e. programmatic downloads... | [
"def",
"get_file",
"(",
"self",
",",
"file_hash",
",",
"save_file_at",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'hash'",
":",
"file_hash",
",",
"'apikey'",
":",
"self",
".",
"api_key",
"}",
"try",
":",
"response",
"=",
"requests",
".... | 46.518519 | 28.555556 |
def accel_prev(self, *args):
"""Callback to go to the previous tab. Called by the accel key.
"""
if self.get_notebook().get_current_page() == 0:
self.get_notebook().set_current_page(self.get_notebook().get_n_pages() - 1)
else:
self.get_notebook().prev_page()
... | [
"def",
"accel_prev",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"get_notebook",
"(",
")",
".",
"get_current_page",
"(",
")",
"==",
"0",
":",
"self",
".",
"get_notebook",
"(",
")",
".",
"set_current_page",
"(",
"self",
".",
"get_noteboo... | 40.875 | 15.625 |
def consume(self, length):
"""
>>> OutBuffer().add(b"spam").consume(2).getvalue() == b"am"
True
@type length: int
@returns: self
"""
self.buff = io.BytesIO(self.getvalue()[length:])
return self | [
"def",
"consume",
"(",
"self",
",",
"length",
")",
":",
"self",
".",
"buff",
"=",
"io",
".",
"BytesIO",
"(",
"self",
".",
"getvalue",
"(",
")",
"[",
"length",
":",
"]",
")",
"return",
"self"
] | 20.1 | 19.1 |
def getSignalParameters(fitParams, n_std=3):
'''
return minimum, average, maximum of the signal peak
'''
signal = getSignalPeak(fitParams)
mx = signal[1] + n_std * signal[2]
mn = signal[1] - n_std * signal[2]
if mn < fitParams[0][1]:
mn = fitParams[0][1] # set to bg
ret... | [
"def",
"getSignalParameters",
"(",
"fitParams",
",",
"n_std",
"=",
"3",
")",
":",
"signal",
"=",
"getSignalPeak",
"(",
"fitParams",
")",
"mx",
"=",
"signal",
"[",
"1",
"]",
"+",
"n_std",
"*",
"signal",
"[",
"2",
"]",
"mn",
"=",
"signal",
"[",
"1",
... | 33.2 | 11.4 |
def get_context_data(self, **kwargs):
"""
We supplement the normal context data by adding our fields and labels.
"""
context = super(SmartView, self).get_context_data(**kwargs)
# derive our field config
self.field_config = self.derive_field_config()
# add our fi... | [
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"SmartView",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"# derive our field config",
"self",
".",
"field_config",
"=",
"s... | 34.214286 | 19.178571 |
def aniso_magic_nb(infile='specimens.txt', samp_file='samples.txt', site_file='sites.txt', verbose=True,
ipar=False, ihext=True, ivec=False, isite=False, iloc=False, iboot=False, vec=0,
Dir=[], PDir=[], crd="s", num_bootstraps=1000, dir_path=".", fignum=1,
save_p... | [
"def",
"aniso_magic_nb",
"(",
"infile",
"=",
"'specimens.txt'",
",",
"samp_file",
"=",
"'samples.txt'",
",",
"site_file",
"=",
"'sites.txt'",
",",
"verbose",
"=",
"True",
",",
"ipar",
"=",
"False",
",",
"ihext",
"=",
"True",
",",
"ivec",
"=",
"False",
",",... | 43.164706 | 19.870588 |
def reset(self, new_session=True):
"""Clear all internal namespaces, and attempt to release references to
user objects.
If new_session is True, a new history session will be opened.
"""
# Clear histories
self.history_manager.reset(new_session)
# Reset counter use... | [
"def",
"reset",
"(",
"self",
",",
"new_session",
"=",
"True",
")",
":",
"# Clear histories",
"self",
".",
"history_manager",
".",
"reset",
"(",
"new_session",
")",
"# Reset counter used to index all histories",
"if",
"new_session",
":",
"self",
".",
"execution_count... | 34.340909 | 15.818182 |
def read_namespaced_replication_controller(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_replication_controller # noqa: E501
read the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP... | [
"def",
"read_namespaced_replication_controller",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":... | 59.4 | 31.4 |
def _convert_slice_incement_inconsistencies(dicom_input):
"""
If there is slice increment inconsistency detected, for the moment CT images, then split the volumes into subvolumes based on the slice increment and process each volume separately using a space constructed based on the highest resolution increment
... | [
"def",
"_convert_slice_incement_inconsistencies",
"(",
"dicom_input",
")",
":",
"# Estimate the \"first\" slice increment based on the 2 first slices",
"increment",
"=",
"numpy",
".",
"array",
"(",
"dicom_input",
"[",
"0",
"]",
".",
"ImagePositionPatient",
")",
"-",
"nump... | 55.25 | 30.472222 |
def register_child(cls, prop, child_cls):
"""
Register a new :class:`XMLStreamClass` instance `child_cls` for a given
:class:`Child` descriptor `prop`.
.. warning::
This method cannot be used after a class has been derived from this
class. This is for consistency:... | [
"def",
"register_child",
"(",
"cls",
",",
"prop",
",",
"child_cls",
")",
":",
"if",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"register_child is forbidden on classes with subclasses\"",
"\" (subclasses: {})\"",
".",
"format",
"(",
"\"... | 43.955556 | 25.911111 |
def remove(self, key, value):
"""
Removes the given key-value tuple from the multimap.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's class.**
:param key: (object), the k... | [
"def",
"remove",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"check_not_none",
"(",
"key",
",",
"\"value can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
... | 52.117647 | 26.588235 |
def check_rdd_dtype(rdd, expected_dtype):
"""Checks if the blocks in the RDD matches the expected types.
Parameters:
-----------
rdd: splearn.BlockRDD
The RDD to check
expected_dtype: {type, list of types, tuple of types, dict of types}
Expected type(s). If the RDD is a DictRDD the ... | [
"def",
"check_rdd_dtype",
"(",
"rdd",
",",
"expected_dtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"rdd",
",",
"BlockRDD",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected {0} for parameter rdd, got {1}.\"",
".",
"format",
"(",
"BlockRDD",
",",
"type",
"(",
... | 35.333333 | 17.305556 |
def score_braycurtis(self, term1, term2, **kwargs):
"""
Compute a weighting score based on the "City Block" distance between
the kernel density estimates of two terms.
Args:
term1 (str)
term2 (str)
Returns: float
"""
t1_kde = self.kde(t... | [
"def",
"score_braycurtis",
"(",
"self",
",",
"term1",
",",
"term2",
",",
"*",
"*",
"kwargs",
")",
":",
"t1_kde",
"=",
"self",
".",
"kde",
"(",
"term1",
",",
"*",
"*",
"kwargs",
")",
"t2_kde",
"=",
"self",
".",
"kde",
"(",
"term2",
",",
"*",
"*",
... | 24.470588 | 20.705882 |
def formatError(self, test, err):
"""Add captured log messages to error output.
"""
# logic flow copied from Capture.formatError
test.capturedLogging = records = self.formatLogRecords()
if not records:
return err
ec, ev, tb = err
return (ec, self.addCa... | [
"def",
"formatError",
"(",
"self",
",",
"test",
",",
"err",
")",
":",
"# logic flow copied from Capture.formatError",
"test",
".",
"capturedLogging",
"=",
"records",
"=",
"self",
".",
"formatLogRecords",
"(",
")",
"if",
"not",
"records",
":",
"return",
"err",
... | 37.777778 | 12.444444 |
def kernel_config():
"""Create a config object with IPython kernel options."""
import ipykernel
from IPython.core.application import get_ipython_dir
from traitlets.config.loader import Config, load_pyconfig_files
# ---- IPython config ----
try:
profile_path = osp.join(get_ipython_dir(),... | [
"def",
"kernel_config",
"(",
")",
":",
"import",
"ipykernel",
"from",
"IPython",
".",
"core",
".",
"application",
"import",
"get_ipython_dir",
"from",
"traitlets",
".",
"config",
".",
"loader",
"import",
"Config",
",",
"load_pyconfig_files",
"# ---- IPython config -... | 37.213873 | 17.751445 |
def newNsProp(self, node, name, value):
"""Create a new property tagged with a namespace and carried
by a node. """
if node is None: node__o = None
else: node__o = node._o
ret = libxml2mod.xmlNewNsProp(node__o, self._o, name, value)
if ret is None:raise treeError('xmlN... | [
"def",
"newNsProp",
"(",
"self",
",",
"node",
",",
"name",
",",
"value",
")",
":",
"if",
"node",
"is",
"None",
":",
"node__o",
"=",
"None",
"else",
":",
"node__o",
"=",
"node",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlNewNsProp",
"(",
"node__o",... | 42.888889 | 9.888889 |
def Nu_Jackson(Re, Pr, rho_w=None, rho_b=None, Cp_avg=None, Cp_b=None, T_b=None,
T_w=None, T_pc=None):
r'''Calculates internal convection Nusselt number for turbulent vertical
upward flow in a pipe under supercritical conditions according to [1]_.
.. math::
Nu_b = 0.0183 Re_b... | [
"def",
"Nu_Jackson",
"(",
"Re",
",",
"Pr",
",",
"rho_w",
"=",
"None",
",",
"rho_b",
"=",
"None",
",",
"Cp_avg",
"=",
"None",
",",
"Cp_b",
"=",
"None",
",",
"T_b",
"=",
"None",
",",
"T_w",
"=",
"None",
",",
"T_pc",
"=",
"None",
")",
":",
"if",
... | 38.346535 | 23.950495 |
def is_none_or(self):
"""
Ensures :attr:`subject` is either ``None``, or satisfies subsequent (chained) conditions::
Ensure(None).is_none_or.is_an(int)
"""
if self._subject is None:
return NoOpInspector(subject=self._subject, error_factory=self._error_factory)
... | [
"def",
"is_none_or",
"(",
"self",
")",
":",
"if",
"self",
".",
"_subject",
"is",
"None",
":",
"return",
"NoOpInspector",
"(",
"subject",
"=",
"self",
".",
"_subject",
",",
"error_factory",
"=",
"self",
".",
"_error_factory",
")",
"else",
":",
"return",
"... | 34.6 | 22.4 |
def settings_system_update(self, data):
"""
Set system settings. Uses PUT to /settings/system interface
:Args:
* *data*: (dict) Settings dictionary as specified `here <https://cloud.knuverse.com/docs/api/#api-System_Settings-Set_System_Settings>`_.
:Returns: None
"... | [
"def",
"settings_system_update",
"(",
"self",
",",
"data",
")",
":",
"data",
"[",
"\"auth_password\"",
"]",
"=",
"self",
".",
"_password",
"response",
"=",
"self",
".",
"_put",
"(",
"url",
".",
"settings_system",
",",
"body",
"=",
"data",
")",
"self",
".... | 35.615385 | 25.461538 |
def _parse_example_spec(self):
"""Returns a `tf.Example` parsing spec as dict."""
height, width = image_util.get_expected_image_size(self.module_spec)
input_shape = [height, width, 3]
return {self.key: tf_v1.FixedLenFeature(input_shape, tf.float32)} | [
"def",
"_parse_example_spec",
"(",
"self",
")",
":",
"height",
",",
"width",
"=",
"image_util",
".",
"get_expected_image_size",
"(",
"self",
".",
"module_spec",
")",
"input_shape",
"=",
"[",
"height",
",",
"width",
",",
"3",
"]",
"return",
"{",
"self",
"."... | 52.2 | 15 |
def load_sound_font(self, sf2):
"""Load a sound font.
Return True on success, False on failure.
This function should be called before your audio can be played,
since the instruments are kept in the sf2 file.
"""
self.sfid = self.fs.sfload(sf2)
return not self.sf... | [
"def",
"load_sound_font",
"(",
"self",
",",
"sf2",
")",
":",
"self",
".",
"sfid",
"=",
"self",
".",
"fs",
".",
"sfload",
"(",
"sf2",
")",
"return",
"not",
"self",
".",
"sfid",
"==",
"-",
"1"
] | 31.9 | 15.1 |
def _get_binary(self):
""" find binaries available"""
## check for binary
backup_binaries = ["raxmlHPC-PTHREADS", "raxmlHPC-PTHREADS-SSE3"]
## check user binary first, then backups
for binary in [self.params.binary] + backup_binaries:
proc = subprocess.Popen(["which... | [
"def",
"_get_binary",
"(",
"self",
")",
":",
"## check for binary",
"backup_binaries",
"=",
"[",
"\"raxmlHPC-PTHREADS\"",
",",
"\"raxmlHPC-PTHREADS-SSE3\"",
"]",
"## check user binary first, then backups",
"for",
"binary",
"in",
"[",
"self",
".",
"params",
".",
"binary"... | 36.666667 | 19.111111 |
def cast(keys, data):
"""Cast a set of keys and an array to a Matrix object."""
matrix = Matrix()
matrix.keys = keys
matrix.data = data
return matrix | [
"def",
"cast",
"(",
"keys",
",",
"data",
")",
":",
"matrix",
"=",
"Matrix",
"(",
")",
"matrix",
".",
"keys",
"=",
"keys",
"matrix",
".",
"data",
"=",
"data",
"return",
"matrix"
] | 30.666667 | 13.5 |
def slot_add_binding(self, slot_number, adapter):
"""
Adds a slot binding (a module into a slot).
:param slot_number: slot number
:param adapter: device to add in the corresponding slot
"""
try:
slot = self._slots[slot_number]
except IndexError:
... | [
"def",
"slot_add_binding",
"(",
"self",
",",
"slot_number",
",",
"adapter",
")",
":",
"try",
":",
"slot",
"=",
"self",
".",
"_slots",
"[",
"slot_number",
"]",
"except",
"IndexError",
":",
"raise",
"DynamipsError",
"(",
"'Slot {slot_number} does not exist on router... | 65.354167 | 48.1875 |
def _ParseTokenType(self, file_object, file_offset):
"""Parses a token type.
Args:
file_object (dfvfs.FileIO): file-like object.
file_offset (int): offset of the token relative to the start of
the file-like object.
Returns:
int: token type
"""
token_type_map = self._Get... | [
"def",
"_ParseTokenType",
"(",
"self",
",",
"file_object",
",",
"file_offset",
")",
":",
"token_type_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'uint8'",
")",
"token_type",
",",
"_",
"=",
"self",
".",
"_ReadStructureFromFileObject",
"(",
"file_object",
","... | 26.647059 | 20.647059 |
def timeseries(self):
"""
Feed-in time series of generator
It returns the actual time series used in power flow analysis. If
:attr:`_timeseries` is not :obj:`None`, it is returned. Otherwise,
:meth:`timeseries` looks for generation and curtailment time series
of the acco... | [
"def",
"timeseries",
"(",
"self",
")",
":",
"if",
"self",
".",
"_timeseries",
"is",
"None",
":",
"# get time series for active power depending on if they are",
"# differentiated by weather cell ID or not",
"if",
"isinstance",
"(",
"self",
".",
"grid",
".",
"network",
".... | 42.2 | 21.153846 |
def _imm_repr(self):
'''
The default representation function for an immutable object.
'''
return (type(self).__name__
+ ('(' if _imm_is_persist(self) else '*(')
+ ', '.join([k + '=' + str(v) for (k,v) in six.iteritems(imm_params(self))])
+ ')') | [
"def",
"_imm_repr",
"(",
"self",
")",
":",
"return",
"(",
"type",
"(",
"self",
")",
".",
"__name__",
"+",
"(",
"'('",
"if",
"_imm_is_persist",
"(",
"self",
")",
"else",
"'*('",
")",
"+",
"', '",
".",
"join",
"(",
"[",
"k",
"+",
"'='",
"+",
"str",... | 36.125 | 25.375 |
def _sigma_ee_rel(self, gam, eps):
"""
Eq. A1, A4 of Baring et al. (1999)
Use for Ee > 2 MeV
"""
A = 1 - 8 / 3 * (gam - 1) ** 0.2 / (gam + 1) * (eps / gam) ** (
1.0 / 3.0
)
return (self._sigma_1(gam, eps) + self._sigma_2(gam, eps)) * A | [
"def",
"_sigma_ee_rel",
"(",
"self",
",",
"gam",
",",
"eps",
")",
":",
"A",
"=",
"1",
"-",
"8",
"/",
"3",
"*",
"(",
"gam",
"-",
"1",
")",
"**",
"0.2",
"/",
"(",
"gam",
"+",
"1",
")",
"*",
"(",
"eps",
"/",
"gam",
")",
"**",
"(",
"1.0",
"... | 29.5 | 17.3 |
def vars(self):
"""Alternative naming, you can use `node.vars.name` instead of `node.v_name`"""
if self._vars is None:
self._vars = NNTreeNodeVars(self)
return self._vars | [
"def",
"vars",
"(",
"self",
")",
":",
"if",
"self",
".",
"_vars",
"is",
"None",
":",
"self",
".",
"_vars",
"=",
"NNTreeNodeVars",
"(",
"self",
")",
"return",
"self",
".",
"_vars"
] | 40.4 | 11 |
def count_protein_group_hits(lineproteins, groups):
"""Takes a list of protein accessions and a list of protein groups
content from DB. Counts for each group in list how many proteins
are found in lineproteins. Returns list of str amounts.
"""
hits = []
for group in groups:
hits.append(0... | [
"def",
"count_protein_group_hits",
"(",
"lineproteins",
",",
"groups",
")",
":",
"hits",
"=",
"[",
"]",
"for",
"group",
"in",
"groups",
":",
"hits",
".",
"append",
"(",
"0",
")",
"for",
"protein",
"in",
"lineproteins",
":",
"if",
"protein",
"in",
"group"... | 37 | 12.416667 |
def _create_request_schema(self, params, required):
"""Create a JSON schema for a request.
:param list params: A list of keys specifying which definitions from
the base schema should be allowed in the request.
:param list required: A subset of the params that the requester must
... | [
"def",
"_create_request_schema",
"(",
"self",
",",
"params",
",",
"required",
")",
":",
"# We allow additional properties because the data this will validate",
"# may also include kwargs passed by decorators on the handler method.",
"schema",
"=",
"{",
"'additionalProperties'",
":",
... | 45.95 | 16.1 |
def _get_visit_name(self):
"""
return the visit name for the mixed class. When calling 'accept', the
method <'visit_' + name returned by this method> will be called on the
visitor
"""
try:
# pylint: disable=no-member
return self.TYPE.replace("-", "... | [
"def",
"_get_visit_name",
"(",
"self",
")",
":",
"try",
":",
"# pylint: disable=no-member",
"return",
"self",
".",
"TYPE",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"# pylint: disable=broad-except",
"except",
"Exception",
":",
"return",
"self",
".",
"__cl... | 35.666667 | 14.666667 |
def cornerbound(results, it=None, idx=None, prior_transform=None,
periodic=None, ndraws=5000, color='gray', plot_kwargs=None,
labels=None, label_kwargs=None, max_n_ticks=5,
use_math_text=False, show_live=False, live_color='darkviolet',
live_kwargs=None, sp... | [
"def",
"cornerbound",
"(",
"results",
",",
"it",
"=",
"None",
",",
"idx",
"=",
"None",
",",
"prior_transform",
"=",
"None",
",",
"periodic",
"=",
"None",
",",
"ndraws",
"=",
"5000",
",",
"color",
"=",
"'gray'",
",",
"plot_kwargs",
"=",
"None",
",",
"... | 40.457726 | 20.189504 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.