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,011 | def test_number_aware_alphabetical_key():
l = ['0', 'mystr_1', 'mystr_10', 'mystr_2', 'mystr_1_a', 'mystr']
l.sort(key=number_aware_alphabetical_key)
print(l)
assert (l == ['0', 'mystr', 'mystr_1', 'mystr_1_a', 'mystr_2', 'mystr_10'])
| [
"def",
"test_number_aware_alphabetical_key",
"(",
")",
":",
"l",
"=",
"[",
"'0'",
",",
"'mystr_1'",
",",
"'mystr_10'",
",",
"'mystr_2'",
",",
"'mystr_1_a'",
",",
"'mystr'",
"]",
"l",
".",
"sort",
"(",
"key",
"=",
"number_aware_alphabetical_key",
")",
"print",
"(",
"l",
")",
"assert",
"(",
"l",
"==",
"[",
"'0'",
",",
"'mystr'",
",",
"'mystr_1'",
",",
"'mystr_1_a'",
",",
"'mystr_2'",
",",
"'mystr_10'",
"]",
")"
] | tests that number-aware sorting matches a manually generated output on a specific example . | train | false |
22,012 | def readPlistFromResource(path, restype='plst', resid=0):
warnings.warnpy3k('In 3.x, readPlistFromResource is removed.', stacklevel=2)
from Carbon.File import FSRef, FSGetResourceForkName
from Carbon.Files import fsRdPerm
from Carbon import Res
fsRef = FSRef(path)
resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm)
Res.UseResFile(resNum)
plistData = Res.Get1Resource(restype, resid).data
Res.CloseResFile(resNum)
return readPlistFromString(plistData)
| [
"def",
"readPlistFromResource",
"(",
"path",
",",
"restype",
"=",
"'plst'",
",",
"resid",
"=",
"0",
")",
":",
"warnings",
".",
"warnpy3k",
"(",
"'In 3.x, readPlistFromResource is removed.'",
",",
"stacklevel",
"=",
"2",
")",
"from",
"Carbon",
".",
"File",
"import",
"FSRef",
",",
"FSGetResourceForkName",
"from",
"Carbon",
".",
"Files",
"import",
"fsRdPerm",
"from",
"Carbon",
"import",
"Res",
"fsRef",
"=",
"FSRef",
"(",
"path",
")",
"resNum",
"=",
"Res",
".",
"FSOpenResourceFile",
"(",
"fsRef",
",",
"FSGetResourceForkName",
"(",
")",
",",
"fsRdPerm",
")",
"Res",
".",
"UseResFile",
"(",
"resNum",
")",
"plistData",
"=",
"Res",
".",
"Get1Resource",
"(",
"restype",
",",
"resid",
")",
".",
"data",
"Res",
".",
"CloseResFile",
"(",
"resNum",
")",
"return",
"readPlistFromString",
"(",
"plistData",
")"
] | read plst resource from the resource fork of path . | train | false |
22,013 | def dependency_is_none(dependency):
return (dependency is None)
| [
"def",
"dependency_is_none",
"(",
"dependency",
")",
":",
"return",
"(",
"dependency",
"is",
"None",
")"
] | return true if the dependency is none . | train | false |
22,014 | def import_js(path, lib_name, globals):
with codecs.open(path_as_local(path), 'r', 'utf-8') as f:
js = f.read()
e = EvalJs()
e.execute(js)
var = e.context['var']
globals[lib_name] = var.to_python()
| [
"def",
"import_js",
"(",
"path",
",",
"lib_name",
",",
"globals",
")",
":",
"with",
"codecs",
".",
"open",
"(",
"path_as_local",
"(",
"path",
")",
",",
"'r'",
",",
"'utf-8'",
")",
"as",
"f",
":",
"js",
"=",
"f",
".",
"read",
"(",
")",
"e",
"=",
"EvalJs",
"(",
")",
"e",
".",
"execute",
"(",
"js",
")",
"var",
"=",
"e",
".",
"context",
"[",
"'var'",
"]",
"globals",
"[",
"lib_name",
"]",
"=",
"var",
".",
"to_python",
"(",
")"
] | imports from javascript source file . | train | true |
22,016 | def set_debug_function(func_cb=debug.print_to_stdout, warnings=True, notices=True, speed=True):
debug.debug_function = func_cb
debug.enable_warning = warnings
debug.enable_notice = notices
debug.enable_speed = speed
| [
"def",
"set_debug_function",
"(",
"func_cb",
"=",
"debug",
".",
"print_to_stdout",
",",
"warnings",
"=",
"True",
",",
"notices",
"=",
"True",
",",
"speed",
"=",
"True",
")",
":",
"debug",
".",
"debug_function",
"=",
"func_cb",
"debug",
".",
"enable_warning",
"=",
"warnings",
"debug",
".",
"enable_notice",
"=",
"notices",
"debug",
".",
"enable_speed",
"=",
"speed"
] | define a callback debug function to get all the debug messages . | train | false |
22,018 | def show_diff(seqm):
output = []
insert_el = '<span style="background:#4AA02C; font-size:1.5em; ">'
ins_el_close = '</span>'
del_el = '<span style="background:#D16587; font-size:1.5em;">'
del_el_close = '</span>'
for (opcode, a0, a1, b0, b1) in seqm.get_opcodes():
content_a = strip_html(seqm.a[a0:a1])
content_b = strip_html(seqm.b[b0:b1])
if (opcode == 'equal'):
output.append(content_a)
elif (opcode == 'insert'):
output.append(((insert_el + content_b) + ins_el_close))
elif (opcode == 'delete'):
output.append(((del_el + content_a) + del_el_close))
elif (opcode == 'replace'):
output.append((((((del_el + content_a) + del_el_close) + insert_el) + content_b) + ins_el_close))
else:
raise RuntimeError('unexpected opcode')
return ''.join(output)
| [
"def",
"show_diff",
"(",
"seqm",
")",
":",
"output",
"=",
"[",
"]",
"insert_el",
"=",
"'<span style=\"background:#4AA02C; font-size:1.5em; \">'",
"ins_el_close",
"=",
"'</span>'",
"del_el",
"=",
"'<span style=\"background:#D16587; font-size:1.5em;\">'",
"del_el_close",
"=",
"'</span>'",
"for",
"(",
"opcode",
",",
"a0",
",",
"a1",
",",
"b0",
",",
"b1",
")",
"in",
"seqm",
".",
"get_opcodes",
"(",
")",
":",
"content_a",
"=",
"strip_html",
"(",
"seqm",
".",
"a",
"[",
"a0",
":",
"a1",
"]",
")",
"content_b",
"=",
"strip_html",
"(",
"seqm",
".",
"b",
"[",
"b0",
":",
"b1",
"]",
")",
"if",
"(",
"opcode",
"==",
"'equal'",
")",
":",
"output",
".",
"append",
"(",
"content_a",
")",
"elif",
"(",
"opcode",
"==",
"'insert'",
")",
":",
"output",
".",
"append",
"(",
"(",
"(",
"insert_el",
"+",
"content_b",
")",
"+",
"ins_el_close",
")",
")",
"elif",
"(",
"opcode",
"==",
"'delete'",
")",
":",
"output",
".",
"append",
"(",
"(",
"(",
"del_el",
"+",
"content_a",
")",
"+",
"del_el_close",
")",
")",
"elif",
"(",
"opcode",
"==",
"'replace'",
")",
":",
"output",
".",
"append",
"(",
"(",
"(",
"(",
"(",
"(",
"del_el",
"+",
"content_a",
")",
"+",
"del_el_close",
")",
"+",
"insert_el",
")",
"+",
"content_b",
")",
"+",
"ins_el_close",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"'unexpected opcode'",
")",
"return",
"''",
".",
"join",
"(",
"output",
")"
] | unify operations between two compared strings seqm is a difflib . | train | false |
22,020 | def net_connections(kind='inet'):
return _psplatform.net_connections(kind)
| [
"def",
"net_connections",
"(",
"kind",
"=",
"'inet'",
")",
":",
"return",
"_psplatform",
".",
"net_connections",
"(",
"kind",
")"
] | return system-wide open connections . | train | false |
22,021 | def filter_paths(stats, path_dir_wildcard):
entries = [(s, basename(s.path)) for s in stats.dependencies]
paths = tuple((Path(join(path_dir_wildcard.symbolic_path, basename), stat) for (stat, basename) in entries if fnmatch(basename, path_dir_wildcard.wildcard)))
return FilteredPaths(Paths(paths))
| [
"def",
"filter_paths",
"(",
"stats",
",",
"path_dir_wildcard",
")",
":",
"entries",
"=",
"[",
"(",
"s",
",",
"basename",
"(",
"s",
".",
"path",
")",
")",
"for",
"s",
"in",
"stats",
".",
"dependencies",
"]",
"paths",
"=",
"tuple",
"(",
"(",
"Path",
"(",
"join",
"(",
"path_dir_wildcard",
".",
"symbolic_path",
",",
"basename",
")",
",",
"stat",
")",
"for",
"(",
"stat",
",",
"basename",
")",
"in",
"entries",
"if",
"fnmatch",
"(",
"basename",
",",
"path_dir_wildcard",
".",
"wildcard",
")",
")",
")",
"return",
"FilteredPaths",
"(",
"Paths",
"(",
"paths",
")",
")"
] | path_list - a list of file paths to check . | train | false |
22,022 | @testing.requires_testing_data
@requires_nibabel(vox2ras_tkr=True)
def test_mgz_header():
header = _get_mgz_header(fname_mri)
mri_hdr = _get_mri_header(fname_mri)
assert_allclose(mri_hdr.get_data_shape(), header['dims'])
assert_allclose(mri_hdr.get_vox2ras_tkr(), header['vox2ras_tkr'])
assert_allclose(mri_hdr.get_ras2vox(), header['ras2vox'])
| [
"@",
"testing",
".",
"requires_testing_data",
"@",
"requires_nibabel",
"(",
"vox2ras_tkr",
"=",
"True",
")",
"def",
"test_mgz_header",
"(",
")",
":",
"header",
"=",
"_get_mgz_header",
"(",
"fname_mri",
")",
"mri_hdr",
"=",
"_get_mri_header",
"(",
"fname_mri",
")",
"assert_allclose",
"(",
"mri_hdr",
".",
"get_data_shape",
"(",
")",
",",
"header",
"[",
"'dims'",
"]",
")",
"assert_allclose",
"(",
"mri_hdr",
".",
"get_vox2ras_tkr",
"(",
")",
",",
"header",
"[",
"'vox2ras_tkr'",
"]",
")",
"assert_allclose",
"(",
"mri_hdr",
".",
"get_ras2vox",
"(",
")",
",",
"header",
"[",
"'ras2vox'",
"]",
")"
] | test mgz header reading . | train | false |
22,023 | def _read_hc(directory):
fname = _make_ctf_name(directory, 'hc', raise_error=False)
if (fname is None):
logger.info(' hc data not present')
return None
s = list()
with open(fname, 'rb') as fid:
while True:
p = _read_one_coil_point(fid)
if (p is None):
if (len(s) == 0):
logger.info('hc file empty, no data present')
return None
logger.info(' hc data read.')
return s
if p['valid']:
s.append(p)
| [
"def",
"_read_hc",
"(",
"directory",
")",
":",
"fname",
"=",
"_make_ctf_name",
"(",
"directory",
",",
"'hc'",
",",
"raise_error",
"=",
"False",
")",
"if",
"(",
"fname",
"is",
"None",
")",
":",
"logger",
".",
"info",
"(",
"' hc data not present'",
")",
"return",
"None",
"s",
"=",
"list",
"(",
")",
"with",
"open",
"(",
"fname",
",",
"'rb'",
")",
"as",
"fid",
":",
"while",
"True",
":",
"p",
"=",
"_read_one_coil_point",
"(",
"fid",
")",
"if",
"(",
"p",
"is",
"None",
")",
":",
"if",
"(",
"len",
"(",
"s",
")",
"==",
"0",
")",
":",
"logger",
".",
"info",
"(",
"'hc file empty, no data present'",
")",
"return",
"None",
"logger",
".",
"info",
"(",
"' hc data read.'",
")",
"return",
"s",
"if",
"p",
"[",
"'valid'",
"]",
":",
"s",
".",
"append",
"(",
"p",
")"
] | read the hc file to get the hpi info and to prepare for coord trans . | train | false |
22,024 | def lint_citations(tool_xml, lint_ctx):
root = tool_xml.getroot()
citations = root.findall('citations')
if (len(citations) > 1):
lint_ctx.error('More than one citation section found, behavior undefined.')
return
if (len(citations) == 0):
lint_ctx.warn('No citations found, consider adding citations to your tool.')
return
valid_citations = 0
for citation in citations[0]:
if (citation.tag != 'citation'):
lint_ctx.warn(('Unknown tag discovered in citations block [%s], will be ignored.' % citation.tag))
if ('type' in citation.attrib):
citation_type = citation.attrib.get('type')
if (citation_type not in ['doi', 'bibtex']):
lint_ctx.warn('Unknown citation type discovered [%s], will be ignored.', citation_type)
else:
valid_citations += 1
if (valid_citations > 0):
lint_ctx.valid('Found %d likely valid citations.', valid_citations)
| [
"def",
"lint_citations",
"(",
"tool_xml",
",",
"lint_ctx",
")",
":",
"root",
"=",
"tool_xml",
".",
"getroot",
"(",
")",
"citations",
"=",
"root",
".",
"findall",
"(",
"'citations'",
")",
"if",
"(",
"len",
"(",
"citations",
")",
">",
"1",
")",
":",
"lint_ctx",
".",
"error",
"(",
"'More than one citation section found, behavior undefined.'",
")",
"return",
"if",
"(",
"len",
"(",
"citations",
")",
"==",
"0",
")",
":",
"lint_ctx",
".",
"warn",
"(",
"'No citations found, consider adding citations to your tool.'",
")",
"return",
"valid_citations",
"=",
"0",
"for",
"citation",
"in",
"citations",
"[",
"0",
"]",
":",
"if",
"(",
"citation",
".",
"tag",
"!=",
"'citation'",
")",
":",
"lint_ctx",
".",
"warn",
"(",
"(",
"'Unknown tag discovered in citations block [%s], will be ignored.'",
"%",
"citation",
".",
"tag",
")",
")",
"if",
"(",
"'type'",
"in",
"citation",
".",
"attrib",
")",
":",
"citation_type",
"=",
"citation",
".",
"attrib",
".",
"get",
"(",
"'type'",
")",
"if",
"(",
"citation_type",
"not",
"in",
"[",
"'doi'",
",",
"'bibtex'",
"]",
")",
":",
"lint_ctx",
".",
"warn",
"(",
"'Unknown citation type discovered [%s], will be ignored.'",
",",
"citation_type",
")",
"else",
":",
"valid_citations",
"+=",
"1",
"if",
"(",
"valid_citations",
">",
"0",
")",
":",
"lint_ctx",
".",
"valid",
"(",
"'Found %d likely valid citations.'",
",",
"valid_citations",
")"
] | ensure tool contains at least one valid citation . | train | false |
22,025 | def flags2hash(flags):
return __options2hash(flagsplit(flags))
| [
"def",
"flags2hash",
"(",
"flags",
")",
":",
"return",
"__options2hash",
"(",
"flagsplit",
"(",
"flags",
")",
")"
] | converts imap response string from eg imap4 . | train | false |
22,026 | @register.simple_tag(takes_context=True)
def file_attachment_comments(context, file_attachment):
review_ui = file_attachment.review_ui
if (not review_ui):
review_ui = FileAttachmentReviewUI(file_attachment.review_request, file_attachment)
review_ui.request = context[u'request']
return json.dumps(review_ui.serialize_comments(file_attachment.get_comments()))
| [
"@",
"register",
".",
"simple_tag",
"(",
"takes_context",
"=",
"True",
")",
"def",
"file_attachment_comments",
"(",
"context",
",",
"file_attachment",
")",
":",
"review_ui",
"=",
"file_attachment",
".",
"review_ui",
"if",
"(",
"not",
"review_ui",
")",
":",
"review_ui",
"=",
"FileAttachmentReviewUI",
"(",
"file_attachment",
".",
"review_request",
",",
"file_attachment",
")",
"review_ui",
".",
"request",
"=",
"context",
"[",
"u'request'",
"]",
"return",
"json",
".",
"dumps",
"(",
"review_ui",
".",
"serialize_comments",
"(",
"file_attachment",
".",
"get_comments",
"(",
")",
")",
")"
] | returns a json array of current comments for a file attachment . | train | false |
22,027 | def is_int(s):
if (not s):
return True
try:
int(s)
return True
except ValueError:
return False
| [
"def",
"is_int",
"(",
"s",
")",
":",
"if",
"(",
"not",
"s",
")",
":",
"return",
"True",
"try",
":",
"int",
"(",
"s",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | return s is blank or represents an int . | train | false |
22,028 | def is_interactive():
return _is_interactive
| [
"def",
"is_interactive",
"(",
")",
":",
"return",
"_is_interactive"
] | return true if plot mode is interactive . | train | false |
22,029 | def deserializers(**deserializers):
def decorator(func):
if (not hasattr(func, 'wsgi_deserializers')):
func.wsgi_deserializers = {}
func.wsgi_deserializers.update(deserializers)
return func
return decorator
| [
"def",
"deserializers",
"(",
"**",
"deserializers",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"func",
",",
"'wsgi_deserializers'",
")",
")",
":",
"func",
".",
"wsgi_deserializers",
"=",
"{",
"}",
"func",
".",
"wsgi_deserializers",
".",
"update",
"(",
"deserializers",
")",
"return",
"func",
"return",
"decorator"
] | attaches deserializers to a method . | train | false |
22,030 | def json_out(content_type='application/json', debug=False, handler=json_handler):
request = cherrypy.serving.request
if (request.handler is None):
return
if debug:
cherrypy.log(('Replacing %s with JSON handler' % request.handler), 'TOOLS.JSON_OUT')
request._json_inner_handler = request.handler
request.handler = handler
if (content_type is not None):
if debug:
cherrypy.log(('Setting Content-Type to %s' % content_type), 'TOOLS.JSON_OUT')
cherrypy.serving.response.headers['Content-Type'] = content_type
| [
"def",
"json_out",
"(",
"content_type",
"=",
"'application/json'",
",",
"debug",
"=",
"False",
",",
"handler",
"=",
"json_handler",
")",
":",
"request",
"=",
"cherrypy",
".",
"serving",
".",
"request",
"if",
"(",
"request",
".",
"handler",
"is",
"None",
")",
":",
"return",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"(",
"'Replacing %s with JSON handler'",
"%",
"request",
".",
"handler",
")",
",",
"'TOOLS.JSON_OUT'",
")",
"request",
".",
"_json_inner_handler",
"=",
"request",
".",
"handler",
"request",
".",
"handler",
"=",
"handler",
"if",
"(",
"content_type",
"is",
"not",
"None",
")",
":",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"(",
"'Setting Content-Type to %s'",
"%",
"content_type",
")",
",",
"'TOOLS.JSON_OUT'",
")",
"cherrypy",
".",
"serving",
".",
"response",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"content_type"
] | wrap request . | train | false |
22,032 | def getReadCraftSequence():
return skeinforge_profile.getCraftTypePluginModule().getCraftSequence()
| [
"def",
"getReadCraftSequence",
"(",
")",
":",
"return",
"skeinforge_profile",
".",
"getCraftTypePluginModule",
"(",
")",
".",
"getCraftSequence",
"(",
")"
] | get profile sequence . | train | false |
22,033 | def slepian(M, width, sym=True):
if _len_guards(M):
return np.ones(M)
(M, needs_trunc) = _extend(M, sym)
width = (width / 2)
width = (width / 2)
m = np.arange(M, dtype='d')
H = np.zeros((2, M))
H[0, 1:] = ((m[1:] * (M - m[1:])) / 2)
H[1, :] = (((((M - 1) - (2 * m)) / 2) ** 2) * np.cos(((2 * np.pi) * width)))
(_, win) = linalg.eig_banded(H, select='i', select_range=((M - 1), (M - 1)))
win = (win.ravel() / win.max())
return _truncate(win, needs_trunc)
| [
"def",
"slepian",
"(",
"M",
",",
"width",
",",
"sym",
"=",
"True",
")",
":",
"if",
"_len_guards",
"(",
"M",
")",
":",
"return",
"np",
".",
"ones",
"(",
"M",
")",
"(",
"M",
",",
"needs_trunc",
")",
"=",
"_extend",
"(",
"M",
",",
"sym",
")",
"width",
"=",
"(",
"width",
"/",
"2",
")",
"width",
"=",
"(",
"width",
"/",
"2",
")",
"m",
"=",
"np",
".",
"arange",
"(",
"M",
",",
"dtype",
"=",
"'d'",
")",
"H",
"=",
"np",
".",
"zeros",
"(",
"(",
"2",
",",
"M",
")",
")",
"H",
"[",
"0",
",",
"1",
":",
"]",
"=",
"(",
"(",
"m",
"[",
"1",
":",
"]",
"*",
"(",
"M",
"-",
"m",
"[",
"1",
":",
"]",
")",
")",
"/",
"2",
")",
"H",
"[",
"1",
",",
":",
"]",
"=",
"(",
"(",
"(",
"(",
"(",
"M",
"-",
"1",
")",
"-",
"(",
"2",
"*",
"m",
")",
")",
"/",
"2",
")",
"**",
"2",
")",
"*",
"np",
".",
"cos",
"(",
"(",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"*",
"width",
")",
")",
")",
"(",
"_",
",",
"win",
")",
"=",
"linalg",
".",
"eig_banded",
"(",
"H",
",",
"select",
"=",
"'i'",
",",
"select_range",
"=",
"(",
"(",
"M",
"-",
"1",
")",
",",
"(",
"M",
"-",
"1",
")",
")",
")",
"win",
"=",
"(",
"win",
".",
"ravel",
"(",
")",
"/",
"win",
".",
"max",
"(",
")",
")",
"return",
"_truncate",
"(",
"win",
",",
"needs_trunc",
")"
] | return a digital slepian window . | train | false |
22,034 | def test_nested_basic_call_coroutine():
@hug.call()
@asyncio.coroutine
def hello_world():
return asyncio.async(nested_hello_world())
@hug.local()
@asyncio.coroutine
def nested_hello_world():
return 'Hello World!'
assert (loop.run_until_complete(hello_world()) == 'Hello World!')
| [
"def",
"test_nested_basic_call_coroutine",
"(",
")",
":",
"@",
"hug",
".",
"call",
"(",
")",
"@",
"asyncio",
".",
"coroutine",
"def",
"hello_world",
"(",
")",
":",
"return",
"asyncio",
".",
"async",
"(",
"nested_hello_world",
"(",
")",
")",
"@",
"hug",
".",
"local",
"(",
")",
"@",
"asyncio",
".",
"coroutine",
"def",
"nested_hello_world",
"(",
")",
":",
"return",
"'Hello World!'",
"assert",
"(",
"loop",
".",
"run_until_complete",
"(",
"hello_world",
"(",
")",
")",
"==",
"'Hello World!'",
")"
] | the most basic happy-path test for hug apis using async . | train | false |
22,036 | def is_valid_hostname(hostname):
return (re.match('^[a-zA-Z0-9-]+$', hostname) is not None)
| [
"def",
"is_valid_hostname",
"(",
"hostname",
")",
":",
"return",
"(",
"re",
".",
"match",
"(",
"'^[a-zA-Z0-9-]+$'",
",",
"hostname",
")",
"is",
"not",
"None",
")"
] | return true if the provided hostname is a valid hostname . | train | false |
22,037 | def _domain_config_finder(conf_dir):
LOG.info(_LI('Scanning %r for domain config files'), conf_dir)
for (r, d, f) in os.walk(conf_dir):
for fname in f:
if (fname.startswith(DOMAIN_CONF_FHEAD) and fname.endswith(DOMAIN_CONF_FTAIL)):
if (fname.count('.') >= 2):
domain_name = fname[len(DOMAIN_CONF_FHEAD):(- len(DOMAIN_CONF_FTAIL))]
(yield (os.path.join(r, fname), domain_name))
continue
LOG.warning(_LW('Ignoring file (%s) while scanning domain config directory'), fname)
| [
"def",
"_domain_config_finder",
"(",
"conf_dir",
")",
":",
"LOG",
".",
"info",
"(",
"_LI",
"(",
"'Scanning %r for domain config files'",
")",
",",
"conf_dir",
")",
"for",
"(",
"r",
",",
"d",
",",
"f",
")",
"in",
"os",
".",
"walk",
"(",
"conf_dir",
")",
":",
"for",
"fname",
"in",
"f",
":",
"if",
"(",
"fname",
".",
"startswith",
"(",
"DOMAIN_CONF_FHEAD",
")",
"and",
"fname",
".",
"endswith",
"(",
"DOMAIN_CONF_FTAIL",
")",
")",
":",
"if",
"(",
"fname",
".",
"count",
"(",
"'.'",
")",
">=",
"2",
")",
":",
"domain_name",
"=",
"fname",
"[",
"len",
"(",
"DOMAIN_CONF_FHEAD",
")",
":",
"(",
"-",
"len",
"(",
"DOMAIN_CONF_FTAIL",
")",
")",
"]",
"(",
"yield",
"(",
"os",
".",
"path",
".",
"join",
"(",
"r",
",",
"fname",
")",
",",
"domain_name",
")",
")",
"continue",
"LOG",
".",
"warning",
"(",
"_LW",
"(",
"'Ignoring file (%s) while scanning domain config directory'",
")",
",",
"fname",
")"
] | return a generator of all domain config files found in a directory . | train | false |
22,038 | def pretty_file_size(size, use_decimal=False, **kwargs):
try:
size = max(float(size), 0.0)
except (ValueError, TypeError):
size = 0.0
remaining_size = size
units = kwargs.pop(u'units', [u'B', u'KB', u'MB', u'GB', u'TB', u'PB'])
block = (1024.0 if (not use_decimal) else 1000.0)
for unit in units:
if (remaining_size < block):
return u'{0:3.2f} {1}'.format(remaining_size, unit)
remaining_size /= block
return size
| [
"def",
"pretty_file_size",
"(",
"size",
",",
"use_decimal",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"size",
"=",
"max",
"(",
"float",
"(",
"size",
")",
",",
"0.0",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"size",
"=",
"0.0",
"remaining_size",
"=",
"size",
"units",
"=",
"kwargs",
".",
"pop",
"(",
"u'units'",
",",
"[",
"u'B'",
",",
"u'KB'",
",",
"u'MB'",
",",
"u'GB'",
",",
"u'TB'",
",",
"u'PB'",
"]",
")",
"block",
"=",
"(",
"1024.0",
"if",
"(",
"not",
"use_decimal",
")",
"else",
"1000.0",
")",
"for",
"unit",
"in",
"units",
":",
"if",
"(",
"remaining_size",
"<",
"block",
")",
":",
"return",
"u'{0:3.2f} {1}'",
".",
"format",
"(",
"remaining_size",
",",
"unit",
")",
"remaining_size",
"/=",
"block",
"return",
"size"
] | return a human readable representation of the provided size . | train | false |
22,039 | @require_http_methods(('DELETE', 'POST', 'PUT'))
@login_required
@ensure_csrf_cookie
def _update_asset(request, course_key, asset_key):
if (request.method == 'DELETE'):
try:
delete_asset(course_key, asset_key)
return JsonResponse()
except AssetNotFoundException:
return JsonResponse(status=404)
elif (request.method in ('PUT', 'POST')):
if ('file' in request.FILES):
return _upload_asset(request, course_key)
else:
try:
modified_asset = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest()
contentstore().set_attr(asset_key, 'locked', modified_asset['locked'])
del_cached_content(asset_key)
return JsonResponse(modified_asset, status=201)
| [
"@",
"require_http_methods",
"(",
"(",
"'DELETE'",
",",
"'POST'",
",",
"'PUT'",
")",
")",
"@",
"login_required",
"@",
"ensure_csrf_cookie",
"def",
"_update_asset",
"(",
"request",
",",
"course_key",
",",
"asset_key",
")",
":",
"if",
"(",
"request",
".",
"method",
"==",
"'DELETE'",
")",
":",
"try",
":",
"delete_asset",
"(",
"course_key",
",",
"asset_key",
")",
"return",
"JsonResponse",
"(",
")",
"except",
"AssetNotFoundException",
":",
"return",
"JsonResponse",
"(",
"status",
"=",
"404",
")",
"elif",
"(",
"request",
".",
"method",
"in",
"(",
"'PUT'",
",",
"'POST'",
")",
")",
":",
"if",
"(",
"'file'",
"in",
"request",
".",
"FILES",
")",
":",
"return",
"_upload_asset",
"(",
"request",
",",
"course_key",
")",
"else",
":",
"try",
":",
"modified_asset",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"body",
")",
"except",
"ValueError",
":",
"return",
"HttpResponseBadRequest",
"(",
")",
"contentstore",
"(",
")",
".",
"set_attr",
"(",
"asset_key",
",",
"'locked'",
",",
"modified_asset",
"[",
"'locked'",
"]",
")",
"del_cached_content",
"(",
"asset_key",
")",
"return",
"JsonResponse",
"(",
"modified_asset",
",",
"status",
"=",
"201",
")"
] | restful crud operations for a course asset . | train | false |
22,040 | @depends(HAS_PYVMOMI)
def list_non_ssds(host, username, password, protocol=None, port=None, host_names=None):
service_instance = salt.utils.vmware.get_service_instance(host=host, username=username, password=password, protocol=protocol, port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
names = []
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
disks = _get_host_non_ssds(host_ref)
for disk in disks:
names.append(disk.canonicalName)
ret.update({host_name: names})
return ret
| [
"@",
"depends",
"(",
"HAS_PYVMOMI",
")",
"def",
"list_non_ssds",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_instance",
"(",
"host",
"=",
"host",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
",",
"protocol",
"=",
"protocol",
",",
"port",
"=",
"port",
")",
"host_names",
"=",
"_check_hosts",
"(",
"service_instance",
",",
"host",
",",
"host_names",
")",
"ret",
"=",
"{",
"}",
"names",
"=",
"[",
"]",
"for",
"host_name",
"in",
"host_names",
":",
"host_ref",
"=",
"_get_host_ref",
"(",
"service_instance",
",",
"host",
",",
"host_name",
"=",
"host_name",
")",
"disks",
"=",
"_get_host_non_ssds",
"(",
"host_ref",
")",
"for",
"disk",
"in",
"disks",
":",
"names",
".",
"append",
"(",
"disk",
".",
"canonicalName",
")",
"ret",
".",
"update",
"(",
"{",
"host_name",
":",
"names",
"}",
")",
"return",
"ret"
] | returns a list of non-ssd disks for the given host or list of host_names . | train | true |
22,041 | def NS(domain, resolve=True, nameserver=None):
dig = ['dig', '+short', str(domain), 'NS']
if (nameserver is not None):
dig.append('@{0}'.format(nameserver))
cmd = __salt__['cmd.run_all'](dig, python_shell=False)
if (cmd['retcode'] != 0):
log.warning("dig returned exit code '{0}'. Returning empty list as fallback.".format(cmd['retcode']))
return []
if resolve:
ret = []
for ns_host in cmd['stdout'].split('\n'):
for ip_addr in A(ns_host, nameserver):
ret.append(ip_addr)
return ret
return cmd['stdout'].split('\n')
| [
"def",
"NS",
"(",
"domain",
",",
"resolve",
"=",
"True",
",",
"nameserver",
"=",
"None",
")",
":",
"dig",
"=",
"[",
"'dig'",
",",
"'+short'",
",",
"str",
"(",
"domain",
")",
",",
"'NS'",
"]",
"if",
"(",
"nameserver",
"is",
"not",
"None",
")",
":",
"dig",
".",
"append",
"(",
"'@{0}'",
".",
"format",
"(",
"nameserver",
")",
")",
"cmd",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"dig",
",",
"python_shell",
"=",
"False",
")",
"if",
"(",
"cmd",
"[",
"'retcode'",
"]",
"!=",
"0",
")",
":",
"log",
".",
"warning",
"(",
"\"dig returned exit code '{0}'. Returning empty list as fallback.\"",
".",
"format",
"(",
"cmd",
"[",
"'retcode'",
"]",
")",
")",
"return",
"[",
"]",
"if",
"resolve",
":",
"ret",
"=",
"[",
"]",
"for",
"ns_host",
"in",
"cmd",
"[",
"'stdout'",
"]",
".",
"split",
"(",
"'\\n'",
")",
":",
"for",
"ip_addr",
"in",
"A",
"(",
"ns_host",
",",
"nameserver",
")",
":",
"ret",
".",
"append",
"(",
"ip_addr",
")",
"return",
"ret",
"return",
"cmd",
"[",
"'stdout'",
"]",
".",
"split",
"(",
"'\\n'",
")"
] | return a list of ips of the nameservers for domain if resolve is false . | train | true |
22,042 | def sha256_digest(instr):
if six.PY3:
b = salt.utils.to_bytes(instr)
return hashlib.sha256(b).hexdigest()
return hashlib.sha256(instr).hexdigest()
| [
"def",
"sha256_digest",
"(",
"instr",
")",
":",
"if",
"six",
".",
"PY3",
":",
"b",
"=",
"salt",
".",
"utils",
".",
"to_bytes",
"(",
"instr",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"b",
")",
".",
"hexdigest",
"(",
")",
"return",
"hashlib",
".",
"sha256",
"(",
"instr",
")",
".",
"hexdigest",
"(",
")"
] | generate an sha256 hash of a given string . | train | false |
22,043 | def _safe_output(line):
return (not any([(line.startswith('Listing') and line.endswith('...')), ('...done' in line), line.startswith('WARNING:')]))
| [
"def",
"_safe_output",
"(",
"line",
")",
":",
"return",
"(",
"not",
"any",
"(",
"[",
"(",
"line",
".",
"startswith",
"(",
"'Listing'",
")",
"and",
"line",
".",
"endswith",
"(",
"'...'",
")",
")",
",",
"(",
"'...done'",
"in",
"line",
")",
",",
"line",
".",
"startswith",
"(",
"'WARNING:'",
")",
"]",
")",
")"
] | looks for rabbitmqctl warning . | train | true |
22,044 | def get_connection_string():
raw_ips = file_io.read(RABBITMQ_LOCATION_FILE)
ips = raw_ips.split('\n')
rabbitmq_ip = ips[0]
return (((('amqp://guest:guest@' + rabbitmq_ip) + ':') + str(RABBITMQ_PORT)) + '//')
| [
"def",
"get_connection_string",
"(",
")",
":",
"raw_ips",
"=",
"file_io",
".",
"read",
"(",
"RABBITMQ_LOCATION_FILE",
")",
"ips",
"=",
"raw_ips",
".",
"split",
"(",
"'\\n'",
")",
"rabbitmq_ip",
"=",
"ips",
"[",
"0",
"]",
"return",
"(",
"(",
"(",
"(",
"'amqp://guest:guest@'",
"+",
"rabbitmq_ip",
")",
"+",
"':'",
")",
"+",
"str",
"(",
"RABBITMQ_PORT",
")",
")",
"+",
"'//'",
")"
] | reads from the local fs to get the rabbitmq location to connect to . | train | false |
22,045 | @handle_response_format
@treeio_login_required
def watchlist(request, response_format='html'):
profile = request.user.profile
watchlist = profile.subscriptions.all()
context = {'profile': profile, 'watchlist': watchlist}
return render_to_response('account/watchlist', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"watchlist",
"(",
"request",
",",
"response_format",
"=",
"'html'",
")",
":",
"profile",
"=",
"request",
".",
"user",
".",
"profile",
"watchlist",
"=",
"profile",
".",
"subscriptions",
".",
"all",
"(",
")",
"context",
"=",
"{",
"'profile'",
":",
"profile",
",",
"'watchlist'",
":",
"watchlist",
"}",
"return",
"render_to_response",
"(",
"'account/watchlist'",
",",
"context",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | displays all objects a user is subscribed to . | train | false |
22,046 | def add_lowess(ax, lines_idx=0, frac=0.2, **lowess_kwargs):
y0 = ax.get_lines()[lines_idx]._y
x0 = ax.get_lines()[lines_idx]._x
lres = lowess(y0, x0, frac=frac, **lowess_kwargs)
ax.plot(lres[:, 0], lres[:, 1], 'r', lw=1.5)
return ax.figure
| [
"def",
"add_lowess",
"(",
"ax",
",",
"lines_idx",
"=",
"0",
",",
"frac",
"=",
"0.2",
",",
"**",
"lowess_kwargs",
")",
":",
"y0",
"=",
"ax",
".",
"get_lines",
"(",
")",
"[",
"lines_idx",
"]",
".",
"_y",
"x0",
"=",
"ax",
".",
"get_lines",
"(",
")",
"[",
"lines_idx",
"]",
".",
"_x",
"lres",
"=",
"lowess",
"(",
"y0",
",",
"x0",
",",
"frac",
"=",
"frac",
",",
"**",
"lowess_kwargs",
")",
"ax",
".",
"plot",
"(",
"lres",
"[",
":",
",",
"0",
"]",
",",
"lres",
"[",
":",
",",
"1",
"]",
",",
"'r'",
",",
"lw",
"=",
"1.5",
")",
"return",
"ax",
".",
"figure"
] | add lowess line to a plot . | train | false |
22,047 | @api_wrapper
def update_pool(module, system, pool):
changed = False
size = module.params['size']
vsize = module.params['vsize']
ssd_cache = module.params['ssd_cache']
if size:
physical_capacity = Capacity(size).roundup(((6 * 64) * KiB))
if (pool.get_physical_capacity() != physical_capacity):
if (not module.check_mode):
pool.update_physical_capacity(physical_capacity)
changed = True
if vsize:
virtual_capacity = Capacity(vsize).roundup(((6 * 64) * KiB))
if (pool.get_virtual_capacity() != virtual_capacity):
if (not module.check_mode):
pool.update_virtual_capacity(virtual_capacity)
changed = True
if (pool.get_ssd_enabled() != ssd_cache):
if (not module.check_mode):
pool.update_ssd_enabled(ssd_cache)
changed = True
module.exit_json(changed=changed)
| [
"@",
"api_wrapper",
"def",
"update_pool",
"(",
"module",
",",
"system",
",",
"pool",
")",
":",
"changed",
"=",
"False",
"size",
"=",
"module",
".",
"params",
"[",
"'size'",
"]",
"vsize",
"=",
"module",
".",
"params",
"[",
"'vsize'",
"]",
"ssd_cache",
"=",
"module",
".",
"params",
"[",
"'ssd_cache'",
"]",
"if",
"size",
":",
"physical_capacity",
"=",
"Capacity",
"(",
"size",
")",
".",
"roundup",
"(",
"(",
"(",
"6",
"*",
"64",
")",
"*",
"KiB",
")",
")",
"if",
"(",
"pool",
".",
"get_physical_capacity",
"(",
")",
"!=",
"physical_capacity",
")",
":",
"if",
"(",
"not",
"module",
".",
"check_mode",
")",
":",
"pool",
".",
"update_physical_capacity",
"(",
"physical_capacity",
")",
"changed",
"=",
"True",
"if",
"vsize",
":",
"virtual_capacity",
"=",
"Capacity",
"(",
"vsize",
")",
".",
"roundup",
"(",
"(",
"(",
"6",
"*",
"64",
")",
"*",
"KiB",
")",
")",
"if",
"(",
"pool",
".",
"get_virtual_capacity",
"(",
")",
"!=",
"virtual_capacity",
")",
":",
"if",
"(",
"not",
"module",
".",
"check_mode",
")",
":",
"pool",
".",
"update_virtual_capacity",
"(",
"virtual_capacity",
")",
"changed",
"=",
"True",
"if",
"(",
"pool",
".",
"get_ssd_enabled",
"(",
")",
"!=",
"ssd_cache",
")",
":",
"if",
"(",
"not",
"module",
".",
"check_mode",
")",
":",
"pool",
".",
"update_ssd_enabled",
"(",
"ssd_cache",
")",
"changed",
"=",
"True",
"module",
".",
"exit_json",
"(",
"changed",
"=",
"changed",
")"
] | update pool . | train | false |
22,049 | def approx_point_little(src, dest):
xy = src.read((2 * 8))
dest.write('\x00\x00\x00')
dest.write(xy[(-13):(-8)])
dest.write('\x00\x00\x00')
dest.write(xy[(-5):])
| [
"def",
"approx_point_little",
"(",
"src",
",",
"dest",
")",
":",
"xy",
"=",
"src",
".",
"read",
"(",
"(",
"2",
"*",
"8",
")",
")",
"dest",
".",
"write",
"(",
"'\\x00\\x00\\x00'",
")",
"dest",
".",
"write",
"(",
"xy",
"[",
"(",
"-",
"13",
")",
":",
"(",
"-",
"8",
")",
"]",
")",
"dest",
".",
"write",
"(",
"'\\x00\\x00\\x00'",
")",
"dest",
".",
"write",
"(",
"xy",
"[",
"(",
"-",
"5",
")",
":",
"]",
")"
] | copy a pair of little-endian doubles between files . | train | false |
22,050 | def get_resume_recommendations(user, request):
final = get_most_recent_incomplete_item(user)
if final:
content = get_content_item(language=request.language, channel=getattr(final, 'channel', 'khan'), content_id=final.get('id'))
return ([content] if content else [])
else:
return []
| [
"def",
"get_resume_recommendations",
"(",
"user",
",",
"request",
")",
":",
"final",
"=",
"get_most_recent_incomplete_item",
"(",
"user",
")",
"if",
"final",
":",
"content",
"=",
"get_content_item",
"(",
"language",
"=",
"request",
".",
"language",
",",
"channel",
"=",
"getattr",
"(",
"final",
",",
"'channel'",
",",
"'khan'",
")",
",",
"content_id",
"=",
"final",
".",
"get",
"(",
"'id'",
")",
")",
"return",
"(",
"[",
"content",
"]",
"if",
"content",
"else",
"[",
"]",
")",
"else",
":",
"return",
"[",
"]"
] | get the recommendation for the resume section . | train | false |
22,051 | def approve_files(files_with_review_type):
for (file_, review_type) in files_with_review_type:
version = file_.version
addon = version.addon
helper = ReviewHelper(request=None, addon=addon, version=file_.version)
helper.set_data({'addon_files': [file_], 'comments': u'bulk approval'})
if (review_type == 'full'):
helper.handler.process_public()
log.info(u'File %s (addon %s) approved', file_.pk, addon.pk)
else:
log.info(u'File %s (addon %s) not approved: addon status: %s, file status: %s', file_.pk, addon.pk, addon.status, file_.status)
| [
"def",
"approve_files",
"(",
"files_with_review_type",
")",
":",
"for",
"(",
"file_",
",",
"review_type",
")",
"in",
"files_with_review_type",
":",
"version",
"=",
"file_",
".",
"version",
"addon",
"=",
"version",
".",
"addon",
"helper",
"=",
"ReviewHelper",
"(",
"request",
"=",
"None",
",",
"addon",
"=",
"addon",
",",
"version",
"=",
"file_",
".",
"version",
")",
"helper",
".",
"set_data",
"(",
"{",
"'addon_files'",
":",
"[",
"file_",
"]",
",",
"'comments'",
":",
"u'bulk approval'",
"}",
")",
"if",
"(",
"review_type",
"==",
"'full'",
")",
":",
"helper",
".",
"handler",
".",
"process_public",
"(",
")",
"log",
".",
"info",
"(",
"u'File %s (addon %s) approved'",
",",
"file_",
".",
"pk",
",",
"addon",
".",
"pk",
")",
"else",
":",
"log",
".",
"info",
"(",
"u'File %s (addon %s) not approved: addon status: %s, file status: %s'",
",",
"file_",
".",
"pk",
",",
"addon",
".",
"pk",
",",
"addon",
".",
"status",
",",
"file_",
".",
"status",
")"
] | approve the files waiting for review . | train | false |
22,052 | def test_stereo_motorcycle():
data.stereo_motorcycle()
| [
"def",
"test_stereo_motorcycle",
"(",
")",
":",
"data",
".",
"stereo_motorcycle",
"(",
")"
] | test that "stereo_motorcycle" image can be loaded . | train | false |
22,054 | def cigame(registry, xml_parent, data):
XML.SubElement(xml_parent, 'hudson.plugins.cigame.GamePublisher')
| [
"def",
"cigame",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.cigame.GamePublisher'",
")"
] | yaml: cigame this plugin introduces a game where users get points for improving the builds . | train | false |
22,056 | @task
def pypi_register():
with cd('/home/vagrant/repos/sympy'):
run('python setup.py register')
| [
"@",
"task",
"def",
"pypi_register",
"(",
")",
":",
"with",
"cd",
"(",
"'/home/vagrant/repos/sympy'",
")",
":",
"run",
"(",
"'python setup.py register'",
")"
] | register a release with pypi this should only be done for the final release . | train | false |
22,057 | def user_has_perm_app(user, obj):
has_perm = False
if (obj.__class__ == Webapp):
has_perm = (user.addons.filter(pk=obj.id).exists() or (user.email in obj.get_mozilla_contacts()))
elif (obj.__class__ == Extension):
has_perm = user.extension_set.filter(pk=obj.id).exists()
return (has_perm or check_acls(user, None, 'reviewer') or check_acls(user, None, 'senior_reviewer') or check_acls(user, None, 'admin'))
| [
"def",
"user_has_perm_app",
"(",
"user",
",",
"obj",
")",
":",
"has_perm",
"=",
"False",
"if",
"(",
"obj",
".",
"__class__",
"==",
"Webapp",
")",
":",
"has_perm",
"=",
"(",
"user",
".",
"addons",
".",
"filter",
"(",
"pk",
"=",
"obj",
".",
"id",
")",
".",
"exists",
"(",
")",
"or",
"(",
"user",
".",
"email",
"in",
"obj",
".",
"get_mozilla_contacts",
"(",
")",
")",
")",
"elif",
"(",
"obj",
".",
"__class__",
"==",
"Extension",
")",
":",
"has_perm",
"=",
"user",
".",
"extension_set",
".",
"filter",
"(",
"pk",
"=",
"obj",
".",
"id",
")",
".",
"exists",
"(",
")",
"return",
"(",
"has_perm",
"or",
"check_acls",
"(",
"user",
",",
"None",
",",
"'reviewer'",
")",
"or",
"check_acls",
"(",
"user",
",",
"None",
",",
"'senior_reviewer'",
")",
"or",
"check_acls",
"(",
"user",
",",
"None",
",",
"'admin'",
")",
")"
] | its named app for historical reasons . | train | false |
22,058 | def getBytesFromFile(filename, offset, numBytes):
if ((not isinstance(offset, int)) or (not isinstance(numBytes, int))):
return ((-1), 'The offset and the number of bytes must be integers')
if os.path.exists(filename):
fileSize = os.path.getsize(filename)
bytesFile = open(filename, 'rb')
bytesFile.seek(offset)
if ((offset + numBytes) > fileSize):
bytes = bytesFile.read()
else:
bytes = bytesFile.read(numBytes)
bytesFile.close()
return (0, bytes)
else:
return ((-1), 'File does not exist')
| [
"def",
"getBytesFromFile",
"(",
"filename",
",",
"offset",
",",
"numBytes",
")",
":",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"offset",
",",
"int",
")",
")",
"or",
"(",
"not",
"isinstance",
"(",
"numBytes",
",",
"int",
")",
")",
")",
":",
"return",
"(",
"(",
"-",
"1",
")",
",",
"'The offset and the number of bytes must be integers'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"fileSize",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
"bytesFile",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"bytesFile",
".",
"seek",
"(",
"offset",
")",
"if",
"(",
"(",
"offset",
"+",
"numBytes",
")",
">",
"fileSize",
")",
":",
"bytes",
"=",
"bytesFile",
".",
"read",
"(",
")",
"else",
":",
"bytes",
"=",
"bytesFile",
".",
"read",
"(",
"numBytes",
")",
"bytesFile",
".",
"close",
"(",
")",
"return",
"(",
"0",
",",
"bytes",
")",
"else",
":",
"return",
"(",
"(",
"-",
"1",
")",
",",
"'File does not exist'",
")"
] | returns the number of bytes specified from a file . | train | false |
22,059 | def create_executable():
dist = Distribution()
name = 'spyder'
ver = spyder.__version__
try:
imp.find_module('PyQt4')
python_qt = 'pyqt'
except ImportError:
python_qt = 'pyside'
dist.setup(name='Spyder', version=ver, script='spyder/spyder.py', description='Scientific PYthon Development EnviRonment', target_name=('%s.exe' % name), icon=('%s.ico' % name), target_dir=('%s-win32-%s-sa-%s' % (name, python_qt, ver)))
spyder.add_to_distribution(dist)
dist.add_modules('matplotlib', 'h5py', 'scipy.io', 'guidata', 'pygments')
try:
import guiqwt
dist.add_modules('guiqwt')
except ImportError:
pass
dist.includes += ['spyder.scientific_startup', 'spyder.widgets.externalshell.sitecustomize']
dist.excludes += ['sphinx', 'zmq', 'IPython']
if osp.isfile('Spyderdoc.chm'):
dist.add_data_file('Spyderdoc.chm')
dist.add_data_file(osp.join('rope', 'base', 'default_config.py'))
dist.build('cx_Freeze')
| [
"def",
"create_executable",
"(",
")",
":",
"dist",
"=",
"Distribution",
"(",
")",
"name",
"=",
"'spyder'",
"ver",
"=",
"spyder",
".",
"__version__",
"try",
":",
"imp",
".",
"find_module",
"(",
"'PyQt4'",
")",
"python_qt",
"=",
"'pyqt'",
"except",
"ImportError",
":",
"python_qt",
"=",
"'pyside'",
"dist",
".",
"setup",
"(",
"name",
"=",
"'Spyder'",
",",
"version",
"=",
"ver",
",",
"script",
"=",
"'spyder/spyder.py'",
",",
"description",
"=",
"'Scientific PYthon Development EnviRonment'",
",",
"target_name",
"=",
"(",
"'%s.exe'",
"%",
"name",
")",
",",
"icon",
"=",
"(",
"'%s.ico'",
"%",
"name",
")",
",",
"target_dir",
"=",
"(",
"'%s-win32-%s-sa-%s'",
"%",
"(",
"name",
",",
"python_qt",
",",
"ver",
")",
")",
")",
"spyder",
".",
"add_to_distribution",
"(",
"dist",
")",
"dist",
".",
"add_modules",
"(",
"'matplotlib'",
",",
"'h5py'",
",",
"'scipy.io'",
",",
"'guidata'",
",",
"'pygments'",
")",
"try",
":",
"import",
"guiqwt",
"dist",
".",
"add_modules",
"(",
"'guiqwt'",
")",
"except",
"ImportError",
":",
"pass",
"dist",
".",
"includes",
"+=",
"[",
"'spyder.scientific_startup'",
",",
"'spyder.widgets.externalshell.sitecustomize'",
"]",
"dist",
".",
"excludes",
"+=",
"[",
"'sphinx'",
",",
"'zmq'",
",",
"'IPython'",
"]",
"if",
"osp",
".",
"isfile",
"(",
"'Spyderdoc.chm'",
")",
":",
"dist",
".",
"add_data_file",
"(",
"'Spyderdoc.chm'",
")",
"dist",
".",
"add_data_file",
"(",
"osp",
".",
"join",
"(",
"'rope'",
",",
"'base'",
",",
"'default_config.py'",
")",
")",
"dist",
".",
"build",
"(",
"'cx_Freeze'",
")"
] | build executable using guidata . | train | false |
22,060 | def APEValue(value, kind):
try:
type_ = _get_value_type(kind)
except ValueError:
raise ValueError('kind must be TEXT, BINARY, or EXTERNAL')
else:
return type_(value)
| [
"def",
"APEValue",
"(",
"value",
",",
"kind",
")",
":",
"try",
":",
"type_",
"=",
"_get_value_type",
"(",
"kind",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'kind must be TEXT, BINARY, or EXTERNAL'",
")",
"else",
":",
"return",
"type_",
"(",
"value",
")"
] | apev2 tag value factory . | train | true |
22,064 | def read_sql(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None, chunksize=None):
pandas_sql = pandasSQL_builder(con)
if isinstance(pandas_sql, SQLiteDatabase):
return pandas_sql.read_query(sql, index_col=index_col, params=params, coerce_float=coerce_float, parse_dates=parse_dates, chunksize=chunksize)
try:
_is_table_name = pandas_sql.has_table(sql)
except:
_is_table_name = False
if _is_table_name:
pandas_sql.meta.reflect(only=[sql])
return pandas_sql.read_table(sql, index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, columns=columns, chunksize=chunksize)
else:
return pandas_sql.read_query(sql, index_col=index_col, params=params, coerce_float=coerce_float, parse_dates=parse_dates, chunksize=chunksize)
| [
"def",
"read_sql",
"(",
"sql",
",",
"con",
",",
"index_col",
"=",
"None",
",",
"coerce_float",
"=",
"True",
",",
"params",
"=",
"None",
",",
"parse_dates",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"chunksize",
"=",
"None",
")",
":",
"pandas_sql",
"=",
"pandasSQL_builder",
"(",
"con",
")",
"if",
"isinstance",
"(",
"pandas_sql",
",",
"SQLiteDatabase",
")",
":",
"return",
"pandas_sql",
".",
"read_query",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"params",
"=",
"params",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"chunksize",
"=",
"chunksize",
")",
"try",
":",
"_is_table_name",
"=",
"pandas_sql",
".",
"has_table",
"(",
"sql",
")",
"except",
":",
"_is_table_name",
"=",
"False",
"if",
"_is_table_name",
":",
"pandas_sql",
".",
"meta",
".",
"reflect",
"(",
"only",
"=",
"[",
"sql",
"]",
")",
"return",
"pandas_sql",
".",
"read_table",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"columns",
"=",
"columns",
",",
"chunksize",
"=",
"chunksize",
")",
"else",
":",
"return",
"pandas_sql",
".",
"read_query",
"(",
"sql",
",",
"index_col",
"=",
"index_col",
",",
"params",
"=",
"params",
",",
"coerce_float",
"=",
"coerce_float",
",",
"parse_dates",
"=",
"parse_dates",
",",
"chunksize",
"=",
"chunksize",
")"
] | read sql query or database table into a dataframe . | train | true |
22,066 | def test_ee_fit_single_class():
ratio = 'auto'
ee = EasyEnsemble(ratio=ratio, random_state=RND_SEED)
y_single_class = np.zeros((X.shape[0],))
assert_warns(UserWarning, ee.fit, X, y_single_class)
| [
"def",
"test_ee_fit_single_class",
"(",
")",
":",
"ratio",
"=",
"'auto'",
"ee",
"=",
"EasyEnsemble",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"y_single_class",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"assert_warns",
"(",
"UserWarning",
",",
"ee",
".",
"fit",
",",
"X",
",",
"y_single_class",
")"
] | test either if an error when there is a single class . | train | false |
22,067 | @pytest.mark.django_db
def test_data_store(tp0):
store = StoreDBFactory(name='foo.po', parent=tp0.directory, translation_project=tp0)
assert (repr(store.data) == ('<StoreData: %s>' % store.pootle_path))
| [
"@",
"pytest",
".",
"mark",
".",
"django_db",
"def",
"test_data_store",
"(",
"tp0",
")",
":",
"store",
"=",
"StoreDBFactory",
"(",
"name",
"=",
"'foo.po'",
",",
"parent",
"=",
"tp0",
".",
"directory",
",",
"translation_project",
"=",
"tp0",
")",
"assert",
"(",
"repr",
"(",
"store",
".",
"data",
")",
"==",
"(",
"'<StoreData: %s>'",
"%",
"store",
".",
"pootle_path",
")",
")"
] | test that you cant add a duplicate file extension . | train | false |
22,069 | def dtype_limits(image, clip_negative=None):
if (clip_negative is None):
clip_negative = True
warn('The default of `clip_negative` in `skimage.util.dtype_limits` will change to `False` in version 0.15.')
(imin, imax) = dtype_range[image.dtype.type]
if clip_negative:
imin = 0
return (imin, imax)
| [
"def",
"dtype_limits",
"(",
"image",
",",
"clip_negative",
"=",
"None",
")",
":",
"if",
"(",
"clip_negative",
"is",
"None",
")",
":",
"clip_negative",
"=",
"True",
"warn",
"(",
"'The default of `clip_negative` in `skimage.util.dtype_limits` will change to `False` in version 0.15.'",
")",
"(",
"imin",
",",
"imax",
")",
"=",
"dtype_range",
"[",
"image",
".",
"dtype",
".",
"type",
"]",
"if",
"clip_negative",
":",
"imin",
"=",
"0",
"return",
"(",
"imin",
",",
"imax",
")"
] | return intensity limits . | train | false |
22,070 | def assign_role_for_collection(committer_id, collection_id, assignee_id, new_role):
_assign_role(committer_id, assignee_id, new_role, collection_id, feconf.ACTIVITY_TYPE_COLLECTION)
if (new_role in [ROLE_OWNER, ROLE_EDITOR]):
subscription_services.subscribe_to_collection(assignee_id, collection_id)
| [
"def",
"assign_role_for_collection",
"(",
"committer_id",
",",
"collection_id",
",",
"assignee_id",
",",
"new_role",
")",
":",
"_assign_role",
"(",
"committer_id",
",",
"assignee_id",
",",
"new_role",
",",
"collection_id",
",",
"feconf",
".",
"ACTIVITY_TYPE_COLLECTION",
")",
"if",
"(",
"new_role",
"in",
"[",
"ROLE_OWNER",
",",
"ROLE_EDITOR",
"]",
")",
":",
"subscription_services",
".",
"subscribe_to_collection",
"(",
"assignee_id",
",",
"collection_id",
")"
] | assign assignee_id to the given role and subscribes the assignee to future collection updates . | train | false |
22,073 | def rebot_cli(arguments, exit=True):
return Rebot().execute_cli(arguments, exit=exit)
| [
"def",
"rebot_cli",
"(",
"arguments",
",",
"exit",
"=",
"True",
")",
":",
"return",
"Rebot",
"(",
")",
".",
"execute_cli",
"(",
"arguments",
",",
"exit",
"=",
"exit",
")"
] | command line execution entry point for post-processing outputs . | train | false |
22,075 | def get_security_default():
from hadoop import cluster
cluster = cluster.get_cluster_conf_for_job_submission()
return cluster.SECURITY_ENABLED.get()
| [
"def",
"get_security_default",
"(",
")",
":",
"from",
"hadoop",
"import",
"cluster",
"cluster",
"=",
"cluster",
".",
"get_cluster_conf_for_job_submission",
"(",
")",
"return",
"cluster",
".",
"SECURITY_ENABLED",
".",
"get",
"(",
")"
] | get default security value from hadoop . | train | false |
22,076 | def url_is_from_spider(url, spider):
return url_is_from_any_domain(url, ([spider.name] + getattr(spider, 'allowed_domains', [])))
| [
"def",
"url_is_from_spider",
"(",
"url",
",",
"spider",
")",
":",
"return",
"url_is_from_any_domain",
"(",
"url",
",",
"(",
"[",
"spider",
".",
"name",
"]",
"+",
"getattr",
"(",
"spider",
",",
"'allowed_domains'",
",",
"[",
"]",
")",
")",
")"
] | return true if the url belongs to the given spider . | train | false |
22,077 | def make_abstract_dist(req_to_install):
if req_to_install.editable:
return IsSDist(req_to_install)
elif (req_to_install.link and req_to_install.link.is_wheel):
return IsWheel(req_to_install)
else:
return IsSDist(req_to_install)
| [
"def",
"make_abstract_dist",
"(",
"req_to_install",
")",
":",
"if",
"req_to_install",
".",
"editable",
":",
"return",
"IsSDist",
"(",
"req_to_install",
")",
"elif",
"(",
"req_to_install",
".",
"link",
"and",
"req_to_install",
".",
"link",
".",
"is_wheel",
")",
":",
"return",
"IsWheel",
"(",
"req_to_install",
")",
"else",
":",
"return",
"IsSDist",
"(",
"req_to_install",
")"
] | factory to make an abstract dist object . | train | true |
22,079 | def autolabel(rectangles):
for rect in rectangles:
height = rect.get_height()
ax.text((rect.get_x() + (rect.get_width() / 2.0)), (1.05 * height), ('%.4f' % height), ha='center', va='bottom')
| [
"def",
"autolabel",
"(",
"rectangles",
")",
":",
"for",
"rect",
"in",
"rectangles",
":",
"height",
"=",
"rect",
".",
"get_height",
"(",
")",
"ax",
".",
"text",
"(",
"(",
"rect",
".",
"get_x",
"(",
")",
"+",
"(",
"rect",
".",
"get_width",
"(",
")",
"/",
"2.0",
")",
")",
",",
"(",
"1.05",
"*",
"height",
")",
",",
"(",
"'%.4f'",
"%",
"height",
")",
",",
"ha",
"=",
"'center'",
",",
"va",
"=",
"'bottom'",
")"
] | attach some text vi autolabel on rectangles . | train | false |
22,080 | def _is_unicode_combining(u):
i = ord(u)
for r in _COMBINING_RANGES:
if (r[0] <= i <= r[1]):
return True
return False
| [
"def",
"_is_unicode_combining",
"(",
"u",
")",
":",
"i",
"=",
"ord",
"(",
"u",
")",
"for",
"r",
"in",
"_COMBINING_RANGES",
":",
"if",
"(",
"r",
"[",
"0",
"]",
"<=",
"i",
"<=",
"r",
"[",
"1",
"]",
")",
":",
"return",
"True",
"return",
"False"
] | check if input unicode is combining diacritical mark . | train | false |
22,082 | @slow_test
@testing.requires_testing_data
def test_volume_source_space():
tempdir = _TempDir()
src = read_source_spaces(fname_vol)
temp_name = op.join(tempdir, 'temp-src.fif')
surf = read_bem_surfaces(fname_bem, s_id=FIFF.FIFFV_BEM_SURF_ID_BRAIN)
surf['rr'] *= 1000.0
for (bem, surf) in zip((fname_bem, None), (None, surf)):
src_new = setup_volume_source_space('sample', temp_name, pos=7.0, bem=bem, surface=surf, mri='T1.mgz', subjects_dir=subjects_dir)
src[0]['subject_his_id'] = 'sample'
_compare_source_spaces(src, src_new, mode='approx')
del src_new
src_new = read_source_spaces(temp_name)
_compare_source_spaces(src, src_new, mode='approx')
assert_raises(IOError, setup_volume_source_space, 'sample', temp_name, pos=7.0, bem=None, surface='foo', mri=fname_mri, subjects_dir=subjects_dir)
assert_equal(repr(src), repr(src_new))
assert_equal(src.kind, 'volume')
| [
"@",
"slow_test",
"@",
"testing",
".",
"requires_testing_data",
"def",
"test_volume_source_space",
"(",
")",
":",
"tempdir",
"=",
"_TempDir",
"(",
")",
"src",
"=",
"read_source_spaces",
"(",
"fname_vol",
")",
"temp_name",
"=",
"op",
".",
"join",
"(",
"tempdir",
",",
"'temp-src.fif'",
")",
"surf",
"=",
"read_bem_surfaces",
"(",
"fname_bem",
",",
"s_id",
"=",
"FIFF",
".",
"FIFFV_BEM_SURF_ID_BRAIN",
")",
"surf",
"[",
"'rr'",
"]",
"*=",
"1000.0",
"for",
"(",
"bem",
",",
"surf",
")",
"in",
"zip",
"(",
"(",
"fname_bem",
",",
"None",
")",
",",
"(",
"None",
",",
"surf",
")",
")",
":",
"src_new",
"=",
"setup_volume_source_space",
"(",
"'sample'",
",",
"temp_name",
",",
"pos",
"=",
"7.0",
",",
"bem",
"=",
"bem",
",",
"surface",
"=",
"surf",
",",
"mri",
"=",
"'T1.mgz'",
",",
"subjects_dir",
"=",
"subjects_dir",
")",
"src",
"[",
"0",
"]",
"[",
"'subject_his_id'",
"]",
"=",
"'sample'",
"_compare_source_spaces",
"(",
"src",
",",
"src_new",
",",
"mode",
"=",
"'approx'",
")",
"del",
"src_new",
"src_new",
"=",
"read_source_spaces",
"(",
"temp_name",
")",
"_compare_source_spaces",
"(",
"src",
",",
"src_new",
",",
"mode",
"=",
"'approx'",
")",
"assert_raises",
"(",
"IOError",
",",
"setup_volume_source_space",
",",
"'sample'",
",",
"temp_name",
",",
"pos",
"=",
"7.0",
",",
"bem",
"=",
"None",
",",
"surface",
"=",
"'foo'",
",",
"mri",
"=",
"fname_mri",
",",
"subjects_dir",
"=",
"subjects_dir",
")",
"assert_equal",
"(",
"repr",
"(",
"src",
")",
",",
"repr",
"(",
"src_new",
")",
")",
"assert_equal",
"(",
"src",
".",
"kind",
",",
"'volume'",
")"
] | test setting up volume source spaces . | train | false |
22,084 | def delete_model(model, item_id, event_id=None):
if (event_id is not None):
item = get_object_in_event(model, item_id, event_id)
else:
item = get_object_or_404(model, item_id)
if hasattr(item, 'in_trash'):
item.in_trash = True
save_to_db(item, '{} moved to trash'.format(model.__name__))
else:
delete_from_db(item, '{} deleted'.format(model.__name__))
return item
| [
"def",
"delete_model",
"(",
"model",
",",
"item_id",
",",
"event_id",
"=",
"None",
")",
":",
"if",
"(",
"event_id",
"is",
"not",
"None",
")",
":",
"item",
"=",
"get_object_in_event",
"(",
"model",
",",
"item_id",
",",
"event_id",
")",
"else",
":",
"item",
"=",
"get_object_or_404",
"(",
"model",
",",
"item_id",
")",
"if",
"hasattr",
"(",
"item",
",",
"'in_trash'",
")",
":",
"item",
".",
"in_trash",
"=",
"True",
"save_to_db",
"(",
"item",
",",
"'{} moved to trash'",
".",
"format",
"(",
"model",
".",
"__name__",
")",
")",
"else",
":",
"delete_from_db",
"(",
"item",
",",
"'{} deleted'",
".",
"format",
"(",
"model",
".",
"__name__",
")",
")",
"return",
"item"
] | deletes a model if event_id is set . | train | false |
22,086 | @utils.no_4byte_params
def metadef_tag_create(context, namespace_name, tag_dict, session=None):
session = (session or get_session())
return metadef_tag_api.create(context, namespace_name, tag_dict, session)
| [
"@",
"utils",
".",
"no_4byte_params",
"def",
"metadef_tag_create",
"(",
"context",
",",
"namespace_name",
",",
"tag_dict",
",",
"session",
"=",
"None",
")",
":",
"session",
"=",
"(",
"session",
"or",
"get_session",
"(",
")",
")",
"return",
"metadef_tag_api",
".",
"create",
"(",
"context",
",",
"namespace_name",
",",
"tag_dict",
",",
"session",
")"
] | create a metadef tag . | train | false |
22,087 | @lower_constant(types.Record)
def constant_record(context, builder, ty, pyval):
lty = ir.ArrayType(ir.IntType(8), pyval.nbytes)
val = lty(bytearray(pyval.tostring()))
return cgutils.alloca_once_value(builder, val)
| [
"@",
"lower_constant",
"(",
"types",
".",
"Record",
")",
"def",
"constant_record",
"(",
"context",
",",
"builder",
",",
"ty",
",",
"pyval",
")",
":",
"lty",
"=",
"ir",
".",
"ArrayType",
"(",
"ir",
".",
"IntType",
"(",
"8",
")",
",",
"pyval",
".",
"nbytes",
")",
"val",
"=",
"lty",
"(",
"bytearray",
"(",
"pyval",
".",
"tostring",
"(",
")",
")",
")",
"return",
"cgutils",
".",
"alloca_once_value",
"(",
"builder",
",",
"val",
")"
] | create a record constant as a stack-allocated array of bytes . | train | false |
22,090 | def modelControlFinishLearningCb(model):
model.finishLearning()
return
| [
"def",
"modelControlFinishLearningCb",
"(",
"model",
")",
":",
"model",
".",
"finishLearning",
"(",
")",
"return"
] | passes the "finish learning" command to the model . | train | false |
22,095 | def check_header_required_fields(header, errors, sample_id_ix, desc_ix, bc_ix, linker_primer_ix, added_demultiplex_field=None):
header_checks = {sample_id_ix: 'SampleID', desc_ix: 'Description', bc_ix: 'BarcodeSequence', linker_primer_ix: 'LinkerPrimerSequence'}
for curr_check in header_checks:
if ((header[curr_check] != header_checks[curr_check]) and (header_checks[curr_check] == 'Description')):
errors.append((('Found header field %s, last field should be %s' % (header[curr_check], header_checks[curr_check])) + (' DCTB %d,%d' % (0, curr_check))))
elif ((header[curr_check] != header_checks[curr_check]) and (header_checks[curr_check] != 'Description')):
errors.append((('Found header field %s, expected field %s' % (header[curr_check], header_checks[curr_check])) + (' DCTB %d,%d' % (0, curr_check))))
if added_demultiplex_field:
if (added_demultiplex_field not in header):
errors.append(('Missing added demultiplex field %s DCTB %d,%d' % (added_demultiplex_field, (-1), (-1))))
return errors
| [
"def",
"check_header_required_fields",
"(",
"header",
",",
"errors",
",",
"sample_id_ix",
",",
"desc_ix",
",",
"bc_ix",
",",
"linker_primer_ix",
",",
"added_demultiplex_field",
"=",
"None",
")",
":",
"header_checks",
"=",
"{",
"sample_id_ix",
":",
"'SampleID'",
",",
"desc_ix",
":",
"'Description'",
",",
"bc_ix",
":",
"'BarcodeSequence'",
",",
"linker_primer_ix",
":",
"'LinkerPrimerSequence'",
"}",
"for",
"curr_check",
"in",
"header_checks",
":",
"if",
"(",
"(",
"header",
"[",
"curr_check",
"]",
"!=",
"header_checks",
"[",
"curr_check",
"]",
")",
"and",
"(",
"header_checks",
"[",
"curr_check",
"]",
"==",
"'Description'",
")",
")",
":",
"errors",
".",
"append",
"(",
"(",
"(",
"'Found header field %s, last field should be %s'",
"%",
"(",
"header",
"[",
"curr_check",
"]",
",",
"header_checks",
"[",
"curr_check",
"]",
")",
")",
"+",
"(",
"' DCTB %d,%d'",
"%",
"(",
"0",
",",
"curr_check",
")",
")",
")",
")",
"elif",
"(",
"(",
"header",
"[",
"curr_check",
"]",
"!=",
"header_checks",
"[",
"curr_check",
"]",
")",
"and",
"(",
"header_checks",
"[",
"curr_check",
"]",
"!=",
"'Description'",
")",
")",
":",
"errors",
".",
"append",
"(",
"(",
"(",
"'Found header field %s, expected field %s'",
"%",
"(",
"header",
"[",
"curr_check",
"]",
",",
"header_checks",
"[",
"curr_check",
"]",
")",
")",
"+",
"(",
"' DCTB %d,%d'",
"%",
"(",
"0",
",",
"curr_check",
")",
")",
")",
")",
"if",
"added_demultiplex_field",
":",
"if",
"(",
"added_demultiplex_field",
"not",
"in",
"header",
")",
":",
"errors",
".",
"append",
"(",
"(",
"'Missing added demultiplex field %s DCTB %d,%d'",
"%",
"(",
"added_demultiplex_field",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
")",
")",
"return",
"errors"
] | checks for required header fields . | train | false |
22,096 | def _find_files(metadata):
ret = {}
for (bucket, data) in six.iteritems(metadata):
if (bucket not in ret):
ret[bucket] = []
filePaths = [k['Key'] for k in data]
ret[bucket] += [k for k in filePaths if (not k.endswith('/'))]
return ret
| [
"def",
"_find_files",
"(",
"metadata",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"(",
"bucket",
",",
"data",
")",
"in",
"six",
".",
"iteritems",
"(",
"metadata",
")",
":",
"if",
"(",
"bucket",
"not",
"in",
"ret",
")",
":",
"ret",
"[",
"bucket",
"]",
"=",
"[",
"]",
"filePaths",
"=",
"[",
"k",
"[",
"'Key'",
"]",
"for",
"k",
"in",
"data",
"]",
"ret",
"[",
"bucket",
"]",
"+=",
"[",
"k",
"for",
"k",
"in",
"filePaths",
"if",
"(",
"not",
"k",
".",
"endswith",
"(",
"'/'",
")",
")",
"]",
"return",
"ret"
] | return a list of paths to all modules below the given directory . | train | true |
22,097 | def rogerstanimoto(u, v):
u = _validate_vector(u)
v = _validate_vector(v)
(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)
return (float((2.0 * (ntf + nft))) / float(((ntt + nff) + (2.0 * (ntf + nft)))))
| [
"def",
"rogerstanimoto",
"(",
"u",
",",
"v",
")",
":",
"u",
"=",
"_validate_vector",
"(",
"u",
")",
"v",
"=",
"_validate_vector",
"(",
"v",
")",
"(",
"nff",
",",
"nft",
",",
"ntf",
",",
"ntt",
")",
"=",
"_nbool_correspond_all",
"(",
"u",
",",
"v",
")",
"return",
"(",
"float",
"(",
"(",
"2.0",
"*",
"(",
"ntf",
"+",
"nft",
")",
")",
")",
"/",
"float",
"(",
"(",
"(",
"ntt",
"+",
"nff",
")",
"+",
"(",
"2.0",
"*",
"(",
"ntf",
"+",
"nft",
")",
")",
")",
")",
")"
] | computes the rogers-tanimoto dissimilarity between two boolean 1-d arrays . | train | false |
22,099 | def join_css_classes(class_list):
return ' '.join(sorted((str(val) for val in class_list if val)))
| [
"def",
"join_css_classes",
"(",
"class_list",
")",
":",
"return",
"' '",
".",
"join",
"(",
"sorted",
"(",
"(",
"str",
"(",
"val",
")",
"for",
"val",
"in",
"class_list",
"if",
"val",
")",
")",
")"
] | join an iterable of truthy values by spaces . | train | false |
22,100 | @deprecated(Version('Twisted', 16, 7, 0), _GETPAGE_REPLACEMENT_TEXT)
def downloadPage(url, file, contextFactory=None, *args, **kwargs):
factoryFactory = (lambda url, *a, **kw: HTTPDownloader(url, file, *a, **kw))
return _makeGetterFactory(url, factoryFactory, contextFactory=contextFactory, *args, **kwargs).deferred
| [
"@",
"deprecated",
"(",
"Version",
"(",
"'Twisted'",
",",
"16",
",",
"7",
",",
"0",
")",
",",
"_GETPAGE_REPLACEMENT_TEXT",
")",
"def",
"downloadPage",
"(",
"url",
",",
"file",
",",
"contextFactory",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"factoryFactory",
"=",
"(",
"lambda",
"url",
",",
"*",
"a",
",",
"**",
"kw",
":",
"HTTPDownloader",
"(",
"url",
",",
"file",
",",
"*",
"a",
",",
"**",
"kw",
")",
")",
"return",
"_makeGetterFactory",
"(",
"url",
",",
"factoryFactory",
",",
"contextFactory",
"=",
"contextFactory",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
".",
"deferred"
] | download a web page to a file . | train | false |
22,101 | def load_custom_properties():
filename = 'schema-image.json'
match = CONF.find_file(filename)
if match:
schema_file = open(match)
schema_data = schema_file.read()
return json.loads(schema_data)
else:
msg = _('Could not find schema properties file %s. Continuing without custom properties')
LOG.warn((msg % filename))
return {}
| [
"def",
"load_custom_properties",
"(",
")",
":",
"filename",
"=",
"'schema-image.json'",
"match",
"=",
"CONF",
".",
"find_file",
"(",
"filename",
")",
"if",
"match",
":",
"schema_file",
"=",
"open",
"(",
"match",
")",
"schema_data",
"=",
"schema_file",
".",
"read",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"schema_data",
")",
"else",
":",
"msg",
"=",
"_",
"(",
"'Could not find schema properties file %s. Continuing without custom properties'",
")",
"LOG",
".",
"warn",
"(",
"(",
"msg",
"%",
"filename",
")",
")",
"return",
"{",
"}"
] | find the schema properties files and load them into a dict . | train | false |
22,102 | def _is_junction(arg):
return (isinstance(arg, dict) and (len(arg) == 1) and (next(six.iterkeys(arg)) == 'junction'))
| [
"def",
"_is_junction",
"(",
"arg",
")",
":",
"return",
"(",
"isinstance",
"(",
"arg",
",",
"dict",
")",
"and",
"(",
"len",
"(",
"arg",
")",
"==",
"1",
")",
"and",
"(",
"next",
"(",
"six",
".",
"iterkeys",
"(",
"arg",
")",
")",
"==",
"'junction'",
")",
")"
] | return true . | train | true |
22,103 | def get_recommended_folders(container, names):
from calibre.ebooks.oeb.polish.utils import guess_type
counts = defaultdict(Counter)
for (name, mt) in container.mime_map.iteritems():
folder = (name.rpartition(u'/')[0] if (u'/' in name) else u'')
counts[mt_to_category(container, mt)][folder] += 1
try:
opf_folder = counts[u'opf'].most_common(1)[0][0]
except KeyError:
opf_folder = u''
recommendations = {category: counter.most_common(1)[0][0] for (category, counter) in counts.iteritems()}
return {n: recommendations.get(mt_to_category(container, guess_type(os.path.basename(n))), opf_folder) for n in names}
| [
"def",
"get_recommended_folders",
"(",
"container",
",",
"names",
")",
":",
"from",
"calibre",
".",
"ebooks",
".",
"oeb",
".",
"polish",
".",
"utils",
"import",
"guess_type",
"counts",
"=",
"defaultdict",
"(",
"Counter",
")",
"for",
"(",
"name",
",",
"mt",
")",
"in",
"container",
".",
"mime_map",
".",
"iteritems",
"(",
")",
":",
"folder",
"=",
"(",
"name",
".",
"rpartition",
"(",
"u'/'",
")",
"[",
"0",
"]",
"if",
"(",
"u'/'",
"in",
"name",
")",
"else",
"u''",
")",
"counts",
"[",
"mt_to_category",
"(",
"container",
",",
"mt",
")",
"]",
"[",
"folder",
"]",
"+=",
"1",
"try",
":",
"opf_folder",
"=",
"counts",
"[",
"u'opf'",
"]",
".",
"most_common",
"(",
"1",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"except",
"KeyError",
":",
"opf_folder",
"=",
"u''",
"recommendations",
"=",
"{",
"category",
":",
"counter",
".",
"most_common",
"(",
"1",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"for",
"(",
"category",
",",
"counter",
")",
"in",
"counts",
".",
"iteritems",
"(",
")",
"}",
"return",
"{",
"n",
":",
"recommendations",
".",
"get",
"(",
"mt_to_category",
"(",
"container",
",",
"guess_type",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"n",
")",
")",
")",
",",
"opf_folder",
")",
"for",
"n",
"in",
"names",
"}"
] | return the folders that are recommended for the given filenames . | train | false |
22,104 | @register.filter
def plugin_enabled(plugin_name):
return (plugin_name in django_settings.INSTALLED_APPS)
| [
"@",
"register",
".",
"filter",
"def",
"plugin_enabled",
"(",
"plugin_name",
")",
":",
"return",
"(",
"plugin_name",
"in",
"django_settings",
".",
"INSTALLED_APPS",
")"
] | example: {% if wiki . | train | false |
22,106 | def numify(string):
return ''.join([c for c in str(string) if c.isdigit()])
| [
"def",
"numify",
"(",
"string",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"str",
"(",
"string",
")",
"if",
"c",
".",
"isdigit",
"(",
")",
"]",
")"
] | removes all non-digit characters from string . | train | false |
22,107 | def backup_update(context, backup_id, values):
return IMPL.backup_update(context, backup_id, values)
| [
"def",
"backup_update",
"(",
"context",
",",
"backup_id",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"backup_update",
"(",
"context",
",",
"backup_id",
",",
"values",
")"
] | set the given properties on a backup and update it . | train | false |
22,108 | @pytest.fixture
def sess_man(tmpdir):
return sessions.SessionManager(base_path=str(tmpdir))
| [
"@",
"pytest",
".",
"fixture",
"def",
"sess_man",
"(",
"tmpdir",
")",
":",
"return",
"sessions",
".",
"SessionManager",
"(",
"base_path",
"=",
"str",
"(",
"tmpdir",
")",
")"
] | fixture providing a sessionmanager . | train | false |
22,109 | def online_help(query):
from .extern.six.moves.urllib.parse import urlencode
import webbrowser
version = __version__
if ('dev' in version):
version = 'latest'
else:
version = ('v' + version)
url = 'http://docs.astropy.org/en/{0}/search.html?{1}'.format(version, urlencode({'q': query}))
webbrowser.open(url)
| [
"def",
"online_help",
"(",
"query",
")",
":",
"from",
".",
"extern",
".",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
"import",
"urlencode",
"import",
"webbrowser",
"version",
"=",
"__version__",
"if",
"(",
"'dev'",
"in",
"version",
")",
":",
"version",
"=",
"'latest'",
"else",
":",
"version",
"=",
"(",
"'v'",
"+",
"version",
")",
"url",
"=",
"'http://docs.astropy.org/en/{0}/search.html?{1}'",
".",
"format",
"(",
"version",
",",
"urlencode",
"(",
"{",
"'q'",
":",
"query",
"}",
")",
")",
"webbrowser",
".",
"open",
"(",
"url",
")"
] | search the online astropy documentation for the given query . | train | false |
22,111 | def _prep_acl_for_compare(ACL):
ret = deepcopy(ACL)
ret['Owner'] = _normalize_user(ret['Owner'])
for item in ret.get('Grants', ()):
item['Grantee'] = _normalize_user(item.get('Grantee'))
return ret
| [
"def",
"_prep_acl_for_compare",
"(",
"ACL",
")",
":",
"ret",
"=",
"deepcopy",
"(",
"ACL",
")",
"ret",
"[",
"'Owner'",
"]",
"=",
"_normalize_user",
"(",
"ret",
"[",
"'Owner'",
"]",
")",
"for",
"item",
"in",
"ret",
".",
"get",
"(",
"'Grants'",
",",
"(",
")",
")",
":",
"item",
"[",
"'Grantee'",
"]",
"=",
"_normalize_user",
"(",
"item",
".",
"get",
"(",
"'Grantee'",
")",
")",
"return",
"ret"
] | prepares the acl returned from the aws api for comparison with a given one . | train | true |
22,112 | def output_server(session_id=None, url='default', app_path='/'):
deprecated((0, 12, 3), 'bokeh.io.output_server()', '\n bokeh.client sessions as described at http://bokeh.pydata.org/en/latest/docs/user_guide/server.html#connecting-with-bokeh-client"\n ')
from .client import DEFAULT_SESSION_ID
if (session_id is None):
session_id = DEFAULT_SESSION_ID
_state.output_server(session_id=session_id, url=url, app_path=app_path)
| [
"def",
"output_server",
"(",
"session_id",
"=",
"None",
",",
"url",
"=",
"'default'",
",",
"app_path",
"=",
"'/'",
")",
":",
"deprecated",
"(",
"(",
"0",
",",
"12",
",",
"3",
")",
",",
"'bokeh.io.output_server()'",
",",
"'\\n bokeh.client sessions as described at http://bokeh.pydata.org/en/latest/docs/user_guide/server.html#connecting-with-bokeh-client\"\\n '",
")",
"from",
".",
"client",
"import",
"DEFAULT_SESSION_ID",
"if",
"(",
"session_id",
"is",
"None",
")",
":",
"session_id",
"=",
"DEFAULT_SESSION_ID",
"_state",
".",
"output_server",
"(",
"session_id",
"=",
"session_id",
",",
"url",
"=",
"url",
",",
"app_path",
"=",
"app_path",
")"
] | configure the default output state to push its document to a session on a bokeh server . | train | false |
22,113 | def test_wheel_exit_status_code_when_blank_requirements_file(script):
script.pip('install', 'wheel')
script.scratch_path.join('blank.txt').write('\n')
script.pip('wheel', '-r', 'blank.txt')
| [
"def",
"test_wheel_exit_status_code_when_blank_requirements_file",
"(",
"script",
")",
":",
"script",
".",
"pip",
"(",
"'install'",
",",
"'wheel'",
")",
"script",
".",
"scratch_path",
".",
"join",
"(",
"'blank.txt'",
")",
".",
"write",
"(",
"'\\n'",
")",
"script",
".",
"pip",
"(",
"'wheel'",
",",
"'-r'",
",",
"'blank.txt'",
")"
] | test wheel exit status code when blank requirements file specified . | train | false |
22,114 | def fetch_things2(query, chunk_size=100, batch_fn=None, chunks=False):
assert query._sort, 'you must specify the sort order in your query!'
orig_rules = deepcopy(query._rules)
query._limit = chunk_size
items = list(query)
done = False
while (items and (not done)):
if (len(items) < chunk_size):
done = True
after = items[(-1)]
if batch_fn:
items = batch_fn(items)
if chunks:
(yield items)
else:
for i in items:
(yield i)
if (not done):
query._rules = deepcopy(orig_rules)
query._after(after)
items = list(query)
| [
"def",
"fetch_things2",
"(",
"query",
",",
"chunk_size",
"=",
"100",
",",
"batch_fn",
"=",
"None",
",",
"chunks",
"=",
"False",
")",
":",
"assert",
"query",
".",
"_sort",
",",
"'you must specify the sort order in your query!'",
"orig_rules",
"=",
"deepcopy",
"(",
"query",
".",
"_rules",
")",
"query",
".",
"_limit",
"=",
"chunk_size",
"items",
"=",
"list",
"(",
"query",
")",
"done",
"=",
"False",
"while",
"(",
"items",
"and",
"(",
"not",
"done",
")",
")",
":",
"if",
"(",
"len",
"(",
"items",
")",
"<",
"chunk_size",
")",
":",
"done",
"=",
"True",
"after",
"=",
"items",
"[",
"(",
"-",
"1",
")",
"]",
"if",
"batch_fn",
":",
"items",
"=",
"batch_fn",
"(",
"items",
")",
"if",
"chunks",
":",
"(",
"yield",
"items",
")",
"else",
":",
"for",
"i",
"in",
"items",
":",
"(",
"yield",
"i",
")",
"if",
"(",
"not",
"done",
")",
":",
"query",
".",
"_rules",
"=",
"deepcopy",
"(",
"orig_rules",
")",
"query",
".",
"_after",
"(",
"after",
")",
"items",
"=",
"list",
"(",
"query",
")"
] | incrementally run query with a limit of chunk_size until there are no results left . | train | false |
22,116 | def createResolver(servers=None, resolvconf=None, hosts=None):
from twisted.names import resolve, cache, root, hosts as hostsModule
if (platform.getType() == 'posix'):
if (resolvconf is None):
resolvconf = '/etc/resolv.conf'
if (hosts is None):
hosts = '/etc/hosts'
theResolver = Resolver(resolvconf, servers)
hostResolver = hostsModule.Resolver(hosts)
else:
if (hosts is None):
hosts = 'c:\\windows\\hosts'
from twisted.internet import reactor
bootstrap = _ThreadedResolverImpl(reactor)
hostResolver = hostsModule.Resolver(hosts)
theResolver = root.bootstrap(bootstrap)
L = [hostResolver, cache.CacheResolver(), theResolver]
return resolve.ResolverChain(L)
| [
"def",
"createResolver",
"(",
"servers",
"=",
"None",
",",
"resolvconf",
"=",
"None",
",",
"hosts",
"=",
"None",
")",
":",
"from",
"twisted",
".",
"names",
"import",
"resolve",
",",
"cache",
",",
"root",
",",
"hosts",
"as",
"hostsModule",
"if",
"(",
"platform",
".",
"getType",
"(",
")",
"==",
"'posix'",
")",
":",
"if",
"(",
"resolvconf",
"is",
"None",
")",
":",
"resolvconf",
"=",
"'/etc/resolv.conf'",
"if",
"(",
"hosts",
"is",
"None",
")",
":",
"hosts",
"=",
"'/etc/hosts'",
"theResolver",
"=",
"Resolver",
"(",
"resolvconf",
",",
"servers",
")",
"hostResolver",
"=",
"hostsModule",
".",
"Resolver",
"(",
"hosts",
")",
"else",
":",
"if",
"(",
"hosts",
"is",
"None",
")",
":",
"hosts",
"=",
"'c:\\\\windows\\\\hosts'",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"bootstrap",
"=",
"_ThreadedResolverImpl",
"(",
"reactor",
")",
"hostResolver",
"=",
"hostsModule",
".",
"Resolver",
"(",
"hosts",
")",
"theResolver",
"=",
"root",
".",
"bootstrap",
"(",
"bootstrap",
")",
"L",
"=",
"[",
"hostResolver",
",",
"cache",
".",
"CacheResolver",
"(",
")",
",",
"theResolver",
"]",
"return",
"resolve",
".",
"ResolverChain",
"(",
"L",
")"
] | create and return a resolver . | train | false |
22,117 | def Time(hour, minute, second):
return datetime.time(hour, minute, second)
| [
"def",
"Time",
"(",
"hour",
",",
"minute",
",",
"second",
")",
":",
"return",
"datetime",
".",
"time",
"(",
"hour",
",",
"minute",
",",
"second",
")"
] | this function constructs an object holding a time value . | train | false |
22,118 | def _get_msupdate_status():
obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')
col_services = obj_sm.Services
for service in col_services:
if (service.name == 'Microsoft Update'):
return True
return False
| [
"def",
"_get_msupdate_status",
"(",
")",
":",
"obj_sm",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"'Microsoft.Update.ServiceManager'",
")",
"col_services",
"=",
"obj_sm",
".",
"Services",
"for",
"service",
"in",
"col_services",
":",
"if",
"(",
"service",
".",
"name",
"==",
"'Microsoft Update'",
")",
":",
"return",
"True",
"return",
"False"
] | check to see if microsoft update is enabled return boolean . | train | false |
22,119 | def _partition_index_names(provisioned_index_names, index_names):
existing_index_names = set()
new_index_names = set()
for name in index_names:
if (name in provisioned_index_names):
existing_index_names.add(name)
else:
new_index_names.add(name)
index_names_to_be_deleted = (provisioned_index_names - existing_index_names)
return (existing_index_names, new_index_names, index_names_to_be_deleted)
| [
"def",
"_partition_index_names",
"(",
"provisioned_index_names",
",",
"index_names",
")",
":",
"existing_index_names",
"=",
"set",
"(",
")",
"new_index_names",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"index_names",
":",
"if",
"(",
"name",
"in",
"provisioned_index_names",
")",
":",
"existing_index_names",
".",
"add",
"(",
"name",
")",
"else",
":",
"new_index_names",
".",
"add",
"(",
"name",
")",
"index_names_to_be_deleted",
"=",
"(",
"provisioned_index_names",
"-",
"existing_index_names",
")",
"return",
"(",
"existing_index_names",
",",
"new_index_names",
",",
"index_names_to_be_deleted",
")"
] | returns 3 disjoint sets of indexes: existing . | train | true |
22,120 | def test_parallel(num_threads=2, kwargs_list=None):
assert (num_threads > 0)
has_kwargs_list = (kwargs_list is not None)
if has_kwargs_list:
assert (len(kwargs_list) == num_threads)
import threading
def wrapper(func):
@wraps(func)
def inner(*args, **kwargs):
if has_kwargs_list:
update_kwargs = (lambda i: dict(kwargs, **kwargs_list[i]))
else:
update_kwargs = (lambda i: kwargs)
threads = []
for i in range(num_threads):
updated_kwargs = update_kwargs(i)
thread = threading.Thread(target=func, args=args, kwargs=updated_kwargs)
threads.append(thread)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return inner
return wrapper
| [
"def",
"test_parallel",
"(",
"num_threads",
"=",
"2",
",",
"kwargs_list",
"=",
"None",
")",
":",
"assert",
"(",
"num_threads",
">",
"0",
")",
"has_kwargs_list",
"=",
"(",
"kwargs_list",
"is",
"not",
"None",
")",
"if",
"has_kwargs_list",
":",
"assert",
"(",
"len",
"(",
"kwargs_list",
")",
"==",
"num_threads",
")",
"import",
"threading",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"has_kwargs_list",
":",
"update_kwargs",
"=",
"(",
"lambda",
"i",
":",
"dict",
"(",
"kwargs",
",",
"**",
"kwargs_list",
"[",
"i",
"]",
")",
")",
"else",
":",
"update_kwargs",
"=",
"(",
"lambda",
"i",
":",
"kwargs",
")",
"threads",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"num_threads",
")",
":",
"updated_kwargs",
"=",
"update_kwargs",
"(",
"i",
")",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"func",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"updated_kwargs",
")",
"threads",
".",
"append",
"(",
"thread",
")",
"for",
"thread",
"in",
"threads",
":",
"thread",
".",
"start",
"(",
")",
"for",
"thread",
"in",
"threads",
":",
"thread",
".",
"join",
"(",
")",
"return",
"inner",
"return",
"wrapper"
] | decorator to run the same function multiple times in parallel . | train | false |
22,121 | def _nodetool(cmd):
nodetool = __salt__['config.option']('cassandra.nodetool')
host = __salt__['config.option']('cassandra.host')
return __salt__['cmd.run_stdout']('{0} -h {1} {2}'.format(nodetool, host, cmd))
| [
"def",
"_nodetool",
"(",
"cmd",
")",
":",
"nodetool",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'cassandra.nodetool'",
")",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'cassandra.host'",
")",
"return",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"'{0} -h {1} {2}'",
".",
"format",
"(",
"nodetool",
",",
"host",
",",
"cmd",
")",
")"
] | internal cassandra nodetool wrapper . | train | true |
22,123 | def test_roles_stripped_env_hosts():
@roles('r1')
def command():
pass
eq_hosts(command, ['a', 'b'], env={'roledefs': spaced_roles})
| [
"def",
"test_roles_stripped_env_hosts",
"(",
")",
":",
"@",
"roles",
"(",
"'r1'",
")",
"def",
"command",
"(",
")",
":",
"pass",
"eq_hosts",
"(",
"command",
",",
"[",
"'a'",
",",
"'b'",
"]",
",",
"env",
"=",
"{",
"'roledefs'",
":",
"spaced_roles",
"}",
")"
] | make sure hosts defined in env . | train | false |
22,124 | @commands(u'getsafeforwork', u'getsfw')
@example(u'.getsfw [channel]')
def get_channel_sfw(bot, trigger):
channel = trigger.group(2)
if (not channel):
channel = trigger.sender
if channel.is_nick():
return bot.say(u'.getsfw with no channel param is only permitted in channels')
channel = channel.strip()
sfw = bot.db.get_channel_value(channel, u'sfw')
if sfw:
bot.say((u'%s is flagged as SFW' % channel))
else:
bot.say((u'%s is flagged as NSFW' % channel))
| [
"@",
"commands",
"(",
"u'getsafeforwork'",
",",
"u'getsfw'",
")",
"@",
"example",
"(",
"u'.getsfw [channel]'",
")",
"def",
"get_channel_sfw",
"(",
"bot",
",",
"trigger",
")",
":",
"channel",
"=",
"trigger",
".",
"group",
"(",
"2",
")",
"if",
"(",
"not",
"channel",
")",
":",
"channel",
"=",
"trigger",
".",
"sender",
"if",
"channel",
".",
"is_nick",
"(",
")",
":",
"return",
"bot",
".",
"say",
"(",
"u'.getsfw with no channel param is only permitted in channels'",
")",
"channel",
"=",
"channel",
".",
"strip",
"(",
")",
"sfw",
"=",
"bot",
".",
"db",
".",
"get_channel_value",
"(",
"channel",
",",
"u'sfw'",
")",
"if",
"sfw",
":",
"bot",
".",
"say",
"(",
"(",
"u'%s is flagged as SFW'",
"%",
"channel",
")",
")",
"else",
":",
"bot",
".",
"say",
"(",
"(",
"u'%s is flagged as NSFW'",
"%",
"channel",
")",
")"
] | gets the preferred channels safe for work status . | train | false |
22,125 | def _GenerateMSBuildRulePropsFile(props_path, msbuild_rules):
content = ['Project', {'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'}]
for rule in msbuild_rules:
content.extend([['PropertyGroup', {'Condition': ("'$(%s)' == '' and '$(%s)' == '' and '$(ConfigurationType)' != 'Makefile'" % (rule.before_targets, rule.after_targets))}, [rule.before_targets, 'Midl'], [rule.after_targets, 'CustomBuild']], ['PropertyGroup', [rule.depends_on, {'Condition': "'$(ConfigurationType)' != 'Makefile'"}, ('_SelectedFiles;$(%s)' % rule.depends_on)]], ['ItemDefinitionGroup', [rule.rule_name, ['CommandLineTemplate', rule.command], ['Outputs', rule.outputs], ['ExecutionDescription', rule.description], ['AdditionalDependencies', rule.additional_dependencies]]]])
easy_xml.WriteXmlIfChanged(content, props_path, pretty=True, win32=True)
| [
"def",
"_GenerateMSBuildRulePropsFile",
"(",
"props_path",
",",
"msbuild_rules",
")",
":",
"content",
"=",
"[",
"'Project'",
",",
"{",
"'xmlns'",
":",
"'http://schemas.microsoft.com/developer/msbuild/2003'",
"}",
"]",
"for",
"rule",
"in",
"msbuild_rules",
":",
"content",
".",
"extend",
"(",
"[",
"[",
"'PropertyGroup'",
",",
"{",
"'Condition'",
":",
"(",
"\"'$(%s)' == '' and '$(%s)' == '' and '$(ConfigurationType)' != 'Makefile'\"",
"%",
"(",
"rule",
".",
"before_targets",
",",
"rule",
".",
"after_targets",
")",
")",
"}",
",",
"[",
"rule",
".",
"before_targets",
",",
"'Midl'",
"]",
",",
"[",
"rule",
".",
"after_targets",
",",
"'CustomBuild'",
"]",
"]",
",",
"[",
"'PropertyGroup'",
",",
"[",
"rule",
".",
"depends_on",
",",
"{",
"'Condition'",
":",
"\"'$(ConfigurationType)' != 'Makefile'\"",
"}",
",",
"(",
"'_SelectedFiles;$(%s)'",
"%",
"rule",
".",
"depends_on",
")",
"]",
"]",
",",
"[",
"'ItemDefinitionGroup'",
",",
"[",
"rule",
".",
"rule_name",
",",
"[",
"'CommandLineTemplate'",
",",
"rule",
".",
"command",
"]",
",",
"[",
"'Outputs'",
",",
"rule",
".",
"outputs",
"]",
",",
"[",
"'ExecutionDescription'",
",",
"rule",
".",
"description",
"]",
",",
"[",
"'AdditionalDependencies'",
",",
"rule",
".",
"additional_dependencies",
"]",
"]",
"]",
"]",
")",
"easy_xml",
".",
"WriteXmlIfChanged",
"(",
"content",
",",
"props_path",
",",
"pretty",
"=",
"True",
",",
"win32",
"=",
"True",
")"
] | generate the . | train | false |
22,126 | def get_filesystem_encoding():
global _warned_about_filesystem_encoding
rv = sys.getfilesystemencoding()
if ((has_likely_buggy_unicode_filesystem and (not rv)) or _is_ascii_encoding(rv)):
if (not _warned_about_filesystem_encoding):
warnings.warn('Detected a misconfigured UNIX filesystem: Will use UTF-8 as filesystem encoding instead of {0!r}'.format(rv), BrokenFilesystemWarning)
_warned_about_filesystem_encoding = True
return 'utf-8'
return rv
| [
"def",
"get_filesystem_encoding",
"(",
")",
":",
"global",
"_warned_about_filesystem_encoding",
"rv",
"=",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"if",
"(",
"(",
"has_likely_buggy_unicode_filesystem",
"and",
"(",
"not",
"rv",
")",
")",
"or",
"_is_ascii_encoding",
"(",
"rv",
")",
")",
":",
"if",
"(",
"not",
"_warned_about_filesystem_encoding",
")",
":",
"warnings",
".",
"warn",
"(",
"'Detected a misconfigured UNIX filesystem: Will use UTF-8 as filesystem encoding instead of {0!r}'",
".",
"format",
"(",
"rv",
")",
",",
"BrokenFilesystemWarning",
")",
"_warned_about_filesystem_encoding",
"=",
"True",
"return",
"'utf-8'",
"return",
"rv"
] | returns the filesystem encoding that should be used . | train | true |
22,127 | @contextmanager
def bake_in_temp_dir(cookies, *args, **kwargs):
result = cookies.bake(*args, **kwargs)
try:
(yield result)
finally:
rmtree(str(result.project))
| [
"@",
"contextmanager",
"def",
"bake_in_temp_dir",
"(",
"cookies",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"result",
"=",
"cookies",
".",
"bake",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"try",
":",
"(",
"yield",
"result",
")",
"finally",
":",
"rmtree",
"(",
"str",
"(",
"result",
".",
"project",
")",
")"
] | delete the temporal directory that is created when executing the tests . | train | false |
22,129 | def invert_unique(d, check=True):
if check:
assert (len(set(d.values())) == len(d)), 'Values were not unique!'
return {v: k for (k, v) in iteritems(d)}
| [
"def",
"invert_unique",
"(",
"d",
",",
"check",
"=",
"True",
")",
":",
"if",
"check",
":",
"assert",
"(",
"len",
"(",
"set",
"(",
"d",
".",
"values",
"(",
")",
")",
")",
"==",
"len",
"(",
"d",
")",
")",
",",
"'Values were not unique!'",
"return",
"{",
"v",
":",
"k",
"for",
"(",
"k",
",",
"v",
")",
"in",
"iteritems",
"(",
"d",
")",
"}"
] | invert a dictionary with unique values into a dictionary with pairs flipped . | train | false |
22,130 | def ciglob(text, patterns):
if isinstance(patterns, str):
patterns = (patterns,)
return glob(text.lower(), [p.lower() for p in patterns])
| [
"def",
"ciglob",
"(",
"text",
",",
"patterns",
")",
":",
"if",
"isinstance",
"(",
"patterns",
",",
"str",
")",
":",
"patterns",
"=",
"(",
"patterns",
",",
")",
"return",
"glob",
"(",
"text",
".",
"lower",
"(",
")",
",",
"[",
"p",
".",
"lower",
"(",
")",
"for",
"p",
"in",
"patterns",
"]",
")"
] | case-insensitive version of glob . | train | false |
22,131 | def test_iht_fit():
iht = InstanceHardnessThreshold(ESTIMATOR, random_state=RND_SEED)
iht.fit(X, Y)
assert_equal(iht.min_c_, 0)
assert_equal(iht.maj_c_, 1)
assert_equal(iht.stats_c_[0], 6)
assert_equal(iht.stats_c_[1], 9)
| [
"def",
"test_iht_fit",
"(",
")",
":",
"iht",
"=",
"InstanceHardnessThreshold",
"(",
"ESTIMATOR",
",",
"random_state",
"=",
"RND_SEED",
")",
"iht",
".",
"fit",
"(",
"X",
",",
"Y",
")",
"assert_equal",
"(",
"iht",
".",
"min_c_",
",",
"0",
")",
"assert_equal",
"(",
"iht",
".",
"maj_c_",
",",
"1",
")",
"assert_equal",
"(",
"iht",
".",
"stats_c_",
"[",
"0",
"]",
",",
"6",
")",
"assert_equal",
"(",
"iht",
".",
"stats_c_",
"[",
"1",
"]",
",",
"9",
")"
] | test the fitting method . | train | false |
22,132 | def leave_transaction_management():
thread_ident = thread.get_ident()
if (state.has_key(thread_ident) and state[thread_ident]):
del state[thread_ident][(-1)]
else:
raise TransactionManagementError("This code isn't under transaction management")
if dirty.get(thread_ident, False):
rollback()
raise TransactionManagementError('Transaction managed block ended with pending COMMIT/ROLLBACK')
dirty[thread_ident] = False
| [
"def",
"leave_transaction_management",
"(",
")",
":",
"thread_ident",
"=",
"thread",
".",
"get_ident",
"(",
")",
"if",
"(",
"state",
".",
"has_key",
"(",
"thread_ident",
")",
"and",
"state",
"[",
"thread_ident",
"]",
")",
":",
"del",
"state",
"[",
"thread_ident",
"]",
"[",
"(",
"-",
"1",
")",
"]",
"else",
":",
"raise",
"TransactionManagementError",
"(",
"\"This code isn't under transaction management\"",
")",
"if",
"dirty",
".",
"get",
"(",
"thread_ident",
",",
"False",
")",
":",
"rollback",
"(",
")",
"raise",
"TransactionManagementError",
"(",
"'Transaction managed block ended with pending COMMIT/ROLLBACK'",
")",
"dirty",
"[",
"thread_ident",
"]",
"=",
"False"
] | leaves transaction management for a running thread . | train | false |
22,135 | def encoders():
return list(_encoders)
| [
"def",
"encoders",
"(",
")",
":",
"return",
"list",
"(",
"_encoders",
")"
] | return a list of available compression methods . | train | false |
22,137 | def NotImplementedFake(*args, **kwargs):
raise NotImplementedError('This class/method is not available.')
| [
"def",
"NotImplementedFake",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"'This class/method is not available.'",
")"
] | fake for methods/functions that are not implemented in the production environment . | train | false |
22,138 | def cov_corr_chunk(df, corr=False):
mat = df.values
mask = np.isfinite(mat)
keep = np.bitwise_and(mask[:, None, :], mask[:, :, None])
x = np.where(keep, mat[:, None, :], np.nan)
sums = np.nansum(x, 0)
counts = keep.astype('int').sum(0)
cov = df.cov().values
dtype = [('sum', sums.dtype), ('count', counts.dtype), ('cov', cov.dtype)]
if corr:
m = np.nansum(((x - (sums / np.where(counts, counts, np.nan))) ** 2), 0)
dtype.append(('m', m.dtype))
out = np.empty(counts.shape, dtype=dtype)
out['sum'] = sums
out['count'] = counts
out['cov'] = (cov * (counts - 1))
if corr:
out['m'] = m
return out
| [
"def",
"cov_corr_chunk",
"(",
"df",
",",
"corr",
"=",
"False",
")",
":",
"mat",
"=",
"df",
".",
"values",
"mask",
"=",
"np",
".",
"isfinite",
"(",
"mat",
")",
"keep",
"=",
"np",
".",
"bitwise_and",
"(",
"mask",
"[",
":",
",",
"None",
",",
":",
"]",
",",
"mask",
"[",
":",
",",
":",
",",
"None",
"]",
")",
"x",
"=",
"np",
".",
"where",
"(",
"keep",
",",
"mat",
"[",
":",
",",
"None",
",",
":",
"]",
",",
"np",
".",
"nan",
")",
"sums",
"=",
"np",
".",
"nansum",
"(",
"x",
",",
"0",
")",
"counts",
"=",
"keep",
".",
"astype",
"(",
"'int'",
")",
".",
"sum",
"(",
"0",
")",
"cov",
"=",
"df",
".",
"cov",
"(",
")",
".",
"values",
"dtype",
"=",
"[",
"(",
"'sum'",
",",
"sums",
".",
"dtype",
")",
",",
"(",
"'count'",
",",
"counts",
".",
"dtype",
")",
",",
"(",
"'cov'",
",",
"cov",
".",
"dtype",
")",
"]",
"if",
"corr",
":",
"m",
"=",
"np",
".",
"nansum",
"(",
"(",
"(",
"x",
"-",
"(",
"sums",
"/",
"np",
".",
"where",
"(",
"counts",
",",
"counts",
",",
"np",
".",
"nan",
")",
")",
")",
"**",
"2",
")",
",",
"0",
")",
"dtype",
".",
"append",
"(",
"(",
"'m'",
",",
"m",
".",
"dtype",
")",
")",
"out",
"=",
"np",
".",
"empty",
"(",
"counts",
".",
"shape",
",",
"dtype",
"=",
"dtype",
")",
"out",
"[",
"'sum'",
"]",
"=",
"sums",
"out",
"[",
"'count'",
"]",
"=",
"counts",
"out",
"[",
"'cov'",
"]",
"=",
"(",
"cov",
"*",
"(",
"counts",
"-",
"1",
")",
")",
"if",
"corr",
":",
"out",
"[",
"'m'",
"]",
"=",
"m",
"return",
"out"
] | chunk part of a covariance or correlation computation . | train | false |
22,139 | def get_mount_info(partition_list):
mount_info = set()
for p in partition_list:
try:
uuid = utils.system_output(('blkid -p -s UUID -o value %s' % p.device))
except error.CmdError:
uuid = p.device
mount_info.add((uuid, p.get_mountpoint()))
return mount_info
| [
"def",
"get_mount_info",
"(",
"partition_list",
")",
":",
"mount_info",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"partition_list",
":",
"try",
":",
"uuid",
"=",
"utils",
".",
"system_output",
"(",
"(",
"'blkid -p -s UUID -o value %s'",
"%",
"p",
".",
"device",
")",
")",
"except",
"error",
".",
"CmdError",
":",
"uuid",
"=",
"p",
".",
"device",
"mount_info",
".",
"add",
"(",
"(",
"uuid",
",",
"p",
".",
"get_mountpoint",
"(",
")",
")",
")",
"return",
"mount_info"
] | picks up mount point information about the machine mounts . | train | false |
22,140 | def check_pointer(result, func, cargs):
if isinstance(result, (int, long)):
result = c_void_p(result)
if bool(result):
return result
else:
raise OGRException(('Invalid pointer returned from "%s"' % func.__name__))
| [
"def",
"check_pointer",
"(",
"result",
",",
"func",
",",
"cargs",
")",
":",
"if",
"isinstance",
"(",
"result",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"result",
"=",
"c_void_p",
"(",
"result",
")",
"if",
"bool",
"(",
"result",
")",
":",
"return",
"result",
"else",
":",
"raise",
"OGRException",
"(",
"(",
"'Invalid pointer returned from \"%s\"'",
"%",
"func",
".",
"__name__",
")",
")"
] | makes sure the result pointer is valid . | train | false |
22,141 | def test_upgrade_with_newest_already_installed(script, data):
script.pip('install', '-f', data.find_links, '--no-index', 'simple')
result = script.pip('install', '--upgrade', '-f', data.find_links, '--no-index', 'simple')
assert (not result.files_created), 'simple upgraded when it should not have'
assert ('already up-to-date' in result.stdout), result.stdout
| [
"def",
"test_upgrade_with_newest_already_installed",
"(",
"script",
",",
"data",
")",
":",
"script",
".",
"pip",
"(",
"'install'",
",",
"'-f'",
",",
"data",
".",
"find_links",
",",
"'--no-index'",
",",
"'simple'",
")",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"'--upgrade'",
",",
"'-f'",
",",
"data",
".",
"find_links",
",",
"'--no-index'",
",",
"'simple'",
")",
"assert",
"(",
"not",
"result",
".",
"files_created",
")",
",",
"'simple upgraded when it should not have'",
"assert",
"(",
"'already up-to-date'",
"in",
"result",
".",
"stdout",
")",
",",
"result",
".",
"stdout"
] | if the newest version of a package is already installed . | train | false |
22,142 | def register_transfer(fn):
transfer._others.append(fn)
| [
"def",
"register_transfer",
"(",
"fn",
")",
":",
"transfer",
".",
"_others",
".",
"append",
"(",
"fn",
")"
] | register a transfer function for alternative targets . | train | false |
22,144 | def test_write_valid_meta_ipac():
table = ascii.get_reader(Reader=ascii.Ipac)
data = table.read('t/no_data_ipac.dat')
data.meta['keywords']['blah'] = {'value': 'invalid'}
with catch_warnings(AstropyWarning) as ASwarn:
out = StringIO()
data.write(out, format='ascii.ipac')
assert (len(ASwarn) == 0)
| [
"def",
"test_write_valid_meta_ipac",
"(",
")",
":",
"table",
"=",
"ascii",
".",
"get_reader",
"(",
"Reader",
"=",
"ascii",
".",
"Ipac",
")",
"data",
"=",
"table",
".",
"read",
"(",
"'t/no_data_ipac.dat'",
")",
"data",
".",
"meta",
"[",
"'keywords'",
"]",
"[",
"'blah'",
"]",
"=",
"{",
"'value'",
":",
"'invalid'",
"}",
"with",
"catch_warnings",
"(",
"AstropyWarning",
")",
"as",
"ASwarn",
":",
"out",
"=",
"StringIO",
"(",
")",
"data",
".",
"write",
"(",
"out",
",",
"format",
"=",
"'ascii.ipac'",
")",
"assert",
"(",
"len",
"(",
"ASwarn",
")",
"==",
"0",
")"
] | write an ipac table that contains no data and has *correctly* specified metadata . | train | false |
22,145 | def atoi(string):
return int(delocalize(string))
| [
"def",
"atoi",
"(",
"string",
")",
":",
"return",
"int",
"(",
"delocalize",
"(",
"string",
")",
")"
] | converts a string to an integer according to the locale settings . | train | false |
22,147 | def makeRGBA(*args, **kwds):
kwds['useRGBA'] = True
return makeARGB(*args, **kwds)
| [
"def",
"makeRGBA",
"(",
"*",
"args",
",",
"**",
"kwds",
")",
":",
"kwds",
"[",
"'useRGBA'",
"]",
"=",
"True",
"return",
"makeARGB",
"(",
"*",
"args",
",",
"**",
"kwds",
")"
] | equivalent to makeargb . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.