text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_trainer(self, model, method='sgd', config=None, annealer=None, validator=None):
"""
Get a trainer to optimize given model.
:rtype: deepy.trainers.GeneralNeuralTrainer
"""
from deepy.trainers import GeneralNeuralTrainer
return GeneralNeuralTrainer(model, method=me... | [
"def",
"get_trainer",
"(",
"self",
",",
"model",
",",
"method",
"=",
"'sgd'",
",",
"config",
"=",
"None",
",",
"annealer",
"=",
"None",
",",
"validator",
"=",
"None",
")",
":",
"from",
"deepy",
".",
"trainers",
"import",
"GeneralNeuralTrainer",
"return",
... | 53.428571 | 21.714286 |
def rollback(cls, bigchain, new_height, txn_ids):
"""Looks for election and vote transactions inside the block and
cleans up the database artifacts possibly created in `process_blocks`.
Part of the `end_block`/`commit` crash recovery.
"""
# delete election records for ele... | [
"def",
"rollback",
"(",
"cls",
",",
"bigchain",
",",
"new_height",
",",
"txn_ids",
")",
":",
"# delete election records for elections initiated at this height and",
"# elections concluded at this height",
"bigchain",
".",
"delete_elections",
"(",
"new_height",
")",
"txns",
... | 41 | 20 |
def cleanup_service(self, factory, svc_registration):
# type: (Any, ServiceRegistration) -> bool
"""
If this bundle used that factory, releases the reference; else does
nothing
:param factory: The service factory
:param svc_registration: The ServiceRegistration object
... | [
"def",
"cleanup_service",
"(",
"self",
",",
"factory",
",",
"svc_registration",
")",
":",
"# type: (Any, ServiceRegistration) -> bool",
"svc_ref",
"=",
"svc_registration",
".",
"get_reference",
"(",
")",
"try",
":",
"# \"service\" for factories, \"services\" for prototypes",
... | 37.911765 | 17.970588 |
def to_data(value):
"""Standardize data types. Converts PyTorch tensors to Numpy arrays,
and Numpy scalars to Python scalars."""
# TODO: Use get_framework() for better detection.
if value.__class__.__module__.startswith("torch"):
import torch
if isinstance(value, torch.nn.parameter.Param... | [
"def",
"to_data",
"(",
"value",
")",
":",
"# TODO: Use get_framework() for better detection.",
"if",
"value",
".",
"__class__",
".",
"__module__",
".",
"startswith",
"(",
"\"torch\"",
")",
":",
"import",
"torch",
"if",
"isinstance",
"(",
"value",
",",
"torch",
"... | 41.736842 | 12 |
def new_bg(self,bg):
"""
m.new_bg(,bg) -- Change the ACGT background frequencies to those in the supplied dictionary.
Recompute log-likelihood, etc. with new background.
"""
counts = []
for pos in self.logP:
D = {}
for L,lp in po... | [
"def",
"new_bg",
"(",
"self",
",",
"bg",
")",
":",
"counts",
"=",
"[",
"]",
"for",
"pos",
"in",
"self",
".",
"logP",
":",
"D",
"=",
"{",
"}",
"for",
"L",
",",
"lp",
"in",
"pos",
".",
"items",
"(",
")",
":",
"D",
"[",
"L",
"]",
"=",
"math"... | 35.307692 | 15.615385 |
def get_all_saved_searches(self, **kwargs): # noqa: E501
"""Get all saved searches for a user # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_all_saved_se... | [
"def",
"get_all_saved_searches",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_all_saved_search... | 40.909091 | 19.045455 |
async def _catch_response(self, h11_connection):
'''
Instantiates the parser which manages incoming data, first getting
the headers, storing cookies, and then parsing the response's body,
if any.
This function also instances the Response class in which the response
statu... | [
"async",
"def",
"_catch_response",
"(",
"self",
",",
"h11_connection",
")",
":",
"response",
"=",
"await",
"self",
".",
"_recv_event",
"(",
"h11_connection",
")",
"resp_data",
"=",
"{",
"'encoding'",
":",
"self",
".",
"encoding",
",",
"'method'",
":",
"self"... | 38.315217 | 22.858696 |
async def packet_receiver(queue):
""" Asynchronous function that processes queue until None is posted in queue """
LOG.info("Entering packet_receiver")
while True:
packet = await queue.get()
if packet is None:
break
LOG.info("Framenumber %s", packet.framenumber)
LOG.... | [
"async",
"def",
"packet_receiver",
"(",
"queue",
")",
":",
"LOG",
".",
"info",
"(",
"\"Entering packet_receiver\"",
")",
"while",
"True",
":",
"packet",
"=",
"await",
"queue",
".",
"get",
"(",
")",
"if",
"packet",
"is",
"None",
":",
"break",
"LOG",
".",
... | 34.2 | 13 |
def normalize_namespace(namespace):
""" Given a namespace (e.g. '.' or 'mynamespace'),
returns it in normalized form. That is:
- always prefixed with a dot
- no trailing dots
- any double dots are converted to single dot (..my..namespace => .my.namespace)
- one or more dots (e.g.... | [
"def",
"normalize_namespace",
"(",
"namespace",
")",
":",
"namespace",
"=",
"(",
"DOT",
"+",
"DOT",
".",
"join",
"(",
"RE_DOTS",
".",
"split",
"(",
"namespace",
")",
")",
")",
".",
"rstrip",
"(",
"DOT",
")",
"+",
"DOT",
"return",
"namespace"
] | 47.5 | 18 |
def set_if_empty(self, param, default):
""" Set the parameter to the default if it doesn't exist """
if not self.has(param):
self.set(param, default) | [
"def",
"set_if_empty",
"(",
"self",
",",
"param",
",",
"default",
")",
":",
"if",
"not",
"self",
".",
"has",
"(",
"param",
")",
":",
"self",
".",
"set",
"(",
"param",
",",
"default",
")"
] | 43.5 | 3.5 |
def FixedOffset(offset, _tzinfos = {}):
"""return a fixed-offset timezone based off a number of minutes.
>>> one = FixedOffset(-330)
>>> one
pytz.FixedOffset(-330)
>>> one.utcoffset(datetime.datetime.now())
datetime.timedelta(-1, 66600)
>>> one.dst(datetime.datetime.... | [
"def",
"FixedOffset",
"(",
"offset",
",",
"_tzinfos",
"=",
"{",
"}",
")",
":",
"if",
"offset",
"==",
"0",
":",
"return",
"UTC",
"info",
"=",
"_tzinfos",
".",
"get",
"(",
"offset",
")",
"if",
"info",
"is",
"None",
":",
"# We haven't seen this one before. ... | 27.523077 | 20.215385 |
def _insert_f_additive(s):
"""i.B:.-+u.M:.-O:.-' => i.f.B:.-+u.f.M:.-O:.-'"""
subst, attr, mode = s
assert isinstance(mode, NullScript)
if isinstance(subst, AdditiveScript):
subst = AdditiveScript([_insert_attr_f(_s) for _s in subst])
else:
subst = _insert_attr_f(subst)
return ... | [
"def",
"_insert_f_additive",
"(",
"s",
")",
":",
"subst",
",",
"attr",
",",
"mode",
"=",
"s",
"assert",
"isinstance",
"(",
"mode",
",",
"NullScript",
")",
"if",
"isinstance",
"(",
"subst",
",",
"AdditiveScript",
")",
":",
"subst",
"=",
"AdditiveScript",
... | 29.454545 | 17.090909 |
def async_chain(chain, group=None, cached=Conf.CACHED, sync=Conf.SYNC, broker=None):
"""
enqueues a chain of tasks
the chain must be in the format [(func,(args),{kwargs}),(func,(args),{kwargs})]
"""
if not group:
group = uuid()[1]
args = ()
kwargs = {}
task = chain.pop(0)
if ... | [
"def",
"async_chain",
"(",
"chain",
",",
"group",
"=",
"None",
",",
"cached",
"=",
"Conf",
".",
"CACHED",
",",
"sync",
"=",
"Conf",
".",
"SYNC",
",",
"broker",
"=",
"None",
")",
":",
"if",
"not",
"group",
":",
"group",
"=",
"uuid",
"(",
")",
"[",... | 28.391304 | 16.73913 |
def encode_field(self, field, value):
"""Encode a python field value to a JSON value.
Args:
field: A ProtoRPC field instance.
value: A python value supported by field.
Returns:
A JSON serializable value appropriate for field.
"""
if isinstance(fiel... | [
"def",
"encode_field",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"messages",
".",
"BytesField",
")",
":",
"if",
"field",
".",
"repeated",
":",
"value",
"=",
"[",
"base64",
".",
"b64encode",
"(",
"byte",
... | 35.954545 | 16.590909 |
def _set_interface_ospfv3_conf(self, v, load=False):
"""
Setter method for interface_ospfv3_conf, mapped from YANG variable /rbridge_id/interface/ve/ipv6/interface_ospfv3_conf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_ospfv3_conf is considered... | [
"def",
"_set_interface_ospfv3_conf",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 93.458333 | 45.958333 |
def make_python_identifier(string, namespace=None, reserved_words=None,
convert='drop', handle='force'):
"""
Takes an arbitrary string and creates a valid Python identifier.
If the input string is in the namespace, return its value.
If the python identifier created is alread... | [
"def",
"make_python_identifier",
"(",
"string",
",",
"namespace",
"=",
"None",
",",
"reserved_words",
"=",
"None",
",",
"convert",
"=",
"'drop'",
",",
"handle",
"=",
"'force'",
")",
":",
"if",
"namespace",
"is",
"None",
":",
"namespace",
"=",
"dict",
"(",
... | 37.818182 | 23.818182 |
def get_actual_start_time(self):
"""Gets the time this assessment was started.
return: (osid.calendaring.DateTime) - the start time
raise: IllegalState - ``has_started()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
if not self.has_star... | [
"def",
"get_actual_start_time",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_started",
"(",
")",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'this assessment has not yet started'",
")",
"if",
"self",
".",
"_my_map",
"[",
"'actualStartTime'",
"]",... | 46.333333 | 18.619048 |
def _val(var, is_percent=False):
"""
Tries to determine the appropriate value of a particular variable that is
passed in. If the value is supposed to be a percentage, a whole integer
will be sought after and then turned into a floating point number between
0 and 1. If the value is supposed to be a... | [
"def",
"_val",
"(",
"var",
",",
"is_percent",
"=",
"False",
")",
":",
"try",
":",
"if",
"is_percent",
":",
"var",
"=",
"float",
"(",
"int",
"(",
"var",
".",
"strip",
"(",
"'%'",
")",
")",
"/",
"100.0",
")",
"else",
":",
"var",
"=",
"int",
"(",
... | 34.882353 | 22.647059 |
def cf_number_to_number(value):
"""
Converts a CFNumber object to a python float or integer
:param value:
The CFNumber object
:return:
A python number (float or integer)
"""
type_ = CoreFoundation.CFNumberGetType(_cast_pointer_p(value))
... | [
"def",
"cf_number_to_number",
"(",
"value",
")",
":",
"type_",
"=",
"CoreFoundation",
".",
"CFNumberGetType",
"(",
"_cast_pointer_p",
"(",
"value",
")",
")",
"c_type",
"=",
"{",
"1",
":",
"c_byte",
",",
"# kCFNumberSInt8Type",
"2",
":",
"ctypes",
".",
"c_sho... | 41.909091 | 19.060606 |
def text_color(background, dark_color=rgb_min, light_color=rgb_max):
"""
Given a background color in the form of an RGB 3-tuple, returns the color the text should be (defaulting to white
and black) for best readability. The light (white) and dark (black) defaults can be overridden to return preferred
va... | [
"def",
"text_color",
"(",
"background",
",",
"dark_color",
"=",
"rgb_min",
",",
"light_color",
"=",
"rgb_max",
")",
":",
"max_y",
"=",
"rgb_to_yiq",
"(",
"rgb_max",
")",
"[",
"0",
"]",
"return",
"light_color",
"if",
"rgb_to_yiq",
"(",
"background",
")",
"[... | 40.076923 | 29.153846 |
def report(config, output, use, output_dir, accounts,
field, no_default_fields, tags, region, debug, verbose,
policy, policy_tags, format, resource, cache_path):
"""report on a cross account policy execution."""
accounts_config, custodian_config, executor = init(
config, use, debug... | [
"def",
"report",
"(",
"config",
",",
"output",
",",
"use",
",",
"output_dir",
",",
"accounts",
",",
"field",
",",
"no_default_fields",
",",
"tags",
",",
"region",
",",
"debug",
",",
"verbose",
",",
"policy",
",",
"policy_tags",
",",
"format",
",",
"resou... | 35.830769 | 16.523077 |
def get_rpms(self):
"""
Build a list of installed RPMs in the format required for the
metadata.
"""
tags = [
'NAME',
'VERSION',
'RELEASE',
'ARCH',
'EPOCH',
'SIGMD5',
'SIGPGP:pgpsig',
... | [
"def",
"get_rpms",
"(",
"self",
")",
":",
"tags",
"=",
"[",
"'NAME'",
",",
"'VERSION'",
",",
"'RELEASE'",
",",
"'ARCH'",
",",
"'EPOCH'",
",",
"'SIGMD5'",
",",
"'SIGPGP:pgpsig'",
",",
"'SIGGPG:pgpsig'",
",",
"]",
"cmd",
"=",
"\"/bin/rpm \"",
"+",
"rpm_qf_ar... | 29.538462 | 19.128205 |
def set_write_bit(fn):
# type: (str) -> None
"""
Set read-write permissions for the current user on the target path. Fail silently
if the path doesn't exist.
:param str fn: The target filename or path
:return: None
"""
fn = fs_encode(fn)
if not os.path.exists(fn):
return
... | [
"def",
"set_write_bit",
"(",
"fn",
")",
":",
"# type: (str) -> None",
"fn",
"=",
"fs_encode",
"(",
"fn",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"return",
"file_stat",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
".",
"s... | 32.052632 | 18.789474 |
def create_deep_linking_urls(self, url_params):
"""
Bulk Creates Deep Linking URLs
See the URL https://dev.branch.io/references/http_api/#bulk-creating-deep-linking-urls
:param url_params: Array of values returned from "create_deep_link_url(..., skip_api_call=True)"
:return: Th... | [
"def",
"create_deep_linking_urls",
"(",
"self",
",",
"url_params",
")",
":",
"url",
"=",
"\"/v1/url/bulk/%s\"",
"%",
"self",
".",
"branch_key",
"method",
"=",
"\"POST\"",
"# Checks params",
"self",
".",
"_check_param",
"(",
"value",
"=",
"url_params",
",",
"type... | 34.352941 | 26.823529 |
def check_bounding_rect(rect_pos):
"""Ensure the rect spec is valid."""
if not isinstance(rect_pos, Iterable):
raise ValueError('rectangle spect must be a tuple of floats '
'specifying (left, right, width, height)')
left, bottom, width, height = rect_pos
for val, name ... | [
"def",
"check_bounding_rect",
"(",
"rect_pos",
")",
":",
"if",
"not",
"isinstance",
"(",
"rect_pos",
",",
"Iterable",
")",
":",
"raise",
"ValueError",
"(",
"'rectangle spect must be a tuple of floats '",
"'specifying (left, right, width, height)'",
")",
"left",
",",
"bo... | 39.227273 | 23.136364 |
def skip(self, count):
'''
:param count: number of cases to skip
:return: number of cases skipped
'''
self._get_ready()
skipped = 0
for i in range(count):
if self.mutate():
skipped += 1
else:
break
re... | [
"def",
"skip",
"(",
"self",
",",
"count",
")",
":",
"self",
".",
"_get_ready",
"(",
")",
"skipped",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"if",
"self",
".",
"mutate",
"(",
")",
":",
"skipped",
"+=",
"1",
"else",
":",
"bre... | 24.615385 | 16.153846 |
def NewPathSpec(cls, type_indicator, **kwargs):
"""Creates a new path specification for the specific type indicator.
Args:
type_indicator (str): type indicator.
kwargs (dict): keyword arguments depending on the path specification.
Returns:
PathSpec: path specification.
Raises:
... | [
"def",
"NewPathSpec",
"(",
"cls",
",",
"type_indicator",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"type_indicator",
"not",
"in",
"cls",
".",
"_path_spec_types",
":",
"raise",
"KeyError",
"(",
"'Path specification type: {0:s} not set.'",
".",
"format",
"(",
"type... | 33.25 | 20.875 |
def get_definition(self):
"""Checks variable and executable code elements based on the current
context for a code element whose name matches context.exact_match
perfectly.
"""
#Check the variables first, then the functions.
match = self._bracket_exact_var(self.context.exa... | [
"def",
"get_definition",
"(",
"self",
")",
":",
"#Check the variables first, then the functions.",
"match",
"=",
"self",
".",
"_bracket_exact_var",
"(",
"self",
".",
"context",
".",
"exact_match",
")",
"if",
"match",
"is",
"None",
":",
"match",
"=",
"self",
".",... | 39.727273 | 19.454545 |
def conv_precip_frac(precip_largescale, precip_convective):
"""Fraction of total precip that is from convection parameterization.
Parameters
----------
precip_largescale, precip_convective : xarray.DataArrays
Precipitation from grid-scale condensation and from convective
parameterizatio... | [
"def",
"conv_precip_frac",
"(",
"precip_largescale",
",",
"precip_convective",
")",
":",
"total",
"=",
"total_precip",
"(",
"precip_largescale",
",",
"precip_convective",
")",
"# Mask using xarray's `where` method to prevent divide-by-zero.",
"return",
"precip_convective",
"/",... | 34.75 | 21.125 |
def fetchall_triples_xrefs(prefix):
"""
fetch all xrefs for a prefix, e.g. CHEBI
"""
logging.info("fetching xrefs for: "+prefix)
query = """
SELECT * WHERE {{
?c <{p}> ?x
}}
""".format(p=prefixmap[prefix])
bindings = run_sparql(query)
rows = [(r['c']['value'], r['x']['value']... | [
"def",
"fetchall_triples_xrefs",
"(",
"prefix",
")",
":",
"logging",
".",
"info",
"(",
"\"fetching xrefs for: \"",
"+",
"prefix",
")",
"query",
"=",
"\"\"\"\n SELECT * WHERE {{\n ?c <{p}> ?x\n }}\n \"\"\"",
".",
"format",
"(",
"p",
"=",
"prefixmap",
"[",
"... | 26.461538 | 11.692308 |
def file_variations(filename, extensions):
"""Create a variation of file names.
Generate a list of variations on a filename by replacing the extension with
a the provided list.
:param filename: The original file name to use as a base.
:param extensions: A list of file extensions to generate new f... | [
"def",
"file_variations",
"(",
"filename",
",",
"extensions",
")",
":",
"(",
"label",
",",
"ext",
")",
"=",
"splitext",
"(",
"filename",
")",
"return",
"[",
"label",
"+",
"extention",
"for",
"extention",
"in",
"extensions",
"]"
] | 35.25 | 21.166667 |
def visit_and_update(self, visitor_fn):
"""Create an updated version (if needed) of BinaryComposition via the visitor pattern."""
new_left = self.left.visit_and_update(visitor_fn)
new_right = self.right.visit_and_update(visitor_fn)
if new_left is not self.left or new_right is not self.r... | [
"def",
"visit_and_update",
"(",
"self",
",",
"visitor_fn",
")",
":",
"new_left",
"=",
"self",
".",
"left",
".",
"visit_and_update",
"(",
"visitor_fn",
")",
"new_right",
"=",
"self",
".",
"right",
".",
"visit_and_update",
"(",
"visitor_fn",
")",
"if",
"new_le... | 50.222222 | 20.111111 |
def makevFunc(self,solution):
'''
Make the beginning-of-period value function (unconditional on the shock).
Parameters
----------
solution : ConsumerSolution
The solution to this single period problem, which must include the
consumption function.
... | [
"def",
"makevFunc",
"(",
"self",
",",
"solution",
")",
":",
"# Compute expected value and marginal value on a grid of market resources,",
"# accounting for all of the discrete preference shocks",
"PrefShkCount",
"=",
"self",
".",
"PrefShkVals",
".",
"size",
"mNrm_temp",
"=",
"s... | 47.075 | 23.425 |
def get_config(self):
"""Return configurations of LinearAnnealedPolicy
# Returns
Dict of config
"""
config = super(LinearAnnealedPolicy, self).get_config()
config['attr'] = self.attr
config['value_max'] = self.value_max
config['value_min'] = self.valu... | [
"def",
"get_config",
"(",
"self",
")",
":",
"config",
"=",
"super",
"(",
"LinearAnnealedPolicy",
",",
"self",
")",
".",
"get_config",
"(",
")",
"config",
"[",
"'attr'",
"]",
"=",
"self",
".",
"attr",
"config",
"[",
"'value_max'",
"]",
"=",
"self",
".",... | 35.285714 | 13.5 |
def system_info(conf, args):
"""Retieve SDC system information."""
src = conf.config['instances'][args.src]
src_url = api.build_system_url(build_instance_url(src))
src_auth = tuple([conf.creds['instances'][args.src]['user'],
conf.creds['instances'][args.src]['pass']])
verify_ss... | [
"def",
"system_info",
"(",
"conf",
",",
"args",
")",
":",
"src",
"=",
"conf",
".",
"config",
"[",
"'instances'",
"]",
"[",
"args",
".",
"src",
"]",
"src_url",
"=",
"api",
".",
"build_system_url",
"(",
"build_instance_url",
"(",
"src",
")",
")",
"src_au... | 48.111111 | 14.444444 |
def _start_date_of_year(year: int) -> datetime.date:
"""
Return start date of the year using MMWR week rules
"""
jan_one = datetime.date(year, 1, 1)
diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday()
return jan_one + datetime.timedelta(days=diff) | [
"def",
"_start_date_of_year",
"(",
"year",
":",
"int",
")",
"->",
"datetime",
".",
"date",
":",
"jan_one",
"=",
"datetime",
".",
"date",
"(",
"year",
",",
"1",
",",
"1",
")",
"diff",
"=",
"7",
"*",
"(",
"jan_one",
".",
"isoweekday",
"(",
")",
">",
... | 30.444444 | 15.777778 |
def start(self, key):
"""
Start a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and starts a concurrent operation on it.
"""
start_d = self._get_limiter(key).start()
self._cleanup_limiter(key)
return ... | [
"def",
"start",
"(",
"self",
",",
"key",
")",
":",
"start_d",
"=",
"self",
".",
"_get_limiter",
"(",
"key",
")",
".",
"start",
"(",
")",
"self",
".",
"_cleanup_limiter",
"(",
"key",
")",
"return",
"start_d"
] | 31.8 | 14.8 |
def poke(library, session, address, width, data):
"""Writes an 8, 16 or 32-bit value from the specified address.
Corresponds to viPoke* functions of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source ... | [
"def",
"poke",
"(",
"library",
",",
"session",
",",
"address",
",",
"width",
",",
"data",
")",
":",
"if",
"width",
"==",
"8",
":",
"return",
"poke_8",
"(",
"library",
",",
"session",
",",
"address",
",",
"data",
")",
"elif",
"width",
"==",
"16",
":... | 38 | 18.318182 |
def analyze(problem, Y, M=4, print_to_console=False, seed=None):
"""Performs the Fourier Amplitude Sensitivity Test (FAST) on model outputs.
Returns a dictionary with keys 'S1' and 'ST', where each entry is a list of
size D (the number of parameters) containing the indices in the same order
as the... | [
"def",
"analyze",
"(",
"problem",
",",
"Y",
",",
"M",
"=",
"4",
",",
"print_to_console",
"=",
"False",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"D",
"=",
"problem",
"[",
"'num_vars... | 34.75 | 21.894737 |
def chown(self, uid, gid):
"""
Change the owner (C{uid}) and group (C{gid}) of this file. As with
python's C{os.chown} function, you must pass both arguments, so if you
only want to change one, use L{stat} first to retrieve the current
owner and group.
@param uid: new o... | [
"def",
"chown",
"(",
"self",
",",
"uid",
",",
"gid",
")",
":",
"self",
".",
"sftp",
".",
"_log",
"(",
"DEBUG",
",",
"'chown(%s, %r, %r)'",
"%",
"(",
"hexlify",
"(",
"self",
".",
"handle",
")",
",",
"uid",
",",
"gid",
")",
")",
"attr",
"=",
"SFTPA... | 39.25 | 18.875 |
def hello_user(api_client):
"""Use an authorized client to fetch and print profile information.
Parameters
api_client (UberRidesClient)
An UberRidesClient with OAuth 2.0 credentials.
"""
try:
response = api_client.get_user_profile()
except (ClientError, ServerError) as... | [
"def",
"hello_user",
"(",
"api_client",
")",
":",
"try",
":",
"response",
"=",
"api_client",
".",
"get_user_profile",
"(",
")",
"except",
"(",
"ClientError",
",",
"ServerError",
")",
"as",
"error",
":",
"fail_print",
"(",
"error",
")",
"return",
"else",
":... | 29.176471 | 17.588235 |
def get(self, service_id, insert_defaults=None):
"""
Get a service.
Args:
service_id (str): The ID of the service.
insert_defaults (boolean): If true, default values will be merged
into the output.
Returns:
:py:class:`Service`: The se... | [
"def",
"get",
"(",
"self",
",",
"service_id",
",",
"insert_defaults",
"=",
"None",
")",
":",
"return",
"self",
".",
"prepare_model",
"(",
"self",
".",
"client",
".",
"api",
".",
"inspect_service",
"(",
"service_id",
",",
"insert_defaults",
")",
")"
] | 33.125 | 18.125 |
def _reduced_call(self, **params_to_override):
"""
Simplified version of PatternGenerator's __call__ method.
"""
p=param.ParamOverrides(self,params_to_override)
fn_result = self.function(p)
self._apply_mask(p,fn_result)
result = p.scale*fn_result+p.offset
... | [
"def",
"_reduced_call",
"(",
"self",
",",
"*",
"*",
"params_to_override",
")",
":",
"p",
"=",
"param",
".",
"ParamOverrides",
"(",
"self",
",",
"params_to_override",
")",
"fn_result",
"=",
"self",
".",
"function",
"(",
"p",
")",
"self",
".",
"_apply_mask",... | 32.5 | 11.5 |
def frommembers(cls, members):
"""Series from iterable of member iterables."""
return cls.frombitsets(map(cls.BitSet.frommembers, members)) | [
"def",
"frommembers",
"(",
"cls",
",",
"members",
")",
":",
"return",
"cls",
".",
"frombitsets",
"(",
"map",
"(",
"cls",
".",
"BitSet",
".",
"frommembers",
",",
"members",
")",
")"
] | 51 | 12.666667 |
def _extract_cell(args, cell_body):
"""Implements the BigQuery extract magic used to extract query or table data to GCS.
The supported syntax is:
%bq extract <args>
Args:
args: the arguments following '%bigquery extract'.
"""
env = google.datalab.utils.commands.notebook_environment()
config = g... | [
"def",
"_extract_cell",
"(",
"args",
",",
"cell_body",
")",
":",
"env",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"notebook_environment",
"(",
")",
"config",
"=",
"google",
".",
"datalab",
".",
"utils",
".",
"commands",
".",
"par... | 46.630435 | 27.478261 |
def pin_chat_message(self, chat_id, message_id, disable_notification=False):
"""
Use this method to pin a message in a supergroup.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Returns True on success.
:param chat_id: In... | [
"def",
"pin_chat_message",
"(",
"self",
",",
"chat_id",
",",
"message_id",
",",
"disable_notification",
"=",
"False",
")",
":",
"return",
"apihelper",
".",
"pin_chat_message",
"(",
"self",
".",
"token",
",",
"chat_id",
",",
"message_id",
",",
"disable_notificati... | 60.384615 | 29.769231 |
def is_namedtuple(val):
"""
Use Duck Typing to check if val is a named tuple. Checks that val is of type tuple and contains
the attribute _fields which is defined for named tuples.
:param val: value to check type of
:return: True if val is a namedtuple
"""
val_type = type(val)
bases = va... | [
"def",
"is_namedtuple",
"(",
"val",
")",
":",
"val_type",
"=",
"type",
"(",
"val",
")",
"bases",
"=",
"val_type",
".",
"__bases__",
"if",
"len",
"(",
"bases",
")",
"!=",
"1",
"or",
"bases",
"[",
"0",
"]",
"!=",
"tuple",
":",
"return",
"False",
"fie... | 37.615385 | 12.692308 |
def get_stack_info():
'''Capture locals, module name, filename, and line number from the
stacktrace to provide the source of the assertion error and
formatted note.
'''
stack = traceback.walk_stack(sys._getframe().f_back)
# We want locals from the test definition (which always begins
# with... | [
"def",
"get_stack_info",
"(",
")",
":",
"stack",
"=",
"traceback",
".",
"walk_stack",
"(",
"sys",
".",
"_getframe",
"(",
")",
".",
"f_back",
")",
"# We want locals from the test definition (which always begins",
"# with 'test_' in unittest), which will be at a different",
"... | 42.894737 | 20.789474 |
def set_chime(self, sound, cycles=None):
"""
:param sound: a str, one of ["doorbell", "fur_elise", "doorbell_extended", "alert",
"william_tell", "rondo_alla_turca", "police_siren",
""evacuation", "beep_beep", "beep", "inactive... | [
"def",
"set_chime",
"(",
"self",
",",
"sound",
",",
"cycles",
"=",
"None",
")",
":",
"desired_state",
"=",
"{",
"\"activate_chime\"",
":",
"sound",
"}",
"if",
"cycles",
"is",
"not",
"None",
":",
"desired_state",
".",
"update",
"(",
"{",
"\"chime_cycles\"",... | 54.071429 | 21.5 |
def _create_mappings(self):
'Create the field type mapping.'
self.conn.indices.put_mapping(
index=self.index, doc_type=self.type,
timeout=60, request_timeout=60,
body={
self.type: {
'dynamic_templates': [{
'd... | [
"def",
"_create_mappings",
"(",
"self",
")",
":",
"self",
".",
"conn",
".",
"indices",
".",
"put_mapping",
"(",
"index",
"=",
"self",
".",
"index",
",",
"doc_type",
"=",
"self",
".",
"type",
",",
"timeout",
"=",
"60",
",",
"request_timeout",
"=",
"60",... | 42.033333 | 16.833333 |
def invalidate_token(self, body, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-invalidate-token.html>`_
:arg body: The token to invalidate
"""
if body in SKIP_IN_PATH:
raise ValueError("Empty value passed for a requi... | [
"def",
"invalidate_token",
"(",
"self",
",",
"body",
",",
"params",
"=",
"None",
")",
":",
"if",
"body",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"Empty value passed for a required argument 'body'.\"",
")",
"return",
"self",
".",
"transport",
".",
... | 42.090909 | 21.727273 |
def read_line(self):
"""
Interrupted respecting reader for stdin.
Raises EOFError if the end of stream has been reached
"""
try:
line = self.inp.readline().strip()
except KeyboardInterrupt:
raise EOFError()
# i3status sends EOF, or an em... | [
"def",
"read_line",
"(",
"self",
")",
":",
"try",
":",
"line",
"=",
"self",
".",
"inp",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"raise",
"EOFError",
"(",
")",
"# i3status sends EOF, or an empty line",
"if",
"n... | 23.9375 | 17.5625 |
def from_text(cls, text: str):
""" Construct an AnalysisGraph object from text, using Eidos to perform
machine reading. """
eidosProcessor = process_text(text)
return cls.from_statements(eidosProcessor.statements) | [
"def",
"from_text",
"(",
"cls",
",",
"text",
":",
"str",
")",
":",
"eidosProcessor",
"=",
"process_text",
"(",
"text",
")",
"return",
"cls",
".",
"from_statements",
"(",
"eidosProcessor",
".",
"statements",
")"
] | 40.166667 | 12.333333 |
def write(self, presets_path):
"""Write this preset to disk in JSON notation.
:param presets_path: the directory where the preset will be
written.
"""
if self.builtin:
raise TypeError("Cannot write built-in preset")
# Make dictio... | [
"def",
"write",
"(",
"self",
",",
"presets_path",
")",
":",
"if",
"self",
".",
"builtin",
":",
"raise",
"TypeError",
"(",
"\"Cannot write built-in preset\"",
")",
"# Make dictionaries of PresetDefaults values",
"odict",
"=",
"self",
".",
"opts",
".",
"dict",
"(",
... | 36.055556 | 19 |
def get(self, id):
"""Get a single group by ID.
:param str id: a group ID
:return: a group
:rtype: :class:`~groupy.api.groups.Group`
"""
url = utils.urljoin(self.url, id)
response = self.session.get(url)
return Group(self, **response.data) | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"utils",
".",
"urljoin",
"(",
"self",
".",
"url",
",",
"id",
")",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
"return",
"Group",
"(",
"self",
",",
"*",
"*",
... | 29.5 | 9.8 |
async def _load_message_field(self, reader, msg, field):
"""
Loads message field from the reader. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:return:
"""
... | [
"async",
"def",
"_load_message_field",
"(",
"self",
",",
"reader",
",",
"msg",
",",
"field",
")",
":",
"fname",
",",
"ftype",
",",
"params",
"=",
"field",
"[",
"0",
"]",
",",
"field",
"[",
"1",
"]",
",",
"field",
"[",
"2",
":",
"]",
"await",
"sel... | 36.5 | 21.666667 |
def add(self, properties):
"""
Add a faked Port resource.
Parameters:
properties (dict):
Resource properties.
Special handling and requirements for certain properties:
* 'element-id' will be auto-generated with a unique value across
... | [
"def",
"add",
"(",
"self",
",",
"properties",
")",
":",
"new_port",
"=",
"super",
"(",
"FakedPortManager",
",",
"self",
")",
".",
"add",
"(",
"properties",
")",
"adapter",
"=",
"self",
".",
"parent",
"if",
"'network-port-uris'",
"in",
"adapter",
".",
"pr... | 38.71875 | 23.15625 |
def hacking_python3x_metaclass(logical_line, noqa):
r"""Check for metaclass to be Python 3.x compatible.
Okay: @six.add_metaclass(Meta)\nclass Foo(object):\n pass
Okay: @six.with_metaclass(Meta)\nclass Foo(object):\n pass
Okay: class Foo(object):\n '''docstring\n\n __metaclass__ = Meta\n'''... | [
"def",
"hacking_python3x_metaclass",
"(",
"logical_line",
",",
"noqa",
")",
":",
"if",
"noqa",
":",
"return",
"split_line",
"=",
"logical_line",
".",
"split",
"(",
")",
"if",
"(",
"len",
"(",
"split_line",
")",
">",
"2",
"and",
"split_line",
"[",
"0",
"]... | 47.8 | 19.45 |
def _expand_list(names):
""" Do a wildchar name expansion of object names in a list and return expanded list.
The items are expected to exist as this is used for copy sources or delete targets.
Currently we support wildchars in the key name only.
"""
if names is None:
names = []
elif isinstance(na... | [
"def",
"_expand_list",
"(",
"names",
")",
":",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"names",
",",
"basestring",
")",
":",
"names",
"=",
"[",
"names",
"]",
"results",
"=",
"[",
"]",
"# The expanded list.",... | 36.754717 | 19.90566 |
def _module_imports(ctx: GeneratorContext) -> Iterable[ast.Import]:
"""Generate the Python Import AST node for importing all required
language support modules."""
# Yield `import basilisp` so code attempting to call fully qualified
# `basilisp.lang...` modules don't result in compiler errors
yield a... | [
"def",
"_module_imports",
"(",
"ctx",
":",
"GeneratorContext",
")",
"->",
"Iterable",
"[",
"ast",
".",
"Import",
"]",
":",
"# Yield `import basilisp` so code attempting to call fully qualified",
"# `basilisp.lang...` modules don't result in compiler errors",
"yield",
"ast",
"."... | 54.2 | 17.3 |
def do_dice_roll():
"""
Roll n-sided dice and return each result and the total
"""
options = get_options()
dice = Dice(options.sides)
rolls = [dice.roll() for n in range(options.number)]
for roll in rolls:
print('rolled', roll)
if options.number > 1:
print('total', sum(rolls)) | [
"def",
"do_dice_roll",
"(",
")",
":",
"options",
"=",
"get_options",
"(",
")",
"dice",
"=",
"Dice",
"(",
"options",
".",
"sides",
")",
"rolls",
"=",
"[",
"dice",
".",
"roll",
"(",
")",
"for",
"n",
"in",
"range",
"(",
"options",
".",
"number",
")",
... | 25.363636 | 13.181818 |
def sanitized_name(self):
"""Sanitized name of the agent, used for file and directory creation.
"""
a = re.split("[:/]", self.name)
return "_".join([i for i in a if len(i) > 0]) | [
"def",
"sanitized_name",
"(",
"self",
")",
":",
"a",
"=",
"re",
".",
"split",
"(",
"\"[:/]\"",
",",
"self",
".",
"name",
")",
"return",
"\"_\"",
".",
"join",
"(",
"[",
"i",
"for",
"i",
"in",
"a",
"if",
"len",
"(",
"i",
")",
">",
"0",
"]",
")"... | 41 | 5.8 |
def graph_dot(self):
"""
Export a graph of the data in dot format.
"""
default_graphviz_template = """
digraph role_dependencies {
size="%size"
dpi=%dpi
ratio="fill"
landscape=false
rankdir="BT";
node [shape = "box",
style = ... | [
"def",
"graph_dot",
"(",
"self",
")",
":",
"default_graphviz_template",
"=",
"\"\"\"\ndigraph role_dependencies {\n size=\"%size\"\n dpi=%dpi\n ratio=\"fill\"\n landscape=false\n rankdir=\"BT\";\n\n node [shape = \"box\",\n style = \"rounded,fil... | 34.625 | 21.15 |
def action(self, action_id, **kwargs):
"""Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to... | [
"def",
"action",
"(",
"self",
",",
"action_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'method'",
"in",
"kwargs",
":",
"method",
"=",
"kwargs",
"[",
"'method'",
"]",
"del",
"kwargs",
"[",
"'method'",
"]",
"else",
":",
"method",
"=",
"'GET'",
"if",... | 47.4 | 15.933333 |
def send(self, packet, interfaces=None):
"""write packet to given interfaces, default is broadcast to all interfaces"""
interfaces = interfaces or self.interfaces # default to all interfaces
interfaces = interfaces if hasattr(interfaces, '__iter__') else [interfaces]
for interface in i... | [
"def",
"send",
"(",
"self",
",",
"packet",
",",
"interfaces",
"=",
"None",
")",
":",
"interfaces",
"=",
"interfaces",
"or",
"self",
".",
"interfaces",
"# default to all interfaces",
"interfaces",
"=",
"interfaces",
"if",
"hasattr",
"(",
"interfaces",
",",
"'__... | 59.666667 | 27.5 |
def _check_dataframe(dv=None, between=None, within=None, subject=None,
effects=None, data=None):
"""Check dataframe"""
# Check that data is a dataframe
if not isinstance(data, pd.DataFrame):
raise ValueError('Data must be a pandas dataframe.')
# Check that both dv and data a... | [
"def",
"_check_dataframe",
"(",
"dv",
"=",
"None",
",",
"between",
"=",
"None",
",",
"within",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"effects",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"# Check that data is a dataframe",
"if",
"not",
"is... | 54.032258 | 15.677419 |
def disqus_dev(context):
"""
Return the HTML/js code to enable DISQUS comments on a local
development server if settings.DEBUG is True.
"""
if settings.DEBUG:
disqus_url = '//{}{}'.format(
Site.objects.get_current().domain,
context['request'].path
)
... | [
"def",
"disqus_dev",
"(",
"context",
")",
":",
"if",
"settings",
".",
"DEBUG",
":",
"disqus_url",
"=",
"'//{}{}'",
".",
"format",
"(",
"Site",
".",
"objects",
".",
"get_current",
"(",
")",
".",
"domain",
",",
"context",
"[",
"'request'",
"]",
".",
"pat... | 23.6 | 17.333333 |
def make_field_objects(field_data, names):
# type: (List[Dict[Text, Text]], Names) -> List[Field]
"""We're going to need to make message parameters too."""
field_objects = []
field_names = [] # type: List[Text]
for field in field_data:
if hasattr(field, 'get') and ca... | [
"def",
"make_field_objects",
"(",
"field_data",
",",
"names",
")",
":",
"# type: (List[Dict[Text, Text]], Names) -> List[Field]",
"field_objects",
"=",
"[",
"]",
"field_names",
"=",
"[",
"]",
"# type: List[Text]",
"for",
"field",
"in",
"field_data",
":",
"if",
"hasatt... | 46.225806 | 15.612903 |
def build_columns(self, X, verbose=False):
"""construct the model matrix columns for the term
Parameters
----------
X : array-like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
-------
scipy sparse arr... | [
"def",
"build_columns",
"(",
"self",
",",
"X",
",",
"verbose",
"=",
"False",
")",
":",
"return",
"sp",
".",
"sparse",
".",
"csc_matrix",
"(",
"np",
".",
"ones",
"(",
"(",
"len",
"(",
"X",
")",
",",
"1",
")",
")",
")"
] | 24.3125 | 17.375 |
async def get_prefix(self, message):
"""|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
... | [
"async",
"def",
"get_prefix",
"(",
"self",
",",
"message",
")",
":",
"prefix",
"=",
"ret",
"=",
"self",
".",
"command_prefix",
"if",
"callable",
"(",
"prefix",
")",
":",
"ret",
"=",
"await",
"discord",
".",
"utils",
".",
"maybe_coroutine",
"(",
"prefix",... | 34.459459 | 23.216216 |
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'par... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'paral... | 33.763441 | 21.870968 |
def _compute_value(self, pkt):
# type: (packet.Packet) -> int
""" Computes the value of this field based on the provided packet and
the length_of field and the adjust callback
@param packet.Packet pkt: the packet from which is computed this field value. # noqa: E501
@return int... | [
"def",
"_compute_value",
"(",
"self",
",",
"pkt",
")",
":",
"# type: (packet.Packet) -> int",
"fld",
",",
"fval",
"=",
"pkt",
".",
"getfield_and_val",
"(",
"self",
".",
"_length_of",
")",
"val",
"=",
"fld",
".",
"i2len",
"(",
"pkt",
",",
"fval",
")",
"re... | 42.882353 | 16.764706 |
def distance_to(self, other):
"""Return Euclidian distance between self and other Firefly"""
return np.linalg.norm(self.position-other.position) | [
"def",
"distance_to",
"(",
"self",
",",
"other",
")",
":",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"position",
"-",
"other",
".",
"position",
")"
] | 52.666667 | 10 |
def multi_get(self, urls, query_params=None, to_json=True):
"""Issue multiple GET requests.
Args:
urls - A string URL or list of string URLs
query_params - None, a dict, or a list of dicts representing the query params
to_json - A boolean, should the responses be ret... | [
"def",
"multi_get",
"(",
"self",
",",
"urls",
",",
"query_params",
"=",
"None",
",",
"to_json",
"=",
"True",
")",
":",
"return",
"self",
".",
"_multi_request",
"(",
"MultiRequest",
".",
"_VERB_GET",
",",
"urls",
",",
"query_params",
",",
"data",
"=",
"No... | 41.625 | 22.625 |
def Sample(self, task, status):
"""Takes a sample of the status of a task for profiling.
Args:
task (Task): a task.
status (str): status.
"""
sample_time = time.time()
sample = '{0:f}\t{1:s}\t{2:s}\n'.format(
sample_time, task.identifier, status)
self._WritesString(sample) | [
"def",
"Sample",
"(",
"self",
",",
"task",
",",
"status",
")",
":",
"sample_time",
"=",
"time",
".",
"time",
"(",
")",
"sample",
"=",
"'{0:f}\\t{1:s}\\t{2:s}\\n'",
".",
"format",
"(",
"sample_time",
",",
"task",
".",
"identifier",
",",
"status",
")",
"se... | 28 | 12.454545 |
def request_encode_body(self, method, url, fields=None, headers=None,
encode_multipart=True, multipart_boundary=None,
**urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for reques... | [
"def",
"request_encode_body",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"encode_multipart",
"=",
"True",
",",
"multipart_boundary",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"if",
"hea... | 43.916667 | 26.216667 |
def non_decreasing(values):
"""True if values are not decreasing."""
return all(x <= y for x, y in zip(values, values[1:])) | [
"def",
"non_decreasing",
"(",
"values",
")",
":",
"return",
"all",
"(",
"x",
"<=",
"y",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"values",
",",
"values",
"[",
"1",
":",
"]",
")",
")"
] | 43 | 10.333333 |
def get_cli_multi_parser(funcs, skip_first=0):
"""makes a parser for parsing cli arguments for `func`.
:param list funcs: the function the parser will parse
:param int skip_first: skip this many first arguments of the func
"""
parser = ArgumentParser(description='which subcommand do you want?')
... | [
"def",
"get_cli_multi_parser",
"(",
"funcs",
",",
"skip_first",
"=",
"0",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'which subcommand do you want?'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
"'subcomman... | 42.4 | 18.933333 |
def delete(table, chain=None, position=None, rule=None, family='ipv4'):
'''
Delete a rule from the specified table/chain, specifying either the rule
in its entirety, or the rule's position in the chain.
This function accepts a rule in a standard iptables command format,
starting with the ch... | [
"def",
"delete",
"(",
"table",
",",
"chain",
"=",
"None",
",",
"position",
"=",
"None",
",",
"rule",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
")",
":",
"if",
"position",
"and",
"rule",
":",
"return",
"'Error: Only specify a position or a rule, not both'",
... | 34.888889 | 25.833333 |
def __replace_names(sentence, counts):
"""Lets find and replace all instances of #NAME
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NAME') != -1:
sentence = sentence.replace('#NAME', str(__get_name(counts)), 1)
if sentence.fin... | [
"def",
"__replace_names",
"(",
"sentence",
",",
"counts",
")",
":",
"if",
"sentence",
"is",
"not",
"None",
":",
"while",
"sentence",
".",
"find",
"(",
"'#NAME'",
")",
"!=",
"-",
"1",
":",
"sentence",
"=",
"sentence",
".",
"replace",
"(",
"'#NAME'",
","... | 25.75 | 18.25 |
def encode_varint(v, f):
"""Encode integer `v` to file `f`.
Parameters
----------
v: int
Integer v >= 0.
f: file
Object containing a write method.
Returns
-------
int
Number of bytes written.
"""
assert v >= 0
num_bytes = 0
while True:
b... | [
"def",
"encode_varint",
"(",
"v",
",",
"f",
")",
":",
"assert",
"v",
">=",
"0",
"num_bytes",
"=",
"0",
"while",
"True",
":",
"b",
"=",
"v",
"%",
"0x80",
"v",
"=",
"v",
"//",
"0x80",
"if",
"v",
">",
"0",
":",
"b",
"=",
"b",
"|",
"0x80",
"f",... | 15.125 | 23.84375 |
def _notification_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle notification statement."""
self._handle_child(NotificationNode(), stmt, sctx) | [
"def",
"_notification_stmt",
"(",
"self",
",",
"stmt",
":",
"Statement",
",",
"sctx",
":",
"SchemaContext",
")",
"->",
"None",
":",
"self",
".",
"_handle_child",
"(",
"NotificationNode",
"(",
")",
",",
"stmt",
",",
"sctx",
")"
] | 59 | 17.666667 |
def _lmder1_kowalik_osborne():
"""Kowalik & Osborne function (lmder1 test #9)"""
v = np.asfarray([4, 2, 1, 0.5, 0.25, 0.167, 0.125, 0.1, 0.0833, 0.0714, 0.0625])
y2 = np.asfarray([0.1957, 0.1947, 0.1735, 0.16, 0.0844, 0.0627, 0.0456,
0.0342, 0.0323, 0.0235, 0.0246])
def func(param... | [
"def",
"_lmder1_kowalik_osborne",
"(",
")",
":",
"v",
"=",
"np",
".",
"asfarray",
"(",
"[",
"4",
",",
"2",
",",
"1",
",",
"0.5",
",",
"0.25",
",",
"0.167",
",",
"0.125",
",",
"0.1",
",",
"0.0833",
",",
"0.0714",
",",
"0.0625",
"]",
")",
"y2",
"... | 42 | 18.448276 |
def getByteStatistic(self, wanInterfaceId=1, timeout=1):
"""Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: a tuple of two ... | [
"def",
"getByteStatistic",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getByteStatistic\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
... | 50.0625 | 25.6875 |
def add_papyrus_handler(self, route_name_prefix, base_url, handler):
""" Add a Papyrus handler, i.e. a handler defining the MapFish
HTTP interface.
Example::
import papyrus
config.include(papyrus)
config.add_papyrus_handler(
'spots', '/spots', 'mypackage.handlers.SpotHa... | [
"def",
"add_papyrus_handler",
"(",
"self",
",",
"route_name_prefix",
",",
"base_url",
",",
"handler",
")",
":",
"route_name",
"=",
"route_name_prefix",
"+",
"'_read_many'",
"self",
".",
"add_handler",
"(",
"route_name",
",",
"base_url",
",",
"handler",
",",
"act... | 40.425 | 19.1 |
def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
"""
Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
"""
if root2:
if not drv2 and drv:
return drv, root2, [drv +... | [
"def",
"join_parsed_parts",
"(",
"self",
",",
"drv",
",",
"root",
",",
"parts",
",",
"drv2",
",",
"root2",
",",
"parts2",
")",
":",
"if",
"root2",
":",
"if",
"not",
"drv2",
"and",
"drv",
":",
"return",
"drv",
",",
"root2",
",",
"[",
"drv",
"+",
"... | 43.0625 | 17.4375 |
def get_sensor_data(self):
"""Get sensor reading objects
Iterates sensor reading objects pertaining to the currently
managed BMC.
:returns: Iterator of sdr.SensorReading objects
"""
self.init_sdr()
for sensor in self._sdr.get_sensor_numbers():
rsp = ... | [
"def",
"get_sensor_data",
"(",
"self",
")",
":",
"self",
".",
"init_sdr",
"(",
")",
"for",
"sensor",
"in",
"self",
".",
"_sdr",
".",
"get_sensor_numbers",
"(",
")",
":",
"rsp",
"=",
"self",
".",
"raw_command",
"(",
"command",
"=",
"0x2d",
",",
"netfn",... | 39.368421 | 20.526316 |
def quantile_normalize(matrix, inplace=False, target=None):
"""Quantile normalization, allowing for missing values (NaN).
In case of nan values, this implementation will calculate evenly
distributed quantiles and fill in the missing data with those values.
Quantile normalization is then performed on th... | [
"def",
"quantile_normalize",
"(",
"matrix",
",",
"inplace",
"=",
"False",
",",
"target",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"matrix",
",",
"ExpMatrix",
")",
"assert",
"isinstance",
"(",
"inplace",
",",
"bool",
")",
"if",
"target",
"is",
... | 32.105263 | 20.210526 |
def delete(self, user: str) -> None:
"""Remove user."""
data = {
'action': 'remove',
'user': user
}
self._request('post', URL, data=data) | [
"def",
"delete",
"(",
"self",
",",
"user",
":",
"str",
")",
"->",
"None",
":",
"data",
"=",
"{",
"'action'",
":",
"'remove'",
",",
"'user'",
":",
"user",
"}",
"self",
".",
"_request",
"(",
"'post'",
",",
"URL",
",",
"data",
"=",
"data",
")"
] | 23.375 | 16.125 |
def sample(net: BayesNet,
sample_from: Iterable[Vertex],
sampling_algorithm: PosteriorSamplingAlgorithm = None,
draws: int = 500,
drop: int = 0,
down_sample_interval: int = 1,
plot: bool = False,
ax: Any = None) -> sample_types:
"""
:p... | [
"def",
"sample",
"(",
"net",
":",
"BayesNet",
",",
"sample_from",
":",
"Iterable",
"[",
"Vertex",
"]",
",",
"sampling_algorithm",
":",
"PosteriorSamplingAlgorithm",
"=",
"None",
",",
"draws",
":",
"int",
"=",
"500",
",",
"drop",
":",
"int",
"=",
"0",
","... | 51.410714 | 32.803571 |
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which is returned by the daemon.
Args:
command (string): The type of payload this should ... | [
"def",
"command_factory",
"(",
"command",
")",
":",
"def",
"communicate",
"(",
"body",
"=",
"{",
"}",
",",
"root_dir",
"=",
"None",
")",
":",
"\"\"\"Communicate with the daemon.\n\n This function sends a payload to the daemon and returns the unpickled\n object sen... | 37.769231 | 21.512821 |
def fetch(self):
"""
Fetch a CallSummaryInstance
:returns: Fetched CallSummaryInstance
:rtype: twilio.rest.insights.v1.summary.CallSummaryInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
par... | [
"def",
"fetch",
"(",
"self",
")",
":",
"params",
"=",
"values",
".",
"of",
"(",
"{",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"fetch",
"(",
"'GET'",
",",
"self",
".",
"_uri",
",",
"params",
"=",
"params",
",",
")",
"return",
"CallS... | 26.5625 | 20.9375 |
def convert_tkinter_size_to_Wx(size):
"""
Converts size in characters to size in pixels
:param size: size in characters, rows
:return: size in pixels, pixels
"""
qtsize = size
if size[1] is not None and size[1] < DEFAULT_PIXEL_TO_CHARS_CUTOFF: # change from character based size to pi... | [
"def",
"convert_tkinter_size_to_Wx",
"(",
"size",
")",
":",
"qtsize",
"=",
"size",
"if",
"size",
"[",
"1",
"]",
"is",
"not",
"None",
"and",
"size",
"[",
"1",
"]",
"<",
"DEFAULT_PIXEL_TO_CHARS_CUTOFF",
":",
"# change from character based size to pixels (roughly)",
... | 44.7 | 22.1 |
def run_spec(spec,
benchmark_hosts,
result_hosts=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
action=None,
fail_if=None,
sample_mode='reservoir'):
"""Run a spec file, executing the statements on... | [
"def",
"run_spec",
"(",
"spec",
",",
"benchmark_hosts",
",",
"result_hosts",
"=",
"None",
",",
"output_fmt",
"=",
"None",
",",
"logfile_info",
"=",
"None",
",",
"logfile_result",
"=",
"None",
",",
"action",
"=",
"None",
",",
"fail_if",
"=",
"None",
",",
... | 32.107692 | 17.138462 |
def generate_content_encoding(self):
"""
Means decoding value when it's encoded by base64.
.. code-block:: python
{
'contentEncoding': 'base64',
}
"""
if self._definition['contentEncoding'] == 'base64':
with self.l('if isinsta... | [
"def",
"generate_content_encoding",
"(",
"self",
")",
":",
"if",
"self",
".",
"_definition",
"[",
"'contentEncoding'",
"]",
"==",
"'base64'",
":",
"with",
"self",
".",
"l",
"(",
"'if isinstance({variable}, str):'",
")",
":",
"with",
"self",
".",
"l",
"(",
"'... | 40.210526 | 19.263158 |
def last_month(self):
"""
Access the last_month
:returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList
:rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthList
"""
if self._last_month is None:
self._last_month = LastM... | [
"def",
"last_month",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_month",
"is",
"None",
":",
"self",
".",
"_last_month",
"=",
"LastMonthList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
... | 41.1 | 23.5 |
def close(self):
"""
Close the connection by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`.
"""
if not self.is_closed():
self._closing = True
# Let the ConnectionActor do the actual close operations.
# It will do t... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_closed",
"(",
")",
":",
"self",
".",
"_closing",
"=",
"True",
"# Let the ConnectionActor do the actual close operations.",
"# It will do the work on CloseOK",
"self",
".",
"sender",
".",
"send_Clos... | 38.695652 | 17.391304 |
def decode(code, encoding_type='default'):
"""Converts a string of morse code into English message
The encoded message can also be decoded using the same morse chart
backwards.
>>> code = '... --- ...'
>>> decode(code)
'SOS'
"""
reversed_morsetab = {symbol: character for character,... | [
"def",
"decode",
"(",
"code",
",",
"encoding_type",
"=",
"'default'",
")",
":",
"reversed_morsetab",
"=",
"{",
"symbol",
":",
"character",
"for",
"character",
",",
"symbol",
"in",
"list",
"(",
"getattr",
"(",
"encoding",
",",
"'morsetab'",
")",
".",
"items... | 33.020408 | 19.755102 |
def create(dataset, annotations=None, feature=None, model='darknet-yolo',
classes=None, batch_size=0, max_iterations=0, verbose=True,
**kwargs):
"""
Create a :class:`ObjectDetector` model.
Parameters
----------
dataset : SFrame
Input data. The columns named by the ``fe... | [
"def",
"create",
"(",
"dataset",
",",
"annotations",
"=",
"None",
",",
"feature",
"=",
"None",
",",
"model",
"=",
"'darknet-yolo'",
",",
"classes",
"=",
"None",
",",
"batch_size",
"=",
"0",
",",
"max_iterations",
"=",
"0",
",",
"verbose",
"=",
"True",
... | 41.057143 | 22.028571 |
def read_filtering_config (self):
"""
Read configuration options in section "filtering".
"""
section = "filtering"
if self.has_option(section, "ignorewarnings"):
self.config['ignorewarnings'] = [f.strip().lower() for f in \
self.get(section, 'ignorewa... | [
"def",
"read_filtering_config",
"(",
"self",
")",
":",
"section",
"=",
"\"filtering\"",
"if",
"self",
".",
"has_option",
"(",
"section",
",",
"\"ignorewarnings\"",
")",
":",
"self",
".",
"config",
"[",
"'ignorewarnings'",
"]",
"=",
"[",
"f",
".",
"strip",
... | 49.7 | 14.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.