id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
46,381 | def _simple_domain_name_validator(value):
if (not value):
return
checks = ((s in value) for s in string.whitespace)
if any(checks):
raise ValidationError(_('The domain name cannot contain any spaces or tabs.'), code='invalid')
| [
"def",
"_simple_domain_name_validator",
"(",
"value",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"return",
"checks",
"=",
"(",
"(",
"s",
"in",
"value",
")",
"for",
"s",
"in",
"string",
".",
"whitespace",
")",
"if",
"any",
"(",
"checks",
")",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'The domain name cannot contain any spaces or tabs.'",
")",
",",
"code",
"=",
"'invalid'",
")"
] | validates that the given value contains no whitespaces to prevent common typos . | train | false |
46,382 | def _infer_geometry(value):
if isinstance(value, dict):
if ('$geometry' in value):
return value
elif (('coordinates' in value) and ('type' in value)):
return {'$geometry': value}
raise InvalidQueryError('Invalid $geometry dictionary should have type and coordinates keys')
elif isinstance(value, (list, set)):
try:
value[0][0][0]
return {'$geometry': {'type': 'Polygon', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0][0]
return {'$geometry': {'type': 'LineString', 'coordinates': value}}
except (TypeError, IndexError):
pass
try:
value[0]
return {'$geometry': {'type': 'Point', 'coordinates': value}}
except (TypeError, IndexError):
pass
raise InvalidQueryError('Invalid $geometry data. Can be either a dictionary or (nested) lists of coordinate(s)')
| [
"def",
"_infer_geometry",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"(",
"'$geometry'",
"in",
"value",
")",
":",
"return",
"value",
"elif",
"(",
"(",
"'coordinates'",
"in",
"value",
")",
"and",
"(",
"'type'",
"in",
"value",
")",
")",
":",
"return",
"{",
"'$geometry'",
":",
"value",
"}",
"raise",
"InvalidQueryError",
"(",
"'Invalid $geometry dictionary should have type and coordinates keys'",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"set",
")",
")",
":",
"try",
":",
"value",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
"return",
"{",
"'$geometry'",
":",
"{",
"'type'",
":",
"'Polygon'",
",",
"'coordinates'",
":",
"value",
"}",
"}",
"except",
"(",
"TypeError",
",",
"IndexError",
")",
":",
"pass",
"try",
":",
"value",
"[",
"0",
"]",
"[",
"0",
"]",
"return",
"{",
"'$geometry'",
":",
"{",
"'type'",
":",
"'LineString'",
",",
"'coordinates'",
":",
"value",
"}",
"}",
"except",
"(",
"TypeError",
",",
"IndexError",
")",
":",
"pass",
"try",
":",
"value",
"[",
"0",
"]",
"return",
"{",
"'$geometry'",
":",
"{",
"'type'",
":",
"'Point'",
",",
"'coordinates'",
":",
"value",
"}",
"}",
"except",
"(",
"TypeError",
",",
"IndexError",
")",
":",
"pass",
"raise",
"InvalidQueryError",
"(",
"'Invalid $geometry data. Can be either a dictionary or (nested) lists of coordinate(s)'",
")"
] | helper method that tries to infer the $geometry shape for a given value . | train | false |
46,383 | def cert_get_bitstrength(cert):
if hasattr(cert.public_key(), 'key_size'):
return cert.public_key().key_size
else:
return None
| [
"def",
"cert_get_bitstrength",
"(",
"cert",
")",
":",
"if",
"hasattr",
"(",
"cert",
".",
"public_key",
"(",
")",
",",
"'key_size'",
")",
":",
"return",
"cert",
".",
"public_key",
"(",
")",
".",
"key_size",
"else",
":",
"return",
"None"
] | calculates a certificates public key bit length . | train | false |
46,384 | def not_send_status(func):
@functools.wraps(func)
def wrapper(self, response, task):
self._extinfo['not_send_status'] = True
function = func.__get__(self, self.__class__)
return self._run_func(function, response, task)
return wrapper
| [
"def",
"not_send_status",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"response",
",",
"task",
")",
":",
"self",
".",
"_extinfo",
"[",
"'not_send_status'",
"]",
"=",
"True",
"function",
"=",
"func",
".",
"__get__",
"(",
"self",
",",
"self",
".",
"__class__",
")",
"return",
"self",
".",
"_run_func",
"(",
"function",
",",
"response",
",",
"task",
")",
"return",
"wrapper"
] | do not send process status package back to scheduler . | train | true |
46,385 | def get_thread(request, thread_id, requested_fields=None):
(cc_thread, context) = _get_thread_and_context(request, thread_id, retrieve_kwargs={'with_responses': True, 'user_id': unicode(request.user.id)})
return _serialize_discussion_entities(request, context, [cc_thread], requested_fields, DiscussionEntity.thread)[0]
| [
"def",
"get_thread",
"(",
"request",
",",
"thread_id",
",",
"requested_fields",
"=",
"None",
")",
":",
"(",
"cc_thread",
",",
"context",
")",
"=",
"_get_thread_and_context",
"(",
"request",
",",
"thread_id",
",",
"retrieve_kwargs",
"=",
"{",
"'with_responses'",
":",
"True",
",",
"'user_id'",
":",
"unicode",
"(",
"request",
".",
"user",
".",
"id",
")",
"}",
")",
"return",
"_serialize_discussion_entities",
"(",
"request",
",",
"context",
",",
"[",
"cc_thread",
"]",
",",
"requested_fields",
",",
"DiscussionEntity",
".",
"thread",
")",
"[",
"0",
"]"
] | retrieve a thread . | train | false |
46,386 | def _parse_hive_site():
global _HIVE_SITE_DICT
global _HIVE_SITE_PATH
_HIVE_SITE_PATH = os.path.join(beeswax.conf.HIVE_CONF_DIR.get(), 'hive-site.xml')
try:
data = file(_HIVE_SITE_PATH, 'r').read()
except IOError as err:
if (err.errno != errno.ENOENT):
LOG.error(('Cannot read from "%s": %s' % (_HIVE_SITE_PATH, err)))
return
data = ''
_HIVE_SITE_DICT = confparse.ConfParse(data)
| [
"def",
"_parse_hive_site",
"(",
")",
":",
"global",
"_HIVE_SITE_DICT",
"global",
"_HIVE_SITE_PATH",
"_HIVE_SITE_PATH",
"=",
"os",
".",
"path",
".",
"join",
"(",
"beeswax",
".",
"conf",
".",
"HIVE_CONF_DIR",
".",
"get",
"(",
")",
",",
"'hive-site.xml'",
")",
"try",
":",
"data",
"=",
"file",
"(",
"_HIVE_SITE_PATH",
",",
"'r'",
")",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"err",
":",
"if",
"(",
"err",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
")",
":",
"LOG",
".",
"error",
"(",
"(",
"'Cannot read from \"%s\": %s'",
"%",
"(",
"_HIVE_SITE_PATH",
",",
"err",
")",
")",
")",
"return",
"data",
"=",
"''",
"_HIVE_SITE_DICT",
"=",
"confparse",
".",
"ConfParse",
"(",
"data",
")"
] | parse hive-site . | train | false |
46,388 | def cpuCount():
if (sys.platform == 'win32'):
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = (-1)
elif (sys.platform == 'darwin'):
try:
num = int(os.popen('sysctl -n hw.ncpu').read())
except ValueError:
num = (-1)
else:
try:
num = os.sysconf('SC_NPROCESSORS_ONLN')
except (ValueError, OSError, AttributeError):
num = (-1)
return num
| [
"def",
"cpuCount",
"(",
")",
":",
"if",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
":",
"try",
":",
"num",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'NUMBER_OF_PROCESSORS'",
"]",
")",
"except",
"(",
"ValueError",
",",
"KeyError",
")",
":",
"num",
"=",
"(",
"-",
"1",
")",
"elif",
"(",
"sys",
".",
"platform",
"==",
"'darwin'",
")",
":",
"try",
":",
"num",
"=",
"int",
"(",
"os",
".",
"popen",
"(",
"'sysctl -n hw.ncpu'",
")",
".",
"read",
"(",
")",
")",
"except",
"ValueError",
":",
"num",
"=",
"(",
"-",
"1",
")",
"else",
":",
"try",
":",
"num",
"=",
"os",
".",
"sysconf",
"(",
"'SC_NPROCESSORS_ONLN'",
")",
"except",
"(",
"ValueError",
",",
"OSError",
",",
"AttributeError",
")",
":",
"num",
"=",
"(",
"-",
"1",
")",
"return",
"num"
] | returns the number of cpus in the system . | train | false |
46,390 | def test_imports():
from ...utils import find_current_module
pkgornm = find_current_module(1).__name__.split(u'.')[0]
if isinstance(pkgornm, six.string_types):
package = pkgutil.get_loader(pkgornm).load_module(pkgornm)
elif (isinstance(pkgornm, types.ModuleType) and (u'__init__' in pkgornm.__file__)):
package = pkgornm
else:
msg = u'test_imports is not determining a valid package/package name'
raise TypeError(msg)
if hasattr(package, u'__path__'):
pkgpath = package.__path__
elif hasattr(package, u'__file__'):
pkgpath = os.path.split(package.__file__)[0]
else:
raise AttributeError(u'package to generate config items for does not have __file__ or __path__')
if six.PY2:
excludes = _py3_packages
else:
excludes = _py2_packages
prefix = (package.__name__ + u'.')
def onerror(name):
if (not any((name.startswith(excl) for excl in excludes))):
raise
for (imper, nm, ispkg) in pkgutil.walk_packages(pkgpath, prefix, onerror=onerror):
imper.find_module(nm)
| [
"def",
"test_imports",
"(",
")",
":",
"from",
"...",
"utils",
"import",
"find_current_module",
"pkgornm",
"=",
"find_current_module",
"(",
"1",
")",
".",
"__name__",
".",
"split",
"(",
"u'.'",
")",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"pkgornm",
",",
"six",
".",
"string_types",
")",
":",
"package",
"=",
"pkgutil",
".",
"get_loader",
"(",
"pkgornm",
")",
".",
"load_module",
"(",
"pkgornm",
")",
"elif",
"(",
"isinstance",
"(",
"pkgornm",
",",
"types",
".",
"ModuleType",
")",
"and",
"(",
"u'__init__'",
"in",
"pkgornm",
".",
"__file__",
")",
")",
":",
"package",
"=",
"pkgornm",
"else",
":",
"msg",
"=",
"u'test_imports is not determining a valid package/package name'",
"raise",
"TypeError",
"(",
"msg",
")",
"if",
"hasattr",
"(",
"package",
",",
"u'__path__'",
")",
":",
"pkgpath",
"=",
"package",
".",
"__path__",
"elif",
"hasattr",
"(",
"package",
",",
"u'__file__'",
")",
":",
"pkgpath",
"=",
"os",
".",
"path",
".",
"split",
"(",
"package",
".",
"__file__",
")",
"[",
"0",
"]",
"else",
":",
"raise",
"AttributeError",
"(",
"u'package to generate config items for does not have __file__ or __path__'",
")",
"if",
"six",
".",
"PY2",
":",
"excludes",
"=",
"_py3_packages",
"else",
":",
"excludes",
"=",
"_py2_packages",
"prefix",
"=",
"(",
"package",
".",
"__name__",
"+",
"u'.'",
")",
"def",
"onerror",
"(",
"name",
")",
":",
"if",
"(",
"not",
"any",
"(",
"(",
"name",
".",
"startswith",
"(",
"excl",
")",
"for",
"excl",
"in",
"excludes",
")",
")",
")",
":",
"raise",
"for",
"(",
"imper",
",",
"nm",
",",
"ispkg",
")",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"pkgpath",
",",
"prefix",
",",
"onerror",
"=",
"onerror",
")",
":",
"imper",
".",
"find_module",
"(",
"nm",
")"
] | this just imports all modules in astropy . | train | false |
46,391 | def test_no_data_with_no_values(Chart):
chart = Chart()
q = chart.render_pyquery()
assert (q('.text-overlay text').text() == 'No data')
| [
"def",
"test_no_data_with_no_values",
"(",
"Chart",
")",
":",
"chart",
"=",
"Chart",
"(",
")",
"q",
"=",
"chart",
".",
"render_pyquery",
"(",
")",
"assert",
"(",
"q",
"(",
"'.text-overlay text'",
")",
".",
"text",
"(",
")",
"==",
"'No data'",
")"
] | test no data . | train | false |
46,392 | def grading_context_for_course(course_key):
course_structure = get_course_in_cache(course_key)
return grading_context(course_structure)
| [
"def",
"grading_context_for_course",
"(",
"course_key",
")",
":",
"course_structure",
"=",
"get_course_in_cache",
"(",
"course_key",
")",
"return",
"grading_context",
"(",
"course_structure",
")"
] | same as grading_context . | train | false |
46,394 | def verify_header(pkt):
if (endian_int(pkt[0:3]) is 1):
if (int(pkt[3], 16) is 1):
return True
return False
| [
"def",
"verify_header",
"(",
"pkt",
")",
":",
"if",
"(",
"endian_int",
"(",
"pkt",
"[",
"0",
":",
"3",
"]",
")",
"is",
"1",
")",
":",
"if",
"(",
"int",
"(",
"pkt",
"[",
"3",
"]",
",",
"16",
")",
"is",
"1",
")",
":",
"return",
"True",
"return",
"False"
] | not all packets have a mysql header . | train | false |
46,395 | def list_instance_profiles(path_prefix='/', region=None, key=None, keyid=None, profile=None):
p = get_all_instance_profiles(path_prefix, region, key, keyid, profile)
return [i['instance_profile_name'] for i in p]
| [
"def",
"list_instance_profiles",
"(",
"path_prefix",
"=",
"'/'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"p",
"=",
"get_all_instance_profiles",
"(",
"path_prefix",
",",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
"return",
"[",
"i",
"[",
"'instance_profile_name'",
"]",
"for",
"i",
"in",
"p",
"]"
] | list all iam instance profiles . | train | true |
46,398 | def header_encode(header, charset='iso-8859-1', keep_eols=False, maxlinelen=76, eol=NL):
if (not header):
return header
if (not keep_eols):
header = fix_eols(header)
quoted = []
if (maxlinelen is None):
max_encoded = 100000
else:
max_encoded = (((maxlinelen - len(charset)) - MISC_LEN) - 1)
for c in header:
if (c == ' '):
_max_append(quoted, '_', max_encoded)
elif (not hqre.match(c)):
_max_append(quoted, c, max_encoded)
else:
_max_append(quoted, ('=%02X' % ord(c)), max_encoded)
joiner = (eol + ' ')
return joiner.join([('=?%s?q?%s?=' % (charset, line)) for line in quoted])
| [
"def",
"header_encode",
"(",
"header",
",",
"charset",
"=",
"'iso-8859-1'",
",",
"keep_eols",
"=",
"False",
",",
"maxlinelen",
"=",
"76",
",",
"eol",
"=",
"NL",
")",
":",
"if",
"(",
"not",
"header",
")",
":",
"return",
"header",
"if",
"(",
"not",
"keep_eols",
")",
":",
"header",
"=",
"fix_eols",
"(",
"header",
")",
"quoted",
"=",
"[",
"]",
"if",
"(",
"maxlinelen",
"is",
"None",
")",
":",
"max_encoded",
"=",
"100000",
"else",
":",
"max_encoded",
"=",
"(",
"(",
"(",
"maxlinelen",
"-",
"len",
"(",
"charset",
")",
")",
"-",
"MISC_LEN",
")",
"-",
"1",
")",
"for",
"c",
"in",
"header",
":",
"if",
"(",
"c",
"==",
"' '",
")",
":",
"_max_append",
"(",
"quoted",
",",
"'_'",
",",
"max_encoded",
")",
"elif",
"(",
"not",
"hqre",
".",
"match",
"(",
"c",
")",
")",
":",
"_max_append",
"(",
"quoted",
",",
"c",
",",
"max_encoded",
")",
"else",
":",
"_max_append",
"(",
"quoted",
",",
"(",
"'=%02X'",
"%",
"ord",
"(",
"c",
")",
")",
",",
"max_encoded",
")",
"joiner",
"=",
"(",
"eol",
"+",
"' '",
")",
"return",
"joiner",
".",
"join",
"(",
"[",
"(",
"'=?%s?q?%s?='",
"%",
"(",
"charset",
",",
"line",
")",
")",
"for",
"line",
"in",
"quoted",
"]",
")"
] | encode a single header line with quoted-printable encoding . | train | false |
46,399 | @must_have_permission(ADMIN)
@must_be_branched_from_node
@http_error_if_disk_saving_mode
def register_draft_registration(auth, node, draft, *args, **kwargs):
data = request.get_json()
registration_choice = data.get('registrationChoice', 'immediate')
validate_registration_choice(registration_choice)
register = draft.register(auth)
draft.save()
if (registration_choice == 'embargo'):
embargo_end_date = parse_date(data['embargoEndDate'], ignoretz=True).replace(tzinfo=pytz.utc)
try:
register.embargo_registration(auth.user, embargo_end_date)
except ValidationValueError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
else:
try:
register.require_approval(auth.user)
except NodeStateError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
register.save()
push_status_message(language.AFTER_REGISTER_ARCHIVING, kind='info', trust=False)
return ({'status': 'initiated', 'urls': {'registrations': node.web_url_for('node_registrations')}}, http.ACCEPTED)
| [
"@",
"must_have_permission",
"(",
"ADMIN",
")",
"@",
"must_be_branched_from_node",
"@",
"http_error_if_disk_saving_mode",
"def",
"register_draft_registration",
"(",
"auth",
",",
"node",
",",
"draft",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"data",
"=",
"request",
".",
"get_json",
"(",
")",
"registration_choice",
"=",
"data",
".",
"get",
"(",
"'registrationChoice'",
",",
"'immediate'",
")",
"validate_registration_choice",
"(",
"registration_choice",
")",
"register",
"=",
"draft",
".",
"register",
"(",
"auth",
")",
"draft",
".",
"save",
"(",
")",
"if",
"(",
"registration_choice",
"==",
"'embargo'",
")",
":",
"embargo_end_date",
"=",
"parse_date",
"(",
"data",
"[",
"'embargoEndDate'",
"]",
",",
"ignoretz",
"=",
"True",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"try",
":",
"register",
".",
"embargo_registration",
"(",
"auth",
".",
"user",
",",
"embargo_end_date",
")",
"except",
"ValidationValueError",
"as",
"err",
":",
"raise",
"HTTPError",
"(",
"http",
".",
"BAD_REQUEST",
",",
"data",
"=",
"dict",
"(",
"message_long",
"=",
"err",
".",
"message",
")",
")",
"else",
":",
"try",
":",
"register",
".",
"require_approval",
"(",
"auth",
".",
"user",
")",
"except",
"NodeStateError",
"as",
"err",
":",
"raise",
"HTTPError",
"(",
"http",
".",
"BAD_REQUEST",
",",
"data",
"=",
"dict",
"(",
"message_long",
"=",
"err",
".",
"message",
")",
")",
"register",
".",
"save",
"(",
")",
"push_status_message",
"(",
"language",
".",
"AFTER_REGISTER_ARCHIVING",
",",
"kind",
"=",
"'info'",
",",
"trust",
"=",
"False",
")",
"return",
"(",
"{",
"'status'",
":",
"'initiated'",
",",
"'urls'",
":",
"{",
"'registrations'",
":",
"node",
".",
"web_url_for",
"(",
"'node_registrations'",
")",
"}",
"}",
",",
"http",
".",
"ACCEPTED",
")"
] | initiate a registration from a draft registration :return: success message; url to registrations page :rtype: dict . | train | false |
46,400 | def byteArrayToInt(packed_data):
value = struct.unpack('B B B B B B B B', packed_data)
return ((((((((value[0] << 56) | (value[1] << 48)) | (value[2] << 40)) | (value[3] << 32)) | (value[4] << 24)) | (value[5] << 16)) | (value[6] << 8)) | value[7])
| [
"def",
"byteArrayToInt",
"(",
"packed_data",
")",
":",
"value",
"=",
"struct",
".",
"unpack",
"(",
"'B B B B B B B B'",
",",
"packed_data",
")",
"return",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"value",
"[",
"0",
"]",
"<<",
"56",
")",
"|",
"(",
"value",
"[",
"1",
"]",
"<<",
"48",
")",
")",
"|",
"(",
"value",
"[",
"2",
"]",
"<<",
"40",
")",
")",
"|",
"(",
"value",
"[",
"3",
"]",
"<<",
"32",
")",
")",
"|",
"(",
"value",
"[",
"4",
"]",
"<<",
"24",
")",
")",
"|",
"(",
"value",
"[",
"5",
"]",
"<<",
"16",
")",
")",
"|",
"(",
"value",
"[",
"6",
"]",
"<<",
"8",
")",
")",
"|",
"value",
"[",
"7",
"]",
")"
] | converts a byte array into an integer . | train | false |
46,401 | def serialize_tree(items):
for (name, mode, hexsha) in items:
(yield ((((('%04o' % mode).encode('ascii') + ' ') + name) + '\x00') + hex_to_sha(hexsha)))
| [
"def",
"serialize_tree",
"(",
"items",
")",
":",
"for",
"(",
"name",
",",
"mode",
",",
"hexsha",
")",
"in",
"items",
":",
"(",
"yield",
"(",
"(",
"(",
"(",
"(",
"'%04o'",
"%",
"mode",
")",
".",
"encode",
"(",
"'ascii'",
")",
"+",
"' '",
")",
"+",
"name",
")",
"+",
"'\\x00'",
")",
"+",
"hex_to_sha",
"(",
"hexsha",
")",
")",
")"
] | serialize the items in a tree to a text . | train | false |
46,402 | def get_validation_set_from_train(train, train_cv):
for (new_train, new_valid) in train_cv:
return (train[new_train], train[new_valid])
| [
"def",
"get_validation_set_from_train",
"(",
"train",
",",
"train_cv",
")",
":",
"for",
"(",
"new_train",
",",
"new_valid",
")",
"in",
"train_cv",
":",
"return",
"(",
"train",
"[",
"new_train",
"]",
",",
"train",
"[",
"new_valid",
"]",
")"
] | repartition training set into training and validation sets using the given subset iterator . | train | false |
46,403 | @utils.arg('server', metavar='<server>', help=_('Name (old name) or ID of server.'))
@utils.arg('--name', metavar='<name>', dest='name', default=None, help=_('New name for the server.'))
@utils.arg('--description', metavar='<description>', dest='description', default=None, help=_('New description for the server. If it equals to empty string (i.g. ""), the server description will be removed.'), start_version='2.19')
def do_update(cs, args):
update_kwargs = {}
if args.name:
update_kwargs['name'] = args.name
if (('description' in args) and (args.description is not None)):
update_kwargs['description'] = args.description
_find_server(cs, args.server).update(**update_kwargs)
| [
"@",
"utils",
".",
"arg",
"(",
"'server'",
",",
"metavar",
"=",
"'<server>'",
",",
"help",
"=",
"_",
"(",
"'Name (old name) or ID of server.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'--name'",
",",
"metavar",
"=",
"'<name>'",
",",
"dest",
"=",
"'name'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"_",
"(",
"'New name for the server.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'--description'",
",",
"metavar",
"=",
"'<description>'",
",",
"dest",
"=",
"'description'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"_",
"(",
"'New description for the server. If it equals to empty string (i.g. \"\"), the server description will be removed.'",
")",
",",
"start_version",
"=",
"'2.19'",
")",
"def",
"do_update",
"(",
"cs",
",",
"args",
")",
":",
"update_kwargs",
"=",
"{",
"}",
"if",
"args",
".",
"name",
":",
"update_kwargs",
"[",
"'name'",
"]",
"=",
"args",
".",
"name",
"if",
"(",
"(",
"'description'",
"in",
"args",
")",
"and",
"(",
"args",
".",
"description",
"is",
"not",
"None",
")",
")",
":",
"update_kwargs",
"[",
"'description'",
"]",
"=",
"args",
".",
"description",
"_find_server",
"(",
"cs",
",",
"args",
".",
"server",
")",
".",
"update",
"(",
"**",
"update_kwargs",
")"
] | update the name or the description for a server . | train | false |
46,404 | def always_iterable(item):
if (isinstance(item, six.string_types) or (not hasattr(item, '__iter__'))):
item = (item,)
return item
| [
"def",
"always_iterable",
"(",
"item",
")",
":",
"if",
"(",
"isinstance",
"(",
"item",
",",
"six",
".",
"string_types",
")",
"or",
"(",
"not",
"hasattr",
"(",
"item",
",",
"'__iter__'",
")",
")",
")",
":",
"item",
"=",
"(",
"item",
",",
")",
"return",
"item"
] | given an object . | train | false |
46,405 | @open_file(1, mode='wb')
def write_adjlist(G, path, comments='#', delimiter=' ', encoding='utf-8'):
import sys
import time
pargs = ((comments + ' '.join(sys.argv)) + '\n')
header = ((((pargs + comments) + ' GMT {}\n'.format(time.asctime(time.gmtime()))) + comments) + ' {}\n'.format(G.name))
path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter):
line += '\n'
path.write(line.encode(encoding))
| [
"@",
"open_file",
"(",
"1",
",",
"mode",
"=",
"'wb'",
")",
"def",
"write_adjlist",
"(",
"G",
",",
"path",
",",
"comments",
"=",
"'#'",
",",
"delimiter",
"=",
"' '",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"import",
"sys",
"import",
"time",
"pargs",
"=",
"(",
"(",
"comments",
"+",
"' '",
".",
"join",
"(",
"sys",
".",
"argv",
")",
")",
"+",
"'\\n'",
")",
"header",
"=",
"(",
"(",
"(",
"(",
"pargs",
"+",
"comments",
")",
"+",
"' GMT {}\\n'",
".",
"format",
"(",
"time",
".",
"asctime",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
")",
")",
"+",
"comments",
")",
"+",
"' {}\\n'",
".",
"format",
"(",
"G",
".",
"name",
")",
")",
"path",
".",
"write",
"(",
"header",
".",
"encode",
"(",
"encoding",
")",
")",
"for",
"line",
"in",
"generate_adjlist",
"(",
"G",
",",
"delimiter",
")",
":",
"line",
"+=",
"'\\n'",
"path",
".",
"write",
"(",
"line",
".",
"encode",
"(",
"encoding",
")",
")"
] | write graph g in single-line adjacency-list format to path . | train | false |
46,406 | def end_file(fid):
data_size = 0
fid.write(np.array(FIFF.FIFF_NOP, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFT_VOID, dtype='>i4').tostring())
fid.write(np.array(data_size, dtype='>i4').tostring())
fid.write(np.array(FIFF.FIFFV_NEXT_NONE, dtype='>i4').tostring())
check_fiff_length(fid)
fid.close()
| [
"def",
"end_file",
"(",
"fid",
")",
":",
"data_size",
"=",
"0",
"fid",
".",
"write",
"(",
"np",
".",
"array",
"(",
"FIFF",
".",
"FIFF_NOP",
",",
"dtype",
"=",
"'>i4'",
")",
".",
"tostring",
"(",
")",
")",
"fid",
".",
"write",
"(",
"np",
".",
"array",
"(",
"FIFF",
".",
"FIFFT_VOID",
",",
"dtype",
"=",
"'>i4'",
")",
".",
"tostring",
"(",
")",
")",
"fid",
".",
"write",
"(",
"np",
".",
"array",
"(",
"data_size",
",",
"dtype",
"=",
"'>i4'",
")",
".",
"tostring",
"(",
")",
")",
"fid",
".",
"write",
"(",
"np",
".",
"array",
"(",
"FIFF",
".",
"FIFFV_NEXT_NONE",
",",
"dtype",
"=",
"'>i4'",
")",
".",
"tostring",
"(",
")",
")",
"check_fiff_length",
"(",
"fid",
")",
"fid",
".",
"close",
"(",
")"
] | write the closing tags to a fif file and closes the file . | train | false |
46,407 | def offset_of_timezone(timezone_name):
now = now_in_timezone(timezone_name)
offset = now.tzinfo.utcoffset(now)
minutes = ((offset.seconds / 60) + ((offset.days * 24) * 60))
return minutes
| [
"def",
"offset_of_timezone",
"(",
"timezone_name",
")",
":",
"now",
"=",
"now_in_timezone",
"(",
"timezone_name",
")",
"offset",
"=",
"now",
".",
"tzinfo",
".",
"utcoffset",
"(",
"now",
")",
"minutes",
"=",
"(",
"(",
"offset",
".",
"seconds",
"/",
"60",
")",
"+",
"(",
"(",
"offset",
".",
"days",
"*",
"24",
")",
"*",
"60",
")",
")",
"return",
"minutes"
] | return offset from utc of named time zone . | train | false |
46,409 | def merge_kwargs(local_kwarg, default_kwarg):
if (default_kwarg is None):
return local_kwarg
if isinstance(local_kwarg, str):
return local_kwarg
if (local_kwarg is None):
return default_kwarg
if (not hasattr(default_kwarg, 'items')):
return local_kwarg
default_kwarg = from_key_val_list(default_kwarg)
local_kwarg = from_key_val_list(local_kwarg)
def get_original_key(original_keys, new_key):
'\n Finds the key from original_keys that case-insensitive matches new_key.\n '
for original_key in original_keys:
if (key.lower() == original_key.lower()):
return original_key
return new_key
kwargs = default_kwarg.copy()
original_keys = kwargs.keys()
for (key, value) in local_kwarg.items():
kwargs[get_original_key(original_keys, key)] = value
for (k, v) in local_kwarg.items():
if (v is None):
del kwargs[k]
return kwargs
| [
"def",
"merge_kwargs",
"(",
"local_kwarg",
",",
"default_kwarg",
")",
":",
"if",
"(",
"default_kwarg",
"is",
"None",
")",
":",
"return",
"local_kwarg",
"if",
"isinstance",
"(",
"local_kwarg",
",",
"str",
")",
":",
"return",
"local_kwarg",
"if",
"(",
"local_kwarg",
"is",
"None",
")",
":",
"return",
"default_kwarg",
"if",
"(",
"not",
"hasattr",
"(",
"default_kwarg",
",",
"'items'",
")",
")",
":",
"return",
"local_kwarg",
"default_kwarg",
"=",
"from_key_val_list",
"(",
"default_kwarg",
")",
"local_kwarg",
"=",
"from_key_val_list",
"(",
"local_kwarg",
")",
"def",
"get_original_key",
"(",
"original_keys",
",",
"new_key",
")",
":",
"for",
"original_key",
"in",
"original_keys",
":",
"if",
"(",
"key",
".",
"lower",
"(",
")",
"==",
"original_key",
".",
"lower",
"(",
")",
")",
":",
"return",
"original_key",
"return",
"new_key",
"kwargs",
"=",
"default_kwarg",
".",
"copy",
"(",
")",
"original_keys",
"=",
"kwargs",
".",
"keys",
"(",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"local_kwarg",
".",
"items",
"(",
")",
":",
"kwargs",
"[",
"get_original_key",
"(",
"original_keys",
",",
"key",
")",
"]",
"=",
"value",
"for",
"(",
"k",
",",
"v",
")",
"in",
"local_kwarg",
".",
"items",
"(",
")",
":",
"if",
"(",
"v",
"is",
"None",
")",
":",
"del",
"kwargs",
"[",
"k",
"]",
"return",
"kwargs"
] | merges kwarg dictionaries . | train | false |
46,410 | def _unauthorized():
return Response('Unauthorized', 401, {'WWW-Authenticate': 'Negotiate'})
| [
"def",
"_unauthorized",
"(",
")",
":",
"return",
"Response",
"(",
"'Unauthorized'",
",",
"401",
",",
"{",
"'WWW-Authenticate'",
":",
"'Negotiate'",
"}",
")"
] | indicate that authorization is required :return: . | train | false |
46,411 | def case_status():
return s3_rest_controller()
| [
"def",
"case_status",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | case statuses: restful crud controller . | train | false |
46,412 | def is_complete_v3_key(v3_key):
assert (v3_key.path().element_size() >= 1)
last_element = v3_key.path().element_list()[(-1)]
return ((last_element.has_id() and (last_element.id() != 0)) or (last_element.has_name() and (last_element.name() != '')))
| [
"def",
"is_complete_v3_key",
"(",
"v3_key",
")",
":",
"assert",
"(",
"v3_key",
".",
"path",
"(",
")",
".",
"element_size",
"(",
")",
">=",
"1",
")",
"last_element",
"=",
"v3_key",
".",
"path",
"(",
")",
".",
"element_list",
"(",
")",
"[",
"(",
"-",
"1",
")",
"]",
"return",
"(",
"(",
"last_element",
".",
"has_id",
"(",
")",
"and",
"(",
"last_element",
".",
"id",
"(",
")",
"!=",
"0",
")",
")",
"or",
"(",
"last_element",
".",
"has_name",
"(",
")",
"and",
"(",
"last_element",
".",
"name",
"(",
")",
"!=",
"''",
")",
")",
")"
] | returns true if a key specifies an id or name . | train | false |
46,414 | def transform_checker(tests, transformer, **kwargs):
transformer = transformer(**kwargs)
try:
for (inp, tr) in tests:
if (inp is None):
out = transformer.reset()
else:
out = transformer.push(inp)
nt.assert_equal(out, tr)
finally:
transformer.reset()
| [
"def",
"transform_checker",
"(",
"tests",
",",
"transformer",
",",
"**",
"kwargs",
")",
":",
"transformer",
"=",
"transformer",
"(",
"**",
"kwargs",
")",
"try",
":",
"for",
"(",
"inp",
",",
"tr",
")",
"in",
"tests",
":",
"if",
"(",
"inp",
"is",
"None",
")",
":",
"out",
"=",
"transformer",
".",
"reset",
"(",
")",
"else",
":",
"out",
"=",
"transformer",
".",
"push",
"(",
"inp",
")",
"nt",
".",
"assert_equal",
"(",
"out",
",",
"tr",
")",
"finally",
":",
"transformer",
".",
"reset",
"(",
")"
] | utility to loop over test inputs . | train | false |
46,415 | def getVisibleObjectLoopsList(importRadius, visibleObjects, z):
visibleObjectLoopsList = []
for visibleObject in visibleObjects:
visibleObjectLoops = visibleObject.getLoops(importRadius, z)
visibleObjectLoopsList.append(visibleObjectLoops)
return visibleObjectLoopsList
| [
"def",
"getVisibleObjectLoopsList",
"(",
"importRadius",
",",
"visibleObjects",
",",
"z",
")",
":",
"visibleObjectLoopsList",
"=",
"[",
"]",
"for",
"visibleObject",
"in",
"visibleObjects",
":",
"visibleObjectLoops",
"=",
"visibleObject",
".",
"getLoops",
"(",
"importRadius",
",",
"z",
")",
"visibleObjectLoopsList",
".",
"append",
"(",
"visibleObjectLoops",
")",
"return",
"visibleObjectLoopsList"
] | get visible object loops list . | train | false |
46,416 | def _timestamp_from_json(value, field):
if _not_null(value, field):
return _datetime_from_microseconds((1000000.0 * float(value)))
| [
"def",
"_timestamp_from_json",
"(",
"value",
",",
"field",
")",
":",
"if",
"_not_null",
"(",
"value",
",",
"field",
")",
":",
"return",
"_datetime_from_microseconds",
"(",
"(",
"1000000.0",
"*",
"float",
"(",
"value",
")",
")",
")"
] | coerce value to a datetime . | train | false |
46,419 | def dmp_ff_lcm(f, g, u, K):
h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K)
return dmp_ground_monic(h, u, K)
| [
"def",
"dmp_ff_lcm",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
":",
"h",
"=",
"dmp_quo",
"(",
"dmp_mul",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
",",
"dmp_gcd",
"(",
"f",
",",
"g",
",",
"u",
",",
"K",
")",
",",
"u",
",",
"K",
")",
"return",
"dmp_ground_monic",
"(",
"h",
",",
"u",
",",
"K",
")"
] | computes polynomial lcm over a field in k[x] . | train | false |
46,420 | def filter_samples_from_distance_matrix(dm, samples_to_discard, negate=False):
try:
(sample_ids, dm_data) = dm
except ValueError:
(sample_ids, dm_data) = parse_distmat(dm)
sample_lookup = {}.fromkeys([e.split()[0] for e in samples_to_discard])
temp_dm_data = []
new_dm_data = []
new_sample_ids = []
if negate:
def keep_sample(s):
return (s in sample_lookup)
else:
def keep_sample(s):
return (s not in sample_lookup)
for (row, sample_id) in zip(dm_data, sample_ids):
if keep_sample(sample_id):
temp_dm_data.append(row)
new_sample_ids.append(sample_id)
temp_dm_data = array(temp_dm_data).transpose()
for (col, sample_id) in zip(temp_dm_data, sample_ids):
if keep_sample(sample_id):
new_dm_data.append(col)
new_dm_data = array(new_dm_data).transpose()
return format_distance_matrix(new_sample_ids, new_dm_data)
| [
"def",
"filter_samples_from_distance_matrix",
"(",
"dm",
",",
"samples_to_discard",
",",
"negate",
"=",
"False",
")",
":",
"try",
":",
"(",
"sample_ids",
",",
"dm_data",
")",
"=",
"dm",
"except",
"ValueError",
":",
"(",
"sample_ids",
",",
"dm_data",
")",
"=",
"parse_distmat",
"(",
"dm",
")",
"sample_lookup",
"=",
"{",
"}",
".",
"fromkeys",
"(",
"[",
"e",
".",
"split",
"(",
")",
"[",
"0",
"]",
"for",
"e",
"in",
"samples_to_discard",
"]",
")",
"temp_dm_data",
"=",
"[",
"]",
"new_dm_data",
"=",
"[",
"]",
"new_sample_ids",
"=",
"[",
"]",
"if",
"negate",
":",
"def",
"keep_sample",
"(",
"s",
")",
":",
"return",
"(",
"s",
"in",
"sample_lookup",
")",
"else",
":",
"def",
"keep_sample",
"(",
"s",
")",
":",
"return",
"(",
"s",
"not",
"in",
"sample_lookup",
")",
"for",
"(",
"row",
",",
"sample_id",
")",
"in",
"zip",
"(",
"dm_data",
",",
"sample_ids",
")",
":",
"if",
"keep_sample",
"(",
"sample_id",
")",
":",
"temp_dm_data",
".",
"append",
"(",
"row",
")",
"new_sample_ids",
".",
"append",
"(",
"sample_id",
")",
"temp_dm_data",
"=",
"array",
"(",
"temp_dm_data",
")",
".",
"transpose",
"(",
")",
"for",
"(",
"col",
",",
"sample_id",
")",
"in",
"zip",
"(",
"temp_dm_data",
",",
"sample_ids",
")",
":",
"if",
"keep_sample",
"(",
"sample_id",
")",
":",
"new_dm_data",
".",
"append",
"(",
"col",
")",
"new_dm_data",
"=",
"array",
"(",
"new_dm_data",
")",
".",
"transpose",
"(",
")",
"return",
"format_distance_matrix",
"(",
"new_sample_ids",
",",
"new_dm_data",
")"
] | remove specified samples from distance matrix dm: tuple . | train | false |
46,421 | def object_build_datadescriptor(node, member, name):
return _base_class_object_build(node, member, [], name)
| [
"def",
"object_build_datadescriptor",
"(",
"node",
",",
"member",
",",
"name",
")",
":",
"return",
"_base_class_object_build",
"(",
"node",
",",
"member",
",",
"[",
"]",
",",
"name",
")"
] | create astroid for a living data descriptor object . | train | false |
46,422 | def generate_new_element(items, prefix, numeric=False):
while True:
if numeric:
candidate = (prefix + generate_random_numeric(8))
else:
candidate = (prefix + generate_random_alphanumeric(8))
if (candidate not in items):
return candidate
LOG.debug(('Random collision on %s' % candidate))
| [
"def",
"generate_new_element",
"(",
"items",
",",
"prefix",
",",
"numeric",
"=",
"False",
")",
":",
"while",
"True",
":",
"if",
"numeric",
":",
"candidate",
"=",
"(",
"prefix",
"+",
"generate_random_numeric",
"(",
"8",
")",
")",
"else",
":",
"candidate",
"=",
"(",
"prefix",
"+",
"generate_random_alphanumeric",
"(",
"8",
")",
")",
"if",
"(",
"candidate",
"not",
"in",
"items",
")",
":",
"return",
"candidate",
"LOG",
".",
"debug",
"(",
"(",
"'Random collision on %s'",
"%",
"candidate",
")",
")"
] | creates a random string with prefix . | train | false |
46,423 | def complex_abs_impl(context, builder, sig, args):
def complex_abs(z):
return math.hypot(z.real, z.imag)
res = context.compile_internal(builder, complex_abs, sig, args)
return impl_ret_untracked(context, builder, sig.return_type, res)
| [
"def",
"complex_abs_impl",
"(",
"context",
",",
"builder",
",",
"sig",
",",
"args",
")",
":",
"def",
"complex_abs",
"(",
"z",
")",
":",
"return",
"math",
".",
"hypot",
"(",
"z",
".",
"real",
",",
"z",
".",
"imag",
")",
"res",
"=",
"context",
".",
"compile_internal",
"(",
"builder",
",",
"complex_abs",
",",
"sig",
",",
"args",
")",
"return",
"impl_ret_untracked",
"(",
"context",
",",
"builder",
",",
"sig",
".",
"return_type",
",",
"res",
")"
] | abs(z) := hypot . | train | false |
46,425 | def organization_show(context, data_dict):
return _group_or_org_show(context, data_dict, is_org=True)
| [
"def",
"organization_show",
"(",
"context",
",",
"data_dict",
")",
":",
"return",
"_group_or_org_show",
"(",
"context",
",",
"data_dict",
",",
"is_org",
"=",
"True",
")"
] | return the details of a organization . | train | false |
46,428 | def enable_server(name, backend, socket='/var/run/haproxy.sock'):
if (backend == '*'):
backends = show_backends(socket=socket).split('\n')
else:
backends = [backend]
results = {}
for backend in backends:
ha_conn = _get_conn(socket)
ha_cmd = haproxy.cmds.enableServer(server=name, backend=backend)
ha_conn.sendCmd(ha_cmd)
results[backend] = list_servers(backend, socket=socket)
return results
| [
"def",
"enable_server",
"(",
"name",
",",
"backend",
",",
"socket",
"=",
"'/var/run/haproxy.sock'",
")",
":",
"if",
"(",
"backend",
"==",
"'*'",
")",
":",
"backends",
"=",
"show_backends",
"(",
"socket",
"=",
"socket",
")",
".",
"split",
"(",
"'\\n'",
")",
"else",
":",
"backends",
"=",
"[",
"backend",
"]",
"results",
"=",
"{",
"}",
"for",
"backend",
"in",
"backends",
":",
"ha_conn",
"=",
"_get_conn",
"(",
"socket",
")",
"ha_cmd",
"=",
"haproxy",
".",
"cmds",
".",
"enableServer",
"(",
"server",
"=",
"name",
",",
"backend",
"=",
"backend",
")",
"ha_conn",
".",
"sendCmd",
"(",
"ha_cmd",
")",
"results",
"[",
"backend",
"]",
"=",
"list_servers",
"(",
"backend",
",",
"socket",
"=",
"socket",
")",
"return",
"results"
] | enable server in haproxy name server to enable backend haproxy backend . | train | true |
46,430 | def FindPackagePath(packageName, knownFileName, searchPaths):
import regutil, os
pathLook = regutil.GetRegisteredNamedPath(packageName)
if (pathLook and IsPackageDir(pathLook, packageName, knownFileName)):
return (pathLook, None)
for pathLook in searchPaths:
if IsPackageDir(pathLook, packageName, knownFileName):
ret = os.path.abspath(pathLook)
return (ret, ret)
raise error, ('The package %s can not be located' % packageName)
| [
"def",
"FindPackagePath",
"(",
"packageName",
",",
"knownFileName",
",",
"searchPaths",
")",
":",
"import",
"regutil",
",",
"os",
"pathLook",
"=",
"regutil",
".",
"GetRegisteredNamedPath",
"(",
"packageName",
")",
"if",
"(",
"pathLook",
"and",
"IsPackageDir",
"(",
"pathLook",
",",
"packageName",
",",
"knownFileName",
")",
")",
":",
"return",
"(",
"pathLook",
",",
"None",
")",
"for",
"pathLook",
"in",
"searchPaths",
":",
"if",
"IsPackageDir",
"(",
"pathLook",
",",
"packageName",
",",
"knownFileName",
")",
":",
"ret",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"pathLook",
")",
"return",
"(",
"ret",
",",
"ret",
")",
"raise",
"error",
",",
"(",
"'The package %s can not be located'",
"%",
"packageName",
")"
] | find a package . | train | false |
46,431 | def p_direct_abstract_declarator_4(t):
pass
| [
"def",
"p_direct_abstract_declarator_4",
"(",
"t",
")",
":",
"pass"
] | direct_abstract_declarator : direct_abstract_declarator lparen parameter_type_list_opt rparen . | train | false |
46,433 | def get_sum(path, form='sha256'):
path = os.path.expanduser(path)
if (not os.path.isfile(path)):
return 'File not found'
return salt.utils.get_hash(path, form, 4096)
| [
"def",
"get_sum",
"(",
"path",
",",
"form",
"=",
"'sha256'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
")",
":",
"return",
"'File not found'",
"return",
"salt",
".",
"utils",
".",
"get_hash",
"(",
"path",
",",
"form",
",",
"4096",
")"
] | return the checksum for the given file . | train | true |
46,434 | def attach_ordinal(num):
suffixes = dict(((str(i), v) for (i, v) in enumerate(['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'])))
v = str(num)
if (v in {'11', '12', '13'}):
return (v + 'th')
return (v + suffixes[v[(-1)]])
| [
"def",
"attach_ordinal",
"(",
"num",
")",
":",
"suffixes",
"=",
"dict",
"(",
"(",
"(",
"str",
"(",
"i",
")",
",",
"v",
")",
"for",
"(",
"i",
",",
"v",
")",
"in",
"enumerate",
"(",
"[",
"'th'",
",",
"'st'",
",",
"'nd'",
",",
"'rd'",
",",
"'th'",
",",
"'th'",
",",
"'th'",
",",
"'th'",
",",
"'th'",
",",
"'th'",
"]",
")",
")",
")",
"v",
"=",
"str",
"(",
"num",
")",
"if",
"(",
"v",
"in",
"{",
"'11'",
",",
"'12'",
",",
"'13'",
"}",
")",
":",
"return",
"(",
"v",
"+",
"'th'",
")",
"return",
"(",
"v",
"+",
"suffixes",
"[",
"v",
"[",
"(",
"-",
"1",
")",
"]",
"]",
")"
] | helper function to add ordinal string to integers 1 -> 1st 56 -> 56th . | train | false |
46,437 | def copyartifact_build_selector_param(registry, xml_parent, data):
t = XML.SubElement(xml_parent, 'hudson.plugins.copyartifact.BuildSelectorParameter')
try:
name = data['name']
except KeyError:
raise MissingAttributeError('name')
XML.SubElement(t, 'name').text = name
XML.SubElement(t, 'description').text = data.get('description', '')
copyartifact_build_selector(t, data, 'defaultSelector')
| [
"def",
"copyartifact_build_selector_param",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"t",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.copyartifact.BuildSelectorParameter'",
")",
"try",
":",
"name",
"=",
"data",
"[",
"'name'",
"]",
"except",
"KeyError",
":",
"raise",
"MissingAttributeError",
"(",
"'name'",
")",
"XML",
".",
"SubElement",
"(",
"t",
",",
"'name'",
")",
".",
"text",
"=",
"name",
"XML",
".",
"SubElement",
"(",
"t",
",",
"'description'",
")",
".",
"text",
"=",
"data",
".",
"get",
"(",
"'description'",
",",
"''",
")",
"copyartifact_build_selector",
"(",
"t",
",",
"data",
",",
"'defaultSelector'",
")"
] | yaml: copyartifact-build-selector control via a build parameter . | train | false |
46,438 | @staff_member_required
def update_issue(request, pk, mode=None, action=None):
issue = Issue.obj.get(pk=pk)
if (mode == 'delete'):
issue.delete()
return redir('admin:issues_issue_changelist')
else:
if (mode == 'progress'):
val = int(action)
else:
val = bool((action == 'on'))
setattr(issue, mode, val)
issue.save()
return HttpResponse('')
| [
"@",
"staff_member_required",
"def",
"update_issue",
"(",
"request",
",",
"pk",
",",
"mode",
"=",
"None",
",",
"action",
"=",
"None",
")",
":",
"issue",
"=",
"Issue",
".",
"obj",
".",
"get",
"(",
"pk",
"=",
"pk",
")",
"if",
"(",
"mode",
"==",
"'delete'",
")",
":",
"issue",
".",
"delete",
"(",
")",
"return",
"redir",
"(",
"'admin:issues_issue_changelist'",
")",
"else",
":",
"if",
"(",
"mode",
"==",
"'progress'",
")",
":",
"val",
"=",
"int",
"(",
"action",
")",
"else",
":",
"val",
"=",
"bool",
"(",
"(",
"action",
"==",
"'on'",
")",
")",
"setattr",
"(",
"issue",
",",
"mode",
",",
"val",
")",
"issue",
".",
"save",
"(",
")",
"return",
"HttpResponse",
"(",
"''",
")"
] | ajax view . | train | false |
46,439 | def checkPath(filename, reporter=None):
if (reporter is None):
reporter = modReporter._makeDefaultReporter()
try:
if (sys.version_info < (2, 7)):
mode = 'rU'
else:
mode = 'rb'
with open(filename, mode) as f:
codestr = f.read()
if (sys.version_info < (2, 7)):
codestr += '\n'
except UnicodeError:
reporter.unexpectedError(filename, 'problem decoding source')
return 1
except IOError:
msg = sys.exc_info()[1]
reporter.unexpectedError(filename, msg.args[1])
return 1
return check(codestr, filename, reporter)
| [
"def",
"checkPath",
"(",
"filename",
",",
"reporter",
"=",
"None",
")",
":",
"if",
"(",
"reporter",
"is",
"None",
")",
":",
"reporter",
"=",
"modReporter",
".",
"_makeDefaultReporter",
"(",
")",
"try",
":",
"if",
"(",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"7",
")",
")",
":",
"mode",
"=",
"'rU'",
"else",
":",
"mode",
"=",
"'rb'",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"f",
":",
"codestr",
"=",
"f",
".",
"read",
"(",
")",
"if",
"(",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"7",
")",
")",
":",
"codestr",
"+=",
"'\\n'",
"except",
"UnicodeError",
":",
"reporter",
".",
"unexpectedError",
"(",
"filename",
",",
"'problem decoding source'",
")",
"return",
"1",
"except",
"IOError",
":",
"msg",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
"reporter",
".",
"unexpectedError",
"(",
"filename",
",",
"msg",
".",
"args",
"[",
"1",
"]",
")",
"return",
"1",
"return",
"check",
"(",
"codestr",
",",
"filename",
",",
"reporter",
")"
] | check the given path . | train | false |
46,441 | def worker_create(context, **values):
return IMPL.worker_create(context, **values)
| [
"def",
"worker_create",
"(",
"context",
",",
"**",
"values",
")",
":",
"return",
"IMPL",
".",
"worker_create",
"(",
"context",
",",
"**",
"values",
")"
] | create a worker entry from optional arguments . | train | false |
46,442 | def _fix_query_encoding(parse_result):
query_params = parse_qsl(parse_result.query, keep_blank_values=True)
return parse_result._replace(query=urllib.urlencode(query_params))
| [
"def",
"_fix_query_encoding",
"(",
"parse_result",
")",
":",
"query_params",
"=",
"parse_qsl",
"(",
"parse_result",
".",
"query",
",",
"keep_blank_values",
"=",
"True",
")",
"return",
"parse_result",
".",
"_replace",
"(",
"query",
"=",
"urllib",
".",
"urlencode",
"(",
"query_params",
")",
")"
] | fix encoding in the query string . | train | false |
46,444 | def get_masked_string(s, p):
return fromstring(s, dtype=uint8)[p].tostring()
| [
"def",
"get_masked_string",
"(",
"s",
",",
"p",
")",
":",
"return",
"fromstring",
"(",
"s",
",",
"dtype",
"=",
"uint8",
")",
"[",
"p",
"]",
".",
"tostring",
"(",
")"
] | extracts valid positions in string s using index array p . | train | false |
46,445 | def read_index(group):
return (u'%s_%s' % (settings.ES_INDEX_PREFIX, settings.ES_INDEXES[group]))
| [
"def",
"read_index",
"(",
"group",
")",
":",
"return",
"(",
"u'%s_%s'",
"%",
"(",
"settings",
".",
"ES_INDEX_PREFIX",
",",
"settings",
".",
"ES_INDEXES",
"[",
"group",
"]",
")",
")"
] | gets the name of the read index for a group . | train | false |
46,447 | def del_nic(si, vm, nic_number):
nic_prefix_label = 'Network adapter '
nic_label = (nic_prefix_label + str(nic_number))
virtual_nic_device = None
for dev in vm.config.hardware.device:
if (isinstance(dev, vim.vm.device.VirtualEthernetCard) and (dev.deviceInfo.label == nic_label)):
virtual_nic_device = dev
if (not virtual_nic_device):
raise RuntimeError('Virtual {} could not be found.'.format(nic_label))
virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
virtual_nic_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove
virtual_nic_spec.device = virtual_nic_device
spec = vim.vm.ConfigSpec()
spec.deviceChange = [virtual_nic_spec]
task = vm.ReconfigVM_Task(spec=spec)
tasks.wait_for_tasks(si, [task])
return True
| [
"def",
"del_nic",
"(",
"si",
",",
"vm",
",",
"nic_number",
")",
":",
"nic_prefix_label",
"=",
"'Network adapter '",
"nic_label",
"=",
"(",
"nic_prefix_label",
"+",
"str",
"(",
"nic_number",
")",
")",
"virtual_nic_device",
"=",
"None",
"for",
"dev",
"in",
"vm",
".",
"config",
".",
"hardware",
".",
"device",
":",
"if",
"(",
"isinstance",
"(",
"dev",
",",
"vim",
".",
"vm",
".",
"device",
".",
"VirtualEthernetCard",
")",
"and",
"(",
"dev",
".",
"deviceInfo",
".",
"label",
"==",
"nic_label",
")",
")",
":",
"virtual_nic_device",
"=",
"dev",
"if",
"(",
"not",
"virtual_nic_device",
")",
":",
"raise",
"RuntimeError",
"(",
"'Virtual {} could not be found.'",
".",
"format",
"(",
"nic_label",
")",
")",
"virtual_nic_spec",
"=",
"vim",
".",
"vm",
".",
"device",
".",
"VirtualDeviceSpec",
"(",
")",
"virtual_nic_spec",
".",
"operation",
"=",
"vim",
".",
"vm",
".",
"device",
".",
"VirtualDeviceSpec",
".",
"Operation",
".",
"remove",
"virtual_nic_spec",
".",
"device",
"=",
"virtual_nic_device",
"spec",
"=",
"vim",
".",
"vm",
".",
"ConfigSpec",
"(",
")",
"spec",
".",
"deviceChange",
"=",
"[",
"virtual_nic_spec",
"]",
"task",
"=",
"vm",
".",
"ReconfigVM_Task",
"(",
"spec",
"=",
"spec",
")",
"tasks",
".",
"wait_for_tasks",
"(",
"si",
",",
"[",
"task",
"]",
")",
"return",
"True"
] | deletes virtual nic based on nic number . | train | false |
46,449 | def max_filename_length(path, limit=MAX_FILENAME_LENGTH):
if hasattr(os, 'statvfs'):
try:
res = os.statvfs(path)
except OSError:
return limit
return min(res[9], limit)
else:
return limit
| [
"def",
"max_filename_length",
"(",
"path",
",",
"limit",
"=",
"MAX_FILENAME_LENGTH",
")",
":",
"if",
"hasattr",
"(",
"os",
",",
"'statvfs'",
")",
":",
"try",
":",
"res",
"=",
"os",
".",
"statvfs",
"(",
"path",
")",
"except",
"OSError",
":",
"return",
"limit",
"return",
"min",
"(",
"res",
"[",
"9",
"]",
",",
"limit",
")",
"else",
":",
"return",
"limit"
] | attempt to determine the maximum filename length for the filesystem containing path . | train | false |
46,451 | def display_to_paper(x, y, layout):
num_x = (x - layout['margin']['l'])
den_x = (layout['width'] - (layout['margin']['l'] + layout['margin']['r']))
num_y = (y - layout['margin']['b'])
den_y = (layout['height'] - (layout['margin']['b'] + layout['margin']['t']))
return ((num_x / den_x), (num_y / den_y))
| [
"def",
"display_to_paper",
"(",
"x",
",",
"y",
",",
"layout",
")",
":",
"num_x",
"=",
"(",
"x",
"-",
"layout",
"[",
"'margin'",
"]",
"[",
"'l'",
"]",
")",
"den_x",
"=",
"(",
"layout",
"[",
"'width'",
"]",
"-",
"(",
"layout",
"[",
"'margin'",
"]",
"[",
"'l'",
"]",
"+",
"layout",
"[",
"'margin'",
"]",
"[",
"'r'",
"]",
")",
")",
"num_y",
"=",
"(",
"y",
"-",
"layout",
"[",
"'margin'",
"]",
"[",
"'b'",
"]",
")",
"den_y",
"=",
"(",
"layout",
"[",
"'height'",
"]",
"-",
"(",
"layout",
"[",
"'margin'",
"]",
"[",
"'b'",
"]",
"+",
"layout",
"[",
"'margin'",
"]",
"[",
"'t'",
"]",
")",
")",
"return",
"(",
"(",
"num_x",
"/",
"den_x",
")",
",",
"(",
"num_y",
"/",
"den_y",
")",
")"
] | convert mpl display coordinates to plotly paper coordinates . | train | false |
46,452 | def mac2eui64(mac, prefix=None):
eui64 = re.sub('[.:-]', '', mac).lower()
eui64 = ((eui64[0:6] + 'fffe') + eui64[6:])
eui64 = (hex((int(eui64[0:2], 16) | 2))[2:].zfill(2) + eui64[2:])
if (prefix is None):
return ':'.join(re.findall('.{4}', eui64))
else:
try:
net = ipaddress.ip_network(prefix, strict=False)
euil = int('0x{0}'.format(eui64), 16)
return '{0}/{1}'.format(net[euil], net.prefixlen)
except:
return
| [
"def",
"mac2eui64",
"(",
"mac",
",",
"prefix",
"=",
"None",
")",
":",
"eui64",
"=",
"re",
".",
"sub",
"(",
"'[.:-]'",
",",
"''",
",",
"mac",
")",
".",
"lower",
"(",
")",
"eui64",
"=",
"(",
"(",
"eui64",
"[",
"0",
":",
"6",
"]",
"+",
"'fffe'",
")",
"+",
"eui64",
"[",
"6",
":",
"]",
")",
"eui64",
"=",
"(",
"hex",
"(",
"(",
"int",
"(",
"eui64",
"[",
"0",
":",
"2",
"]",
",",
"16",
")",
"|",
"2",
")",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"2",
")",
"+",
"eui64",
"[",
"2",
":",
"]",
")",
"if",
"(",
"prefix",
"is",
"None",
")",
":",
"return",
"':'",
".",
"join",
"(",
"re",
".",
"findall",
"(",
"'.{4}'",
",",
"eui64",
")",
")",
"else",
":",
"try",
":",
"net",
"=",
"ipaddress",
".",
"ip_network",
"(",
"prefix",
",",
"strict",
"=",
"False",
")",
"euil",
"=",
"int",
"(",
"'0x{0}'",
".",
"format",
"(",
"eui64",
")",
",",
"16",
")",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"net",
"[",
"euil",
"]",
",",
"net",
".",
"prefixlen",
")",
"except",
":",
"return"
] | convert a mac address to a eui64 identifier or . | train | true |
46,455 | def bypass(result, func, *args, **kw):
d = maybeDeferred(func, *args, **kw)
d.addErrback(logError)
d.addBoth((lambda ignored: result))
return d
| [
"def",
"bypass",
"(",
"result",
",",
"func",
",",
"*",
"args",
",",
"**",
"kw",
")",
":",
"d",
"=",
"maybeDeferred",
"(",
"func",
",",
"*",
"args",
",",
"**",
"kw",
")",
"d",
".",
"addErrback",
"(",
"logError",
")",
"d",
".",
"addBoth",
"(",
"(",
"lambda",
"ignored",
":",
"result",
")",
")",
"return",
"d"
] | perform the function . | train | false |
46,456 | def assert_header_parsing(headers):
if (not isinstance(headers, httplib.HTTPMessage)):
raise TypeError('expected httplib.Message, got {0}.'.format(type(headers)))
defects = getattr(headers, 'defects', None)
get_payload = getattr(headers, 'get_payload', None)
unparsed_data = None
if get_payload:
unparsed_data = get_payload()
if (defects or unparsed_data):
raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
| [
"def",
"assert_header_parsing",
"(",
"headers",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"headers",
",",
"httplib",
".",
"HTTPMessage",
")",
")",
":",
"raise",
"TypeError",
"(",
"'expected httplib.Message, got {0}.'",
".",
"format",
"(",
"type",
"(",
"headers",
")",
")",
")",
"defects",
"=",
"getattr",
"(",
"headers",
",",
"'defects'",
",",
"None",
")",
"get_payload",
"=",
"getattr",
"(",
"headers",
",",
"'get_payload'",
",",
"None",
")",
"unparsed_data",
"=",
"None",
"if",
"get_payload",
":",
"unparsed_data",
"=",
"get_payload",
"(",
")",
"if",
"(",
"defects",
"or",
"unparsed_data",
")",
":",
"raise",
"HeaderParsingError",
"(",
"defects",
"=",
"defects",
",",
"unparsed_data",
"=",
"unparsed_data",
")"
] | asserts whether all headers have been successfully parsed . | train | true |
46,457 | def get_ladder_escape(state):
feature = np.zeros((1, state.size, state.size))
for (x, y) in state.get_legal_moves():
feature[(0, x, y)] = state.is_ladder_escape((x, y))
return feature
| [
"def",
"get_ladder_escape",
"(",
"state",
")",
":",
"feature",
"=",
"np",
".",
"zeros",
"(",
"(",
"1",
",",
"state",
".",
"size",
",",
"state",
".",
"size",
")",
")",
"for",
"(",
"x",
",",
"y",
")",
"in",
"state",
".",
"get_legal_moves",
"(",
")",
":",
"feature",
"[",
"(",
"0",
",",
"x",
",",
"y",
")",
"]",
"=",
"state",
".",
"is_ladder_escape",
"(",
"(",
"x",
",",
"y",
")",
")",
"return",
"feature"
] | a feature wrapping gamestate . | train | false |
46,458 | def underline_node_formatter(nodetext, optionstext, caller=None):
nodetext_width_max = max((m_len(line) for line in nodetext.split('\n')))
options_width_max = max((m_len(line) for line in optionstext.split('\n')))
total_width = max(options_width_max, nodetext_width_max)
separator1 = ((('_' * total_width) + '\n\n') if nodetext_width_max else '')
separator2 = ((('\n' + ('_' * total_width)) + '\n\n') if total_width else '')
return ((((((separator1 + '|n') + nodetext) + '|n') + separator2) + '|n') + optionstext)
| [
"def",
"underline_node_formatter",
"(",
"nodetext",
",",
"optionstext",
",",
"caller",
"=",
"None",
")",
":",
"nodetext_width_max",
"=",
"max",
"(",
"(",
"m_len",
"(",
"line",
")",
"for",
"line",
"in",
"nodetext",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"options_width_max",
"=",
"max",
"(",
"(",
"m_len",
"(",
"line",
")",
"for",
"line",
"in",
"optionstext",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"total_width",
"=",
"max",
"(",
"options_width_max",
",",
"nodetext_width_max",
")",
"separator1",
"=",
"(",
"(",
"(",
"'_'",
"*",
"total_width",
")",
"+",
"'\\n\\n'",
")",
"if",
"nodetext_width_max",
"else",
"''",
")",
"separator2",
"=",
"(",
"(",
"(",
"'\\n'",
"+",
"(",
"'_'",
"*",
"total_width",
")",
")",
"+",
"'\\n\\n'",
")",
"if",
"total_width",
"else",
"''",
")",
"return",
"(",
"(",
"(",
"(",
"(",
"(",
"separator1",
"+",
"'|n'",
")",
"+",
"nodetext",
")",
"+",
"'|n'",
")",
"+",
"separator2",
")",
"+",
"'|n'",
")",
"+",
"optionstext",
")"
] | draws a node with underlines _____ around it . | train | false |
46,459 | def test_xml_filters_change_bars():
plot = Bar(legend_at_bottom=True, explicit_size=True, width=800, height=600)
A = [60, 75, 80, 78, 83, 90]
B = [92, 87, 81, 73, 68, 55]
plot.add('A', A)
plot.add('B', B)
plot.add_xml_filter(ChangeBarsXMLFilter(A, B))
q = plot.render_tree()
assert (len(q.findall('g')) == 2)
assert (q.findall('g')[1].attrib['transform'] == 'translate(0,150), scale(1,0.75)')
| [
"def",
"test_xml_filters_change_bars",
"(",
")",
":",
"plot",
"=",
"Bar",
"(",
"legend_at_bottom",
"=",
"True",
",",
"explicit_size",
"=",
"True",
",",
"width",
"=",
"800",
",",
"height",
"=",
"600",
")",
"A",
"=",
"[",
"60",
",",
"75",
",",
"80",
",",
"78",
",",
"83",
",",
"90",
"]",
"B",
"=",
"[",
"92",
",",
"87",
",",
"81",
",",
"73",
",",
"68",
",",
"55",
"]",
"plot",
".",
"add",
"(",
"'A'",
",",
"A",
")",
"plot",
".",
"add",
"(",
"'B'",
",",
"B",
")",
"plot",
".",
"add_xml_filter",
"(",
"ChangeBarsXMLFilter",
"(",
"A",
",",
"B",
")",
")",
"q",
"=",
"plot",
".",
"render_tree",
"(",
")",
"assert",
"(",
"len",
"(",
"q",
".",
"findall",
"(",
"'g'",
")",
")",
"==",
"2",
")",
"assert",
"(",
"q",
".",
"findall",
"(",
"'g'",
")",
"[",
"1",
"]",
".",
"attrib",
"[",
"'transform'",
"]",
"==",
"'translate(0,150), scale(1,0.75)'",
")"
] | test the use a xml filter . | train | false |
46,460 | def ncenter_path():
tool = os.path.normpath(os.path.join(sabnzbd.DIR_PROG, '../Resources/SABnzbd.app/Contents/MacOS/SABnzbd'))
if os.path.exists(tool):
return tool
else:
return None
| [
"def",
"ncenter_path",
"(",
")",
":",
"tool",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sabnzbd",
".",
"DIR_PROG",
",",
"'../Resources/SABnzbd.app/Contents/MacOS/SABnzbd'",
")",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"tool",
")",
":",
"return",
"tool",
"else",
":",
"return",
"None"
] | return path of notification center tool . | train | false |
46,462 | @pytest.mark.parametrize('cmd', [':message-error test', ':jseval console.log("[FAIL] test");'])
def test_quteproc_error_message(qtbot, quteproc, cmd, request_mock):
with qtbot.waitSignal(quteproc.got_error):
quteproc.send_cmd(cmd)
with pytest.raises(pytest.fail.Exception):
quteproc.after_test()
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'cmd'",
",",
"[",
"':message-error test'",
",",
"':jseval console.log(\"[FAIL] test\");'",
"]",
")",
"def",
"test_quteproc_error_message",
"(",
"qtbot",
",",
"quteproc",
",",
"cmd",
",",
"request_mock",
")",
":",
"with",
"qtbot",
".",
"waitSignal",
"(",
"quteproc",
".",
"got_error",
")",
":",
"quteproc",
".",
"send_cmd",
"(",
"cmd",
")",
"with",
"pytest",
".",
"raises",
"(",
"pytest",
".",
"fail",
".",
"Exception",
")",
":",
"quteproc",
".",
"after_test",
"(",
")"
] | make sure the test fails with an unexpected error message . | train | false |
46,463 | def _parse_proxmox_upid(node, vm_=None):
ret = {}
upid = node
node = node.split(':')
if (node[0] == 'UPID'):
ret['node'] = str(node[1])
ret['pid'] = str(node[2])
ret['pstart'] = str(node[3])
ret['starttime'] = str(node[4])
ret['type'] = str(node[5])
ret['vmid'] = str(node[6])
ret['user'] = str(node[7])
ret['upid'] = str(upid)
if ((vm_ is not None) and ('technology' in vm_)):
ret['technology'] = str(vm_['technology'])
return ret
| [
"def",
"_parse_proxmox_upid",
"(",
"node",
",",
"vm_",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"upid",
"=",
"node",
"node",
"=",
"node",
".",
"split",
"(",
"':'",
")",
"if",
"(",
"node",
"[",
"0",
"]",
"==",
"'UPID'",
")",
":",
"ret",
"[",
"'node'",
"]",
"=",
"str",
"(",
"node",
"[",
"1",
"]",
")",
"ret",
"[",
"'pid'",
"]",
"=",
"str",
"(",
"node",
"[",
"2",
"]",
")",
"ret",
"[",
"'pstart'",
"]",
"=",
"str",
"(",
"node",
"[",
"3",
"]",
")",
"ret",
"[",
"'starttime'",
"]",
"=",
"str",
"(",
"node",
"[",
"4",
"]",
")",
"ret",
"[",
"'type'",
"]",
"=",
"str",
"(",
"node",
"[",
"5",
"]",
")",
"ret",
"[",
"'vmid'",
"]",
"=",
"str",
"(",
"node",
"[",
"6",
"]",
")",
"ret",
"[",
"'user'",
"]",
"=",
"str",
"(",
"node",
"[",
"7",
"]",
")",
"ret",
"[",
"'upid'",
"]",
"=",
"str",
"(",
"upid",
")",
"if",
"(",
"(",
"vm_",
"is",
"not",
"None",
")",
"and",
"(",
"'technology'",
"in",
"vm_",
")",
")",
":",
"ret",
"[",
"'technology'",
"]",
"=",
"str",
"(",
"vm_",
"[",
"'technology'",
"]",
")",
"return",
"ret"
] | upon requesting a task that runs for a longer period of time a upid is given . | train | false |
46,466 | def test_default_imports():
code = 'if 1:\n import dask\n import sys\n\n print(sorted(sys.modules))\n '
out = subprocess.check_output([sys.executable, '-c', code])
modules = set(eval(out.decode()))
assert ('dask' in modules)
blacklist = ['dask.array', 'dask.dataframe', 'numpy', 'pandas', 'partd', 's3fs', 'distributed']
for mod in blacklist:
assert (mod not in modules)
| [
"def",
"test_default_imports",
"(",
")",
":",
"code",
"=",
"'if 1:\\n import dask\\n import sys\\n\\n print(sorted(sys.modules))\\n '",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"sys",
".",
"executable",
",",
"'-c'",
",",
"code",
"]",
")",
"modules",
"=",
"set",
"(",
"eval",
"(",
"out",
".",
"decode",
"(",
")",
")",
")",
"assert",
"(",
"'dask'",
"in",
"modules",
")",
"blacklist",
"=",
"[",
"'dask.array'",
",",
"'dask.dataframe'",
",",
"'numpy'",
",",
"'pandas'",
",",
"'partd'",
",",
"'s3fs'",
",",
"'distributed'",
"]",
"for",
"mod",
"in",
"blacklist",
":",
"assert",
"(",
"mod",
"not",
"in",
"modules",
")"
] | startup time: import dask should not import too many modules . | train | false |
46,467 | def configure_service_cache(service, test_name):
service.http_client.v2_http_client.cache_test_name = test_name
cache_name = service.http_client.v2_http_client.get_cache_file_name()
if (options.get_value('clearcache') == 'true'):
service.http_client.v2_http_client.delete_session(cache_name)
service.http_client.v2_http_client.use_cached_session(cache_name)
| [
"def",
"configure_service_cache",
"(",
"service",
",",
"test_name",
")",
":",
"service",
".",
"http_client",
".",
"v2_http_client",
".",
"cache_test_name",
"=",
"test_name",
"cache_name",
"=",
"service",
".",
"http_client",
".",
"v2_http_client",
".",
"get_cache_file_name",
"(",
")",
"if",
"(",
"options",
".",
"get_value",
"(",
"'clearcache'",
")",
"==",
"'true'",
")",
":",
"service",
".",
"http_client",
".",
"v2_http_client",
".",
"delete_session",
"(",
"cache_name",
")",
"service",
".",
"http_client",
".",
"v2_http_client",
".",
"use_cached_session",
"(",
"cache_name",
")"
] | loads or starts a session recording for a v1 service object . | train | false |
46,468 | def Execute(cmd, args, time_limit=(-1), bypass_whitelist=False, daemon=False, use_client_context=False, cwd=None):
if ((not bypass_whitelist) and (not IsExecutionWhitelisted(cmd, args))):
logging.info('Execution disallowed by whitelist: %s %s.', cmd, ' '.join(args))
return ('', 'Execution disallowed by whitelist.', (-1), (-1))
if daemon:
pid = os.fork()
if (pid == 0):
try:
os.setsid()
except OSError:
pass
_Execute(cmd, args, time_limit, use_client_context=use_client_context, cwd=cwd)
os._exit(0)
else:
return _Execute(cmd, args, time_limit, use_client_context=use_client_context, cwd=cwd)
| [
"def",
"Execute",
"(",
"cmd",
",",
"args",
",",
"time_limit",
"=",
"(",
"-",
"1",
")",
",",
"bypass_whitelist",
"=",
"False",
",",
"daemon",
"=",
"False",
",",
"use_client_context",
"=",
"False",
",",
"cwd",
"=",
"None",
")",
":",
"if",
"(",
"(",
"not",
"bypass_whitelist",
")",
"and",
"(",
"not",
"IsExecutionWhitelisted",
"(",
"cmd",
",",
"args",
")",
")",
")",
":",
"logging",
".",
"info",
"(",
"'Execution disallowed by whitelist: %s %s.'",
",",
"cmd",
",",
"' '",
".",
"join",
"(",
"args",
")",
")",
"return",
"(",
"''",
",",
"'Execution disallowed by whitelist.'",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
"if",
"daemon",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"(",
"pid",
"==",
"0",
")",
":",
"try",
":",
"os",
".",
"setsid",
"(",
")",
"except",
"OSError",
":",
"pass",
"_Execute",
"(",
"cmd",
",",
"args",
",",
"time_limit",
",",
"use_client_context",
"=",
"use_client_context",
",",
"cwd",
"=",
"cwd",
")",
"os",
".",
"_exit",
"(",
"0",
")",
"else",
":",
"return",
"_Execute",
"(",
"cmd",
",",
"args",
",",
"time_limit",
",",
"use_client_context",
"=",
"use_client_context",
",",
"cwd",
"=",
"cwd",
")"
] | executes commands on the client . | train | true |
46,469 | def motion_regressors(motion_params, order=0, derivatives=1):
import numpy as np
out_files = []
for (idx, filename) in enumerate(filename_to_list(motion_params)):
params = np.genfromtxt(filename)
out_params = params
for d in range(1, (derivatives + 1)):
cparams = np.vstack((np.repeat(params[0, :][None, :], d, axis=0), params))
out_params = np.hstack((out_params, np.diff(cparams, d, axis=0)))
out_params2 = out_params
for i in range(2, (order + 1)):
out_params2 = np.hstack((out_params2, np.power(out_params, i)))
filename = os.path.join(os.getcwd(), (u'motion_regressor%02d.txt' % idx))
np.savetxt(filename, out_params2, fmt='%.10f')
out_files.append(filename)
return out_files
| [
"def",
"motion_regressors",
"(",
"motion_params",
",",
"order",
"=",
"0",
",",
"derivatives",
"=",
"1",
")",
":",
"import",
"numpy",
"as",
"np",
"out_files",
"=",
"[",
"]",
"for",
"(",
"idx",
",",
"filename",
")",
"in",
"enumerate",
"(",
"filename_to_list",
"(",
"motion_params",
")",
")",
":",
"params",
"=",
"np",
".",
"genfromtxt",
"(",
"filename",
")",
"out_params",
"=",
"params",
"for",
"d",
"in",
"range",
"(",
"1",
",",
"(",
"derivatives",
"+",
"1",
")",
")",
":",
"cparams",
"=",
"np",
".",
"vstack",
"(",
"(",
"np",
".",
"repeat",
"(",
"params",
"[",
"0",
",",
":",
"]",
"[",
"None",
",",
":",
"]",
",",
"d",
",",
"axis",
"=",
"0",
")",
",",
"params",
")",
")",
"out_params",
"=",
"np",
".",
"hstack",
"(",
"(",
"out_params",
",",
"np",
".",
"diff",
"(",
"cparams",
",",
"d",
",",
"axis",
"=",
"0",
")",
")",
")",
"out_params2",
"=",
"out_params",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"(",
"order",
"+",
"1",
")",
")",
":",
"out_params2",
"=",
"np",
".",
"hstack",
"(",
"(",
"out_params2",
",",
"np",
".",
"power",
"(",
"out_params",
",",
"i",
")",
")",
")",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"(",
"u'motion_regressor%02d.txt'",
"%",
"idx",
")",
")",
"np",
".",
"savetxt",
"(",
"filename",
",",
"out_params2",
",",
"fmt",
"=",
"'%.10f'",
")",
"out_files",
".",
"append",
"(",
"filename",
")",
"return",
"out_files"
] | compute motion regressors upto given order and derivative motion + d/dt + d2/dt2 . | train | false |
46,470 | def kill(coro):
return KillEvent(coro)
| [
"def",
"kill",
"(",
"coro",
")",
":",
"return",
"KillEvent",
"(",
"coro",
")"
] | kill containers in the docker-compose file . | train | false |
46,475 | @pytest.fixture(scope='session')
def clean_jedi_cache(request):
from jedi import settings
old = settings.cache_directory
tmp = tempfile.mkdtemp(prefix='jedi-test-')
settings.cache_directory = tmp
@request.addfinalizer
def restore():
settings.cache_directory = old
shutil.rmtree(tmp)
| [
"@",
"pytest",
".",
"fixture",
"(",
"scope",
"=",
"'session'",
")",
"def",
"clean_jedi_cache",
"(",
"request",
")",
":",
"from",
"jedi",
"import",
"settings",
"old",
"=",
"settings",
".",
"cache_directory",
"tmp",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'jedi-test-'",
")",
"settings",
".",
"cache_directory",
"=",
"tmp",
"@",
"request",
".",
"addfinalizer",
"def",
"restore",
"(",
")",
":",
"settings",
".",
"cache_directory",
"=",
"old",
"shutil",
".",
"rmtree",
"(",
"tmp",
")"
] | set jedi . | train | false |
46,476 | def quorum(name, **kwargs):
paramters = _ordereddict2dict(kwargs)
if (paramters is None):
return _error(name, 'Invalid paramters:%s')
if __opts__['test']:
return _test(name, 'cluster quorum')
try:
cluster_quorum = __salt__['ceph.cluster_quorum'](**paramters)
except (CommandExecutionError, CommandNotFoundError) as err:
return _error(name, err.strerror)
if cluster_quorum:
return _unchanged(name, 'cluster is quorum')
return _error(name, 'cluster is not quorum')
| [
"def",
"quorum",
"(",
"name",
",",
"**",
"kwargs",
")",
":",
"paramters",
"=",
"_ordereddict2dict",
"(",
"kwargs",
")",
"if",
"(",
"paramters",
"is",
"None",
")",
":",
"return",
"_error",
"(",
"name",
",",
"'Invalid paramters:%s'",
")",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"return",
"_test",
"(",
"name",
",",
"'cluster quorum'",
")",
"try",
":",
"cluster_quorum",
"=",
"__salt__",
"[",
"'ceph.cluster_quorum'",
"]",
"(",
"**",
"paramters",
")",
"except",
"(",
"CommandExecutionError",
",",
"CommandNotFoundError",
")",
"as",
"err",
":",
"return",
"_error",
"(",
"name",
",",
"err",
".",
"strerror",
")",
"if",
"cluster_quorum",
":",
"return",
"_unchanged",
"(",
"name",
",",
"'cluster is quorum'",
")",
"return",
"_error",
"(",
"name",
",",
"'cluster is not quorum'",
")"
] | quorum state this state checks the mon daemons are in quorum . | train | true |
46,477 | def _create_rpmmacros():
home = os.path.expanduser('~')
rpmbuilddir = os.path.join(home, 'rpmbuild')
if (not os.path.isdir(rpmbuilddir)):
os.makedirs(rpmbuilddir)
mockdir = os.path.join(home, 'mock')
if (not os.path.isdir(mockdir)):
os.makedirs(mockdir)
rpmmacros = os.path.join(home, '.rpmmacros')
with salt.utils.fopen(rpmmacros, 'w') as afile:
afile.write('%_topdir {0}\n'.format(rpmbuilddir))
afile.write('%signature gpg\n')
afile.write('%_gpg_name packaging@saltstack.com\n')
| [
"def",
"_create_rpmmacros",
"(",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"rpmbuilddir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'rpmbuild'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"rpmbuilddir",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"rpmbuilddir",
")",
"mockdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'mock'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"mockdir",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"mockdir",
")",
"rpmmacros",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"'.rpmmacros'",
")",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"rpmmacros",
",",
"'w'",
")",
"as",
"afile",
":",
"afile",
".",
"write",
"(",
"'%_topdir {0}\\n'",
".",
"format",
"(",
"rpmbuilddir",
")",
")",
"afile",
".",
"write",
"(",
"'%signature gpg\\n'",
")",
"afile",
".",
"write",
"(",
"'%_gpg_name packaging@saltstack.com\\n'",
")"
] | create the . | train | false |
46,478 | def get_installable_version(version):
parsed_version = parse_version(version)
return parsed_version.installable_release
| [
"def",
"get_installable_version",
"(",
"version",
")",
":",
"parsed_version",
"=",
"parse_version",
"(",
"version",
")",
"return",
"parsed_version",
".",
"installable_release"
] | get the version string of the latest version of flocker which can be installed . | train | false |
46,479 | def get_decryption_oracle(secret_name):
assert (secret_name in ('SECRET_ENCRYPTION_KEY', 'BLOCK_ENCRYPTION_KEY'))
return _DecryptionOracle(secret_name)
| [
"def",
"get_decryption_oracle",
"(",
"secret_name",
")",
":",
"assert",
"(",
"secret_name",
"in",
"(",
"'SECRET_ENCRYPTION_KEY'",
",",
"'BLOCK_ENCRYPTION_KEY'",
")",
")",
"return",
"_DecryptionOracle",
"(",
"secret_name",
")"
] | return an decryption oracle for the given secret . | train | false |
46,480 | def test_tl_init():
tl = TomekLinks(random_state=RND_SEED)
assert_equal(tl.n_jobs, 1)
assert_equal(tl.random_state, RND_SEED)
| [
"def",
"test_tl_init",
"(",
")",
":",
"tl",
"=",
"TomekLinks",
"(",
"random_state",
"=",
"RND_SEED",
")",
"assert_equal",
"(",
"tl",
".",
"n_jobs",
",",
"1",
")",
"assert_equal",
"(",
"tl",
".",
"random_state",
",",
"RND_SEED",
")"
] | test the initialisation of the object . | train | false |
46,481 | def preinit():
global _initialized
if (_initialized >= 1):
return
try:
from . import BmpImagePlugin
except ImportError:
pass
try:
from . import GifImagePlugin
except ImportError:
pass
try:
from . import JpegImagePlugin
except ImportError:
pass
try:
from . import PpmImagePlugin
except ImportError:
pass
try:
from . import PngImagePlugin
except ImportError:
pass
_initialized = 1
| [
"def",
"preinit",
"(",
")",
":",
"global",
"_initialized",
"if",
"(",
"_initialized",
">=",
"1",
")",
":",
"return",
"try",
":",
"from",
".",
"import",
"BmpImagePlugin",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
".",
"import",
"GifImagePlugin",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
".",
"import",
"JpegImagePlugin",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
".",
"import",
"PpmImagePlugin",
"except",
"ImportError",
":",
"pass",
"try",
":",
"from",
".",
"import",
"PngImagePlugin",
"except",
"ImportError",
":",
"pass",
"_initialized",
"=",
"1"
] | explicitly load standard file format drivers . | train | false |
46,483 | def check_session_id_signature(session_id, secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()):
secret_key = _ensure_bytes(secret_key)
if signed:
pieces = session_id.split('-', 1)
if (len(pieces) != 2):
return False
base_id = pieces[0]
provided_signature = pieces[1]
expected_signature = _signature(base_id, secret_key)
return hmac.compare_digest(expected_signature, provided_signature)
else:
return True
| [
"def",
"check_session_id_signature",
"(",
"session_id",
",",
"secret_key",
"=",
"settings",
".",
"secret_key_bytes",
"(",
")",
",",
"signed",
"=",
"settings",
".",
"sign_sessions",
"(",
")",
")",
":",
"secret_key",
"=",
"_ensure_bytes",
"(",
"secret_key",
")",
"if",
"signed",
":",
"pieces",
"=",
"session_id",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"if",
"(",
"len",
"(",
"pieces",
")",
"!=",
"2",
")",
":",
"return",
"False",
"base_id",
"=",
"pieces",
"[",
"0",
"]",
"provided_signature",
"=",
"pieces",
"[",
"1",
"]",
"expected_signature",
"=",
"_signature",
"(",
"base_id",
",",
"secret_key",
")",
"return",
"hmac",
".",
"compare_digest",
"(",
"expected_signature",
",",
"provided_signature",
")",
"else",
":",
"return",
"True"
] | check the signature of a session id . | train | true |
46,484 | def test_show_verbose(script):
result = script.pip('show', '--verbose', 'pip')
lines = result.stdout.splitlines()
assert any((line.startswith('Metadata-Version: ') for line in lines))
assert any((line.startswith('Installer: ') for line in lines))
assert ('Entry-points:' in lines)
assert ('Classifiers:' in lines)
| [
"def",
"test_show_verbose",
"(",
"script",
")",
":",
"result",
"=",
"script",
".",
"pip",
"(",
"'show'",
",",
"'--verbose'",
",",
"'pip'",
")",
"lines",
"=",
"result",
".",
"stdout",
".",
"splitlines",
"(",
")",
"assert",
"any",
"(",
"(",
"line",
".",
"startswith",
"(",
"'Metadata-Version: '",
")",
"for",
"line",
"in",
"lines",
")",
")",
"assert",
"any",
"(",
"(",
"line",
".",
"startswith",
"(",
"'Installer: '",
")",
"for",
"line",
"in",
"lines",
")",
")",
"assert",
"(",
"'Entry-points:'",
"in",
"lines",
")",
"assert",
"(",
"'Classifiers:'",
"in",
"lines",
")"
] | test end to end test for verbose show command . | train | false |
46,485 | def _get_gcp_environ_var(var_name, default_value):
return os.environ.get(var_name, default_value)
| [
"def",
"_get_gcp_environ_var",
"(",
"var_name",
",",
"default_value",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"var_name",
",",
"default_value",
")"
] | wrapper around os . | train | false |
46,486 | def assess_same_labelling(cut1, cut2):
co_clust = []
for cut in [cut1, cut2]:
n = len(cut)
k = (cut.max() + 1)
ecut = np.zeros((n, k))
ecut[(np.arange(n), cut)] = 1
co_clust.append(np.dot(ecut, ecut.T))
assert_true((co_clust[0] == co_clust[1]).all())
| [
"def",
"assess_same_labelling",
"(",
"cut1",
",",
"cut2",
")",
":",
"co_clust",
"=",
"[",
"]",
"for",
"cut",
"in",
"[",
"cut1",
",",
"cut2",
"]",
":",
"n",
"=",
"len",
"(",
"cut",
")",
"k",
"=",
"(",
"cut",
".",
"max",
"(",
")",
"+",
"1",
")",
"ecut",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"k",
")",
")",
"ecut",
"[",
"(",
"np",
".",
"arange",
"(",
"n",
")",
",",
"cut",
")",
"]",
"=",
"1",
"co_clust",
".",
"append",
"(",
"np",
".",
"dot",
"(",
"ecut",
",",
"ecut",
".",
"T",
")",
")",
"assert_true",
"(",
"(",
"co_clust",
"[",
"0",
"]",
"==",
"co_clust",
"[",
"1",
"]",
")",
".",
"all",
"(",
")",
")"
] | util for comparison with scipy . | train | false |
46,487 | def render_comment_list(parser, token):
return RenderCommentListNode.handle_token(parser, token)
| [
"def",
"render_comment_list",
"(",
"parser",
",",
"token",
")",
":",
"return",
"RenderCommentListNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
")"
] | render the comment list through the comments/list . | train | false |
46,488 | def simple_cache(func):
saved_results = {}
def wrapper(cls, module):
if (module in saved_results):
return saved_results[module]
saved_results[module] = func(cls, module)
return saved_results[module]
return wrapper
| [
"def",
"simple_cache",
"(",
"func",
")",
":",
"saved_results",
"=",
"{",
"}",
"def",
"wrapper",
"(",
"cls",
",",
"module",
")",
":",
"if",
"(",
"module",
"in",
"saved_results",
")",
":",
"return",
"saved_results",
"[",
"module",
"]",
"saved_results",
"[",
"module",
"]",
"=",
"func",
"(",
"cls",
",",
"module",
")",
"return",
"saved_results",
"[",
"module",
"]",
"return",
"wrapper"
] | save results for the :meth:path . | train | true |
46,489 | def espell(**keywds):
cgi = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/espell.fcgi'
variables = {}
variables.update(keywds)
return _open(cgi, variables)
| [
"def",
"espell",
"(",
"**",
"keywds",
")",
":",
"cgi",
"=",
"'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/espell.fcgi'",
"variables",
"=",
"{",
"}",
"variables",
".",
"update",
"(",
"keywds",
")",
"return",
"_open",
"(",
"cgi",
",",
"variables",
")"
] | espell retrieves spelling suggestions . | train | false |
46,490 | def _lucas_selfridge_params(n):
from sympy.core import igcd
from sympy.ntheory.residue_ntheory import jacobi_symbol
D = 5
while True:
g = igcd(abs(D), n)
if ((g > 1) and (g != n)):
return (0, 0, 0)
if (jacobi_symbol(D, n) == (-1)):
break
if (D > 0):
D = ((- D) - 2)
else:
D = ((- D) + 2)
return _int_tuple(D, 1, ((1 - D) / 4))
| [
"def",
"_lucas_selfridge_params",
"(",
"n",
")",
":",
"from",
"sympy",
".",
"core",
"import",
"igcd",
"from",
"sympy",
".",
"ntheory",
".",
"residue_ntheory",
"import",
"jacobi_symbol",
"D",
"=",
"5",
"while",
"True",
":",
"g",
"=",
"igcd",
"(",
"abs",
"(",
"D",
")",
",",
"n",
")",
"if",
"(",
"(",
"g",
">",
"1",
")",
"and",
"(",
"g",
"!=",
"n",
")",
")",
":",
"return",
"(",
"0",
",",
"0",
",",
"0",
")",
"if",
"(",
"jacobi_symbol",
"(",
"D",
",",
"n",
")",
"==",
"(",
"-",
"1",
")",
")",
":",
"break",
"if",
"(",
"D",
">",
"0",
")",
":",
"D",
"=",
"(",
"(",
"-",
"D",
")",
"-",
"2",
")",
"else",
":",
"D",
"=",
"(",
"(",
"-",
"D",
")",
"+",
"2",
")",
"return",
"_int_tuple",
"(",
"D",
",",
"1",
",",
"(",
"(",
"1",
"-",
"D",
")",
"/",
"4",
")",
")"
] | calculates the selfridge parameters for n . | train | false |
46,491 | def prep_totals(head_res, baseline_res):
(head_res, baseline_res) = head_res.align(baseline_res)
ratio = (head_res['timing'] / baseline_res['timing'])
totals = DataFrame({HEAD_COL: head_res['timing'], BASE_COL: baseline_res['timing'], 'ratio': ratio, 'name': baseline_res.name}, columns=[HEAD_COL, BASE_COL, 'ratio', 'name'])
totals = totals.ix[(totals[HEAD_COL] > args.min_duration)]
totals = totals.dropna().sort('ratio').set_index('name')
return totals
| [
"def",
"prep_totals",
"(",
"head_res",
",",
"baseline_res",
")",
":",
"(",
"head_res",
",",
"baseline_res",
")",
"=",
"head_res",
".",
"align",
"(",
"baseline_res",
")",
"ratio",
"=",
"(",
"head_res",
"[",
"'timing'",
"]",
"/",
"baseline_res",
"[",
"'timing'",
"]",
")",
"totals",
"=",
"DataFrame",
"(",
"{",
"HEAD_COL",
":",
"head_res",
"[",
"'timing'",
"]",
",",
"BASE_COL",
":",
"baseline_res",
"[",
"'timing'",
"]",
",",
"'ratio'",
":",
"ratio",
",",
"'name'",
":",
"baseline_res",
".",
"name",
"}",
",",
"columns",
"=",
"[",
"HEAD_COL",
",",
"BASE_COL",
",",
"'ratio'",
",",
"'name'",
"]",
")",
"totals",
"=",
"totals",
".",
"ix",
"[",
"(",
"totals",
"[",
"HEAD_COL",
"]",
">",
"args",
".",
"min_duration",
")",
"]",
"totals",
"=",
"totals",
".",
"dropna",
"(",
")",
".",
"sort",
"(",
"'ratio'",
")",
".",
"set_index",
"(",
"'name'",
")",
"return",
"totals"
] | each argument should be a dataframe with timing and name columns where name is the name of the vbench . | train | false |
46,492 | @contextlib.contextmanager
def temp_git_commit_file():
basedir = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir, os.pardir)
path = os.path.join(basedir, 'qutebrowser', 'git-commit-id')
with open(path, 'wb') as f:
f.write('fake-frozen-git-commit')
(yield)
os.remove(path)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"temp_git_commit_file",
"(",
")",
":",
"basedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
",",
"os",
".",
"path",
".",
"pardir",
",",
"os",
".",
"pardir",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"'qutebrowser'",
",",
"'git-commit-id'",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'fake-frozen-git-commit'",
")",
"(",
"yield",
")",
"os",
".",
"remove",
"(",
"path",
")"
] | context manager to temporarily create a fake git-commit-id file . | train | false |
46,493 | def init_db(app):
try:
app.log.info('Initializing EasyEngine Database')
Base.metadata.create_all(bind=engine)
except Exception as e:
app.log.debug('{0}'.format(e))
| [
"def",
"init_db",
"(",
"app",
")",
":",
"try",
":",
"app",
".",
"log",
".",
"info",
"(",
"'Initializing EasyEngine Database'",
")",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"bind",
"=",
"engine",
")",
"except",
"Exception",
"as",
"e",
":",
"app",
".",
"log",
".",
"debug",
"(",
"'{0}'",
".",
"format",
"(",
"e",
")",
")"
] | initializes and creates all tables from models into the database . | train | false |
46,495 | def hashfile(fn, lcache=None, logger=None):
db = {}
try:
dbfile = os.path.join(lcache, 'link_cache.json')
if os.path.exists(dbfile):
db = simplejson.load(open(dbfile, 'r'))
except:
pass
mtime = os.stat(fn).st_mtime
if (fn in db):
if (db[fn][0] >= mtime):
return db[fn][1]
if os.path.exists(fn):
cmd = ('/usr/bin/sha1sum %s' % fn)
key = subprocess_get(logger, cmd).split(' ')[0]
if (lcache is not None):
db[fn] = (mtime, key)
simplejson.dump(db, open(dbfile, 'w'))
return key
else:
return None
| [
"def",
"hashfile",
"(",
"fn",
",",
"lcache",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"db",
"=",
"{",
"}",
"try",
":",
"dbfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"lcache",
",",
"'link_cache.json'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dbfile",
")",
":",
"db",
"=",
"simplejson",
".",
"load",
"(",
"open",
"(",
"dbfile",
",",
"'r'",
")",
")",
"except",
":",
"pass",
"mtime",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
".",
"st_mtime",
"if",
"(",
"fn",
"in",
"db",
")",
":",
"if",
"(",
"db",
"[",
"fn",
"]",
"[",
"0",
"]",
">=",
"mtime",
")",
":",
"return",
"db",
"[",
"fn",
"]",
"[",
"1",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"cmd",
"=",
"(",
"'/usr/bin/sha1sum %s'",
"%",
"fn",
")",
"key",
"=",
"subprocess_get",
"(",
"logger",
",",
"cmd",
")",
".",
"split",
"(",
"' '",
")",
"[",
"0",
"]",
"if",
"(",
"lcache",
"is",
"not",
"None",
")",
":",
"db",
"[",
"fn",
"]",
"=",
"(",
"mtime",
",",
"key",
")",
"simplejson",
".",
"dump",
"(",
"db",
",",
"open",
"(",
"dbfile",
",",
"'w'",
")",
")",
"return",
"key",
"else",
":",
"return",
"None"
] | returns the sha1sum of the file . | train | false |
46,497 | def B36Check(b36val):
int(b36val, 36)
return str(b36val).lower()
| [
"def",
"B36Check",
"(",
"b36val",
")",
":",
"int",
"(",
"b36val",
",",
"36",
")",
"return",
"str",
"(",
"b36val",
")",
".",
"lower",
"(",
")"
] | verify that a string is a valid path base-36 integer . | train | false |
46,500 | def minimize_batch(target_fn, gradient_fn, theta_0, tolerance=1e-06):
step_sizes = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 1e-05]
theta = theta_0
target_fn = safe(target_fn)
value = target_fn(theta)
while True:
gradient = gradient_fn(theta)
next_thetas = [step(theta, gradient, (- step_size)) for step_size in step_sizes]
next_theta = min(next_thetas, key=target_fn)
next_value = target_fn(next_theta)
if (abs((value - next_value)) < tolerance):
return theta
else:
(theta, value) = (next_theta, next_value)
| [
"def",
"minimize_batch",
"(",
"target_fn",
",",
"gradient_fn",
",",
"theta_0",
",",
"tolerance",
"=",
"1e-06",
")",
":",
"step_sizes",
"=",
"[",
"100",
",",
"10",
",",
"1",
",",
"0.1",
",",
"0.01",
",",
"0.001",
",",
"0.0001",
",",
"1e-05",
"]",
"theta",
"=",
"theta_0",
"target_fn",
"=",
"safe",
"(",
"target_fn",
")",
"value",
"=",
"target_fn",
"(",
"theta",
")",
"while",
"True",
":",
"gradient",
"=",
"gradient_fn",
"(",
"theta",
")",
"next_thetas",
"=",
"[",
"step",
"(",
"theta",
",",
"gradient",
",",
"(",
"-",
"step_size",
")",
")",
"for",
"step_size",
"in",
"step_sizes",
"]",
"next_theta",
"=",
"min",
"(",
"next_thetas",
",",
"key",
"=",
"target_fn",
")",
"next_value",
"=",
"target_fn",
"(",
"next_theta",
")",
"if",
"(",
"abs",
"(",
"(",
"value",
"-",
"next_value",
")",
")",
"<",
"tolerance",
")",
":",
"return",
"theta",
"else",
":",
"(",
"theta",
",",
"value",
")",
"=",
"(",
"next_theta",
",",
"next_value",
")"
] | use gradient descent to find theta that minimizes target function . | train | false |
46,501 | def stn(s, length, encoding, errors):
s = s.encode(encoding, errors)
return (s[:length] + ((length - len(s)) * NUL))
| [
"def",
"stn",
"(",
"s",
",",
"length",
",",
"encoding",
",",
"errors",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"return",
"(",
"s",
"[",
":",
"length",
"]",
"+",
"(",
"(",
"length",
"-",
"len",
"(",
"s",
")",
")",
"*",
"NUL",
")",
")"
] | convert a string to a null-terminated bytes object . | train | true |
46,503 | def check_host(fn):
def wrapped(self, req, id, service=None, *args, **kwargs):
listed_hosts = _list_hosts(req, service)
hosts = [h['host_name'] for h in listed_hosts]
if (id in hosts):
return fn(self, req, id, *args, **kwargs)
else:
message = (_("Host '%s' could not be found.") % id)
raise webob.exc.HTTPNotFound(explanation=message)
return wrapped
| [
"def",
"check_host",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"req",
",",
"id",
",",
"service",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"listed_hosts",
"=",
"_list_hosts",
"(",
"req",
",",
"service",
")",
"hosts",
"=",
"[",
"h",
"[",
"'host_name'",
"]",
"for",
"h",
"in",
"listed_hosts",
"]",
"if",
"(",
"id",
"in",
"hosts",
")",
":",
"return",
"fn",
"(",
"self",
",",
"req",
",",
"id",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"else",
":",
"message",
"=",
"(",
"_",
"(",
"\"Host '%s' could not be found.\"",
")",
"%",
"id",
")",
"raise",
"webob",
".",
"exc",
".",
"HTTPNotFound",
"(",
"explanation",
"=",
"message",
")",
"return",
"wrapped"
] | makes sure that the host exists . | train | false |
46,504 | def set_relay_ip_list(addresses=None, server=_DEFAULT_SERVER):
setting = 'RelayIpList'
formatted_addresses = list()
current_addresses = get_relay_ip_list(server)
if (list(addresses) == current_addresses):
_LOG.debug('%s already contains the provided addresses.', setting)
return True
if addresses:
if (addresses[0] is None):
formatted_addresses = None
else:
for address in addresses:
for octet in address.split('.'):
formatted_addresses.append(octet)
_LOG.debug('Formatted %s addresses: %s', setting, formatted_addresses)
_set_wmi_setting('IIsSmtpServerSetting', setting, formatted_addresses, server)
new_addresses = get_relay_ip_list(server)
ret = (list(addresses) == new_addresses)
if ret:
_LOG.debug('%s configured successfully: %s', setting, addresses)
return ret
_LOG.error('Unable to configure %s with value: %s', setting, addresses)
return ret
| [
"def",
"set_relay_ip_list",
"(",
"addresses",
"=",
"None",
",",
"server",
"=",
"_DEFAULT_SERVER",
")",
":",
"setting",
"=",
"'RelayIpList'",
"formatted_addresses",
"=",
"list",
"(",
")",
"current_addresses",
"=",
"get_relay_ip_list",
"(",
"server",
")",
"if",
"(",
"list",
"(",
"addresses",
")",
"==",
"current_addresses",
")",
":",
"_LOG",
".",
"debug",
"(",
"'%s already contains the provided addresses.'",
",",
"setting",
")",
"return",
"True",
"if",
"addresses",
":",
"if",
"(",
"addresses",
"[",
"0",
"]",
"is",
"None",
")",
":",
"formatted_addresses",
"=",
"None",
"else",
":",
"for",
"address",
"in",
"addresses",
":",
"for",
"octet",
"in",
"address",
".",
"split",
"(",
"'.'",
")",
":",
"formatted_addresses",
".",
"append",
"(",
"octet",
")",
"_LOG",
".",
"debug",
"(",
"'Formatted %s addresses: %s'",
",",
"setting",
",",
"formatted_addresses",
")",
"_set_wmi_setting",
"(",
"'IIsSmtpServerSetting'",
",",
"setting",
",",
"formatted_addresses",
",",
"server",
")",
"new_addresses",
"=",
"get_relay_ip_list",
"(",
"server",
")",
"ret",
"=",
"(",
"list",
"(",
"addresses",
")",
"==",
"new_addresses",
")",
"if",
"ret",
":",
"_LOG",
".",
"debug",
"(",
"'%s configured successfully: %s'",
",",
"setting",
",",
"addresses",
")",
"return",
"ret",
"_LOG",
".",
"error",
"(",
"'Unable to configure %s with value: %s'",
",",
"setting",
",",
"addresses",
")",
"return",
"ret"
] | set the relayiplist list for the smtp virtual server . | train | true |
46,505 | def run_check(name, path=None):
confd_path = (path or os.path.join(get_confd_path(get_os()), ('%s.yaml' % name)))
try:
f = open(confd_path)
except IOError:
raise Exception(('Unable to open configuration at %s' % confd_path))
config_str = f.read()
f.close()
(check, instances) = get_check(name, config_str)
if (not instances):
raise Exception('YAML configuration returned no instances.')
for instance in instances:
check.check(instance)
if check.has_events():
print 'Events:\n'
pprint(check.get_events(), indent=4)
print 'Metrics:\n'
pprint(check.get_metrics(), indent=4)
| [
"def",
"run_check",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"confd_path",
"=",
"(",
"path",
"or",
"os",
".",
"path",
".",
"join",
"(",
"get_confd_path",
"(",
"get_os",
"(",
")",
")",
",",
"(",
"'%s.yaml'",
"%",
"name",
")",
")",
")",
"try",
":",
"f",
"=",
"open",
"(",
"confd_path",
")",
"except",
"IOError",
":",
"raise",
"Exception",
"(",
"(",
"'Unable to open configuration at %s'",
"%",
"confd_path",
")",
")",
"config_str",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"(",
"check",
",",
"instances",
")",
"=",
"get_check",
"(",
"name",
",",
"config_str",
")",
"if",
"(",
"not",
"instances",
")",
":",
"raise",
"Exception",
"(",
"'YAML configuration returned no instances.'",
")",
"for",
"instance",
"in",
"instances",
":",
"check",
".",
"check",
"(",
"instance",
")",
"if",
"check",
".",
"has_events",
"(",
")",
":",
"print",
"'Events:\\n'",
"pprint",
"(",
"check",
".",
"get_events",
"(",
")",
",",
"indent",
"=",
"4",
")",
"print",
"'Metrics:\\n'",
"pprint",
"(",
"check",
".",
"get_metrics",
"(",
")",
",",
"indent",
"=",
"4",
")"
] | test custom checks on windows . | train | false |
46,506 | @testing.requires_testing_data
@requires_mayavi
def test_plot_dipole_locations():
dipoles = read_dipole(dip_fname)
trans = read_trans(trans_fname)
dipoles.plot_locations(trans, 'sample', subjects_dir, fig_name='foo')
assert_raises(ValueError, dipoles.plot_locations, trans, 'sample', subjects_dir, mode='foo')
| [
"@",
"testing",
".",
"requires_testing_data",
"@",
"requires_mayavi",
"def",
"test_plot_dipole_locations",
"(",
")",
":",
"dipoles",
"=",
"read_dipole",
"(",
"dip_fname",
")",
"trans",
"=",
"read_trans",
"(",
"trans_fname",
")",
"dipoles",
".",
"plot_locations",
"(",
"trans",
",",
"'sample'",
",",
"subjects_dir",
",",
"fig_name",
"=",
"'foo'",
")",
"assert_raises",
"(",
"ValueError",
",",
"dipoles",
".",
"plot_locations",
",",
"trans",
",",
"'sample'",
",",
"subjects_dir",
",",
"mode",
"=",
"'foo'",
")"
] | test plotting dipole locations . | train | false |
46,508 | @contextlib.contextmanager
def working_directory(directory=None, filename=None):
assert (bool(directory) != bool(filename))
if (not directory):
directory = os.path.dirname(filename)
prev_cwd = os.getcwd()
os.chdir(directory)
try:
(yield)
finally:
os.chdir(prev_cwd)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"working_directory",
"(",
"directory",
"=",
"None",
",",
"filename",
"=",
"None",
")",
":",
"assert",
"(",
"bool",
"(",
"directory",
")",
"!=",
"bool",
"(",
"filename",
")",
")",
"if",
"(",
"not",
"directory",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"prev_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"os",
".",
"chdir",
"(",
"directory",
")",
"try",
":",
"(",
"yield",
")",
"finally",
":",
"os",
".",
"chdir",
"(",
"prev_cwd",
")"
] | a context manager which changes the working directory to the given path . | train | false |
46,509 | def detect_conf_var():
f = file(CONF.CCACHE_PATH.get(), 'rb')
try:
data = f.read()
return ('X-CACHECONF:' in data)
finally:
f.close()
| [
"def",
"detect_conf_var",
"(",
")",
":",
"f",
"=",
"file",
"(",
"CONF",
".",
"CCACHE_PATH",
".",
"get",
"(",
")",
",",
"'rb'",
")",
"try",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"return",
"(",
"'X-CACHECONF:'",
"in",
"data",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | return true if the ticket cache contains "conf" information as is found in ticket caches of kerboers 1 . | train | false |
46,510 | def uninstall_package(package, version=None, local=False, npm='npm'):
if version:
package += ('@%s' % version)
if local:
run(('%(npm)s uninstall -l %(package)s' % locals()))
else:
run_as_root(('HOME=/root %(npm)s uninstall -g %(package)s' % locals()))
| [
"def",
"uninstall_package",
"(",
"package",
",",
"version",
"=",
"None",
",",
"local",
"=",
"False",
",",
"npm",
"=",
"'npm'",
")",
":",
"if",
"version",
":",
"package",
"+=",
"(",
"'@%s'",
"%",
"version",
")",
"if",
"local",
":",
"run",
"(",
"(",
"'%(npm)s uninstall -l %(package)s'",
"%",
"locals",
"(",
")",
")",
")",
"else",
":",
"run_as_root",
"(",
"(",
"'HOME=/root %(npm)s uninstall -g %(package)s'",
"%",
"locals",
"(",
")",
")",
")"
] | uninstall a node . | train | false |
46,511 | def nearest_colour_index(colour_map, rgb, debug=0):
best_metric = ((3 * 256) * 256)
best_colourx = 0
for (colourx, cand_rgb) in colour_map.items():
if (cand_rgb is None):
continue
metric = 0
for (v1, v2) in zip(rgb, cand_rgb):
metric += ((v1 - v2) * (v1 - v2))
if (metric < best_metric):
best_metric = metric
best_colourx = colourx
if (metric == 0):
break
if (0 and debug):
print(('nearest_colour_index for %r is %r -> %r; best_metric is %d' % (rgb, best_colourx, colour_map[best_colourx], best_metric)))
return best_colourx
| [
"def",
"nearest_colour_index",
"(",
"colour_map",
",",
"rgb",
",",
"debug",
"=",
"0",
")",
":",
"best_metric",
"=",
"(",
"(",
"3",
"*",
"256",
")",
"*",
"256",
")",
"best_colourx",
"=",
"0",
"for",
"(",
"colourx",
",",
"cand_rgb",
")",
"in",
"colour_map",
".",
"items",
"(",
")",
":",
"if",
"(",
"cand_rgb",
"is",
"None",
")",
":",
"continue",
"metric",
"=",
"0",
"for",
"(",
"v1",
",",
"v2",
")",
"in",
"zip",
"(",
"rgb",
",",
"cand_rgb",
")",
":",
"metric",
"+=",
"(",
"(",
"v1",
"-",
"v2",
")",
"*",
"(",
"v1",
"-",
"v2",
")",
")",
"if",
"(",
"metric",
"<",
"best_metric",
")",
":",
"best_metric",
"=",
"metric",
"best_colourx",
"=",
"colourx",
"if",
"(",
"metric",
"==",
"0",
")",
":",
"break",
"if",
"(",
"0",
"and",
"debug",
")",
":",
"print",
"(",
"(",
"'nearest_colour_index for %r is %r -> %r; best_metric is %d'",
"%",
"(",
"rgb",
",",
"best_colourx",
",",
"colour_map",
"[",
"best_colourx",
"]",
",",
"best_metric",
")",
")",
")",
"return",
"best_colourx"
] | general purpose function . | train | false |
46,512 | def write_open_mode(filename):
if is_binary(filename):
return 'wb'
return 'w'
| [
"def",
"write_open_mode",
"(",
"filename",
")",
":",
"if",
"is_binary",
"(",
"filename",
")",
":",
"return",
"'wb'",
"return",
"'w'"
] | return the write mode that should used to open file . | train | false |
46,515 | def get_disk_type_from_path(path):
if path.startswith('/dev'):
return 'lvm'
elif path.startswith('rbd:'):
return 'rbd'
elif (os.path.isdir(path) and os.path.exists(os.path.join(path, 'DiskDescriptor.xml'))):
return 'ploop'
return None
| [
"def",
"get_disk_type_from_path",
"(",
"path",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"'/dev'",
")",
":",
"return",
"'lvm'",
"elif",
"path",
".",
"startswith",
"(",
"'rbd:'",
")",
":",
"return",
"'rbd'",
"elif",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'DiskDescriptor.xml'",
")",
")",
")",
":",
"return",
"'ploop'",
"return",
"None"
] | retrieve disk type for given file . | train | false |
46,516 | @manager.command
def sync_jira():
from security_monkey import jirasync
if jirasync:
app.logger.info('Syncing issues with Jira')
jirasync.sync_issues()
else:
app.logger.info('Jira sync not configured. Is SECURITY_MONKEY_JIRA_SYNC set?')
| [
"@",
"manager",
".",
"command",
"def",
"sync_jira",
"(",
")",
":",
"from",
"security_monkey",
"import",
"jirasync",
"if",
"jirasync",
":",
"app",
".",
"logger",
".",
"info",
"(",
"'Syncing issues with Jira'",
")",
"jirasync",
".",
"sync_issues",
"(",
")",
"else",
":",
"app",
".",
"logger",
".",
"info",
"(",
"'Jira sync not configured. Is SECURITY_MONKEY_JIRA_SYNC set?'",
")"
] | syncs issues with jira . | train | false |
46,517 | @pytest.mark.usefixtures('freezer')
def test_resource_filename():
filename = utils.resource_filename(os.path.join('utils', 'testfile'))
with open(filename, 'r', encoding='utf-8') as f:
assert (f.read().splitlines()[0] == 'Hello World!')
| [
"@",
"pytest",
".",
"mark",
".",
"usefixtures",
"(",
"'freezer'",
")",
"def",
"test_resource_filename",
"(",
")",
":",
"filename",
"=",
"utils",
".",
"resource_filename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'utils'",
",",
"'testfile'",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"assert",
"(",
"f",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"==",
"'Hello World!'",
")"
] | read a test file . | train | false |
46,519 | def hmac_sha256_digest(key, msg):
return hmac.new(key, msg, hashlib.sha256).digest()
| [
"def",
"hmac_sha256_digest",
"(",
"key",
",",
"msg",
")",
":",
"return",
"hmac",
".",
"new",
"(",
"key",
",",
"msg",
",",
"hashlib",
".",
"sha256",
")",
".",
"digest",
"(",
")"
] | return the hmac-sha256 message authentication code of the message msg with key key . | train | false |
46,520 | def disable_for_loaddata(signal_handler):
@wraps(signal_handler)
def wrapper(*args, **kwargs):
for fr in inspect.stack():
if (inspect.getmodulename(fr[1]) == 'loaddata'):
return
signal_handler(*args, **kwargs)
return wrapper
| [
"def",
"disable_for_loaddata",
"(",
"signal_handler",
")",
":",
"@",
"wraps",
"(",
"signal_handler",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"fr",
"in",
"inspect",
".",
"stack",
"(",
")",
":",
"if",
"(",
"inspect",
".",
"getmodulename",
"(",
"fr",
"[",
"1",
"]",
")",
"==",
"'loaddata'",
")",
":",
"return",
"signal_handler",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"wrapper"
] | decorator for disabling signals sent by post_save on loaddata command . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.