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 |
|---|---|---|---|---|---|
14,772 | def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs):
ret = line_search_wolfe1(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs)
if (ret[0] is None):
ret = line_search_wolfe2(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs)
if (ret[0] is None):
raise _LineSearchError()
return ret
| [
"def",
"_line_search_wolfe12",
"(",
"f",
",",
"fprime",
",",
"xk",
",",
"pk",
",",
"gfk",
",",
"old_fval",
",",
"old_old_fval",
",",
"**",
"kwargs",
")",
":",
"ret",
"=",
"line_search_wolfe1",
"(",
"f",
",",
"fprime",
",",
"xk",
",",
"pk",
",",
"gfk",
",",
"old_fval",
",",
"old_old_fval",
",",
"**",
"kwargs",
")",
"if",
"(",
"ret",
"[",
"0",
"]",
"is",
"None",
")",
":",
"ret",
"=",
"line_search_wolfe2",
"(",
"f",
",",
"fprime",
",",
"xk",
",",
"pk",
",",
"gfk",
",",
"old_fval",
",",
"old_old_fval",
",",
"**",
"kwargs",
")",
"if",
"(",
"ret",
"[",
"0",
"]",
"is",
"None",
")",
":",
"raise",
"_LineSearchError",
"(",
")",
"return",
"ret"
] | same as line_search_wolfe1 . | train | false |
14,773 | def fly():
args = parse_arguments()
try:
proxy_connect(args)
init(args)
except TwitterHTTPError as e:
printNicely('')
printNicely(magenta('We have connection problem with twitter REST API right now :('))
detail_twitter_error(e)
save_history()
sys.exit()
except (socks.ProxyConnectionError, URLError):
printNicely(magenta('There seems to be a connection problem.'))
printNicely(magenta('You might want to check your proxy settings (host, port and type)!'))
save_history()
sys.exit()
target = args.stream.split()[0]
if (target == 'mine'):
spawn_personal_stream(args)
else:
try:
stuff = args.stream.split()[1]
except:
stuff = None
spawn_dict = {'public': spawn_public_stream, 'list': spawn_list_stream}
spawn_dict.get(target)(args, stuff)
time.sleep(0.5)
g['reset'] = True
g['prefix'] = True
listen()
| [
"def",
"fly",
"(",
")",
":",
"args",
"=",
"parse_arguments",
"(",
")",
"try",
":",
"proxy_connect",
"(",
"args",
")",
"init",
"(",
"args",
")",
"except",
"TwitterHTTPError",
"as",
"e",
":",
"printNicely",
"(",
"''",
")",
"printNicely",
"(",
"magenta",
"(",
"'We have connection problem with twitter REST API right now :('",
")",
")",
"detail_twitter_error",
"(",
"e",
")",
"save_history",
"(",
")",
"sys",
".",
"exit",
"(",
")",
"except",
"(",
"socks",
".",
"ProxyConnectionError",
",",
"URLError",
")",
":",
"printNicely",
"(",
"magenta",
"(",
"'There seems to be a connection problem.'",
")",
")",
"printNicely",
"(",
"magenta",
"(",
"'You might want to check your proxy settings (host, port and type)!'",
")",
")",
"save_history",
"(",
")",
"sys",
".",
"exit",
"(",
")",
"target",
"=",
"args",
".",
"stream",
".",
"split",
"(",
")",
"[",
"0",
"]",
"if",
"(",
"target",
"==",
"'mine'",
")",
":",
"spawn_personal_stream",
"(",
"args",
")",
"else",
":",
"try",
":",
"stuff",
"=",
"args",
".",
"stream",
".",
"split",
"(",
")",
"[",
"1",
"]",
"except",
":",
"stuff",
"=",
"None",
"spawn_dict",
"=",
"{",
"'public'",
":",
"spawn_public_stream",
",",
"'list'",
":",
"spawn_list_stream",
"}",
"spawn_dict",
".",
"get",
"(",
"target",
")",
"(",
"args",
",",
"stuff",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"g",
"[",
"'reset'",
"]",
"=",
"True",
"g",
"[",
"'prefix'",
"]",
"=",
"True",
"listen",
"(",
")"
] | main function . | train | false |
14,775 | def write_example_config(filename, config):
with open(os.path.realpath(filename), 'w') as f:
f.write(yaml.dump(config, default_flow_style=False))
| [
"def",
"write_example_config",
"(",
"filename",
",",
"config",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"filename",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"yaml",
".",
"dump",
"(",
"config",
",",
"default_flow_style",
"=",
"False",
")",
")"
] | dump generated configuration to a file . | train | false |
14,776 | def remove_var(var):
makeconf = _get_makeconf()
old_value = get_var(var)
if (old_value is not None):
__salt__['file.sed'](makeconf, '^{0}=.*'.format(var), '')
new_value = get_var(var)
return {var: {'old': old_value, 'new': new_value}}
| [
"def",
"remove_var",
"(",
"var",
")",
":",
"makeconf",
"=",
"_get_makeconf",
"(",
")",
"old_value",
"=",
"get_var",
"(",
"var",
")",
"if",
"(",
"old_value",
"is",
"not",
"None",
")",
":",
"__salt__",
"[",
"'file.sed'",
"]",
"(",
"makeconf",
",",
"'^{0}=.*'",
".",
"format",
"(",
"var",
")",
",",
"''",
")",
"new_value",
"=",
"get_var",
"(",
"var",
")",
"return",
"{",
"var",
":",
"{",
"'old'",
":",
"old_value",
",",
"'new'",
":",
"new_value",
"}",
"}"
] | remove a variable from the make . | train | true |
14,778 | def global_max_pool(incoming, name='GlobalMaxPool'):
input_shape = utils.get_incoming_shape(incoming)
assert (len(input_shape) == 4), 'Incoming Tensor shape must be 4-D'
with tf.name_scope(name):
inference = tf.reduce_max(incoming, [1, 2])
tf.add_to_collection(((tf.GraphKeys.LAYER_TENSOR + '/') + name), inference)
return inference
| [
"def",
"global_max_pool",
"(",
"incoming",
",",
"name",
"=",
"'GlobalMaxPool'",
")",
":",
"input_shape",
"=",
"utils",
".",
"get_incoming_shape",
"(",
"incoming",
")",
"assert",
"(",
"len",
"(",
"input_shape",
")",
"==",
"4",
")",
",",
"'Incoming Tensor shape must be 4-D'",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
":",
"inference",
"=",
"tf",
".",
"reduce_max",
"(",
"incoming",
",",
"[",
"1",
",",
"2",
"]",
")",
"tf",
".",
"add_to_collection",
"(",
"(",
"(",
"tf",
".",
"GraphKeys",
".",
"LAYER_TENSOR",
"+",
"'/'",
")",
"+",
"name",
")",
",",
"inference",
")",
"return",
"inference"
] | global max pooling . | train | false |
14,780 | def _EndRecData64(fpin, offset, endrec):
fpin.seek((offset - sizeEndCentDir64Locator), 2)
data = fpin.read(sizeEndCentDir64Locator)
(sig, diskno, reloff, disks) = struct.unpack(structEndArchive64Locator, data)
if (sig != stringEndArchive64Locator):
return endrec
if ((diskno != 0) or (disks != 1)):
raise BadZipfile('zipfiles that span multiple disks are not supported')
fpin.seek(((offset - sizeEndCentDir64Locator) - sizeEndCentDir64), 2)
data = fpin.read(sizeEndCentDir64)
(sig, sz, create_version, read_version, disk_num, disk_dir, dircount, dircount2, dirsize, diroffset) = struct.unpack(structEndArchive64, data)
if (sig != stringEndArchive64):
return endrec
endrec[_ECD_SIGNATURE] = sig
endrec[_ECD_DISK_NUMBER] = disk_num
endrec[_ECD_DISK_START] = disk_dir
endrec[_ECD_ENTRIES_THIS_DISK] = dircount
endrec[_ECD_ENTRIES_TOTAL] = dircount2
endrec[_ECD_SIZE] = dirsize
endrec[_ECD_OFFSET] = diroffset
return endrec
| [
"def",
"_EndRecData64",
"(",
"fpin",
",",
"offset",
",",
"endrec",
")",
":",
"fpin",
".",
"seek",
"(",
"(",
"offset",
"-",
"sizeEndCentDir64Locator",
")",
",",
"2",
")",
"data",
"=",
"fpin",
".",
"read",
"(",
"sizeEndCentDir64Locator",
")",
"(",
"sig",
",",
"diskno",
",",
"reloff",
",",
"disks",
")",
"=",
"struct",
".",
"unpack",
"(",
"structEndArchive64Locator",
",",
"data",
")",
"if",
"(",
"sig",
"!=",
"stringEndArchive64Locator",
")",
":",
"return",
"endrec",
"if",
"(",
"(",
"diskno",
"!=",
"0",
")",
"or",
"(",
"disks",
"!=",
"1",
")",
")",
":",
"raise",
"BadZipfile",
"(",
"'zipfiles that span multiple disks are not supported'",
")",
"fpin",
".",
"seek",
"(",
"(",
"(",
"offset",
"-",
"sizeEndCentDir64Locator",
")",
"-",
"sizeEndCentDir64",
")",
",",
"2",
")",
"data",
"=",
"fpin",
".",
"read",
"(",
"sizeEndCentDir64",
")",
"(",
"sig",
",",
"sz",
",",
"create_version",
",",
"read_version",
",",
"disk_num",
",",
"disk_dir",
",",
"dircount",
",",
"dircount2",
",",
"dirsize",
",",
"diroffset",
")",
"=",
"struct",
".",
"unpack",
"(",
"structEndArchive64",
",",
"data",
")",
"if",
"(",
"sig",
"!=",
"stringEndArchive64",
")",
":",
"return",
"endrec",
"endrec",
"[",
"_ECD_SIGNATURE",
"]",
"=",
"sig",
"endrec",
"[",
"_ECD_DISK_NUMBER",
"]",
"=",
"disk_num",
"endrec",
"[",
"_ECD_DISK_START",
"]",
"=",
"disk_dir",
"endrec",
"[",
"_ECD_ENTRIES_THIS_DISK",
"]",
"=",
"dircount",
"endrec",
"[",
"_ECD_ENTRIES_TOTAL",
"]",
"=",
"dircount2",
"endrec",
"[",
"_ECD_SIZE",
"]",
"=",
"dirsize",
"endrec",
"[",
"_ECD_OFFSET",
"]",
"=",
"diroffset",
"return",
"endrec"
] | read the zip64 end-of-archive records and use that to update endrec . | train | true |
14,781 | def getSocketFamily(socket):
if _PY3:
return socket.family
else:
return getsockfam(socket.fileno())
| [
"def",
"getSocketFamily",
"(",
"socket",
")",
":",
"if",
"_PY3",
":",
"return",
"socket",
".",
"family",
"else",
":",
"return",
"getsockfam",
"(",
"socket",
".",
"fileno",
"(",
")",
")"
] | return the family of the given socket . | train | false |
14,783 | def _strip_postfix(req):
match = re.search('^(.*?)(?:-dev|-\\d.*)$', req)
if match:
req = match.group(1)
return req
| [
"def",
"_strip_postfix",
"(",
"req",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"'^(.*?)(?:-dev|-\\\\d.*)$'",
",",
"req",
")",
"if",
"match",
":",
"req",
"=",
"match",
".",
"group",
"(",
"1",
")",
"return",
"req"
] | strip req postfix . | train | true |
14,784 | def get_all_topics(region=None, key=None, keyid=None, profile=None):
cache_key = _cache_get_key()
try:
return __context__[cache_key]
except KeyError:
pass
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
__context__[cache_key] = {}
topics = conn.get_all_topics()
for t in topics['ListTopicsResponse']['ListTopicsResult']['Topics']:
short_name = t['TopicArn'].split(':')[(-1)]
__context__[cache_key][short_name] = t['TopicArn']
return __context__[cache_key]
| [
"def",
"get_all_topics",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"cache_key",
"=",
"_cache_get_key",
"(",
")",
"try",
":",
"return",
"__context__",
"[",
"cache_key",
"]",
"except",
"KeyError",
":",
"pass",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"__context__",
"[",
"cache_key",
"]",
"=",
"{",
"}",
"topics",
"=",
"conn",
".",
"get_all_topics",
"(",
")",
"for",
"t",
"in",
"topics",
"[",
"'ListTopicsResponse'",
"]",
"[",
"'ListTopicsResult'",
"]",
"[",
"'Topics'",
"]",
":",
"short_name",
"=",
"t",
"[",
"'TopicArn'",
"]",
".",
"split",
"(",
"':'",
")",
"[",
"(",
"-",
"1",
")",
"]",
"__context__",
"[",
"cache_key",
"]",
"[",
"short_name",
"]",
"=",
"t",
"[",
"'TopicArn'",
"]",
"return",
"__context__",
"[",
"cache_key",
"]"
] | returns a list of the all topics . | train | true |
14,786 | def add_constructor(tag, constructor, Loader=Loader):
Loader.add_constructor(tag, constructor)
| [
"def",
"add_constructor",
"(",
"tag",
",",
"constructor",
",",
"Loader",
"=",
"Loader",
")",
":",
"Loader",
".",
"add_constructor",
"(",
"tag",
",",
"constructor",
")"
] | add a constructor for the given tag . | train | false |
14,787 | def dt_str_to_posix(dt_str):
(parsable, _) = dt_str.split('.')
dt = datetime.datetime.strptime(parsable, _DT_FORMAT)
return calendar.timegm(dt.utctimetuple())
| [
"def",
"dt_str_to_posix",
"(",
"dt_str",
")",
":",
"(",
"parsable",
",",
"_",
")",
"=",
"dt_str",
".",
"split",
"(",
"'.'",
")",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parsable",
",",
"_DT_FORMAT",
")",
"return",
"calendar",
".",
"timegm",
"(",
"dt",
".",
"utctimetuple",
"(",
")",
")"
] | format str to posix . | train | true |
14,788 | def dup_shift(f, a, K):
(f, n) = (list(f), (len(f) - 1))
for i in range(n, 0, (-1)):
for j in range(0, i):
f[(j + 1)] += (a * f[j])
return f
| [
"def",
"dup_shift",
"(",
"f",
",",
"a",
",",
"K",
")",
":",
"(",
"f",
",",
"n",
")",
"=",
"(",
"list",
"(",
"f",
")",
",",
"(",
"len",
"(",
"f",
")",
"-",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n",
",",
"0",
",",
"(",
"-",
"1",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"i",
")",
":",
"f",
"[",
"(",
"j",
"+",
"1",
")",
"]",
"+=",
"(",
"a",
"*",
"f",
"[",
"j",
"]",
")",
"return",
"f"
] | evaluate efficiently taylor shift f in k[x] . | train | false |
14,789 | def cost_per_click(spend, clicks):
if clicks:
return (float(spend) / clicks)
else:
return 0
| [
"def",
"cost_per_click",
"(",
"spend",
",",
"clicks",
")",
":",
"if",
"clicks",
":",
"return",
"(",
"float",
"(",
"spend",
")",
"/",
"clicks",
")",
"else",
":",
"return",
"0"
] | return the cost-per-click given ad spend and clicks . | train | false |
14,790 | def generate_nt_hash(password):
return binascii.hexlify(hashlib.new('md4', password.encode('utf-16le')).digest()).upper()
| [
"def",
"generate_nt_hash",
"(",
"password",
")",
":",
"return",
"binascii",
".",
"hexlify",
"(",
"hashlib",
".",
"new",
"(",
"'md4'",
",",
"password",
".",
"encode",
"(",
"'utf-16le'",
")",
")",
".",
"digest",
"(",
")",
")",
".",
"upper",
"(",
")"
] | generate a nt hash cli example: . | train | true |
14,792 | def get_comment_app_name():
return getattr(settings, 'COMMENTS_APP', DEFAULT_COMMENTS_APP)
| [
"def",
"get_comment_app_name",
"(",
")",
":",
"return",
"getattr",
"(",
"settings",
",",
"'COMMENTS_APP'",
",",
"DEFAULT_COMMENTS_APP",
")"
] | returns the name of the comment app . | train | false |
14,794 | def p_rulelist(p):
if (len(p) == 2):
p[0] = [p[1]]
else:
p[0] = p[1]
p[1].append(p[2])
| [
"def",
"p_rulelist",
"(",
"p",
")",
":",
"if",
"(",
"len",
"(",
"p",
")",
"==",
"2",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
"]",
"else",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"2",
"]",
")"
] | rulelist : rulelist ruleitem | ruleitem . | train | false |
14,796 | def getIsIntersectingWithinList(loop, loopList):
leftPoint = euclidean.getLeftPoint(loop)
for otherLoop in loopList:
if ((euclidean.getNumberOfIntersectionsToLeft(otherLoop, leftPoint) % 2) == 1):
return True
return euclidean.isLoopIntersectingLoops(loop, loopList)
| [
"def",
"getIsIntersectingWithinList",
"(",
"loop",
",",
"loopList",
")",
":",
"leftPoint",
"=",
"euclidean",
".",
"getLeftPoint",
"(",
"loop",
")",
"for",
"otherLoop",
"in",
"loopList",
":",
"if",
"(",
"(",
"euclidean",
".",
"getNumberOfIntersectionsToLeft",
"(",
"otherLoop",
",",
"leftPoint",
")",
"%",
"2",
")",
"==",
"1",
")",
":",
"return",
"True",
"return",
"euclidean",
".",
"isLoopIntersectingLoops",
"(",
"loop",
",",
"loopList",
")"
] | determine if the loop is intersecting or is within the loop list . | train | false |
14,798 | @outer_atomic
def reset_attempts_module_state(xmodule_instance_args, _module_descriptor, student_module, _task_input):
update_status = UPDATE_STATUS_SKIPPED
problem_state = (json.loads(student_module.state) if student_module.state else {})
if ('attempts' in problem_state):
old_number_of_attempts = problem_state['attempts']
if (old_number_of_attempts > 0):
problem_state['attempts'] = 0
student_module.state = json.dumps(problem_state)
student_module.save()
track_function = _get_track_function_for_task(student_module.student, xmodule_instance_args)
event_info = {'old_attempts': old_number_of_attempts, 'new_attempts': 0}
track_function('problem_reset_attempts', event_info)
update_status = UPDATE_STATUS_SUCCEEDED
return update_status
| [
"@",
"outer_atomic",
"def",
"reset_attempts_module_state",
"(",
"xmodule_instance_args",
",",
"_module_descriptor",
",",
"student_module",
",",
"_task_input",
")",
":",
"update_status",
"=",
"UPDATE_STATUS_SKIPPED",
"problem_state",
"=",
"(",
"json",
".",
"loads",
"(",
"student_module",
".",
"state",
")",
"if",
"student_module",
".",
"state",
"else",
"{",
"}",
")",
"if",
"(",
"'attempts'",
"in",
"problem_state",
")",
":",
"old_number_of_attempts",
"=",
"problem_state",
"[",
"'attempts'",
"]",
"if",
"(",
"old_number_of_attempts",
">",
"0",
")",
":",
"problem_state",
"[",
"'attempts'",
"]",
"=",
"0",
"student_module",
".",
"state",
"=",
"json",
".",
"dumps",
"(",
"problem_state",
")",
"student_module",
".",
"save",
"(",
")",
"track_function",
"=",
"_get_track_function_for_task",
"(",
"student_module",
".",
"student",
",",
"xmodule_instance_args",
")",
"event_info",
"=",
"{",
"'old_attempts'",
":",
"old_number_of_attempts",
",",
"'new_attempts'",
":",
"0",
"}",
"track_function",
"(",
"'problem_reset_attempts'",
",",
"event_info",
")",
"update_status",
"=",
"UPDATE_STATUS_SUCCEEDED",
"return",
"update_status"
] | resets problem attempts to zero for specified student_module . | train | false |
14,799 | def test_parameter_properties():
m = MockModel()
p = m.alpha
assert (p.name == u'alpha')
with pytest.raises(AttributeError):
p.name = u'beta'
assert (p.fixed is False)
p.fixed = True
assert (p.fixed is True)
assert (p.tied is False)
p.tied = (lambda _: 0)
p.tied = False
assert (p.tied is False)
assert (p.min is None)
p.min = 42
assert (p.min == 42)
p.min = None
assert (p.min is None)
assert (p.max is None)
p.max = 41
assert (p.max == 41)
| [
"def",
"test_parameter_properties",
"(",
")",
":",
"m",
"=",
"MockModel",
"(",
")",
"p",
"=",
"m",
".",
"alpha",
"assert",
"(",
"p",
".",
"name",
"==",
"u'alpha'",
")",
"with",
"pytest",
".",
"raises",
"(",
"AttributeError",
")",
":",
"p",
".",
"name",
"=",
"u'beta'",
"assert",
"(",
"p",
".",
"fixed",
"is",
"False",
")",
"p",
".",
"fixed",
"=",
"True",
"assert",
"(",
"p",
".",
"fixed",
"is",
"True",
")",
"assert",
"(",
"p",
".",
"tied",
"is",
"False",
")",
"p",
".",
"tied",
"=",
"(",
"lambda",
"_",
":",
"0",
")",
"p",
".",
"tied",
"=",
"False",
"assert",
"(",
"p",
".",
"tied",
"is",
"False",
")",
"assert",
"(",
"p",
".",
"min",
"is",
"None",
")",
"p",
".",
"min",
"=",
"42",
"assert",
"(",
"p",
".",
"min",
"==",
"42",
")",
"p",
".",
"min",
"=",
"None",
"assert",
"(",
"p",
".",
"min",
"is",
"None",
")",
"assert",
"(",
"p",
".",
"max",
"is",
"None",
")",
"p",
".",
"max",
"=",
"41",
"assert",
"(",
"p",
".",
"max",
"==",
"41",
")"
] | test if getting / setting of parameter properties works . | train | false |
14,800 | def string_to_class_name(string):
string = re.sub('[A-Za-z]', (lambda m: m.group().title()), string, count=1)
string = re.sub('_[A-Za-z0-9]+', (lambda m: m.group()[1:].title()), string)
return str(string)
| [
"def",
"string_to_class_name",
"(",
"string",
")",
":",
"string",
"=",
"re",
".",
"sub",
"(",
"'[A-Za-z]'",
",",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
")",
".",
"title",
"(",
")",
")",
",",
"string",
",",
"count",
"=",
"1",
")",
"string",
"=",
"re",
".",
"sub",
"(",
"'_[A-Za-z0-9]+'",
",",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
")",
"[",
"1",
":",
"]",
".",
"title",
"(",
")",
")",
",",
"string",
")",
"return",
"str",
"(",
"string",
")"
] | single function to handle turning object names into class names . | train | false |
14,802 | def get_svc_broken_path(name='*'):
if (not SERVICE_DIR):
raise CommandExecutionError('Could not find service directory.')
ret = set()
for el in glob.glob(os.path.join(SERVICE_DIR, name)):
if (not _is_svc(el)):
ret.add(el)
return sorted(ret)
| [
"def",
"get_svc_broken_path",
"(",
"name",
"=",
"'*'",
")",
":",
"if",
"(",
"not",
"SERVICE_DIR",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Could not find service directory.'",
")",
"ret",
"=",
"set",
"(",
")",
"for",
"el",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"SERVICE_DIR",
",",
"name",
")",
")",
":",
"if",
"(",
"not",
"_is_svc",
"(",
"el",
")",
")",
":",
"ret",
".",
"add",
"(",
"el",
")",
"return",
"sorted",
"(",
"ret",
")"
] | return list of broken path(s) in service_dir that match name a path is broken if it is a broken symlink or can not be a runit service name a glob for service name . | train | true |
14,803 | @task
def bdist_wininst_sse3(options):
bdist_wininst_arch(options.python_version, 'sse3')
| [
"@",
"task",
"def",
"bdist_wininst_sse3",
"(",
"options",
")",
":",
"bdist_wininst_arch",
"(",
"options",
".",
"python_version",
",",
"'sse3'",
")"
] | build the sse3 wininst installer . | train | false |
14,804 | def max_name_width(service_names, max_index_width=3):
return (max((len(name) for name in service_names)) + max_index_width)
| [
"def",
"max_name_width",
"(",
"service_names",
",",
"max_index_width",
"=",
"3",
")",
":",
"return",
"(",
"max",
"(",
"(",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"service_names",
")",
")",
"+",
"max_index_width",
")"
] | calculate the maximum width of container names so we can make the log prefixes line up like so: db_1 | listening web_1 | listening . | train | false |
14,805 | @register_canonicalize
@gof.local_optimizer([Reshape])
def local_useless_dimshuffle_in_reshape(node):
op = node.op
if (not isinstance(op, Reshape)):
return False
if (not ((node.inputs[0].owner is not None) and isinstance(node.inputs[0].owner.op, DimShuffle))):
return False
new_order = node.inputs[0].owner.op.new_order
input = node.inputs[0].owner.inputs[0]
broadcastables = node.inputs[0].broadcastable
new_order_of_nonbroadcast = []
for (i, bd) in zip(new_order, broadcastables):
if (not bd):
new_order_of_nonbroadcast.append(i)
no_change_in_order = all(((new_order_of_nonbroadcast[i] <= new_order_of_nonbroadcast[(i + 1)]) for i in xrange((len(new_order_of_nonbroadcast) - 1))))
if no_change_in_order:
shape = node.inputs[1]
ret = op.__class__(node.outputs[0].ndim)(input, shape)
copy_stack_trace(node.outputs[0], ret)
return [ret]
| [
"@",
"register_canonicalize",
"@",
"gof",
".",
"local_optimizer",
"(",
"[",
"Reshape",
"]",
")",
"def",
"local_useless_dimshuffle_in_reshape",
"(",
"node",
")",
":",
"op",
"=",
"node",
".",
"op",
"if",
"(",
"not",
"isinstance",
"(",
"op",
",",
"Reshape",
")",
")",
":",
"return",
"False",
"if",
"(",
"not",
"(",
"(",
"node",
".",
"inputs",
"[",
"0",
"]",
".",
"owner",
"is",
"not",
"None",
")",
"and",
"isinstance",
"(",
"node",
".",
"inputs",
"[",
"0",
"]",
".",
"owner",
".",
"op",
",",
"DimShuffle",
")",
")",
")",
":",
"return",
"False",
"new_order",
"=",
"node",
".",
"inputs",
"[",
"0",
"]",
".",
"owner",
".",
"op",
".",
"new_order",
"input",
"=",
"node",
".",
"inputs",
"[",
"0",
"]",
".",
"owner",
".",
"inputs",
"[",
"0",
"]",
"broadcastables",
"=",
"node",
".",
"inputs",
"[",
"0",
"]",
".",
"broadcastable",
"new_order_of_nonbroadcast",
"=",
"[",
"]",
"for",
"(",
"i",
",",
"bd",
")",
"in",
"zip",
"(",
"new_order",
",",
"broadcastables",
")",
":",
"if",
"(",
"not",
"bd",
")",
":",
"new_order_of_nonbroadcast",
".",
"append",
"(",
"i",
")",
"no_change_in_order",
"=",
"all",
"(",
"(",
"(",
"new_order_of_nonbroadcast",
"[",
"i",
"]",
"<=",
"new_order_of_nonbroadcast",
"[",
"(",
"i",
"+",
"1",
")",
"]",
")",
"for",
"i",
"in",
"xrange",
"(",
"(",
"len",
"(",
"new_order_of_nonbroadcast",
")",
"-",
"1",
")",
")",
")",
")",
"if",
"no_change_in_order",
":",
"shape",
"=",
"node",
".",
"inputs",
"[",
"1",
"]",
"ret",
"=",
"op",
".",
"__class__",
"(",
"node",
".",
"outputs",
"[",
"0",
"]",
".",
"ndim",
")",
"(",
"input",
",",
"shape",
")",
"copy_stack_trace",
"(",
"node",
".",
"outputs",
"[",
"0",
"]",
",",
"ret",
")",
"return",
"[",
"ret",
"]"
] | removes useless dimshuffle operation inside reshape: reshape(vector . | train | false |
14,807 | def is_special_url(url):
if (not url.isValid()):
return False
special_schemes = ('about', 'qute', 'file')
return (url.scheme() in special_schemes)
| [
"def",
"is_special_url",
"(",
"url",
")",
":",
"if",
"(",
"not",
"url",
".",
"isValid",
"(",
")",
")",
":",
"return",
"False",
"special_schemes",
"=",
"(",
"'about'",
",",
"'qute'",
",",
"'file'",
")",
"return",
"(",
"url",
".",
"scheme",
"(",
")",
"in",
"special_schemes",
")"
] | return true if url is an about: . | train | false |
14,808 | def get_all_fix_names(fixer_pkg, remove_prefix=True):
pkg = __import__(fixer_pkg, [], [], ['*'])
fixer_dir = os.path.dirname(pkg.__file__)
fix_names = []
for name in sorted(os.listdir(fixer_dir)):
if (name.startswith('fix_') and name.endswith('.py')):
if remove_prefix:
name = name[4:]
fix_names.append(name[:(-3)])
return fix_names
| [
"def",
"get_all_fix_names",
"(",
"fixer_pkg",
",",
"remove_prefix",
"=",
"True",
")",
":",
"pkg",
"=",
"__import__",
"(",
"fixer_pkg",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"'*'",
"]",
")",
"fixer_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pkg",
".",
"__file__",
")",
"fix_names",
"=",
"[",
"]",
"for",
"name",
"in",
"sorted",
"(",
"os",
".",
"listdir",
"(",
"fixer_dir",
")",
")",
":",
"if",
"(",
"name",
".",
"startswith",
"(",
"'fix_'",
")",
"and",
"name",
".",
"endswith",
"(",
"'.py'",
")",
")",
":",
"if",
"remove_prefix",
":",
"name",
"=",
"name",
"[",
"4",
":",
"]",
"fix_names",
".",
"append",
"(",
"name",
"[",
":",
"(",
"-",
"3",
")",
"]",
")",
"return",
"fix_names"
] | return a sorted list of all available fix names in the given package . | train | true |
14,811 | def date_parser(timestr, parserinfo=None, **kwargs):
flags = (re.IGNORECASE | re.VERBOSE)
if re.search(_q_pattern, timestr, flags):
(y, q) = timestr.replace(':', '').lower().split('q')
(month, day) = _quarter_to_day[q.upper()]
year = int(y)
elif re.search(_m_pattern, timestr, flags):
(y, m) = timestr.replace(':', '').lower().split('m')
(month, day) = _month_to_day[m.upper()]
year = int(y)
if (_is_leap(y) and (month == 2)):
day += 1
elif re.search(_y_pattern, timestr, flags):
(month, day) = (12, 31)
year = int(timestr)
else:
return pandas_datetools.to_datetime(timestr, **kwargs)
return datetime.datetime(year, month, day)
| [
"def",
"date_parser",
"(",
"timestr",
",",
"parserinfo",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"flags",
"=",
"(",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"VERBOSE",
")",
"if",
"re",
".",
"search",
"(",
"_q_pattern",
",",
"timestr",
",",
"flags",
")",
":",
"(",
"y",
",",
"q",
")",
"=",
"timestr",
".",
"replace",
"(",
"':'",
",",
"''",
")",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'q'",
")",
"(",
"month",
",",
"day",
")",
"=",
"_quarter_to_day",
"[",
"q",
".",
"upper",
"(",
")",
"]",
"year",
"=",
"int",
"(",
"y",
")",
"elif",
"re",
".",
"search",
"(",
"_m_pattern",
",",
"timestr",
",",
"flags",
")",
":",
"(",
"y",
",",
"m",
")",
"=",
"timestr",
".",
"replace",
"(",
"':'",
",",
"''",
")",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'m'",
")",
"(",
"month",
",",
"day",
")",
"=",
"_month_to_day",
"[",
"m",
".",
"upper",
"(",
")",
"]",
"year",
"=",
"int",
"(",
"y",
")",
"if",
"(",
"_is_leap",
"(",
"y",
")",
"and",
"(",
"month",
"==",
"2",
")",
")",
":",
"day",
"+=",
"1",
"elif",
"re",
".",
"search",
"(",
"_y_pattern",
",",
"timestr",
",",
"flags",
")",
":",
"(",
"month",
",",
"day",
")",
"=",
"(",
"12",
",",
"31",
")",
"year",
"=",
"int",
"(",
"timestr",
")",
"else",
":",
"return",
"pandas_datetools",
".",
"to_datetime",
"(",
"timestr",
",",
"**",
"kwargs",
")",
"return",
"datetime",
".",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
")"
] | uses dateutil . | train | false |
14,812 | def _normalize_sequence(input, rank, array_type=None):
is_str = isinstance(input, string_types)
if (hasattr(input, '__iter__') and (not is_str)):
normalized = list(input)
if (len(normalized) != rank):
err = 'sequence argument must have length equal to input rank'
raise RuntimeError(err)
else:
normalized = ([input] * rank)
return normalized
| [
"def",
"_normalize_sequence",
"(",
"input",
",",
"rank",
",",
"array_type",
"=",
"None",
")",
":",
"is_str",
"=",
"isinstance",
"(",
"input",
",",
"string_types",
")",
"if",
"(",
"hasattr",
"(",
"input",
",",
"'__iter__'",
")",
"and",
"(",
"not",
"is_str",
")",
")",
":",
"normalized",
"=",
"list",
"(",
"input",
")",
"if",
"(",
"len",
"(",
"normalized",
")",
"!=",
"rank",
")",
":",
"err",
"=",
"'sequence argument must have length equal to input rank'",
"raise",
"RuntimeError",
"(",
"err",
")",
"else",
":",
"normalized",
"=",
"(",
"[",
"input",
"]",
"*",
"rank",
")",
"return",
"normalized"
] | if input is a scalar . | train | false |
14,813 | def init_repo(path):
sh(('git clone %s %s' % (pages_repo, path)))
here = os.getcwdu()
cd(path)
sh('git checkout gh-pages')
cd(here)
| [
"def",
"init_repo",
"(",
"path",
")",
":",
"sh",
"(",
"(",
"'git clone %s %s'",
"%",
"(",
"pages_repo",
",",
"path",
")",
")",
")",
"here",
"=",
"os",
".",
"getcwdu",
"(",
")",
"cd",
"(",
"path",
")",
"sh",
"(",
"'git checkout gh-pages'",
")",
"cd",
"(",
"here",
")"
] | create the git bare repository for bup in a given path . | train | false |
14,814 | def activatePdpContextAccept(PacketDataProtocolAddress_presence=0, ProtocolConfigurationOptions_presence=0):
a = TpPd(pd=8)
b = MessageType(mesType=66)
c = LlcServiceAccessPointIdentifier()
d = QualityOfService()
e = RadioPriorityAndSpareHalfOctets()
packet = ((((a / b) / c) / d) / e)
if (PacketDataProtocolAddress_presence is 1):
f = PacketDataProtocolAddress(ieiPDPA=43)
packet = (packet / f)
if (ProtocolConfigurationOptions_presence is 1):
g = ProtocolConfigurationOptions(ieiPCO=39)
packet = (packet / g)
return packet
| [
"def",
"activatePdpContextAccept",
"(",
"PacketDataProtocolAddress_presence",
"=",
"0",
",",
"ProtocolConfigurationOptions_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"8",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"66",
")",
"c",
"=",
"LlcServiceAccessPointIdentifier",
"(",
")",
"d",
"=",
"QualityOfService",
"(",
")",
"e",
"=",
"RadioPriorityAndSpareHalfOctets",
"(",
")",
"packet",
"=",
"(",
"(",
"(",
"(",
"a",
"/",
"b",
")",
"/",
"c",
")",
"/",
"d",
")",
"/",
"e",
")",
"if",
"(",
"PacketDataProtocolAddress_presence",
"is",
"1",
")",
":",
"f",
"=",
"PacketDataProtocolAddress",
"(",
"ieiPDPA",
"=",
"43",
")",
"packet",
"=",
"(",
"packet",
"/",
"f",
")",
"if",
"(",
"ProtocolConfigurationOptions_presence",
"is",
"1",
")",
":",
"g",
"=",
"ProtocolConfigurationOptions",
"(",
"ieiPCO",
"=",
"39",
")",
"packet",
"=",
"(",
"packet",
"/",
"g",
")",
"return",
"packet"
] | activate pdp context accept section 9 . | train | true |
14,816 | def undeployed(name, url='http://localhost:8080/manager', timeout=180):
ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
if (not __salt__['tomcat.status'](url, timeout)):
ret['comment'] = 'Tomcat Manager does not respond'
ret['result'] = False
return ret
try:
version = __salt__['tomcat.ls'](url, timeout)[name]['version']
ret['changes'] = {'undeploy': version}
except KeyError:
return ret
if __opts__['test']:
ret['result'] = None
return ret
undeploy = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
if undeploy.startswith('FAIL'):
ret['result'] = False
ret['comment'] = undeploy
return ret
return ret
| [
"def",
"undeployed",
"(",
"name",
",",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"if",
"(",
"not",
"__salt__",
"[",
"'tomcat.status'",
"]",
"(",
"url",
",",
"timeout",
")",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Tomcat Manager does not respond'",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"return",
"ret",
"try",
":",
"version",
"=",
"__salt__",
"[",
"'tomcat.ls'",
"]",
"(",
"url",
",",
"timeout",
")",
"[",
"name",
"]",
"[",
"'version'",
"]",
"ret",
"[",
"'changes'",
"]",
"=",
"{",
"'undeploy'",
":",
"version",
"}",
"except",
"KeyError",
":",
"return",
"ret",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'result'",
"]",
"=",
"None",
"return",
"ret",
"undeploy",
"=",
"__salt__",
"[",
"'tomcat.undeploy'",
"]",
"(",
"name",
",",
"url",
",",
"timeout",
"=",
"timeout",
")",
"if",
"undeploy",
".",
"startswith",
"(",
"'FAIL'",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'comment'",
"]",
"=",
"undeploy",
"return",
"ret",
"return",
"ret"
] | enforce that the war will be undeployed from the server name the context path to undeploy . | train | true |
14,817 | def newDerInteger(number):
der = DerInteger(number)
return der
| [
"def",
"newDerInteger",
"(",
"number",
")",
":",
"der",
"=",
"DerInteger",
"(",
"number",
")",
"return",
"der"
] | create a derinteger object . | train | false |
14,818 | def _split_proto_line(line, allowed):
if (not line):
fields = [None]
else:
fields = line.rstrip('\n').split(' ', 1)
command = fields[0]
if ((allowed is not None) and (command not in allowed)):
raise UnexpectedCommandError(command)
if ((len(fields) == 1) and (command in (COMMAND_DONE, None))):
return (command, None)
elif (len(fields) == 2):
if (command in (COMMAND_WANT, COMMAND_HAVE, COMMAND_SHALLOW, COMMAND_UNSHALLOW)):
if (not valid_hexsha(fields[1])):
raise GitProtocolError('Invalid sha')
return tuple(fields)
elif (command == COMMAND_DEEPEN):
return (command, int(fields[1]))
raise GitProtocolError(('Received invalid line from client: %r' % line))
| [
"def",
"_split_proto_line",
"(",
"line",
",",
"allowed",
")",
":",
"if",
"(",
"not",
"line",
")",
":",
"fields",
"=",
"[",
"None",
"]",
"else",
":",
"fields",
"=",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"' '",
",",
"1",
")",
"command",
"=",
"fields",
"[",
"0",
"]",
"if",
"(",
"(",
"allowed",
"is",
"not",
"None",
")",
"and",
"(",
"command",
"not",
"in",
"allowed",
")",
")",
":",
"raise",
"UnexpectedCommandError",
"(",
"command",
")",
"if",
"(",
"(",
"len",
"(",
"fields",
")",
"==",
"1",
")",
"and",
"(",
"command",
"in",
"(",
"COMMAND_DONE",
",",
"None",
")",
")",
")",
":",
"return",
"(",
"command",
",",
"None",
")",
"elif",
"(",
"len",
"(",
"fields",
")",
"==",
"2",
")",
":",
"if",
"(",
"command",
"in",
"(",
"COMMAND_WANT",
",",
"COMMAND_HAVE",
",",
"COMMAND_SHALLOW",
",",
"COMMAND_UNSHALLOW",
")",
")",
":",
"if",
"(",
"not",
"valid_hexsha",
"(",
"fields",
"[",
"1",
"]",
")",
")",
":",
"raise",
"GitProtocolError",
"(",
"'Invalid sha'",
")",
"return",
"tuple",
"(",
"fields",
")",
"elif",
"(",
"command",
"==",
"COMMAND_DEEPEN",
")",
":",
"return",
"(",
"command",
",",
"int",
"(",
"fields",
"[",
"1",
"]",
")",
")",
"raise",
"GitProtocolError",
"(",
"(",
"'Received invalid line from client: %r'",
"%",
"line",
")",
")"
] | split a line read from the wire . | train | false |
14,819 | def getAllMonitors():
monitorList = glob.glob(os.path.join(monitorFolder, '*.calib'))
split = os.path.split
splitext = os.path.splitext
monitorList = [splitext(split(thisFile)[(-1)])[0] for thisFile in monitorList]
return monitorList
| [
"def",
"getAllMonitors",
"(",
")",
":",
"monitorList",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"monitorFolder",
",",
"'*.calib'",
")",
")",
"split",
"=",
"os",
".",
"path",
".",
"split",
"splitext",
"=",
"os",
".",
"path",
".",
"splitext",
"monitorList",
"=",
"[",
"splitext",
"(",
"split",
"(",
"thisFile",
")",
"[",
"(",
"-",
"1",
")",
"]",
")",
"[",
"0",
"]",
"for",
"thisFile",
"in",
"monitorList",
"]",
"return",
"monitorList"
] | find the names of all monitors for which calibration files exist . | train | false |
14,821 | def p_cast_expression_2(t):
pass
| [
"def",
"p_cast_expression_2",
"(",
"t",
")",
":",
"pass"
] | cast_expression : lparen type_name rparen cast_expression . | train | false |
14,822 | def _create_more_application():
from prompt_toolkit.shortcuts import create_prompt_application
registry = Registry()
@registry.add_binding(u' ')
@registry.add_binding(u'y')
@registry.add_binding(u'Y')
@registry.add_binding(Keys.ControlJ)
@registry.add_binding(Keys.ControlI)
def _(event):
event.cli.set_return_value(True)
@registry.add_binding(u'n')
@registry.add_binding(u'N')
@registry.add_binding(u'q')
@registry.add_binding(u'Q')
@registry.add_binding(Keys.ControlC)
def _(event):
event.cli.set_return_value(False)
return create_prompt_application(u'--MORE--', key_bindings_registry=registry, erase_when_done=True)
| [
"def",
"_create_more_application",
"(",
")",
":",
"from",
"prompt_toolkit",
".",
"shortcuts",
"import",
"create_prompt_application",
"registry",
"=",
"Registry",
"(",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u' '",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u'y'",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u'Y'",
")",
"@",
"registry",
".",
"add_binding",
"(",
"Keys",
".",
"ControlJ",
")",
"@",
"registry",
".",
"add_binding",
"(",
"Keys",
".",
"ControlI",
")",
"def",
"_",
"(",
"event",
")",
":",
"event",
".",
"cli",
".",
"set_return_value",
"(",
"True",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u'n'",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u'N'",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u'q'",
")",
"@",
"registry",
".",
"add_binding",
"(",
"u'Q'",
")",
"@",
"registry",
".",
"add_binding",
"(",
"Keys",
".",
"ControlC",
")",
"def",
"_",
"(",
"event",
")",
":",
"event",
".",
"cli",
".",
"set_return_value",
"(",
"False",
")",
"return",
"create_prompt_application",
"(",
"u'--MORE--'",
",",
"key_bindings_registry",
"=",
"registry",
",",
"erase_when_done",
"=",
"True",
")"
] | create an application instance that displays the "--more--" . | train | false |
14,823 | def get_pointer_parent(pointer):
parent_refs = pointer.node__parent
assert (len(parent_refs) == 1), 'Pointer must have exactly one parent.'
return parent_refs[0]
| [
"def",
"get_pointer_parent",
"(",
"pointer",
")",
":",
"parent_refs",
"=",
"pointer",
".",
"node__parent",
"assert",
"(",
"len",
"(",
"parent_refs",
")",
"==",
"1",
")",
",",
"'Pointer must have exactly one parent.'",
"return",
"parent_refs",
"[",
"0",
"]"
] | given a pointer object . | train | false |
14,824 | def is_imdb_url(url):
if (not isinstance(url, basestring)):
return
return re.match(u'https?://[^/]*imdb\\.com/', url)
| [
"def",
"is_imdb_url",
"(",
"url",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"url",
",",
"basestring",
")",
")",
":",
"return",
"return",
"re",
".",
"match",
"(",
"u'https?://[^/]*imdb\\\\.com/'",
",",
"url",
")"
] | tests the url to see if its for imdb . | train | false |
14,825 | def get_prefix_from_ns_name(ns_name):
dash_index = ns_name.find('-')
if (0 <= dash_index):
return ns_name[:(dash_index + 1)]
| [
"def",
"get_prefix_from_ns_name",
"(",
"ns_name",
")",
":",
"dash_index",
"=",
"ns_name",
".",
"find",
"(",
"'-'",
")",
"if",
"(",
"0",
"<=",
"dash_index",
")",
":",
"return",
"ns_name",
"[",
":",
"(",
"dash_index",
"+",
"1",
")",
"]"
] | parses prefix from prefix-identifier . | train | false |
14,826 | def crypt_generic_passwd(password, salt, uppercase=False):
retVal = crypt(password, salt)
return (retVal.upper() if uppercase else retVal)
| [
"def",
"crypt_generic_passwd",
"(",
"password",
",",
"salt",
",",
"uppercase",
"=",
"False",
")",
":",
"retVal",
"=",
"crypt",
"(",
"password",
",",
"salt",
")",
"return",
"(",
"retVal",
".",
"upper",
"(",
")",
"if",
"uppercase",
"else",
"retVal",
")"
] | reference(s): URL URL URL URL . | train | false |
14,827 | def make_gax_metrics_api(client):
channel = make_secure_channel(client._connection.credentials, DEFAULT_USER_AGENT, MetricsServiceV2Client.SERVICE_ADDRESS)
generated = MetricsServiceV2Client(channel=channel)
return _MetricsAPI(generated, client)
| [
"def",
"make_gax_metrics_api",
"(",
"client",
")",
":",
"channel",
"=",
"make_secure_channel",
"(",
"client",
".",
"_connection",
".",
"credentials",
",",
"DEFAULT_USER_AGENT",
",",
"MetricsServiceV2Client",
".",
"SERVICE_ADDRESS",
")",
"generated",
"=",
"MetricsServiceV2Client",
"(",
"channel",
"=",
"channel",
")",
"return",
"_MetricsAPI",
"(",
"generated",
",",
"client",
")"
] | create an instance of the gax metrics api . | train | false |
14,828 | def corner_orientations(image, corners, mask):
return _corner_orientations(image, corners, mask)
| [
"def",
"corner_orientations",
"(",
"image",
",",
"corners",
",",
"mask",
")",
":",
"return",
"_corner_orientations",
"(",
"image",
",",
"corners",
",",
"mask",
")"
] | compute the orientation of corners . | train | false |
14,830 | def find_first_remote_branch(remotes, branch_name):
for remote in remotes:
try:
return remote.refs[branch_name]
except IndexError:
continue
raise InvalidGitRepositoryError(("Didn't find remote branch '%r' in any of the given remotes" % branch_name))
| [
"def",
"find_first_remote_branch",
"(",
"remotes",
",",
"branch_name",
")",
":",
"for",
"remote",
"in",
"remotes",
":",
"try",
":",
"return",
"remote",
".",
"refs",
"[",
"branch_name",
"]",
"except",
"IndexError",
":",
"continue",
"raise",
"InvalidGitRepositoryError",
"(",
"(",
"\"Didn't find remote branch '%r' in any of the given remotes\"",
"%",
"branch_name",
")",
")"
] | find the remote branch matching the name of the given branch or raise invalidgitrepositoryerror . | train | true |
14,831 | def get_modules_dir():
kernel_version = os.uname()[2]
return ('/lib/modules/%s/kernel' % kernel_version)
| [
"def",
"get_modules_dir",
"(",
")",
":",
"kernel_version",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"2",
"]",
"return",
"(",
"'/lib/modules/%s/kernel'",
"%",
"kernel_version",
")"
] | return the modules dir for the running kernel version . | train | false |
14,832 | def inference(images, keep_probability, phase_train=True, weight_decay=0.0):
endpoints = {}
net = network.conv(images, 3, 64, 7, 7, 2, 2, 'SAME', 'conv1_7x7', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['conv1'] = net
net = network.mpool(net, 3, 3, 2, 2, 'SAME', 'pool1')
endpoints['pool1'] = net
net = network.conv(net, 64, 64, 1, 1, 1, 1, 'SAME', 'conv2_1x1', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['conv2_1x1'] = net
net = network.conv(net, 64, 192, 3, 3, 1, 1, 'SAME', 'conv3_3x3', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['conv3_3x3'] = net
net = network.mpool(net, 3, 3, 2, 2, 'SAME', 'pool3')
endpoints['pool3'] = net
net = network.inception(net, 192, 1, 64, 96, 128, 16, 32, 3, 32, 1, 'MAX', 'incept3a', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept3a'] = net
net = network.inception(net, 256, 1, 64, 96, 128, 32, 64, 3, 64, 1, 'MAX', 'incept3b', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept3b'] = net
net = network.inception(net, 320, 2, 0, 128, 256, 32, 64, 3, 0, 2, 'MAX', 'incept3c', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept3c'] = net
net = network.inception(net, 640, 1, 256, 96, 192, 32, 64, 3, 128, 1, 'MAX', 'incept4a', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept4a'] = net
net = network.inception(net, 640, 1, 224, 112, 224, 32, 64, 3, 128, 1, 'MAX', 'incept4b', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept4b'] = net
net = network.inception(net, 640, 1, 192, 128, 256, 32, 64, 3, 128, 1, 'MAX', 'incept4c', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept4c'] = net
net = network.inception(net, 640, 1, 160, 144, 288, 32, 64, 3, 128, 1, 'MAX', 'incept4d', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept4d'] = net
net = network.inception(net, 640, 2, 0, 160, 256, 64, 128, 3, 0, 2, 'MAX', 'incept4e', phase_train=phase_train, use_batch_norm=True)
endpoints['incept4e'] = net
net = network.inception(net, 1024, 1, 384, 192, 384, 0, 0, 3, 128, 1, 'MAX', 'incept5a', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept5a'] = net
net = network.inception(net, 896, 1, 384, 192, 384, 0, 0, 3, 128, 1, 'MAX', 'incept5b', phase_train=phase_train, use_batch_norm=True, weight_decay=weight_decay)
endpoints['incept5b'] = net
net = network.apool(net, 3, 3, 1, 1, 'VALID', 'pool6')
endpoints['pool6'] = net
net = tf.reshape(net, [(-1), 896])
endpoints['prelogits'] = net
net = tf.nn.dropout(net, keep_probability)
endpoints['dropout'] = net
return (net, endpoints)
| [
"def",
"inference",
"(",
"images",
",",
"keep_probability",
",",
"phase_train",
"=",
"True",
",",
"weight_decay",
"=",
"0.0",
")",
":",
"endpoints",
"=",
"{",
"}",
"net",
"=",
"network",
".",
"conv",
"(",
"images",
",",
"3",
",",
"64",
",",
"7",
",",
"7",
",",
"2",
",",
"2",
",",
"'SAME'",
",",
"'conv1_7x7'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'conv1'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"mpool",
"(",
"net",
",",
"3",
",",
"3",
",",
"2",
",",
"2",
",",
"'SAME'",
",",
"'pool1'",
")",
"endpoints",
"[",
"'pool1'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"conv",
"(",
"net",
",",
"64",
",",
"64",
",",
"1",
",",
"1",
",",
"1",
",",
"1",
",",
"'SAME'",
",",
"'conv2_1x1'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'conv2_1x1'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"conv",
"(",
"net",
",",
"64",
",",
"192",
",",
"3",
",",
"3",
",",
"1",
",",
"1",
",",
"'SAME'",
",",
"'conv3_3x3'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'conv3_3x3'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"mpool",
"(",
"net",
",",
"3",
",",
"3",
",",
"2",
",",
"2",
",",
"'SAME'",
",",
"'pool3'",
")",
"endpoints",
"[",
"'pool3'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"192",
",",
"1",
",",
"64",
",",
"96",
",",
"128",
",",
"16",
",",
"32",
",",
"3",
",",
"32",
",",
"1",
",",
"'MAX'",
",",
"'incept3a'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept3a'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"256",
",",
"1",
",",
"64",
",",
"96",
",",
"128",
",",
"32",
",",
"64",
",",
"3",
",",
"64",
",",
"1",
",",
"'MAX'",
",",
"'incept3b'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept3b'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"320",
",",
"2",
",",
"0",
",",
"128",
",",
"256",
",",
"32",
",",
"64",
",",
"3",
",",
"0",
",",
"2",
",",
"'MAX'",
",",
"'incept3c'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept3c'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"640",
",",
"1",
",",
"256",
",",
"96",
",",
"192",
",",
"32",
",",
"64",
",",
"3",
",",
"128",
",",
"1",
",",
"'MAX'",
",",
"'incept4a'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept4a'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"640",
",",
"1",
",",
"224",
",",
"112",
",",
"224",
",",
"32",
",",
"64",
",",
"3",
",",
"128",
",",
"1",
",",
"'MAX'",
",",
"'incept4b'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept4b'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"640",
",",
"1",
",",
"192",
",",
"128",
",",
"256",
",",
"32",
",",
"64",
",",
"3",
",",
"128",
",",
"1",
",",
"'MAX'",
",",
"'incept4c'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept4c'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"640",
",",
"1",
",",
"160",
",",
"144",
",",
"288",
",",
"32",
",",
"64",
",",
"3",
",",
"128",
",",
"1",
",",
"'MAX'",
",",
"'incept4d'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept4d'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"640",
",",
"2",
",",
"0",
",",
"160",
",",
"256",
",",
"64",
",",
"128",
",",
"3",
",",
"0",
",",
"2",
",",
"'MAX'",
",",
"'incept4e'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
")",
"endpoints",
"[",
"'incept4e'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"1024",
",",
"1",
",",
"384",
",",
"192",
",",
"384",
",",
"0",
",",
"0",
",",
"3",
",",
"128",
",",
"1",
",",
"'MAX'",
",",
"'incept5a'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept5a'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"inception",
"(",
"net",
",",
"896",
",",
"1",
",",
"384",
",",
"192",
",",
"384",
",",
"0",
",",
"0",
",",
"3",
",",
"128",
",",
"1",
",",
"'MAX'",
",",
"'incept5b'",
",",
"phase_train",
"=",
"phase_train",
",",
"use_batch_norm",
"=",
"True",
",",
"weight_decay",
"=",
"weight_decay",
")",
"endpoints",
"[",
"'incept5b'",
"]",
"=",
"net",
"net",
"=",
"network",
".",
"apool",
"(",
"net",
",",
"3",
",",
"3",
",",
"1",
",",
"1",
",",
"'VALID'",
",",
"'pool6'",
")",
"endpoints",
"[",
"'pool6'",
"]",
"=",
"net",
"net",
"=",
"tf",
".",
"reshape",
"(",
"net",
",",
"[",
"(",
"-",
"1",
")",
",",
"896",
"]",
")",
"endpoints",
"[",
"'prelogits'",
"]",
"=",
"net",
"net",
"=",
"tf",
".",
"nn",
".",
"dropout",
"(",
"net",
",",
"keep_probability",
")",
"endpoints",
"[",
"'dropout'",
"]",
"=",
"net",
"return",
"(",
"net",
",",
"endpoints",
")"
] | build inception v3 model architecture . | train | false |
14,833 | def PrefixFromPattern(pattern):
if pattern.endswith('*'):
return pattern[:(-1)]
elif pattern.endswith('/'):
return ('' if (pattern == '/') else pattern)
elif (pattern == ''):
return pattern
else:
return (pattern + '/')
| [
"def",
"PrefixFromPattern",
"(",
"pattern",
")",
":",
"if",
"pattern",
".",
"endswith",
"(",
"'*'",
")",
":",
"return",
"pattern",
"[",
":",
"(",
"-",
"1",
")",
"]",
"elif",
"pattern",
".",
"endswith",
"(",
"'/'",
")",
":",
"return",
"(",
"''",
"if",
"(",
"pattern",
"==",
"'/'",
")",
"else",
"pattern",
")",
"elif",
"(",
"pattern",
"==",
"''",
")",
":",
"return",
"pattern",
"else",
":",
"return",
"(",
"pattern",
"+",
"'/'",
")"
] | given a path pattern . | train | false |
14,834 | def __filter_items(items, name_filter, before_str):
result = []
for item in items:
if (not name_filter.match(item.get('name'))):
continue
if ((before_str is None) or (determine_timestamp(item) < before_str)):
result.append(item)
return result
| [
"def",
"__filter_items",
"(",
"items",
",",
"name_filter",
",",
"before_str",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"(",
"not",
"name_filter",
".",
"match",
"(",
"item",
".",
"get",
"(",
"'name'",
")",
")",
")",
":",
"continue",
"if",
"(",
"(",
"before_str",
"is",
"None",
")",
"or",
"(",
"determine_timestamp",
"(",
"item",
")",
"<",
"before_str",
")",
")",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] | args: items: [list of dict] list of item candidates . | train | false |
14,836 | def test_bool_column(tmpdir):
arr = np.ones(5, dtype=bool)
(arr[::2] == np.False_)
t = Table([arr])
t.write(str(tmpdir.join('test.fits')), overwrite=True)
with fits.open(str(tmpdir.join('test.fits'))) as hdul:
assert (hdul[1].data['col0'].dtype == np.dtype('bool'))
assert np.all((hdul[1].data['col0'] == arr))
| [
"def",
"test_bool_column",
"(",
"tmpdir",
")",
":",
"arr",
"=",
"np",
".",
"ones",
"(",
"5",
",",
"dtype",
"=",
"bool",
")",
"(",
"arr",
"[",
":",
":",
"2",
"]",
"==",
"np",
".",
"False_",
")",
"t",
"=",
"Table",
"(",
"[",
"arr",
"]",
")",
"t",
".",
"write",
"(",
"str",
"(",
"tmpdir",
".",
"join",
"(",
"'test.fits'",
")",
")",
",",
"overwrite",
"=",
"True",
")",
"with",
"fits",
".",
"open",
"(",
"str",
"(",
"tmpdir",
".",
"join",
"(",
"'test.fits'",
")",
")",
")",
"as",
"hdul",
":",
"assert",
"(",
"hdul",
"[",
"1",
"]",
".",
"data",
"[",
"'col0'",
"]",
".",
"dtype",
"==",
"np",
".",
"dtype",
"(",
"'bool'",
")",
")",
"assert",
"np",
".",
"all",
"(",
"(",
"hdul",
"[",
"1",
"]",
".",
"data",
"[",
"'col0'",
"]",
"==",
"arr",
")",
")"
] | regression test for URL ensures that table columns of bools are properly written to a fits table . | train | false |
14,838 | def as_value(s):
return ('<value>%s</value>' % saxutils.escape(s))
| [
"def",
"as_value",
"(",
"s",
")",
":",
"return",
"(",
"'<value>%s</value>'",
"%",
"saxutils",
".",
"escape",
"(",
"s",
")",
")"
] | helper function for simulating xenapi plugin responses . | train | false |
14,839 | @receiver(SignalHandler.pre_publish)
def on_pre_publish(sender, course_key, **kwargs):
from openedx.core.djangoapps.credit import api
if api.is_credit_course(course_key):
log.info(u'Starting to update in-course reverification access rules')
update_verification_partitions(course_key)
log.info(u'Finished updating in-course reverification access rules')
| [
"@",
"receiver",
"(",
"SignalHandler",
".",
"pre_publish",
")",
"def",
"on_pre_publish",
"(",
"sender",
",",
"course_key",
",",
"**",
"kwargs",
")",
":",
"from",
"openedx",
".",
"core",
".",
"djangoapps",
".",
"credit",
"import",
"api",
"if",
"api",
".",
"is_credit_course",
"(",
"course_key",
")",
":",
"log",
".",
"info",
"(",
"u'Starting to update in-course reverification access rules'",
")",
"update_verification_partitions",
"(",
"course_key",
")",
"log",
".",
"info",
"(",
"u'Finished updating in-course reverification access rules'",
")"
] | create user partitions for verification checkpoints . | train | false |
14,840 | def _get_proc_cmdline(proc):
try:
return (proc.cmdline() if PSUTIL2 else proc.cmdline)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return ''
| [
"def",
"_get_proc_cmdline",
"(",
"proc",
")",
":",
"try",
":",
"return",
"(",
"proc",
".",
"cmdline",
"(",
")",
"if",
"PSUTIL2",
"else",
"proc",
".",
"cmdline",
")",
"except",
"(",
"psutil",
".",
"NoSuchProcess",
",",
"psutil",
".",
"AccessDenied",
")",
":",
"return",
"''"
] | returns the cmdline of a process instance . | train | false |
14,841 | def nbinstall(overwrite=False, user=True):
if (check_nbextension('matplotlib') or check_nbextension('matplotlib', True)):
return
tempdir = mkdtemp()
path = os.path.join(os.path.dirname(__file__), 'web_backend')
shutil.copy2(os.path.join(path, 'nbagg_mpl.js'), tempdir)
with open(os.path.join(path, 'mpl.js')) as fid:
contents = fid.read()
with open(os.path.join(tempdir, 'mpl.js'), 'w') as fid:
fid.write('define(["jquery"], function($) {\n')
fid.write(contents)
fid.write('\nreturn mpl;\n});')
install_nbextension(tempdir, overwrite=overwrite, symlink=False, destination='matplotlib', verbose=0, **({'user': user} if (version_info >= (3, 0, 0, '')) else {}))
| [
"def",
"nbinstall",
"(",
"overwrite",
"=",
"False",
",",
"user",
"=",
"True",
")",
":",
"if",
"(",
"check_nbextension",
"(",
"'matplotlib'",
")",
"or",
"check_nbextension",
"(",
"'matplotlib'",
",",
"True",
")",
")",
":",
"return",
"tempdir",
"=",
"mkdtemp",
"(",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'web_backend'",
")",
"shutil",
".",
"copy2",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'nbagg_mpl.js'",
")",
",",
"tempdir",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'mpl.js'",
")",
")",
"as",
"fid",
":",
"contents",
"=",
"fid",
".",
"read",
"(",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"'mpl.js'",
")",
",",
"'w'",
")",
"as",
"fid",
":",
"fid",
".",
"write",
"(",
"'define([\"jquery\"], function($) {\\n'",
")",
"fid",
".",
"write",
"(",
"contents",
")",
"fid",
".",
"write",
"(",
"'\\nreturn mpl;\\n});'",
")",
"install_nbextension",
"(",
"tempdir",
",",
"overwrite",
"=",
"overwrite",
",",
"symlink",
"=",
"False",
",",
"destination",
"=",
"'matplotlib'",
",",
"verbose",
"=",
"0",
",",
"**",
"(",
"{",
"'user'",
":",
"user",
"}",
"if",
"(",
"version_info",
">=",
"(",
"3",
",",
"0",
",",
"0",
",",
"''",
")",
")",
"else",
"{",
"}",
")",
")"
] | copies javascript dependencies to the /nbextensions folder in your ipython directory . | train | false |
14,842 | @pytest.fixture
def store_po(tp0):
from pootle_translationproject.models import TranslationProject
tp = TranslationProject.objects.get(project__code='project0', language__code='language0')
store = StoreDBFactory(parent=tp.directory, translation_project=tp, name='test_store.po')
return store
| [
"@",
"pytest",
".",
"fixture",
"def",
"store_po",
"(",
"tp0",
")",
":",
"from",
"pootle_translationproject",
".",
"models",
"import",
"TranslationProject",
"tp",
"=",
"TranslationProject",
".",
"objects",
".",
"get",
"(",
"project__code",
"=",
"'project0'",
",",
"language__code",
"=",
"'language0'",
")",
"store",
"=",
"StoreDBFactory",
"(",
"parent",
"=",
"tp",
".",
"directory",
",",
"translation_project",
"=",
"tp",
",",
"name",
"=",
"'test_store.po'",
")",
"return",
"store"
] | an empty store in the /language0/project0 tp . | train | false |
14,844 | def getCacheByName(name):
if (name.lower() == 'test'):
return Test
elif (name.lower() == 'disk'):
return Disk
elif (name.lower() == 'multi'):
return Multi
elif (name.lower() == 'memcache'):
return Memcache.Cache
elif (name.lower() == 'redis'):
return Redis.Cache
elif (name.lower() == 's3'):
return S3.Cache
raise Exception(('Unknown cache name: "%s"' % name))
| [
"def",
"getCacheByName",
"(",
"name",
")",
":",
"if",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'test'",
")",
":",
"return",
"Test",
"elif",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'disk'",
")",
":",
"return",
"Disk",
"elif",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'multi'",
")",
":",
"return",
"Multi",
"elif",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'memcache'",
")",
":",
"return",
"Memcache",
".",
"Cache",
"elif",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'redis'",
")",
":",
"return",
"Redis",
".",
"Cache",
"elif",
"(",
"name",
".",
"lower",
"(",
")",
"==",
"'s3'",
")",
":",
"return",
"S3",
".",
"Cache",
"raise",
"Exception",
"(",
"(",
"'Unknown cache name: \"%s\"'",
"%",
"name",
")",
")"
] | retrieve a cache object by name . | train | false |
14,845 | def get_config_dir():
if mswin:
confdir = os.environ['APPDATA']
elif ('XDG_CONFIG_HOME' in os.environ):
confdir = os.environ['XDG_CONFIG_HOME']
else:
confdir = os.path.join(os.path.expanduser('~'), '.config')
mps_confdir = os.path.join(confdir, 'mps-youtube')
os.makedirs(mps_confdir, exist_ok=True)
return mps_confdir
| [
"def",
"get_config_dir",
"(",
")",
":",
"if",
"mswin",
":",
"confdir",
"=",
"os",
".",
"environ",
"[",
"'APPDATA'",
"]",
"elif",
"(",
"'XDG_CONFIG_HOME'",
"in",
"os",
".",
"environ",
")",
":",
"confdir",
"=",
"os",
".",
"environ",
"[",
"'XDG_CONFIG_HOME'",
"]",
"else",
":",
"confdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.config'",
")",
"mps_confdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"confdir",
",",
"'mps-youtube'",
")",
"os",
".",
"makedirs",
"(",
"mps_confdir",
",",
"exist_ok",
"=",
"True",
")",
"return",
"mps_confdir"
] | determines the astropy configuration directory name and creates the directory if it doesnt exist . | train | false |
14,847 | def parse_authorization_code_response(uri, state=None):
if (not is_secure_transport(uri)):
raise InsecureTransportError()
query = urlparse.urlparse(uri).query
params = dict(urlparse.parse_qsl(query))
if (not (u'code' in params)):
raise MissingCodeError(u'Missing code parameter in response.')
if (state and (params.get(u'state', None) != state)):
raise MismatchingStateError()
return params
| [
"def",
"parse_authorization_code_response",
"(",
"uri",
",",
"state",
"=",
"None",
")",
":",
"if",
"(",
"not",
"is_secure_transport",
"(",
"uri",
")",
")",
":",
"raise",
"InsecureTransportError",
"(",
")",
"query",
"=",
"urlparse",
".",
"urlparse",
"(",
"uri",
")",
".",
"query",
"params",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"query",
")",
")",
"if",
"(",
"not",
"(",
"u'code'",
"in",
"params",
")",
")",
":",
"raise",
"MissingCodeError",
"(",
"u'Missing code parameter in response.'",
")",
"if",
"(",
"state",
"and",
"(",
"params",
".",
"get",
"(",
"u'state'",
",",
"None",
")",
"!=",
"state",
")",
")",
":",
"raise",
"MismatchingStateError",
"(",
")",
"return",
"params"
] | parse authorization grant response uri into a dict . | train | true |
14,849 | def reloaded(manager, containers, count, name):
containers.refresh()
for container in manager.get_differing_containers():
manager.stop_containers([container])
manager.remove_containers([container])
started(manager, containers, count, name)
| [
"def",
"reloaded",
"(",
"manager",
",",
"containers",
",",
"count",
",",
"name",
")",
":",
"containers",
".",
"refresh",
"(",
")",
"for",
"container",
"in",
"manager",
".",
"get_differing_containers",
"(",
")",
":",
"manager",
".",
"stop_containers",
"(",
"[",
"container",
"]",
")",
"manager",
".",
"remove_containers",
"(",
"[",
"container",
"]",
")",
"started",
"(",
"manager",
",",
"containers",
",",
"count",
",",
"name",
")"
] | reloads syslog-ng . | train | false |
14,850 | def group_package_show(context, data_dict):
model = context['model']
group_id = _get_or_bust(data_dict, 'id')
limit = data_dict.get('limit')
if limit:
try:
limit = int(data_dict.get('limit'))
if (limit < 0):
raise logic.ValidationError('Limit must be a positive integer')
except ValueError:
raise logic.ValidationError('Limit must be a positive integer')
group = model.Group.get(group_id)
context['group'] = group
if (group is None):
raise NotFound
_check_access('group_show', context, data_dict)
result = logic.get_action('package_search')(context, {'fq': 'groups:{0}'.format(group.name), 'rows': limit})
return result['results']
| [
"def",
"group_package_show",
"(",
"context",
",",
"data_dict",
")",
":",
"model",
"=",
"context",
"[",
"'model'",
"]",
"group_id",
"=",
"_get_or_bust",
"(",
"data_dict",
",",
"'id'",
")",
"limit",
"=",
"data_dict",
".",
"get",
"(",
"'limit'",
")",
"if",
"limit",
":",
"try",
":",
"limit",
"=",
"int",
"(",
"data_dict",
".",
"get",
"(",
"'limit'",
")",
")",
"if",
"(",
"limit",
"<",
"0",
")",
":",
"raise",
"logic",
".",
"ValidationError",
"(",
"'Limit must be a positive integer'",
")",
"except",
"ValueError",
":",
"raise",
"logic",
".",
"ValidationError",
"(",
"'Limit must be a positive integer'",
")",
"group",
"=",
"model",
".",
"Group",
".",
"get",
"(",
"group_id",
")",
"context",
"[",
"'group'",
"]",
"=",
"group",
"if",
"(",
"group",
"is",
"None",
")",
":",
"raise",
"NotFound",
"_check_access",
"(",
"'group_show'",
",",
"context",
",",
"data_dict",
")",
"result",
"=",
"logic",
".",
"get_action",
"(",
"'package_search'",
")",
"(",
"context",
",",
"{",
"'fq'",
":",
"'groups:{0}'",
".",
"format",
"(",
"group",
".",
"name",
")",
",",
"'rows'",
":",
"limit",
"}",
")",
"return",
"result",
"[",
"'results'",
"]"
] | return the datasets of a group . | train | false |
14,852 | def libvlc_vlm_show_media(p_instance, psz_name):
f = (_Cfunctions.get('libvlc_vlm_show_media', None) or _Cfunction('libvlc_vlm_show_media', ((1,), (1,)), string_result, ctypes.c_void_p, Instance, ctypes.c_char_p))
return f(p_instance, psz_name)
| [
"def",
"libvlc_vlm_show_media",
"(",
"p_instance",
",",
"psz_name",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_vlm_show_media'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_vlm_show_media'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
")",
",",
"string_result",
",",
"ctypes",
".",
"c_void_p",
",",
"Instance",
",",
"ctypes",
".",
"c_char_p",
")",
")",
"return",
"f",
"(",
"p_instance",
",",
"psz_name",
")"
] | return information about the named media as a json string representation . | train | true |
14,853 | @ignore_warnings
def check_estimators_unfitted(name, Estimator):
(X, y) = _boston_subset()
est = Estimator()
msg = 'fit'
if hasattr(est, 'predict'):
assert_raise_message((AttributeError, ValueError), msg, est.predict, X)
if hasattr(est, 'decision_function'):
assert_raise_message((AttributeError, ValueError), msg, est.decision_function, X)
if hasattr(est, 'predict_proba'):
assert_raise_message((AttributeError, ValueError), msg, est.predict_proba, X)
if hasattr(est, 'predict_log_proba'):
assert_raise_message((AttributeError, ValueError), msg, est.predict_log_proba, X)
| [
"@",
"ignore_warnings",
"def",
"check_estimators_unfitted",
"(",
"name",
",",
"Estimator",
")",
":",
"(",
"X",
",",
"y",
")",
"=",
"_boston_subset",
"(",
")",
"est",
"=",
"Estimator",
"(",
")",
"msg",
"=",
"'fit'",
"if",
"hasattr",
"(",
"est",
",",
"'predict'",
")",
":",
"assert_raise_message",
"(",
"(",
"AttributeError",
",",
"ValueError",
")",
",",
"msg",
",",
"est",
".",
"predict",
",",
"X",
")",
"if",
"hasattr",
"(",
"est",
",",
"'decision_function'",
")",
":",
"assert_raise_message",
"(",
"(",
"AttributeError",
",",
"ValueError",
")",
",",
"msg",
",",
"est",
".",
"decision_function",
",",
"X",
")",
"if",
"hasattr",
"(",
"est",
",",
"'predict_proba'",
")",
":",
"assert_raise_message",
"(",
"(",
"AttributeError",
",",
"ValueError",
")",
",",
"msg",
",",
"est",
".",
"predict_proba",
",",
"X",
")",
"if",
"hasattr",
"(",
"est",
",",
"'predict_log_proba'",
")",
":",
"assert_raise_message",
"(",
"(",
"AttributeError",
",",
"ValueError",
")",
",",
"msg",
",",
"est",
".",
"predict_log_proba",
",",
"X",
")"
] | check that predict raises an exception in an unfitted estimator . | train | false |
14,854 | def has_common(l1, l2):
return (set(l1) & set(l2))
| [
"def",
"has_common",
"(",
"l1",
",",
"l2",
")",
":",
"return",
"(",
"set",
"(",
"l1",
")",
"&",
"set",
"(",
"l2",
")",
")"
] | returns truthy value if there are common elements in lists l1 and l2 . | train | false |
14,856 | def splitlines(string):
return re.split('\n|\r\n', string)
| [
"def",
"splitlines",
"(",
"string",
")",
":",
"return",
"re",
".",
"split",
"(",
"'\\n|\\r\\n'",
",",
"string",
")"
] | a splitlines for python code . | train | false |
14,857 | def test_affine_wrapper(backend_default):
nout = 11
aff = Affine(nout, Uniform())
assert isinstance(aff, list)
assert (len(aff) == 1)
assert isinstance(aff[0], Linear)
assert (aff[0].nout == nout)
aff = Affine(nout, Uniform(), bias=Uniform())
assert isinstance(aff, list)
assert (len(aff) == 2)
assert isinstance(aff[0], Linear)
assert isinstance(aff[1], Bias)
aff = Affine(nout, Uniform(), activation=Rectlin())
assert isinstance(aff, list)
assert (len(aff) == 2)
assert isinstance(aff[0], Linear)
assert isinstance(aff[1], Activation)
aff = Affine(nout, Uniform(), bias=Uniform(), activation=Rectlin())
assert isinstance(aff, list)
assert (len(aff) == 3)
assert isinstance(aff[0], Linear)
assert isinstance(aff[1], Bias)
assert isinstance(aff[2], Activation)
| [
"def",
"test_affine_wrapper",
"(",
"backend_default",
")",
":",
"nout",
"=",
"11",
"aff",
"=",
"Affine",
"(",
"nout",
",",
"Uniform",
"(",
")",
")",
"assert",
"isinstance",
"(",
"aff",
",",
"list",
")",
"assert",
"(",
"len",
"(",
"aff",
")",
"==",
"1",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"0",
"]",
",",
"Linear",
")",
"assert",
"(",
"aff",
"[",
"0",
"]",
".",
"nout",
"==",
"nout",
")",
"aff",
"=",
"Affine",
"(",
"nout",
",",
"Uniform",
"(",
")",
",",
"bias",
"=",
"Uniform",
"(",
")",
")",
"assert",
"isinstance",
"(",
"aff",
",",
"list",
")",
"assert",
"(",
"len",
"(",
"aff",
")",
"==",
"2",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"0",
"]",
",",
"Linear",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"1",
"]",
",",
"Bias",
")",
"aff",
"=",
"Affine",
"(",
"nout",
",",
"Uniform",
"(",
")",
",",
"activation",
"=",
"Rectlin",
"(",
")",
")",
"assert",
"isinstance",
"(",
"aff",
",",
"list",
")",
"assert",
"(",
"len",
"(",
"aff",
")",
"==",
"2",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"0",
"]",
",",
"Linear",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"1",
"]",
",",
"Activation",
")",
"aff",
"=",
"Affine",
"(",
"nout",
",",
"Uniform",
"(",
")",
",",
"bias",
"=",
"Uniform",
"(",
")",
",",
"activation",
"=",
"Rectlin",
"(",
")",
")",
"assert",
"isinstance",
"(",
"aff",
",",
"list",
")",
"assert",
"(",
"len",
"(",
"aff",
")",
"==",
"3",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"0",
"]",
",",
"Linear",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"1",
"]",
",",
"Bias",
")",
"assert",
"isinstance",
"(",
"aff",
"[",
"2",
"]",
",",
"Activation",
")"
] | verify that the affine wrapper constructs the right layer objects . | train | false |
14,859 | def gammainc(a, x, dps=50, maxterms=(10 ** 8)):
with mp.workdps(dps):
(z, a, b) = (mp.mpf(a), mp.mpf(x), mp.mpf(x))
G = [z]
negb = mp.fneg(b, exact=True)
def h(z):
T1 = ([mp.exp(negb), b, z], [1, z, (-1)], [], G, [1], [(1 + z)], b)
return (T1,)
res = mp.hypercomb(h, [z], maxterms=maxterms)
return mpf2float(res)
| [
"def",
"gammainc",
"(",
"a",
",",
"x",
",",
"dps",
"=",
"50",
",",
"maxterms",
"=",
"(",
"10",
"**",
"8",
")",
")",
":",
"with",
"mp",
".",
"workdps",
"(",
"dps",
")",
":",
"(",
"z",
",",
"a",
",",
"b",
")",
"=",
"(",
"mp",
".",
"mpf",
"(",
"a",
")",
",",
"mp",
".",
"mpf",
"(",
"x",
")",
",",
"mp",
".",
"mpf",
"(",
"x",
")",
")",
"G",
"=",
"[",
"z",
"]",
"negb",
"=",
"mp",
".",
"fneg",
"(",
"b",
",",
"exact",
"=",
"True",
")",
"def",
"h",
"(",
"z",
")",
":",
"T1",
"=",
"(",
"[",
"mp",
".",
"exp",
"(",
"negb",
")",
",",
"b",
",",
"z",
"]",
",",
"[",
"1",
",",
"z",
",",
"(",
"-",
"1",
")",
"]",
",",
"[",
"]",
",",
"G",
",",
"[",
"1",
"]",
",",
"[",
"(",
"1",
"+",
"z",
")",
"]",
",",
"b",
")",
"return",
"(",
"T1",
",",
")",
"res",
"=",
"mp",
".",
"hypercomb",
"(",
"h",
",",
"[",
"z",
"]",
",",
"maxterms",
"=",
"maxterms",
")",
"return",
"mpf2float",
"(",
"res",
")"
] | compute gammainc exactly like mpmath does but allow for more summands in hypercomb . | train | false |
14,860 | def _cleanup():
for inst in _ACTIVE[:]:
res = inst.isalive()
if (res is not True):
try:
_ACTIVE.remove(inst)
except ValueError:
pass
| [
"def",
"_cleanup",
"(",
")",
":",
"for",
"inst",
"in",
"_ACTIVE",
"[",
":",
"]",
":",
"res",
"=",
"inst",
".",
"isalive",
"(",
")",
"if",
"(",
"res",
"is",
"not",
"True",
")",
":",
"try",
":",
"_ACTIVE",
".",
"remove",
"(",
"inst",
")",
"except",
"ValueError",
":",
"pass"
] | make sure that any terminal processes still running when __del__ was called to the waited and cleaned up . | train | true |
14,861 | def get_pending_component_servicing():
vname = '(Default)'
key = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending'
reg_ret = __salt__['reg.read_value']('HKLM', key, vname)
if reg_ret['success']:
log.debug('Found key: %s', key)
return True
else:
log.debug('Unable to access key: %s', key)
return False
| [
"def",
"get_pending_component_servicing",
"(",
")",
":",
"vname",
"=",
"'(Default)'",
"key",
"=",
"'SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Component Based Servicing\\\\RebootPending'",
"reg_ret",
"=",
"__salt__",
"[",
"'reg.read_value'",
"]",
"(",
"'HKLM'",
",",
"key",
",",
"vname",
")",
"if",
"reg_ret",
"[",
"'success'",
"]",
":",
"log",
".",
"debug",
"(",
"'Found key: %s'",
",",
"key",
")",
"return",
"True",
"else",
":",
"log",
".",
"debug",
"(",
"'Unable to access key: %s'",
",",
"key",
")",
"return",
"False"
] | determine whether there are pending component based servicing tasks that require a reboot . | train | false |
14,862 | @view
def people(request):
data = {}
query = request.GET.get('q', '')
data['raw_query'] = query
parsed_query = mysite.profile.view_helpers.parse_string_query(query)
data.update(parsed_query)
if parsed_query['q'].strip():
search_results = parsed_query['callable_searcher']()
(everybody, extra_data) = (search_results.people, search_results.template_data)
data.update(extra_data)
data['people'] = everybody
person_id_ranges = mysite.base.view_helpers.int_list2ranges([x.id for x in data['people']])
person_ids = ''
for (stop, start) in person_id_ranges:
if (stop == start):
person_ids += ('%d,' % (stop,))
else:
person_ids += ('%d-%d,' % (stop, start))
else:
data = {}
return (request, 'profile/search_people.html', data)
| [
"@",
"view",
"def",
"people",
"(",
"request",
")",
":",
"data",
"=",
"{",
"}",
"query",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'q'",
",",
"''",
")",
"data",
"[",
"'raw_query'",
"]",
"=",
"query",
"parsed_query",
"=",
"mysite",
".",
"profile",
".",
"view_helpers",
".",
"parse_string_query",
"(",
"query",
")",
"data",
".",
"update",
"(",
"parsed_query",
")",
"if",
"parsed_query",
"[",
"'q'",
"]",
".",
"strip",
"(",
")",
":",
"search_results",
"=",
"parsed_query",
"[",
"'callable_searcher'",
"]",
"(",
")",
"(",
"everybody",
",",
"extra_data",
")",
"=",
"(",
"search_results",
".",
"people",
",",
"search_results",
".",
"template_data",
")",
"data",
".",
"update",
"(",
"extra_data",
")",
"data",
"[",
"'people'",
"]",
"=",
"everybody",
"person_id_ranges",
"=",
"mysite",
".",
"base",
".",
"view_helpers",
".",
"int_list2ranges",
"(",
"[",
"x",
".",
"id",
"for",
"x",
"in",
"data",
"[",
"'people'",
"]",
"]",
")",
"person_ids",
"=",
"''",
"for",
"(",
"stop",
",",
"start",
")",
"in",
"person_id_ranges",
":",
"if",
"(",
"stop",
"==",
"start",
")",
":",
"person_ids",
"+=",
"(",
"'%d,'",
"%",
"(",
"stop",
",",
")",
")",
"else",
":",
"person_ids",
"+=",
"(",
"'%d-%d,'",
"%",
"(",
"stop",
",",
"start",
")",
")",
"else",
":",
"data",
"=",
"{",
"}",
"return",
"(",
"request",
",",
"'profile/search_people.html'",
",",
"data",
")"
] | display a list of people . | train | false |
14,863 | @pytest.mark.integration
def test_scrolled_down_img(caret_tester):
caret_tester.js.load('position_caret/scrolled_down_img.html')
caret_tester.js.scroll_anchor('anchor')
caret_tester.check_scrolled()
caret_tester.check()
| [
"@",
"pytest",
".",
"mark",
".",
"integration",
"def",
"test_scrolled_down_img",
"(",
"caret_tester",
")",
":",
"caret_tester",
".",
"js",
".",
"load",
"(",
"'position_caret/scrolled_down_img.html'",
")",
"caret_tester",
".",
"js",
".",
"scroll_anchor",
"(",
"'anchor'",
")",
"caret_tester",
".",
"check_scrolled",
"(",
")",
"caret_tester",
".",
"check",
"(",
")"
] | test with an image at the top with the viewport scrolled down . | train | false |
14,864 | def ProcessGlobalSuppresions(lines):
for line in lines:
if _SEARCH_C_FILE.search(line):
for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
if _SEARCH_KERNEL_FILE.search(line):
for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
| [
"def",
"ProcessGlobalSuppresions",
"(",
"lines",
")",
":",
"for",
"line",
"in",
"lines",
":",
"if",
"_SEARCH_C_FILE",
".",
"search",
"(",
"line",
")",
":",
"for",
"category",
"in",
"_DEFAULT_C_SUPPRESSED_CATEGORIES",
":",
"_global_error_suppressions",
"[",
"category",
"]",
"=",
"True",
"if",
"_SEARCH_KERNEL_FILE",
".",
"search",
"(",
"line",
")",
":",
"for",
"category",
"in",
"_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES",
":",
"_global_error_suppressions",
"[",
"category",
"]",
"=",
"True"
] | updates the list of global error suppressions . | train | true |
14,866 | @click.command(u'set-admin-password')
@click.argument(u'admin-password')
@pass_context
def set_admin_password(context, admin_password):
import getpass
from frappe.utils.password import update_password
for site in context.sites:
try:
frappe.init(site=site)
while (not admin_password):
admin_password = getpass.getpass(u"Administrator's password for {0}: ".format(site))
frappe.connect()
update_password(u'Administrator', admin_password)
frappe.db.commit()
admin_password = None
finally:
frappe.destroy()
| [
"@",
"click",
".",
"command",
"(",
"u'set-admin-password'",
")",
"@",
"click",
".",
"argument",
"(",
"u'admin-password'",
")",
"@",
"pass_context",
"def",
"set_admin_password",
"(",
"context",
",",
"admin_password",
")",
":",
"import",
"getpass",
"from",
"frappe",
".",
"utils",
".",
"password",
"import",
"update_password",
"for",
"site",
"in",
"context",
".",
"sites",
":",
"try",
":",
"frappe",
".",
"init",
"(",
"site",
"=",
"site",
")",
"while",
"(",
"not",
"admin_password",
")",
":",
"admin_password",
"=",
"getpass",
".",
"getpass",
"(",
"u\"Administrator's password for {0}: \"",
".",
"format",
"(",
"site",
")",
")",
"frappe",
".",
"connect",
"(",
")",
"update_password",
"(",
"u'Administrator'",
",",
"admin_password",
")",
"frappe",
".",
"db",
".",
"commit",
"(",
")",
"admin_password",
"=",
"None",
"finally",
":",
"frappe",
".",
"destroy",
"(",
")"
] | set administrator password for a site . | train | false |
14,867 | def wait_for_server_termination(client, server_id, ignore_error=False):
start_time = int(time.time())
while True:
try:
body = client.show_server(server_id)['server']
except lib_exc.NotFound:
return
server_status = body['status']
if ((server_status == 'ERROR') and (not ignore_error)):
raise exceptions.BuildErrorException(server_id=server_id)
if ((int(time.time()) - start_time) >= client.build_timeout):
raise lib_exc.TimeoutException
time.sleep(client.build_interval)
| [
"def",
"wait_for_server_termination",
"(",
"client",
",",
"server_id",
",",
"ignore_error",
"=",
"False",
")",
":",
"start_time",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"while",
"True",
":",
"try",
":",
"body",
"=",
"client",
".",
"show_server",
"(",
"server_id",
")",
"[",
"'server'",
"]",
"except",
"lib_exc",
".",
"NotFound",
":",
"return",
"server_status",
"=",
"body",
"[",
"'status'",
"]",
"if",
"(",
"(",
"server_status",
"==",
"'ERROR'",
")",
"and",
"(",
"not",
"ignore_error",
")",
")",
":",
"raise",
"exceptions",
".",
"BuildErrorException",
"(",
"server_id",
"=",
"server_id",
")",
"if",
"(",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"-",
"start_time",
")",
">=",
"client",
".",
"build_timeout",
")",
":",
"raise",
"lib_exc",
".",
"TimeoutException",
"time",
".",
"sleep",
"(",
"client",
".",
"build_interval",
")"
] | waits for server to reach termination . | train | false |
14,868 | def check_addon_ownership(request, addon, viewer=False, dev=False, support=False, admin=True, ignore_disabled=False):
if (not request.user.is_authenticated()):
return False
if addon.is_deleted:
return False
if (admin and action_allowed(request, 'Addons', 'Edit')):
return True
if ((addon.status == amo.STATUS_DISABLED) and (not ignore_disabled)):
return False
roles = (amo.AUTHOR_ROLE_OWNER,)
if dev:
roles += (amo.AUTHOR_ROLE_DEV,)
elif viewer:
roles += (amo.AUTHOR_ROLE_DEV, amo.AUTHOR_ROLE_VIEWER, amo.AUTHOR_ROLE_SUPPORT)
elif support:
roles += (amo.AUTHOR_ROLE_SUPPORT,)
return addon.authors.filter(pk=request.user.pk, addonuser__role__in=roles).exists()
| [
"def",
"check_addon_ownership",
"(",
"request",
",",
"addon",
",",
"viewer",
"=",
"False",
",",
"dev",
"=",
"False",
",",
"support",
"=",
"False",
",",
"admin",
"=",
"True",
",",
"ignore_disabled",
"=",
"False",
")",
":",
"if",
"(",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
")",
":",
"return",
"False",
"if",
"addon",
".",
"is_deleted",
":",
"return",
"False",
"if",
"(",
"admin",
"and",
"action_allowed",
"(",
"request",
",",
"'Addons'",
",",
"'Edit'",
")",
")",
":",
"return",
"True",
"if",
"(",
"(",
"addon",
".",
"status",
"==",
"amo",
".",
"STATUS_DISABLED",
")",
"and",
"(",
"not",
"ignore_disabled",
")",
")",
":",
"return",
"False",
"roles",
"=",
"(",
"amo",
".",
"AUTHOR_ROLE_OWNER",
",",
")",
"if",
"dev",
":",
"roles",
"+=",
"(",
"amo",
".",
"AUTHOR_ROLE_DEV",
",",
")",
"elif",
"viewer",
":",
"roles",
"+=",
"(",
"amo",
".",
"AUTHOR_ROLE_DEV",
",",
"amo",
".",
"AUTHOR_ROLE_VIEWER",
",",
"amo",
".",
"AUTHOR_ROLE_SUPPORT",
")",
"elif",
"support",
":",
"roles",
"+=",
"(",
"amo",
".",
"AUTHOR_ROLE_SUPPORT",
",",
")",
"return",
"addon",
".",
"authors",
".",
"filter",
"(",
"pk",
"=",
"request",
".",
"user",
".",
"pk",
",",
"addonuser__role__in",
"=",
"roles",
")",
".",
"exists",
"(",
")"
] | check request . | train | false |
14,870 | def test_nearmiss_bad_ratio():
ratio = (-1.0)
nm1 = NearMiss(ratio=ratio, random_state=RND_SEED)
assert_raises(ValueError, nm1.fit, X, Y)
ratio = 100.0
nm1 = NearMiss(ratio=ratio, random_state=RND_SEED)
assert_raises(ValueError, nm1.fit, X, Y)
ratio = 'rnd'
nm1 = NearMiss(ratio=ratio, random_state=RND_SEED)
assert_raises(ValueError, nm1.fit, X, Y)
ratio = [0.5, 0.5]
nm1 = NearMiss(ratio=ratio, random_state=RND_SEED)
assert_raises(ValueError, nm1.fit, X, Y)
| [
"def",
"test_nearmiss_bad_ratio",
"(",
")",
":",
"ratio",
"=",
"(",
"-",
"1.0",
")",
"nm1",
"=",
"NearMiss",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"ValueError",
",",
"nm1",
".",
"fit",
",",
"X",
",",
"Y",
")",
"ratio",
"=",
"100.0",
"nm1",
"=",
"NearMiss",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"ValueError",
",",
"nm1",
".",
"fit",
",",
"X",
",",
"Y",
")",
"ratio",
"=",
"'rnd'",
"nm1",
"=",
"NearMiss",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"ValueError",
",",
"nm1",
".",
"fit",
",",
"X",
",",
"Y",
")",
"ratio",
"=",
"[",
"0.5",
",",
"0.5",
"]",
"nm1",
"=",
"NearMiss",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_raises",
"(",
"ValueError",
",",
"nm1",
".",
"fit",
",",
"X",
",",
"Y",
")"
] | test either if an error is raised with a wrong decimal value for the ratio . | train | false |
14,871 | def barabasi_albert_graph(n, m, seed=None):
if ((m < 1) or (m >= n)):
raise nx.NetworkXError(('Barab\xc3\xa1si\xe2\x80\x93Albert network must have m >= 1 and m < n, m = %d, n = %d' % (m, n)))
if (seed is not None):
random.seed(seed)
G = empty_graph(m)
G.name = ('barabasi_albert_graph(%s,%s)' % (n, m))
targets = list(range(m))
repeated_nodes = []
source = m
while (source < n):
G.add_edges_from(zip(([source] * m), targets))
repeated_nodes.extend(targets)
repeated_nodes.extend(([source] * m))
targets = _random_subset(repeated_nodes, m)
source += 1
return G
| [
"def",
"barabasi_albert_graph",
"(",
"n",
",",
"m",
",",
"seed",
"=",
"None",
")",
":",
"if",
"(",
"(",
"m",
"<",
"1",
")",
"or",
"(",
"m",
">=",
"n",
")",
")",
":",
"raise",
"nx",
".",
"NetworkXError",
"(",
"(",
"'Barab\\xc3\\xa1si\\xe2\\x80\\x93Albert network must have m >= 1 and m < n, m = %d, n = %d'",
"%",
"(",
"m",
",",
"n",
")",
")",
")",
"if",
"(",
"seed",
"is",
"not",
"None",
")",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"G",
"=",
"empty_graph",
"(",
"m",
")",
"G",
".",
"name",
"=",
"(",
"'barabasi_albert_graph(%s,%s)'",
"%",
"(",
"n",
",",
"m",
")",
")",
"targets",
"=",
"list",
"(",
"range",
"(",
"m",
")",
")",
"repeated_nodes",
"=",
"[",
"]",
"source",
"=",
"m",
"while",
"(",
"source",
"<",
"n",
")",
":",
"G",
".",
"add_edges_from",
"(",
"zip",
"(",
"(",
"[",
"source",
"]",
"*",
"m",
")",
",",
"targets",
")",
")",
"repeated_nodes",
".",
"extend",
"(",
"targets",
")",
"repeated_nodes",
".",
"extend",
"(",
"(",
"[",
"source",
"]",
"*",
"m",
")",
")",
"targets",
"=",
"_random_subset",
"(",
"repeated_nodes",
",",
"m",
")",
"source",
"+=",
"1",
"return",
"G"
] | returns a random graph according to the barabási–albert preferential attachment model . | train | false |
14,872 | def _collectWarnings(observeWarning, f, *args, **kwargs):
def showWarning(message, category, filename, lineno, file=None, line=None):
assert isinstance(message, Warning)
observeWarning(_Warning(message.args[0], category, filename, lineno))
for v in sys.modules.itervalues():
if (v is not None):
try:
v.__warningregistry__ = None
except:
pass
origFilters = warnings.filters[:]
origShow = warnings.showwarning
warnings.simplefilter('always')
try:
warnings.showwarning = showWarning
result = f(*args, **kwargs)
finally:
warnings.filters[:] = origFilters
warnings.showwarning = origShow
return result
| [
"def",
"_collectWarnings",
"(",
"observeWarning",
",",
"f",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"def",
"showWarning",
"(",
"message",
",",
"category",
",",
"filename",
",",
"lineno",
",",
"file",
"=",
"None",
",",
"line",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"message",
",",
"Warning",
")",
"observeWarning",
"(",
"_Warning",
"(",
"message",
".",
"args",
"[",
"0",
"]",
",",
"category",
",",
"filename",
",",
"lineno",
")",
")",
"for",
"v",
"in",
"sys",
".",
"modules",
".",
"itervalues",
"(",
")",
":",
"if",
"(",
"v",
"is",
"not",
"None",
")",
":",
"try",
":",
"v",
".",
"__warningregistry__",
"=",
"None",
"except",
":",
"pass",
"origFilters",
"=",
"warnings",
".",
"filters",
"[",
":",
"]",
"origShow",
"=",
"warnings",
".",
"showwarning",
"warnings",
".",
"simplefilter",
"(",
"'always'",
")",
"try",
":",
"warnings",
".",
"showwarning",
"=",
"showWarning",
"result",
"=",
"f",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"finally",
":",
"warnings",
".",
"filters",
"[",
":",
"]",
"=",
"origFilters",
"warnings",
".",
"showwarning",
"=",
"origShow",
"return",
"result"
] | call c{f} with c{args} positional arguments and c{kwargs} keyword arguments and collect all warnings which are emitted as a result in a list . | train | false |
14,876 | def check_equal_numpy(x, y):
if (isinstance(x, numpy.ndarray) and isinstance(y, numpy.ndarray)):
return ((x.dtype == y.dtype) and (x.shape == y.shape) and numpy.all((abs((x - y)) < 1e-10)))
elif (isinstance(x, numpy.random.RandomState) and isinstance(y, numpy.random.RandomState)):
return python_all((numpy.all((a == b)) for (a, b) in izip(x.__getstate__(), y.__getstate__())))
else:
return (x == y)
| [
"def",
"check_equal_numpy",
"(",
"x",
",",
"y",
")",
":",
"if",
"(",
"isinstance",
"(",
"x",
",",
"numpy",
".",
"ndarray",
")",
"and",
"isinstance",
"(",
"y",
",",
"numpy",
".",
"ndarray",
")",
")",
":",
"return",
"(",
"(",
"x",
".",
"dtype",
"==",
"y",
".",
"dtype",
")",
"and",
"(",
"x",
".",
"shape",
"==",
"y",
".",
"shape",
")",
"and",
"numpy",
".",
"all",
"(",
"(",
"abs",
"(",
"(",
"x",
"-",
"y",
")",
")",
"<",
"1e-10",
")",
")",
")",
"elif",
"(",
"isinstance",
"(",
"x",
",",
"numpy",
".",
"random",
".",
"RandomState",
")",
"and",
"isinstance",
"(",
"y",
",",
"numpy",
".",
"random",
".",
"RandomState",
")",
")",
":",
"return",
"python_all",
"(",
"(",
"numpy",
".",
"all",
"(",
"(",
"a",
"==",
"b",
")",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"izip",
"(",
"x",
".",
"__getstate__",
"(",
")",
",",
"y",
".",
"__getstate__",
"(",
")",
")",
")",
")",
"else",
":",
"return",
"(",
"x",
"==",
"y",
")"
] | return true iff x and y are equal . | train | false |
14,877 | @profiler.trace
def image_delete_properties(request, image_id, keys):
return glanceclient(request, '2').images.update(image_id, keys)
| [
"@",
"profiler",
".",
"trace",
"def",
"image_delete_properties",
"(",
"request",
",",
"image_id",
",",
"keys",
")",
":",
"return",
"glanceclient",
"(",
"request",
",",
"'2'",
")",
".",
"images",
".",
"update",
"(",
"image_id",
",",
"keys",
")"
] | delete custom properties for an image . | train | false |
14,878 | def enable_dns_cache():
om.out.debug('Enabling _dns_cache()')
if (not hasattr(socket, 'already_configured')):
socket._getaddrinfo = socket.getaddrinfo
_dns_cache = SynchronizedLRUDict(200)
def _caching_getaddrinfo(*args, **kwargs):
query = args
try:
res = _dns_cache[query]
return res
except KeyError:
res = socket._getaddrinfo(*args, **kwargs)
_dns_cache[args] = res
msg = 'DNS response from DNS server for domain: %s'
om.out.debug((msg % query[0]))
return res
if (not hasattr(socket, 'already_configured')):
socket.getaddrinfo = _caching_getaddrinfo
socket.already_configured = True
| [
"def",
"enable_dns_cache",
"(",
")",
":",
"om",
".",
"out",
".",
"debug",
"(",
"'Enabling _dns_cache()'",
")",
"if",
"(",
"not",
"hasattr",
"(",
"socket",
",",
"'already_configured'",
")",
")",
":",
"socket",
".",
"_getaddrinfo",
"=",
"socket",
".",
"getaddrinfo",
"_dns_cache",
"=",
"SynchronizedLRUDict",
"(",
"200",
")",
"def",
"_caching_getaddrinfo",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"query",
"=",
"args",
"try",
":",
"res",
"=",
"_dns_cache",
"[",
"query",
"]",
"return",
"res",
"except",
"KeyError",
":",
"res",
"=",
"socket",
".",
"_getaddrinfo",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"_dns_cache",
"[",
"args",
"]",
"=",
"res",
"msg",
"=",
"'DNS response from DNS server for domain: %s'",
"om",
".",
"out",
".",
"debug",
"(",
"(",
"msg",
"%",
"query",
"[",
"0",
"]",
")",
")",
"return",
"res",
"if",
"(",
"not",
"hasattr",
"(",
"socket",
",",
"'already_configured'",
")",
")",
":",
"socket",
".",
"getaddrinfo",
"=",
"_caching_getaddrinfo",
"socket",
".",
"already_configured",
"=",
"True"
] | dns cache trick this will speed up all the test! before this dns cache voodoo magic every request to the http server required a dns query . | train | false |
14,881 | @_docstring('url')
def get_url_by_id(id, includes=[]):
return _do_mb_query('url', id, includes)
| [
"@",
"_docstring",
"(",
"'url'",
")",
"def",
"get_url_by_id",
"(",
"id",
",",
"includes",
"=",
"[",
"]",
")",
":",
"return",
"_do_mb_query",
"(",
"'url'",
",",
"id",
",",
"includes",
")"
] | get the url with the musicbrainz id as a dict with a url key . | train | false |
14,882 | def file_ns_handler(importer, path_item, packageName, module):
subpath = os.path.join(path_item, packageName.split('.')[(-1)])
normalized = _normalize_cached(subpath)
for item in module.__path__:
if (_normalize_cached(item) == normalized):
break
else:
return subpath
| [
"def",
"file_ns_handler",
"(",
"importer",
",",
"path_item",
",",
"packageName",
",",
"module",
")",
":",
"subpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"packageName",
".",
"split",
"(",
"'.'",
")",
"[",
"(",
"-",
"1",
")",
"]",
")",
"normalized",
"=",
"_normalize_cached",
"(",
"subpath",
")",
"for",
"item",
"in",
"module",
".",
"__path__",
":",
"if",
"(",
"_normalize_cached",
"(",
"item",
")",
"==",
"normalized",
")",
":",
"break",
"else",
":",
"return",
"subpath"
] | compute an ns-package subpath for a filesystem or zipfile importer . | train | true |
14,883 | def _find_unpurge_targets(desired):
return [x for x in desired if (x in __salt__['pkg.list_pkgs'](purge_desired=True))]
| [
"def",
"_find_unpurge_targets",
"(",
"desired",
")",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"desired",
"if",
"(",
"x",
"in",
"__salt__",
"[",
"'pkg.list_pkgs'",
"]",
"(",
"purge_desired",
"=",
"True",
")",
")",
"]"
] | find packages which are marked to be purged but cant yet be removed because they are dependencies for other installed packages . | train | true |
14,884 | def already_listening(port, renewer=False):
if USE_PSUTIL:
return already_listening_psutil(port, renewer=renewer)
else:
logger.debug('Psutil not found, using simple socket check.')
return already_listening_socket(port, renewer=renewer)
| [
"def",
"already_listening",
"(",
"port",
",",
"renewer",
"=",
"False",
")",
":",
"if",
"USE_PSUTIL",
":",
"return",
"already_listening_psutil",
"(",
"port",
",",
"renewer",
"=",
"renewer",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"'Psutil not found, using simple socket check.'",
")",
"return",
"already_listening_socket",
"(",
"port",
",",
"renewer",
"=",
"renewer",
")"
] | check if a process is already listening on the port . | train | false |
14,885 | def generate_paragraph(start_with_lorem=False):
return _GENERATOR.generate_paragraph(start_with_lorem)
| [
"def",
"generate_paragraph",
"(",
"start_with_lorem",
"=",
"False",
")",
":",
"return",
"_GENERATOR",
".",
"generate_paragraph",
"(",
"start_with_lorem",
")"
] | utility function to generate a single random paragraph with stats . | train | false |
14,886 | def get_default_pyspark_file():
current_dir = os.path.dirname(os.path.abspath(__file__))
f = open(os.path.join(current_dir, DEFAULT_FILENAME), 'r')
return (f, DEFAULT_FILENAME)
| [
"def",
"get_default_pyspark_file",
"(",
")",
":",
"current_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"f",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"current_dir",
",",
"DEFAULT_FILENAME",
")",
",",
"'r'",
")",
"return",
"(",
"f",
",",
"DEFAULT_FILENAME",
")"
] | gets the pyspark file from this directory . | train | false |
14,887 | def toxcmd_main(args=None):
usage = 'USAGE: %(prog)s [OPTIONS] COMMAND args...'
if (args is None):
args = sys.argv[1:]
parser = argparse.ArgumentParser(description=inspect.getdoc(toxcmd_main), formatter_class=FORMATTER_CLASS)
common_parser = parser.add_argument_group('Common options')
common_parser.add_argument('--version', action='version', version=VERSION)
subparsers = parser.add_subparsers(help='commands')
for command in discover_commands():
command_parser = subparsers.add_parser(command.name, usage=command.usage, description=command.description, help=command.short_description, formatter_class=FORMATTER_CLASS)
command_parser.set_defaults(func=command)
command.setup_parser(command_parser)
command.parser = command_parser
options = parser.parse_args(args)
command_function = options.func
return command_function(options)
| [
"def",
"toxcmd_main",
"(",
"args",
"=",
"None",
")",
":",
"usage",
"=",
"'USAGE: %(prog)s [OPTIONS] COMMAND args...'",
"if",
"(",
"args",
"is",
"None",
")",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"inspect",
".",
"getdoc",
"(",
"toxcmd_main",
")",
",",
"formatter_class",
"=",
"FORMATTER_CLASS",
")",
"common_parser",
"=",
"parser",
".",
"add_argument_group",
"(",
"'Common options'",
")",
"common_parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"VERSION",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"help",
"=",
"'commands'",
")",
"for",
"command",
"in",
"discover_commands",
"(",
")",
":",
"command_parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"command",
".",
"name",
",",
"usage",
"=",
"command",
".",
"usage",
",",
"description",
"=",
"command",
".",
"description",
",",
"help",
"=",
"command",
".",
"short_description",
",",
"formatter_class",
"=",
"FORMATTER_CLASS",
")",
"command_parser",
".",
"set_defaults",
"(",
"func",
"=",
"command",
")",
"command",
".",
"setup_parser",
"(",
"command_parser",
")",
"command",
".",
"parser",
"=",
"command_parser",
"options",
"=",
"parser",
".",
"parse_args",
"(",
"args",
")",
"command_function",
"=",
"options",
".",
"func",
"return",
"command_function",
"(",
"options",
")"
] | command util with subcommands for tox environments . | train | true |
14,888 | def _is_datastore_valid(propdict, datastore_regex, ds_types):
return (propdict.get('summary.accessible') and ((propdict.get('summary.maintenanceMode') is None) or (propdict.get('summary.maintenanceMode') == 'normal')) and (propdict['summary.type'] in ds_types) and ((datastore_regex is None) or datastore_regex.match(propdict['summary.name'])))
| [
"def",
"_is_datastore_valid",
"(",
"propdict",
",",
"datastore_regex",
",",
"ds_types",
")",
":",
"return",
"(",
"propdict",
".",
"get",
"(",
"'summary.accessible'",
")",
"and",
"(",
"(",
"propdict",
".",
"get",
"(",
"'summary.maintenanceMode'",
")",
"is",
"None",
")",
"or",
"(",
"propdict",
".",
"get",
"(",
"'summary.maintenanceMode'",
")",
"==",
"'normal'",
")",
")",
"and",
"(",
"propdict",
"[",
"'summary.type'",
"]",
"in",
"ds_types",
")",
"and",
"(",
"(",
"datastore_regex",
"is",
"None",
")",
"or",
"datastore_regex",
".",
"match",
"(",
"propdict",
"[",
"'summary.name'",
"]",
")",
")",
")"
] | checks if a datastore is valid based on the following criteria . | train | false |
14,889 | def read_label_file(dataset_dir, filename=LABELS_FILENAME):
labels_filename = os.path.join(dataset_dir, filename)
with tf.gfile.Open(labels_filename, 'r') as f:
lines = f.read().decode()
lines = lines.split('\n')
lines = filter(None, lines)
labels_to_class_names = {}
for line in lines:
index = line.index(':')
labels_to_class_names[int(line[:index])] = line[(index + 1):]
return labels_to_class_names
| [
"def",
"read_label_file",
"(",
"dataset_dir",
",",
"filename",
"=",
"LABELS_FILENAME",
")",
":",
"labels_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataset_dir",
",",
"filename",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"labels_filename",
",",
"'r'",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
")",
"lines",
"=",
"lines",
".",
"split",
"(",
"'\\n'",
")",
"lines",
"=",
"filter",
"(",
"None",
",",
"lines",
")",
"labels_to_class_names",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"index",
"=",
"line",
".",
"index",
"(",
"':'",
")",
"labels_to_class_names",
"[",
"int",
"(",
"line",
"[",
":",
"index",
"]",
")",
"]",
"=",
"line",
"[",
"(",
"index",
"+",
"1",
")",
":",
"]",
"return",
"labels_to_class_names"
] | reads the labels file and returns a mapping from id to class name . | train | false |
14,890 | def test_random_sample_repeated_computation():
a = db.from_sequence(range(50), npartitions=5)
b = a.random_sample(0.2)
assert (list(b) == list(b))
| [
"def",
"test_random_sample_repeated_computation",
"(",
")",
":",
"a",
"=",
"db",
".",
"from_sequence",
"(",
"range",
"(",
"50",
")",
",",
"npartitions",
"=",
"5",
")",
"b",
"=",
"a",
".",
"random_sample",
"(",
"0.2",
")",
"assert",
"(",
"list",
"(",
"b",
")",
"==",
"list",
"(",
"b",
")",
")"
] | repeated computation of a defined random sampling operation generates identical results . | train | false |
14,892 | def ishold():
return gca().ishold()
| [
"def",
"ishold",
"(",
")",
":",
"return",
"gca",
"(",
")",
".",
"ishold",
"(",
")"
] | return the hold status of the current axes . | train | false |
14,894 | def _intersect_1d(breaks):
start = 0
last_end = 0
old_idx = 0
ret = []
ret_next = []
for idx in range(1, len(breaks)):
(label, br) = breaks[idx]
(last_label, last_br) = breaks[(idx - 1)]
if (last_label == 'n'):
if ret_next:
ret.append(ret_next)
ret_next = []
if (last_label == 'o'):
start = 0
else:
start = last_end
end = ((br - last_br) + start)
last_end = end
if (br == last_br):
continue
ret_next.append((old_idx, slice(start, end)))
if (label == 'o'):
old_idx += 1
start = 0
if ret_next:
ret.append(ret_next)
return ret
| [
"def",
"_intersect_1d",
"(",
"breaks",
")",
":",
"start",
"=",
"0",
"last_end",
"=",
"0",
"old_idx",
"=",
"0",
"ret",
"=",
"[",
"]",
"ret_next",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"breaks",
")",
")",
":",
"(",
"label",
",",
"br",
")",
"=",
"breaks",
"[",
"idx",
"]",
"(",
"last_label",
",",
"last_br",
")",
"=",
"breaks",
"[",
"(",
"idx",
"-",
"1",
")",
"]",
"if",
"(",
"last_label",
"==",
"'n'",
")",
":",
"if",
"ret_next",
":",
"ret",
".",
"append",
"(",
"ret_next",
")",
"ret_next",
"=",
"[",
"]",
"if",
"(",
"last_label",
"==",
"'o'",
")",
":",
"start",
"=",
"0",
"else",
":",
"start",
"=",
"last_end",
"end",
"=",
"(",
"(",
"br",
"-",
"last_br",
")",
"+",
"start",
")",
"last_end",
"=",
"end",
"if",
"(",
"br",
"==",
"last_br",
")",
":",
"continue",
"ret_next",
".",
"append",
"(",
"(",
"old_idx",
",",
"slice",
"(",
"start",
",",
"end",
")",
")",
")",
"if",
"(",
"label",
"==",
"'o'",
")",
":",
"old_idx",
"+=",
"1",
"start",
"=",
"0",
"if",
"ret_next",
":",
"ret",
".",
"append",
"(",
"ret_next",
")",
"return",
"ret"
] | internal utility to intersect chunks for 1d after preprocessing . | train | false |
14,898 | def s_qword(value, endian='<', format='binary', signed=False, full_range=False, fuzzable=True, name=None):
qword = primitives.qword(value, endian, format, signed, full_range, fuzzable, name)
blocks.CURRENT.push(qword)
| [
"def",
"s_qword",
"(",
"value",
",",
"endian",
"=",
"'<'",
",",
"format",
"=",
"'binary'",
",",
"signed",
"=",
"False",
",",
"full_range",
"=",
"False",
",",
"fuzzable",
"=",
"True",
",",
"name",
"=",
"None",
")",
":",
"qword",
"=",
"primitives",
".",
"qword",
"(",
"value",
",",
"endian",
",",
"format",
",",
"signed",
",",
"full_range",
",",
"fuzzable",
",",
"name",
")",
"blocks",
".",
"CURRENT",
".",
"push",
"(",
"qword",
")"
] | push a quad word onto the current block stack . | train | false |
14,899 | def fmt_text(text):
PRINTABLE_CHAR = set((list(range(ord(u' '), (ord(u'~') + 1))) + [ord(u'\r'), ord(u'\n')]))
newtext = ((u'\\x{:02X}'.format(c) if (c not in PRINTABLE_CHAR) else chr(c)) for c in text)
textlines = u'\r\n'.join((l.strip(u'\r') for l in u''.join(newtext).split(u'\n')))
return textlines
| [
"def",
"fmt_text",
"(",
"text",
")",
":",
"PRINTABLE_CHAR",
"=",
"set",
"(",
"(",
"list",
"(",
"range",
"(",
"ord",
"(",
"u' '",
")",
",",
"(",
"ord",
"(",
"u'~'",
")",
"+",
"1",
")",
")",
")",
"+",
"[",
"ord",
"(",
"u'\\r'",
")",
",",
"ord",
"(",
"u'\\n'",
")",
"]",
")",
")",
"newtext",
"=",
"(",
"(",
"u'\\\\x{:02X}'",
".",
"format",
"(",
"c",
")",
"if",
"(",
"c",
"not",
"in",
"PRINTABLE_CHAR",
")",
"else",
"chr",
"(",
"c",
")",
")",
"for",
"c",
"in",
"text",
")",
"textlines",
"=",
"u'\\r\\n'",
".",
"join",
"(",
"(",
"l",
".",
"strip",
"(",
"u'\\r'",
")",
"for",
"l",
"in",
"u''",
".",
"join",
"(",
"newtext",
")",
".",
"split",
"(",
"u'\\n'",
")",
")",
")",
"return",
"textlines"
] | convert characters that arent printable to hex format . | train | false |
14,900 | def gf_csolve(f, n):
from sympy.polys.domains import ZZ
P = factorint(n)
X = [csolve_prime(f, p, e) for (p, e) in P.items()]
pools = list(map(tuple, X))
perms = [[]]
for pool in pools:
perms = [(x + [y]) for x in perms for y in pool]
dist_factors = [pow(p, e) for (p, e) in P.items()]
return sorted([gf_crt(per, dist_factors, ZZ) for per in perms])
| [
"def",
"gf_csolve",
"(",
"f",
",",
"n",
")",
":",
"from",
"sympy",
".",
"polys",
".",
"domains",
"import",
"ZZ",
"P",
"=",
"factorint",
"(",
"n",
")",
"X",
"=",
"[",
"csolve_prime",
"(",
"f",
",",
"p",
",",
"e",
")",
"for",
"(",
"p",
",",
"e",
")",
"in",
"P",
".",
"items",
"(",
")",
"]",
"pools",
"=",
"list",
"(",
"map",
"(",
"tuple",
",",
"X",
")",
")",
"perms",
"=",
"[",
"[",
"]",
"]",
"for",
"pool",
"in",
"pools",
":",
"perms",
"=",
"[",
"(",
"x",
"+",
"[",
"y",
"]",
")",
"for",
"x",
"in",
"perms",
"for",
"y",
"in",
"pool",
"]",
"dist_factors",
"=",
"[",
"pow",
"(",
"p",
",",
"e",
")",
"for",
"(",
"p",
",",
"e",
")",
"in",
"P",
".",
"items",
"(",
")",
"]",
"return",
"sorted",
"(",
"[",
"gf_crt",
"(",
"per",
",",
"dist_factors",
",",
"ZZ",
")",
"for",
"per",
"in",
"perms",
"]",
")"
] | to solve f(x) congruent 0 mod(n) . | train | false |
14,901 | def rlimitTestAndSet(name, limit):
(soft, hard) = getrlimit(name)
if (soft < limit):
hardLimit = (hard if (limit < hard) else limit)
setrlimit(name, (limit, hardLimit))
| [
"def",
"rlimitTestAndSet",
"(",
"name",
",",
"limit",
")",
":",
"(",
"soft",
",",
"hard",
")",
"=",
"getrlimit",
"(",
"name",
")",
"if",
"(",
"soft",
"<",
"limit",
")",
":",
"hardLimit",
"=",
"(",
"hard",
"if",
"(",
"limit",
"<",
"hard",
")",
"else",
"limit",
")",
"setrlimit",
"(",
"name",
",",
"(",
"limit",
",",
"hardLimit",
")",
")"
] | helper function to set rlimits . | train | false |
14,902 | def DEFINE_bytes(name, default, help):
CONFIG.AddOption(type_info.Bytes(name=name, default=(default or ''), description=help))
| [
"def",
"DEFINE_bytes",
"(",
"name",
",",
"default",
",",
"help",
")",
":",
"CONFIG",
".",
"AddOption",
"(",
"type_info",
".",
"Bytes",
"(",
"name",
"=",
"name",
",",
"default",
"=",
"(",
"default",
"or",
"''",
")",
",",
"description",
"=",
"help",
")",
")"
] | a helper for defining bytes options . | train | false |
14,905 | def get_log_dir(env=None):
if (env is None):
env = os.environ
if (ROS_LOG_DIR in env):
return env[ROS_LOG_DIR]
else:
return os.path.join(get_ros_home(env), 'log')
| [
"def",
"get_log_dir",
"(",
"env",
"=",
"None",
")",
":",
"if",
"(",
"env",
"is",
"None",
")",
":",
"env",
"=",
"os",
".",
"environ",
"if",
"(",
"ROS_LOG_DIR",
"in",
"env",
")",
":",
"return",
"env",
"[",
"ROS_LOG_DIR",
"]",
"else",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"get_ros_home",
"(",
"env",
")",
",",
"'log'",
")"
] | get directory to use for writing log files . | train | false |
14,906 | def s_block_end(name=None):
blocks.CURRENT.pop()
| [
"def",
"s_block_end",
"(",
"name",
"=",
"None",
")",
":",
"blocks",
".",
"CURRENT",
".",
"pop",
"(",
")"
] | close the last opened block . | train | false |
14,907 | def _get_switch_str(opt):
if ((opt[2] is None) or (opt[2] is True) or (opt[2] is False)):
default = ''
else:
default = '[VAL]'
if opt[0]:
return ('-%s, --%s %s' % (opt[0], opt[1], default))
else:
return ('--%s %s' % (opt[1], default))
| [
"def",
"_get_switch_str",
"(",
"opt",
")",
":",
"if",
"(",
"(",
"opt",
"[",
"2",
"]",
"is",
"None",
")",
"or",
"(",
"opt",
"[",
"2",
"]",
"is",
"True",
")",
"or",
"(",
"opt",
"[",
"2",
"]",
"is",
"False",
")",
")",
":",
"default",
"=",
"''",
"else",
":",
"default",
"=",
"'[VAL]'",
"if",
"opt",
"[",
"0",
"]",
":",
"return",
"(",
"'-%s, --%s %s'",
"%",
"(",
"opt",
"[",
"0",
"]",
",",
"opt",
"[",
"1",
"]",
",",
"default",
")",
")",
"else",
":",
"return",
"(",
"'--%s %s'",
"%",
"(",
"opt",
"[",
"1",
"]",
",",
"default",
")",
")"
] | output just the -r . | train | false |
14,908 | def fateman_poly_F_2(n):
Y = [Symbol(('y_' + str(i))) for i in range(0, (n + 1))]
y_0 = Y[0]
u = Add(*[y for y in Y[1:]])
H = Poly((((y_0 + u) + 1) ** 2), *Y)
F = Poly((((y_0 - u) - 2) ** 2), *Y)
G = Poly((((y_0 + u) + 2) ** 2), *Y)
return ((H * F), (H * G), H)
| [
"def",
"fateman_poly_F_2",
"(",
"n",
")",
":",
"Y",
"=",
"[",
"Symbol",
"(",
"(",
"'y_'",
"+",
"str",
"(",
"i",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"(",
"n",
"+",
"1",
")",
")",
"]",
"y_0",
"=",
"Y",
"[",
"0",
"]",
"u",
"=",
"Add",
"(",
"*",
"[",
"y",
"for",
"y",
"in",
"Y",
"[",
"1",
":",
"]",
"]",
")",
"H",
"=",
"Poly",
"(",
"(",
"(",
"(",
"y_0",
"+",
"u",
")",
"+",
"1",
")",
"**",
"2",
")",
",",
"*",
"Y",
")",
"F",
"=",
"Poly",
"(",
"(",
"(",
"(",
"y_0",
"-",
"u",
")",
"-",
"2",
")",
"**",
"2",
")",
",",
"*",
"Y",
")",
"G",
"=",
"Poly",
"(",
"(",
"(",
"(",
"y_0",
"+",
"u",
")",
"+",
"2",
")",
"**",
"2",
")",
",",
"*",
"Y",
")",
"return",
"(",
"(",
"H",
"*",
"F",
")",
",",
"(",
"H",
"*",
"G",
")",
",",
"H",
")"
] | fatemans gcd benchmark: linearly dense quartic inputs . | train | false |
14,909 | def one_to_index(s):
return d1_to_index[s]
| [
"def",
"one_to_index",
"(",
"s",
")",
":",
"return",
"d1_to_index",
"[",
"s",
"]"
] | one letter code to index . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.