text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_objective_banks(self):
"""Gets all ``ObjectiveBanks``.
In plenary mode, the returned list contains all known objective
banks or an error results. Otherwise, the returned list may
contain only those objective banks that are accessible through
this session.
return... | [
"def",
"get_objective_banks",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.BinLookupSession.get_bins_template",
"# NOTE: This implementation currently ignores plenary view",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"... | 45.230769 | 21.230769 |
def save(self, processes=1, manifests=False):
"""
save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set th... | [
"def",
"save",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"manifests",
"=",
"False",
")",
":",
"# Error checking",
"if",
"not",
"self",
".",
"path",
":",
"raise",
"BagError",
"(",
"\"Bag does not have a path.\"",
")",
"# Change working directory to bag director... | 41.736842 | 24.263158 |
def need_maintenance_response(request):
"""
Tells if the given request needs a maintenance response or not.
"""
try:
view_match = resolve(request.path)
view_func = view_match[0]
view_dict = view_func.__dict__
view_force_maintenance_mode_off = view_dict.get(
... | [
"def",
"need_maintenance_response",
"(",
"request",
")",
":",
"try",
":",
"view_match",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
"view_func",
"=",
"view_match",
"[",
"0",
"]",
"view_dict",
"=",
"view_func",
".",
"__dict__",
"view_force_maintenance_mode_... | 29.635036 | 21.065693 |
def AddImportCallbackBySuffix(path, callback):
"""Register import hook.
This function overrides the default import process. Then whenever a module
whose suffix matches path is imported, the callback will be invoked.
A module may be imported multiple times. Import event only means that the
Python code contai... | [
"def",
"AddImportCallbackBySuffix",
"(",
"path",
",",
"callback",
")",
":",
"def",
"RemoveCallback",
"(",
")",
":",
"# This is a read-if-del operation on _import_callbacks. Lock to prevent",
"# callbacks from being inserted just before the key is deleted. Thus, it",
"# must be locked a... | 40.44186 | 24.604651 |
def run(self):
"""Run robustness command."""
reaction = self._get_objective()
if not self._mm.has_reaction(reaction):
self.fail('Specified biomass reaction is not in model: {}'.format(
reaction))
varying_reaction = self._args.varying
if not self._mm.... | [
"def",
"run",
"(",
"self",
")",
":",
"reaction",
"=",
"self",
".",
"_get_objective",
"(",
")",
"if",
"not",
"self",
".",
"_mm",
".",
"has_reaction",
"(",
"reaction",
")",
":",
"self",
".",
"fail",
"(",
"'Specified biomass reaction is not in model: {}'",
".",... | 36.47619 | 19.654762 |
def amust(self, args, argv):
'''
Requires the User to provide a certain parameter
for the method to function properly.
Else, an Exception is raised.
args - (tuple) arguments you are looking for.
argv - (dict) arguments you have received and want to inspect.
'''
... | [
"def",
"amust",
"(",
"self",
",",
"args",
",",
"argv",
")",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"str",
"(",
"arg",
")",
"not",
"in",
"argv",
":",
"raise",
"KeyError",
"(",
"\"ArgMissing: \"",
"+",
"str",
"(",
"arg",
")",
"+",
"\" not passed... | 40.272727 | 17.181818 |
def create(cls, name, master_type, mgmt_ip, mgmt_network,
mgmt_interface=0,
log_server_ref=None, zone_ref=None,
domain_server_address=None, enable_gti=False,
enable_antivirus=False, comment=None):
"""
Create a Master Engine with management inte... | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"master_type",
",",
"mgmt_ip",
",",
"mgmt_network",
",",
"mgmt_interface",
"=",
"0",
",",
"log_server_ref",
"=",
"None",
",",
"zone_ref",
"=",
"None",
",",
"domain_server_address",
"=",
"None",
",",
"enable_gti"... | 44.555556 | 18.777778 |
def cvtToMag(rh, size):
"""
Convert a size value to a number with a magnitude appended.
Input:
Request Handle
Size bytes
Output:
Converted value with a magnitude
"""
rh.printSysLog("Enter generalUtils.cvtToMag")
mSize = ''
size = size / (1024 * 1024)
if size... | [
"def",
"cvtToMag",
"(",
"rh",
",",
"size",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter generalUtils.cvtToMag\"",
")",
"mSize",
"=",
"''",
"size",
"=",
"size",
"/",
"(",
"1024",
"*",
"1024",
")",
"if",
"size",
">",
"(",
"1024",
"*",
"5",
")",
... | 22.62963 | 21.962963 |
def freeze(name=None, force=False, **kwargs):
'''
Save the list of package and repos in a freeze file.
As this module is build on top of the pkg module, the user can
send extra attributes to the underlying pkg module via kwargs.
This function will call ``pkg.list_pkgs`` and ``pkg.list_repos``,
... | [
"def",
"freeze",
"(",
"name",
"=",
"None",
",",
"force",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"states_path",
"=",
"_states_path",
"(",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"states_path",
")",
"except",
"OSError",
"as",
"e",
":",
... | 31.681818 | 22.181818 |
def _options_to_dict(df):
"""Make a dictionary to print."""
kolums = ["k1", "k2", "value"]
d = df[kolums].values.tolist()
dc = {}
for x in d:
dc.setdefault(x[0], {})
dc[x[0]][x[1]] = x[2]
return dc | [
"def",
"_options_to_dict",
"(",
"df",
")",
":",
"kolums",
"=",
"[",
"\"k1\"",
",",
"\"k2\"",
",",
"\"value\"",
"]",
"d",
"=",
"df",
"[",
"kolums",
"]",
".",
"values",
".",
"tolist",
"(",
")",
"dc",
"=",
"{",
"}",
"for",
"x",
"in",
"d",
":",
"dc... | 25.444444 | 14.222222 |
def check_param_list_validity(self, param_list):
"""
Parameters
----------
param_list : list.
Contains four elements, each being a numpy array. Either all of the
arrays should be 1D or all of the arrays should be 2D. If 2D, the
arrays should have the s... | [
"def",
"check_param_list_validity",
"(",
"self",
",",
"param_list",
")",
":",
"if",
"param_list",
"is",
"None",
":",
"return",
"None",
"# Make sure there are four elements in param_list",
"check_type_and_size_of_param_list",
"(",
"param_list",
",",
"4",
")",
"# Make sure ... | 42.971429 | 24.514286 |
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all cir... | [
"def",
"send_head",
"(",
"self",
")",
":",
"offerredPath",
"=",
"self",
".",
"absFilePath",
"f",
"=",
"None",
"fName",
"=",
"_path",
".",
"basename",
"(",
"offerredPath",
")",
"urlPath",
"=",
"_U2",
".",
"unquote",
"(",
"self",
".",
"path",
")",
"if",
... | 32.97619 | 18.452381 |
def _set_fcoe_fabric_map(self, v, load=False):
"""
Setter method for fcoe_fabric_map, mapped from YANG variable /fcoe/fcoe_fabric_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fabric_map is considered as a private
method. Backends looking to populat... | [
"def",
"_set_fcoe_fabric_map",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 131.166667 | 64.333333 |
def _partition_all_internal(s, sep):
"""
Uses str.partition() to split every occurrence of sep in s. The returned list does not contain empty strings.
:param s: The string to split.
:param sep: A separator string.
:return: A list of parts split by sep
"""
parts = list(s.partition(sep))
... | [
"def",
"_partition_all_internal",
"(",
"s",
",",
"sep",
")",
":",
"parts",
"=",
"list",
"(",
"s",
".",
"partition",
"(",
"sep",
")",
")",
"# if sep found",
"if",
"parts",
"[",
"1",
"]",
"==",
"sep",
":",
"new_parts",
"=",
"partition_all",
"(",
"parts",... | 27.428571 | 17.238095 |
def main():
"""
Get arguments and call the execution function
"""
prog = sys.argv[0]
arg_parser = create_parser(prog)
opts = parse_cmdline(arg_parser)
print('Parameters: server=%s\n username=%s\n namespace=%s\n'
' classname=%s\n max_pull_size=%s\n use_pull=%s' %
(o... | [
"def",
"main",
"(",
")",
":",
"prog",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"arg_parser",
"=",
"create_parser",
"(",
"prog",
")",
"opts",
"=",
"parse_cmdline",
"(",
"arg_parser",
")",
"print",
"(",
"'Parameters: server=%s\\n username=%s\\n namespace=%s\\n'",
... | 32.341772 | 18.949367 |
def get_annotations(df,annotations,kind='lines',theme=None,**kwargs):
"""
Generates an annotations object
Parameters:
-----------
df : DataFrame
Original DataFrame of values
annotations : dict or list
Dictionary of annotations
{x_point : text}
or
List of Plotly annotations
"""
for key in ... | [
"def",
"get_annotations",
"(",
"df",
",",
"annotations",
",",
"kind",
"=",
"'lines'",
",",
"theme",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
"in",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
"not",
"i... | 25.144231 | 21.701923 |
def put(self, key, value):
'''Stores the object `value` named by `key`.
Args:
key: Key naming `value`
value: the object to store.
'''
path = self.object_path(key)
self._write_object(path, value) | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"path",
"=",
"self",
".",
"object_path",
"(",
"key",
")",
"self",
".",
"_write_object",
"(",
"path",
",",
"value",
")"
] | 24.333333 | 17.444444 |
def get_doc_type_mappings(self, doc_type):
"""Converts all doc_types' fields to .kibana"""
doc_fields_arr = []
found_score = False
for (key, val) in iteritems(doc_type):
# self.pr_dbg("\t\tfield: %s" % key)
# self.pr_dbg("\tval: %s" % val)
add_it = Fal... | [
"def",
"get_doc_type_mappings",
"(",
"self",
",",
"doc_type",
")",
":",
"doc_fields_arr",
"=",
"[",
"]",
"found_score",
"=",
"False",
"for",
"(",
"key",
",",
"val",
")",
"in",
"iteritems",
"(",
"doc_type",
")",
":",
"# self.pr_dbg(\"\\t\\tfield: %s\" % key)",
... | 43.032787 | 10.983607 |
def all_balances(currency, services=None, verbose=False, timeout=None):
"""
Get balances for passed in currency for all exchanges.
"""
balances = {}
if not services:
services = [
x(verbose=verbose, timeout=timeout)
for x in ExchangeUniverse.get_authenticated_services(... | [
"def",
"all_balances",
"(",
"currency",
",",
"services",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"timeout",
"=",
"None",
")",
":",
"balances",
"=",
"{",
"}",
"if",
"not",
"services",
":",
"services",
"=",
"[",
"x",
"(",
"verbose",
"=",
"verbo... | 30.727273 | 19.909091 |
def _tile(self, n):
""" Get the tile surrounding particle `n` """
zsc = np.array([1.0/self.zscale, 1, 1])
pos, rad = self.pos[n], self.rad[n]
pos = self._trans(pos)
return Tile(pos - zsc*rad, pos + zsc*rad).pad(self.support_pad) | [
"def",
"_tile",
"(",
"self",
",",
"n",
")",
":",
"zsc",
"=",
"np",
".",
"array",
"(",
"[",
"1.0",
"/",
"self",
".",
"zscale",
",",
"1",
",",
"1",
"]",
")",
"pos",
",",
"rad",
"=",
"self",
".",
"pos",
"[",
"n",
"]",
",",
"self",
".",
"rad"... | 43.833333 | 12 |
def push(self, **kwargs):
"""
Push build record results to Brew.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_functio... | [
"def",
"push",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"push_with_http_info",
"(",
"*",
"*",
"kwargs",
... | 37.76 | 14.56 |
def make_loci_and_stats(data, samples, ipyclient):
"""
Makes the .loci file from h5 data base. Iterates by optim loci at a
time and write to file. Also makes alleles file if requested.
"""
## start vcf progress bar
start = time.time()
printstr = " building loci/stats | {} | s7 |"
elaps... | [
"def",
"make_loci_and_stats",
"(",
"data",
",",
"samples",
",",
"ipyclient",
")",
":",
"## start vcf progress bar",
"start",
"=",
"time",
".",
"time",
"(",
")",
"printstr",
"=",
"\" building loci/stats | {} | s7 |\"",
"elapsed",
"=",
"datetime",
".",
"timedelta",
... | 36.225806 | 18.774194 |
def _features_with_strokes(self, hwr_obj):
"""Calculate the ConstantPointCoordinates features for the case of
a fixed number of strokes."""
x = []
img = Image.new('L', ((int(hwr_obj.get_width()*self.scaling_factor) + 2), (int(hwr_obj.get_height()*self.scaling_factor) + 2)), 'black')
... | [
"def",
"_features_with_strokes",
"(",
"self",
",",
"hwr_obj",
")",
":",
"x",
"=",
"[",
"]",
"img",
"=",
"Image",
".",
"new",
"(",
"'L'",
",",
"(",
"(",
"int",
"(",
"hwr_obj",
".",
"get_width",
"(",
")",
"*",
"self",
".",
"scaling_factor",
")",
"+",... | 56.296296 | 21 |
def update(self, request, *args, **kwargs):
"""Update a resource."""
# NOTE: Use the original method instead when support for locking is added:
# https://github.com/encode/django-rest-framework/issues/4675
# return super().update(request, *args, **kwargs)
with transaction.a... | [
"def",
"update",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# NOTE: Use the original method instead when support for locking is added:",
"# https://github.com/encode/django-rest-framework/issues/4675",
"# return super().update(request, ... | 54.285714 | 17.142857 |
def get_location_from_HDX_code(code, locations=None, configuration=None):
# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]
"""Get location from HDX location code
Args:
code (str): code for which to get location name
locations (Optional[List[D... | [
"def",
"get_location_from_HDX_code",
"(",
"code",
",",
"locations",
"=",
"None",
",",
"configuration",
"=",
"None",
")",
":",
"# type: (str, Optional[List[Dict]], Optional[Configuration]) -> Optional[str]",
"if",
"locations",
"is",
"None",
":",
"locations",
"=",
"Location... | 43.944444 | 24.222222 |
def build(cls, data, *args, **kwargs):
"""
Constructs a classification or regression tree in a single batch by
analyzing the given data.
"""
assert isinstance(data, Data)
if data.is_continuous_class:
fitness_func = gain_variance
else:
fitne... | [
"def",
"build",
"(",
"cls",
",",
"data",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"Data",
")",
"if",
"data",
".",
"is_continuous_class",
":",
"fitness_func",
"=",
"gain_variance",
"else",
":",
"fitn... | 30.681818 | 11.318182 |
def translate_resource_args(func):
"""Decorator that converts Issue and Project resources to their keys when used as arguments."""
@wraps(func)
def wrapper(*args, **kwargs):
"""
:type args: *Any
:type kwargs: **Any
:return: Any
"""
arg_list = []
for ar... | [
"def",
"translate_resource_args",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"\n :type args: *Any\n :type kwargs: **Any\n :return: Any\n \"\"\"",
"arg_li... | 28.578947 | 12.631579 |
def arrivalboard(self, stop_id, date=None, direction=None):
""" arrivalBoard """
date = date if date else datetime.now()
request_parameters = {
'id': stop_id,
'date': date.strftime(DATE_FORMAT),
'time': date.strftime(TIME_FORMAT)
}
if direction... | [
"def",
"arrivalboard",
"(",
"self",
",",
"stop_id",
",",
"date",
"=",
"None",
",",
"direction",
"=",
"None",
")",
":",
"date",
"=",
"date",
"if",
"date",
"else",
"datetime",
".",
"now",
"(",
")",
"request_parameters",
"=",
"{",
"'id'",
":",
"stop_id",
... | 37.357143 | 12.642857 |
def fcoe_fcoe_map_fcoe_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_map = ET.SubElement(fcoe, "fcoe-map")
fcoe_map_name = ET.SubElement(fcoe_map, "fc... | [
"def",
"fcoe_fcoe_map_fcoe_map_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"fcoe\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:m... | 42.818182 | 15.818182 |
def pklc_fovcatalog_objectinfo(
pklcdir,
fovcatalog,
fovcatalog_columns=[0,1,2,
6,7,
8,9,
10,11,
13,14,15,16,
17,18,19,
20,21],
... | [
"def",
"pklc_fovcatalog_objectinfo",
"(",
"pklcdir",
",",
"fovcatalog",
",",
"fovcatalog_columns",
"=",
"[",
"0",
",",
"1",
",",
"2",
",",
"6",
",",
"7",
",",
"8",
",",
"9",
",",
"10",
",",
"11",
",",
"13",
",",
"14",
",",
"15",
",",
"16",
",",
... | 34.978723 | 18.680851 |
def realForm(self, req, tag):
"""
Render L{liveForm}.
"""
self.liveForm.setFragmentParent(self)
return self.liveForm | [
"def",
"realForm",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"self",
".",
"liveForm",
".",
"setFragmentParent",
"(",
"self",
")",
"return",
"self",
".",
"liveForm"
] | 25.166667 | 6.833333 |
def _fill_missing_values(df, range_values, fill_value=0, fill_method=None):
"""
Will get the names of the index colums of df, obtain their ranges from
range_values dict and return a reindexed version of df with the given
range values.
:param df: pandas DataFrame
:param ... | [
"def",
"_fill_missing_values",
"(",
"df",
",",
"range_values",
",",
"fill_value",
"=",
"0",
",",
"fill_method",
"=",
"None",
")",
":",
"idx_colnames",
"=",
"df",
".",
"index",
".",
"names",
"idx_colranges",
"=",
"[",
"range_values",
"[",
"x",
"]",
"for",
... | 40 | 24.717949 |
def id_by_name(self, hostname):
"""
Returns the database ID for specified hostname.
The id might be useful as array index. 0 is unknown.
:arg hostname: Hostname to get ID from.
"""
addr = self._gethostbyname(hostname)
return self.id_by_addr(addr) | [
"def",
"id_by_name",
"(",
"self",
",",
"hostname",
")",
":",
"addr",
"=",
"self",
".",
"_gethostbyname",
"(",
"hostname",
")",
"return",
"self",
".",
"id_by_addr",
"(",
"addr",
")"
] | 32.777778 | 11 |
def last_modified_version(self, **kwargs):
""" Get the last modified version
"""
self.items(**kwargs)
return int(self.request.headers.get("last-modified-version", 0)) | [
"def",
"last_modified_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"items",
"(",
"*",
"*",
"kwargs",
")",
"return",
"int",
"(",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"\"last-modified-version\"",
",",
"0",
")... | 38.8 | 9.2 |
def add_keywords_from_list(self, keyword_list):
"""To add keywords from a list
Args:
keyword_list (list(str)): List of keywords to add
Examples:
>>> keyword_processor.add_keywords_from_list(["java", "python"]})
Raises:
AttributeError: If `keyword_lis... | [
"def",
"add_keywords_from_list",
"(",
"self",
",",
"keyword_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"keyword_list",
",",
"list",
")",
":",
"raise",
"AttributeError",
"(",
"\"keyword_list should be a list\"",
")",
"for",
"keyword",
"in",
"keyword_list",
":... | 30.764706 | 21.058824 |
def genl_register(ops):
"""Register Generic Netlink family backed cache.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241
Same as genl_register_family() but additionally registers the specified cache operations using
nl_cache_mngt_register() and associates it with the Generic Net... | [
"def",
"genl_register",
"(",
"ops",
")",
":",
"if",
"ops",
".",
"co_protocol",
"!=",
"NETLINK_GENERIC",
":",
"return",
"-",
"NLE_PROTO_MISMATCH",
"if",
"ops",
".",
"co_hdrsize",
"<",
"GENL_HDRSIZE",
"(",
"0",
")",
":",
"return",
"-",
"NLE_INVAL",
"if",
"op... | 32.709677 | 19.580645 |
def insert_files(self, rootpath, directoryInFilter=None, directoryExFilter=None, compileInFilter=None, compileExFilter=None, contentInFilter=None, contentExFilter=None):
"""
Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters.
:param s... | [
"def",
"insert_files",
"(",
"self",
",",
"rootpath",
",",
"directoryInFilter",
"=",
"None",
",",
"directoryExFilter",
"=",
"None",
",",
"compileInFilter",
"=",
"None",
",",
"compileExFilter",
"=",
"None",
",",
"contentInFilter",
"=",
"None",
",",
"contentExFilte... | 72.688889 | 47.888889 |
def _load_h5(file, devices, channels):
"""
Function used for reading .h5 files generated by OpenSignals.
----------
Parameters
----------
file : file path.
File Path.
devices : list ["mac_address_1" <str>, "mac_address_2" <str>...]
List of devices selected by the user.
... | [
"def",
"_load_h5",
"(",
"file",
",",
"devices",
",",
"channels",
")",
":",
"# %%%%%%%%%%%%%%%%%%%%%%%%%%%% Creation of h5py object %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%",
"h5_object",
"=",
"h5py",
".",
"File",
"(",
"file",
")",
"# %%%%%%%%%%%%%%%%%%%%%%%%% Data of the selec... | 35.142857 | 25.190476 |
def baba_panel_plot(
ttree,
tests,
boots,
show_tip_labels=True,
show_test_labels=True,
use_edge_lengths=False,
collapse_outgroup=False,
pct_tree_x=0.4,
pct_tree_y=0.2,
alpha=3.0,
*args,
**kwargs):
"""
signature...
"""
## create Panel plot object an... | [
"def",
"baba_panel_plot",
"(",
"ttree",
",",
"tests",
",",
"boots",
",",
"show_tip_labels",
"=",
"True",
",",
"show_test_labels",
"=",
"True",
",",
"use_edge_lengths",
"=",
"False",
",",
"collapse_outgroup",
"=",
"False",
",",
"pct_tree_x",
"=",
"0.4",
",",
... | 29.390244 | 19.829268 |
def get_table_list(dbconn):
"""
Get a list of tables that exist in dbconn
:param dbconn: database connection
:return: List of table names
"""
cur = dbconn.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
try:
return [item[0] for item in cur.fetchall()]
... | [
"def",
"get_table_list",
"(",
"dbconn",
")",
":",
"cur",
"=",
"dbconn",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"SELECT name FROM sqlite_master WHERE type='table';\"",
")",
"try",
":",
"return",
"[",
"item",
"[",
"0",
"]",
"for",
"item",
"in",... | 30.666667 | 11.333333 |
def load_progress(self, resume_step):
""" load_progress: loads progress from restoration file
Args: resume_step (str): step at which to resume session
Returns: manager with progress from step
"""
resume_step = Status[resume_step]
progress_path = self.get_restore_p... | [
"def",
"load_progress",
"(",
"self",
",",
"resume_step",
")",
":",
"resume_step",
"=",
"Status",
"[",
"resume_step",
"]",
"progress_path",
"=",
"self",
".",
"get_restore_path",
"(",
"resume_step",
")",
"# If progress is corrupted, revert to step before",
"while",
"not... | 44.961538 | 17.884615 |
def ParseOptions(self, options):
"""Parses the options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The extraction options are dependent on the data location.
helpers_manager.ArgumentHelperManager.ParseOptio... | [
"def",
"ParseOptions",
"(",
"self",
",",
"options",
")",
":",
"# The extraction options are dependent on the data location.",
"helpers_manager",
".",
"ArgumentHelperManager",
".",
"ParseOptions",
"(",
"options",
",",
"self",
",",
"names",
"=",
"[",
"'data_location'",
"]... | 35.423077 | 22.769231 |
def add_atmost(self, lits, k, no_return=True):
"""
This method is responsible for adding a new *native* AtMostK (see
:mod:`pysat.card`) constraint into :class:`Minicard`.
**Note that none of the other solvers supports native AtMostK
constraints**.
An... | [
"def",
"add_atmost",
"(",
"self",
",",
"lits",
",",
"k",
",",
"no_return",
"=",
"True",
")",
":",
"if",
"self",
".",
"solver",
":",
"res",
"=",
"self",
".",
"solver",
".",
"add_atmost",
"(",
"lits",
",",
"k",
",",
"no_return",
")",
"if",
"not",
"... | 37.297297 | 24.108108 |
def dependencies(self):
"""
Returns the dependencies of the package.
:return: the list of Dependency objects
:rtype: list of Dependency
"""
result = []
dependencies = javabridge.get_collection_wrapper(
javabridge.call(self.jobject, "getDependencies", ... | [
"def",
"dependencies",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"dependencies",
"=",
"javabridge",
".",
"get_collection_wrapper",
"(",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"getDependencies\"",
",",
"\"()Ljava/util/List;\"",
")",
... | 34 | 14.461538 |
def handle_services(changeset):
"""Populate the change set with addCharm and deploy changes."""
charms = {}
for service_name, service in sorted(changeset.bundle['services'].items()):
# Add the addCharm record if one hasn't been added yet.
if service['charm'] not in charms:
record... | [
"def",
"handle_services",
"(",
"changeset",
")",
":",
"charms",
"=",
"{",
"}",
"for",
"service_name",
",",
"service",
"in",
"sorted",
"(",
"changeset",
".",
"bundle",
"[",
"'services'",
"]",
".",
"items",
"(",
")",
")",
":",
"# Add the addCharm record if one... | 35.925926 | 14.981481 |
def parse_const_argument(lexer: Lexer) -> ArgumentNode:
"""Argument[Const]: Name : Value[?Const]"""
start = lexer.token
return ArgumentNode(
name=parse_name(lexer),
value=expect_token(lexer, TokenKind.COLON) and parse_const_value(lexer),
loc=loc(lexer, start),
) | [
"def",
"parse_const_argument",
"(",
"lexer",
":",
"Lexer",
")",
"->",
"ArgumentNode",
":",
"start",
"=",
"lexer",
".",
"token",
"return",
"ArgumentNode",
"(",
"name",
"=",
"parse_name",
"(",
"lexer",
")",
",",
"value",
"=",
"expect_token",
"(",
"lexer",
",... | 36.875 | 17.75 |
def log_error(self, e):
"""
Print errors. Stop travis-ci from leaking api keys
:param e: The error
:return: None
"""
if not environ.get('CI'):
self.log_function(e)
if hasattr(e, 'response') and hasattr(e.response, 'text'):
... | [
"def",
"log_error",
"(",
"self",
",",
"e",
")",
":",
"if",
"not",
"environ",
".",
"get",
"(",
"'CI'",
")",
":",
"self",
".",
"log_function",
"(",
"e",
")",
"if",
"hasattr",
"(",
"e",
",",
"'response'",
")",
"and",
"hasattr",
"(",
"e",
".",
"respo... | 28.916667 | 16.416667 |
def color(cls, value):
"""task value/score color"""
index = bisect(cls.breakpoints, value)
return colors.fg(cls.colors_[index]) | [
"def",
"color",
"(",
"cls",
",",
"value",
")",
":",
"index",
"=",
"bisect",
"(",
"cls",
".",
"breakpoints",
",",
"value",
")",
"return",
"colors",
".",
"fg",
"(",
"cls",
".",
"colors_",
"[",
"index",
"]",
")"
] | 37 | 7 |
def expand_template(template, value):
"""
:param template: A UNICODE STRING WITH VARIABLE NAMES IN MOUSTACHES `{{.}}`
:param value: Data HOLDING THE PARAMTER VALUES
:return: UNICODE STRING WITH VARIABLES EXPANDED
"""
value = wrap(value)
if is_text(template):
return _simple_expand(tem... | [
"def",
"expand_template",
"(",
"template",
",",
"value",
")",
":",
"value",
"=",
"wrap",
"(",
"value",
")",
"if",
"is_text",
"(",
"template",
")",
":",
"return",
"_simple_expand",
"(",
"template",
",",
"(",
"value",
",",
")",
")",
"return",
"_expand",
... | 33.272727 | 13.272727 |
def forward(self, data_batch, is_train=None, carry_state=True):
"""Forward computation. States from previous forward computation are carried
to the current iteration if `carry_state` is set to `True`.
"""
# propagate states from the previous iteration
if carry_state:
... | [
"def",
"forward",
"(",
"self",
",",
"data_batch",
",",
"is_train",
"=",
"None",
",",
"carry_state",
"=",
"True",
")",
":",
"# propagate states from the previous iteration",
"if",
"carry_state",
":",
"if",
"isinstance",
"(",
"self",
".",
"_next_states",
",",
"(",... | 51.923077 | 16.923077 |
def add_param_annotations(
logic: Callable, params: List[RequestParamAnnotation]) -> Callable:
"""Adds parameter annotations to a logic function.
This adds additional required and/or optional parameters to the logic
function that are not part of it's signature. It's intended to be used
by deco... | [
"def",
"add_param_annotations",
"(",
"logic",
":",
"Callable",
",",
"params",
":",
"List",
"[",
"RequestParamAnnotation",
"]",
")",
"->",
"Callable",
":",
"# If we've already added param annotations to this function get the",
"# values from the logic, otherwise we need to inspect... | 42.851064 | 19.93617 |
def generate_conf_file(argv: List[str]) -> bool:
"""
Convert a set of FHIR resources into their corresponding i2b2 counterparts.
:param argv: Command line arguments. See: create_parser for details
:return:
"""
parser = ArgumentParser(description="Generate SQL db_conf file template")
parser... | [
"def",
"generate_conf_file",
"(",
"argv",
":",
"List",
"[",
"str",
"]",
")",
"->",
"bool",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Generate SQL db_conf file template\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-f\"",
",",
"\"--confi... | 40.666667 | 18.777778 |
async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest,
iA=None,
i=None) -> (Claims, Dict[str, ClaimAttributeValues]):
"""
Issue a claim for the given user and schema.
:param schemaId: The schema ID (reference to claim
defin... | [
"async",
"def",
"issueClaim",
"(",
"self",
",",
"schemaId",
":",
"ID",
",",
"claimRequest",
":",
"ClaimRequest",
",",
"iA",
"=",
"None",
",",
"i",
"=",
"None",
")",
"->",
"(",
"Claims",
",",
"Dict",
"[",
"str",
",",
"ClaimAttributeValues",
"]",
")",
... | 44.285714 | 24.457143 |
def logout(self):
"""Logout of a vSphere server."""
if self._logged_in is True:
self.si.flush_cache()
self.sc.sessionManager.Logout()
self._logged_in = False | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"_logged_in",
"is",
"True",
":",
"self",
".",
"si",
".",
"flush_cache",
"(",
")",
"self",
".",
"sc",
".",
"sessionManager",
".",
"Logout",
"(",
")",
"self",
".",
"_logged_in",
"=",
"False"
] | 34 | 7.166667 |
def _get_fault_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates for a simple or complex fault source
:param source:
Fault source as instance of :class:
openquake.hazardlib.source.simple_fault.SimpleFaultSource or
openquake.hazardlib.source.complex_f... | [
"def",
"_get_fault_rates",
"(",
"self",
",",
"source",
",",
"mmin",
",",
"mmax",
"=",
"np",
".",
"inf",
")",
":",
"for",
"rupt",
"in",
"list",
"(",
"source",
".",
"iter_ruptures",
"(",
")",
")",
":",
"valid_rupt",
"=",
"(",
"rupt",
".",
"mag",
">="... | 46.409091 | 17.136364 |
def cap_list(caps):
"""Given a cap string, return a list of cap, value."""
out = []
caps = caps.split()
for cap in caps:
# turn modifier chars into named modifiers
mods = []
while len(cap) > 0 and cap[0] in cap_modifiers:
attr = cap[0]
cap = cap[1:]
... | [
"def",
"cap_list",
"(",
"caps",
")",
":",
"out",
"=",
"[",
"]",
"caps",
"=",
"caps",
".",
"split",
"(",
")",
"for",
"cap",
"in",
"caps",
":",
"# turn modifier chars into named modifiers",
"mods",
"=",
"[",
"]",
"while",
"len",
"(",
"cap",
")",
">",
"... | 25.923077 | 21.230769 |
def Update(self, menu=None, tooltip=None,filename=None, data=None, data_base64=None,):
'''
Updates the menu, tooltip or icon
:param menu: menu defintion
:param tooltip: string representing tooltip
:param filename: icon filename
:param data: icon raw image
:param... | [
"def",
"Update",
"(",
"self",
",",
"menu",
"=",
"None",
",",
"tooltip",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
",",
"data_base64",
"=",
"None",
",",
")",
":",
"# Menu",
"if",
"menu",
"is",
"not",
"None",
":",
"self",
... | 35.083333 | 11.861111 |
def search_for(self, query, include_draft=False):
"""
Search for a query text.
:param query: keyword to query
:param include_draft: return draft posts/pages or not
:return: an iterable object of posts and pages (if allowed).
"""
query = query.lower()
if n... | [
"def",
"search_for",
"(",
"self",
",",
"query",
",",
"include_draft",
"=",
"False",
")",
":",
"query",
"=",
"query",
".",
"lower",
"(",
")",
"if",
"not",
"query",
":",
"return",
"[",
"]",
"def",
"contains_query_keyword",
"(",
"post_or_page",
")",
":",
... | 38.32 | 16.56 |
def get_instance(self, payload):
"""
Build an instance of InteractionInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.proxy.v1.service.session.interaction.InteractionInstance
:rtype: twilio.rest.proxy.v1.service.session.interaction.InteractionIn... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"InteractionInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"session_sid",
"=",
"self",
".",
... | 35.2 | 20.133333 |
def get_interface_detail_output_interface_flow_control(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
... | [
"def",
"get_interface_detail_output_interface_flow_control",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",
"conf... | 49.294118 | 18.058824 |
def Dumper(obj, indent=0, increase=4, encoding='utf-8'):
"""appropriately view a given dict/list/tuple/object data structure"""
##############################################################################
def p(given):
"""ensure proper decoding from unicode, if necessary"""
if isinstance(g... | [
"def",
"Dumper",
"(",
"obj",
",",
"indent",
"=",
"0",
",",
"increase",
"=",
"4",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"##############################################################################",
"def",
"p",
"(",
"given",
")",
":",
"\"\"\"ensure proper dec... | 49.5 | 17.733333 |
def _rx_timer_handler(self):
"""Method called every time the rx_timer times out, due to the peer not
sending a consecutive frame within the expected time window"""
with self.rx_mutex:
if self.rx_state == ISOTP_WAIT_DATA:
# we did not get new data frames in time.
... | [
"def",
"_rx_timer_handler",
"(",
"self",
")",
":",
"with",
"self",
".",
"rx_mutex",
":",
"if",
"self",
".",
"rx_state",
"==",
"ISOTP_WAIT_DATA",
":",
"# we did not get new data frames in time.",
"# reset rx state",
"self",
".",
"rx_state",
"=",
"ISOTP_IDLE",
"warnin... | 44.3 | 12 |
def delete(self):
"""Delete this job."""
self.conn.delete(self.jid)
self.reserved = False | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"conn",
".",
"delete",
"(",
"self",
".",
"jid",
")",
"self",
".",
"reserved",
"=",
"False"
] | 27.5 | 10 |
def fromRFC2822(klass, rfc822string):
"""
Return a new Time instance from a string formated as described in RFC 2822.
@type rfc822string: str
@raise ValueError: if the timestamp is not formatted properly (or if
certain obsoleted elements of the specification are used).
... | [
"def",
"fromRFC2822",
"(",
"klass",
",",
"rfc822string",
")",
":",
"# parsedate_tz is going to give us a \"struct_time plus\", a 10-tuple",
"# containing the 9 values a struct_time would, i.e.: (tm_year, tm_mon,",
"# tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst), plus a",
"# bon... | 38.5625 | 22.0625 |
def get_interpreter_path(version=None):
"""Return the executable of a specified or current version."""
if version and version != str(sys.version_info[0]):
return settings.PYTHON_INTERPRETER + version
else:
return sys.executable | [
"def",
"get_interpreter_path",
"(",
"version",
"=",
"None",
")",
":",
"if",
"version",
"and",
"version",
"!=",
"str",
"(",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
":",
"return",
"settings",
".",
"PYTHON_INTERPRETER",
"+",
"version",
"else",
":",
... | 41.666667 | 11.666667 |
def get_text_tokenizer(query_string):
"""
Tokenize the input string and return two lists, exclude list is for words that
start with a dash (ex: -word) and include list is for all other words
"""
# Regex to split on double-quotes, single-quotes, and continuous non-whitespace characters.
split_pat... | [
"def",
"get_text_tokenizer",
"(",
"query_string",
")",
":",
"# Regex to split on double-quotes, single-quotes, and continuous non-whitespace characters.",
"split_pattern",
"=",
"re",
".",
"compile",
"(",
"'(\"[^\"]+\"|\\'[^\\']+\\'|\\S+)'",
")",
"# Pattern to remove more than one inter... | 51 | 26 |
def refresh_toc(self, refresh_done_callback, toc_cache):
"""
Initiate a refresh of the parameter TOC.
"""
self._useV2 = self.cf.platform.get_protocol_version() >= 4
toc_fetcher = TocFetcher(self.cf, ParamTocElement,
CRTPPort.PARAM, self.toc,
... | [
"def",
"refresh_toc",
"(",
"self",
",",
"refresh_done_callback",
",",
"toc_cache",
")",
":",
"self",
".",
"_useV2",
"=",
"self",
".",
"cf",
".",
"platform",
".",
"get_protocol_version",
"(",
")",
">=",
"4",
"toc_fetcher",
"=",
"TocFetcher",
"(",
"self",
".... | 44.555556 | 13.888889 |
def hmsToDeg(h, m, s):
"""Convert RA hours, minutes, seconds into an angle in degrees."""
return h * degPerHMSHour + m * degPerHMSMin + s * degPerHMSSec | [
"def",
"hmsToDeg",
"(",
"h",
",",
"m",
",",
"s",
")",
":",
"return",
"h",
"*",
"degPerHMSHour",
"+",
"m",
"*",
"degPerHMSMin",
"+",
"s",
"*",
"degPerHMSSec"
] | 52.666667 | 14.666667 |
def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF Entity ID.
Parameters:
None.
Returns:
A string representing this UDF Entity ID.
'''
if not self._initialized:
raise pycdlibexception.PyCd... | [
"def",
"record",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF Entity ID not initialized'",
")",
"return",
"struct",
".",
"pack",
"(",
"self",
".",
... | 31.142857 | 27.142857 |
def on_consumer_cancelled(self, method_frame):
"""Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
receiving messages.
:param pika.frame.Method method_frame: The Basic.Cancel frame
"""
logger.debug('Consumer was cancelled remotely, shutting down: %r', method_fra... | [
"def",
"on_consumer_cancelled",
"(",
"self",
",",
"method_frame",
")",
":",
"logger",
".",
"debug",
"(",
"'Consumer was cancelled remotely, shutting down: %r'",
",",
"method_frame",
")",
"if",
"self",
".",
"_channel",
":",
"self",
".",
"_channel",
".",
"close",
"(... | 41.666667 | 17.555556 |
def is_allowed(self, subject_id, action, resource_id, policy_sets=[]):
"""
Evaluate a policy-set against a subject and resource.
example/
is_allowed('/user/j12y', 'GET', '/asset/12')
"""
body = {
"action": action,
"subjectIdentifier": subjec... | [
"def",
"is_allowed",
"(",
"self",
",",
"subject_id",
",",
"action",
",",
"resource_id",
",",
"policy_sets",
"=",
"[",
"]",
")",
":",
"body",
"=",
"{",
"\"action\"",
":",
"action",
",",
"\"subjectIdentifier\"",
":",
"subject_id",
",",
"\"resourceIdentifier\"",
... | 26.290323 | 20.935484 |
def is_multifile_object_without_children(self, location: str) -> bool:
"""
Returns True if an item with this location is present as a multifile object without children.
For this implementation, this means that there is a file with the appropriate name but without extension
:param locati... | [
"def",
"is_multifile_object_without_children",
"(",
"self",
",",
"location",
":",
"str",
")",
"->",
"bool",
":",
"# (1) Find the base directory and base name",
"if",
"isdir",
"(",
"location",
")",
":",
"# special case: parent location is the root folder where all the files are.... | 48.888889 | 30.222222 |
def get_file(self, file_hash, save_file_at):
""" 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 will
... | [
"def",
"get_file",
"(",
"self",
",",
"file_hash",
",",
"save_file_at",
")",
":",
"params",
"=",
"{",
"'hash'",
":",
"file_hash",
",",
"'apikey'",
":",
"self",
".",
"api_key",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
... | 50.37037 | 28.62963 |
def tgread_bytes(self):
"""
Reads a Telegram-encoded byte array, without the need of
specifying its length.
"""
first_byte = self.read_byte()
if first_byte == 254:
length = self.read_byte() | (self.read_byte() << 8) | (
self.read_byte() << 16)
... | [
"def",
"tgread_bytes",
"(",
"self",
")",
":",
"first_byte",
"=",
"self",
".",
"read_byte",
"(",
")",
"if",
"first_byte",
"==",
"254",
":",
"length",
"=",
"self",
".",
"read_byte",
"(",
")",
"|",
"(",
"self",
".",
"read_byte",
"(",
")",
"<<",
"8",
"... | 28.1 | 14.1 |
def covariance_plot(ax, Si, param_dict, unit=""):
'''Plots mu* against sigma or the 95% confidence interval
'''
if Si['sigma'] is not None:
# sigma is not present if using morris groups
y = Si['sigma']
out = ax.scatter(Si['mu_star'], y, c=u'k', marker=u'o',
... | [
"def",
"covariance_plot",
"(",
"ax",
",",
"Si",
",",
"param_dict",
",",
"unit",
"=",
"\"\"",
")",
":",
"if",
"Si",
"[",
"'sigma'",
"]",
"is",
"not",
"None",
":",
"# sigma is not present if using morris groups",
"y",
"=",
"Si",
"[",
"'sigma'",
"]",
"out",
... | 32.888889 | 23.222222 |
def add_dispatcher(self, dsp, inputs, outputs, dsp_id=None,
input_domain=None, weight=None, inp_weight=None,
description=None, include_defaults=False,
await_domain=None, **kwargs):
"""
Add a single sub-dispatcher node to dispatcher.
... | [
"def",
"add_dispatcher",
"(",
"self",
",",
"dsp",
",",
"inputs",
",",
"outputs",
",",
"dsp_id",
"=",
"None",
",",
"input_domain",
"=",
"None",
",",
"weight",
"=",
"None",
",",
"inp_weight",
"=",
"None",
",",
"description",
"=",
"None",
",",
"include_defa... | 40.220779 | 22.636364 |
def save(self, path=None, encoding=None, eol=None):
"""
save([path][, encoding][, eol])
Use initial path if no other provided.
Use initial encoding if no other provided.
Use initial eol if no other provided.
"""
path = path or self.path
encoding = encodin... | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"eol",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"self",
".",
"path",
"encoding",
"=",
"encoding",
"or",
"self",
".",
"encoding",
"save_file",
"=",
"co... | 32.785714 | 11.785714 |
def _proxy_to_logger(self, method_name, event, *event_args,
**event_kw):
"""
Propagate a method call to the wrapped logger.
This is the same as the superclass implementation, except that
it also preserves positional arguments in the `event_dict` so
that ... | [
"def",
"_proxy_to_logger",
"(",
"self",
",",
"method_name",
",",
"event",
",",
"*",
"event_args",
",",
"*",
"*",
"event_kw",
")",
":",
"if",
"isinstance",
"(",
"event",
",",
"bytes",
")",
":",
"event",
"=",
"event",
".",
"decode",
"(",
"'utf-8'",
")",
... | 38.894737 | 21.421053 |
def create_api(self):
"""Create the REST API."""
created_api = self.client.create_rest_api(name=self.trigger_settings.get('api_name', self.app_name))
api_id = created_api['id']
self.log.info("Successfully created API")
return api_id | [
"def",
"create_api",
"(",
"self",
")",
":",
"created_api",
"=",
"self",
".",
"client",
".",
"create_rest_api",
"(",
"name",
"=",
"self",
".",
"trigger_settings",
".",
"get",
"(",
"'api_name'",
",",
"self",
".",
"app_name",
")",
")",
"api_id",
"=",
"creat... | 44.5 | 20.166667 |
def _format_range_dt(self, d):
"""Format range filter datetime to the closest aggregation interval."""
if not isinstance(d, six.string_types):
d = d.isoformat()
return '{0}||/{1}'.format(
d, self.dt_rounding_map[self.aggregation_interval]) | [
"def",
"_format_range_dt",
"(",
"self",
",",
"d",
")",
":",
"if",
"not",
"isinstance",
"(",
"d",
",",
"six",
".",
"string_types",
")",
":",
"d",
"=",
"d",
".",
"isoformat",
"(",
")",
"return",
"'{0}||/{1}'",
".",
"format",
"(",
"d",
",",
"self",
".... | 47 | 9.5 |
def stream(self, start_date=values.unset, end_date=values.unset,
identity=values.unset, tag=values.unset, limit=None, page_size=None):
"""
Streams BindingInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the l... | [
"def",
"stream",
"(",
"self",
",",
"start_date",
"=",
"values",
".",
"unset",
",",
"end_date",
"=",
"values",
".",
"unset",
",",
"identity",
"=",
"values",
".",
"unset",
",",
"tag",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_s... | 53.727273 | 32.030303 |
def nsname(self, uri: Union[str, URIRef]) -> str:
"""
Return the 'ns:name' format of URI
:param uri: URI to transform
:return: nsname format of URI or straight URI if no mapping
"""
uri = str(uri)
nsuri = ""
prefix = None
for pfx, ns in self:
... | [
"def",
"nsname",
"(",
"self",
",",
"uri",
":",
"Union",
"[",
"str",
",",
"URIRef",
"]",
")",
"->",
"str",
":",
"uri",
"=",
"str",
"(",
"uri",
")",
"nsuri",
"=",
"\"\"",
"prefix",
"=",
"None",
"for",
"pfx",
",",
"ns",
"in",
"self",
":",
"nss",
... | 33.3125 | 16.3125 |
def save_reduce(self, func, args, state=None,
listitems=None, dictitems=None, obj=None):
"""Modified to support __transient__ on new objects
Change only affects protocol level 2 (which is always used by PiCloud"""
# Assert that args is a tuple or None
if not isinstanc... | [
"def",
"save_reduce",
"(",
"self",
",",
"func",
",",
"args",
",",
"state",
"=",
"None",
",",
"listitems",
"=",
"None",
",",
"dictitems",
"=",
"None",
",",
"obj",
"=",
"None",
")",
":",
"# Assert that args is a tuple or None",
"if",
"not",
"isinstance",
"("... | 35.95082 | 18 |
def processes(self):
"""Initialise and return the list of processes associated with this pool"""
if self._processes is None:
self._processes = []
for p in range(self.workers):
t = Task(self._target, self._args, self._kwargs)
t.name = "%s-%d" % (sel... | [
"def",
"processes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_processes",
"is",
"None",
":",
"self",
".",
"_processes",
"=",
"[",
"]",
"for",
"p",
"in",
"range",
"(",
"self",
".",
"workers",
")",
":",
"t",
"=",
"Task",
"(",
"self",
".",
"_targe... | 40.2 | 12.5 |
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_... | [
"def",
"list_nodes_full",
"(",
"mask",
"=",
"'mask[id, hostname, primaryIpAddress, \\\n primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]'",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"... | 33.842105 | 24.684211 |
def convolve_gaussian_2d(image, gaussian_kernel_1d):
"""Convolve 2d gaussian."""
result = scipy.ndimage.filters.correlate1d(
image, gaussian_kernel_1d, axis=0)
result = scipy.ndimage.filters.correlate1d(
result, gaussian_kernel_1d, axis=1)
return result | [
"def",
"convolve_gaussian_2d",
"(",
"image",
",",
"gaussian_kernel_1d",
")",
":",
"result",
"=",
"scipy",
".",
"ndimage",
".",
"filters",
".",
"correlate1d",
"(",
"image",
",",
"gaussian_kernel_1d",
",",
"axis",
"=",
"0",
")",
"result",
"=",
"scipy",
".",
... | 39.857143 | 7.714286 |
def ref_coords(self):
'''Returns a pyfastaq.intervals.Interval object of the start and end coordinates in the reference sequence'''
return pyfastaq.intervals.Interval(min(self.ref_start, self.ref_end), max(self.ref_start, self.ref_end)) | [
"def",
"ref_coords",
"(",
"self",
")",
":",
"return",
"pyfastaq",
".",
"intervals",
".",
"Interval",
"(",
"min",
"(",
"self",
".",
"ref_start",
",",
"self",
".",
"ref_end",
")",
",",
"max",
"(",
"self",
".",
"ref_start",
",",
"self",
".",
"ref_end",
... | 83.333333 | 56 |
def browser(tags=None, proxy=None, other_caps=None):
"""
Interpret environment variables to configure Selenium.
Performs validation, logging, and sensible defaults.
There are three cases:
1. Local browsers: If the proper environment variables are not all set for the second case,
then we us... | [
"def",
"browser",
"(",
"tags",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"other_caps",
"=",
"None",
")",
":",
"browser_name",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SELENIUM_BROWSER'",
",",
"'firefox'",
")",
"def",
"browser_check_func",
"(",
")... | 44.219048 | 31.238095 |
def exception(self):
"""
The exception that occured while the job executed. The value is #None if
no exception occurred.
# Raises
InvalidState: If the job is #PENDING or #RUNNING.
"""
if self.__state in (Job.PENDING, Job.RUNNING):
raise self.InvalidState('job is {0}'.format(self.__st... | [
"def",
"exception",
"(",
"self",
")",
":",
"if",
"self",
".",
"__state",
"in",
"(",
"Job",
".",
"PENDING",
",",
"Job",
".",
"RUNNING",
")",
":",
"raise",
"self",
".",
"InvalidState",
"(",
"'job is {0}'",
".",
"format",
"(",
"self",
".",
"__state",
")... | 32.736842 | 18.842105 |
def combine_apply(d, leaf_keys, func, new_name,
unflatten_level=1, remove_lkeys=True, overwrite=False,
list_of_dicts=False, deepcopy=True, **kwargs):
""" combine values with certain leaf (terminal) keys by a function
Parameters
----------
d : dict
leaf_keys : lis... | [
"def",
"combine_apply",
"(",
"d",
",",
"leaf_keys",
",",
"func",
",",
"new_name",
",",
"unflatten_level",
"=",
"1",
",",
"remove_lkeys",
"=",
"True",
",",
"overwrite",
"=",
"False",
",",
"list_of_dicts",
"=",
"False",
",",
"deepcopy",
"=",
"True",
",",
"... | 33.626667 | 18.893333 |
def chain(self, wrapper, *args, **kwargs):
"""
Add a wrapper to the chain. Any extra positional or keyword
arguments will be passed to that wrapper through construction
of a ``TendrilPartial``. For convenience, returns the
WrapperChain object, allowing ``chain()`` to be called ... | [
"def",
"chain",
"(",
"self",
",",
"wrapper",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"or",
"kwargs",
":",
"wrapper",
"=",
"TendrilPartial",
"(",
"wrapper",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_... | 34.8125 | 19.5625 |
def get_mapping(self, meta_fields=True):
'''
Returns the mapping for the index as a dictionary.
:param meta_fields: Also include elasticsearch meta fields in the dictionary.
:return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
'''... | [
"def",
"get_mapping",
"(",
"self",
",",
"meta_fields",
"=",
"True",
")",
":",
"return",
"{",
"'properties'",
":",
"dict",
"(",
"(",
"name",
",",
"field",
".",
"json",
"(",
")",
")",
"for",
"name",
",",
"field",
"in",
"iteritems",
"(",
"self",
".",
... | 58.625 | 43.125 |
def readDataAsync(self, fileName, callback):
"""
Interprets the specified data file asynchronously. When interpreting is
over, the specified callback is called. The file is interpreted as
data. As a side effect, it invalidates all entities (as the passed file
can contain any arbi... | [
"def",
"readDataAsync",
"(",
"self",
",",
"fileName",
",",
"callback",
")",
":",
"def",
"async_call",
"(",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_impl",
".",
"readData",
"(",
"fileName",
")",
"self",
".",... | 36.269231 | 17.038462 |
def set_password(ctx, new_password, remember):
"""
Password protect the OATH credentials.
Allows you to set a password that will be required to access the OATH
credentials stored on your YubiKey.
"""
ensure_validated(ctx, prompt='Enter your current password')
if not new_password:
ne... | [
"def",
"set_password",
"(",
"ctx",
",",
"new_password",
",",
"remember",
")",
":",
"ensure_validated",
"(",
"ctx",
",",
"prompt",
"=",
"'Enter your current password'",
")",
"if",
"not",
"new_password",
":",
"new_password",
"=",
"click",
".",
"prompt",
"(",
"'E... | 32.407407 | 11.444444 |
def _parse_access_token(self, resp_text):
' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true '
r = self._qs2dict(resp_text)
access_token = r.pop('access_token')
expires = time.time() + float(r.pop('expires_in'))
return JsonDict(access_t... | [
"def",
"_parse_access_token",
"(",
"self",
",",
"resp_text",
")",
":",
"r",
"=",
"self",
".",
"_qs2dict",
"(",
"resp_text",
")",
"access_token",
"=",
"r",
".",
"pop",
"(",
"'access_token'",
")",
"expires",
"=",
"time",
".",
"time",
"(",
")",
"+",
"floa... | 59.166667 | 20.5 |
def _create_storage_folder(self):
'''
Creates a storage folder using the query name by replacing
spaces in the query with '_' (underscore)
'''
try:
print(colored('\nCreating Storage Folder...', 'yellow'))
self._storageFolder = os.path.join(
... | [
"def",
"_create_storage_folder",
"(",
"self",
")",
":",
"try",
":",
"print",
"(",
"colored",
"(",
"'\\nCreating Storage Folder...'",
",",
"'yellow'",
")",
")",
"self",
".",
"_storageFolder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_destinatio... | 38.15 | 21.85 |
def route(*args, response_formatter=jsonify, **kwargs):
"""Combines `Flask.route` and webargs parsing. Allows arguments to be specified
as function annotations. An output schema can optionally be specified by a
return annotation.
"""
def decorator(func):
@app.route(*args, **kwargs)
... | [
"def",
"route",
"(",
"*",
"args",
",",
"response_formatter",
"=",
"jsonify",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"app",
".",
"route",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"@",
"functools",
... | 36.821429 | 18.392857 |
async def notifications(dev: Device, notification: str, listen_all: bool):
"""List available notifications and listen to them.
Using --listen-all [notification] allows to listen to all notifications
from the given subsystem.
If the subsystem is omited, notifications from all subsystems are
request... | [
"async",
"def",
"notifications",
"(",
"dev",
":",
"Device",
",",
"notification",
":",
"str",
",",
"listen_all",
":",
"bool",
")",
":",
"notifications",
"=",
"await",
"dev",
".",
"get_notifications",
"(",
")",
"async",
"def",
"handle_notification",
"(",
"x",
... | 36.529412 | 21.647059 |
def update_raw(self, fields=None):
"""Update the current entity.
Make an HTTP PUT call to ``self.path('base')``. The request payload
consists of whatever is returned by :meth:`update_payload`. Return the
response.
:param fields: See :meth:`update`.
:return: A ``requests... | [
"def",
"update_raw",
"(",
"self",
",",
"fields",
"=",
"None",
")",
":",
"return",
"client",
".",
"put",
"(",
"self",
".",
"path",
"(",
"'self'",
")",
",",
"self",
".",
"update_payload",
"(",
"fields",
")",
",",
"*",
"*",
"self",
".",
"_server_config"... | 31.25 | 18.75 |
def _reset_file_descriptors(self):
"""Close open file descriptors and redirect standard streams."""
if self.close_open_files:
# Attempt to determine the max number of open files
max_fds = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if max_fds == resource.RLIM_INFINI... | [
"def",
"_reset_file_descriptors",
"(",
"self",
")",
":",
"if",
"self",
".",
"close_open_files",
":",
"# Attempt to determine the max number of open files",
"max_fds",
"=",
"resource",
".",
"getrlimit",
"(",
"resource",
".",
"RLIMIT_NOFILE",
")",
"[",
"1",
"]",
"if",... | 38.04 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.