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 |
|---|---|---|---|---|---|
39,854 | def _key_value_callback(option, opt_str, value, parser):
try:
(k, v) = value.split('=', 1)
except ValueError:
parser.error(('%s argument %r is not of the form KEY=VALUE' % (opt_str, value)))
_default_to(parser, option.dest, {})
getattr(parser.values, option.dest)[k] = v
| [
"def",
"_key_value_callback",
"(",
"option",
",",
"opt_str",
",",
"value",
",",
"parser",
")",
":",
"try",
":",
"(",
"k",
",",
"v",
")",
"=",
"value",
".",
"split",
"(",
"'='",
",",
"1",
")",
"except",
"ValueError",
":",
"parser",
".",
"error",
"(",
"(",
"'%s argument %r is not of the form KEY=VALUE'",
"%",
"(",
"opt_str",
",",
"value",
")",
")",
")",
"_default_to",
"(",
"parser",
",",
"option",
".",
"dest",
",",
"{",
"}",
")",
"getattr",
"(",
"parser",
".",
"values",
",",
"option",
".",
"dest",
")",
"[",
"k",
"]",
"=",
"v"
] | callback for key=value pairs . | train | false |
39,855 | def upcharge(amount):
typecheck(amount, Decimal)
charge_amount = ((amount + FEE_CHARGE[0]) / (1 - FEE_CHARGE[1]))
charge_amount = charge_amount.quantize(FEE_CHARGE[0], rounding=ROUND_UP)
return (charge_amount, (charge_amount - amount))
| [
"def",
"upcharge",
"(",
"amount",
")",
":",
"typecheck",
"(",
"amount",
",",
"Decimal",
")",
"charge_amount",
"=",
"(",
"(",
"amount",
"+",
"FEE_CHARGE",
"[",
"0",
"]",
")",
"/",
"(",
"1",
"-",
"FEE_CHARGE",
"[",
"1",
"]",
")",
")",
"charge_amount",
"=",
"charge_amount",
".",
"quantize",
"(",
"FEE_CHARGE",
"[",
"0",
"]",
",",
"rounding",
"=",
"ROUND_UP",
")",
"return",
"(",
"charge_amount",
",",
"(",
"charge_amount",
"-",
"amount",
")",
")"
] | given an amount . | train | false |
39,856 | def _to_datetime(iso8601_time):
if (iso8601_time is None):
return None
return iso8601_to_datetime(iso8601_time)
| [
"def",
"_to_datetime",
"(",
"iso8601_time",
")",
":",
"if",
"(",
"iso8601_time",
"is",
"None",
")",
":",
"return",
"None",
"return",
"iso8601_to_datetime",
"(",
"iso8601_time",
")"
] | convert a iso8601-formatted datetime to a :py:class:datetime . | train | false |
39,857 | @then(u'an undefined-step snippet should not exist for "{step}"')
def step_undefined_step_snippet_should_not_exist_for(context, step):
undefined_step_snippet = make_undefined_step_snippet(step)
context.execute_steps(u'Then the command output should not contain:\n """\n {undefined_step_snippet}\n """\n '.format(undefined_step_snippet=text_indent(undefined_step_snippet, 4)))
| [
"@",
"then",
"(",
"u'an undefined-step snippet should not exist for \"{step}\"'",
")",
"def",
"step_undefined_step_snippet_should_not_exist_for",
"(",
"context",
",",
"step",
")",
":",
"undefined_step_snippet",
"=",
"make_undefined_step_snippet",
"(",
"step",
")",
"context",
".",
"execute_steps",
"(",
"u'Then the command output should not contain:\\n \"\"\"\\n {undefined_step_snippet}\\n \"\"\"\\n '",
".",
"format",
"(",
"undefined_step_snippet",
"=",
"text_indent",
"(",
"undefined_step_snippet",
",",
"4",
")",
")",
")"
] | checks if an undefined-step snippet is provided for a step in behave command output . | train | false |
39,858 | def create_ipsecpolicy(name, profile=None, **kwargs):
conn = _auth(profile)
return conn.create_ipsecpolicy(name, **kwargs)
| [
"def",
"create_ipsecpolicy",
"(",
"name",
",",
"profile",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"create_ipsecpolicy",
"(",
"name",
",",
"**",
"kwargs",
")"
] | creates a new ipsecpolicy cli example: . | train | true |
39,860 | def generate_datafile(number_items=20000):
from utils import generate_dataset_shelve
filename = 'samples.shelve'
dataset = generate_dataset_shelve(filename, number_items)
print ('%s generated with %d samples' % (filename, number_items))
| [
"def",
"generate_datafile",
"(",
"number_items",
"=",
"20000",
")",
":",
"from",
"utils",
"import",
"generate_dataset_shelve",
"filename",
"=",
"'samples.shelve'",
"dataset",
"=",
"generate_dataset_shelve",
"(",
"filename",
",",
"number_items",
")",
"print",
"(",
"'%s generated with %d samples'",
"%",
"(",
"filename",
",",
"number_items",
")",
")"
] | create the samples . | train | true |
39,861 | def benchmark_command(command, benchmark_script, summarize_script, output_dir, num_iterations, dry_run, upkeep=None, cleanup=None):
performance_dir = os.path.join(output_dir, 'performance')
if os.path.exists(performance_dir):
shutil.rmtree(performance_dir)
os.makedirs(performance_dir)
try:
for i in range(num_iterations):
out_file = ('performance%s.csv' % i)
out_file = os.path.join(performance_dir, out_file)
benchmark_args = [benchmark_script, command, '--output-file', out_file]
if (not dry_run):
subprocess.check_call(benchmark_args)
if (upkeep is not None):
upkeep()
if (not dry_run):
summarize(summarize_script, performance_dir, output_dir)
finally:
if ((not dry_run) and (cleanup is not None)):
cleanup()
| [
"def",
"benchmark_command",
"(",
"command",
",",
"benchmark_script",
",",
"summarize_script",
",",
"output_dir",
",",
"num_iterations",
",",
"dry_run",
",",
"upkeep",
"=",
"None",
",",
"cleanup",
"=",
"None",
")",
":",
"performance_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_dir",
",",
"'performance'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"performance_dir",
")",
":",
"shutil",
".",
"rmtree",
"(",
"performance_dir",
")",
"os",
".",
"makedirs",
"(",
"performance_dir",
")",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"num_iterations",
")",
":",
"out_file",
"=",
"(",
"'performance%s.csv'",
"%",
"i",
")",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"performance_dir",
",",
"out_file",
")",
"benchmark_args",
"=",
"[",
"benchmark_script",
",",
"command",
",",
"'--output-file'",
",",
"out_file",
"]",
"if",
"(",
"not",
"dry_run",
")",
":",
"subprocess",
".",
"check_call",
"(",
"benchmark_args",
")",
"if",
"(",
"upkeep",
"is",
"not",
"None",
")",
":",
"upkeep",
"(",
")",
"if",
"(",
"not",
"dry_run",
")",
":",
"summarize",
"(",
"summarize_script",
",",
"performance_dir",
",",
"output_dir",
")",
"finally",
":",
"if",
"(",
"(",
"not",
"dry_run",
")",
"and",
"(",
"cleanup",
"is",
"not",
"None",
")",
")",
":",
"cleanup",
"(",
")"
] | benchmark several runs of a long-running command . | train | false |
39,862 | def unary_predicate(func):
func.argtypes = [GEOM_PTR]
func.restype = c_char
func.errcheck = check_predicate
return func
| [
"def",
"unary_predicate",
"(",
"func",
")",
":",
"func",
".",
"argtypes",
"=",
"[",
"GEOM_PTR",
"]",
"func",
".",
"restype",
"=",
"c_char",
"func",
".",
"errcheck",
"=",
"check_predicate",
"return",
"func"
] | for geos unary predicate functions . | train | false |
39,863 | def stack_size(size=None):
if (size is not None):
raise error('setting thread stack size not supported')
return 0
| [
"def",
"stack_size",
"(",
"size",
"=",
"None",
")",
":",
"if",
"(",
"size",
"is",
"not",
"None",
")",
":",
"raise",
"error",
"(",
"'setting thread stack size not supported'",
")",
"return",
"0"
] | dummy implementation of thread . | train | false |
39,864 | def report_test_tree(output, flaky_tests):
reporter = TreeReporter(output)
for (test, flaky) in flaky_tests:
new_test = clone_test_with_new_id(test, '{}({})'.format(test.id(), ', '.join(flaky.jira_keys)))
reporter.startTest(new_test)
reporter.addSuccess(new_test)
reporter.stopTest(new_test)
reporter.done()
| [
"def",
"report_test_tree",
"(",
"output",
",",
"flaky_tests",
")",
":",
"reporter",
"=",
"TreeReporter",
"(",
"output",
")",
"for",
"(",
"test",
",",
"flaky",
")",
"in",
"flaky_tests",
":",
"new_test",
"=",
"clone_test_with_new_id",
"(",
"test",
",",
"'{}({})'",
".",
"format",
"(",
"test",
".",
"id",
"(",
")",
",",
"', '",
".",
"join",
"(",
"flaky",
".",
"jira_keys",
")",
")",
")",
"reporter",
".",
"startTest",
"(",
"new_test",
")",
"reporter",
".",
"addSuccess",
"(",
"new_test",
")",
"reporter",
".",
"stopTest",
"(",
"new_test",
")",
"reporter",
".",
"done",
"(",
")"
] | print all flaky tests as a tree . | train | false |
39,865 | def check_optional(name, allowXHTML=False, merge_multiple=False):
def check(n, filename):
n = get_nodes_by_name(n, name)
if ((len(n) > 1) and (not merge_multiple)):
raise ManifestException(("Invalid manifest file: must have a single '%s' element" % name))
if n:
values = []
for child in n:
if allowXHTML:
values.append(''.join([x.toxml() for x in child.childNodes]))
else:
values.append(_get_text(child.childNodes).strip())
return ', '.join(values)
return check
| [
"def",
"check_optional",
"(",
"name",
",",
"allowXHTML",
"=",
"False",
",",
"merge_multiple",
"=",
"False",
")",
":",
"def",
"check",
"(",
"n",
",",
"filename",
")",
":",
"n",
"=",
"get_nodes_by_name",
"(",
"n",
",",
"name",
")",
"if",
"(",
"(",
"len",
"(",
"n",
")",
">",
"1",
")",
"and",
"(",
"not",
"merge_multiple",
")",
")",
":",
"raise",
"ManifestException",
"(",
"(",
"\"Invalid manifest file: must have a single '%s' element\"",
"%",
"name",
")",
")",
"if",
"n",
":",
"values",
"=",
"[",
"]",
"for",
"child",
"in",
"n",
":",
"if",
"allowXHTML",
":",
"values",
".",
"append",
"(",
"''",
".",
"join",
"(",
"[",
"x",
".",
"toxml",
"(",
")",
"for",
"x",
"in",
"child",
".",
"childNodes",
"]",
")",
")",
"else",
":",
"values",
".",
"append",
"(",
"_get_text",
"(",
"child",
".",
"childNodes",
")",
".",
"strip",
"(",
")",
")",
"return",
"', '",
".",
"join",
"(",
"values",
")",
"return",
"check"
] | validator for optional elements . | train | false |
39,867 | def get_by_name_or_id(context, identity):
if (not uuidutils.is_uuid_like(identity)):
return get_volume_type_by_name(context, identity)
return get_volume_type(context, identity)
| [
"def",
"get_by_name_or_id",
"(",
"context",
",",
"identity",
")",
":",
"if",
"(",
"not",
"uuidutils",
".",
"is_uuid_like",
"(",
"identity",
")",
")",
":",
"return",
"get_volume_type_by_name",
"(",
"context",
",",
"identity",
")",
"return",
"get_volume_type",
"(",
"context",
",",
"identity",
")"
] | retrieves volume type by id or name . | train | false |
39,869 | def _get_image_blob(im):
im_orig = im.astype(np.float32, copy=True)
im_orig -= cfg.PIXEL_MEANS
im_shape = im_orig.shape
im_size_min = np.min(im_shape[0:2])
im_size_max = np.max(im_shape[0:2])
processed_ims = []
im_scale_factors = []
for target_size in cfg.TEST.SCALES:
im_scale = (float(target_size) / float(im_size_min))
if (np.round((im_scale * im_size_max)) > cfg.TEST.MAX_SIZE):
im_scale = (float(cfg.TEST.MAX_SIZE) / float(im_size_max))
im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale, interpolation=cv2.INTER_LINEAR)
im_scale_factors.append(im_scale)
processed_ims.append(im)
blob = im_list_to_blob(processed_ims)
return (blob, np.array(im_scale_factors))
| [
"def",
"_get_image_blob",
"(",
"im",
")",
":",
"im_orig",
"=",
"im",
".",
"astype",
"(",
"np",
".",
"float32",
",",
"copy",
"=",
"True",
")",
"im_orig",
"-=",
"cfg",
".",
"PIXEL_MEANS",
"im_shape",
"=",
"im_orig",
".",
"shape",
"im_size_min",
"=",
"np",
".",
"min",
"(",
"im_shape",
"[",
"0",
":",
"2",
"]",
")",
"im_size_max",
"=",
"np",
".",
"max",
"(",
"im_shape",
"[",
"0",
":",
"2",
"]",
")",
"processed_ims",
"=",
"[",
"]",
"im_scale_factors",
"=",
"[",
"]",
"for",
"target_size",
"in",
"cfg",
".",
"TEST",
".",
"SCALES",
":",
"im_scale",
"=",
"(",
"float",
"(",
"target_size",
")",
"/",
"float",
"(",
"im_size_min",
")",
")",
"if",
"(",
"np",
".",
"round",
"(",
"(",
"im_scale",
"*",
"im_size_max",
")",
")",
">",
"cfg",
".",
"TEST",
".",
"MAX_SIZE",
")",
":",
"im_scale",
"=",
"(",
"float",
"(",
"cfg",
".",
"TEST",
".",
"MAX_SIZE",
")",
"/",
"float",
"(",
"im_size_max",
")",
")",
"im",
"=",
"cv2",
".",
"resize",
"(",
"im_orig",
",",
"None",
",",
"None",
",",
"fx",
"=",
"im_scale",
",",
"fy",
"=",
"im_scale",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_LINEAR",
")",
"im_scale_factors",
".",
"append",
"(",
"im_scale",
")",
"processed_ims",
".",
"append",
"(",
"im",
")",
"blob",
"=",
"im_list_to_blob",
"(",
"processed_ims",
")",
"return",
"(",
"blob",
",",
"np",
".",
"array",
"(",
"im_scale_factors",
")",
")"
] | converts an image into a network input . | train | false |
39,870 | def _lookup_error(number):
return_values = {2: 'Invalid OU or specifying OU is not supported', 5: 'Access is denied', 53: 'The network path was not found', 87: 'The parameter is incorrect', 110: 'The system cannot open the specified object', 1323: 'Unable to update the password', 1326: 'Logon failure: unknown username or bad password', 1355: 'The specified domain either does not exist or could not be contacted', 2224: 'The account already exists', 2691: 'The machine is already joined to the domain', 2692: 'The machine is not currently joined to a domain'}
return return_values[number]
| [
"def",
"_lookup_error",
"(",
"number",
")",
":",
"return_values",
"=",
"{",
"2",
":",
"'Invalid OU or specifying OU is not supported'",
",",
"5",
":",
"'Access is denied'",
",",
"53",
":",
"'The network path was not found'",
",",
"87",
":",
"'The parameter is incorrect'",
",",
"110",
":",
"'The system cannot open the specified object'",
",",
"1323",
":",
"'Unable to update the password'",
",",
"1326",
":",
"'Logon failure: unknown username or bad password'",
",",
"1355",
":",
"'The specified domain either does not exist or could not be contacted'",
",",
"2224",
":",
"'The account already exists'",
",",
"2691",
":",
"'The machine is already joined to the domain'",
",",
"2692",
":",
"'The machine is not currently joined to a domain'",
"}",
"return",
"return_values",
"[",
"number",
"]"
] | lookup the error based on the passed number . | train | false |
39,871 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | return a fresh instance of the hash object . | train | false |
39,872 | def filter_headers(headers, remove_headers):
remove_headers = [((h, None) if isinstance(h, basestring) else h) for h in remove_headers]
remove_headers = dict(((h.lower(), v) for (h, v) in remove_headers))
headers = dict(((h, remove_headers.get(h.lower(), v)) for (h, v) in headers.items()))
headers = dict(((h, v) for (h, v) in headers.items() if (v is not None)))
return headers
| [
"def",
"filter_headers",
"(",
"headers",
",",
"remove_headers",
")",
":",
"remove_headers",
"=",
"[",
"(",
"(",
"h",
",",
"None",
")",
"if",
"isinstance",
"(",
"h",
",",
"basestring",
")",
"else",
"h",
")",
"for",
"h",
"in",
"remove_headers",
"]",
"remove_headers",
"=",
"dict",
"(",
"(",
"(",
"h",
".",
"lower",
"(",
")",
",",
"v",
")",
"for",
"(",
"h",
",",
"v",
")",
"in",
"remove_headers",
")",
")",
"headers",
"=",
"dict",
"(",
"(",
"(",
"h",
",",
"remove_headers",
".",
"get",
"(",
"h",
".",
"lower",
"(",
")",
",",
"v",
")",
")",
"for",
"(",
"h",
",",
"v",
")",
"in",
"headers",
".",
"items",
"(",
")",
")",
")",
"headers",
"=",
"dict",
"(",
"(",
"(",
"h",
",",
"v",
")",
"for",
"(",
"h",
",",
"v",
")",
"in",
"headers",
".",
"items",
"(",
")",
"if",
"(",
"v",
"is",
"not",
"None",
")",
")",
")",
"return",
"headers"
] | remove undesired headers from the provided headers dict . | train | false |
39,873 | def p_equality_expression_2(t):
pass
| [
"def",
"p_equality_expression_2",
"(",
"t",
")",
":",
"pass"
] | equality_expression : equality_expression eq relational_expression . | train | false |
39,874 | def loopbackTCP(server, client, port=0, noisy=True):
from twisted.internet import reactor
f = policies.WrappingFactory(protocol.Factory())
serverWrapper = _FireOnClose(f, server)
f.noisy = noisy
f.buildProtocol = (lambda addr: serverWrapper)
serverPort = reactor.listenTCP(port, f, interface='127.0.0.1')
clientF = LoopbackClientFactory(client)
clientF.noisy = noisy
reactor.connectTCP('127.0.0.1', serverPort.getHost().port, clientF)
d = clientF.deferred
d.addCallback((lambda x: serverWrapper.deferred))
d.addCallback((lambda x: serverPort.stopListening()))
return d
| [
"def",
"loopbackTCP",
"(",
"server",
",",
"client",
",",
"port",
"=",
"0",
",",
"noisy",
"=",
"True",
")",
":",
"from",
"twisted",
".",
"internet",
"import",
"reactor",
"f",
"=",
"policies",
".",
"WrappingFactory",
"(",
"protocol",
".",
"Factory",
"(",
")",
")",
"serverWrapper",
"=",
"_FireOnClose",
"(",
"f",
",",
"server",
")",
"f",
".",
"noisy",
"=",
"noisy",
"f",
".",
"buildProtocol",
"=",
"(",
"lambda",
"addr",
":",
"serverWrapper",
")",
"serverPort",
"=",
"reactor",
".",
"listenTCP",
"(",
"port",
",",
"f",
",",
"interface",
"=",
"'127.0.0.1'",
")",
"clientF",
"=",
"LoopbackClientFactory",
"(",
"client",
")",
"clientF",
".",
"noisy",
"=",
"noisy",
"reactor",
".",
"connectTCP",
"(",
"'127.0.0.1'",
",",
"serverPort",
".",
"getHost",
"(",
")",
".",
"port",
",",
"clientF",
")",
"d",
"=",
"clientF",
".",
"deferred",
"d",
".",
"addCallback",
"(",
"(",
"lambda",
"x",
":",
"serverWrapper",
".",
"deferred",
")",
")",
"d",
".",
"addCallback",
"(",
"(",
"lambda",
"x",
":",
"serverPort",
".",
"stopListening",
"(",
")",
")",
")",
"return",
"d"
] | run session between server and client protocol instances over tcp . | train | false |
39,875 | def _is_scaled_mri_subject(subject, subjects_dir=None):
subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
if (not _is_mri_subject(subject, subjects_dir)):
return False
fname = os.path.join(subjects_dir, subject, 'MRI scaling parameters.cfg')
return os.path.exists(fname)
| [
"def",
"_is_scaled_mri_subject",
"(",
"subject",
",",
"subjects_dir",
"=",
"None",
")",
":",
"subjects_dir",
"=",
"get_subjects_dir",
"(",
"subjects_dir",
",",
"raise_error",
"=",
"True",
")",
"if",
"(",
"not",
"_is_mri_subject",
"(",
"subject",
",",
"subjects_dir",
")",
")",
":",
"return",
"False",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"subjects_dir",
",",
"subject",
",",
"'MRI scaling parameters.cfg'",
")",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")"
] | check whether a directory in subjects_dir is a scaled mri subject . | train | false |
39,876 | @utils.arg('flavor', metavar='<flavor>', help=_('Flavor name or ID to add access for the given tenant.'))
@utils.arg('tenant', metavar='<tenant_id>', help=_('Tenant ID to add flavor access for.'))
def do_flavor_access_add(cs, args):
flavor = _find_flavor(cs, args.flavor)
access_list = cs.flavor_access.add_tenant_access(flavor, args.tenant)
columns = ['Flavor_ID', 'Tenant_ID']
utils.print_list(access_list, columns)
| [
"@",
"utils",
".",
"arg",
"(",
"'flavor'",
",",
"metavar",
"=",
"'<flavor>'",
",",
"help",
"=",
"_",
"(",
"'Flavor name or ID to add access for the given tenant.'",
")",
")",
"@",
"utils",
".",
"arg",
"(",
"'tenant'",
",",
"metavar",
"=",
"'<tenant_id>'",
",",
"help",
"=",
"_",
"(",
"'Tenant ID to add flavor access for.'",
")",
")",
"def",
"do_flavor_access_add",
"(",
"cs",
",",
"args",
")",
":",
"flavor",
"=",
"_find_flavor",
"(",
"cs",
",",
"args",
".",
"flavor",
")",
"access_list",
"=",
"cs",
".",
"flavor_access",
".",
"add_tenant_access",
"(",
"flavor",
",",
"args",
".",
"tenant",
")",
"columns",
"=",
"[",
"'Flavor_ID'",
",",
"'Tenant_ID'",
"]",
"utils",
".",
"print_list",
"(",
"access_list",
",",
"columns",
")"
] | add flavor access for the given tenant . | train | false |
39,877 | def _setHTTPTimeout():
if conf.timeout:
infoMsg = 'setting the HTTP timeout'
logger.log(CUSTOM_LOGGING.SYSINFO, infoMsg)
conf.timeout = float(conf.timeout)
if (conf.timeout < 3.0):
warnMsg = 'the minimum HTTP timeout is 3 seconds, pocsuite will going to reset it'
logger.log(CUSTOM_LOGGING.WARNING, warnMsg)
conf.timeout = 3.0
else:
conf.timeout = 30.0
socket.setdefaulttimeout(conf.timeout)
| [
"def",
"_setHTTPTimeout",
"(",
")",
":",
"if",
"conf",
".",
"timeout",
":",
"infoMsg",
"=",
"'setting the HTTP timeout'",
"logger",
".",
"log",
"(",
"CUSTOM_LOGGING",
".",
"SYSINFO",
",",
"infoMsg",
")",
"conf",
".",
"timeout",
"=",
"float",
"(",
"conf",
".",
"timeout",
")",
"if",
"(",
"conf",
".",
"timeout",
"<",
"3.0",
")",
":",
"warnMsg",
"=",
"'the minimum HTTP timeout is 3 seconds, pocsuite will going to reset it'",
"logger",
".",
"log",
"(",
"CUSTOM_LOGGING",
".",
"WARNING",
",",
"warnMsg",
")",
"conf",
".",
"timeout",
"=",
"3.0",
"else",
":",
"conf",
".",
"timeout",
"=",
"30.0",
"socket",
".",
"setdefaulttimeout",
"(",
"conf",
".",
"timeout",
")"
] | set the http timeout . | train | false |
39,878 | def dmp_l1_norm(f, u, K):
if (not u):
return dup_l1_norm(f, K)
v = (u - 1)
return sum([dmp_l1_norm(c, v, K) for c in f])
| [
"def",
"dmp_l1_norm",
"(",
"f",
",",
"u",
",",
"K",
")",
":",
"if",
"(",
"not",
"u",
")",
":",
"return",
"dup_l1_norm",
"(",
"f",
",",
"K",
")",
"v",
"=",
"(",
"u",
"-",
"1",
")",
"return",
"sum",
"(",
"[",
"dmp_l1_norm",
"(",
"c",
",",
"v",
",",
"K",
")",
"for",
"c",
"in",
"f",
"]",
")"
] | returns l1 norm of a polynomial in k[x] . | train | false |
39,879 | def default_request_ip_resolver(request):
return (real_ip(request) or x_forwarded_ip(request) or remote_addr_ip(request))
| [
"def",
"default_request_ip_resolver",
"(",
"request",
")",
":",
"return",
"(",
"real_ip",
"(",
"request",
")",
"or",
"x_forwarded_ip",
"(",
"request",
")",
"or",
"remote_addr_ip",
"(",
"request",
")",
")"
] | this is a hybrid request ip resolver that attempts should address most cases . | train | false |
39,880 | def PackString(name, value, pbvalue):
pbvalue.set_stringvalue(unicode(value).encode('utf-8'))
| [
"def",
"PackString",
"(",
"name",
",",
"value",
",",
"pbvalue",
")",
":",
"pbvalue",
".",
"set_stringvalue",
"(",
"unicode",
"(",
"value",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | packs a string-typed property into a entity_pb . | train | false |
39,881 | @click.command(u'purge-jobs')
@click.option(u'--site', help=u'site name')
@click.option(u'--queue', default=None, help=u'one of "low", "default", "high')
@click.option(u'--event', default=None, help=u'one of "all", "weekly", "monthly", "hourly", "daily", "weekly_long", "daily_long"')
def purge_jobs(site=None, queue=None, event=None):
from frappe.utils.doctor import purge_pending_jobs
frappe.init((site or u''))
count = purge_pending_jobs(event=event, site=site, queue=queue)
print u'Purged {} jobs'.format(count)
| [
"@",
"click",
".",
"command",
"(",
"u'purge-jobs'",
")",
"@",
"click",
".",
"option",
"(",
"u'--site'",
",",
"help",
"=",
"u'site name'",
")",
"@",
"click",
".",
"option",
"(",
"u'--queue'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"u'one of \"low\", \"default\", \"high'",
")",
"@",
"click",
".",
"option",
"(",
"u'--event'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"u'one of \"all\", \"weekly\", \"monthly\", \"hourly\", \"daily\", \"weekly_long\", \"daily_long\"'",
")",
"def",
"purge_jobs",
"(",
"site",
"=",
"None",
",",
"queue",
"=",
"None",
",",
"event",
"=",
"None",
")",
":",
"from",
"frappe",
".",
"utils",
".",
"doctor",
"import",
"purge_pending_jobs",
"frappe",
".",
"init",
"(",
"(",
"site",
"or",
"u''",
")",
")",
"count",
"=",
"purge_pending_jobs",
"(",
"event",
"=",
"event",
",",
"site",
"=",
"site",
",",
"queue",
"=",
"queue",
")",
"print",
"u'Purged {} jobs'",
".",
"format",
"(",
"count",
")"
] | purge any pending periodic tasks . | train | false |
39,882 | def Channel(n):
rv = channels.get(n, None)
if (rv is None):
rv = ChannelImpl(n)
channels[n] = rv
return rv
| [
"def",
"Channel",
"(",
"n",
")",
":",
"rv",
"=",
"channels",
".",
"get",
"(",
"n",
",",
"None",
")",
"if",
"(",
"rv",
"is",
"None",
")",
":",
"rv",
"=",
"ChannelImpl",
"(",
"n",
")",
"channels",
"[",
"n",
"]",
"=",
"rv",
"return",
"rv"
] | gets the channel with the given number . | train | true |
39,883 | @cache_page(3600, key_prefix=('js18n-%s' % get_language()))
def javascript_catalog_all(request, domain='djangojs'):
all_apps = [x.name for x in apps.get_app_configs()]
return javascript_catalog(request, domain, all_apps)
| [
"@",
"cache_page",
"(",
"3600",
",",
"key_prefix",
"=",
"(",
"'js18n-%s'",
"%",
"get_language",
"(",
")",
")",
")",
"def",
"javascript_catalog_all",
"(",
"request",
",",
"domain",
"=",
"'djangojs'",
")",
":",
"all_apps",
"=",
"[",
"x",
".",
"name",
"for",
"x",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
"]",
"return",
"javascript_catalog",
"(",
"request",
",",
"domain",
",",
"all_apps",
")"
] | get javascript message catalog for all apps in installed_apps . | train | false |
39,884 | def test_significant():
f = formatters.significant
assert (f(1) == '1')
assert (f(1.0) == '1')
assert (f((-1.0)) == '-1')
assert (f(10) == '10')
assert (f(10000000000) == '1e+10')
assert (f(100000000000) == '1e+11')
assert (f(120000000000) == '1.2e+11')
assert (f(0.1) == '0.1')
assert (f(0.01) == '0.01')
assert (f(1e-10) == '1e-10')
assert (f((-1e-10)) == '-1e-10')
assert (f(1.002e-10) == '1.002e-10')
assert (f(1.002e-10) == '1.002e-10')
assert (f(0.12345678912345) == '0.1234567891')
assert (f(0.012345678912345) == '0.01234567891')
assert (f(12345678912345) == '1.234567891e+13')
| [
"def",
"test_significant",
"(",
")",
":",
"f",
"=",
"formatters",
".",
"significant",
"assert",
"(",
"f",
"(",
"1",
")",
"==",
"'1'",
")",
"assert",
"(",
"f",
"(",
"1.0",
")",
"==",
"'1'",
")",
"assert",
"(",
"f",
"(",
"(",
"-",
"1.0",
")",
")",
"==",
"'-1'",
")",
"assert",
"(",
"f",
"(",
"10",
")",
"==",
"'10'",
")",
"assert",
"(",
"f",
"(",
"10000000000",
")",
"==",
"'1e+10'",
")",
"assert",
"(",
"f",
"(",
"100000000000",
")",
"==",
"'1e+11'",
")",
"assert",
"(",
"f",
"(",
"120000000000",
")",
"==",
"'1.2e+11'",
")",
"assert",
"(",
"f",
"(",
"0.1",
")",
"==",
"'0.1'",
")",
"assert",
"(",
"f",
"(",
"0.01",
")",
"==",
"'0.01'",
")",
"assert",
"(",
"f",
"(",
"1e-10",
")",
"==",
"'1e-10'",
")",
"assert",
"(",
"f",
"(",
"(",
"-",
"1e-10",
")",
")",
"==",
"'-1e-10'",
")",
"assert",
"(",
"f",
"(",
"1.002e-10",
")",
"==",
"'1.002e-10'",
")",
"assert",
"(",
"f",
"(",
"1.002e-10",
")",
"==",
"'1.002e-10'",
")",
"assert",
"(",
"f",
"(",
"0.12345678912345",
")",
"==",
"'0.1234567891'",
")",
"assert",
"(",
"f",
"(",
"0.012345678912345",
")",
"==",
"'0.01234567891'",
")",
"assert",
"(",
"f",
"(",
"12345678912345",
")",
"==",
"'1.234567891e+13'",
")"
] | test significant formatter . | train | false |
39,885 | @default_selem
def black_tophat(image, selem=None, out=None):
if (out is image):
original = image.copy()
else:
original = image
out = closing(image, selem, out=out)
out -= original
return out
| [
"@",
"default_selem",
"def",
"black_tophat",
"(",
"image",
",",
"selem",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"if",
"(",
"out",
"is",
"image",
")",
":",
"original",
"=",
"image",
".",
"copy",
"(",
")",
"else",
":",
"original",
"=",
"image",
"out",
"=",
"closing",
"(",
"image",
",",
"selem",
",",
"out",
"=",
"out",
")",
"out",
"-=",
"original",
"return",
"out"
] | return black top hat of an image . | train | false |
39,886 | def get_outgoing_url(url):
if (not settings.REDIRECT_URL):
return url
parsed_url = urlparse(url)
url_netloc = parsed_url.netloc
if (parsed_url.scheme not in ['http', 'https']):
return '/'
if ((url_netloc == urlparse(settings.REDIRECT_URL).netloc) or (url_netloc in settings.REDIRECT_URL_ALLOW_LIST)):
return url
url = force_bytes(jinja2.utils.Markup(url).unescape())
sig = hmac.new(settings.REDIRECT_SECRET_KEY, msg=url, digestmod=hashlib.sha256).hexdigest()
return '/'.join([settings.REDIRECT_URL.rstrip('/'), sig, urllib.quote(url, safe='/&=')])
| [
"def",
"get_outgoing_url",
"(",
"url",
")",
":",
"if",
"(",
"not",
"settings",
".",
"REDIRECT_URL",
")",
":",
"return",
"url",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"url_netloc",
"=",
"parsed_url",
".",
"netloc",
"if",
"(",
"parsed_url",
".",
"scheme",
"not",
"in",
"[",
"'http'",
",",
"'https'",
"]",
")",
":",
"return",
"'/'",
"if",
"(",
"(",
"url_netloc",
"==",
"urlparse",
"(",
"settings",
".",
"REDIRECT_URL",
")",
".",
"netloc",
")",
"or",
"(",
"url_netloc",
"in",
"settings",
".",
"REDIRECT_URL_ALLOW_LIST",
")",
")",
":",
"return",
"url",
"url",
"=",
"force_bytes",
"(",
"jinja2",
".",
"utils",
".",
"Markup",
"(",
"url",
")",
".",
"unescape",
"(",
")",
")",
"sig",
"=",
"hmac",
".",
"new",
"(",
"settings",
".",
"REDIRECT_SECRET_KEY",
",",
"msg",
"=",
"url",
",",
"digestmod",
"=",
"hashlib",
".",
"sha256",
")",
".",
"hexdigest",
"(",
")",
"return",
"'/'",
".",
"join",
"(",
"[",
"settings",
".",
"REDIRECT_URL",
".",
"rstrip",
"(",
"'/'",
")",
",",
"sig",
",",
"urllib",
".",
"quote",
"(",
"url",
",",
"safe",
"=",
"'/&='",
")",
"]",
")"
] | bounce a url off an outgoing url redirector . | train | false |
39,889 | def send_draft_copy(account, draft, custom_body, recipient):
response_on_success = encode(draft)
response_on_success['body'] = custom_body
response_on_success = APIEncoder().jsonify(response_on_success)
try:
sendmail_client = get_sendmail_client(account)
sendmail_client.send_custom(draft, custom_body, [recipient])
except SendMailException as exc:
kwargs = {}
if exc.failures:
kwargs['failures'] = exc.failures
if exc.server_error:
kwargs['server_error'] = exc.server_error
return err(exc.http_code, exc.message, **kwargs)
return response_on_success
| [
"def",
"send_draft_copy",
"(",
"account",
",",
"draft",
",",
"custom_body",
",",
"recipient",
")",
":",
"response_on_success",
"=",
"encode",
"(",
"draft",
")",
"response_on_success",
"[",
"'body'",
"]",
"=",
"custom_body",
"response_on_success",
"=",
"APIEncoder",
"(",
")",
".",
"jsonify",
"(",
"response_on_success",
")",
"try",
":",
"sendmail_client",
"=",
"get_sendmail_client",
"(",
"account",
")",
"sendmail_client",
".",
"send_custom",
"(",
"draft",
",",
"custom_body",
",",
"[",
"recipient",
"]",
")",
"except",
"SendMailException",
"as",
"exc",
":",
"kwargs",
"=",
"{",
"}",
"if",
"exc",
".",
"failures",
":",
"kwargs",
"[",
"'failures'",
"]",
"=",
"exc",
".",
"failures",
"if",
"exc",
".",
"server_error",
":",
"kwargs",
"[",
"'server_error'",
"]",
"=",
"exc",
".",
"server_error",
"return",
"err",
"(",
"exc",
".",
"http_code",
",",
"exc",
".",
"message",
",",
"**",
"kwargs",
")",
"return",
"response_on_success"
] | sends a copy of this draft to the recipient . | train | false |
39,891 | def const_non_dominated_sort(iterable, key=(lambda x: x), allowequality=True):
items = set(iterable)
fronts = []
while items:
front = const_non_dominated_front(items, key, allowequality)
items -= front
fronts.append(front)
return fronts
| [
"def",
"const_non_dominated_sort",
"(",
"iterable",
",",
"key",
"=",
"(",
"lambda",
"x",
":",
"x",
")",
",",
"allowequality",
"=",
"True",
")",
":",
"items",
"=",
"set",
"(",
"iterable",
")",
"fronts",
"=",
"[",
"]",
"while",
"items",
":",
"front",
"=",
"const_non_dominated_front",
"(",
"items",
",",
"key",
",",
"allowequality",
")",
"items",
"-=",
"front",
"fronts",
".",
"append",
"(",
"front",
")",
"return",
"fronts"
] | return a list that is sorted in a non-dominating fashion . | train | false |
39,892 | def number_of_nodes(G):
return G.number_of_nodes()
| [
"def",
"number_of_nodes",
"(",
"G",
")",
":",
"return",
"G",
".",
"number_of_nodes",
"(",
")"
] | return the number of nodes in the graph . | train | false |
39,893 | def test_group_column_from_table(T1):
cg = T1['c'].group_by(np.array(T1['a']))
assert np.all((cg.groups.keys == np.array([0, 1, 2])))
assert np.all((cg.groups.indices == np.array([0, 1, 4, 8])))
| [
"def",
"test_group_column_from_table",
"(",
"T1",
")",
":",
"cg",
"=",
"T1",
"[",
"'c'",
"]",
".",
"group_by",
"(",
"np",
".",
"array",
"(",
"T1",
"[",
"'a'",
"]",
")",
")",
"assert",
"np",
".",
"all",
"(",
"(",
"cg",
".",
"groups",
".",
"keys",
"==",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
",",
"2",
"]",
")",
")",
")",
"assert",
"np",
".",
"all",
"(",
"(",
"cg",
".",
"groups",
".",
"indices",
"==",
"np",
".",
"array",
"(",
"[",
"0",
",",
"1",
",",
"4",
",",
"8",
"]",
")",
")",
")"
] | group a column that is part of a table . | train | false |
39,894 | def tar(file, filelist, expression='^.+$'):
tar = tarfile.TarFile(file, 'w')
try:
for element in filelist:
try:
for file in listdir(element, expression, add_dirs=True):
tar.add(os.path.join(element, file), file, False)
except:
tar.add(element)
finally:
tar.close()
| [
"def",
"tar",
"(",
"file",
",",
"filelist",
",",
"expression",
"=",
"'^.+$'",
")",
":",
"tar",
"=",
"tarfile",
".",
"TarFile",
"(",
"file",
",",
"'w'",
")",
"try",
":",
"for",
"element",
"in",
"filelist",
":",
"try",
":",
"for",
"file",
"in",
"listdir",
"(",
"element",
",",
"expression",
",",
"add_dirs",
"=",
"True",
")",
":",
"tar",
".",
"add",
"(",
"os",
".",
"path",
".",
"join",
"(",
"element",
",",
"file",
")",
",",
"file",
",",
"False",
")",
"except",
":",
"tar",
".",
"add",
"(",
"element",
")",
"finally",
":",
"tar",
".",
"close",
"(",
")"
] | tars dir into file . | train | false |
39,896 | def saltpath():
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)}
| [
"def",
"saltpath",
"(",
")",
":",
"salt_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"os",
".",
"path",
".",
"pardir",
")",
")",
"return",
"{",
"'saltpath'",
":",
"os",
".",
"path",
".",
"dirname",
"(",
"salt_path",
")",
"}"
] | return the path of the salt module . | train | true |
39,898 | def install_cygwin(name, install_args=None, override_args=False):
return install(name, source='cygwin', install_args=install_args, override_args=override_args)
| [
"def",
"install_cygwin",
"(",
"name",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"source",
"=",
"'cygwin'",
",",
"install_args",
"=",
"install_args",
",",
"override_args",
"=",
"override_args",
")"
] | instructs chocolatey to install a package via cygwin . | train | true |
39,899 | def get_blas_funcs(names, arrays=(), dtype=None):
return _get_funcs(names, arrays, dtype, 'BLAS', _fblas, _cblas, 'fblas', 'cblas', _blas_alias)
| [
"def",
"get_blas_funcs",
"(",
"names",
",",
"arrays",
"=",
"(",
")",
",",
"dtype",
"=",
"None",
")",
":",
"return",
"_get_funcs",
"(",
"names",
",",
"arrays",
",",
"dtype",
",",
"'BLAS'",
",",
"_fblas",
",",
"_cblas",
",",
"'fblas'",
",",
"'cblas'",
",",
"_blas_alias",
")"
] | return available blas function objects from names . | train | false |
39,900 | def get_theme_dir(name):
theme = get_themes()[name]
return os.path.dirname(os.path.abspath(theme.load().__file__))
| [
"def",
"get_theme_dir",
"(",
"name",
")",
":",
"theme",
"=",
"get_themes",
"(",
")",
"[",
"name",
"]",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"theme",
".",
"load",
"(",
")",
".",
"__file__",
")",
")"
] | return the directory of an installed theme by name . | train | false |
39,901 | def index_alt():
s3_redirect_default(URL(f='person'))
| [
"def",
"index_alt",
"(",
")",
":",
"s3_redirect_default",
"(",
"URL",
"(",
"f",
"=",
"'person'",
")",
")"
] | module homepage for non-admin users when no cms content found . | train | false |
39,902 | def create_client_from_parsed_globals(session, service_name, parsed_globals, overrides=None):
client_args = {}
if ('region' in parsed_globals):
client_args['region_name'] = parsed_globals.region
if ('endpoint_url' in parsed_globals):
client_args['endpoint_url'] = parsed_globals.endpoint_url
if ('verify_ssl' in parsed_globals):
client_args['verify'] = parsed_globals.verify_ssl
if overrides:
client_args.update(overrides)
return session.create_client(service_name, **client_args)
| [
"def",
"create_client_from_parsed_globals",
"(",
"session",
",",
"service_name",
",",
"parsed_globals",
",",
"overrides",
"=",
"None",
")",
":",
"client_args",
"=",
"{",
"}",
"if",
"(",
"'region'",
"in",
"parsed_globals",
")",
":",
"client_args",
"[",
"'region_name'",
"]",
"=",
"parsed_globals",
".",
"region",
"if",
"(",
"'endpoint_url'",
"in",
"parsed_globals",
")",
":",
"client_args",
"[",
"'endpoint_url'",
"]",
"=",
"parsed_globals",
".",
"endpoint_url",
"if",
"(",
"'verify_ssl'",
"in",
"parsed_globals",
")",
":",
"client_args",
"[",
"'verify'",
"]",
"=",
"parsed_globals",
".",
"verify_ssl",
"if",
"overrides",
":",
"client_args",
".",
"update",
"(",
"overrides",
")",
"return",
"session",
".",
"create_client",
"(",
"service_name",
",",
"**",
"client_args",
")"
] | creates a service client . | train | false |
39,905 | def test_ast_good_drop():
can_compile(u'(drop 1 [2 3])')
| [
"def",
"test_ast_good_drop",
"(",
")",
":",
"can_compile",
"(",
"u'(drop 1 [2 3])'",
")"
] | make sure ast can compile valid drop . | train | false |
39,908 | def installPexpect(vm, prompt=Prompt):
vm.sendline('sudo -n apt-get -qy install python-pexpect')
vm.expect(prompt)
| [
"def",
"installPexpect",
"(",
"vm",
",",
"prompt",
"=",
"Prompt",
")",
":",
"vm",
".",
"sendline",
"(",
"'sudo -n apt-get -qy install python-pexpect'",
")",
"vm",
".",
"expect",
"(",
"prompt",
")"
] | install pexpect . | train | false |
39,909 | def is_app_name_valid(app_name):
if re.match(VALID_APP_NAME_CHARS_REGEX, app_name):
return True
else:
return False
| [
"def",
"is_app_name_valid",
"(",
"app_name",
")",
":",
"if",
"re",
".",
"match",
"(",
"VALID_APP_NAME_CHARS_REGEX",
",",
"app_name",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | validates an application by checking if it contains certain characters . | train | false |
39,910 | def _count_syllables(word):
n = 0
p = False
for ch in ((word.endswith('e') and word[:(-1)]) or word):
v = (ch in VOWELS)
n += int((v and (not p)))
p = v
return n
| [
"def",
"_count_syllables",
"(",
"word",
")",
":",
"n",
"=",
"0",
"p",
"=",
"False",
"for",
"ch",
"in",
"(",
"(",
"word",
".",
"endswith",
"(",
"'e'",
")",
"and",
"word",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
"or",
"word",
")",
":",
"v",
"=",
"(",
"ch",
"in",
"VOWELS",
")",
"n",
"+=",
"int",
"(",
"(",
"v",
"and",
"(",
"not",
"p",
")",
")",
")",
"p",
"=",
"v",
"return",
"n"
] | returns the estimated number of syllables in the word by counting vowel-groups . | train | false |
39,911 | @library.filter
def entity_decode(str):
return htmlparser.unescape(str)
| [
"@",
"library",
".",
"filter",
"def",
"entity_decode",
"(",
"str",
")",
":",
"return",
"htmlparser",
".",
"unescape",
"(",
"str",
")"
] | turn html entities in a string into unicode . | train | false |
39,913 | def Linkable(filename):
return filename.endswith('.o')
| [
"def",
"Linkable",
"(",
"filename",
")",
":",
"return",
"filename",
".",
"endswith",
"(",
"'.o'",
")"
] | return true if the file is linkable . | train | false |
39,914 | @bdd.then(bdd.parsers.parse('{path} should be requested'))
def path_should_be_requested(httpbin, path):
httpbin.wait_for(verb='GET', path=('/' + path))
| [
"@",
"bdd",
".",
"then",
"(",
"bdd",
".",
"parsers",
".",
"parse",
"(",
"'{path} should be requested'",
")",
")",
"def",
"path_should_be_requested",
"(",
"httpbin",
",",
"path",
")",
":",
"httpbin",
".",
"wait_for",
"(",
"verb",
"=",
"'GET'",
",",
"path",
"=",
"(",
"'/'",
"+",
"path",
")",
")"
] | make sure the given path was loaded from the webserver . | train | false |
39,919 | def unicode_from_os(e):
if (sys.version_info >= (3,)):
return str(e)
try:
if isinstance(e, Exception):
e = e.args[0]
if isinstance(e, str_cls):
return e
if isinstance(e, int):
e = str(e)
return str_cls(e, _encoding)
except UnicodeDecodeError:
for encoding in _fallback_encodings:
try:
return str_cls(e, encoding, errors='strict')
except:
pass
return str_cls(e, errors='replace')
| [
"def",
"unicode_from_os",
"(",
"e",
")",
":",
"if",
"(",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
")",
")",
":",
"return",
"str",
"(",
"e",
")",
"try",
":",
"if",
"isinstance",
"(",
"e",
",",
"Exception",
")",
":",
"e",
"=",
"e",
".",
"args",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"e",
",",
"str_cls",
")",
":",
"return",
"e",
"if",
"isinstance",
"(",
"e",
",",
"int",
")",
":",
"e",
"=",
"str",
"(",
"e",
")",
"return",
"str_cls",
"(",
"e",
",",
"_encoding",
")",
"except",
"UnicodeDecodeError",
":",
"for",
"encoding",
"in",
"_fallback_encodings",
":",
"try",
":",
"return",
"str_cls",
"(",
"e",
",",
"encoding",
",",
"errors",
"=",
"'strict'",
")",
"except",
":",
"pass",
"return",
"str_cls",
"(",
"e",
",",
"errors",
"=",
"'replace'",
")"
] | this is needed as some exceptions coming from the os are already encoded and so just calling unicode(e) will result in an unicodedecodeerror as the string isnt in ascii form . | train | false |
39,920 | def rotation3d(x=0, y=0, z=0):
cos_x = cos(x)
cos_y = cos(y)
cos_z = cos(z)
sin_x = sin(x)
sin_y = sin(y)
sin_z = sin(z)
r = np.array([[(cos_y * cos_z), (((- cos_x) * sin_z) + ((sin_x * sin_y) * cos_z)), ((sin_x * sin_z) + ((cos_x * sin_y) * cos_z))], [(cos_y * sin_z), ((cos_x * cos_z) + ((sin_x * sin_y) * sin_z)), (((- sin_x) * cos_z) + ((cos_x * sin_y) * sin_z))], [(- sin_y), (sin_x * cos_y), (cos_x * cos_y)]], dtype=float)
return r
| [
"def",
"rotation3d",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"z",
"=",
"0",
")",
":",
"cos_x",
"=",
"cos",
"(",
"x",
")",
"cos_y",
"=",
"cos",
"(",
"y",
")",
"cos_z",
"=",
"cos",
"(",
"z",
")",
"sin_x",
"=",
"sin",
"(",
"x",
")",
"sin_y",
"=",
"sin",
"(",
"y",
")",
"sin_z",
"=",
"sin",
"(",
"z",
")",
"r",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"(",
"cos_y",
"*",
"cos_z",
")",
",",
"(",
"(",
"(",
"-",
"cos_x",
")",
"*",
"sin_z",
")",
"+",
"(",
"(",
"sin_x",
"*",
"sin_y",
")",
"*",
"cos_z",
")",
")",
",",
"(",
"(",
"sin_x",
"*",
"sin_z",
")",
"+",
"(",
"(",
"cos_x",
"*",
"sin_y",
")",
"*",
"cos_z",
")",
")",
"]",
",",
"[",
"(",
"cos_y",
"*",
"sin_z",
")",
",",
"(",
"(",
"cos_x",
"*",
"cos_z",
")",
"+",
"(",
"(",
"sin_x",
"*",
"sin_y",
")",
"*",
"sin_z",
")",
")",
",",
"(",
"(",
"(",
"-",
"sin_x",
")",
"*",
"cos_z",
")",
"+",
"(",
"(",
"cos_x",
"*",
"sin_y",
")",
"*",
"sin_z",
")",
")",
"]",
",",
"[",
"(",
"-",
"sin_y",
")",
",",
"(",
"sin_x",
"*",
"cos_y",
")",
",",
"(",
"cos_x",
"*",
"cos_y",
")",
"]",
"]",
",",
"dtype",
"=",
"float",
")",
"return",
"r"
] | create an array with a 3 dimensional rotation matrix . | train | false |
39,921 | def print_headers_as_table(args):
tables = []
for filename in args.filename:
try:
formatter = TableHeaderFormatter(filename)
tbl = formatter.parse(args.extensions, args.keywords, args.compressed)
if tbl:
tables.append(tbl)
except IOError as e:
log.error(str(e))
if (len(tables) == 0):
return False
elif (len(tables) == 1):
resulting_table = tables[0]
else:
resulting_table = table.vstack(tables)
resulting_table.write(sys.stdout, format=args.table)
| [
"def",
"print_headers_as_table",
"(",
"args",
")",
":",
"tables",
"=",
"[",
"]",
"for",
"filename",
"in",
"args",
".",
"filename",
":",
"try",
":",
"formatter",
"=",
"TableHeaderFormatter",
"(",
"filename",
")",
"tbl",
"=",
"formatter",
".",
"parse",
"(",
"args",
".",
"extensions",
",",
"args",
".",
"keywords",
",",
"args",
".",
"compressed",
")",
"if",
"tbl",
":",
"tables",
".",
"append",
"(",
"tbl",
")",
"except",
"IOError",
"as",
"e",
":",
"log",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"if",
"(",
"len",
"(",
"tables",
")",
"==",
"0",
")",
":",
"return",
"False",
"elif",
"(",
"len",
"(",
"tables",
")",
"==",
"1",
")",
":",
"resulting_table",
"=",
"tables",
"[",
"0",
"]",
"else",
":",
"resulting_table",
"=",
"table",
".",
"vstack",
"(",
"tables",
")",
"resulting_table",
".",
"write",
"(",
"sys",
".",
"stdout",
",",
"format",
"=",
"args",
".",
"table",
")"
] | prints fits header(s) in a machine-readable table format . | train | false |
39,922 | def header_quopri_check(c):
return bool(hqre.match(c))
| [
"def",
"header_quopri_check",
"(",
"c",
")",
":",
"return",
"bool",
"(",
"hqre",
".",
"match",
"(",
"c",
")",
")"
] | return true if the character should be escaped with header quopri . | train | false |
39,923 | def parse_coverage(report_dir, coveragerc):
report_dir.makedirs_p()
msg = colorize('green', 'Combining coverage reports')
print msg
sh('coverage combine --rcfile={}'.format(coveragerc))
msg = colorize('green', 'Generating coverage reports')
print msg
sh('coverage html --rcfile={}'.format(coveragerc))
sh('coverage xml --rcfile={}'.format(coveragerc))
sh('coverage report --rcfile={}'.format(coveragerc))
| [
"def",
"parse_coverage",
"(",
"report_dir",
",",
"coveragerc",
")",
":",
"report_dir",
".",
"makedirs_p",
"(",
")",
"msg",
"=",
"colorize",
"(",
"'green'",
",",
"'Combining coverage reports'",
")",
"print",
"msg",
"sh",
"(",
"'coverage combine --rcfile={}'",
".",
"format",
"(",
"coveragerc",
")",
")",
"msg",
"=",
"colorize",
"(",
"'green'",
",",
"'Generating coverage reports'",
")",
"print",
"msg",
"sh",
"(",
"'coverage html --rcfile={}'",
".",
"format",
"(",
"coveragerc",
")",
")",
"sh",
"(",
"'coverage xml --rcfile={}'",
".",
"format",
"(",
"coveragerc",
")",
")",
"sh",
"(",
"'coverage report --rcfile={}'",
".",
"format",
"(",
"coveragerc",
")",
")"
] | generate coverage reports for bok-choy or a11y tests . | train | false |
39,924 | @require_POST
def ajax_enable(request):
if (not request.user.is_authenticated()):
raise PermissionDenied
enable_notifications(request.user)
return HttpResponse(status=204)
| [
"@",
"require_POST",
"def",
"ajax_enable",
"(",
"request",
")",
":",
"if",
"(",
"not",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
")",
":",
"raise",
"PermissionDenied",
"enable_notifications",
"(",
"request",
".",
"user",
")",
"return",
"HttpResponse",
"(",
"status",
"=",
"204",
")"
] | a view that enables notifications for the authenticated user this view should be invoked by an ajax post call . | train | false |
39,925 | def compile_views(folder, skip_failed_views=False):
path = pjoin(folder, 'views')
failed_views = []
for fname in listdir(path, '^[\\w/\\-]+(\\.\\w+)*$'):
try:
data = parse_template(fname, path)
except Exception as e:
if skip_failed_views:
failed_views.append(fname)
else:
raise Exception(('%s in %s' % (e, fname)))
else:
filename = ('views.%s.py' % fname.replace(os.path.sep, '.'))
filename = pjoin(folder, 'compiled', filename)
write_file(filename, data)
save_pyc(filename)
os.unlink(filename)
return (failed_views if failed_views else None)
| [
"def",
"compile_views",
"(",
"folder",
",",
"skip_failed_views",
"=",
"False",
")",
":",
"path",
"=",
"pjoin",
"(",
"folder",
",",
"'views'",
")",
"failed_views",
"=",
"[",
"]",
"for",
"fname",
"in",
"listdir",
"(",
"path",
",",
"'^[\\\\w/\\\\-]+(\\\\.\\\\w+)*$'",
")",
":",
"try",
":",
"data",
"=",
"parse_template",
"(",
"fname",
",",
"path",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"skip_failed_views",
":",
"failed_views",
".",
"append",
"(",
"fname",
")",
"else",
":",
"raise",
"Exception",
"(",
"(",
"'%s in %s'",
"%",
"(",
"e",
",",
"fname",
")",
")",
")",
"else",
":",
"filename",
"=",
"(",
"'views.%s.py'",
"%",
"fname",
".",
"replace",
"(",
"os",
".",
"path",
".",
"sep",
",",
"'.'",
")",
")",
"filename",
"=",
"pjoin",
"(",
"folder",
",",
"'compiled'",
",",
"filename",
")",
"write_file",
"(",
"filename",
",",
"data",
")",
"save_pyc",
"(",
"filename",
")",
"os",
".",
"unlink",
"(",
"filename",
")",
"return",
"(",
"failed_views",
"if",
"failed_views",
"else",
"None",
")"
] | compiles all the views in the application specified by folder . | train | false |
39,926 | def makeData(amount=10000):
center = array([0.5, 0.5])
def makePoint():
"Return a random point and its satellite information.\n\n Satellite is 'blue' if point is in the circle, else 'red'."
point = (random.random((2,)) * 10)
vectorLength = (lambda x: dot(x.T, x))
return (point, ('blue' if (vectorLength((point - center)) < 25) else 'red'))
return [makePoint() for _ in range(amount)]
| [
"def",
"makeData",
"(",
"amount",
"=",
"10000",
")",
":",
"center",
"=",
"array",
"(",
"[",
"0.5",
",",
"0.5",
"]",
")",
"def",
"makePoint",
"(",
")",
":",
"point",
"=",
"(",
"random",
".",
"random",
"(",
"(",
"2",
",",
")",
")",
"*",
"10",
")",
"vectorLength",
"=",
"(",
"lambda",
"x",
":",
"dot",
"(",
"x",
".",
"T",
",",
"x",
")",
")",
"return",
"(",
"point",
",",
"(",
"'blue'",
"if",
"(",
"vectorLength",
"(",
"(",
"point",
"-",
"center",
")",
")",
"<",
"25",
")",
"else",
"'red'",
")",
")",
"return",
"[",
"makePoint",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"amount",
")",
"]"
] | return 2d dataset of points in where points in a circle of radius . | train | false |
39,927 | def get_latest_changelog():
started = False
lines = []
with open(CHANGELOG) as f:
for line in f:
if re.match('^--+$', line.strip()):
if started:
del lines[(-1)]
break
else:
started = True
elif started:
lines.append(line)
return ''.join(lines).strip()
| [
"def",
"get_latest_changelog",
"(",
")",
":",
"started",
"=",
"False",
"lines",
"=",
"[",
"]",
"with",
"open",
"(",
"CHANGELOG",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"if",
"re",
".",
"match",
"(",
"'^--+$'",
",",
"line",
".",
"strip",
"(",
")",
")",
":",
"if",
"started",
":",
"del",
"lines",
"[",
"(",
"-",
"1",
")",
"]",
"break",
"else",
":",
"started",
"=",
"True",
"elif",
"started",
":",
"lines",
".",
"append",
"(",
"line",
")",
"return",
"''",
".",
"join",
"(",
"lines",
")",
".",
"strip",
"(",
")"
] | extract the first section of the changelog . | train | false |
39,928 | def get_indexer_numbering(indexer_id, indexer, sceneSeason, sceneEpisode, fallback_to_xem=True):
if ((indexer_id is None) or (sceneSeason is None) or (sceneEpisode is None)):
return (sceneSeason, sceneEpisode)
indexer_id = int(indexer_id)
indexer = int(indexer)
main_db_con = db.DBConnection()
rows = main_db_con.select('SELECT season, episode FROM scene_numbering WHERE indexer = ? and indexer_id = ? and scene_season = ? and scene_episode = ?', [indexer, indexer_id, sceneSeason, sceneEpisode])
if rows:
return (int(rows[0]['season']), int(rows[0]['episode']))
else:
if fallback_to_xem:
return get_indexer_numbering_for_xem(indexer_id, indexer, sceneSeason, sceneEpisode)
return (sceneSeason, sceneEpisode)
| [
"def",
"get_indexer_numbering",
"(",
"indexer_id",
",",
"indexer",
",",
"sceneSeason",
",",
"sceneEpisode",
",",
"fallback_to_xem",
"=",
"True",
")",
":",
"if",
"(",
"(",
"indexer_id",
"is",
"None",
")",
"or",
"(",
"sceneSeason",
"is",
"None",
")",
"or",
"(",
"sceneEpisode",
"is",
"None",
")",
")",
":",
"return",
"(",
"sceneSeason",
",",
"sceneEpisode",
")",
"indexer_id",
"=",
"int",
"(",
"indexer_id",
")",
"indexer",
"=",
"int",
"(",
"indexer",
")",
"main_db_con",
"=",
"db",
".",
"DBConnection",
"(",
")",
"rows",
"=",
"main_db_con",
".",
"select",
"(",
"'SELECT season, episode FROM scene_numbering WHERE indexer = ? and indexer_id = ? and scene_season = ? and scene_episode = ?'",
",",
"[",
"indexer",
",",
"indexer_id",
",",
"sceneSeason",
",",
"sceneEpisode",
"]",
")",
"if",
"rows",
":",
"return",
"(",
"int",
"(",
"rows",
"[",
"0",
"]",
"[",
"'season'",
"]",
")",
",",
"int",
"(",
"rows",
"[",
"0",
"]",
"[",
"'episode'",
"]",
")",
")",
"else",
":",
"if",
"fallback_to_xem",
":",
"return",
"get_indexer_numbering_for_xem",
"(",
"indexer_id",
",",
"indexer",
",",
"sceneSeason",
",",
"sceneEpisode",
")",
"return",
"(",
"sceneSeason",
",",
"sceneEpisode",
")"
] | returns a tuple . | train | false |
39,929 | @ignore_warnings
def check_estimators_pickle(name, Estimator):
check_methods = ['predict', 'transform', 'decision_function', 'predict_proba']
(X, y) = make_blobs(n_samples=30, centers=[[0, 0, 0], [1, 1, 1]], random_state=0, n_features=2, cluster_std=0.1)
X -= X.min()
y = multioutput_estimator_convert_y_2d(name, y)
estimator = Estimator()
set_random_state(estimator)
set_testing_parameters(estimator)
estimator.fit(X, y)
result = dict()
for method in check_methods:
if hasattr(estimator, method):
result[method] = getattr(estimator, method)(X)
pickled_estimator = pickle.dumps(estimator)
if Estimator.__module__.startswith('sklearn.'):
assert_true(('version' in pickled_estimator))
unpickled_estimator = pickle.loads(pickled_estimator)
for method in result:
unpickled_result = getattr(unpickled_estimator, method)(X)
assert_array_almost_equal(result[method], unpickled_result)
| [
"@",
"ignore_warnings",
"def",
"check_estimators_pickle",
"(",
"name",
",",
"Estimator",
")",
":",
"check_methods",
"=",
"[",
"'predict'",
",",
"'transform'",
",",
"'decision_function'",
",",
"'predict_proba'",
"]",
"(",
"X",
",",
"y",
")",
"=",
"make_blobs",
"(",
"n_samples",
"=",
"30",
",",
"centers",
"=",
"[",
"[",
"0",
",",
"0",
",",
"0",
"]",
",",
"[",
"1",
",",
"1",
",",
"1",
"]",
"]",
",",
"random_state",
"=",
"0",
",",
"n_features",
"=",
"2",
",",
"cluster_std",
"=",
"0.1",
")",
"X",
"-=",
"X",
".",
"min",
"(",
")",
"y",
"=",
"multioutput_estimator_convert_y_2d",
"(",
"name",
",",
"y",
")",
"estimator",
"=",
"Estimator",
"(",
")",
"set_random_state",
"(",
"estimator",
")",
"set_testing_parameters",
"(",
"estimator",
")",
"estimator",
".",
"fit",
"(",
"X",
",",
"y",
")",
"result",
"=",
"dict",
"(",
")",
"for",
"method",
"in",
"check_methods",
":",
"if",
"hasattr",
"(",
"estimator",
",",
"method",
")",
":",
"result",
"[",
"method",
"]",
"=",
"getattr",
"(",
"estimator",
",",
"method",
")",
"(",
"X",
")",
"pickled_estimator",
"=",
"pickle",
".",
"dumps",
"(",
"estimator",
")",
"if",
"Estimator",
".",
"__module__",
".",
"startswith",
"(",
"'sklearn.'",
")",
":",
"assert_true",
"(",
"(",
"'version'",
"in",
"pickled_estimator",
")",
")",
"unpickled_estimator",
"=",
"pickle",
".",
"loads",
"(",
"pickled_estimator",
")",
"for",
"method",
"in",
"result",
":",
"unpickled_result",
"=",
"getattr",
"(",
"unpickled_estimator",
",",
"method",
")",
"(",
"X",
")",
"assert_array_almost_equal",
"(",
"result",
"[",
"method",
"]",
",",
"unpickled_result",
")"
] | test that we can pickle all estimators . | train | false |
39,930 | def get_model_front_url(request, object):
if (not object.pk):
return None
if (u'shuup.front' in settings.INSTALLED_APPS):
try:
from shuup.front.template_helpers.urls import model_url
return model_url({u'request': request}, object)
except (ValueError, NoReverseMatch):
pass
return None
| [
"def",
"get_model_front_url",
"(",
"request",
",",
"object",
")",
":",
"if",
"(",
"not",
"object",
".",
"pk",
")",
":",
"return",
"None",
"if",
"(",
"u'shuup.front'",
"in",
"settings",
".",
"INSTALLED_APPS",
")",
":",
"try",
":",
"from",
"shuup",
".",
"front",
".",
"template_helpers",
".",
"urls",
"import",
"model_url",
"return",
"model_url",
"(",
"{",
"u'request'",
":",
"request",
"}",
",",
"object",
")",
"except",
"(",
"ValueError",
",",
"NoReverseMatch",
")",
":",
"pass",
"return",
"None"
] | get a frontend url for an object . | train | false |
39,931 | def GC_skew(seq, window=100):
values = []
for i in range(0, len(seq), window):
s = seq[i:(i + window)]
g = (s.count('G') + s.count('g'))
c = (s.count('C') + s.count('c'))
skew = ((g - c) / float((g + c)))
values.append(skew)
return values
| [
"def",
"GC_skew",
"(",
"seq",
",",
"window",
"=",
"100",
")",
":",
"values",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"seq",
")",
",",
"window",
")",
":",
"s",
"=",
"seq",
"[",
"i",
":",
"(",
"i",
"+",
"window",
")",
"]",
"g",
"=",
"(",
"s",
".",
"count",
"(",
"'G'",
")",
"+",
"s",
".",
"count",
"(",
"'g'",
")",
")",
"c",
"=",
"(",
"s",
".",
"count",
"(",
"'C'",
")",
"+",
"s",
".",
"count",
"(",
"'c'",
")",
")",
"skew",
"=",
"(",
"(",
"g",
"-",
"c",
")",
"/",
"float",
"(",
"(",
"g",
"+",
"c",
")",
")",
")",
"values",
".",
"append",
"(",
"skew",
")",
"return",
"values"
] | calculates gc skew / for multiple windows along the sequence . | train | false |
39,932 | def run_example(example, reporter=None):
if reporter:
reporter.write(example)
else:
print(('=' * 79))
print('Running: ', example)
try:
mod = load_example_module(example)
if reporter:
suppress_output(mod.main)
reporter.write('[PASS]', 'Green', align='right')
else:
mod.main()
return True
except KeyboardInterrupt as e:
raise e
except:
if reporter:
reporter.write('[FAIL]', 'Red', align='right')
traceback.print_exc()
return False
| [
"def",
"run_example",
"(",
"example",
",",
"reporter",
"=",
"None",
")",
":",
"if",
"reporter",
":",
"reporter",
".",
"write",
"(",
"example",
")",
"else",
":",
"print",
"(",
"(",
"'='",
"*",
"79",
")",
")",
"print",
"(",
"'Running: '",
",",
"example",
")",
"try",
":",
"mod",
"=",
"load_example_module",
"(",
"example",
")",
"if",
"reporter",
":",
"suppress_output",
"(",
"mod",
".",
"main",
")",
"reporter",
".",
"write",
"(",
"'[PASS]'",
",",
"'Green'",
",",
"align",
"=",
"'right'",
")",
"else",
":",
"mod",
".",
"main",
"(",
")",
"return",
"True",
"except",
"KeyboardInterrupt",
"as",
"e",
":",
"raise",
"e",
"except",
":",
"if",
"reporter",
":",
"reporter",
".",
"write",
"(",
"'[FAIL]'",
",",
"'Red'",
",",
"align",
"=",
"'right'",
")",
"traceback",
".",
"print_exc",
"(",
")",
"return",
"False"
] | run a specific example . | train | false |
39,934 | @deprecated.Callable(deprecation=u'4.0', removal=u'5.0', alternative=u'Please use celery.app.backends.by_url')
def get_backend_cls(backend=None, loader=None, **kwargs):
return _backends.by_name(backend=backend, loader=loader, **kwargs)
| [
"@",
"deprecated",
".",
"Callable",
"(",
"deprecation",
"=",
"u'4.0'",
",",
"removal",
"=",
"u'5.0'",
",",
"alternative",
"=",
"u'Please use celery.app.backends.by_url'",
")",
"def",
"get_backend_cls",
"(",
"backend",
"=",
"None",
",",
"loader",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"return",
"_backends",
".",
"by_name",
"(",
"backend",
"=",
"backend",
",",
"loader",
"=",
"loader",
",",
"**",
"kwargs",
")"
] | get backend class by name/alias . | train | false |
39,935 | def scan_directory(project_tree, directory):
try:
return DirectoryListing(directory, tuple(project_tree.scandir(directory.path)), exists=True)
except (IOError, OSError) as e:
if (e.errno == errno.ENOENT):
return DirectoryListing(directory, tuple(), exists=False)
else:
raise e
| [
"def",
"scan_directory",
"(",
"project_tree",
",",
"directory",
")",
":",
"try",
":",
"return",
"DirectoryListing",
"(",
"directory",
",",
"tuple",
"(",
"project_tree",
".",
"scandir",
"(",
"directory",
".",
"path",
")",
")",
",",
"exists",
"=",
"True",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"e",
":",
"if",
"(",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
")",
":",
"return",
"DirectoryListing",
"(",
"directory",
",",
"tuple",
"(",
")",
",",
"exists",
"=",
"False",
")",
"else",
":",
"raise",
"e"
] | list stat objects directly below the given path . | train | false |
39,937 | def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='simplex', callback=None, options=None):
meth = method.lower()
if (options is None):
options = {}
if (meth == 'simplex'):
return _linprog_simplex(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds, callback=callback, **options)
else:
raise ValueError(('Unknown solver %s' % method))
| [
"def",
"linprog",
"(",
"c",
",",
"A_ub",
"=",
"None",
",",
"b_ub",
"=",
"None",
",",
"A_eq",
"=",
"None",
",",
"b_eq",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"method",
"=",
"'simplex'",
",",
"callback",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"meth",
"=",
"method",
".",
"lower",
"(",
")",
"if",
"(",
"options",
"is",
"None",
")",
":",
"options",
"=",
"{",
"}",
"if",
"(",
"meth",
"==",
"'simplex'",
")",
":",
"return",
"_linprog_simplex",
"(",
"c",
",",
"A_ub",
"=",
"A_ub",
",",
"b_ub",
"=",
"b_ub",
",",
"A_eq",
"=",
"A_eq",
",",
"b_eq",
"=",
"b_eq",
",",
"bounds",
"=",
"bounds",
",",
"callback",
"=",
"callback",
",",
"**",
"options",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'Unknown solver %s'",
"%",
"method",
")",
")"
] | minimize a linear objective function subject to linear equality and inequality constraints . | train | false |
39,938 | @pytest.fixture
def tutorial(english, settings):
import pytest_pootle
shutil.copytree(os.path.join(os.path.dirname(pytest_pootle.__file__), 'data', 'po', 'tutorial'), os.path.join(settings.POOTLE_TRANSLATION_DIRECTORY, 'tutorial'))
return _require_project('tutorial', 'Tutorial', english)
| [
"@",
"pytest",
".",
"fixture",
"def",
"tutorial",
"(",
"english",
",",
"settings",
")",
":",
"import",
"pytest_pootle",
"shutil",
".",
"copytree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"pytest_pootle",
".",
"__file__",
")",
",",
"'data'",
",",
"'po'",
",",
"'tutorial'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"POOTLE_TRANSLATION_DIRECTORY",
",",
"'tutorial'",
")",
")",
"return",
"_require_project",
"(",
"'tutorial'",
",",
"'Tutorial'",
",",
"english",
")"
] | require tutorial test project . | train | false |
39,939 | def _tessellate_sphere_surf(level, rad=1.0):
(rr, tris) = _tessellate_sphere(level)
npt = len(rr)
ntri = len(tris)
nn = rr.copy()
rr *= rad
s = dict(rr=rr, np=npt, tris=tris, use_tris=tris, ntri=ntri, nuse=np, nn=nn, inuse=np.ones(npt, int))
return s
| [
"def",
"_tessellate_sphere_surf",
"(",
"level",
",",
"rad",
"=",
"1.0",
")",
":",
"(",
"rr",
",",
"tris",
")",
"=",
"_tessellate_sphere",
"(",
"level",
")",
"npt",
"=",
"len",
"(",
"rr",
")",
"ntri",
"=",
"len",
"(",
"tris",
")",
"nn",
"=",
"rr",
".",
"copy",
"(",
")",
"rr",
"*=",
"rad",
"s",
"=",
"dict",
"(",
"rr",
"=",
"rr",
",",
"np",
"=",
"npt",
",",
"tris",
"=",
"tris",
",",
"use_tris",
"=",
"tris",
",",
"ntri",
"=",
"ntri",
",",
"nuse",
"=",
"np",
",",
"nn",
"=",
"nn",
",",
"inuse",
"=",
"np",
".",
"ones",
"(",
"npt",
",",
"int",
")",
")",
"return",
"s"
] | return a surface structure instead of the details . | train | false |
39,940 | def p_list_type(p):
p[0] = (TType.LIST, p[3])
| [
"def",
"p_list_type",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"TType",
".",
"LIST",
",",
"p",
"[",
"3",
"]",
")"
] | list_type : list < field_type > . | train | false |
39,941 | @receiver(post_save, sender=CourseTeam)
def team_post_save_callback(sender, instance, **kwargs):
changed_fields = instance.field_tracker.changed()
if (not kwargs['created']):
for field in changed_fields:
if (field not in instance.FIELD_BLACKLIST):
truncated_fields = truncate_fields(unicode(changed_fields[field]), unicode(getattr(instance, field)))
truncated_fields['team_id'] = instance.team_id
truncated_fields['field'] = field
emit_team_event('edx.team.changed', instance.course_id, truncated_fields)
| [
"@",
"receiver",
"(",
"post_save",
",",
"sender",
"=",
"CourseTeam",
")",
"def",
"team_post_save_callback",
"(",
"sender",
",",
"instance",
",",
"**",
"kwargs",
")",
":",
"changed_fields",
"=",
"instance",
".",
"field_tracker",
".",
"changed",
"(",
")",
"if",
"(",
"not",
"kwargs",
"[",
"'created'",
"]",
")",
":",
"for",
"field",
"in",
"changed_fields",
":",
"if",
"(",
"field",
"not",
"in",
"instance",
".",
"FIELD_BLACKLIST",
")",
":",
"truncated_fields",
"=",
"truncate_fields",
"(",
"unicode",
"(",
"changed_fields",
"[",
"field",
"]",
")",
",",
"unicode",
"(",
"getattr",
"(",
"instance",
",",
"field",
")",
")",
")",
"truncated_fields",
"[",
"'team_id'",
"]",
"=",
"instance",
".",
"team_id",
"truncated_fields",
"[",
"'field'",
"]",
"=",
"field",
"emit_team_event",
"(",
"'edx.team.changed'",
",",
"instance",
".",
"course_id",
",",
"truncated_fields",
")"
] | emits signal after the team is saved . | train | false |
39,942 | @handle_response_format
@treeio_login_required
def file_delete(request, file_id, response_format='html'):
file = get_object_or_404(File, pk=file_id)
if (not request.user.profile.has_permission(file, mode='w')):
return user_denied(request, message="You don't have access to this File")
if request.POST:
if ('delete' in request.POST):
if ('trash' in request.POST):
file.trash = True
file.save()
else:
file.delete()
return HttpResponseRedirect(reverse('document_index'))
elif ('cancel' in request.POST):
return HttpResponseRedirect(reverse('documents_file_view', args=[file.id]))
context = _get_default_context(request)
context.update({'file': file})
return render_to_response('documents/file_delete', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"file_delete",
"(",
"request",
",",
"file_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"file",
"=",
"get_object_or_404",
"(",
"File",
",",
"pk",
"=",
"file_id",
")",
"if",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"has_permission",
"(",
"file",
",",
"mode",
"=",
"'w'",
")",
")",
":",
"return",
"user_denied",
"(",
"request",
",",
"message",
"=",
"\"You don't have access to this File\"",
")",
"if",
"request",
".",
"POST",
":",
"if",
"(",
"'delete'",
"in",
"request",
".",
"POST",
")",
":",
"if",
"(",
"'trash'",
"in",
"request",
".",
"POST",
")",
":",
"file",
".",
"trash",
"=",
"True",
"file",
".",
"save",
"(",
")",
"else",
":",
"file",
".",
"delete",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'document_index'",
")",
")",
"elif",
"(",
"'cancel'",
"in",
"request",
".",
"POST",
")",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'documents_file_view'",
",",
"args",
"=",
"[",
"file",
".",
"id",
"]",
")",
")",
"context",
"=",
"_get_default_context",
"(",
"request",
")",
"context",
".",
"update",
"(",
"{",
"'file'",
":",
"file",
"}",
")",
"return",
"render_to_response",
"(",
"'documents/file_delete'",
",",
"context",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | file delete . | train | false |
39,943 | def path_to_local_directory_uri(relpath):
if isinstance(relpath, compat.text_type):
relpath = relpath.encode(u'utf-8')
return (u'local:directory:%s' % urllib.quote(relpath))
| [
"def",
"path_to_local_directory_uri",
"(",
"relpath",
")",
":",
"if",
"isinstance",
"(",
"relpath",
",",
"compat",
".",
"text_type",
")",
":",
"relpath",
"=",
"relpath",
".",
"encode",
"(",
"u'utf-8'",
")",
"return",
"(",
"u'local:directory:%s'",
"%",
"urllib",
".",
"quote",
"(",
"relpath",
")",
")"
] | convert path relative to :confval:local/media_dir to directory uri . | train | false |
39,945 | def group_show(context, data_dict):
return _group_or_org_show(context, data_dict)
| [
"def",
"group_show",
"(",
"context",
",",
"data_dict",
")",
":",
"return",
"_group_or_org_show",
"(",
"context",
",",
"data_dict",
")"
] | return the details of a group . | train | false |
39,947 | def stop_tuning(step):
if hasattr(step, 'tune'):
step.tune = False
elif hasattr(step, 'methods'):
step.methods = [stop_tuning(s) for s in step.methods]
return step
| [
"def",
"stop_tuning",
"(",
"step",
")",
":",
"if",
"hasattr",
"(",
"step",
",",
"'tune'",
")",
":",
"step",
".",
"tune",
"=",
"False",
"elif",
"hasattr",
"(",
"step",
",",
"'methods'",
")",
":",
"step",
".",
"methods",
"=",
"[",
"stop_tuning",
"(",
"s",
")",
"for",
"s",
"in",
"step",
".",
"methods",
"]",
"return",
"step"
] | stop tuning the current step method . | train | false |
39,948 | def rid():
return (struct.unpack('@Q', os.urandom(8))[0] & _WAMP_ID_MASK)
| [
"def",
"rid",
"(",
")",
":",
"return",
"(",
"struct",
".",
"unpack",
"(",
"'@Q'",
",",
"os",
".",
"urandom",
"(",
"8",
")",
")",
"[",
"0",
"]",
"&",
"_WAMP_ID_MASK",
")"
] | generate a new random integer id from range **[0 . | train | false |
39,949 | def clear_mappers():
mapperlib._CONFIGURE_MUTEX.acquire()
try:
while _mapper_registry:
try:
(mapper, b) = _mapper_registry.popitem()
mapper.dispose()
except KeyError:
pass
finally:
mapperlib._CONFIGURE_MUTEX.release()
| [
"def",
"clear_mappers",
"(",
")",
":",
"mapperlib",
".",
"_CONFIGURE_MUTEX",
".",
"acquire",
"(",
")",
"try",
":",
"while",
"_mapper_registry",
":",
"try",
":",
"(",
"mapper",
",",
"b",
")",
"=",
"_mapper_registry",
".",
"popitem",
"(",
")",
"mapper",
".",
"dispose",
"(",
")",
"except",
"KeyError",
":",
"pass",
"finally",
":",
"mapperlib",
".",
"_CONFIGURE_MUTEX",
".",
"release",
"(",
")"
] | remove all mappers from all classes . | train | false |
39,950 | def _statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip):
if isinstance(bw, string_types):
bw_func = getattr(smnp.bandwidths, ('bw_' + bw))
x_bw = bw_func(x)
y_bw = bw_func(y)
bw = [x_bw, y_bw]
elif np.isscalar(bw):
bw = [bw, bw]
if isinstance(x, pd.Series):
x = x.values
if isinstance(y, pd.Series):
y = y.values
kde = smnp.KDEMultivariate([x, y], 'cc', bw)
x_support = _kde_support(x, kde.bw[0], gridsize, cut, clip[0])
y_support = _kde_support(y, kde.bw[1], gridsize, cut, clip[1])
(xx, yy) = np.meshgrid(x_support, y_support)
z = kde.pdf([xx.ravel(), yy.ravel()]).reshape(xx.shape)
return (xx, yy, z)
| [
"def",
"_statsmodels_bivariate_kde",
"(",
"x",
",",
"y",
",",
"bw",
",",
"gridsize",
",",
"cut",
",",
"clip",
")",
":",
"if",
"isinstance",
"(",
"bw",
",",
"string_types",
")",
":",
"bw_func",
"=",
"getattr",
"(",
"smnp",
".",
"bandwidths",
",",
"(",
"'bw_'",
"+",
"bw",
")",
")",
"x_bw",
"=",
"bw_func",
"(",
"x",
")",
"y_bw",
"=",
"bw_func",
"(",
"y",
")",
"bw",
"=",
"[",
"x_bw",
",",
"y_bw",
"]",
"elif",
"np",
".",
"isscalar",
"(",
"bw",
")",
":",
"bw",
"=",
"[",
"bw",
",",
"bw",
"]",
"if",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Series",
")",
":",
"x",
"=",
"x",
".",
"values",
"if",
"isinstance",
"(",
"y",
",",
"pd",
".",
"Series",
")",
":",
"y",
"=",
"y",
".",
"values",
"kde",
"=",
"smnp",
".",
"KDEMultivariate",
"(",
"[",
"x",
",",
"y",
"]",
",",
"'cc'",
",",
"bw",
")",
"x_support",
"=",
"_kde_support",
"(",
"x",
",",
"kde",
".",
"bw",
"[",
"0",
"]",
",",
"gridsize",
",",
"cut",
",",
"clip",
"[",
"0",
"]",
")",
"y_support",
"=",
"_kde_support",
"(",
"y",
",",
"kde",
".",
"bw",
"[",
"1",
"]",
",",
"gridsize",
",",
"cut",
",",
"clip",
"[",
"1",
"]",
")",
"(",
"xx",
",",
"yy",
")",
"=",
"np",
".",
"meshgrid",
"(",
"x_support",
",",
"y_support",
")",
"z",
"=",
"kde",
".",
"pdf",
"(",
"[",
"xx",
".",
"ravel",
"(",
")",
",",
"yy",
".",
"ravel",
"(",
")",
"]",
")",
".",
"reshape",
"(",
"xx",
".",
"shape",
")",
"return",
"(",
"xx",
",",
"yy",
",",
"z",
")"
] | compute a bivariate kde using statsmodels . | train | false |
39,951 | def create_anonymous_user(sender, **kwargs):
User = get_user_model()
try:
lookup = {User.USERNAME_FIELD: guardian_settings.ANONYMOUS_USER_NAME}
User.objects.get(**lookup)
except User.DoesNotExist:
retrieve_anonymous_function = import_string(guardian_settings.GET_INIT_ANONYMOUS_USER)
user = retrieve_anonymous_function(User)
user.save()
| [
"def",
"create_anonymous_user",
"(",
"sender",
",",
"**",
"kwargs",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"try",
":",
"lookup",
"=",
"{",
"User",
".",
"USERNAME_FIELD",
":",
"guardian_settings",
".",
"ANONYMOUS_USER_NAME",
"}",
"User",
".",
"objects",
".",
"get",
"(",
"**",
"lookup",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"retrieve_anonymous_function",
"=",
"import_string",
"(",
"guardian_settings",
".",
"GET_INIT_ANONYMOUS_USER",
")",
"user",
"=",
"retrieve_anonymous_function",
"(",
"User",
")",
"user",
".",
"save",
"(",
")"
] | creates anonymous user instance with id and username from settings . | train | false |
39,952 | def create_replicated_mapping_file(map_f, num_replicates, sample_ids):
if (num_replicates < 1):
raise ValueError(('Must specify at least one sample replicate (was provided %d).' % num_replicates))
(map_data, header, comments) = parse_mapping_file(map_f)
rep_map_data = []
for row in map_data:
if (row[0] in sample_ids):
for rep_num in range(num_replicates):
rep_map_data.append(([('%s.%i' % (row[0], rep_num))] + row[1:]))
return format_mapping_file(header, rep_map_data, comments)
| [
"def",
"create_replicated_mapping_file",
"(",
"map_f",
",",
"num_replicates",
",",
"sample_ids",
")",
":",
"if",
"(",
"num_replicates",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Must specify at least one sample replicate (was provided %d).'",
"%",
"num_replicates",
")",
")",
"(",
"map_data",
",",
"header",
",",
"comments",
")",
"=",
"parse_mapping_file",
"(",
"map_f",
")",
"rep_map_data",
"=",
"[",
"]",
"for",
"row",
"in",
"map_data",
":",
"if",
"(",
"row",
"[",
"0",
"]",
"in",
"sample_ids",
")",
":",
"for",
"rep_num",
"in",
"range",
"(",
"num_replicates",
")",
":",
"rep_map_data",
".",
"append",
"(",
"(",
"[",
"(",
"'%s.%i'",
"%",
"(",
"row",
"[",
"0",
"]",
",",
"rep_num",
")",
")",
"]",
"+",
"row",
"[",
"1",
":",
"]",
")",
")",
"return",
"format_mapping_file",
"(",
"header",
",",
"rep_map_data",
",",
"comments",
")"
] | returns a formatted mapping file with replicated sample ids . | train | false |
39,953 | def median_absolute_deviation(x):
x = asarray(x)
median_x = median(x)
median_abs_deviation = median(abs((x - median_x)))
return (median_abs_deviation, median_x)
| [
"def",
"median_absolute_deviation",
"(",
"x",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"median_x",
"=",
"median",
"(",
"x",
")",
"median_abs_deviation",
"=",
"median",
"(",
"abs",
"(",
"(",
"x",
"-",
"median_x",
")",
")",
")",
"return",
"(",
"median_abs_deviation",
",",
"median_x",
")"
] | compute the median of the absolute deviations from the median . | train | false |
39,955 | def sync_ldap_users(connection, failed_users=None):
users = User.objects.filter(userprofile__creation_method=str(UserProfile.CreationMethod.EXTERNAL)).all()
for user in users:
_import_ldap_users(connection, user.username, failed_users=failed_users)
return users
| [
"def",
"sync_ldap_users",
"(",
"connection",
",",
"failed_users",
"=",
"None",
")",
":",
"users",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"userprofile__creation_method",
"=",
"str",
"(",
"UserProfile",
".",
"CreationMethod",
".",
"EXTERNAL",
")",
")",
".",
"all",
"(",
")",
"for",
"user",
"in",
"users",
":",
"_import_ldap_users",
"(",
"connection",
",",
"user",
".",
"username",
",",
"failed_users",
"=",
"failed_users",
")",
"return",
"users"
] | syncs ldap user information . | train | false |
39,956 | def test_defn():
cant_compile(u'(defn if* [] 1)')
cant_compile(u'(defn "hy" [] 1)')
cant_compile(u'(defn :hy [] 1)')
can_compile(u'(defn &hy [] 1)')
| [
"def",
"test_defn",
"(",
")",
":",
"cant_compile",
"(",
"u'(defn if* [] 1)'",
")",
"cant_compile",
"(",
"u'(defn \"hy\" [] 1)'",
")",
"cant_compile",
"(",
"u'(defn :hy [] 1)'",
")",
"can_compile",
"(",
"u'(defn &hy [] 1)'",
")"
] | ensure that defn works correctly in various corner cases . | train | false |
39,957 | def create_folder(name, location='\\'):
if (name in list_folders(location)):
return '{0} already exists'.format(name)
pythoncom.CoInitialize()
task_service = win32com.client.Dispatch('Schedule.Service')
task_service.Connect()
task_folder = task_service.GetFolder(location)
task_folder.CreateFolder(name)
if (name in list_folders(location)):
return True
else:
return False
| [
"def",
"create_folder",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"if",
"(",
"name",
"in",
"list_folders",
"(",
"location",
")",
")",
":",
"return",
"'{0} already exists'",
".",
"format",
"(",
"name",
")",
"pythoncom",
".",
"CoInitialize",
"(",
")",
"task_service",
"=",
"win32com",
".",
"client",
".",
"Dispatch",
"(",
"'Schedule.Service'",
")",
"task_service",
".",
"Connect",
"(",
")",
"task_folder",
"=",
"task_service",
".",
"GetFolder",
"(",
"location",
")",
"task_folder",
".",
"CreateFolder",
"(",
"name",
")",
"if",
"(",
"name",
"in",
"list_folders",
"(",
"location",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | create a new folder inside the one received as a param . | train | false |
39,958 | def pportTristate(state):
global ctrlReg
if (state == 0):
ctrlReg = (ctrlReg & (~ 16))
else:
ctrlReg = (ctrlReg | 16)
port.DlPortWritePortUchar(ctrlRegAdrs, ctrlReg)
| [
"def",
"pportTristate",
"(",
"state",
")",
":",
"global",
"ctrlReg",
"if",
"(",
"state",
"==",
"0",
")",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"&",
"(",
"~",
"16",
")",
")",
"else",
":",
"ctrlReg",
"=",
"(",
"ctrlReg",
"|",
"16",
")",
"port",
".",
"DlPortWritePortUchar",
"(",
"ctrlRegAdrs",
",",
"ctrlReg",
")"
] | toggle tristate output bit . | train | false |
39,959 | def force_unicode(s):
if (s is None):
return None
else:
return unicod(s)
| [
"def",
"force_unicode",
"(",
"s",
")",
":",
"if",
"(",
"s",
"is",
"None",
")",
":",
"return",
"None",
"else",
":",
"return",
"unicod",
"(",
"s",
")"
] | wrapper around djangos version . | train | false |
39,960 | def dynamicsymbols(names, level=0):
esses = symbols(names, cls=Function)
t = dynamicsymbols._t
if iterable(esses):
esses = [reduce(diff, ([t] * level), e(t)) for e in esses]
return esses
else:
return reduce(diff, ([t] * level), esses(t))
| [
"def",
"dynamicsymbols",
"(",
"names",
",",
"level",
"=",
"0",
")",
":",
"esses",
"=",
"symbols",
"(",
"names",
",",
"cls",
"=",
"Function",
")",
"t",
"=",
"dynamicsymbols",
".",
"_t",
"if",
"iterable",
"(",
"esses",
")",
":",
"esses",
"=",
"[",
"reduce",
"(",
"diff",
",",
"(",
"[",
"t",
"]",
"*",
"level",
")",
",",
"e",
"(",
"t",
")",
")",
"for",
"e",
"in",
"esses",
"]",
"return",
"esses",
"else",
":",
"return",
"reduce",
"(",
"diff",
",",
"(",
"[",
"t",
"]",
"*",
"level",
")",
",",
"esses",
"(",
"t",
")",
")"
] | uses symbols and function for functions of time . | train | false |
39,961 | def provide_fake_entries(group):
return _FAKE_ENTRIES.get(group, [])
| [
"def",
"provide_fake_entries",
"(",
"group",
")",
":",
"return",
"_FAKE_ENTRIES",
".",
"get",
"(",
"group",
",",
"[",
"]",
")"
] | give a set of fake entries for known groups . | train | false |
39,962 | @xfail_py3
@xfail(wxPython_fail, reason='PyInstaller does not support this wxPython version')
@importorskip('wx.lib.pubsub.core')
def test_wx_lib_pubsub_protocol_kwargs(pyi_builder):
pyi_builder.test_script('pyi_hooks/wx_lib_pubsub_setupkwargs.py')
| [
"@",
"xfail_py3",
"@",
"xfail",
"(",
"wxPython_fail",
",",
"reason",
"=",
"'PyInstaller does not support this wxPython version'",
")",
"@",
"importorskip",
"(",
"'wx.lib.pubsub.core'",
")",
"def",
"test_wx_lib_pubsub_protocol_kwargs",
"(",
"pyi_builder",
")",
":",
"pyi_builder",
".",
"test_script",
"(",
"'pyi_hooks/wx_lib_pubsub_setupkwargs.py'",
")"
] | functional test specific to version 3 of the pypubsub api . | train | false |
39,963 | def get_exc_from_name(name):
exc = None
try:
return rc_exc_cache[name]
except KeyError:
m = rc_exc_regex.match(name)
if m:
base = m.group(1)
rc_or_sig_name = m.group(2)
if (base == 'SignalException'):
try:
rc = (- int(rc_or_sig_name))
except ValueError:
rc = (- getattr(signal, rc_or_sig_name))
else:
rc = int(rc_or_sig_name)
exc = get_rc_exc(rc)
return exc
| [
"def",
"get_exc_from_name",
"(",
"name",
")",
":",
"exc",
"=",
"None",
"try",
":",
"return",
"rc_exc_cache",
"[",
"name",
"]",
"except",
"KeyError",
":",
"m",
"=",
"rc_exc_regex",
".",
"match",
"(",
"name",
")",
"if",
"m",
":",
"base",
"=",
"m",
".",
"group",
"(",
"1",
")",
"rc_or_sig_name",
"=",
"m",
".",
"group",
"(",
"2",
")",
"if",
"(",
"base",
"==",
"'SignalException'",
")",
":",
"try",
":",
"rc",
"=",
"(",
"-",
"int",
"(",
"rc_or_sig_name",
")",
")",
"except",
"ValueError",
":",
"rc",
"=",
"(",
"-",
"getattr",
"(",
"signal",
",",
"rc_or_sig_name",
")",
")",
"else",
":",
"rc",
"=",
"int",
"(",
"rc_or_sig_name",
")",
"exc",
"=",
"get_rc_exc",
"(",
"rc",
")",
"return",
"exc"
] | takes an exception name . | train | true |
39,964 | def set_sff_trimpoints(sff_dir, technical_lengths):
for (lib_id, sff_fp) in get_per_lib_sff_fps(sff_dir):
try:
readlength = technical_lengths[lib_id]
except KeyError:
continue
sff_data = parse_binary_sff(open(sff_fp), True)
(clipped_header, clipped_reads) = set_clip_qual_left(sff_data, readlength)
(fd, temp_fp) = mkstemp(dir=sff_dir)
close(fd)
with open(temp_fp, 'w') as f:
write_binary_sff(f, clipped_header, clipped_reads)
move(temp_fp, sff_fp)
| [
"def",
"set_sff_trimpoints",
"(",
"sff_dir",
",",
"technical_lengths",
")",
":",
"for",
"(",
"lib_id",
",",
"sff_fp",
")",
"in",
"get_per_lib_sff_fps",
"(",
"sff_dir",
")",
":",
"try",
":",
"readlength",
"=",
"technical_lengths",
"[",
"lib_id",
"]",
"except",
"KeyError",
":",
"continue",
"sff_data",
"=",
"parse_binary_sff",
"(",
"open",
"(",
"sff_fp",
")",
",",
"True",
")",
"(",
"clipped_header",
",",
"clipped_reads",
")",
"=",
"set_clip_qual_left",
"(",
"sff_data",
",",
"readlength",
")",
"(",
"fd",
",",
"temp_fp",
")",
"=",
"mkstemp",
"(",
"dir",
"=",
"sff_dir",
")",
"close",
"(",
"fd",
")",
"with",
"open",
"(",
"temp_fp",
",",
"'w'",
")",
"as",
"f",
":",
"write_binary_sff",
"(",
"f",
",",
"clipped_header",
",",
"clipped_reads",
")",
"move",
"(",
"temp_fp",
",",
"sff_fp",
")"
] | set trimpoints to end of technical read for all sff files in directory . | train | false |
39,965 | def _combine_similar_molecules(molecules_list):
new_guys_start_idx = 0
while (new_guys_start_idx < len(molecules_list)):
combined = ([False] * len(molecules_list))
new_guys = []
for j in xrange(new_guys_start_idx, len(molecules_list)):
for i in xrange(0, j):
if combined[i]:
continue
((g1, m1), (g2, m2)) = (molecules_list[i], molecules_list[j])
js = _jaccard_similarity(g1, g2)
if (js > JACCARD_THRESHOLD):
new_guys.append((g1.union(g2), m1.union(m2)))
(combined[i], combined[j]) = (True, True)
break
molecules_list = [molecule for (molecule, was_combined) in zip(molecules_list, combined) if (not was_combined)]
new_guys_start_idx = len(molecules_list)
molecules_list.extend(new_guys)
return molecules_list
| [
"def",
"_combine_similar_molecules",
"(",
"molecules_list",
")",
":",
"new_guys_start_idx",
"=",
"0",
"while",
"(",
"new_guys_start_idx",
"<",
"len",
"(",
"molecules_list",
")",
")",
":",
"combined",
"=",
"(",
"[",
"False",
"]",
"*",
"len",
"(",
"molecules_list",
")",
")",
"new_guys",
"=",
"[",
"]",
"for",
"j",
"in",
"xrange",
"(",
"new_guys_start_idx",
",",
"len",
"(",
"molecules_list",
")",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"j",
")",
":",
"if",
"combined",
"[",
"i",
"]",
":",
"continue",
"(",
"(",
"g1",
",",
"m1",
")",
",",
"(",
"g2",
",",
"m2",
")",
")",
"=",
"(",
"molecules_list",
"[",
"i",
"]",
",",
"molecules_list",
"[",
"j",
"]",
")",
"js",
"=",
"_jaccard_similarity",
"(",
"g1",
",",
"g2",
")",
"if",
"(",
"js",
">",
"JACCARD_THRESHOLD",
")",
":",
"new_guys",
".",
"append",
"(",
"(",
"g1",
".",
"union",
"(",
"g2",
")",
",",
"m1",
".",
"union",
"(",
"m2",
")",
")",
")",
"(",
"combined",
"[",
"i",
"]",
",",
"combined",
"[",
"j",
"]",
")",
"=",
"(",
"True",
",",
"True",
")",
"break",
"molecules_list",
"=",
"[",
"molecule",
"for",
"(",
"molecule",
",",
"was_combined",
")",
"in",
"zip",
"(",
"molecules_list",
",",
"combined",
")",
"if",
"(",
"not",
"was_combined",
")",
"]",
"new_guys_start_idx",
"=",
"len",
"(",
"molecules_list",
")",
"molecules_list",
".",
"extend",
"(",
"new_guys",
")",
"return",
"molecules_list"
] | using a greedy approach here for speed . | train | false |
39,966 | def _tryint(v):
try:
return int(v)
except:
return 0
| [
"def",
"_tryint",
"(",
"v",
")",
":",
"try",
":",
"return",
"int",
"(",
"v",
")",
"except",
":",
"return",
"0"
] | tries to convert v to an integer . | train | false |
39,967 | def getDictionaryString(dictionary):
output = cStringIO.StringIO()
keys = dictionary.keys()
keys.sort()
for key in keys:
addValueToOutput(0, key, output, dictionary[key])
return output.getvalue()
| [
"def",
"getDictionaryString",
"(",
"dictionary",
")",
":",
"output",
"=",
"cStringIO",
".",
"StringIO",
"(",
")",
"keys",
"=",
"dictionary",
".",
"keys",
"(",
")",
"keys",
".",
"sort",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"addValueToOutput",
"(",
"0",
",",
"key",
",",
"output",
",",
"dictionary",
"[",
"key",
"]",
")",
"return",
"output",
".",
"getvalue",
"(",
")"
] | get the dictionary string . | train | false |
39,968 | def getPythonContainers(meth):
containers = []
containers.append(meth.im_class)
moduleName = meth.im_class.__module__
while (moduleName is not None):
module = sys.modules.get(moduleName, None)
if (module is None):
module = __import__(moduleName)
containers.append(module)
moduleName = getattr(module, '__module__', None)
return containers
| [
"def",
"getPythonContainers",
"(",
"meth",
")",
":",
"containers",
"=",
"[",
"]",
"containers",
".",
"append",
"(",
"meth",
".",
"im_class",
")",
"moduleName",
"=",
"meth",
".",
"im_class",
".",
"__module__",
"while",
"(",
"moduleName",
"is",
"not",
"None",
")",
":",
"module",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"moduleName",
",",
"None",
")",
"if",
"(",
"module",
"is",
"None",
")",
":",
"module",
"=",
"__import__",
"(",
"moduleName",
")",
"containers",
".",
"append",
"(",
"module",
")",
"moduleName",
"=",
"getattr",
"(",
"module",
",",
"'__module__'",
",",
"None",
")",
"return",
"containers"
] | walk up the python tree from method meth . | train | false |
39,969 | def t_KEGG_Compound(testfiles):
for file in testfiles:
fh = open(os.path.join('KEGG', file))
print((('Testing Bio.KEGG.Compound on ' + file) + '\n\n'))
records = Compound.parse(fh)
for record in records:
print(record)
print('\n')
fh.close()
| [
"def",
"t_KEGG_Compound",
"(",
"testfiles",
")",
":",
"for",
"file",
"in",
"testfiles",
":",
"fh",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"'KEGG'",
",",
"file",
")",
")",
"print",
"(",
"(",
"(",
"'Testing Bio.KEGG.Compound on '",
"+",
"file",
")",
"+",
"'\\n\\n'",
")",
")",
"records",
"=",
"Compound",
".",
"parse",
"(",
"fh",
")",
"for",
"record",
"in",
"records",
":",
"print",
"(",
"record",
")",
"print",
"(",
"'\\n'",
")",
"fh",
".",
"close",
"(",
")"
] | tests bio . | train | false |
39,970 | def makelist(inlist, listchar='', stringify=False, escape=False, encoding=None):
if stringify:
inlist = list_stringify(inlist)
listdict = {'[': '[%s]', '(': '(%s)', '': '%s'}
outline = []
if (len(inlist) < 2):
listchar = (listchar or '[')
for item in inlist:
if (not isinstance(item, (list, tuple))):
if escape:
item = quote_escape(item)
outline.append(elem_quote(item, encoding=encoding))
else:
outline.append(makelist(item, (listchar or '['), stringify, escape, encoding))
return (listdict[listchar] % ', '.join(outline))
| [
"def",
"makelist",
"(",
"inlist",
",",
"listchar",
"=",
"''",
",",
"stringify",
"=",
"False",
",",
"escape",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"stringify",
":",
"inlist",
"=",
"list_stringify",
"(",
"inlist",
")",
"listdict",
"=",
"{",
"'['",
":",
"'[%s]'",
",",
"'('",
":",
"'(%s)'",
",",
"''",
":",
"'%s'",
"}",
"outline",
"=",
"[",
"]",
"if",
"(",
"len",
"(",
"inlist",
")",
"<",
"2",
")",
":",
"listchar",
"=",
"(",
"listchar",
"or",
"'['",
")",
"for",
"item",
"in",
"inlist",
":",
"if",
"(",
"not",
"isinstance",
"(",
"item",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
":",
"if",
"escape",
":",
"item",
"=",
"quote_escape",
"(",
"item",
")",
"outline",
".",
"append",
"(",
"elem_quote",
"(",
"item",
",",
"encoding",
"=",
"encoding",
")",
")",
"else",
":",
"outline",
".",
"append",
"(",
"makelist",
"(",
"item",
",",
"(",
"listchar",
"or",
"'['",
")",
",",
"stringify",
",",
"escape",
",",
"encoding",
")",
")",
"return",
"(",
"listdict",
"[",
"listchar",
"]",
"%",
"', '",
".",
"join",
"(",
"outline",
")",
")"
] | given a list - turn it into a string that represents that list . | train | false |
39,971 | def get_urls_proxy(output_pipe=sys.stderr):
try:
from django.conf import settings
except Exception as e:
output_pipe.write((('\n\nWarning, exception fetching KA Lite settings module:\n\n' + str(e)) + '\n\n'))
return
if (hasattr(settings, 'USER_FACING_PORT') and settings.USER_FACING_PORT and hasattr(settings, 'HTTP_PORT') and (not (settings.USER_FACING_PORT == settings.HTTP_PORT))):
output_pipe.write('\nKA Lite configured behind another server, primary addresses are:\n\n')
for addr in get_ip_addresses():
(yield 'http://{}:{}/'.format(addr, settings.USER_FACING_PORT))
| [
"def",
"get_urls_proxy",
"(",
"output_pipe",
"=",
"sys",
".",
"stderr",
")",
":",
"try",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"except",
"Exception",
"as",
"e",
":",
"output_pipe",
".",
"write",
"(",
"(",
"(",
"'\\n\\nWarning, exception fetching KA Lite settings module:\\n\\n'",
"+",
"str",
"(",
"e",
")",
")",
"+",
"'\\n\\n'",
")",
")",
"return",
"if",
"(",
"hasattr",
"(",
"settings",
",",
"'USER_FACING_PORT'",
")",
"and",
"settings",
".",
"USER_FACING_PORT",
"and",
"hasattr",
"(",
"settings",
",",
"'HTTP_PORT'",
")",
"and",
"(",
"not",
"(",
"settings",
".",
"USER_FACING_PORT",
"==",
"settings",
".",
"HTTP_PORT",
")",
")",
")",
":",
"output_pipe",
".",
"write",
"(",
"'\\nKA Lite configured behind another server, primary addresses are:\\n\\n'",
")",
"for",
"addr",
"in",
"get_ip_addresses",
"(",
")",
":",
"(",
"yield",
"'http://{}:{}/'",
".",
"format",
"(",
"addr",
",",
"settings",
".",
"USER_FACING_PORT",
")",
")"
] | get addresses of the server if were using settings . | train | false |
39,972 | def db_optimize(name, table=None, **connection_args):
ret = []
if (table is None):
tables = db_tables(name, **connection_args)
for table in tables:
log.info("Optimizing table '{0}' in db '{1}'..".format(name, table))
ret.append(__optimize_table(name, table, **connection_args))
else:
log.info("Optimizing table '{0}' in db '{1}'..".format(name, table))
ret = __optimize_table(name, table, **connection_args)
return ret
| [
"def",
"db_optimize",
"(",
"name",
",",
"table",
"=",
"None",
",",
"**",
"connection_args",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"(",
"table",
"is",
"None",
")",
":",
"tables",
"=",
"db_tables",
"(",
"name",
",",
"**",
"connection_args",
")",
"for",
"table",
"in",
"tables",
":",
"log",
".",
"info",
"(",
"\"Optimizing table '{0}' in db '{1}'..\"",
".",
"format",
"(",
"name",
",",
"table",
")",
")",
"ret",
".",
"append",
"(",
"__optimize_table",
"(",
"name",
",",
"table",
",",
"**",
"connection_args",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"Optimizing table '{0}' in db '{1}'..\"",
".",
"format",
"(",
"name",
",",
"table",
")",
")",
"ret",
"=",
"__optimize_table",
"(",
"name",
",",
"table",
",",
"**",
"connection_args",
")",
"return",
"ret"
] | optimizes the full database or just a given table cli example: . | train | true |
39,973 | def plugins_update():
for env in PluginGlobals.env_registry.values():
for service in env.services.copy():
if (service.__class__ not in _PLUGINS_CLASS):
service.deactivate()
import ckan.config.environment as environment
environment.update_config()
| [
"def",
"plugins_update",
"(",
")",
":",
"for",
"env",
"in",
"PluginGlobals",
".",
"env_registry",
".",
"values",
"(",
")",
":",
"for",
"service",
"in",
"env",
".",
"services",
".",
"copy",
"(",
")",
":",
"if",
"(",
"service",
".",
"__class__",
"not",
"in",
"_PLUGINS_CLASS",
")",
":",
"service",
".",
"deactivate",
"(",
")",
"import",
"ckan",
".",
"config",
".",
"environment",
"as",
"environment",
"environment",
".",
"update_config",
"(",
")"
] | this is run when plugins have been loaded or unloaded and allows us to run any specific code to ensure that the new plugin setting are correctly setup . | train | false |
39,974 | def is_leap(year):
x = math.fmod(year, 4)
y = math.fmod(year, 100)
z = math.fmod(year, 400)
return ((not x) and (y or (not z)))
| [
"def",
"is_leap",
"(",
"year",
")",
":",
"x",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"4",
")",
"y",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"100",
")",
"z",
"=",
"math",
".",
"fmod",
"(",
"year",
",",
"400",
")",
"return",
"(",
"(",
"not",
"x",
")",
"and",
"(",
"y",
"or",
"(",
"not",
"z",
")",
")",
")"
] | leap year or not in the gregorian calendar . | train | true |
39,975 | def iso8601_from_timestamp(timestamp, microsecond=False):
return isotime(datetime.datetime.utcfromtimestamp(timestamp), microsecond)
| [
"def",
"iso8601_from_timestamp",
"(",
"timestamp",
",",
"microsecond",
"=",
"False",
")",
":",
"return",
"isotime",
"(",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"timestamp",
")",
",",
"microsecond",
")"
] | returns a iso8601 formated date from timestamp . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.