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 |
|---|---|---|---|---|---|
22,289 | def dump_crypto_meta(crypto_meta):
def b64_encode_meta(crypto_meta):
return {name: (base64.b64encode(value).decode() if (name in ('iv', 'key')) else (b64_encode_meta(value) if isinstance(value, dict) else value)) for (name, value) in crypto_meta.items()}
return urlparse.quote_plus(json.dumps(b64_encode_meta(crypto_meta), sort_keys=True))
| [
"def",
"dump_crypto_meta",
"(",
"crypto_meta",
")",
":",
"def",
"b64_encode_meta",
"(",
"crypto_meta",
")",
":",
"return",
"{",
"name",
":",
"(",
"base64",
".",
"b64encode",
"(",
"value",
")",
".",
"decode",
"(",
")",
"if",
"(",
"name",
"in",
"(",
"'iv'",
",",
"'key'",
")",
")",
"else",
"(",
"b64_encode_meta",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"else",
"value",
")",
")",
"for",
"(",
"name",
",",
"value",
")",
"in",
"crypto_meta",
".",
"items",
"(",
")",
"}",
"return",
"urlparse",
".",
"quote_plus",
"(",
"json",
".",
"dumps",
"(",
"b64_encode_meta",
"(",
"crypto_meta",
")",
",",
"sort_keys",
"=",
"True",
")",
")"
] | serialize crypto meta to a form suitable for including in a header value . | train | false |
22,290 | def pusher(url, count, size, poll, copy):
ctx = zmq.Context()
s = ctx.socket(zmq.PUSH)
if poll:
p = zmq.Poller()
p.register(s)
s.connect(url)
msg = zmq.Message((' ' * size))
block = (zmq.NOBLOCK if poll else 0)
for i in range(count):
if poll:
res = p.poll()
assert (res[0][1] & zmq.POLLOUT)
s.send(msg, block, copy=copy)
s.close()
ctx.term()
| [
"def",
"pusher",
"(",
"url",
",",
"count",
",",
"size",
",",
"poll",
",",
"copy",
")",
":",
"ctx",
"=",
"zmq",
".",
"Context",
"(",
")",
"s",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"PUSH",
")",
"if",
"poll",
":",
"p",
"=",
"zmq",
".",
"Poller",
"(",
")",
"p",
".",
"register",
"(",
"s",
")",
"s",
".",
"connect",
"(",
"url",
")",
"msg",
"=",
"zmq",
".",
"Message",
"(",
"(",
"' '",
"*",
"size",
")",
")",
"block",
"=",
"(",
"zmq",
".",
"NOBLOCK",
"if",
"poll",
"else",
"0",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"if",
"poll",
":",
"res",
"=",
"p",
".",
"poll",
"(",
")",
"assert",
"(",
"res",
"[",
"0",
"]",
"[",
"1",
"]",
"&",
"zmq",
".",
"POLLOUT",
")",
"s",
".",
"send",
"(",
"msg",
",",
"block",
",",
"copy",
"=",
"copy",
")",
"s",
".",
"close",
"(",
")",
"ctx",
".",
"term",
"(",
")"
] | send a bunch of messages on a push socket . | train | false |
22,291 | def unregister_trophy(trophy):
warnings.warn(u'unregister_trophy() is deprecated. Please use reviewboard.accounts.trophies:trophies_registry.unregister() instead.', DeprecationWarning)
if (not issubclass(trophy, TrophyType)):
raise TypeError(u'Only TrophyType subclasses can be unregistered')
try:
trophies_registry.unregister(trophy)
except ItemLookupError as e:
raise ValueError(six.text_type(e))
| [
"def",
"unregister_trophy",
"(",
"trophy",
")",
":",
"warnings",
".",
"warn",
"(",
"u'unregister_trophy() is deprecated. Please use reviewboard.accounts.trophies:trophies_registry.unregister() instead.'",
",",
"DeprecationWarning",
")",
"if",
"(",
"not",
"issubclass",
"(",
"trophy",
",",
"TrophyType",
")",
")",
":",
"raise",
"TypeError",
"(",
"u'Only TrophyType subclasses can be unregistered'",
")",
"try",
":",
"trophies_registry",
".",
"unregister",
"(",
"trophy",
")",
"except",
"ItemLookupError",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"six",
".",
"text_type",
"(",
"e",
")",
")"
] | unregister a trophytype subclass . | train | false |
22,292 | def _check_rbenv(ret, user=None):
if (not __salt__['rbenv.is_installed'](user)):
ret['result'] = False
ret['comment'] = 'Rbenv is not installed.'
return ret
| [
"def",
"_check_rbenv",
"(",
"ret",
",",
"user",
"=",
"None",
")",
":",
"if",
"(",
"not",
"__salt__",
"[",
"'rbenv.is_installed'",
"]",
"(",
"user",
")",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'comment'",
"]",
"=",
"'Rbenv is not installed.'",
"return",
"ret"
] | check to see if rbenv is installed . | train | false |
22,293 | def partial_check_positive_definite(C):
if (C.ndim == 1):
d = C
else:
d = np.diag(C)
(i,) = np.nonzero(np.logical_or(np.isnan(d), (d <= 0)))
if len(i):
raise PositiveDefiniteError('Simple check failed. Diagonal contains negatives', i)
| [
"def",
"partial_check_positive_definite",
"(",
"C",
")",
":",
"if",
"(",
"C",
".",
"ndim",
"==",
"1",
")",
":",
"d",
"=",
"C",
"else",
":",
"d",
"=",
"np",
".",
"diag",
"(",
"C",
")",
"(",
"i",
",",
")",
"=",
"np",
".",
"nonzero",
"(",
"np",
".",
"logical_or",
"(",
"np",
".",
"isnan",
"(",
"d",
")",
",",
"(",
"d",
"<=",
"0",
")",
")",
")",
"if",
"len",
"(",
"i",
")",
":",
"raise",
"PositiveDefiniteError",
"(",
"'Simple check failed. Diagonal contains negatives'",
",",
"i",
")"
] | simple but partial check for positive definiteness . | train | false |
22,294 | def rand_str(size=9999999999, hash_type=None):
if (not hash_type):
hash_type = 'md5'
hasher = getattr(hashlib, hash_type)
return hasher(to_bytes(str(random.SystemRandom().randint(0, size)))).hexdigest()
| [
"def",
"rand_str",
"(",
"size",
"=",
"9999999999",
",",
"hash_type",
"=",
"None",
")",
":",
"if",
"(",
"not",
"hash_type",
")",
":",
"hash_type",
"=",
"'md5'",
"hasher",
"=",
"getattr",
"(",
"hashlib",
",",
"hash_type",
")",
"return",
"hasher",
"(",
"to_bytes",
"(",
"str",
"(",
"random",
".",
"SystemRandom",
"(",
")",
".",
"randint",
"(",
"0",
",",
"size",
")",
")",
")",
")",
".",
"hexdigest",
"(",
")"
] | return a random string size size of the string to generate hash_type hash type to use . | train | false |
22,295 | def test_read():
django_conf.settings.TOP_SECRET = 1234
assert (assets_conf.settings.TOP_SECRET == 1234)
django_conf.settings.TOP_SECRET = 'helloworld'
assert (assets_conf.settings.TOP_SECRET == 'helloworld')
| [
"def",
"test_read",
"(",
")",
":",
"django_conf",
".",
"settings",
".",
"TOP_SECRET",
"=",
"1234",
"assert",
"(",
"assets_conf",
".",
"settings",
".",
"TOP_SECRET",
"==",
"1234",
")",
"django_conf",
".",
"settings",
".",
"TOP_SECRET",
"=",
"'helloworld'",
"assert",
"(",
"assets_conf",
".",
"settings",
".",
"TOP_SECRET",
"==",
"'helloworld'",
")"
] | test that we can read djangos own config values from our own settings object . | train | false |
22,296 | @with_session
def reset_schema(plugin, session=None):
if (plugin not in plugin_schemas):
raise ValueError((u'The plugin %s has no stored schema to reset.' % plugin))
table_names = plugin_schemas[plugin].get(u'tables', [])
tables = [table_schema(name, session) for name in table_names]
for table in tables:
try:
table.drop()
except OperationalError as e:
if (u'no such table' in str(e)):
continue
raise e
session.query(PluginSchema).filter((PluginSchema.plugin == plugin)).delete()
session.commit()
Base.metadata.create_all(bind=session.bind)
| [
"@",
"with_session",
"def",
"reset_schema",
"(",
"plugin",
",",
"session",
"=",
"None",
")",
":",
"if",
"(",
"plugin",
"not",
"in",
"plugin_schemas",
")",
":",
"raise",
"ValueError",
"(",
"(",
"u'The plugin %s has no stored schema to reset.'",
"%",
"plugin",
")",
")",
"table_names",
"=",
"plugin_schemas",
"[",
"plugin",
"]",
".",
"get",
"(",
"u'tables'",
",",
"[",
"]",
")",
"tables",
"=",
"[",
"table_schema",
"(",
"name",
",",
"session",
")",
"for",
"name",
"in",
"table_names",
"]",
"for",
"table",
"in",
"tables",
":",
"try",
":",
"table",
".",
"drop",
"(",
")",
"except",
"OperationalError",
"as",
"e",
":",
"if",
"(",
"u'no such table'",
"in",
"str",
"(",
"e",
")",
")",
":",
"continue",
"raise",
"e",
"session",
".",
"query",
"(",
"PluginSchema",
")",
".",
"filter",
"(",
"(",
"PluginSchema",
".",
"plugin",
"==",
"plugin",
")",
")",
".",
"delete",
"(",
")",
"session",
".",
"commit",
"(",
")",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"bind",
"=",
"session",
".",
"bind",
")"
] | removes all tables from given plugin from the database . | train | false |
22,297 | def toUTF8(s):
return s
| [
"def",
"toUTF8",
"(",
"s",
")",
":",
"return",
"s"
] | for some strange reason . | train | false |
22,298 | def CHECK_EXTRACT_CMD(state, package_tarball_paths):
if (not package_tarball_paths):
return
def extracted_size(tarball_path):
with tarfile.open(tarball_path) as tar_bz2:
return reduce(add, (m.size for m in tar_bz2.getmembers()), 0)
size = reduce(add, (extracted_size(dist) for dist in package_tarball_paths), 0)
prefix = state['prefix']
assert isdir(prefix)
check_size(prefix, size)
| [
"def",
"CHECK_EXTRACT_CMD",
"(",
"state",
",",
"package_tarball_paths",
")",
":",
"if",
"(",
"not",
"package_tarball_paths",
")",
":",
"return",
"def",
"extracted_size",
"(",
"tarball_path",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"tarball_path",
")",
"as",
"tar_bz2",
":",
"return",
"reduce",
"(",
"add",
",",
"(",
"m",
".",
"size",
"for",
"m",
"in",
"tar_bz2",
".",
"getmembers",
"(",
")",
")",
",",
"0",
")",
"size",
"=",
"reduce",
"(",
"add",
",",
"(",
"extracted_size",
"(",
"dist",
")",
"for",
"dist",
"in",
"package_tarball_paths",
")",
",",
"0",
")",
"prefix",
"=",
"state",
"[",
"'prefix'",
"]",
"assert",
"isdir",
"(",
"prefix",
")",
"check_size",
"(",
"prefix",
",",
"size",
")"
] | check whether there is enough space for extract packages . | train | false |
22,299 | def disable_signal_for_loaddata(signal_handler):
@wraps(signal_handler)
def wrapper(*args, **kwargs):
if kwargs.get(u'raw', False):
return
return signal_handler(*args, **kwargs)
return wrapper
| [
"def",
"disable_signal_for_loaddata",
"(",
"signal_handler",
")",
":",
"@",
"wraps",
"(",
"signal_handler",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"u'raw'",
",",
"False",
")",
":",
"return",
"return",
"signal_handler",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"wrapper"
] | decorator that turns off signal handlers when loading fixture data . | train | false |
22,300 | def killall(greenlets, exception=GreenletExit, block=True, timeout=None):
greenlets = list(greenlets)
if (not greenlets):
return
loop = greenlets[0].loop
if block:
waiter = Waiter()
loop.run_callback(_killall3, greenlets, exception, waiter)
t = Timeout._start_new_or_dummy(timeout)
try:
alive = waiter.get()
if alive:
joinall(alive, raise_error=False)
finally:
t.cancel()
else:
loop.run_callback(_killall, greenlets, exception)
| [
"def",
"killall",
"(",
"greenlets",
",",
"exception",
"=",
"GreenletExit",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"greenlets",
"=",
"list",
"(",
"greenlets",
")",
"if",
"(",
"not",
"greenlets",
")",
":",
"return",
"loop",
"=",
"greenlets",
"[",
"0",
"]",
".",
"loop",
"if",
"block",
":",
"waiter",
"=",
"Waiter",
"(",
")",
"loop",
".",
"run_callback",
"(",
"_killall3",
",",
"greenlets",
",",
"exception",
",",
"waiter",
")",
"t",
"=",
"Timeout",
".",
"_start_new_or_dummy",
"(",
"timeout",
")",
"try",
":",
"alive",
"=",
"waiter",
".",
"get",
"(",
")",
"if",
"alive",
":",
"joinall",
"(",
"alive",
",",
"raise_error",
"=",
"False",
")",
"finally",
":",
"t",
".",
"cancel",
"(",
")",
"else",
":",
"loop",
".",
"run_callback",
"(",
"_killall",
",",
"greenlets",
",",
"exception",
")"
] | forceably terminate all the greenlets by causing them to raise exception . | train | false |
22,301 | def structparser(token):
m = STRUCT_PACK_RE.match(token)
if (not m):
return [token]
else:
endian = m.group('endian')
if (endian is None):
return [token]
formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
fmt = ''.join([((f[(-1)] * int(f[:(-1)])) if (len(f) != 1) else f) for f in formatlist])
if (endian == '@'):
if (byteorder == 'little'):
endian = '<'
else:
assert (byteorder == 'big')
endian = '>'
if (endian == '<'):
tokens = [REPLACEMENTS_LE[c] for c in fmt]
else:
assert (endian == '>')
tokens = [REPLACEMENTS_BE[c] for c in fmt]
return tokens
| [
"def",
"structparser",
"(",
"token",
")",
":",
"m",
"=",
"STRUCT_PACK_RE",
".",
"match",
"(",
"token",
")",
"if",
"(",
"not",
"m",
")",
":",
"return",
"[",
"token",
"]",
"else",
":",
"endian",
"=",
"m",
".",
"group",
"(",
"'endian'",
")",
"if",
"(",
"endian",
"is",
"None",
")",
":",
"return",
"[",
"token",
"]",
"formatlist",
"=",
"re",
".",
"findall",
"(",
"STRUCT_SPLIT_RE",
",",
"m",
".",
"group",
"(",
"'fmt'",
")",
")",
"fmt",
"=",
"''",
".",
"join",
"(",
"[",
"(",
"(",
"f",
"[",
"(",
"-",
"1",
")",
"]",
"*",
"int",
"(",
"f",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
")",
"if",
"(",
"len",
"(",
"f",
")",
"!=",
"1",
")",
"else",
"f",
")",
"for",
"f",
"in",
"formatlist",
"]",
")",
"if",
"(",
"endian",
"==",
"'@'",
")",
":",
"if",
"(",
"byteorder",
"==",
"'little'",
")",
":",
"endian",
"=",
"'<'",
"else",
":",
"assert",
"(",
"byteorder",
"==",
"'big'",
")",
"endian",
"=",
"'>'",
"if",
"(",
"endian",
"==",
"'<'",
")",
":",
"tokens",
"=",
"[",
"REPLACEMENTS_LE",
"[",
"c",
"]",
"for",
"c",
"in",
"fmt",
"]",
"else",
":",
"assert",
"(",
"endian",
"==",
"'>'",
")",
"tokens",
"=",
"[",
"REPLACEMENTS_BE",
"[",
"c",
"]",
"for",
"c",
"in",
"fmt",
"]",
"return",
"tokens"
] | parse struct-like format string token into sub-token list . | train | true |
22,302 | def test_adapthist_color():
img = skimage.img_as_uint(data.astronaut())
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
(hist, bin_centers) = exposure.histogram(img)
assert (len(w) > 0)
with expected_warnings(['precision loss']):
adapted = exposure.equalize_adapthist(img, clip_limit=0.01)
assert (adapted.min() == 0)
assert (adapted.max() == 1.0)
assert (img.shape == adapted.shape)
full_scale = skimage.exposure.rescale_intensity(img)
assert_almost_equal(peak_snr(full_scale, adapted), 109.393, 1)
assert_almost_equal(norm_brightness_err(full_scale, adapted), 0.02, 2)
return (data, adapted)
| [
"def",
"test_adapthist_color",
"(",
")",
":",
"img",
"=",
"skimage",
".",
"img_as_uint",
"(",
"data",
".",
"astronaut",
"(",
")",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
"as",
"w",
":",
"warnings",
".",
"simplefilter",
"(",
"'always'",
")",
"(",
"hist",
",",
"bin_centers",
")",
"=",
"exposure",
".",
"histogram",
"(",
"img",
")",
"assert",
"(",
"len",
"(",
"w",
")",
">",
"0",
")",
"with",
"expected_warnings",
"(",
"[",
"'precision loss'",
"]",
")",
":",
"adapted",
"=",
"exposure",
".",
"equalize_adapthist",
"(",
"img",
",",
"clip_limit",
"=",
"0.01",
")",
"assert",
"(",
"adapted",
".",
"min",
"(",
")",
"==",
"0",
")",
"assert",
"(",
"adapted",
".",
"max",
"(",
")",
"==",
"1.0",
")",
"assert",
"(",
"img",
".",
"shape",
"==",
"adapted",
".",
"shape",
")",
"full_scale",
"=",
"skimage",
".",
"exposure",
".",
"rescale_intensity",
"(",
"img",
")",
"assert_almost_equal",
"(",
"peak_snr",
"(",
"full_scale",
",",
"adapted",
")",
",",
"109.393",
",",
"1",
")",
"assert_almost_equal",
"(",
"norm_brightness_err",
"(",
"full_scale",
",",
"adapted",
")",
",",
"0.02",
",",
"2",
")",
"return",
"(",
"data",
",",
"adapted",
")"
] | test an rgb color uint16 image . | train | false |
22,303 | def assertIsNone(expr, msg=''):
return assertIs(expr, None, msg)
| [
"def",
"assertIsNone",
"(",
"expr",
",",
"msg",
"=",
"''",
")",
":",
"return",
"assertIs",
"(",
"expr",
",",
"None",
",",
"msg",
")"
] | checks that expr is none . | train | false |
22,304 | def binary_replace(data, a, b):
if on_win:
if has_pyzzer_entry_point(data):
return replace_pyzzer_entry_point_shebang(data, a, b)
else:
return data
def replace(match):
occurances = match.group().count(a)
padding = ((len(a) - len(b)) * occurances)
if (padding < 0):
raise _PaddingError
return (match.group().replace(a, b) + ('\x00' * padding))
original_data_len = len(data)
pat = re.compile((re.escape(a) + '([^\x00]*?)\x00'))
data = pat.sub(replace, data)
assert (len(data) == original_data_len)
return data
| [
"def",
"binary_replace",
"(",
"data",
",",
"a",
",",
"b",
")",
":",
"if",
"on_win",
":",
"if",
"has_pyzzer_entry_point",
"(",
"data",
")",
":",
"return",
"replace_pyzzer_entry_point_shebang",
"(",
"data",
",",
"a",
",",
"b",
")",
"else",
":",
"return",
"data",
"def",
"replace",
"(",
"match",
")",
":",
"occurances",
"=",
"match",
".",
"group",
"(",
")",
".",
"count",
"(",
"a",
")",
"padding",
"=",
"(",
"(",
"len",
"(",
"a",
")",
"-",
"len",
"(",
"b",
")",
")",
"*",
"occurances",
")",
"if",
"(",
"padding",
"<",
"0",
")",
":",
"raise",
"_PaddingError",
"return",
"(",
"match",
".",
"group",
"(",
")",
".",
"replace",
"(",
"a",
",",
"b",
")",
"+",
"(",
"'\\x00'",
"*",
"padding",
")",
")",
"original_data_len",
"=",
"len",
"(",
"data",
")",
"pat",
"=",
"re",
".",
"compile",
"(",
"(",
"re",
".",
"escape",
"(",
"a",
")",
"+",
"'([^\\x00]*?)\\x00'",
")",
")",
"data",
"=",
"pat",
".",
"sub",
"(",
"replace",
",",
"data",
")",
"assert",
"(",
"len",
"(",
"data",
")",
"==",
"original_data_len",
")",
"return",
"data"
] | perform a binary replacement of data . | train | false |
22,308 | @pytest.fixture(scope=u'function')
def remove_cheese_file(request):
def fin_remove_cheese_file():
if os.path.exists(u'tests/files/cheese.txt'):
os.remove(u'tests/files/cheese.txt')
request.addfinalizer(fin_remove_cheese_file)
| [
"@",
"pytest",
".",
"fixture",
"(",
"scope",
"=",
"u'function'",
")",
"def",
"remove_cheese_file",
"(",
"request",
")",
":",
"def",
"fin_remove_cheese_file",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"u'tests/files/cheese.txt'",
")",
":",
"os",
".",
"remove",
"(",
"u'tests/files/cheese.txt'",
")",
"request",
".",
"addfinalizer",
"(",
"fin_remove_cheese_file",
")"
] | remove the cheese text file which is created by the tests . | train | false |
22,309 | def ellip_harm_2(h2, k2, n, p, s):
with np.errstate(all='ignore'):
return _ellip_harm_2_vec(h2, k2, n, p, s)
| [
"def",
"ellip_harm_2",
"(",
"h2",
",",
"k2",
",",
"n",
",",
"p",
",",
"s",
")",
":",
"with",
"np",
".",
"errstate",
"(",
"all",
"=",
"'ignore'",
")",
":",
"return",
"_ellip_harm_2_vec",
"(",
"h2",
",",
"k2",
",",
"n",
",",
"p",
",",
"s",
")"
] | ellipsoidal harmonic functions f^p_n(l) these are also known as lame functions of the second kind . | train | false |
22,310 | def _glanceclient_from_endpoint(context, endpoint, version=1):
params = {}
params['identity_headers'] = generate_identity_headers(context)
if endpoint.startswith('https://'):
params['insecure'] = CONF.glance.api_insecure
params['ssl_compression'] = False
sslutils.is_enabled(CONF)
if CONF.ssl.cert_file:
params['cert_file'] = CONF.ssl.cert_file
if CONF.ssl.key_file:
params['key_file'] = CONF.ssl.key_file
if CONF.ssl.ca_file:
params['cacert'] = CONF.ssl.ca_file
return glanceclient.Client(str(version), endpoint, **params)
| [
"def",
"_glanceclient_from_endpoint",
"(",
"context",
",",
"endpoint",
",",
"version",
"=",
"1",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"'identity_headers'",
"]",
"=",
"generate_identity_headers",
"(",
"context",
")",
"if",
"endpoint",
".",
"startswith",
"(",
"'https://'",
")",
":",
"params",
"[",
"'insecure'",
"]",
"=",
"CONF",
".",
"glance",
".",
"api_insecure",
"params",
"[",
"'ssl_compression'",
"]",
"=",
"False",
"sslutils",
".",
"is_enabled",
"(",
"CONF",
")",
"if",
"CONF",
".",
"ssl",
".",
"cert_file",
":",
"params",
"[",
"'cert_file'",
"]",
"=",
"CONF",
".",
"ssl",
".",
"cert_file",
"if",
"CONF",
".",
"ssl",
".",
"key_file",
":",
"params",
"[",
"'key_file'",
"]",
"=",
"CONF",
".",
"ssl",
".",
"key_file",
"if",
"CONF",
".",
"ssl",
".",
"ca_file",
":",
"params",
"[",
"'cacert'",
"]",
"=",
"CONF",
".",
"ssl",
".",
"ca_file",
"return",
"glanceclient",
".",
"Client",
"(",
"str",
"(",
"version",
")",
",",
"endpoint",
",",
"**",
"params",
")"
] | instantiate a new glanceclient . | train | false |
22,311 | def find_bindir_path(config_file):
try:
fd = open(config_file)
except IOError as e:
utils.err(('Error for Config file (%s): %s' % (config_file, e)))
return None
try:
for line in fd:
if line.startswith('{path_config_bindir'):
return line.split(',')[1].split('"')[1]
finally:
fd.close()
| [
"def",
"find_bindir_path",
"(",
"config_file",
")",
":",
"try",
":",
"fd",
"=",
"open",
"(",
"config_file",
")",
"except",
"IOError",
"as",
"e",
":",
"utils",
".",
"err",
"(",
"(",
"'Error for Config file (%s): %s'",
"%",
"(",
"config_file",
",",
"e",
")",
")",
")",
"return",
"None",
"try",
":",
"for",
"line",
"in",
"fd",
":",
"if",
"line",
".",
"startswith",
"(",
"'{path_config_bindir'",
")",
":",
"return",
"line",
".",
"split",
"(",
"','",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'\"'",
")",
"[",
"1",
"]",
"finally",
":",
"fd",
".",
"close",
"(",
")"
] | returns the bin directory path . | train | false |
22,312 | def msolve(f, x):
f = lambdify(x, f)
x0 = (-0.001)
dx = 0.001
while ((f((x0 - dx)) * f(x0)) > 0):
x0 = (x0 - dx)
x_max = (x0 - dx)
x_min = x0
assert (f(x_max) > 0)
assert (f(x_min) < 0)
for n in range(100):
x0 = ((x_max + x_min) / 2)
if (f(x0) > 0):
x_max = x0
else:
x_min = x0
return x0
| [
"def",
"msolve",
"(",
"f",
",",
"x",
")",
":",
"f",
"=",
"lambdify",
"(",
"x",
",",
"f",
")",
"x0",
"=",
"(",
"-",
"0.001",
")",
"dx",
"=",
"0.001",
"while",
"(",
"(",
"f",
"(",
"(",
"x0",
"-",
"dx",
")",
")",
"*",
"f",
"(",
"x0",
")",
")",
">",
"0",
")",
":",
"x0",
"=",
"(",
"x0",
"-",
"dx",
")",
"x_max",
"=",
"(",
"x0",
"-",
"dx",
")",
"x_min",
"=",
"x0",
"assert",
"(",
"f",
"(",
"x_max",
")",
">",
"0",
")",
"assert",
"(",
"f",
"(",
"x_min",
")",
"<",
"0",
")",
"for",
"n",
"in",
"range",
"(",
"100",
")",
":",
"x0",
"=",
"(",
"(",
"x_max",
"+",
"x_min",
")",
"/",
"2",
")",
"if",
"(",
"f",
"(",
"x0",
")",
">",
"0",
")",
":",
"x_max",
"=",
"x0",
"else",
":",
"x_min",
"=",
"x0",
"return",
"x0"
] | finds the first root of f(x) to the left of 0 . | train | false |
22,313 | def test_inequalities_symbol_name_same_complex():
for a in (x, S(0), (S(1) / 3), pi, oo):
raises(TypeError, (lambda : Gt(a, I)))
raises(TypeError, (lambda : (a > I)))
raises(TypeError, (lambda : Lt(a, I)))
raises(TypeError, (lambda : (a < I)))
raises(TypeError, (lambda : Ge(a, I)))
raises(TypeError, (lambda : (a >= I)))
raises(TypeError, (lambda : Le(a, I)))
raises(TypeError, (lambda : (a <= I)))
| [
"def",
"test_inequalities_symbol_name_same_complex",
"(",
")",
":",
"for",
"a",
"in",
"(",
"x",
",",
"S",
"(",
"0",
")",
",",
"(",
"S",
"(",
"1",
")",
"/",
"3",
")",
",",
"pi",
",",
"oo",
")",
":",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"Gt",
"(",
"a",
",",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"(",
"a",
">",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"Lt",
"(",
"a",
",",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"(",
"a",
"<",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"Ge",
"(",
"a",
",",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"(",
"a",
">=",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"Le",
"(",
"a",
",",
"I",
")",
")",
")",
"raises",
"(",
"TypeError",
",",
"(",
"lambda",
":",
"(",
"a",
"<=",
"I",
")",
")",
")"
] | using the operator and functional forms should give same results . | train | false |
22,315 | def allow_interpreter_mode(fn):
@functools.wraps(fn)
def _core(*args, **kws):
config.COMPATIBILITY_MODE = True
try:
fn(*args, **kws)
finally:
config.COMPATIBILITY_MODE = False
return _core
| [
"def",
"allow_interpreter_mode",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"_core",
"(",
"*",
"args",
",",
"**",
"kws",
")",
":",
"config",
".",
"COMPATIBILITY_MODE",
"=",
"True",
"try",
":",
"fn",
"(",
"*",
"args",
",",
"**",
"kws",
")",
"finally",
":",
"config",
".",
"COMPATIBILITY_MODE",
"=",
"False",
"return",
"_core"
] | temporarily re-enable intepreter mode . | train | false |
22,316 | def tunnelX11(node, display=None):
if ((display is None) and ('DISPLAY' in environ)):
display = environ['DISPLAY']
if (display is None):
error('Error: Cannot connect to display\n')
return (None, None)
(host, screen) = display.split(':')
if ((not host) or (host == 'unix')):
quietRun('xhost +si:localuser:root')
return (display, None)
else:
port = (6000 + int(float(screen)))
connection = ('TCP\\:%s\\:%s' % (host, port))
cmd = ['socat', ('TCP-LISTEN:%d,fork,reuseaddr' % port), ("EXEC:'mnexec -a 1 socat STDIO %s'" % connection)]
return (('localhost:' + screen), node.popen(cmd))
| [
"def",
"tunnelX11",
"(",
"node",
",",
"display",
"=",
"None",
")",
":",
"if",
"(",
"(",
"display",
"is",
"None",
")",
"and",
"(",
"'DISPLAY'",
"in",
"environ",
")",
")",
":",
"display",
"=",
"environ",
"[",
"'DISPLAY'",
"]",
"if",
"(",
"display",
"is",
"None",
")",
":",
"error",
"(",
"'Error: Cannot connect to display\\n'",
")",
"return",
"(",
"None",
",",
"None",
")",
"(",
"host",
",",
"screen",
")",
"=",
"display",
".",
"split",
"(",
"':'",
")",
"if",
"(",
"(",
"not",
"host",
")",
"or",
"(",
"host",
"==",
"'unix'",
")",
")",
":",
"quietRun",
"(",
"'xhost +si:localuser:root'",
")",
"return",
"(",
"display",
",",
"None",
")",
"else",
":",
"port",
"=",
"(",
"6000",
"+",
"int",
"(",
"float",
"(",
"screen",
")",
")",
")",
"connection",
"=",
"(",
"'TCP\\\\:%s\\\\:%s'",
"%",
"(",
"host",
",",
"port",
")",
")",
"cmd",
"=",
"[",
"'socat'",
",",
"(",
"'TCP-LISTEN:%d,fork,reuseaddr'",
"%",
"port",
")",
",",
"(",
"\"EXEC:'mnexec -a 1 socat STDIO %s'\"",
"%",
"connection",
")",
"]",
"return",
"(",
"(",
"'localhost:'",
"+",
"screen",
")",
",",
"node",
".",
"popen",
"(",
"cmd",
")",
")"
] | create an x11 tunnel from node:6000 to the root host display: display on root host returns: node $display . | train | false |
22,317 | def edit_recarray(r, formatd=None, stringd=None, constant=None, autowin=True):
liststore = RecListStore(r, formatd=formatd, stringd=stringd)
treeview = RecTreeView(liststore, constant=constant)
if autowin:
win = gtk.Window()
win.add(treeview)
win.show_all()
return (liststore, treeview, win)
else:
return (liststore, treeview)
| [
"def",
"edit_recarray",
"(",
"r",
",",
"formatd",
"=",
"None",
",",
"stringd",
"=",
"None",
",",
"constant",
"=",
"None",
",",
"autowin",
"=",
"True",
")",
":",
"liststore",
"=",
"RecListStore",
"(",
"r",
",",
"formatd",
"=",
"formatd",
",",
"stringd",
"=",
"stringd",
")",
"treeview",
"=",
"RecTreeView",
"(",
"liststore",
",",
"constant",
"=",
"constant",
")",
"if",
"autowin",
":",
"win",
"=",
"gtk",
".",
"Window",
"(",
")",
"win",
".",
"add",
"(",
"treeview",
")",
"win",
".",
"show_all",
"(",
")",
"return",
"(",
"liststore",
",",
"treeview",
",",
"win",
")",
"else",
":",
"return",
"(",
"liststore",
",",
"treeview",
")"
] | create a recliststore and rectreeview and return them . | train | false |
22,318 | def _fetch_from_local_file(pathfinder=_find_yaml_path, fileopener=open):
yaml_path = pathfinder()
if yaml_path:
config = Config()
config.ah__conf__load_from_yaml(LoadSingleConf(fileopener(yaml_path)))
logging.debug('Loaded conf parameters from conf.yaml.')
return config
return None
| [
"def",
"_fetch_from_local_file",
"(",
"pathfinder",
"=",
"_find_yaml_path",
",",
"fileopener",
"=",
"open",
")",
":",
"yaml_path",
"=",
"pathfinder",
"(",
")",
"if",
"yaml_path",
":",
"config",
"=",
"Config",
"(",
")",
"config",
".",
"ah__conf__load_from_yaml",
"(",
"LoadSingleConf",
"(",
"fileopener",
"(",
"yaml_path",
")",
")",
")",
"logging",
".",
"debug",
"(",
"'Loaded conf parameters from conf.yaml.'",
")",
"return",
"config",
"return",
"None"
] | get the configuration that was uploaded with this version . | train | false |
22,319 | def _get_user_statuses(user, course_key, checkpoint):
enrollment_cache_key = CourseEnrollment.cache_key_name(user.id, unicode(course_key))
has_skipped_cache_key = SkippedReverification.cache_key_name(user.id, unicode(course_key))
verification_status_cache_key = VerificationStatus.cache_key_name(user.id, unicode(course_key))
cache_values = cache.get_many([enrollment_cache_key, has_skipped_cache_key, verification_status_cache_key])
is_verified = cache_values.get(enrollment_cache_key)
if (is_verified is None):
is_verified = CourseEnrollment.is_enrolled_as_verified(user, course_key)
cache.set(enrollment_cache_key, is_verified)
has_skipped = cache_values.get(has_skipped_cache_key)
if (has_skipped is None):
has_skipped = SkippedReverification.check_user_skipped_reverification_exists(user, course_key)
cache.set(has_skipped_cache_key, has_skipped)
verification_statuses = cache_values.get(verification_status_cache_key)
if (verification_statuses is None):
verification_statuses = VerificationStatus.get_all_checkpoints(user.id, course_key)
cache.set(verification_status_cache_key, verification_statuses)
checkpoint = verification_statuses.get(checkpoint)
has_completed_check = bool(checkpoint)
return (is_verified, has_skipped, has_completed_check)
| [
"def",
"_get_user_statuses",
"(",
"user",
",",
"course_key",
",",
"checkpoint",
")",
":",
"enrollment_cache_key",
"=",
"CourseEnrollment",
".",
"cache_key_name",
"(",
"user",
".",
"id",
",",
"unicode",
"(",
"course_key",
")",
")",
"has_skipped_cache_key",
"=",
"SkippedReverification",
".",
"cache_key_name",
"(",
"user",
".",
"id",
",",
"unicode",
"(",
"course_key",
")",
")",
"verification_status_cache_key",
"=",
"VerificationStatus",
".",
"cache_key_name",
"(",
"user",
".",
"id",
",",
"unicode",
"(",
"course_key",
")",
")",
"cache_values",
"=",
"cache",
".",
"get_many",
"(",
"[",
"enrollment_cache_key",
",",
"has_skipped_cache_key",
",",
"verification_status_cache_key",
"]",
")",
"is_verified",
"=",
"cache_values",
".",
"get",
"(",
"enrollment_cache_key",
")",
"if",
"(",
"is_verified",
"is",
"None",
")",
":",
"is_verified",
"=",
"CourseEnrollment",
".",
"is_enrolled_as_verified",
"(",
"user",
",",
"course_key",
")",
"cache",
".",
"set",
"(",
"enrollment_cache_key",
",",
"is_verified",
")",
"has_skipped",
"=",
"cache_values",
".",
"get",
"(",
"has_skipped_cache_key",
")",
"if",
"(",
"has_skipped",
"is",
"None",
")",
":",
"has_skipped",
"=",
"SkippedReverification",
".",
"check_user_skipped_reverification_exists",
"(",
"user",
",",
"course_key",
")",
"cache",
".",
"set",
"(",
"has_skipped_cache_key",
",",
"has_skipped",
")",
"verification_statuses",
"=",
"cache_values",
".",
"get",
"(",
"verification_status_cache_key",
")",
"if",
"(",
"verification_statuses",
"is",
"None",
")",
":",
"verification_statuses",
"=",
"VerificationStatus",
".",
"get_all_checkpoints",
"(",
"user",
".",
"id",
",",
"course_key",
")",
"cache",
".",
"set",
"(",
"verification_status_cache_key",
",",
"verification_statuses",
")",
"checkpoint",
"=",
"verification_statuses",
".",
"get",
"(",
"checkpoint",
")",
"has_completed_check",
"=",
"bool",
"(",
"checkpoint",
")",
"return",
"(",
"is_verified",
",",
"has_skipped",
",",
"has_completed_check",
")"
] | retrieve all the information we need to determine the users group . | train | false |
22,320 | def _compose2(f, g):
return (lambda *args, **kwargs: f(g(*args, **kwargs)))
| [
"def",
"_compose2",
"(",
"f",
",",
"g",
")",
":",
"return",
"(",
"lambda",
"*",
"args",
",",
"**",
"kwargs",
":",
"f",
"(",
"g",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
")"
] | compose 2 callables . | train | false |
22,321 | def _extract_doc_comment_continuous(content, line, column, markers):
marker_len = len(markers[1])
doc_comment = content[line][column:]
line += 1
while (line < len(content)):
pos = content[line].find(markers[1])
if (pos == (-1)):
return (line, 0, doc_comment)
else:
doc_comment += content[line][(pos + marker_len):]
line += 1
if (content[(line - 1)][(-1)] == '\n'):
column = 0
else:
line -= 1
column = len(content[line])
return (line, column, doc_comment)
| [
"def",
"_extract_doc_comment_continuous",
"(",
"content",
",",
"line",
",",
"column",
",",
"markers",
")",
":",
"marker_len",
"=",
"len",
"(",
"markers",
"[",
"1",
"]",
")",
"doc_comment",
"=",
"content",
"[",
"line",
"]",
"[",
"column",
":",
"]",
"line",
"+=",
"1",
"while",
"(",
"line",
"<",
"len",
"(",
"content",
")",
")",
":",
"pos",
"=",
"content",
"[",
"line",
"]",
".",
"find",
"(",
"markers",
"[",
"1",
"]",
")",
"if",
"(",
"pos",
"==",
"(",
"-",
"1",
")",
")",
":",
"return",
"(",
"line",
",",
"0",
",",
"doc_comment",
")",
"else",
":",
"doc_comment",
"+=",
"content",
"[",
"line",
"]",
"[",
"(",
"pos",
"+",
"marker_len",
")",
":",
"]",
"line",
"+=",
"1",
"if",
"(",
"content",
"[",
"(",
"line",
"-",
"1",
")",
"]",
"[",
"(",
"-",
"1",
")",
"]",
"==",
"'\\n'",
")",
":",
"column",
"=",
"0",
"else",
":",
"line",
"-=",
"1",
"column",
"=",
"len",
"(",
"content",
"[",
"line",
"]",
")",
"return",
"(",
"line",
",",
"column",
",",
"doc_comment",
")"
] | extract a documentation that starts at given beginning with continuous layout . | train | false |
22,323 | def delinkify(text, allow_domains=None, allow_relative=False):
text = force_unicode(text)
if (not text):
return u''
parser = html5lib.HTMLParser(tokenizer=HTMLSanitizer)
forest = parser.parseFragment(text)
if (allow_domains is None):
allow_domains = []
elif isinstance(allow_domains, basestring):
allow_domains = [allow_domains]
def delinkify_nodes(tree):
'Remove <a> tags and replace them with their contents.'
for node in tree.childNodes:
if (node.name == 'a'):
if ('href' not in node.attributes):
continue
parts = urlparse.urlparse(node.attributes['href'])
host = parts.hostname
if any((_domain_match(host, d) for d in allow_domains)):
continue
if ((host is None) and allow_relative):
continue
for n in node.childNodes:
tree.insertBefore(n, node)
tree.removeChild(node)
elif (node.type != NODE_TEXT):
delinkify_nodes(node)
delinkify_nodes(forest)
return _render(forest)
| [
"def",
"delinkify",
"(",
"text",
",",
"allow_domains",
"=",
"None",
",",
"allow_relative",
"=",
"False",
")",
":",
"text",
"=",
"force_unicode",
"(",
"text",
")",
"if",
"(",
"not",
"text",
")",
":",
"return",
"u''",
"parser",
"=",
"html5lib",
".",
"HTMLParser",
"(",
"tokenizer",
"=",
"HTMLSanitizer",
")",
"forest",
"=",
"parser",
".",
"parseFragment",
"(",
"text",
")",
"if",
"(",
"allow_domains",
"is",
"None",
")",
":",
"allow_domains",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"allow_domains",
",",
"basestring",
")",
":",
"allow_domains",
"=",
"[",
"allow_domains",
"]",
"def",
"delinkify_nodes",
"(",
"tree",
")",
":",
"for",
"node",
"in",
"tree",
".",
"childNodes",
":",
"if",
"(",
"node",
".",
"name",
"==",
"'a'",
")",
":",
"if",
"(",
"'href'",
"not",
"in",
"node",
".",
"attributes",
")",
":",
"continue",
"parts",
"=",
"urlparse",
".",
"urlparse",
"(",
"node",
".",
"attributes",
"[",
"'href'",
"]",
")",
"host",
"=",
"parts",
".",
"hostname",
"if",
"any",
"(",
"(",
"_domain_match",
"(",
"host",
",",
"d",
")",
"for",
"d",
"in",
"allow_domains",
")",
")",
":",
"continue",
"if",
"(",
"(",
"host",
"is",
"None",
")",
"and",
"allow_relative",
")",
":",
"continue",
"for",
"n",
"in",
"node",
".",
"childNodes",
":",
"tree",
".",
"insertBefore",
"(",
"n",
",",
"node",
")",
"tree",
".",
"removeChild",
"(",
"node",
")",
"elif",
"(",
"node",
".",
"type",
"!=",
"NODE_TEXT",
")",
":",
"delinkify_nodes",
"(",
"node",
")",
"delinkify_nodes",
"(",
"forest",
")",
"return",
"_render",
"(",
"forest",
")"
] | remove links from text . | train | false |
22,324 | def serialize(name, dataset=None, dataset_pillar=None, user=None, group=None, mode=None, backup='', makedirs=False, show_diff=True, create=True, merge_if_exists=False, **kwargs):
if ('env' in kwargs):
salt.utils.warn_until('Oxygen', "Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.")
kwargs.pop('env')
name = os.path.expanduser(name)
default_serializer_opts = {'yaml.serialize': {'default_flow_style': False}, 'json.serialize': {'indent': 2, 'separators': (',', ': '), 'sort_keys': True}}
ret = {'changes': {}, 'comment': '', 'name': name, 'result': True}
if (not name):
return _error(ret, 'Must provide name to file.serialize')
if (not create):
if (not os.path.isfile(name)):
ret['comment'] = 'File {0} is not present and is not set for creation'.format(name)
return ret
formatter = kwargs.pop('formatter', 'yaml').lower()
if (len([x for x in (dataset, dataset_pillar) if x]) > 1):
return _error(ret, "Only one of 'dataset' and 'dataset_pillar' is permitted")
if dataset_pillar:
dataset = __salt__['pillar.get'](dataset_pillar)
if (dataset is None):
return _error(ret, "Neither 'dataset' nor 'dataset_pillar' was defined")
if salt.utils.is_windows():
if (group is not None):
log.warning('The group argument for {0} has been ignored as this is a Windows system.'.format(name))
group = user
serializer_name = '{0}.serialize'.format(formatter)
deserializer_name = '{0}.deserialize'.format(formatter)
if (serializer_name not in __serializers__):
return {'changes': {}, 'comment': '{0} format is not supported'.format(formatter.capitalize()), 'name': name, 'result': False}
if merge_if_exists:
if os.path.isfile(name):
if ('{0}.deserialize'.format(formatter) not in __serializers__):
return {'changes': {}, 'comment': '{0} format is not supported for merging'.format(formatter.capitalize()), 'name': name, 'result': False}
with salt.utils.fopen(name, 'r') as fhr:
existing_data = __serializers__[deserializer_name](fhr)
if (existing_data is not None):
merged_data = salt.utils.dictupdate.merge_recurse(existing_data, dataset)
if (existing_data == merged_data):
ret['result'] = True
ret['comment'] = 'The file {0} is in the correct state'.format(name)
return ret
dataset = merged_data
contents = __serializers__[serializer_name](dataset, **default_serializer_opts.get(serializer_name, {}))
contents += '\n'
mode = salt.utils.normalize_mode(mode)
if __opts__['test']:
ret['changes'] = __salt__['file.check_managed_changes'](name=name, source=None, source_hash={}, source_hash_name=None, user=user, group=group, mode=mode, template=None, context=None, defaults=None, saltenv=__env__, contents=contents, skip_verify=False, **kwargs)
if ret['changes']:
ret['result'] = None
ret['comment'] = 'Dataset will be serialized and stored into {0}'.format(name)
else:
ret['result'] = True
ret['comment'] = 'The file {0} is in the correct state'.format(name)
return ret
return __salt__['file.manage_file'](name=name, sfn='', ret=ret, source=None, source_sum={}, user=user, group=group, mode=mode, saltenv=__env__, backup=backup, makedirs=makedirs, template=None, show_changes=show_diff, contents=contents)
| [
"def",
"serialize",
"(",
"name",
",",
"dataset",
"=",
"None",
",",
"dataset_pillar",
"=",
"None",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"backup",
"=",
"''",
",",
"makedirs",
"=",
"False",
",",
"show_diff",
"=",
"True",
",",
"create",
"=",
"True",
",",
"merge_if_exists",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"'env'",
"in",
"kwargs",
")",
":",
"salt",
".",
"utils",
".",
"warn_until",
"(",
"'Oxygen'",
",",
"\"Parameter 'env' has been detected in the argument list. This parameter is no longer used and has been replaced by 'saltenv' as of Salt 2016.11.0. This warning will be removed in Salt Oxygen.\"",
")",
"kwargs",
".",
"pop",
"(",
"'env'",
")",
"name",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"default_serializer_opts",
"=",
"{",
"'yaml.serialize'",
":",
"{",
"'default_flow_style'",
":",
"False",
"}",
",",
"'json.serialize'",
":",
"{",
"'indent'",
":",
"2",
",",
"'separators'",
":",
"(",
"','",
",",
"': '",
")",
",",
"'sort_keys'",
":",
"True",
"}",
"}",
"ret",
"=",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
"}",
"if",
"(",
"not",
"name",
")",
":",
"return",
"_error",
"(",
"ret",
",",
"'Must provide name to file.serialize'",
")",
"if",
"(",
"not",
"create",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"name",
")",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'File {0} is not present and is not set for creation'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"formatter",
"=",
"kwargs",
".",
"pop",
"(",
"'formatter'",
",",
"'yaml'",
")",
".",
"lower",
"(",
")",
"if",
"(",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"(",
"dataset",
",",
"dataset_pillar",
")",
"if",
"x",
"]",
")",
">",
"1",
")",
":",
"return",
"_error",
"(",
"ret",
",",
"\"Only one of 'dataset' and 'dataset_pillar' is permitted\"",
")",
"if",
"dataset_pillar",
":",
"dataset",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"dataset_pillar",
")",
"if",
"(",
"dataset",
"is",
"None",
")",
":",
"return",
"_error",
"(",
"ret",
",",
"\"Neither 'dataset' nor 'dataset_pillar' was defined\"",
")",
"if",
"salt",
".",
"utils",
".",
"is_windows",
"(",
")",
":",
"if",
"(",
"group",
"is",
"not",
"None",
")",
":",
"log",
".",
"warning",
"(",
"'The group argument for {0} has been ignored as this is a Windows system.'",
".",
"format",
"(",
"name",
")",
")",
"group",
"=",
"user",
"serializer_name",
"=",
"'{0}.serialize'",
".",
"format",
"(",
"formatter",
")",
"deserializer_name",
"=",
"'{0}.deserialize'",
".",
"format",
"(",
"formatter",
")",
"if",
"(",
"serializer_name",
"not",
"in",
"__serializers__",
")",
":",
"return",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"'{0} format is not supported'",
".",
"format",
"(",
"formatter",
".",
"capitalize",
"(",
")",
")",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
"}",
"if",
"merge_if_exists",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"name",
")",
":",
"if",
"(",
"'{0}.deserialize'",
".",
"format",
"(",
"formatter",
")",
"not",
"in",
"__serializers__",
")",
":",
"return",
"{",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"'{0} format is not supported for merging'",
".",
"format",
"(",
"formatter",
".",
"capitalize",
"(",
")",
")",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
"}",
"with",
"salt",
".",
"utils",
".",
"fopen",
"(",
"name",
",",
"'r'",
")",
"as",
"fhr",
":",
"existing_data",
"=",
"__serializers__",
"[",
"deserializer_name",
"]",
"(",
"fhr",
")",
"if",
"(",
"existing_data",
"is",
"not",
"None",
")",
":",
"merged_data",
"=",
"salt",
".",
"utils",
".",
"dictupdate",
".",
"merge_recurse",
"(",
"existing_data",
",",
"dataset",
")",
"if",
"(",
"existing_data",
"==",
"merged_data",
")",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'The file {0} is in the correct state'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"dataset",
"=",
"merged_data",
"contents",
"=",
"__serializers__",
"[",
"serializer_name",
"]",
"(",
"dataset",
",",
"**",
"default_serializer_opts",
".",
"get",
"(",
"serializer_name",
",",
"{",
"}",
")",
")",
"contents",
"+=",
"'\\n'",
"mode",
"=",
"salt",
".",
"utils",
".",
"normalize_mode",
"(",
"mode",
")",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__",
"[",
"'file.check_managed_changes'",
"]",
"(",
"name",
"=",
"name",
",",
"source",
"=",
"None",
",",
"source_hash",
"=",
"{",
"}",
",",
"source_hash_name",
"=",
"None",
",",
"user",
"=",
"user",
",",
"group",
"=",
"group",
",",
"mode",
"=",
"mode",
",",
"template",
"=",
"None",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"saltenv",
"=",
"__env__",
",",
"contents",
"=",
"contents",
",",
"skip_verify",
"=",
"False",
",",
"**",
"kwargs",
")",
"if",
"ret",
"[",
"'changes'",
"]",
":",
"ret",
"[",
"'result'",
"]",
"=",
"None",
"ret",
"[",
"'comment'",
"]",
"=",
"'Dataset will be serialized and stored into {0}'",
".",
"format",
"(",
"name",
")",
"else",
":",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"ret",
"[",
"'comment'",
"]",
"=",
"'The file {0} is in the correct state'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"return",
"__salt__",
"[",
"'file.manage_file'",
"]",
"(",
"name",
"=",
"name",
",",
"sfn",
"=",
"''",
",",
"ret",
"=",
"ret",
",",
"source",
"=",
"None",
",",
"source_sum",
"=",
"{",
"}",
",",
"user",
"=",
"user",
",",
"group",
"=",
"group",
",",
"mode",
"=",
"mode",
",",
"saltenv",
"=",
"__env__",
",",
"backup",
"=",
"backup",
",",
"makedirs",
"=",
"makedirs",
",",
"template",
"=",
"None",
",",
"show_changes",
"=",
"show_diff",
",",
"contents",
"=",
"contents",
")"
] | save a collection to database . | train | false |
22,325 | def volume_delete(provider, names, **kwargs):
client = _get_client()
info = client.extra_action(provider=provider, names=names, action='volume_delete', **kwargs)
return info
| [
"def",
"volume_delete",
"(",
"provider",
",",
"names",
",",
"**",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"info",
"=",
"client",
".",
"extra_action",
"(",
"provider",
"=",
"provider",
",",
"names",
"=",
"names",
",",
"action",
"=",
"'volume_delete'",
",",
"**",
"kwargs",
")",
"return",
"info"
] | delete block storage device . | train | true |
22,327 | def no_testtools_skip_decorator(logical_line):
if TESTTOOLS_SKIP_DECORATOR.match(logical_line):
(yield (0, 'T109: Cannot use testtools.skip decorator; instead use decorators.skip_because from tempest.lib'))
| [
"def",
"no_testtools_skip_decorator",
"(",
"logical_line",
")",
":",
"if",
"TESTTOOLS_SKIP_DECORATOR",
".",
"match",
"(",
"logical_line",
")",
":",
"(",
"yield",
"(",
"0",
",",
"'T109: Cannot use testtools.skip decorator; instead use decorators.skip_because from tempest.lib'",
")",
")"
] | check that methods do not have the testtools . | train | false |
22,328 | def _find_file_type(file_names, extension):
return filter((lambda f: f.lower().endswith(extension)), file_names)
| [
"def",
"_find_file_type",
"(",
"file_names",
",",
"extension",
")",
":",
"return",
"filter",
"(",
"(",
"lambda",
"f",
":",
"f",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"extension",
")",
")",
",",
"file_names",
")"
] | returns files that end with the given extension from a list of file names . | train | false |
22,331 | @requires_segment_info
def output_lister(pl, segment_info):
return ((updated(segment_info, output=output[u'name']), {u'draw_inner_divider': None}) for output in get_connected_xrandr_outputs(pl))
| [
"@",
"requires_segment_info",
"def",
"output_lister",
"(",
"pl",
",",
"segment_info",
")",
":",
"return",
"(",
"(",
"updated",
"(",
"segment_info",
",",
"output",
"=",
"output",
"[",
"u'name'",
"]",
")",
",",
"{",
"u'draw_inner_divider'",
":",
"None",
"}",
")",
"for",
"output",
"in",
"get_connected_xrandr_outputs",
"(",
"pl",
")",
")"
] | list all outputs in segment_info format . | train | false |
22,332 | def endian_swap_words(source):
assert ((len(source) % 4) == 0)
words = ('I' * (len(source) // 4))
return struct.pack(('<' + words), *struct.unpack(('>' + words), source))
| [
"def",
"endian_swap_words",
"(",
"source",
")",
":",
"assert",
"(",
"(",
"len",
"(",
"source",
")",
"%",
"4",
")",
"==",
"0",
")",
"words",
"=",
"(",
"'I'",
"*",
"(",
"len",
"(",
"source",
")",
"//",
"4",
")",
")",
"return",
"struct",
".",
"pack",
"(",
"(",
"'<'",
"+",
"words",
")",
",",
"*",
"struct",
".",
"unpack",
"(",
"(",
"'>'",
"+",
"words",
")",
",",
"source",
")",
")"
] | endian-swap each word in source bitstring . | train | true |
22,333 | def sync_contains(value):
return var_contains('SYNC', value)
| [
"def",
"sync_contains",
"(",
"value",
")",
":",
"return",
"var_contains",
"(",
"'SYNC'",
",",
"value",
")"
] | verify if sync variable contains a value in make . | train | false |
22,335 | def set_identity_pool_roles(IdentityPoolId, AuthenticatedRole=None, UnauthenticatedRole=None, region=None, key=None, keyid=None, profile=None):
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
conn = _get_conn(**conn_params)
try:
if AuthenticatedRole:
role_arn = _get_role_arn(AuthenticatedRole, **conn_params)
if (role_arn is None):
return {'set': False, 'error': 'invalid AuthenticatedRole {0}'.format(AuthenticatedRole)}
AuthenticatedRole = role_arn
if UnauthenticatedRole:
role_arn = _get_role_arn(UnauthenticatedRole, **conn_params)
if (role_arn is None):
return {'set': False, 'error': 'invalid UnauthenticatedRole {0}'.format(UnauthenticatedRole)}
UnauthenticatedRole = role_arn
Roles = dict()
if AuthenticatedRole:
Roles['authenticated'] = AuthenticatedRole
if UnauthenticatedRole:
Roles['unauthenticated'] = UnauthenticatedRole
conn.set_identity_pool_roles(IdentityPoolId=IdentityPoolId, Roles=Roles)
return {'set': True, 'roles': Roles}
except ClientError as e:
return {'set': False, 'error': salt.utils.boto3.get_error(e)}
| [
"def",
"set_identity_pool_roles",
"(",
"IdentityPoolId",
",",
"AuthenticatedRole",
"=",
"None",
",",
"UnauthenticatedRole",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn_params",
"=",
"dict",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"conn",
"=",
"_get_conn",
"(",
"**",
"conn_params",
")",
"try",
":",
"if",
"AuthenticatedRole",
":",
"role_arn",
"=",
"_get_role_arn",
"(",
"AuthenticatedRole",
",",
"**",
"conn_params",
")",
"if",
"(",
"role_arn",
"is",
"None",
")",
":",
"return",
"{",
"'set'",
":",
"False",
",",
"'error'",
":",
"'invalid AuthenticatedRole {0}'",
".",
"format",
"(",
"AuthenticatedRole",
")",
"}",
"AuthenticatedRole",
"=",
"role_arn",
"if",
"UnauthenticatedRole",
":",
"role_arn",
"=",
"_get_role_arn",
"(",
"UnauthenticatedRole",
",",
"**",
"conn_params",
")",
"if",
"(",
"role_arn",
"is",
"None",
")",
":",
"return",
"{",
"'set'",
":",
"False",
",",
"'error'",
":",
"'invalid UnauthenticatedRole {0}'",
".",
"format",
"(",
"UnauthenticatedRole",
")",
"}",
"UnauthenticatedRole",
"=",
"role_arn",
"Roles",
"=",
"dict",
"(",
")",
"if",
"AuthenticatedRole",
":",
"Roles",
"[",
"'authenticated'",
"]",
"=",
"AuthenticatedRole",
"if",
"UnauthenticatedRole",
":",
"Roles",
"[",
"'unauthenticated'",
"]",
"=",
"UnauthenticatedRole",
"conn",
".",
"set_identity_pool_roles",
"(",
"IdentityPoolId",
"=",
"IdentityPoolId",
",",
"Roles",
"=",
"Roles",
")",
"return",
"{",
"'set'",
":",
"True",
",",
"'roles'",
":",
"Roles",
"}",
"except",
"ClientError",
"as",
"e",
":",
"return",
"{",
"'set'",
":",
"False",
",",
"'error'",
":",
"salt",
".",
"utils",
".",
"boto3",
".",
"get_error",
"(",
"e",
")",
"}"
] | given an identity pool id . | train | true |
22,336 | def _retrieve_grains(proxy):
global GRAINS_CACHE
if (not GRAINS_CACHE):
GRAINS_CACHE = proxy['napalm.grains']()
return GRAINS_CACHE
| [
"def",
"_retrieve_grains",
"(",
"proxy",
")",
":",
"global",
"GRAINS_CACHE",
"if",
"(",
"not",
"GRAINS_CACHE",
")",
":",
"GRAINS_CACHE",
"=",
"proxy",
"[",
"'napalm.grains'",
"]",
"(",
")",
"return",
"GRAINS_CACHE"
] | retrieves the grains from the network device if not cached already . | train | false |
22,337 | def getfigs(*fig_nums):
from matplotlib._pylab_helpers import Gcf
if (not fig_nums):
fig_managers = Gcf.get_all_fig_managers()
return [fm.canvas.figure for fm in fig_managers]
else:
figs = []
for num in fig_nums:
f = Gcf.figs.get(num)
if (f is None):
print ('Warning: figure %s not available.' % num)
else:
figs.append(f.canvas.figure)
return figs
| [
"def",
"getfigs",
"(",
"*",
"fig_nums",
")",
":",
"from",
"matplotlib",
".",
"_pylab_helpers",
"import",
"Gcf",
"if",
"(",
"not",
"fig_nums",
")",
":",
"fig_managers",
"=",
"Gcf",
".",
"get_all_fig_managers",
"(",
")",
"return",
"[",
"fm",
".",
"canvas",
".",
"figure",
"for",
"fm",
"in",
"fig_managers",
"]",
"else",
":",
"figs",
"=",
"[",
"]",
"for",
"num",
"in",
"fig_nums",
":",
"f",
"=",
"Gcf",
".",
"figs",
".",
"get",
"(",
"num",
")",
"if",
"(",
"f",
"is",
"None",
")",
":",
"print",
"(",
"'Warning: figure %s not available.'",
"%",
"num",
")",
"else",
":",
"figs",
".",
"append",
"(",
"f",
".",
"canvas",
".",
"figure",
")",
"return",
"figs"
] | get a list of matplotlib figures by figure numbers . | train | true |
22,338 | def calculator_prompt():
print 'Welcome to the calculator. Press Ctrl+C to exit.'
cp = CalcParser()
try:
while True:
try:
line = raw_input('--> ')
print cp.calc(line)
except ParseError as err:
print 'Error:', err
except KeyboardInterrupt:
print '... Thanks for using the calculator.'
| [
"def",
"calculator_prompt",
"(",
")",
":",
"print",
"'Welcome to the calculator. Press Ctrl+C to exit.'",
"cp",
"=",
"CalcParser",
"(",
")",
"try",
":",
"while",
"True",
":",
"try",
":",
"line",
"=",
"raw_input",
"(",
"'--> '",
")",
"print",
"cp",
".",
"calc",
"(",
"line",
")",
"except",
"ParseError",
"as",
"err",
":",
"print",
"'Error:'",
",",
"err",
"except",
"KeyboardInterrupt",
":",
"print",
"'... Thanks for using the calculator.'"
] | a toy calculator prompt for interactive computations . | train | false |
22,340 | def readUntilWhitespace(stream, maxchars=None):
txt = b_('')
while True:
tok = stream.read(1)
if (tok.isspace() or (not tok)):
break
txt += tok
if (len(txt) == maxchars):
break
return txt
| [
"def",
"readUntilWhitespace",
"(",
"stream",
",",
"maxchars",
"=",
"None",
")",
":",
"txt",
"=",
"b_",
"(",
"''",
")",
"while",
"True",
":",
"tok",
"=",
"stream",
".",
"read",
"(",
"1",
")",
"if",
"(",
"tok",
".",
"isspace",
"(",
")",
"or",
"(",
"not",
"tok",
")",
")",
":",
"break",
"txt",
"+=",
"tok",
"if",
"(",
"len",
"(",
"txt",
")",
"==",
"maxchars",
")",
":",
"break",
"return",
"txt"
] | reads non-whitespace characters and returns them . | train | false |
22,341 | def getMemoryUsage():
return (_thisProcess.memory_info()[0] / 1048576.0)
| [
"def",
"getMemoryUsage",
"(",
")",
":",
"return",
"(",
"_thisProcess",
".",
"memory_info",
"(",
")",
"[",
"0",
"]",
"/",
"1048576.0",
")"
] | get the memory currently used by this python process . | train | false |
22,343 | def log_buffer_bytes():
return logs_buffer().bytes()
| [
"def",
"log_buffer_bytes",
"(",
")",
":",
"return",
"logs_buffer",
"(",
")",
".",
"bytes",
"(",
")"
] | returns the size of the logs buffer . | train | false |
22,344 | def __fixlocaluser(username):
if ('\\' not in username):
username = '{0}\\{1}'.format(__salt__['grains.get']('host'), username)
return username.lower()
| [
"def",
"__fixlocaluser",
"(",
"username",
")",
":",
"if",
"(",
"'\\\\'",
"not",
"in",
"username",
")",
":",
"username",
"=",
"'{0}\\\\{1}'",
".",
"format",
"(",
"__salt__",
"[",
"'grains.get'",
"]",
"(",
"'host'",
")",
",",
"username",
")",
"return",
"username",
".",
"lower",
"(",
")"
] | prefixes a username w/o a backslash with the computername i . | train | false |
22,348 | def test_consistency_cpu_serial():
seed = 12345
n_samples = 5
n_streams = 12
n_substreams = 7
samples = []
curr_rstate = numpy.array(([seed] * 6), dtype='int32')
for i in range(n_streams):
stream_rstate = curr_rstate.copy()
for j in range(n_substreams):
rstate = theano.shared(numpy.array([stream_rstate.copy()], dtype='int32'))
(new_rstate, sample) = rng_mrg.mrg_uniform.new(rstate, ndim=None, dtype=config.floatX, size=(1,))
sample.rstate = rstate
sample.update = (rstate, new_rstate)
rstate.default_update = new_rstate
f = theano.function([], sample)
for k in range(n_samples):
s = f()
samples.append(s)
stream_rstate = rng_mrg.ff_2p72(stream_rstate)
curr_rstate = rng_mrg.ff_2p134(curr_rstate)
samples = numpy.array(samples).flatten()
assert numpy.allclose(samples, java_samples)
| [
"def",
"test_consistency_cpu_serial",
"(",
")",
":",
"seed",
"=",
"12345",
"n_samples",
"=",
"5",
"n_streams",
"=",
"12",
"n_substreams",
"=",
"7",
"samples",
"=",
"[",
"]",
"curr_rstate",
"=",
"numpy",
".",
"array",
"(",
"(",
"[",
"seed",
"]",
"*",
"6",
")",
",",
"dtype",
"=",
"'int32'",
")",
"for",
"i",
"in",
"range",
"(",
"n_streams",
")",
":",
"stream_rstate",
"=",
"curr_rstate",
".",
"copy",
"(",
")",
"for",
"j",
"in",
"range",
"(",
"n_substreams",
")",
":",
"rstate",
"=",
"theano",
".",
"shared",
"(",
"numpy",
".",
"array",
"(",
"[",
"stream_rstate",
".",
"copy",
"(",
")",
"]",
",",
"dtype",
"=",
"'int32'",
")",
")",
"(",
"new_rstate",
",",
"sample",
")",
"=",
"rng_mrg",
".",
"mrg_uniform",
".",
"new",
"(",
"rstate",
",",
"ndim",
"=",
"None",
",",
"dtype",
"=",
"config",
".",
"floatX",
",",
"size",
"=",
"(",
"1",
",",
")",
")",
"sample",
".",
"rstate",
"=",
"rstate",
"sample",
".",
"update",
"=",
"(",
"rstate",
",",
"new_rstate",
")",
"rstate",
".",
"default_update",
"=",
"new_rstate",
"f",
"=",
"theano",
".",
"function",
"(",
"[",
"]",
",",
"sample",
")",
"for",
"k",
"in",
"range",
"(",
"n_samples",
")",
":",
"s",
"=",
"f",
"(",
")",
"samples",
".",
"append",
"(",
"s",
")",
"stream_rstate",
"=",
"rng_mrg",
".",
"ff_2p72",
"(",
"stream_rstate",
")",
"curr_rstate",
"=",
"rng_mrg",
".",
"ff_2p134",
"(",
"curr_rstate",
")",
"samples",
"=",
"numpy",
".",
"array",
"(",
"samples",
")",
".",
"flatten",
"(",
")",
"assert",
"numpy",
".",
"allclose",
"(",
"samples",
",",
"java_samples",
")"
] | verify that the random numbers generated by mrg_uniform . | train | false |
22,350 | def open_docs(kind=None, version=None):
if (kind is None):
kind = get_config('MNE_DOCS_KIND', 'api')
help_dict = dict(api='python_reference.html', tutorials='tutorials.html', examples='auto_examples/index.html')
if (kind not in help_dict):
raise ValueError(('kind must be one of %s, got %s' % (sorted(help_dict.keys()), kind)))
kind = help_dict[kind]
if (version is None):
version = get_config('MNE_DOCS_VERSION', 'stable')
versions = ('stable', 'dev')
if (version not in versions):
raise ValueError(('version must be one of %s, got %s' % (version, versions)))
webbrowser.open_new_tab(('https://martinos.org/mne/%s/%s' % (version, kind)))
| [
"def",
"open_docs",
"(",
"kind",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"if",
"(",
"kind",
"is",
"None",
")",
":",
"kind",
"=",
"get_config",
"(",
"'MNE_DOCS_KIND'",
",",
"'api'",
")",
"help_dict",
"=",
"dict",
"(",
"api",
"=",
"'python_reference.html'",
",",
"tutorials",
"=",
"'tutorials.html'",
",",
"examples",
"=",
"'auto_examples/index.html'",
")",
"if",
"(",
"kind",
"not",
"in",
"help_dict",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'kind must be one of %s, got %s'",
"%",
"(",
"sorted",
"(",
"help_dict",
".",
"keys",
"(",
")",
")",
",",
"kind",
")",
")",
")",
"kind",
"=",
"help_dict",
"[",
"kind",
"]",
"if",
"(",
"version",
"is",
"None",
")",
":",
"version",
"=",
"get_config",
"(",
"'MNE_DOCS_VERSION'",
",",
"'stable'",
")",
"versions",
"=",
"(",
"'stable'",
",",
"'dev'",
")",
"if",
"(",
"version",
"not",
"in",
"versions",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'version must be one of %s, got %s'",
"%",
"(",
"version",
",",
"versions",
")",
")",
")",
"webbrowser",
".",
"open_new_tab",
"(",
"(",
"'https://martinos.org/mne/%s/%s'",
"%",
"(",
"version",
",",
"kind",
")",
")",
")"
] | launch a new web browser tab with the mne documentation . | train | false |
22,351 | def UnregisterPythonExe(exeAlias):
try:
win32api.RegDeleteKey(GetRootKey(), ((GetAppPathsKey() + '\\') + exeAlias))
except win32api.error as exc:
import winerror
if (exc.winerror != winerror.ERROR_FILE_NOT_FOUND):
raise
return
| [
"def",
"UnregisterPythonExe",
"(",
"exeAlias",
")",
":",
"try",
":",
"win32api",
".",
"RegDeleteKey",
"(",
"GetRootKey",
"(",
")",
",",
"(",
"(",
"GetAppPathsKey",
"(",
")",
"+",
"'\\\\'",
")",
"+",
"exeAlias",
")",
")",
"except",
"win32api",
".",
"error",
"as",
"exc",
":",
"import",
"winerror",
"if",
"(",
"exc",
".",
"winerror",
"!=",
"winerror",
".",
"ERROR_FILE_NOT_FOUND",
")",
":",
"raise",
"return"
] | unregister a . | train | false |
22,352 | def _api_config_set_apikey(output, kwargs):
cfg.api_key.set(config.create_api_key())
config.save_config()
return report(output, keyword='apikey', data=cfg.api_key())
| [
"def",
"_api_config_set_apikey",
"(",
"output",
",",
"kwargs",
")",
":",
"cfg",
".",
"api_key",
".",
"set",
"(",
"config",
".",
"create_api_key",
"(",
")",
")",
"config",
".",
"save_config",
"(",
")",
"return",
"report",
"(",
"output",
",",
"keyword",
"=",
"'apikey'",
",",
"data",
"=",
"cfg",
".",
"api_key",
"(",
")",
")"
] | api: accepts output . | train | false |
22,353 | def _gen_rules_port_max(port_max, top_bit):
rules = []
mask = (top_bit - 1)
while True:
if ((port_max & mask) == mask):
rules.append(_hex_format((port_max & (~ mask)), mask))
break
top_bit >>= 1
mask >>= 1
if ((port_max & top_bit) == top_bit):
rules.append(_hex_format(((port_max & (~ mask)) & (~ top_bit)), mask))
return rules
| [
"def",
"_gen_rules_port_max",
"(",
"port_max",
",",
"top_bit",
")",
":",
"rules",
"=",
"[",
"]",
"mask",
"=",
"(",
"top_bit",
"-",
"1",
")",
"while",
"True",
":",
"if",
"(",
"(",
"port_max",
"&",
"mask",
")",
"==",
"mask",
")",
":",
"rules",
".",
"append",
"(",
"_hex_format",
"(",
"(",
"port_max",
"&",
"(",
"~",
"mask",
")",
")",
",",
"mask",
")",
")",
"break",
"top_bit",
">>=",
"1",
"mask",
">>=",
"1",
"if",
"(",
"(",
"port_max",
"&",
"top_bit",
")",
"==",
"top_bit",
")",
":",
"rules",
".",
"append",
"(",
"_hex_format",
"(",
"(",
"(",
"port_max",
"&",
"(",
"~",
"mask",
")",
")",
"&",
"(",
"~",
"top_bit",
")",
")",
",",
"mask",
")",
")",
"return",
"rules"
] | encode a port range range(port_max & ~ . | train | false |
22,354 | @pytest.fixture
def samp_hub(request):
my_hub = SAMPHubServer()
my_hub.start()
request.addfinalizer(my_hub.stop)
| [
"@",
"pytest",
".",
"fixture",
"def",
"samp_hub",
"(",
"request",
")",
":",
"my_hub",
"=",
"SAMPHubServer",
"(",
")",
"my_hub",
".",
"start",
"(",
")",
"request",
".",
"addfinalizer",
"(",
"my_hub",
".",
"stop",
")"
] | a fixture that can be used by client tests that require a hub . | train | false |
22,355 | @plugin.route('/play/<url>')
def play_video_by_url(url):
quality = plugin.get_setting('quality')
url = api.get_media_stream_by_url(quality, url)
plugin.log.info(('Play Quality: %s' % quality))
plugin.log.info(('Playing url: %s' % url))
return plugin.set_resolved_url(url)
| [
"@",
"plugin",
".",
"route",
"(",
"'/play/<url>'",
")",
"def",
"play_video_by_url",
"(",
"url",
")",
":",
"quality",
"=",
"plugin",
".",
"get_setting",
"(",
"'quality'",
")",
"url",
"=",
"api",
".",
"get_media_stream_by_url",
"(",
"quality",
",",
"url",
")",
"plugin",
".",
"log",
".",
"info",
"(",
"(",
"'Play Quality: %s'",
"%",
"quality",
")",
")",
"plugin",
".",
"log",
".",
"info",
"(",
"(",
"'Playing url: %s'",
"%",
"url",
")",
")",
"return",
"plugin",
".",
"set_resolved_url",
"(",
"url",
")"
] | this method is used to play any shahid . | train | false |
22,356 | @Profiler.profile
def test_bulk_save(n):
session = Session(bind=engine)
session.bulk_save_objects([Customer(name=('customer name %d' % i), description=('customer description %d' % i)) for i in range(n)])
session.commit()
| [
"@",
"Profiler",
".",
"profile",
"def",
"test_bulk_save",
"(",
"n",
")",
":",
"session",
"=",
"Session",
"(",
"bind",
"=",
"engine",
")",
"session",
".",
"bulk_save_objects",
"(",
"[",
"Customer",
"(",
"name",
"=",
"(",
"'customer name %d'",
"%",
"i",
")",
",",
"description",
"=",
"(",
"'customer description %d'",
"%",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
")",
"session",
".",
"commit",
"(",
")"
] | individual insert/commit pairs using the "bulk" api . | train | false |
22,357 | def datasets_from_deployment(deployment):
for node in deployment.nodes.itervalues():
if (node.manifestations is None):
continue
for manifestation in node.manifestations.values():
if manifestation.primary:
(yield api_dataset_from_dataset_and_node(manifestation.dataset, node.uuid))
| [
"def",
"datasets_from_deployment",
"(",
"deployment",
")",
":",
"for",
"node",
"in",
"deployment",
".",
"nodes",
".",
"itervalues",
"(",
")",
":",
"if",
"(",
"node",
".",
"manifestations",
"is",
"None",
")",
":",
"continue",
"for",
"manifestation",
"in",
"node",
".",
"manifestations",
".",
"values",
"(",
")",
":",
"if",
"manifestation",
".",
"primary",
":",
"(",
"yield",
"api_dataset_from_dataset_and_node",
"(",
"manifestation",
".",
"dataset",
",",
"node",
".",
"uuid",
")",
")"
] | extract the primary datasets from the supplied deployment instance . | train | false |
22,358 | @contextmanager
def pending_warnings():
logger = logging.getLogger()
memhandler = MemoryHandler()
memhandler.setLevel(logging.WARNING)
try:
handlers = []
for handler in logger.handlers[:]:
if isinstance(handler, WarningStreamHandler):
logger.removeHandler(handler)
handlers.append(handler)
logger.addHandler(memhandler)
(yield memhandler)
finally:
logger.removeHandler(memhandler)
for handler in handlers:
logger.addHandler(handler)
memhandler.flushTo(logger)
| [
"@",
"contextmanager",
"def",
"pending_warnings",
"(",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"memhandler",
"=",
"MemoryHandler",
"(",
")",
"memhandler",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"try",
":",
"handlers",
"=",
"[",
"]",
"for",
"handler",
"in",
"logger",
".",
"handlers",
"[",
":",
"]",
":",
"if",
"isinstance",
"(",
"handler",
",",
"WarningStreamHandler",
")",
":",
"logger",
".",
"removeHandler",
"(",
"handler",
")",
"handlers",
".",
"append",
"(",
"handler",
")",
"logger",
".",
"addHandler",
"(",
"memhandler",
")",
"(",
"yield",
"memhandler",
")",
"finally",
":",
"logger",
".",
"removeHandler",
"(",
"memhandler",
")",
"for",
"handler",
"in",
"handlers",
":",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"memhandler",
".",
"flushTo",
"(",
"logger",
")"
] | contextmanager to pend logging warnings temporary . | train | false |
22,359 | def compile_info(session, vm_ref):
power_state = get_power_state(session, vm_ref)
max_mem = session.call_xenapi('VM.get_memory_static_max', vm_ref)
mem = session.call_xenapi('VM.get_memory_dynamic_max', vm_ref)
num_cpu = session.call_xenapi('VM.get_VCPUs_max', vm_ref)
return hardware.InstanceInfo(state=power_state, max_mem_kb=(int(max_mem) >> 10), mem_kb=(int(mem) >> 10), num_cpu=num_cpu)
| [
"def",
"compile_info",
"(",
"session",
",",
"vm_ref",
")",
":",
"power_state",
"=",
"get_power_state",
"(",
"session",
",",
"vm_ref",
")",
"max_mem",
"=",
"session",
".",
"call_xenapi",
"(",
"'VM.get_memory_static_max'",
",",
"vm_ref",
")",
"mem",
"=",
"session",
".",
"call_xenapi",
"(",
"'VM.get_memory_dynamic_max'",
",",
"vm_ref",
")",
"num_cpu",
"=",
"session",
".",
"call_xenapi",
"(",
"'VM.get_VCPUs_max'",
",",
"vm_ref",
")",
"return",
"hardware",
".",
"InstanceInfo",
"(",
"state",
"=",
"power_state",
",",
"max_mem_kb",
"=",
"(",
"int",
"(",
"max_mem",
")",
">>",
"10",
")",
",",
"mem_kb",
"=",
"(",
"int",
"(",
"mem",
")",
">>",
"10",
")",
",",
"num_cpu",
"=",
"num_cpu",
")"
] | fill record with vm status information . | train | false |
22,361 | def get_text_from_files(vision, index, input_filenames):
texts = vision.detect_text(input_filenames)
for (filename, text) in texts.items():
extract_descriptions(filename, index, text)
| [
"def",
"get_text_from_files",
"(",
"vision",
",",
"index",
",",
"input_filenames",
")",
":",
"texts",
"=",
"vision",
".",
"detect_text",
"(",
"input_filenames",
")",
"for",
"(",
"filename",
",",
"text",
")",
"in",
"texts",
".",
"items",
"(",
")",
":",
"extract_descriptions",
"(",
"filename",
",",
"index",
",",
"text",
")"
] | call the vision api on a file and index the results . | train | false |
22,362 | def flow_hierarchy(G, weight=None):
if (not G.is_directed()):
raise nx.NetworkXError('G must be a digraph in flow_heirarchy')
scc = nx.strongly_connected_components(G)
return (1.0 - (sum((G.subgraph(c).size(weight) for c in scc)) / float(G.size(weight))))
| [
"def",
"flow_hierarchy",
"(",
"G",
",",
"weight",
"=",
"None",
")",
":",
"if",
"(",
"not",
"G",
".",
"is_directed",
"(",
")",
")",
":",
"raise",
"nx",
".",
"NetworkXError",
"(",
"'G must be a digraph in flow_heirarchy'",
")",
"scc",
"=",
"nx",
".",
"strongly_connected_components",
"(",
"G",
")",
"return",
"(",
"1.0",
"-",
"(",
"sum",
"(",
"(",
"G",
".",
"subgraph",
"(",
"c",
")",
".",
"size",
"(",
"weight",
")",
"for",
"c",
"in",
"scc",
")",
")",
"/",
"float",
"(",
"G",
".",
"size",
"(",
"weight",
")",
")",
")",
")"
] | returns the flow hierarchy of a directed network . | train | false |
22,363 | def build_dqn(num_actions, action_repeat):
inputs = tf.placeholder(tf.float32, [None, action_repeat, 84, 84])
net = tf.transpose(inputs, [0, 2, 3, 1])
net = tflearn.conv_2d(net, 32, 8, strides=4, activation='relu')
net = tflearn.conv_2d(net, 64, 4, strides=2, activation='relu')
net = tflearn.fully_connected(net, 256, activation='relu')
q_values = tflearn.fully_connected(net, num_actions)
return (inputs, q_values)
| [
"def",
"build_dqn",
"(",
"num_actions",
",",
"action_repeat",
")",
":",
"inputs",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"[",
"None",
",",
"action_repeat",
",",
"84",
",",
"84",
"]",
")",
"net",
"=",
"tf",
".",
"transpose",
"(",
"inputs",
",",
"[",
"0",
",",
"2",
",",
"3",
",",
"1",
"]",
")",
"net",
"=",
"tflearn",
".",
"conv_2d",
"(",
"net",
",",
"32",
",",
"8",
",",
"strides",
"=",
"4",
",",
"activation",
"=",
"'relu'",
")",
"net",
"=",
"tflearn",
".",
"conv_2d",
"(",
"net",
",",
"64",
",",
"4",
",",
"strides",
"=",
"2",
",",
"activation",
"=",
"'relu'",
")",
"net",
"=",
"tflearn",
".",
"fully_connected",
"(",
"net",
",",
"256",
",",
"activation",
"=",
"'relu'",
")",
"q_values",
"=",
"tflearn",
".",
"fully_connected",
"(",
"net",
",",
"num_actions",
")",
"return",
"(",
"inputs",
",",
"q_values",
")"
] | building a dqn . | train | false |
22,365 | @pytest.mark.cmd
@pytest.mark.django_db
def test_import_onefile_with_user(capfd, tmpdir, site_users):
from pootle_store.models import Store
user = site_users['user'].username
p = tmpdir.mkdir('sub').join('store0.po')
store = Store.objects.get(pootle_path='/language0/project0/store0.po')
p.write(str(get_translated_storefile(store)))
call_command('import', ('--user=%s' % user), os.path.join(p.dirname, p.basename))
(out, err) = capfd.readouterr()
assert (user in out)
assert ('[update]' in err)
assert ('units in /language0/project0/store0.po' in err)
| [
"@",
"pytest",
".",
"mark",
".",
"cmd",
"@",
"pytest",
".",
"mark",
".",
"django_db",
"def",
"test_import_onefile_with_user",
"(",
"capfd",
",",
"tmpdir",
",",
"site_users",
")",
":",
"from",
"pootle_store",
".",
"models",
"import",
"Store",
"user",
"=",
"site_users",
"[",
"'user'",
"]",
".",
"username",
"p",
"=",
"tmpdir",
".",
"mkdir",
"(",
"'sub'",
")",
".",
"join",
"(",
"'store0.po'",
")",
"store",
"=",
"Store",
".",
"objects",
".",
"get",
"(",
"pootle_path",
"=",
"'/language0/project0/store0.po'",
")",
"p",
".",
"write",
"(",
"str",
"(",
"get_translated_storefile",
"(",
"store",
")",
")",
")",
"call_command",
"(",
"'import'",
",",
"(",
"'--user=%s'",
"%",
"user",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"p",
".",
"dirname",
",",
"p",
".",
"basename",
")",
")",
"(",
"out",
",",
"err",
")",
"=",
"capfd",
".",
"readouterr",
"(",
")",
"assert",
"(",
"user",
"in",
"out",
")",
"assert",
"(",
"'[update]'",
"in",
"err",
")",
"assert",
"(",
"'units in /language0/project0/store0.po'",
"in",
"err",
")"
] | load an one unit po file . | train | false |
22,368 | def get_pricing_steps_for_products(context, products):
(mod, ctx) = _get_module_and_context(context)
steps = mod.get_pricing_steps_for_products(ctx, products)
for module in get_discount_modules():
steps = module.get_pricing_steps_for_products(ctx, products, steps)
return steps
| [
"def",
"get_pricing_steps_for_products",
"(",
"context",
",",
"products",
")",
":",
"(",
"mod",
",",
"ctx",
")",
"=",
"_get_module_and_context",
"(",
"context",
")",
"steps",
"=",
"mod",
".",
"get_pricing_steps_for_products",
"(",
"ctx",
",",
"products",
")",
"for",
"module",
"in",
"get_discount_modules",
"(",
")",
":",
"steps",
"=",
"module",
".",
"get_pricing_steps_for_products",
"(",
"ctx",
",",
"products",
",",
"steps",
")",
"return",
"steps"
] | get pricing steps for a bunch of products . | train | false |
22,369 | def decorate_urlpatterns(urlpatterns, decorator):
for pattern in urlpatterns:
if hasattr(pattern, u'url_patterns'):
decorate_urlpatterns(pattern.url_patterns, decorator)
if (DJANGO_VERSION < (1, 10)):
if hasattr(pattern, u'_callback'):
pattern._callback = update_wrapper(decorator(pattern.callback), pattern.callback)
elif getattr(pattern, u'callback', None):
pattern.callback = update_wrapper(decorator(pattern.callback), pattern.callback)
return urlpatterns
| [
"def",
"decorate_urlpatterns",
"(",
"urlpatterns",
",",
"decorator",
")",
":",
"for",
"pattern",
"in",
"urlpatterns",
":",
"if",
"hasattr",
"(",
"pattern",
",",
"u'url_patterns'",
")",
":",
"decorate_urlpatterns",
"(",
"pattern",
".",
"url_patterns",
",",
"decorator",
")",
"if",
"(",
"DJANGO_VERSION",
"<",
"(",
"1",
",",
"10",
")",
")",
":",
"if",
"hasattr",
"(",
"pattern",
",",
"u'_callback'",
")",
":",
"pattern",
".",
"_callback",
"=",
"update_wrapper",
"(",
"decorator",
"(",
"pattern",
".",
"callback",
")",
",",
"pattern",
".",
"callback",
")",
"elif",
"getattr",
"(",
"pattern",
",",
"u'callback'",
",",
"None",
")",
":",
"pattern",
".",
"callback",
"=",
"update_wrapper",
"(",
"decorator",
"(",
"pattern",
".",
"callback",
")",
",",
"pattern",
".",
"callback",
")",
"return",
"urlpatterns"
] | decorate all the views in the passed urlpatterns list with the given decorator . | train | false |
22,370 | def reorder_plugins(placeholder, parent_id, language, order):
plugins = CMSPlugin.objects.filter(parent=parent_id, placeholder=placeholder, language=language).order_by('position')
order = list(order)
if order:
plugins = plugins.filter(pk__in=order)
for plugin in plugins.iterator():
position = order.index(plugin.pk)
plugin.update(position=position)
else:
for (position, plugin) in enumerate(plugins.iterator()):
plugin.update(position=position)
return plugins
| [
"def",
"reorder_plugins",
"(",
"placeholder",
",",
"parent_id",
",",
"language",
",",
"order",
")",
":",
"plugins",
"=",
"CMSPlugin",
".",
"objects",
".",
"filter",
"(",
"parent",
"=",
"parent_id",
",",
"placeholder",
"=",
"placeholder",
",",
"language",
"=",
"language",
")",
".",
"order_by",
"(",
"'position'",
")",
"order",
"=",
"list",
"(",
"order",
")",
"if",
"order",
":",
"plugins",
"=",
"plugins",
".",
"filter",
"(",
"pk__in",
"=",
"order",
")",
"for",
"plugin",
"in",
"plugins",
".",
"iterator",
"(",
")",
":",
"position",
"=",
"order",
".",
"index",
"(",
"plugin",
".",
"pk",
")",
"plugin",
".",
"update",
"(",
"position",
"=",
"position",
")",
"else",
":",
"for",
"(",
"position",
",",
"plugin",
")",
"in",
"enumerate",
"(",
"plugins",
".",
"iterator",
"(",
")",
")",
":",
"plugin",
".",
"update",
"(",
"position",
"=",
"position",
")",
"return",
"plugins"
] | reorder the plugins according the order parameter . | train | false |
22,372 | @treeio_login_required
@handle_response_format
@_process_mass_form
def type_view(request, type_id, response_format='html'):
item_type = get_object_or_404(ItemType, pk=type_id)
if (not request.user.profile.has_permission(item_type)):
return user_denied(request, message="You don't have access to this Item Type", response_format=response_format)
query = Q(item_type=item_type)
if request.GET:
query = (query & _get_filter_query(request.GET))
items = Object.filter_by_request(request, Item.objects.filter(query).order_by('name'))
filters = FilterForm(request.user.profile, ['item_type'], request.GET)
context = _get_default_context(request)
context.update({'items': items, 'filters': filters, 'item_type': item_type})
return render_to_response('infrastructure/item_type_view', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"treeio_login_required",
"@",
"handle_response_format",
"@",
"_process_mass_form",
"def",
"type_view",
"(",
"request",
",",
"type_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"item_type",
"=",
"get_object_or_404",
"(",
"ItemType",
",",
"pk",
"=",
"type_id",
")",
"if",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"has_permission",
"(",
"item_type",
")",
")",
":",
"return",
"user_denied",
"(",
"request",
",",
"message",
"=",
"\"You don't have access to this Item Type\"",
",",
"response_format",
"=",
"response_format",
")",
"query",
"=",
"Q",
"(",
"item_type",
"=",
"item_type",
")",
"if",
"request",
".",
"GET",
":",
"query",
"=",
"(",
"query",
"&",
"_get_filter_query",
"(",
"request",
".",
"GET",
")",
")",
"items",
"=",
"Object",
".",
"filter_by_request",
"(",
"request",
",",
"Item",
".",
"objects",
".",
"filter",
"(",
"query",
")",
".",
"order_by",
"(",
"'name'",
")",
")",
"filters",
"=",
"FilterForm",
"(",
"request",
".",
"user",
".",
"profile",
",",
"[",
"'item_type'",
"]",
",",
"request",
".",
"GET",
")",
"context",
"=",
"_get_default_context",
"(",
"request",
")",
"context",
".",
"update",
"(",
"{",
"'items'",
":",
"items",
",",
"'filters'",
":",
"filters",
",",
"'item_type'",
":",
"item_type",
"}",
")",
"return",
"render_to_response",
"(",
"'infrastructure/item_type_view'",
",",
"context",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | contacts by type . | train | false |
22,373 | def pbkdf2(password, salt, iterations, dklen=0, digest=None):
assert (iterations > 0)
if (not digest):
digest = hashlib.sha256
password = force_bytes(password)
salt = force_bytes(salt)
hlen = digest().digest_size
if (not dklen):
dklen = hlen
if (dklen > (((2 ** 32) - 1) * hlen)):
raise OverflowError(u'dklen too big')
l = (- ((- dklen) // hlen))
r = (dklen - ((l - 1) * hlen))
hex_format_string = (u'%%0%ix' % (hlen * 2))
(inner, outer) = (digest(), digest())
if (len(password) > inner.block_size):
password = digest(password).digest()
password += ('\x00' * (inner.block_size - len(password)))
inner.update(password.translate(hmac.trans_36))
outer.update(password.translate(hmac.trans_5C))
def F(i):
def U():
u = (salt + struct.pack('>I', i))
for j in xrange(int(iterations)):
(dig1, dig2) = (inner.copy(), outer.copy())
dig1.update(u)
dig2.update(dig1.digest())
u = dig2.digest()
(yield _bin_to_long(u))
return _long_to_bin(reduce(operator.xor, U()), hex_format_string)
T = [F(x) for x in range(1, (l + 1))]
return (''.join(T[:(-1)]) + T[(-1)][:r])
| [
"def",
"pbkdf2",
"(",
"password",
",",
"salt",
",",
"iterations",
",",
"dklen",
"=",
"0",
",",
"digest",
"=",
"None",
")",
":",
"assert",
"(",
"iterations",
">",
"0",
")",
"if",
"(",
"not",
"digest",
")",
":",
"digest",
"=",
"hashlib",
".",
"sha256",
"password",
"=",
"force_bytes",
"(",
"password",
")",
"salt",
"=",
"force_bytes",
"(",
"salt",
")",
"hlen",
"=",
"digest",
"(",
")",
".",
"digest_size",
"if",
"(",
"not",
"dklen",
")",
":",
"dklen",
"=",
"hlen",
"if",
"(",
"dklen",
">",
"(",
"(",
"(",
"2",
"**",
"32",
")",
"-",
"1",
")",
"*",
"hlen",
")",
")",
":",
"raise",
"OverflowError",
"(",
"u'dklen too big'",
")",
"l",
"=",
"(",
"-",
"(",
"(",
"-",
"dklen",
")",
"//",
"hlen",
")",
")",
"r",
"=",
"(",
"dklen",
"-",
"(",
"(",
"l",
"-",
"1",
")",
"*",
"hlen",
")",
")",
"hex_format_string",
"=",
"(",
"u'%%0%ix'",
"%",
"(",
"hlen",
"*",
"2",
")",
")",
"(",
"inner",
",",
"outer",
")",
"=",
"(",
"digest",
"(",
")",
",",
"digest",
"(",
")",
")",
"if",
"(",
"len",
"(",
"password",
")",
">",
"inner",
".",
"block_size",
")",
":",
"password",
"=",
"digest",
"(",
"password",
")",
".",
"digest",
"(",
")",
"password",
"+=",
"(",
"'\\x00'",
"*",
"(",
"inner",
".",
"block_size",
"-",
"len",
"(",
"password",
")",
")",
")",
"inner",
".",
"update",
"(",
"password",
".",
"translate",
"(",
"hmac",
".",
"trans_36",
")",
")",
"outer",
".",
"update",
"(",
"password",
".",
"translate",
"(",
"hmac",
".",
"trans_5C",
")",
")",
"def",
"F",
"(",
"i",
")",
":",
"def",
"U",
"(",
")",
":",
"u",
"=",
"(",
"salt",
"+",
"struct",
".",
"pack",
"(",
"'>I'",
",",
"i",
")",
")",
"for",
"j",
"in",
"xrange",
"(",
"int",
"(",
"iterations",
")",
")",
":",
"(",
"dig1",
",",
"dig2",
")",
"=",
"(",
"inner",
".",
"copy",
"(",
")",
",",
"outer",
".",
"copy",
"(",
")",
")",
"dig1",
".",
"update",
"(",
"u",
")",
"dig2",
".",
"update",
"(",
"dig1",
".",
"digest",
"(",
")",
")",
"u",
"=",
"dig2",
".",
"digest",
"(",
")",
"(",
"yield",
"_bin_to_long",
"(",
"u",
")",
")",
"return",
"_long_to_bin",
"(",
"reduce",
"(",
"operator",
".",
"xor",
",",
"U",
"(",
")",
")",
",",
"hex_format_string",
")",
"T",
"=",
"[",
"F",
"(",
"x",
")",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"(",
"l",
"+",
"1",
")",
")",
"]",
"return",
"(",
"''",
".",
"join",
"(",
"T",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
"+",
"T",
"[",
"(",
"-",
"1",
")",
"]",
"[",
":",
"r",
"]",
")"
] | module function to hash a password according to the pbkdf2 specification . | train | false |
22,374 | def assert_not_instance_of(expected, actual, msg=None):
assert (not isinstance(actual, expected, msg))
| [
"def",
"assert_not_instance_of",
"(",
"expected",
",",
"actual",
",",
"msg",
"=",
"None",
")",
":",
"assert",
"(",
"not",
"isinstance",
"(",
"actual",
",",
"expected",
",",
"msg",
")",
")"
] | verify that object is not an instance of expected . | train | false |
22,375 | def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
Loader.add_path_resolver(tag, path, kind)
Dumper.add_path_resolver(tag, path, kind)
| [
"def",
"add_path_resolver",
"(",
"tag",
",",
"path",
",",
"kind",
"=",
"None",
",",
"Loader",
"=",
"Loader",
",",
"Dumper",
"=",
"Dumper",
")",
":",
"Loader",
".",
"add_path_resolver",
"(",
"tag",
",",
"path",
",",
"kind",
")",
"Dumper",
".",
"add_path_resolver",
"(",
"tag",
",",
"path",
",",
"kind",
")"
] | add a path based resolver for the given tag . | train | true |
22,376 | def StartSerialServer(context=None, identity=None, **kwargs):
framer = kwargs.pop('framer', ModbusAsciiFramer)
server = ModbusSerialServer(context, framer, identity, **kwargs)
server.serve_forever()
| [
"def",
"StartSerialServer",
"(",
"context",
"=",
"None",
",",
"identity",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"framer",
"=",
"kwargs",
".",
"pop",
"(",
"'framer'",
",",
"ModbusAsciiFramer",
")",
"server",
"=",
"ModbusSerialServer",
"(",
"context",
",",
"framer",
",",
"identity",
",",
"**",
"kwargs",
")",
"server",
".",
"serve_forever",
"(",
")"
] | helper method to start the modbus async serial server . | train | false |
22,379 | def task_notify(form):
vars = form.vars
pe_id = vars.pe_id
if (not pe_id):
return
user = current.auth.user
if (user and (user.pe_id == pe_id)):
return
if (int(vars.status) not in current.response.s3.project_task_active_statuses):
return
if ((form.record is None) or (int(pe_id) != form.record.pe_id)):
settings = current.deployment_settings
if settings.has_module('msg'):
subject = ('%s: Task assigned to you' % settings.get_system_name_short())
url = ('%s%s' % (settings.get_base_public_url(), URL(c='project', f='task', args=vars.id)))
priority = current.s3db.project_task.priority.represent(int(vars.priority))
message = ('You have been assigned a Task:\n\n%s\n\n%s\n\n%s\n\n%s' % (url, ('%s priority' % priority), vars.name, (vars.description or '')))
current.msg.send_by_pe_id(pe_id, subject, message)
return
| [
"def",
"task_notify",
"(",
"form",
")",
":",
"vars",
"=",
"form",
".",
"vars",
"pe_id",
"=",
"vars",
".",
"pe_id",
"if",
"(",
"not",
"pe_id",
")",
":",
"return",
"user",
"=",
"current",
".",
"auth",
".",
"user",
"if",
"(",
"user",
"and",
"(",
"user",
".",
"pe_id",
"==",
"pe_id",
")",
")",
":",
"return",
"if",
"(",
"int",
"(",
"vars",
".",
"status",
")",
"not",
"in",
"current",
".",
"response",
".",
"s3",
".",
"project_task_active_statuses",
")",
":",
"return",
"if",
"(",
"(",
"form",
".",
"record",
"is",
"None",
")",
"or",
"(",
"int",
"(",
"pe_id",
")",
"!=",
"form",
".",
"record",
".",
"pe_id",
")",
")",
":",
"settings",
"=",
"current",
".",
"deployment_settings",
"if",
"settings",
".",
"has_module",
"(",
"'msg'",
")",
":",
"subject",
"=",
"(",
"'%s: Task assigned to you'",
"%",
"settings",
".",
"get_system_name_short",
"(",
")",
")",
"url",
"=",
"(",
"'%s%s'",
"%",
"(",
"settings",
".",
"get_base_public_url",
"(",
")",
",",
"URL",
"(",
"c",
"=",
"'project'",
",",
"f",
"=",
"'task'",
",",
"args",
"=",
"vars",
".",
"id",
")",
")",
")",
"priority",
"=",
"current",
".",
"s3db",
".",
"project_task",
".",
"priority",
".",
"represent",
"(",
"int",
"(",
"vars",
".",
"priority",
")",
")",
"message",
"=",
"(",
"'You have been assigned a Task:\\n\\n%s\\n\\n%s\\n\\n%s\\n\\n%s'",
"%",
"(",
"url",
",",
"(",
"'%s priority'",
"%",
"priority",
")",
",",
"vars",
".",
"name",
",",
"(",
"vars",
".",
"description",
"or",
"''",
")",
")",
")",
"current",
".",
"msg",
".",
"send_by_pe_id",
"(",
"pe_id",
",",
"subject",
",",
"message",
")",
"return"
] | if the task is assigned to someone then notify them . | train | false |
22,380 | def _section_cohort_management(course, access):
course_key = course.id
ccx_enabled = hasattr(course_key, 'ccx')
section_data = {'section_key': 'cohort_management', 'section_display_name': _('Cohorts'), 'access': access, 'ccx_is_enabled': ccx_enabled, 'course_cohort_settings_url': reverse('course_cohort_settings', kwargs={'course_key_string': unicode(course_key)}), 'cohorts_url': reverse('cohorts', kwargs={'course_key_string': unicode(course_key)}), 'upload_cohorts_csv_url': reverse('add_users_to_cohorts', kwargs={'course_id': unicode(course_key)}), 'discussion_topics_url': reverse('cohort_discussion_topics', kwargs={'course_key_string': unicode(course_key)}), 'verified_track_cohorting_url': reverse('verified_track_cohorting', kwargs={'course_key_string': unicode(course_key)})}
return section_data
| [
"def",
"_section_cohort_management",
"(",
"course",
",",
"access",
")",
":",
"course_key",
"=",
"course",
".",
"id",
"ccx_enabled",
"=",
"hasattr",
"(",
"course_key",
",",
"'ccx'",
")",
"section_data",
"=",
"{",
"'section_key'",
":",
"'cohort_management'",
",",
"'section_display_name'",
":",
"_",
"(",
"'Cohorts'",
")",
",",
"'access'",
":",
"access",
",",
"'ccx_is_enabled'",
":",
"ccx_enabled",
",",
"'course_cohort_settings_url'",
":",
"reverse",
"(",
"'course_cohort_settings'",
",",
"kwargs",
"=",
"{",
"'course_key_string'",
":",
"unicode",
"(",
"course_key",
")",
"}",
")",
",",
"'cohorts_url'",
":",
"reverse",
"(",
"'cohorts'",
",",
"kwargs",
"=",
"{",
"'course_key_string'",
":",
"unicode",
"(",
"course_key",
")",
"}",
")",
",",
"'upload_cohorts_csv_url'",
":",
"reverse",
"(",
"'add_users_to_cohorts'",
",",
"kwargs",
"=",
"{",
"'course_id'",
":",
"unicode",
"(",
"course_key",
")",
"}",
")",
",",
"'discussion_topics_url'",
":",
"reverse",
"(",
"'cohort_discussion_topics'",
",",
"kwargs",
"=",
"{",
"'course_key_string'",
":",
"unicode",
"(",
"course_key",
")",
"}",
")",
",",
"'verified_track_cohorting_url'",
":",
"reverse",
"(",
"'verified_track_cohorting'",
",",
"kwargs",
"=",
"{",
"'course_key_string'",
":",
"unicode",
"(",
"course_key",
")",
"}",
")",
"}",
"return",
"section_data"
] | provide data for the corresponding cohort management section . | train | false |
22,381 | def setUnjellyableForClassTree(module, baseClass, prefix=None):
if (prefix is None):
prefix = module.__name__
if prefix:
prefix = ('%s.' % prefix)
for i in dir(module):
i_ = getattr(module, i)
if (type(i_) == types.ClassType):
if issubclass(i_, baseClass):
setUnjellyableForClass(('%s%s' % (prefix, i)), i_)
| [
"def",
"setUnjellyableForClassTree",
"(",
"module",
",",
"baseClass",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"(",
"prefix",
"is",
"None",
")",
":",
"prefix",
"=",
"module",
".",
"__name__",
"if",
"prefix",
":",
"prefix",
"=",
"(",
"'%s.'",
"%",
"prefix",
")",
"for",
"i",
"in",
"dir",
"(",
"module",
")",
":",
"i_",
"=",
"getattr",
"(",
"module",
",",
"i",
")",
"if",
"(",
"type",
"(",
"i_",
")",
"==",
"types",
".",
"ClassType",
")",
":",
"if",
"issubclass",
"(",
"i_",
",",
"baseClass",
")",
":",
"setUnjellyableForClass",
"(",
"(",
"'%s%s'",
"%",
"(",
"prefix",
",",
"i",
")",
")",
",",
"i_",
")"
] | set all classes in a module derived from c{baseclass} as copiers for a corresponding remote class . | train | false |
22,382 | def create_import_job(task):
ij = ImportJob(task=task, user=g.user)
save_to_db(ij, 'Import job saved')
| [
"def",
"create_import_job",
"(",
"task",
")",
":",
"ij",
"=",
"ImportJob",
"(",
"task",
"=",
"task",
",",
"user",
"=",
"g",
".",
"user",
")",
"save_to_db",
"(",
"ij",
",",
"'Import job saved'",
")"
] | create import record in db . | train | false |
22,384 | def find_number(s):
r = re.search('[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?', s)
if (r is not None):
return r.span(0)
return None
| [
"def",
"find_number",
"(",
"s",
")",
":",
"r",
"=",
"re",
".",
"search",
"(",
"'[+-]?(\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)([eE][+-]?\\\\d+)?'",
",",
"s",
")",
"if",
"(",
"r",
"is",
"not",
"None",
")",
":",
"return",
"r",
".",
"span",
"(",
"0",
")",
"return",
"None"
] | returns none if there are no numbers in the string . | train | false |
22,385 | def tmul(lin_op, value, is_abs=False):
if (lin_op.type is lo.VARIABLE):
return {lin_op.data: value}
elif (lin_op.type is lo.NO_OP):
return {}
else:
if is_abs:
result = op_abs_tmul(lin_op, value)
else:
result = op_tmul(lin_op, value)
result_dicts = []
for arg in lin_op.args:
result_dicts.append(tmul(arg, result, is_abs))
return sum_dicts(result_dicts)
| [
"def",
"tmul",
"(",
"lin_op",
",",
"value",
",",
"is_abs",
"=",
"False",
")",
":",
"if",
"(",
"lin_op",
".",
"type",
"is",
"lo",
".",
"VARIABLE",
")",
":",
"return",
"{",
"lin_op",
".",
"data",
":",
"value",
"}",
"elif",
"(",
"lin_op",
".",
"type",
"is",
"lo",
".",
"NO_OP",
")",
":",
"return",
"{",
"}",
"else",
":",
"if",
"is_abs",
":",
"result",
"=",
"op_abs_tmul",
"(",
"lin_op",
",",
"value",
")",
"else",
":",
"result",
"=",
"op_tmul",
"(",
"lin_op",
",",
"value",
")",
"result_dicts",
"=",
"[",
"]",
"for",
"arg",
"in",
"lin_op",
".",
"args",
":",
"result_dicts",
".",
"append",
"(",
"tmul",
"(",
"arg",
",",
"result",
",",
"is_abs",
")",
")",
"return",
"sum_dicts",
"(",
"result_dicts",
")"
] | multiply the transpose of the expression tree by a vector . | train | false |
22,386 | def get_deployment_id():
try:
acc = appscale_info.get_appcontroller_client()
if acc.deployment_id_exists():
return acc.get_deployment_id()
except AppControllerException:
logging.exception('AppControllerException while querying for deployment ID.')
return None
| [
"def",
"get_deployment_id",
"(",
")",
":",
"try",
":",
"acc",
"=",
"appscale_info",
".",
"get_appcontroller_client",
"(",
")",
"if",
"acc",
".",
"deployment_id_exists",
"(",
")",
":",
"return",
"acc",
".",
"get_deployment_id",
"(",
")",
"except",
"AppControllerException",
":",
"logging",
".",
"exception",
"(",
"'AppControllerException while querying for deployment ID.'",
")",
"return",
"None"
] | retrieves the deployment id for this appscale deployment . | train | false |
22,388 | def interface_decorator(decorator_name, interface, method_decorator, *args, **kwargs):
for method_name in interface.names():
if (not isinstance(interface[method_name], Method)):
raise TypeError('{} does not support interfaces with non-methods attributes'.format(decorator_name))
def class_decorator(cls):
for name in interface.names():
setattr(cls, name, method_decorator(name, *args, **kwargs))
return cls
return class_decorator
| [
"def",
"interface_decorator",
"(",
"decorator_name",
",",
"interface",
",",
"method_decorator",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"for",
"method_name",
"in",
"interface",
".",
"names",
"(",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"interface",
"[",
"method_name",
"]",
",",
"Method",
")",
")",
":",
"raise",
"TypeError",
"(",
"'{} does not support interfaces with non-methods attributes'",
".",
"format",
"(",
"decorator_name",
")",
")",
"def",
"class_decorator",
"(",
"cls",
")",
":",
"for",
"name",
"in",
"interface",
".",
"names",
"(",
")",
":",
"setattr",
"(",
"cls",
",",
"name",
",",
"method_decorator",
"(",
"name",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
"return",
"cls",
"return",
"class_decorator"
] | create a class decorator which applies a method decorator to each method of an interface . | train | false |
22,389 | def natural(text):
def num(s):
'Convert text segment to int if necessary'
return (int(s) if s.isdigit() else s)
return [num(s) for s in re.split('(\\d+)', str(text))]
| [
"def",
"natural",
"(",
"text",
")",
":",
"def",
"num",
"(",
"s",
")",
":",
"return",
"(",
"int",
"(",
"s",
")",
"if",
"s",
".",
"isdigit",
"(",
")",
"else",
"s",
")",
"return",
"[",
"num",
"(",
"s",
")",
"for",
"s",
"in",
"re",
".",
"split",
"(",
"'(\\\\d+)'",
",",
"str",
"(",
"text",
")",
")",
"]"
] | restrict input type to the natural numbers . | train | false |
22,390 | @cleanup
def test_SymLogNorm_colorbar():
norm = mcolors.SymLogNorm(0.1, vmin=(-1), vmax=1, linscale=1)
fig = plt.figure()
cbar = mcolorbar.ColorbarBase(fig.add_subplot(111), norm=norm)
plt.close(fig)
| [
"@",
"cleanup",
"def",
"test_SymLogNorm_colorbar",
"(",
")",
":",
"norm",
"=",
"mcolors",
".",
"SymLogNorm",
"(",
"0.1",
",",
"vmin",
"=",
"(",
"-",
"1",
")",
",",
"vmax",
"=",
"1",
",",
"linscale",
"=",
"1",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"cbar",
"=",
"mcolorbar",
".",
"ColorbarBase",
"(",
"fig",
".",
"add_subplot",
"(",
"111",
")",
",",
"norm",
"=",
"norm",
")",
"plt",
".",
"close",
"(",
"fig",
")"
] | test un-called symlognorm in a colorbar . | train | false |
22,392 | def _default_template_ctx_processor():
reqctx = _request_ctx_stack.top
appctx = _app_ctx_stack.top
rv = {}
if (appctx is not None):
rv['g'] = appctx.g
if (reqctx is not None):
rv['request'] = reqctx.request
rv['session'] = reqctx.session
return rv
| [
"def",
"_default_template_ctx_processor",
"(",
")",
":",
"reqctx",
"=",
"_request_ctx_stack",
".",
"top",
"appctx",
"=",
"_app_ctx_stack",
".",
"top",
"rv",
"=",
"{",
"}",
"if",
"(",
"appctx",
"is",
"not",
"None",
")",
":",
"rv",
"[",
"'g'",
"]",
"=",
"appctx",
".",
"g",
"if",
"(",
"reqctx",
"is",
"not",
"None",
")",
":",
"rv",
"[",
"'request'",
"]",
"=",
"reqctx",
".",
"request",
"rv",
"[",
"'session'",
"]",
"=",
"reqctx",
".",
"session",
"return",
"rv"
] | default template context processor . | train | true |
22,393 | def print_mathml(expr, **settings):
s = MathMLPrinter(settings)
xml = s._print(sympify(expr))
s.apply_patch()
pretty_xml = xml.toprettyxml()
s.restore_patch()
print(pretty_xml)
| [
"def",
"print_mathml",
"(",
"expr",
",",
"**",
"settings",
")",
":",
"s",
"=",
"MathMLPrinter",
"(",
"settings",
")",
"xml",
"=",
"s",
".",
"_print",
"(",
"sympify",
"(",
"expr",
")",
")",
"s",
".",
"apply_patch",
"(",
")",
"pretty_xml",
"=",
"xml",
".",
"toprettyxml",
"(",
")",
"s",
".",
"restore_patch",
"(",
")",
"print",
"(",
"pretty_xml",
")"
] | prints a pretty representation of the mathml code for expr examples . | train | false |
22,395 | def selectionsort(a):
for i in range(len(a)):
min = i
for j in range(i, len(a)):
if (a[j] < a[min]):
min = j
(a[i], a[min]) = (a[min], a[i])
return a
| [
"def",
"selectionsort",
"(",
"a",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
":",
"min",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"i",
",",
"len",
"(",
"a",
")",
")",
":",
"if",
"(",
"a",
"[",
"j",
"]",
"<",
"a",
"[",
"min",
"]",
")",
":",
"min",
"=",
"j",
"(",
"a",
"[",
"i",
"]",
",",
"a",
"[",
"min",
"]",
")",
"=",
"(",
"a",
"[",
"min",
"]",
",",
"a",
"[",
"i",
"]",
")",
"return",
"a"
] | selectionsort implementation . | train | false |
22,396 | @contextmanager
def attempt_effective_uid(username, suppress_errors=False):
original_euid = os.geteuid()
new_euid = pwd.getpwnam(username).pw_uid
restore_euid = False
if (original_euid != new_euid):
try:
os.seteuid(new_euid)
except OSError as e:
if ((not suppress_errors) or (e.errno != 1)):
raise
else:
restore_euid = True
try:
(yield)
finally:
if restore_euid:
os.seteuid(original_euid)
| [
"@",
"contextmanager",
"def",
"attempt_effective_uid",
"(",
"username",
",",
"suppress_errors",
"=",
"False",
")",
":",
"original_euid",
"=",
"os",
".",
"geteuid",
"(",
")",
"new_euid",
"=",
"pwd",
".",
"getpwnam",
"(",
"username",
")",
".",
"pw_uid",
"restore_euid",
"=",
"False",
"if",
"(",
"original_euid",
"!=",
"new_euid",
")",
":",
"try",
":",
"os",
".",
"seteuid",
"(",
"new_euid",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"(",
"(",
"not",
"suppress_errors",
")",
"or",
"(",
"e",
".",
"errno",
"!=",
"1",
")",
")",
":",
"raise",
"else",
":",
"restore_euid",
"=",
"True",
"try",
":",
"(",
"yield",
")",
"finally",
":",
"if",
"restore_euid",
":",
"os",
".",
"seteuid",
"(",
"original_euid",
")"
] | a context manager to temporarily change the effective user id . | train | false |
22,398 | def approx_point_big(src, dest):
xy = src.read((2 * 8))
dest.write(xy[:5])
dest.write('\x00\x00\x00')
dest.write(xy[8:13])
dest.write('\x00\x00\x00')
| [
"def",
"approx_point_big",
"(",
"src",
",",
"dest",
")",
":",
"xy",
"=",
"src",
".",
"read",
"(",
"(",
"2",
"*",
"8",
")",
")",
"dest",
".",
"write",
"(",
"xy",
"[",
":",
"5",
"]",
")",
"dest",
".",
"write",
"(",
"'\\x00\\x00\\x00'",
")",
"dest",
".",
"write",
"(",
"xy",
"[",
"8",
":",
"13",
"]",
")",
"dest",
".",
"write",
"(",
"'\\x00\\x00\\x00'",
")"
] | copy a pair of big-endian doubles between files . | train | false |
22,399 | def educate_backticks(s):
return s.replace('``', '“').replace("''", '”')
| [
"def",
"educate_backticks",
"(",
"s",
")",
":",
"return",
"s",
".",
"replace",
"(",
"'``'",
",",
"'“'",
")",
".",
"replace",
"(",
"\"''\"",
",",
"'”'",
")"
] | parameter: string . | train | false |
22,400 | def user_name_validator(key, data, errors, context):
model = context['model']
new_user_name = data[key]
if (not isinstance(new_user_name, basestring)):
raise Invalid(_('User names must be strings'))
user = model.User.get(new_user_name)
if (user is not None):
user_obj_from_context = context.get('user_obj')
if (user_obj_from_context and (user_obj_from_context.id == user.id)):
return
else:
errors[key].append(_('That login name is not available.'))
| [
"def",
"user_name_validator",
"(",
"key",
",",
"data",
",",
"errors",
",",
"context",
")",
":",
"model",
"=",
"context",
"[",
"'model'",
"]",
"new_user_name",
"=",
"data",
"[",
"key",
"]",
"if",
"(",
"not",
"isinstance",
"(",
"new_user_name",
",",
"basestring",
")",
")",
":",
"raise",
"Invalid",
"(",
"_",
"(",
"'User names must be strings'",
")",
")",
"user",
"=",
"model",
".",
"User",
".",
"get",
"(",
"new_user_name",
")",
"if",
"(",
"user",
"is",
"not",
"None",
")",
":",
"user_obj_from_context",
"=",
"context",
".",
"get",
"(",
"'user_obj'",
")",
"if",
"(",
"user_obj_from_context",
"and",
"(",
"user_obj_from_context",
".",
"id",
"==",
"user",
".",
"id",
")",
")",
":",
"return",
"else",
":",
"errors",
"[",
"key",
"]",
".",
"append",
"(",
"_",
"(",
"'That login name is not available.'",
")",
")"
] | validate a new user name . | train | false |
22,403 | @handle_response_format
@treeio_login_required
def asset_view(request, asset_id, response_format='html'):
asset = get_object_or_404(Asset, pk=asset_id)
return render_to_response('finance/asset_view', {'asset': asset}, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"asset_view",
"(",
"request",
",",
"asset_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"asset",
"=",
"get_object_or_404",
"(",
"Asset",
",",
"pk",
"=",
"asset_id",
")",
"return",
"render_to_response",
"(",
"'finance/asset_view'",
",",
"{",
"'asset'",
":",
"asset",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | single transaction view page . | train | false |
22,404 | def do_comparison(good_record, test_record):
good_handle = StringIO(good_record)
test_handle = StringIO(test_record)
while True:
good_line = good_handle.readline()
test_line = test_handle.readline()
if ((not good_line) and (not test_line)):
break
if (not good_line):
raise AssertionError(('Extra info in Test: %r' % test_line))
if (not test_line):
raise AssertionError(('Extra info in Expected: %r' % good_line))
test_normalized = ' '.join((x for x in test_line.split() if x))
good_normalized = ' '.join((x for x in good_line.split() if x))
assert (test_normalized == good_normalized), ('Expected does not match Test.\nExpect: %r\nTest: %r\n' % (good_line, test_line))
| [
"def",
"do_comparison",
"(",
"good_record",
",",
"test_record",
")",
":",
"good_handle",
"=",
"StringIO",
"(",
"good_record",
")",
"test_handle",
"=",
"StringIO",
"(",
"test_record",
")",
"while",
"True",
":",
"good_line",
"=",
"good_handle",
".",
"readline",
"(",
")",
"test_line",
"=",
"test_handle",
".",
"readline",
"(",
")",
"if",
"(",
"(",
"not",
"good_line",
")",
"and",
"(",
"not",
"test_line",
")",
")",
":",
"break",
"if",
"(",
"not",
"good_line",
")",
":",
"raise",
"AssertionError",
"(",
"(",
"'Extra info in Test: %r'",
"%",
"test_line",
")",
")",
"if",
"(",
"not",
"test_line",
")",
":",
"raise",
"AssertionError",
"(",
"(",
"'Extra info in Expected: %r'",
"%",
"good_line",
")",
")",
"test_normalized",
"=",
"' '",
".",
"join",
"(",
"(",
"x",
"for",
"x",
"in",
"test_line",
".",
"split",
"(",
")",
"if",
"x",
")",
")",
"good_normalized",
"=",
"' '",
".",
"join",
"(",
"(",
"x",
"for",
"x",
"in",
"good_line",
".",
"split",
"(",
")",
"if",
"x",
")",
")",
"assert",
"(",
"test_normalized",
"==",
"good_normalized",
")",
",",
"(",
"'Expected does not match Test.\\nExpect: %r\\nTest: %r\\n'",
"%",
"(",
"good_line",
",",
"test_line",
")",
")"
] | compare two records to see if they are the same . | train | false |
22,405 | def test_cat_list_input(test_data):
num_items = CountDistinct(values=test_data.cat_list).value
bar_builder = BarBuilder(test_data.cat_list)
bar_builder.create()
assert (len(bar_builder.comp_glyphs) == num_items)
| [
"def",
"test_cat_list_input",
"(",
"test_data",
")",
":",
"num_items",
"=",
"CountDistinct",
"(",
"values",
"=",
"test_data",
".",
"cat_list",
")",
".",
"value",
"bar_builder",
"=",
"BarBuilder",
"(",
"test_data",
".",
"cat_list",
")",
"bar_builder",
".",
"create",
"(",
")",
"assert",
"(",
"len",
"(",
"bar_builder",
".",
"comp_glyphs",
")",
"==",
"num_items",
")"
] | given values of categorical data . | train | false |
22,408 | def _enqueue_suggestion_email_task(exploration_id, thread_id):
payload = {'exploration_id': exploration_id, 'thread_id': thread_id}
taskqueue_services.enqueue_task(feconf.TASK_URL_SUGGESTION_EMAILS, payload, 0)
| [
"def",
"_enqueue_suggestion_email_task",
"(",
"exploration_id",
",",
"thread_id",
")",
":",
"payload",
"=",
"{",
"'exploration_id'",
":",
"exploration_id",
",",
"'thread_id'",
":",
"thread_id",
"}",
"taskqueue_services",
".",
"enqueue_task",
"(",
"feconf",
".",
"TASK_URL_SUGGESTION_EMAILS",
",",
"payload",
",",
"0",
")"
] | adds a send suggestion email task into the task queue . | train | false |
22,409 | def verify_open(strategy, backend, user=None, **kwargs):
if ((not user) and (not appsettings.REGISTRATION_OPEN)):
raise AuthException(backend, _(u'New registrations are disabled!'))
| [
"def",
"verify_open",
"(",
"strategy",
",",
"backend",
",",
"user",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"(",
"not",
"user",
")",
"and",
"(",
"not",
"appsettings",
".",
"REGISTRATION_OPEN",
")",
")",
":",
"raise",
"AuthException",
"(",
"backend",
",",
"_",
"(",
"u'New registrations are disabled!'",
")",
")"
] | checks whether it is possible to create new user . | train | false |
22,410 | def Q(filter_, thing):
if isinstance(filter_, type([])):
return flatten(*[_Q(x, thing) for x in filter_])
elif isinstance(filter_, type({})):
d = dict.fromkeys(list(filter_.keys()))
for k in d:
d[k] = Q(k, thing)
return d
elif (' ' in filter_):
parts = filter_.strip().split()
r = None
for p in parts:
r = Ql(p, thing)
thing = r
return r
else:
return flatten(_Q(filter_, thing))
| [
"def",
"Q",
"(",
"filter_",
",",
"thing",
")",
":",
"if",
"isinstance",
"(",
"filter_",
",",
"type",
"(",
"[",
"]",
")",
")",
":",
"return",
"flatten",
"(",
"*",
"[",
"_Q",
"(",
"x",
",",
"thing",
")",
"for",
"x",
"in",
"filter_",
"]",
")",
"elif",
"isinstance",
"(",
"filter_",
",",
"type",
"(",
"{",
"}",
")",
")",
":",
"d",
"=",
"dict",
".",
"fromkeys",
"(",
"list",
"(",
"filter_",
".",
"keys",
"(",
")",
")",
")",
"for",
"k",
"in",
"d",
":",
"d",
"[",
"k",
"]",
"=",
"Q",
"(",
"k",
",",
"thing",
")",
"return",
"d",
"elif",
"(",
"' '",
"in",
"filter_",
")",
":",
"parts",
"=",
"filter_",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"r",
"=",
"None",
"for",
"p",
"in",
"parts",
":",
"r",
"=",
"Ql",
"(",
"p",
",",
"thing",
")",
"thing",
"=",
"r",
"return",
"r",
"else",
":",
"return",
"flatten",
"(",
"_Q",
"(",
"filter_",
",",
"thing",
")",
")"
] | type: - list: a flattened list of all searches - dict: dict with vals each of which is that search notes: [1] parent thing . | train | false |
22,412 | def train_test_split(*arrays, **options):
n_arrays = len(arrays)
if (n_arrays == 0):
raise ValueError('At least one array required as input')
test_size = options.pop('test_size', None)
train_size = options.pop('train_size', None)
random_state = options.pop('random_state', None)
stratify = options.pop('stratify', None)
if options:
raise TypeError(('Invalid parameters passed: %s' % str(options)))
if ((test_size is None) and (train_size is None)):
test_size = 0.25
arrays = indexable(*arrays)
if (stratify is not None):
CVClass = StratifiedShuffleSplit
else:
CVClass = ShuffleSplit
cv = CVClass(test_size=test_size, train_size=train_size, random_state=random_state)
(train, test) = next(cv.split(X=arrays[0], y=stratify))
return list(chain.from_iterable(((safe_indexing(a, train), safe_indexing(a, test)) for a in arrays)))
| [
"def",
"train_test_split",
"(",
"*",
"arrays",
",",
"**",
"options",
")",
":",
"n_arrays",
"=",
"len",
"(",
"arrays",
")",
"if",
"(",
"n_arrays",
"==",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'At least one array required as input'",
")",
"test_size",
"=",
"options",
".",
"pop",
"(",
"'test_size'",
",",
"None",
")",
"train_size",
"=",
"options",
".",
"pop",
"(",
"'train_size'",
",",
"None",
")",
"random_state",
"=",
"options",
".",
"pop",
"(",
"'random_state'",
",",
"None",
")",
"stratify",
"=",
"options",
".",
"pop",
"(",
"'stratify'",
",",
"None",
")",
"if",
"options",
":",
"raise",
"TypeError",
"(",
"(",
"'Invalid parameters passed: %s'",
"%",
"str",
"(",
"options",
")",
")",
")",
"if",
"(",
"(",
"test_size",
"is",
"None",
")",
"and",
"(",
"train_size",
"is",
"None",
")",
")",
":",
"test_size",
"=",
"0.25",
"arrays",
"=",
"indexable",
"(",
"*",
"arrays",
")",
"if",
"(",
"stratify",
"is",
"not",
"None",
")",
":",
"CVClass",
"=",
"StratifiedShuffleSplit",
"else",
":",
"CVClass",
"=",
"ShuffleSplit",
"cv",
"=",
"CVClass",
"(",
"test_size",
"=",
"test_size",
",",
"train_size",
"=",
"train_size",
",",
"random_state",
"=",
"random_state",
")",
"(",
"train",
",",
"test",
")",
"=",
"next",
"(",
"cv",
".",
"split",
"(",
"X",
"=",
"arrays",
"[",
"0",
"]",
",",
"y",
"=",
"stratify",
")",
")",
"return",
"list",
"(",
"chain",
".",
"from_iterable",
"(",
"(",
"(",
"safe_indexing",
"(",
"a",
",",
"train",
")",
",",
"safe_indexing",
"(",
"a",
",",
"test",
")",
")",
"for",
"a",
"in",
"arrays",
")",
")",
")"
] | split arrays or matrices into random train and test subsets quick utility that wraps input validation and next(shufflesplit() . | train | false |
22,413 | def decorated_with_property(node):
if (not node.decorators):
return False
for decorator in node.decorators.nodes:
if (not isinstance(decorator, astroid.Name)):
continue
try:
for infered in decorator.infer():
if isinstance(infered, astroid.Class):
if ((infered.root().name == BUILTINS_NAME) and (infered.name == 'property')):
return True
for ancestor in infered.ancestors():
if ((ancestor.name == 'property') and (ancestor.root().name == BUILTINS_NAME)):
return True
except astroid.InferenceError:
pass
| [
"def",
"decorated_with_property",
"(",
"node",
")",
":",
"if",
"(",
"not",
"node",
".",
"decorators",
")",
":",
"return",
"False",
"for",
"decorator",
"in",
"node",
".",
"decorators",
".",
"nodes",
":",
"if",
"(",
"not",
"isinstance",
"(",
"decorator",
",",
"astroid",
".",
"Name",
")",
")",
":",
"continue",
"try",
":",
"for",
"infered",
"in",
"decorator",
".",
"infer",
"(",
")",
":",
"if",
"isinstance",
"(",
"infered",
",",
"astroid",
".",
"Class",
")",
":",
"if",
"(",
"(",
"infered",
".",
"root",
"(",
")",
".",
"name",
"==",
"BUILTINS_NAME",
")",
"and",
"(",
"infered",
".",
"name",
"==",
"'property'",
")",
")",
":",
"return",
"True",
"for",
"ancestor",
"in",
"infered",
".",
"ancestors",
"(",
")",
":",
"if",
"(",
"(",
"ancestor",
".",
"name",
"==",
"'property'",
")",
"and",
"(",
"ancestor",
".",
"root",
"(",
")",
".",
"name",
"==",
"BUILTINS_NAME",
")",
")",
":",
"return",
"True",
"except",
"astroid",
".",
"InferenceError",
":",
"pass"
] | detect if the given function node is decorated with a property . | train | false |
22,414 | def Internaldate2tuple(resp):
mo = InternalDate.match(resp)
if (not mo):
return None
mon = Mon2num[mo.group('mon')]
zonen = mo.group('zonen')
day = int(mo.group('day'))
year = int(mo.group('year'))
hour = int(mo.group('hour'))
min = int(mo.group('min'))
sec = int(mo.group('sec'))
zoneh = int(mo.group('zoneh'))
zonem = int(mo.group('zonem'))
zone = (((zoneh * 60) + zonem) * 60)
if (zonen == '-'):
zone = (- zone)
tt = (year, mon, day, hour, min, sec, (-1), (-1), (-1))
utc = time.mktime(tt)
lt = time.localtime(utc)
if (time.daylight and lt[(-1)]):
zone = (zone + time.altzone)
else:
zone = (zone + time.timezone)
return time.localtime((utc - zone))
| [
"def",
"Internaldate2tuple",
"(",
"resp",
")",
":",
"mo",
"=",
"InternalDate",
".",
"match",
"(",
"resp",
")",
"if",
"(",
"not",
"mo",
")",
":",
"return",
"None",
"mon",
"=",
"Mon2num",
"[",
"mo",
".",
"group",
"(",
"'mon'",
")",
"]",
"zonen",
"=",
"mo",
".",
"group",
"(",
"'zonen'",
")",
"day",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'day'",
")",
")",
"year",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'year'",
")",
")",
"hour",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'hour'",
")",
")",
"min",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'min'",
")",
")",
"sec",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'sec'",
")",
")",
"zoneh",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'zoneh'",
")",
")",
"zonem",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"'zonem'",
")",
")",
"zone",
"=",
"(",
"(",
"(",
"zoneh",
"*",
"60",
")",
"+",
"zonem",
")",
"*",
"60",
")",
"if",
"(",
"zonen",
"==",
"'-'",
")",
":",
"zone",
"=",
"(",
"-",
"zone",
")",
"tt",
"=",
"(",
"year",
",",
"mon",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
"utc",
"=",
"time",
".",
"mktime",
"(",
"tt",
")",
"lt",
"=",
"time",
".",
"localtime",
"(",
"utc",
")",
"if",
"(",
"time",
".",
"daylight",
"and",
"lt",
"[",
"(",
"-",
"1",
")",
"]",
")",
":",
"zone",
"=",
"(",
"zone",
"+",
"time",
".",
"altzone",
")",
"else",
":",
"zone",
"=",
"(",
"zone",
"+",
"time",
".",
"timezone",
")",
"return",
"time",
".",
"localtime",
"(",
"(",
"utc",
"-",
"zone",
")",
")"
] | parse an imap4 internaldate string . | train | false |
22,415 | def watch_server_pids(server_pids, interval=1, **kwargs):
status = {}
start = time.time()
end = (start + interval)
server_pids = dict(server_pids)
while True:
for (server, pids) in server_pids.items():
for pid in pids:
try:
os.waitpid(pid, os.WNOHANG)
except OSError as e:
if (e.errno not in (errno.ECHILD, errno.ESRCH)):
raise
status[server] = server.get_running_pids(**kwargs)
for pid in pids:
if (pid not in status[server]):
(yield (server, pid))
server_pids[server] = status[server]
if (not [p for (server, pids) in status.items() for p in pids]):
break
if (time.time() > end):
break
else:
time.sleep(0.1)
| [
"def",
"watch_server_pids",
"(",
"server_pids",
",",
"interval",
"=",
"1",
",",
"**",
"kwargs",
")",
":",
"status",
"=",
"{",
"}",
"start",
"=",
"time",
".",
"time",
"(",
")",
"end",
"=",
"(",
"start",
"+",
"interval",
")",
"server_pids",
"=",
"dict",
"(",
"server_pids",
")",
"while",
"True",
":",
"for",
"(",
"server",
",",
"pids",
")",
"in",
"server_pids",
".",
"items",
"(",
")",
":",
"for",
"pid",
"in",
"pids",
":",
"try",
":",
"os",
".",
"waitpid",
"(",
"pid",
",",
"os",
".",
"WNOHANG",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"(",
"e",
".",
"errno",
"not",
"in",
"(",
"errno",
".",
"ECHILD",
",",
"errno",
".",
"ESRCH",
")",
")",
":",
"raise",
"status",
"[",
"server",
"]",
"=",
"server",
".",
"get_running_pids",
"(",
"**",
"kwargs",
")",
"for",
"pid",
"in",
"pids",
":",
"if",
"(",
"pid",
"not",
"in",
"status",
"[",
"server",
"]",
")",
":",
"(",
"yield",
"(",
"server",
",",
"pid",
")",
")",
"server_pids",
"[",
"server",
"]",
"=",
"status",
"[",
"server",
"]",
"if",
"(",
"not",
"[",
"p",
"for",
"(",
"server",
",",
"pids",
")",
"in",
"status",
".",
"items",
"(",
")",
"for",
"p",
"in",
"pids",
"]",
")",
":",
"break",
"if",
"(",
"time",
".",
"time",
"(",
")",
">",
"end",
")",
":",
"break",
"else",
":",
"time",
".",
"sleep",
"(",
"0.1",
")"
] | monitor a collection of server pids yielding back those pids that arent responding to signals . | train | false |
22,416 | def _ask_snippets(snippets):
display = [(as_unicode('%i: %s (%s)') % ((i + 1), escape(s.description, '\\'), escape(s.location, '\\'))) for (i, s) in enumerate(snippets)]
return _ask_user(snippets, display)
| [
"def",
"_ask_snippets",
"(",
"snippets",
")",
":",
"display",
"=",
"[",
"(",
"as_unicode",
"(",
"'%i: %s (%s)'",
")",
"%",
"(",
"(",
"i",
"+",
"1",
")",
",",
"escape",
"(",
"s",
".",
"description",
",",
"'\\\\'",
")",
",",
"escape",
"(",
"s",
".",
"location",
",",
"'\\\\'",
")",
")",
")",
"for",
"(",
"i",
",",
"s",
")",
"in",
"enumerate",
"(",
"snippets",
")",
"]",
"return",
"_ask_user",
"(",
"snippets",
",",
"display",
")"
] | given a list of snippets . | train | false |
22,417 | def onInterfaceAppReady():
INFO_MSG(('onInterfaceAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s' % (os.getenv('KBE_BOOTIDX_GROUP'), os.getenv('KBE_BOOTIDX_GLOBAL'))))
g_poller.start('localhost', 30040)
| [
"def",
"onInterfaceAppReady",
"(",
")",
":",
"INFO_MSG",
"(",
"(",
"'onInterfaceAppReady: bootstrapGroupIndex=%s, bootstrapGlobalIndex=%s'",
"%",
"(",
"os",
".",
"getenv",
"(",
"'KBE_BOOTIDX_GROUP'",
")",
",",
"os",
".",
"getenv",
"(",
"'KBE_BOOTIDX_GLOBAL'",
")",
")",
")",
")",
"g_poller",
".",
"start",
"(",
"'localhost'",
",",
"30040",
")"
] | kbengine method . | train | false |
22,418 | def path_hack():
this_file = os.path.abspath(__file__)
sympy_dir = os.path.join(os.path.dirname(this_file), '..')
sympy_dir = os.path.normpath(sympy_dir)
sys.path.insert(0, sympy_dir)
return sympy_dir
| [
"def",
"path_hack",
"(",
")",
":",
"this_file",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
"sympy_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"this_file",
")",
",",
"'..'",
")",
"sympy_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"sympy_dir",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"sympy_dir",
")",
"return",
"sympy_dir"
] | hack sys . | train | false |
22,420 | def _bytes_iterator_py2(bytes_):
for b in bytes_:
(yield b)
| [
"def",
"_bytes_iterator_py2",
"(",
"bytes_",
")",
":",
"for",
"b",
"in",
"bytes_",
":",
"(",
"yield",
"b",
")"
] | returns iterator over a bytestring in python 2 . | train | false |
22,421 | def connect_cognito_identity(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
from boto.cognito.identity.layer1 import CognitoIdentityConnection
return CognitoIdentityConnection(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs)
| [
"def",
"connect_cognito_identity",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"from",
"boto",
".",
"cognito",
".",
"identity",
".",
"layer1",
"import",
"CognitoIdentityConnection",
"return",
"CognitoIdentityConnection",
"(",
"aws_access_key_id",
"=",
"aws_access_key_id",
",",
"aws_secret_access_key",
"=",
"aws_secret_access_key",
",",
"**",
"kwargs",
")"
] | connect to amazon cognito identity :type aws_access_key_id: string . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.