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 |
|---|---|---|---|---|---|
55,343
|
def _is_astropy_source(path=None):
if (path is None):
path = os.path.join(os.path.dirname(__file__), os.pardir)
elif os.path.isfile(path):
path = os.path.dirname(path)
source_dir = os.path.abspath(path)
return os.path.exists(os.path.join(source_dir, '.astropy-root'))
|
[
"def",
"_is_astropy_source",
"(",
"path",
"=",
"None",
")",
":",
"if",
"(",
"path",
"is",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"os",
".",
"pardir",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"source_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"source_dir",
",",
"'.astropy-root'",
")",
")"
] |
returns whether the source for this module is directly in an astropy source distribution or checkout .
|
train
| false
|
55,344
|
def _ValidateClientId(client_id):
if (not isinstance(client_id, basestring)):
raise InvalidChannelClientIdError(('"%s" is not a string.' % client_id))
if isinstance(client_id, unicode):
client_id = client_id.encode('utf-8')
if (len(client_id) > MAXIMUM_CLIENT_ID_LENGTH):
msg = ('Client id length %d is greater than max length %d' % (len(client_id), MAXIMUM_CLIENT_ID_LENGTH))
raise InvalidChannelClientIdError(msg)
return client_id
|
[
"def",
"_ValidateClientId",
"(",
"client_id",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"client_id",
",",
"basestring",
")",
")",
":",
"raise",
"InvalidChannelClientIdError",
"(",
"(",
"'\"%s\" is not a string.'",
"%",
"client_id",
")",
")",
"if",
"isinstance",
"(",
"client_id",
",",
"unicode",
")",
":",
"client_id",
"=",
"client_id",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"(",
"len",
"(",
"client_id",
")",
">",
"MAXIMUM_CLIENT_ID_LENGTH",
")",
":",
"msg",
"=",
"(",
"'Client id length %d is greater than max length %d'",
"%",
"(",
"len",
"(",
"client_id",
")",
",",
"MAXIMUM_CLIENT_ID_LENGTH",
")",
")",
"raise",
"InvalidChannelClientIdError",
"(",
"msg",
")",
"return",
"client_id"
] |
validates a client id .
|
train
| false
|
55,345
|
def make_fna(sff_fp, output_fp, use_sfftools=False, no_trim=False):
if use_sfftools:
_fail_on_gzipped_sff(sff_fp)
check_sffinfo()
if no_trim:
_check_call(['sffinfo', '-notrim', '-s', sff_fp], stdout=open(output_fp, 'w'))
else:
_check_call(['sffinfo', '-s', sff_fp], stdout=open(output_fp, 'w'))
else:
try:
format_binary_sff_as_fna(qiime_open(sff_fp, 'rb'), open(output_fp, 'w'))
except:
raise IOError(('Could not parse SFF %s' % sff_fp))
|
[
"def",
"make_fna",
"(",
"sff_fp",
",",
"output_fp",
",",
"use_sfftools",
"=",
"False",
",",
"no_trim",
"=",
"False",
")",
":",
"if",
"use_sfftools",
":",
"_fail_on_gzipped_sff",
"(",
"sff_fp",
")",
"check_sffinfo",
"(",
")",
"if",
"no_trim",
":",
"_check_call",
"(",
"[",
"'sffinfo'",
",",
"'-notrim'",
",",
"'-s'",
",",
"sff_fp",
"]",
",",
"stdout",
"=",
"open",
"(",
"output_fp",
",",
"'w'",
")",
")",
"else",
":",
"_check_call",
"(",
"[",
"'sffinfo'",
",",
"'-s'",
",",
"sff_fp",
"]",
",",
"stdout",
"=",
"open",
"(",
"output_fp",
",",
"'w'",
")",
")",
"else",
":",
"try",
":",
"format_binary_sff_as_fna",
"(",
"qiime_open",
"(",
"sff_fp",
",",
"'rb'",
")",
",",
"open",
"(",
"output_fp",
",",
"'w'",
")",
")",
"except",
":",
"raise",
"IOError",
"(",
"(",
"'Could not parse SFF %s'",
"%",
"sff_fp",
")",
")"
] |
makes fna file from sff file .
|
train
| false
|
55,346
|
def perm2tensor(t, g, canon_bp=False):
if (not isinstance(t, TensExpr)):
return t
new_tids = get_tids(t).perm2tensor(g, canon_bp)
coeff = get_coeff(t)
if (g[(-1)] != (len(g) - 1)):
coeff = (- coeff)
res = TensMul.from_TIDS(coeff, new_tids, is_canon_bp=canon_bp)
return res
|
[
"def",
"perm2tensor",
"(",
"t",
",",
"g",
",",
"canon_bp",
"=",
"False",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"t",
",",
"TensExpr",
")",
")",
":",
"return",
"t",
"new_tids",
"=",
"get_tids",
"(",
"t",
")",
".",
"perm2tensor",
"(",
"g",
",",
"canon_bp",
")",
"coeff",
"=",
"get_coeff",
"(",
"t",
")",
"if",
"(",
"g",
"[",
"(",
"-",
"1",
")",
"]",
"!=",
"(",
"len",
"(",
"g",
")",
"-",
"1",
")",
")",
":",
"coeff",
"=",
"(",
"-",
"coeff",
")",
"res",
"=",
"TensMul",
".",
"from_TIDS",
"(",
"coeff",
",",
"new_tids",
",",
"is_canon_bp",
"=",
"canon_bp",
")",
"return",
"res"
] |
returns the tensor corresponding to the permutation g for further details .
|
train
| false
|
55,347
|
def get_build_results(build):
r_url = get_results_raw_url(build)
if (not r_url):
return
return convert_json_to_df(r_url)
|
[
"def",
"get_build_results",
"(",
"build",
")",
":",
"r_url",
"=",
"get_results_raw_url",
"(",
"build",
")",
"if",
"(",
"not",
"r_url",
")",
":",
"return",
"return",
"convert_json_to_df",
"(",
"r_url",
")"
] |
returns a df with the results of the vbench job associated with the travis build .
|
train
| false
|
55,348
|
def get_hash(f):
import hashlib
m = hashlib.md5()
m.update(f)
return m.hexdigest()
|
[
"def",
"get_hash",
"(",
"f",
")",
":",
"import",
"hashlib",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"f",
")",
"return",
"m",
".",
"hexdigest",
"(",
")"
] |
gets hexadmecimal md5 hash of a string .
|
train
| false
|
55,349
|
def _parse_output(output, template):
ret = {}
index = 0
if (not (output and template)):
return ret
if ('translate' in template):
ret = _translate_output(output)
else:
output_list = output.strip().replace('\n', '').split(' ')
if (sum(template.values()) != len(output_list)):
raise ipmiexcept.IPMIException(_('ipmitool output length mismatch'))
for item in template.items():
index_end = (index + item[1])
update_value = output_list[index:index_end]
ret[item[0]] = update_value
index = index_end
return ret
|
[
"def",
"_parse_output",
"(",
"output",
",",
"template",
")",
":",
"ret",
"=",
"{",
"}",
"index",
"=",
"0",
"if",
"(",
"not",
"(",
"output",
"and",
"template",
")",
")",
":",
"return",
"ret",
"if",
"(",
"'translate'",
"in",
"template",
")",
":",
"ret",
"=",
"_translate_output",
"(",
"output",
")",
"else",
":",
"output_list",
"=",
"output",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"split",
"(",
"' '",
")",
"if",
"(",
"sum",
"(",
"template",
".",
"values",
"(",
")",
")",
"!=",
"len",
"(",
"output_list",
")",
")",
":",
"raise",
"ipmiexcept",
".",
"IPMIException",
"(",
"_",
"(",
"'ipmitool output length mismatch'",
")",
")",
"for",
"item",
"in",
"template",
".",
"items",
"(",
")",
":",
"index_end",
"=",
"(",
"index",
"+",
"item",
"[",
"1",
"]",
")",
"update_value",
"=",
"output_list",
"[",
"index",
":",
"index_end",
"]",
"ret",
"[",
"item",
"[",
"0",
"]",
"]",
"=",
"update_value",
"index",
"=",
"index_end",
"return",
"ret"
] |
parse the return value of ipmi command into dict .
|
train
| false
|
55,350
|
def timestamp(x):
if (x.tzinfo is None):
x = x.replace(tzinfo=utc)
if hasattr(x, 'timestamp'):
return x.timestamp()
else:
return (x - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
|
[
"def",
"timestamp",
"(",
"x",
")",
":",
"if",
"(",
"x",
".",
"tzinfo",
"is",
"None",
")",
":",
"x",
"=",
"x",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
"if",
"hasattr",
"(",
"x",
",",
"'timestamp'",
")",
":",
"return",
"x",
".",
"timestamp",
"(",
")",
"else",
":",
"return",
"(",
"x",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"utc",
")",
")",
".",
"total_seconds",
"(",
")"
] |
get a timestamp from a date in python 3 and python 2 .
|
train
| true
|
55,351
|
def get_latest_repository_metadata(app, decoded_repository_id, downloadable=False):
sa_session = app.model.context.current
repository = sa_session.query(app.model.Repository).get(decoded_repository_id)
repo = hg_util.get_repo_for_repository(app, repository=repository, repo_path=None, create=False)
if downloadable:
changeset_revision = get_latest_downloadable_changeset_revision(app, repository, repo)
else:
changeset_revision = get_latest_changeset_revision(app, repository, repo)
return get_repository_metadata_by_changeset_revision(app, app.security.encode_id(repository.id), changeset_revision)
|
[
"def",
"get_latest_repository_metadata",
"(",
"app",
",",
"decoded_repository_id",
",",
"downloadable",
"=",
"False",
")",
":",
"sa_session",
"=",
"app",
".",
"model",
".",
"context",
".",
"current",
"repository",
"=",
"sa_session",
".",
"query",
"(",
"app",
".",
"model",
".",
"Repository",
")",
".",
"get",
"(",
"decoded_repository_id",
")",
"repo",
"=",
"hg_util",
".",
"get_repo_for_repository",
"(",
"app",
",",
"repository",
"=",
"repository",
",",
"repo_path",
"=",
"None",
",",
"create",
"=",
"False",
")",
"if",
"downloadable",
":",
"changeset_revision",
"=",
"get_latest_downloadable_changeset_revision",
"(",
"app",
",",
"repository",
",",
"repo",
")",
"else",
":",
"changeset_revision",
"=",
"get_latest_changeset_revision",
"(",
"app",
",",
"repository",
",",
"repo",
")",
"return",
"get_repository_metadata_by_changeset_revision",
"(",
"app",
",",
"app",
".",
"security",
".",
"encode_id",
"(",
"repository",
".",
"id",
")",
",",
"changeset_revision",
")"
] |
get last metadata defined for a specified repository from the database .
|
train
| false
|
55,353
|
@gen.engine
def ListRecursively(store, pattern, callback):
results = (yield gen.Task(ListAllKeys, store, prefix=PrefixFromPattern(pattern)))
callback(results)
|
[
"@",
"gen",
".",
"engine",
"def",
"ListRecursively",
"(",
"store",
",",
"pattern",
",",
"callback",
")",
":",
"results",
"=",
"(",
"yield",
"gen",
".",
"Task",
"(",
"ListAllKeys",
",",
"store",
",",
"prefix",
"=",
"PrefixFromPattern",
"(",
"pattern",
")",
")",
")",
"callback",
"(",
"results",
")"
] |
recursively list all files matching pattern .
|
train
| false
|
55,354
|
def _extract_doc_comment(content, line, column, markers):
if (markers[1] == ''):
return _extract_doc_comment_simple(content, line, column, markers)
elif (markers[1] == markers[2]):
return _extract_doc_comment_continuous(content, line, column, markers)
else:
return _extract_doc_comment_standard(content, line, column, markers)
|
[
"def",
"_extract_doc_comment",
"(",
"content",
",",
"line",
",",
"column",
",",
"markers",
")",
":",
"if",
"(",
"markers",
"[",
"1",
"]",
"==",
"''",
")",
":",
"return",
"_extract_doc_comment_simple",
"(",
"content",
",",
"line",
",",
"column",
",",
"markers",
")",
"elif",
"(",
"markers",
"[",
"1",
"]",
"==",
"markers",
"[",
"2",
"]",
")",
":",
"return",
"_extract_doc_comment_continuous",
"(",
"content",
",",
"line",
",",
"column",
",",
"markers",
")",
"else",
":",
"return",
"_extract_doc_comment_standard",
"(",
"content",
",",
"line",
",",
"column",
",",
"markers",
")"
] |
delegates depending on the given markers to the right extraction method .
|
train
| false
|
55,355
|
def parseSdr(s):
assert isinstance(s, basestring)
sdr = [int(c) for c in s if (c in ('0', '1'))]
if (len(sdr) != len(s)):
raise ValueError("The provided string %s is malformed. The string should have only 0's and 1's.")
return sdr
|
[
"def",
"parseSdr",
"(",
"s",
")",
":",
"assert",
"isinstance",
"(",
"s",
",",
"basestring",
")",
"sdr",
"=",
"[",
"int",
"(",
"c",
")",
"for",
"c",
"in",
"s",
"if",
"(",
"c",
"in",
"(",
"'0'",
",",
"'1'",
")",
")",
"]",
"if",
"(",
"len",
"(",
"sdr",
")",
"!=",
"len",
"(",
"s",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"The provided string %s is malformed. The string should have only 0's and 1's.\"",
")",
"return",
"sdr"
] |
parses a string containing only 0s and 1s and return a python list object .
|
train
| true
|
55,357
|
def floating_ip_create(kwargs, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The floating_ip_create action must be called with -f or --function')
if ('pool' not in kwargs):
log.error('pool is required')
return False
conn = get_conn()
return conn.floating_ip_create(kwargs['pool'])
|
[
"def",
"floating_ip_create",
"(",
"kwargs",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The floating_ip_create action must be called with -f or --function'",
")",
"if",
"(",
"'pool'",
"not",
"in",
"kwargs",
")",
":",
"log",
".",
"error",
"(",
"'pool is required'",
")",
"return",
"False",
"conn",
"=",
"get_conn",
"(",
")",
"return",
"conn",
".",
"floating_ip_create",
"(",
"kwargs",
"[",
"'pool'",
"]",
")"
] |
allocate a floating ip .
|
train
| true
|
55,358
|
def top_contributors_l10n(start=None, end=None, locale=None, product=None, count=10, page=1):
query = RevisionMetricsMappingType.search().facet('creator_id', filtered=True, size=BIG_NUMBER)
if (locale is None):
query = query.filter((~ F(locale=settings.WIKI_DEFAULT_LANGUAGE)))
query = _apply_filters(query, start, end, locale, product)
return _get_creator_counts(query, count, page)
|
[
"def",
"top_contributors_l10n",
"(",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"locale",
"=",
"None",
",",
"product",
"=",
"None",
",",
"count",
"=",
"10",
",",
"page",
"=",
"1",
")",
":",
"query",
"=",
"RevisionMetricsMappingType",
".",
"search",
"(",
")",
".",
"facet",
"(",
"'creator_id'",
",",
"filtered",
"=",
"True",
",",
"size",
"=",
"BIG_NUMBER",
")",
"if",
"(",
"locale",
"is",
"None",
")",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"(",
"~",
"F",
"(",
"locale",
"=",
"settings",
".",
"WIKI_DEFAULT_LANGUAGE",
")",
")",
")",
"query",
"=",
"_apply_filters",
"(",
"query",
",",
"start",
",",
"end",
",",
"locale",
",",
"product",
")",
"return",
"_get_creator_counts",
"(",
"query",
",",
"count",
",",
"page",
")"
] |
get the top l10n contributors for the kb .
|
train
| false
|
55,359
|
@login_required
@ensure_csrf_cookie
def assets_handler(request, course_key_string=None, asset_key_string=None):
course_key = CourseKey.from_string(course_key_string)
if (not has_course_author_access(request.user, course_key)):
raise PermissionDenied()
response_format = (request.GET.get('format') or request.POST.get('format') or 'html')
if ((response_format == 'json') or ('application/json' in request.META.get('HTTP_ACCEPT', 'application/json'))):
if (request.method == 'GET'):
return _assets_json(request, course_key)
else:
asset_key = (AssetKey.from_string(asset_key_string) if asset_key_string else None)
return _update_asset(request, course_key, asset_key)
elif (request.method == 'GET'):
return _asset_index(request, course_key)
else:
return HttpResponseNotFound()
|
[
"@",
"login_required",
"@",
"ensure_csrf_cookie",
"def",
"assets_handler",
"(",
"request",
",",
"course_key_string",
"=",
"None",
",",
"asset_key_string",
"=",
"None",
")",
":",
"course_key",
"=",
"CourseKey",
".",
"from_string",
"(",
"course_key_string",
")",
"if",
"(",
"not",
"has_course_author_access",
"(",
"request",
".",
"user",
",",
"course_key",
")",
")",
":",
"raise",
"PermissionDenied",
"(",
")",
"response_format",
"=",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'format'",
")",
"or",
"request",
".",
"POST",
".",
"get",
"(",
"'format'",
")",
"or",
"'html'",
")",
"if",
"(",
"(",
"response_format",
"==",
"'json'",
")",
"or",
"(",
"'application/json'",
"in",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT'",
",",
"'application/json'",
")",
")",
")",
":",
"if",
"(",
"request",
".",
"method",
"==",
"'GET'",
")",
":",
"return",
"_assets_json",
"(",
"request",
",",
"course_key",
")",
"else",
":",
"asset_key",
"=",
"(",
"AssetKey",
".",
"from_string",
"(",
"asset_key_string",
")",
"if",
"asset_key_string",
"else",
"None",
")",
"return",
"_update_asset",
"(",
"request",
",",
"course_key",
",",
"asset_key",
")",
"elif",
"(",
"request",
".",
"method",
"==",
"'GET'",
")",
":",
"return",
"_asset_index",
"(",
"request",
",",
"course_key",
")",
"else",
":",
"return",
"HttpResponseNotFound",
"(",
")"
] |
the restful handler for assets .
|
train
| false
|
55,360
|
def clamav(registry, xml_parent, data):
clamav = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.clamav.ClamAvRecorder')
clamav.set('plugin', 'clamav')
mappings = [('includes', 'includes', ''), ('excludes', 'excludes', '')]
helpers.convert_mapping_to_xml(clamav, data, mappings, fail_required=True)
|
[
"def",
"clamav",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"clamav",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'org.jenkinsci.plugins.clamav.ClamAvRecorder'",
")",
"clamav",
".",
"set",
"(",
"'plugin'",
",",
"'clamav'",
")",
"mappings",
"=",
"[",
"(",
"'includes'",
",",
"'includes'",
",",
"''",
")",
",",
"(",
"'excludes'",
",",
"'excludes'",
",",
"''",
")",
"]",
"helpers",
".",
"convert_mapping_to_xml",
"(",
"clamav",
",",
"data",
",",
"mappings",
",",
"fail_required",
"=",
"True",
")"
] |
yaml: clamav check files with clamav .
|
train
| false
|
55,361
|
def tree_support(master, subsampled_tree):
master_tipnames = set(master.getTipNames())
subsampled_tree_trimmed = copy.deepcopy(subsampled_tree)
def delete_test(node):
if (not node.isTip()):
return False
else:
return (node.Name not in master_tipnames)
subsampled_tree_trimmed.removeDeleted(delete_test)
subsampled_tree_trimmed.prune()
subsampled_tree_nodes_names = []
for node in subsampled_tree_trimmed.iterNontips(include_self=True):
subsampled_tree_nodes_names.append(node.getTipNames())
subsampled_tree_nodes_names = map(set, subsampled_tree_nodes_names)
for master_node in master.iterNontips(include_self=True):
if (set(master_node.getTipNames()) in subsampled_tree_nodes_names):
try:
master_node.bootstrap_support += 1
except AttributeError:
master_node.bootstrap_support = 1
|
[
"def",
"tree_support",
"(",
"master",
",",
"subsampled_tree",
")",
":",
"master_tipnames",
"=",
"set",
"(",
"master",
".",
"getTipNames",
"(",
")",
")",
"subsampled_tree_trimmed",
"=",
"copy",
".",
"deepcopy",
"(",
"subsampled_tree",
")",
"def",
"delete_test",
"(",
"node",
")",
":",
"if",
"(",
"not",
"node",
".",
"isTip",
"(",
")",
")",
":",
"return",
"False",
"else",
":",
"return",
"(",
"node",
".",
"Name",
"not",
"in",
"master_tipnames",
")",
"subsampled_tree_trimmed",
".",
"removeDeleted",
"(",
"delete_test",
")",
"subsampled_tree_trimmed",
".",
"prune",
"(",
")",
"subsampled_tree_nodes_names",
"=",
"[",
"]",
"for",
"node",
"in",
"subsampled_tree_trimmed",
".",
"iterNontips",
"(",
"include_self",
"=",
"True",
")",
":",
"subsampled_tree_nodes_names",
".",
"append",
"(",
"node",
".",
"getTipNames",
"(",
")",
")",
"subsampled_tree_nodes_names",
"=",
"map",
"(",
"set",
",",
"subsampled_tree_nodes_names",
")",
"for",
"master_node",
"in",
"master",
".",
"iterNontips",
"(",
"include_self",
"=",
"True",
")",
":",
"if",
"(",
"set",
"(",
"master_node",
".",
"getTipNames",
"(",
")",
")",
"in",
"subsampled_tree_nodes_names",
")",
":",
"try",
":",
"master_node",
".",
"bootstrap_support",
"+=",
"1",
"except",
"AttributeError",
":",
"master_node",
".",
"bootstrap_support",
"=",
"1"
] |
compares master tree to subsampled_tree .
|
train
| false
|
55,363
|
def dlcs_api_request(path, params='', user='', passwd='', throttle=True):
if throttle:
Waiter()
if params:
url = ('%s/%s?%s' % (DLCS_API, path, urllib.urlencode(dict0(params))))
else:
url = ('%s/%s' % (DLCS_API, path))
if DEBUG:
print >>sys.stderr, ('dlcs_api_request: %s' % url)
try:
return http_auth_request(url, DLCS_API_HOST, user, passwd, USER_AGENT)
except DefaultErrorHandler as e:
print >>sys.stderr, ('%s' % e)
|
[
"def",
"dlcs_api_request",
"(",
"path",
",",
"params",
"=",
"''",
",",
"user",
"=",
"''",
",",
"passwd",
"=",
"''",
",",
"throttle",
"=",
"True",
")",
":",
"if",
"throttle",
":",
"Waiter",
"(",
")",
"if",
"params",
":",
"url",
"=",
"(",
"'%s/%s?%s'",
"%",
"(",
"DLCS_API",
",",
"path",
",",
"urllib",
".",
"urlencode",
"(",
"dict0",
"(",
"params",
")",
")",
")",
")",
"else",
":",
"url",
"=",
"(",
"'%s/%s'",
"%",
"(",
"DLCS_API",
",",
"path",
")",
")",
"if",
"DEBUG",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"(",
"'dlcs_api_request: %s'",
"%",
"url",
")",
"try",
":",
"return",
"http_auth_request",
"(",
"url",
",",
"DLCS_API_HOST",
",",
"user",
",",
"passwd",
",",
"USER_AGENT",
")",
"except",
"DefaultErrorHandler",
"as",
"e",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"(",
"'%s'",
"%",
"e",
")"
] |
retrieve/query a path within the del .
|
train
| false
|
55,364
|
def conserve_mpmath_dps(func):
import functools
import mpmath
def func_wrapper(*args, **kwargs):
dps = mpmath.mp.dps
try:
return func(*args, **kwargs)
finally:
mpmath.mp.dps = dps
func_wrapper = functools.update_wrapper(func_wrapper, func)
return func_wrapper
|
[
"def",
"conserve_mpmath_dps",
"(",
"func",
")",
":",
"import",
"functools",
"import",
"mpmath",
"def",
"func_wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"dps",
"=",
"mpmath",
".",
"mp",
".",
"dps",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"finally",
":",
"mpmath",
".",
"mp",
".",
"dps",
"=",
"dps",
"func_wrapper",
"=",
"functools",
".",
"update_wrapper",
"(",
"func_wrapper",
",",
"func",
")",
"return",
"func_wrapper"
] |
after the function finishes .
|
train
| false
|
55,365
|
def pathMatchPatterns(path, repos):
for repo in repos:
if fnmatch(path, repo):
return True
return False
|
[
"def",
"pathMatchPatterns",
"(",
"path",
",",
"repos",
")",
":",
"for",
"repo",
"in",
"repos",
":",
"if",
"fnmatch",
"(",
"path",
",",
"repo",
")",
":",
"return",
"True",
"return",
"False"
] |
check existence of given path against list of path patterns the pattern definition is the as fnmatch .
|
train
| false
|
55,366
|
@domain_constructor(loss_target=(-2))
def distractor():
x = hp.uniform('x', (-15), 15)
f1 = old_div(1.0, (1.0 + scope.exp((- x))))
f2 = (2 * scope.exp((- ((x + 10) ** 2))))
return {'loss': ((- f1) - f2), 'status': base.STATUS_OK}
|
[
"@",
"domain_constructor",
"(",
"loss_target",
"=",
"(",
"-",
"2",
")",
")",
"def",
"distractor",
"(",
")",
":",
"x",
"=",
"hp",
".",
"uniform",
"(",
"'x'",
",",
"(",
"-",
"15",
")",
",",
"15",
")",
"f1",
"=",
"old_div",
"(",
"1.0",
",",
"(",
"1.0",
"+",
"scope",
".",
"exp",
"(",
"(",
"-",
"x",
")",
")",
")",
")",
"f2",
"=",
"(",
"2",
"*",
"scope",
".",
"exp",
"(",
"(",
"-",
"(",
"(",
"x",
"+",
"10",
")",
"**",
"2",
")",
")",
")",
")",
"return",
"{",
"'loss'",
":",
"(",
"(",
"-",
"f1",
")",
"-",
"f2",
")",
",",
"'status'",
":",
"base",
".",
"STATUS_OK",
"}"
] |
this is a nasty function: it has a max in a spike near -10 .
|
train
| false
|
55,369
|
def get_c_init(r, name, sub):
pre = ('\n py_%(name)s = Py_None;\n {Py_XINCREF(py_%(name)s);}\n ' % locals())
return (pre + r.type.c_init(name, sub))
|
[
"def",
"get_c_init",
"(",
"r",
",",
"name",
",",
"sub",
")",
":",
"pre",
"=",
"(",
"'\\n py_%(name)s = Py_None;\\n {Py_XINCREF(py_%(name)s);}\\n '",
"%",
"locals",
"(",
")",
")",
"return",
"(",
"pre",
"+",
"r",
".",
"type",
".",
"c_init",
"(",
"name",
",",
"sub",
")",
")"
] |
wrapper around c_init that initializes py_name to py_none .
|
train
| false
|
55,372
|
def get_messages(request):
return getattr(request, '_messages', [])
|
[
"def",
"get_messages",
"(",
"request",
")",
":",
"return",
"getattr",
"(",
"request",
",",
"'_messages'",
",",
"[",
"]",
")"
] |
returns the message storage on the request if it exists .
|
train
| false
|
55,373
|
def configure_paramiko_logging():
l = logging.getLogger('paramiko')
l.setLevel(logging.DEBUG)
static.create_sc_config_dirs()
lh = logging.handlers.RotatingFileHandler(static.SSH_DEBUG_FILE, maxBytes=1048576, backupCount=2)
lh.setLevel(logging.DEBUG)
format = (('PID: %s ' % str(static.PID)) + '%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d %(name)s: %(message)s')
date_format = '%Y%m%d-%H:%M:%S'
lh.setFormatter(logging.Formatter(format, date_format))
l.addHandler(lh)
|
[
"def",
"configure_paramiko_logging",
"(",
")",
":",
"l",
"=",
"logging",
".",
"getLogger",
"(",
"'paramiko'",
")",
"l",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"static",
".",
"create_sc_config_dirs",
"(",
")",
"lh",
"=",
"logging",
".",
"handlers",
".",
"RotatingFileHandler",
"(",
"static",
".",
"SSH_DEBUG_FILE",
",",
"maxBytes",
"=",
"1048576",
",",
"backupCount",
"=",
"2",
")",
"lh",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"format",
"=",
"(",
"(",
"'PID: %s '",
"%",
"str",
"(",
"static",
".",
"PID",
")",
")",
"+",
"'%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d %(name)s: %(message)s'",
")",
"date_format",
"=",
"'%Y%m%d-%H:%M:%S'",
"lh",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"format",
",",
"date_format",
")",
")",
"l",
".",
"addHandler",
"(",
"lh",
")"
] |
configure ssh to log to a file for debug .
|
train
| false
|
55,374
|
def check_non_negative(X, whom):
X = (X.data if sp.issparse(X) else X)
if (X < 0).any():
raise ValueError(('Negative values in data passed to %s' % whom))
|
[
"def",
"check_non_negative",
"(",
"X",
",",
"whom",
")",
":",
"X",
"=",
"(",
"X",
".",
"data",
"if",
"sp",
".",
"issparse",
"(",
"X",
")",
"else",
"X",
")",
"if",
"(",
"X",
"<",
"0",
")",
".",
"any",
"(",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Negative values in data passed to %s'",
"%",
"whom",
")",
")"
] |
check if there is any negative value in an array .
|
train
| false
|
55,376
|
def setvariable(cursor, mysqlvar, value):
query = ('SET GLOBAL %s = ' % mysql_quote_identifier(mysqlvar, 'vars'))
try:
cursor.execute((query + '%s'), (value,))
cursor.fetchall()
result = True
except Exception:
e = get_exception()
result = str(e)
return result
|
[
"def",
"setvariable",
"(",
"cursor",
",",
"mysqlvar",
",",
"value",
")",
":",
"query",
"=",
"(",
"'SET GLOBAL %s = '",
"%",
"mysql_quote_identifier",
"(",
"mysqlvar",
",",
"'vars'",
")",
")",
"try",
":",
"cursor",
".",
"execute",
"(",
"(",
"query",
"+",
"'%s'",
")",
",",
"(",
"value",
",",
")",
")",
"cursor",
".",
"fetchall",
"(",
")",
"result",
"=",
"True",
"except",
"Exception",
":",
"e",
"=",
"get_exception",
"(",
")",
"result",
"=",
"str",
"(",
"e",
")",
"return",
"result"
] |
set a global mysql variable to a given value the db driver will handle quoting of the given value based on its type .
|
train
| false
|
55,378
|
@login_required
@enforce_shopping_cart_enabled
def show_cart(request):
cart = Order.get_cart_for_user(request.user)
(is_any_course_expired, expired_cart_items, expired_cart_item_names, valid_cart_item_tuples) = verify_for_closed_enrollment(request.user, cart)
site_name = configuration_helpers.get_value('SITE_NAME', settings.SITE_NAME)
if is_any_course_expired:
for expired_item in expired_cart_items:
Order.remove_cart_item_from_order(expired_item, request.user)
cart.update_order_type()
callback_url = request.build_absolute_uri(reverse('shoppingcart.views.postpay_callback'))
form_html = render_purchase_form_html(cart, callback_url=callback_url)
context = {'order': cart, 'shoppingcart_items': valid_cart_item_tuples, 'amount': cart.total_cost, 'is_course_enrollment_closed': is_any_course_expired, 'expired_course_names': expired_cart_item_names, 'site_name': site_name, 'form_html': form_html, 'currency_symbol': settings.PAID_COURSE_REGISTRATION_CURRENCY[1], 'currency': settings.PAID_COURSE_REGISTRATION_CURRENCY[0], 'enable_bulk_purchase': configuration_helpers.get_value('ENABLE_SHOPPING_CART_BULK_PURCHASE', True)}
return render_to_response('shoppingcart/shopping_cart.html', context)
|
[
"@",
"login_required",
"@",
"enforce_shopping_cart_enabled",
"def",
"show_cart",
"(",
"request",
")",
":",
"cart",
"=",
"Order",
".",
"get_cart_for_user",
"(",
"request",
".",
"user",
")",
"(",
"is_any_course_expired",
",",
"expired_cart_items",
",",
"expired_cart_item_names",
",",
"valid_cart_item_tuples",
")",
"=",
"verify_for_closed_enrollment",
"(",
"request",
".",
"user",
",",
"cart",
")",
"site_name",
"=",
"configuration_helpers",
".",
"get_value",
"(",
"'SITE_NAME'",
",",
"settings",
".",
"SITE_NAME",
")",
"if",
"is_any_course_expired",
":",
"for",
"expired_item",
"in",
"expired_cart_items",
":",
"Order",
".",
"remove_cart_item_from_order",
"(",
"expired_item",
",",
"request",
".",
"user",
")",
"cart",
".",
"update_order_type",
"(",
")",
"callback_url",
"=",
"request",
".",
"build_absolute_uri",
"(",
"reverse",
"(",
"'shoppingcart.views.postpay_callback'",
")",
")",
"form_html",
"=",
"render_purchase_form_html",
"(",
"cart",
",",
"callback_url",
"=",
"callback_url",
")",
"context",
"=",
"{",
"'order'",
":",
"cart",
",",
"'shoppingcart_items'",
":",
"valid_cart_item_tuples",
",",
"'amount'",
":",
"cart",
".",
"total_cost",
",",
"'is_course_enrollment_closed'",
":",
"is_any_course_expired",
",",
"'expired_course_names'",
":",
"expired_cart_item_names",
",",
"'site_name'",
":",
"site_name",
",",
"'form_html'",
":",
"form_html",
",",
"'currency_symbol'",
":",
"settings",
".",
"PAID_COURSE_REGISTRATION_CURRENCY",
"[",
"1",
"]",
",",
"'currency'",
":",
"settings",
".",
"PAID_COURSE_REGISTRATION_CURRENCY",
"[",
"0",
"]",
",",
"'enable_bulk_purchase'",
":",
"configuration_helpers",
".",
"get_value",
"(",
"'ENABLE_SHOPPING_CART_BULK_PURCHASE'",
",",
"True",
")",
"}",
"return",
"render_to_response",
"(",
"'shoppingcart/shopping_cart.html'",
",",
"context",
")"
] |
this view shows cart items .
|
train
| false
|
55,380
|
def PostVimMessage(message, warning=True, truncate=False):
echo_command = (u'echom' if warning else u'echo')
vim.command(u'redraw')
if warning:
vim.command(u'echohl WarningMsg')
message = ToUnicode(message)
if truncate:
vim_width = GetIntValue(u'&columns')
message = message.replace(u'\n', u' ')
if (len(message) > vim_width):
message = (message[:(vim_width - 4)] + u'...')
old_ruler = GetIntValue(u'&ruler')
old_showcmd = GetIntValue(u'&showcmd')
vim.command(u'set noruler noshowcmd')
vim.command(u"{0} '{1}'".format(echo_command, EscapeForVim(message)))
SetVariableValue(u'&ruler', old_ruler)
SetVariableValue(u'&showcmd', old_showcmd)
else:
for line in message.split(u'\n'):
vim.command(u"{0} '{1}'".format(echo_command, EscapeForVim(line)))
if warning:
vim.command(u'echohl None')
|
[
"def",
"PostVimMessage",
"(",
"message",
",",
"warning",
"=",
"True",
",",
"truncate",
"=",
"False",
")",
":",
"echo_command",
"=",
"(",
"u'echom'",
"if",
"warning",
"else",
"u'echo'",
")",
"vim",
".",
"command",
"(",
"u'redraw'",
")",
"if",
"warning",
":",
"vim",
".",
"command",
"(",
"u'echohl WarningMsg'",
")",
"message",
"=",
"ToUnicode",
"(",
"message",
")",
"if",
"truncate",
":",
"vim_width",
"=",
"GetIntValue",
"(",
"u'&columns'",
")",
"message",
"=",
"message",
".",
"replace",
"(",
"u'\\n'",
",",
"u' '",
")",
"if",
"(",
"len",
"(",
"message",
")",
">",
"vim_width",
")",
":",
"message",
"=",
"(",
"message",
"[",
":",
"(",
"vim_width",
"-",
"4",
")",
"]",
"+",
"u'...'",
")",
"old_ruler",
"=",
"GetIntValue",
"(",
"u'&ruler'",
")",
"old_showcmd",
"=",
"GetIntValue",
"(",
"u'&showcmd'",
")",
"vim",
".",
"command",
"(",
"u'set noruler noshowcmd'",
")",
"vim",
".",
"command",
"(",
"u\"{0} '{1}'\"",
".",
"format",
"(",
"echo_command",
",",
"EscapeForVim",
"(",
"message",
")",
")",
")",
"SetVariableValue",
"(",
"u'&ruler'",
",",
"old_ruler",
")",
"SetVariableValue",
"(",
"u'&showcmd'",
",",
"old_showcmd",
")",
"else",
":",
"for",
"line",
"in",
"message",
".",
"split",
"(",
"u'\\n'",
")",
":",
"vim",
".",
"command",
"(",
"u\"{0} '{1}'\"",
".",
"format",
"(",
"echo_command",
",",
"EscapeForVim",
"(",
"line",
")",
")",
")",
"if",
"warning",
":",
"vim",
".",
"command",
"(",
"u'echohl None'",
")"
] |
display a message on the vim status line .
|
train
| false
|
55,381
|
def getRadiusByPrefix(prefix, sideLength, xmlElement):
radius = getFloatByPrefixSide((prefix + 'radius'), sideLength, xmlElement)
radius += (0.5 * getFloatByPrefixSide((prefix + 'diameter'), sideLength, xmlElement))
return (radius + (0.5 * getFloatByPrefixSide((prefix + 'size'), sideLength, xmlElement)))
|
[
"def",
"getRadiusByPrefix",
"(",
"prefix",
",",
"sideLength",
",",
"xmlElement",
")",
":",
"radius",
"=",
"getFloatByPrefixSide",
"(",
"(",
"prefix",
"+",
"'radius'",
")",
",",
"sideLength",
",",
"xmlElement",
")",
"radius",
"+=",
"(",
"0.5",
"*",
"getFloatByPrefixSide",
"(",
"(",
"prefix",
"+",
"'diameter'",
")",
",",
"sideLength",
",",
"xmlElement",
")",
")",
"return",
"(",
"radius",
"+",
"(",
"0.5",
"*",
"getFloatByPrefixSide",
"(",
"(",
"prefix",
"+",
"'size'",
")",
",",
"sideLength",
",",
"xmlElement",
")",
")",
")"
] |
get radius by prefix .
|
train
| false
|
55,385
|
def _filter_doc_html(request, doc, doc_html, rendering_params):
if rendering_params['summary']:
return doc.get_summary_html()
if (not (rendering_params['section'] or rendering_params['raw'] or rendering_params['edit_links'] or rendering_params['include'])):
return doc_html
tool = kuma.wiki.content.parse(doc_html)
if rendering_params['raw']:
tool.injectSectionIDs()
tool.filterEditorSafety()
if rendering_params['section']:
tool.extractSection(rendering_params['section'])
if ((rendering_params['edit_links'] or (not rendering_params['raw'])) and request.user.is_authenticated() and doc.allows_revision_by(request.user)):
tool.injectSectionEditingLinks(doc.slug, doc.locale)
doc_html = tool.serialize()
if rendering_params['include']:
doc_html = kuma.wiki.content.filter_out_noinclude(doc_html)
return doc_html
|
[
"def",
"_filter_doc_html",
"(",
"request",
",",
"doc",
",",
"doc_html",
",",
"rendering_params",
")",
":",
"if",
"rendering_params",
"[",
"'summary'",
"]",
":",
"return",
"doc",
".",
"get_summary_html",
"(",
")",
"if",
"(",
"not",
"(",
"rendering_params",
"[",
"'section'",
"]",
"or",
"rendering_params",
"[",
"'raw'",
"]",
"or",
"rendering_params",
"[",
"'edit_links'",
"]",
"or",
"rendering_params",
"[",
"'include'",
"]",
")",
")",
":",
"return",
"doc_html",
"tool",
"=",
"kuma",
".",
"wiki",
".",
"content",
".",
"parse",
"(",
"doc_html",
")",
"if",
"rendering_params",
"[",
"'raw'",
"]",
":",
"tool",
".",
"injectSectionIDs",
"(",
")",
"tool",
".",
"filterEditorSafety",
"(",
")",
"if",
"rendering_params",
"[",
"'section'",
"]",
":",
"tool",
".",
"extractSection",
"(",
"rendering_params",
"[",
"'section'",
"]",
")",
"if",
"(",
"(",
"rendering_params",
"[",
"'edit_links'",
"]",
"or",
"(",
"not",
"rendering_params",
"[",
"'raw'",
"]",
")",
")",
"and",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
"and",
"doc",
".",
"allows_revision_by",
"(",
"request",
".",
"user",
")",
")",
":",
"tool",
".",
"injectSectionEditingLinks",
"(",
"doc",
".",
"slug",
",",
"doc",
".",
"locale",
")",
"doc_html",
"=",
"tool",
".",
"serialize",
"(",
")",
"if",
"rendering_params",
"[",
"'include'",
"]",
":",
"doc_html",
"=",
"kuma",
".",
"wiki",
".",
"content",
".",
"filter_out_noinclude",
"(",
"doc_html",
")",
"return",
"doc_html"
] |
apply needed filtering/annotating operations to a documents html .
|
train
| false
|
55,386
|
def create_minibatch_x(minibatches, minibatch_markers, epoch_axis):
if epoch_axis:
x = np.zeros((minibatches,))
last_e = 0
for (e_idx, e) in enumerate(minibatch_markers):
e_minibatches = (e - last_e)
x[last_e:e] = (e_idx + (np.arange(float(e_minibatches)) / e_minibatches))
last_e = e
else:
x = np.arange(minibatches)
return x
|
[
"def",
"create_minibatch_x",
"(",
"minibatches",
",",
"minibatch_markers",
",",
"epoch_axis",
")",
":",
"if",
"epoch_axis",
":",
"x",
"=",
"np",
".",
"zeros",
"(",
"(",
"minibatches",
",",
")",
")",
"last_e",
"=",
"0",
"for",
"(",
"e_idx",
",",
"e",
")",
"in",
"enumerate",
"(",
"minibatch_markers",
")",
":",
"e_minibatches",
"=",
"(",
"e",
"-",
"last_e",
")",
"x",
"[",
"last_e",
":",
"e",
"]",
"=",
"(",
"e_idx",
"+",
"(",
"np",
".",
"arange",
"(",
"float",
"(",
"e_minibatches",
")",
")",
"/",
"e_minibatches",
")",
")",
"last_e",
"=",
"e",
"else",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"minibatches",
")",
"return",
"x"
] |
helper function to build x axis for data captured per minibatch .
|
train
| false
|
55,387
|
def CDLMORNINGDOJISTAR(barDs, count, penetration=(-4e+37)):
return call_talib_with_ohlc(barDs, count, talib.CDLMORNINGDOJISTAR, penetration)
|
[
"def",
"CDLMORNINGDOJISTAR",
"(",
"barDs",
",",
"count",
",",
"penetration",
"=",
"(",
"-",
"4e+37",
")",
")",
":",
"return",
"call_talib_with_ohlc",
"(",
"barDs",
",",
"count",
",",
"talib",
".",
"CDLMORNINGDOJISTAR",
",",
"penetration",
")"
] |
morning doji star .
|
train
| false
|
55,388
|
def gaussian_convolution(h, Xi, x):
return ((1.0 / np.sqrt((4 * np.pi))) * np.exp(((- ((Xi - x) ** 2)) / ((h ** 2) * 4.0))))
|
[
"def",
"gaussian_convolution",
"(",
"h",
",",
"Xi",
",",
"x",
")",
":",
"return",
"(",
"(",
"1.0",
"/",
"np",
".",
"sqrt",
"(",
"(",
"4",
"*",
"np",
".",
"pi",
")",
")",
")",
"*",
"np",
".",
"exp",
"(",
"(",
"(",
"-",
"(",
"(",
"Xi",
"-",
"x",
")",
"**",
"2",
")",
")",
"/",
"(",
"(",
"h",
"**",
"2",
")",
"*",
"4.0",
")",
")",
")",
")"
] |
calculates the gaussian convolution kernel .
|
train
| false
|
55,389
|
def _map_plays_to_roles(graph, dirs, git_dir, key, type_1, type_2):
Node = namedtuple('Node', ['name', 'type'])
for d in dirs:
d = pathlib2.Path(git_dir, d)
for item in d.iterdir():
if item.match('*.yml'):
yaml_file = _open_yaml_file(item)
if (yaml_file is not None):
for play in yaml_file:
if (key in play):
for role in play[key]:
name = _get_role_name(role)
node_1 = Node(item.stem, type_1)
node_2 = Node(name, type_2)
graph.add_edge(node_2, node_1)
|
[
"def",
"_map_plays_to_roles",
"(",
"graph",
",",
"dirs",
",",
"git_dir",
",",
"key",
",",
"type_1",
",",
"type_2",
")",
":",
"Node",
"=",
"namedtuple",
"(",
"'Node'",
",",
"[",
"'name'",
",",
"'type'",
"]",
")",
"for",
"d",
"in",
"dirs",
":",
"d",
"=",
"pathlib2",
".",
"Path",
"(",
"git_dir",
",",
"d",
")",
"for",
"item",
"in",
"d",
".",
"iterdir",
"(",
")",
":",
"if",
"item",
".",
"match",
"(",
"'*.yml'",
")",
":",
"yaml_file",
"=",
"_open_yaml_file",
"(",
"item",
")",
"if",
"(",
"yaml_file",
"is",
"not",
"None",
")",
":",
"for",
"play",
"in",
"yaml_file",
":",
"if",
"(",
"key",
"in",
"play",
")",
":",
"for",
"role",
"in",
"play",
"[",
"key",
"]",
":",
"name",
"=",
"_get_role_name",
"(",
"role",
")",
"node_1",
"=",
"Node",
"(",
"item",
".",
"stem",
",",
"type_1",
")",
"node_2",
"=",
"Node",
"(",
"name",
",",
"type_2",
")",
"graph",
".",
"add_edge",
"(",
"node_2",
",",
"node_1",
")"
] |
maps plays to the roles they use .
|
train
| false
|
55,391
|
def handler_url(block, handler_name, suffix='', query='', thirdparty=False):
view_name = 'xblock_handler'
if handler_name:
func = getattr(block.__class__, handler_name, None)
if (not func):
raise ValueError('{!r} is not a function name'.format(handler_name))
if thirdparty:
view_name = 'xblock_handler_noauth'
url = reverse(view_name, kwargs={'course_id': unicode(block.location.course_key), 'usage_id': quote_slashes(unicode(block.scope_ids.usage_id).encode('utf-8')), 'handler': handler_name, 'suffix': suffix})
if (not suffix):
url = url.rstrip('/')
if query:
url += ('?' + query)
if thirdparty:
scheme = ('https' if (settings.HTTPS == 'on') else 'http')
url = '{scheme}://{host}{path}'.format(scheme=scheme, host=settings.SITE_NAME, path=url)
return url
|
[
"def",
"handler_url",
"(",
"block",
",",
"handler_name",
",",
"suffix",
"=",
"''",
",",
"query",
"=",
"''",
",",
"thirdparty",
"=",
"False",
")",
":",
"view_name",
"=",
"'xblock_handler'",
"if",
"handler_name",
":",
"func",
"=",
"getattr",
"(",
"block",
".",
"__class__",
",",
"handler_name",
",",
"None",
")",
"if",
"(",
"not",
"func",
")",
":",
"raise",
"ValueError",
"(",
"'{!r} is not a function name'",
".",
"format",
"(",
"handler_name",
")",
")",
"if",
"thirdparty",
":",
"view_name",
"=",
"'xblock_handler_noauth'",
"url",
"=",
"reverse",
"(",
"view_name",
",",
"kwargs",
"=",
"{",
"'course_id'",
":",
"unicode",
"(",
"block",
".",
"location",
".",
"course_key",
")",
",",
"'usage_id'",
":",
"quote_slashes",
"(",
"unicode",
"(",
"block",
".",
"scope_ids",
".",
"usage_id",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"'handler'",
":",
"handler_name",
",",
"'suffix'",
":",
"suffix",
"}",
")",
"if",
"(",
"not",
"suffix",
")",
":",
"url",
"=",
"url",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"query",
":",
"url",
"+=",
"(",
"'?'",
"+",
"query",
")",
"if",
"thirdparty",
":",
"scheme",
"=",
"(",
"'https'",
"if",
"(",
"settings",
".",
"HTTPS",
"==",
"'on'",
")",
"else",
"'http'",
")",
"url",
"=",
"'{scheme}://{host}{path}'",
".",
"format",
"(",
"scheme",
"=",
"scheme",
",",
"host",
"=",
"settings",
".",
"SITE_NAME",
",",
"path",
"=",
"url",
")",
"return",
"url"
] |
this method matches the signature for xblock .
|
train
| false
|
55,392
|
@protocol.commands.add(u'command_list_ok_begin', list_command=False)
def command_list_ok_begin(context):
context.dispatcher.command_list_receiving = True
context.dispatcher.command_list_ok = True
context.dispatcher.command_list = []
|
[
"@",
"protocol",
".",
"commands",
".",
"add",
"(",
"u'command_list_ok_begin'",
",",
"list_command",
"=",
"False",
")",
"def",
"command_list_ok_begin",
"(",
"context",
")",
":",
"context",
".",
"dispatcher",
".",
"command_list_receiving",
"=",
"True",
"context",
".",
"dispatcher",
".",
"command_list_ok",
"=",
"True",
"context",
".",
"dispatcher",
".",
"command_list",
"=",
"[",
"]"
] |
see :meth:command_list_begin() .
|
train
| false
|
55,393
|
def _ace_to_text(ace, objectType):
dc = daclConstants()
objectType = dc.getObjectTypeBit(objectType)
try:
userSid = win32security.LookupAccountSid('', ace[2])
if userSid[1]:
userSid = '{1}\\{0}'.format(userSid[0], userSid[1])
else:
userSid = '{0}'.format(userSid[0])
except Exception:
userSid = win32security.ConvertSidToStringSid(ace[2])
tPerm = ace[1]
tAceType = ace[0][0]
tProps = ace[0][1]
tInherited = ''
for x in dc.validAceTypes:
if (dc.validAceTypes[x]['BITS'] == tAceType):
tAceType = dc.validAceTypes[x]['TEXT']
break
for x in dc.rights[objectType]:
if (dc.rights[objectType][x]['BITS'] == tPerm):
tPerm = dc.rights[objectType][x]['TEXT']
break
if ((tProps & win32security.INHERITED_ACE) == win32security.INHERITED_ACE):
tInherited = '[Inherited]'
tProps = (tProps ^ win32security.INHERITED_ACE)
for x in dc.validPropagations[objectType]:
if (dc.validPropagations[objectType][x]['BITS'] == tProps):
tProps = dc.validPropagations[objectType][x]['TEXT']
break
return '{0} {1} {2} on {3} {4}'.format(userSid, tAceType, tPerm, tProps, tInherited)
|
[
"def",
"_ace_to_text",
"(",
"ace",
",",
"objectType",
")",
":",
"dc",
"=",
"daclConstants",
"(",
")",
"objectType",
"=",
"dc",
".",
"getObjectTypeBit",
"(",
"objectType",
")",
"try",
":",
"userSid",
"=",
"win32security",
".",
"LookupAccountSid",
"(",
"''",
",",
"ace",
"[",
"2",
"]",
")",
"if",
"userSid",
"[",
"1",
"]",
":",
"userSid",
"=",
"'{1}\\\\{0}'",
".",
"format",
"(",
"userSid",
"[",
"0",
"]",
",",
"userSid",
"[",
"1",
"]",
")",
"else",
":",
"userSid",
"=",
"'{0}'",
".",
"format",
"(",
"userSid",
"[",
"0",
"]",
")",
"except",
"Exception",
":",
"userSid",
"=",
"win32security",
".",
"ConvertSidToStringSid",
"(",
"ace",
"[",
"2",
"]",
")",
"tPerm",
"=",
"ace",
"[",
"1",
"]",
"tAceType",
"=",
"ace",
"[",
"0",
"]",
"[",
"0",
"]",
"tProps",
"=",
"ace",
"[",
"0",
"]",
"[",
"1",
"]",
"tInherited",
"=",
"''",
"for",
"x",
"in",
"dc",
".",
"validAceTypes",
":",
"if",
"(",
"dc",
".",
"validAceTypes",
"[",
"x",
"]",
"[",
"'BITS'",
"]",
"==",
"tAceType",
")",
":",
"tAceType",
"=",
"dc",
".",
"validAceTypes",
"[",
"x",
"]",
"[",
"'TEXT'",
"]",
"break",
"for",
"x",
"in",
"dc",
".",
"rights",
"[",
"objectType",
"]",
":",
"if",
"(",
"dc",
".",
"rights",
"[",
"objectType",
"]",
"[",
"x",
"]",
"[",
"'BITS'",
"]",
"==",
"tPerm",
")",
":",
"tPerm",
"=",
"dc",
".",
"rights",
"[",
"objectType",
"]",
"[",
"x",
"]",
"[",
"'TEXT'",
"]",
"break",
"if",
"(",
"(",
"tProps",
"&",
"win32security",
".",
"INHERITED_ACE",
")",
"==",
"win32security",
".",
"INHERITED_ACE",
")",
":",
"tInherited",
"=",
"'[Inherited]'",
"tProps",
"=",
"(",
"tProps",
"^",
"win32security",
".",
"INHERITED_ACE",
")",
"for",
"x",
"in",
"dc",
".",
"validPropagations",
"[",
"objectType",
"]",
":",
"if",
"(",
"dc",
".",
"validPropagations",
"[",
"objectType",
"]",
"[",
"x",
"]",
"[",
"'BITS'",
"]",
"==",
"tProps",
")",
":",
"tProps",
"=",
"dc",
".",
"validPropagations",
"[",
"objectType",
"]",
"[",
"x",
"]",
"[",
"'TEXT'",
"]",
"break",
"return",
"'{0} {1} {2} on {3} {4}'",
".",
"format",
"(",
"userSid",
",",
"tAceType",
",",
"tPerm",
",",
"tProps",
",",
"tInherited",
")"
] |
helper function to convert an ace to a textual representation .
|
train
| true
|
55,395
|
def prime(nth):
n = as_int(nth)
if (n < 1):
raise ValueError('nth must be a positive integer; prime(1) == 2')
if (n <= len(sieve._list)):
return sieve[n]
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 2
b = int((n * (log(n) + log(log(n)))))
while (a < b):
mid = ((a + b) >> 1)
if (li(mid) > n):
b = mid
else:
a = (mid + 1)
n_primes = primepi((a - 1))
while (n_primes < n):
if isprime(a):
n_primes += 1
a += 1
return (a - 1)
|
[
"def",
"prime",
"(",
"nth",
")",
":",
"n",
"=",
"as_int",
"(",
"nth",
")",
"if",
"(",
"n",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'nth must be a positive integer; prime(1) == 2'",
")",
"if",
"(",
"n",
"<=",
"len",
"(",
"sieve",
".",
"_list",
")",
")",
":",
"return",
"sieve",
"[",
"n",
"]",
"from",
"sympy",
".",
"functions",
".",
"special",
".",
"error_functions",
"import",
"li",
"from",
"sympy",
".",
"functions",
".",
"elementary",
".",
"exponential",
"import",
"log",
"a",
"=",
"2",
"b",
"=",
"int",
"(",
"(",
"n",
"*",
"(",
"log",
"(",
"n",
")",
"+",
"log",
"(",
"log",
"(",
"n",
")",
")",
")",
")",
")",
"while",
"(",
"a",
"<",
"b",
")",
":",
"mid",
"=",
"(",
"(",
"a",
"+",
"b",
")",
">>",
"1",
")",
"if",
"(",
"li",
"(",
"mid",
")",
">",
"n",
")",
":",
"b",
"=",
"mid",
"else",
":",
"a",
"=",
"(",
"mid",
"+",
"1",
")",
"n_primes",
"=",
"primepi",
"(",
"(",
"a",
"-",
"1",
")",
")",
"while",
"(",
"n_primes",
"<",
"n",
")",
":",
"if",
"isprime",
"(",
"a",
")",
":",
"n_primes",
"+=",
"1",
"a",
"+=",
"1",
"return",
"(",
"a",
"-",
"1",
")"
] |
return the nth prime .
|
train
| false
|
55,396
|
@register.function
@jinja2.contextfunction
def favorites_widget(context, addon, condensed=False):
c = dict(context.items())
request = c['request']
if request.user.is_authenticated():
is_favorite = (addon.id in request.user.favorite_addons)
faved_class = ('faved' if is_favorite else '')
unfaved_text = ('' if condensed else _('Add to favorites'))
faved_text = (_('Favorite') if condensed else _('Remove from favorites'))
add_url = reverse('collections.alter', args=[request.user.username, 'favorites', 'add'])
remove_url = reverse('collections.alter', args=[request.user.username, 'favorites', 'remove'])
c.update(locals())
t = get_env().get_template('bandwagon/favorites_widget.html').render(c)
return jinja2.Markup(t)
|
[
"@",
"register",
".",
"function",
"@",
"jinja2",
".",
"contextfunction",
"def",
"favorites_widget",
"(",
"context",
",",
"addon",
",",
"condensed",
"=",
"False",
")",
":",
"c",
"=",
"dict",
"(",
"context",
".",
"items",
"(",
")",
")",
"request",
"=",
"c",
"[",
"'request'",
"]",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"is_favorite",
"=",
"(",
"addon",
".",
"id",
"in",
"request",
".",
"user",
".",
"favorite_addons",
")",
"faved_class",
"=",
"(",
"'faved'",
"if",
"is_favorite",
"else",
"''",
")",
"unfaved_text",
"=",
"(",
"''",
"if",
"condensed",
"else",
"_",
"(",
"'Add to favorites'",
")",
")",
"faved_text",
"=",
"(",
"_",
"(",
"'Favorite'",
")",
"if",
"condensed",
"else",
"_",
"(",
"'Remove from favorites'",
")",
")",
"add_url",
"=",
"reverse",
"(",
"'collections.alter'",
",",
"args",
"=",
"[",
"request",
".",
"user",
".",
"username",
",",
"'favorites'",
",",
"'add'",
"]",
")",
"remove_url",
"=",
"reverse",
"(",
"'collections.alter'",
",",
"args",
"=",
"[",
"request",
".",
"user",
".",
"username",
",",
"'favorites'",
",",
"'remove'",
"]",
")",
"c",
".",
"update",
"(",
"locals",
"(",
")",
")",
"t",
"=",
"get_env",
"(",
")",
".",
"get_template",
"(",
"'bandwagon/favorites_widget.html'",
")",
".",
"render",
"(",
"c",
")",
"return",
"jinja2",
".",
"Markup",
"(",
"t",
")"
] |
displays add to favorites widget .
|
train
| false
|
55,398
|
def get_argnames(func):
if six.PY2:
if isinstance(func, functools.partial):
spec = inspect.getargspec(func.func)
elif inspect.isroutine(func):
spec = inspect.getargspec(func)
else:
spec = inspect.getargspec(func.__call__)
args = [arg for arg in spec.args if (arg != 'self')]
else:
sig = inspect.signature(func)
args = [param.name for param in sig.parameters.values() if (param.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD))]
return args
|
[
"def",
"get_argnames",
"(",
"func",
")",
":",
"if",
"six",
".",
"PY2",
":",
"if",
"isinstance",
"(",
"func",
",",
"functools",
".",
"partial",
")",
":",
"spec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
".",
"func",
")",
"elif",
"inspect",
".",
"isroutine",
"(",
"func",
")",
":",
"spec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"else",
":",
"spec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
".",
"__call__",
")",
"args",
"=",
"[",
"arg",
"for",
"arg",
"in",
"spec",
".",
"args",
"if",
"(",
"arg",
"!=",
"'self'",
")",
"]",
"else",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"args",
"=",
"[",
"param",
".",
"name",
"for",
"param",
"in",
"sig",
".",
"parameters",
".",
"values",
"(",
")",
"if",
"(",
"param",
".",
"kind",
"not",
"in",
"(",
"inspect",
".",
"Parameter",
".",
"VAR_POSITIONAL",
",",
"inspect",
".",
"Parameter",
".",
"VAR_KEYWORD",
")",
")",
"]",
"return",
"args"
] |
introspecs the arguments of a callable .
|
train
| false
|
55,399
|
def get_indices(client):
try:
indices = list(client.indices.get_settings(index='_all', params={'expand_wildcards': 'open,closed'}))
version_number = get_version(client)
logger.debug('Detected Elasticsearch version {0}'.format('.'.join(map(str, version_number))))
if ((version_number >= (2, 4, 2)) and (version_number < (5, 0, 0))):
logger.debug('Using Elasticsearch >= 2.4.2 < 5.0.0')
if client.indices.exists(index='.security'):
logger.debug('Found the ".security" index. Adding to list of all indices')
if (not ('.security' in indices)):
indices.append('.security')
logger.debug('All indices: {0}'.format(indices))
return indices
except Exception as e:
raise FailedExecution('Failed to get indices. Error: {0}'.format(e))
|
[
"def",
"get_indices",
"(",
"client",
")",
":",
"try",
":",
"indices",
"=",
"list",
"(",
"client",
".",
"indices",
".",
"get_settings",
"(",
"index",
"=",
"'_all'",
",",
"params",
"=",
"{",
"'expand_wildcards'",
":",
"'open,closed'",
"}",
")",
")",
"version_number",
"=",
"get_version",
"(",
"client",
")",
"logger",
".",
"debug",
"(",
"'Detected Elasticsearch version {0}'",
".",
"format",
"(",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"version_number",
")",
")",
")",
")",
"if",
"(",
"(",
"version_number",
">=",
"(",
"2",
",",
"4",
",",
"2",
")",
")",
"and",
"(",
"version_number",
"<",
"(",
"5",
",",
"0",
",",
"0",
")",
")",
")",
":",
"logger",
".",
"debug",
"(",
"'Using Elasticsearch >= 2.4.2 < 5.0.0'",
")",
"if",
"client",
".",
"indices",
".",
"exists",
"(",
"index",
"=",
"'.security'",
")",
":",
"logger",
".",
"debug",
"(",
"'Found the \".security\" index. Adding to list of all indices'",
")",
"if",
"(",
"not",
"(",
"'.security'",
"in",
"indices",
")",
")",
":",
"indices",
".",
"append",
"(",
"'.security'",
")",
"logger",
".",
"debug",
"(",
"'All indices: {0}'",
".",
"format",
"(",
"indices",
")",
")",
"return",
"indices",
"except",
"Exception",
"as",
"e",
":",
"raise",
"FailedExecution",
"(",
"'Failed to get indices. Error: {0}'",
".",
"format",
"(",
"e",
")",
")"
] |
get the current list of indices from the cluster .
|
train
| false
|
55,400
|
def _initialize_headers(headers):
return ({} if (headers is None) else dict(headers))
|
[
"def",
"_initialize_headers",
"(",
"headers",
")",
":",
"return",
"(",
"{",
"}",
"if",
"(",
"headers",
"is",
"None",
")",
"else",
"dict",
"(",
"headers",
")",
")"
] |
creates a copy of the headers .
|
train
| false
|
55,401
|
@contextmanager
def secret_model():
orig_model = None
try:
orig_model = loading.cache.app_models['tests']['secret']
del loading.cache.app_models['tests']['secret']
except KeyError:
pass
try:
attrs = {'name': EncryptedCharField('Name', max_length=Secret._meta.get_field('name').max_length), 'text': EncryptedTextField('Text'), '__module__': 'django_extensions.tests.models', 'Meta': type('Meta', (object,), {'managed': False, 'db_table': Secret._meta.db_table})}
(yield type('Secret', (models.Model,), attrs))
except:
raise
finally:
try:
loading.cache.app_models['tests']['secret'] = orig_model
except KeyError:
pass
|
[
"@",
"contextmanager",
"def",
"secret_model",
"(",
")",
":",
"orig_model",
"=",
"None",
"try",
":",
"orig_model",
"=",
"loading",
".",
"cache",
".",
"app_models",
"[",
"'tests'",
"]",
"[",
"'secret'",
"]",
"del",
"loading",
".",
"cache",
".",
"app_models",
"[",
"'tests'",
"]",
"[",
"'secret'",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"attrs",
"=",
"{",
"'name'",
":",
"EncryptedCharField",
"(",
"'Name'",
",",
"max_length",
"=",
"Secret",
".",
"_meta",
".",
"get_field",
"(",
"'name'",
")",
".",
"max_length",
")",
",",
"'text'",
":",
"EncryptedTextField",
"(",
"'Text'",
")",
",",
"'__module__'",
":",
"'django_extensions.tests.models'",
",",
"'Meta'",
":",
"type",
"(",
"'Meta'",
",",
"(",
"object",
",",
")",
",",
"{",
"'managed'",
":",
"False",
",",
"'db_table'",
":",
"Secret",
".",
"_meta",
".",
"db_table",
"}",
")",
"}",
"(",
"yield",
"type",
"(",
"'Secret'",
",",
"(",
"models",
".",
"Model",
",",
")",
",",
"attrs",
")",
")",
"except",
":",
"raise",
"finally",
":",
"try",
":",
"loading",
".",
"cache",
".",
"app_models",
"[",
"'tests'",
"]",
"[",
"'secret'",
"]",
"=",
"orig_model",
"except",
"KeyError",
":",
"pass"
] |
a context manager that yields a secret model defined at runtime .
|
train
| false
|
55,402
|
def mark_as_cover(container, name):
if (name not in container.mime_map):
raise ValueError((u'Cannot mark %s as cover as it does not exist' % name))
mt = container.mime_map[name]
if (not is_raster_image(mt)):
raise ValueError((u'Cannot mark %s as the cover image as it is not a raster image' % name))
if (container.book_type == u'azw3'):
mark_as_cover_azw3(container, name)
else:
mark_as_cover_epub(container, name)
|
[
"def",
"mark_as_cover",
"(",
"container",
",",
"name",
")",
":",
"if",
"(",
"name",
"not",
"in",
"container",
".",
"mime_map",
")",
":",
"raise",
"ValueError",
"(",
"(",
"u'Cannot mark %s as cover as it does not exist'",
"%",
"name",
")",
")",
"mt",
"=",
"container",
".",
"mime_map",
"[",
"name",
"]",
"if",
"(",
"not",
"is_raster_image",
"(",
"mt",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"u'Cannot mark %s as the cover image as it is not a raster image'",
"%",
"name",
")",
")",
"if",
"(",
"container",
".",
"book_type",
"==",
"u'azw3'",
")",
":",
"mark_as_cover_azw3",
"(",
"container",
",",
"name",
")",
"else",
":",
"mark_as_cover_epub",
"(",
"container",
",",
"name",
")"
] |
mark the specified image as the cover image .
|
train
| false
|
55,403
|
def is_unit(xblock, parent_xblock=None):
if (xblock.category == 'vertical'):
if (parent_xblock is None):
parent_xblock = get_parent_xblock(xblock)
parent_category = (parent_xblock.category if parent_xblock else None)
return (parent_category == 'sequential')
return False
|
[
"def",
"is_unit",
"(",
"xblock",
",",
"parent_xblock",
"=",
"None",
")",
":",
"if",
"(",
"xblock",
".",
"category",
"==",
"'vertical'",
")",
":",
"if",
"(",
"parent_xblock",
"is",
"None",
")",
":",
"parent_xblock",
"=",
"get_parent_xblock",
"(",
"xblock",
")",
"parent_category",
"=",
"(",
"parent_xblock",
".",
"category",
"if",
"parent_xblock",
"else",
"None",
")",
"return",
"(",
"parent_category",
"==",
"'sequential'",
")",
"return",
"False"
] |
returns true if the specified xblock is a vertical that is treated as a unit .
|
train
| false
|
55,405
|
def assert_no_element_by_id(context, _id, wait_time=MAX_WAIT_FOR_UNEXPECTED_ELEMENT):
_assert_no_element_by(context, By.ID, _id, wait_time)
|
[
"def",
"assert_no_element_by_id",
"(",
"context",
",",
"_id",
",",
"wait_time",
"=",
"MAX_WAIT_FOR_UNEXPECTED_ELEMENT",
")",
":",
"_assert_no_element_by",
"(",
"context",
",",
"By",
".",
"ID",
",",
"_id",
",",
"wait_time",
")"
] |
assert that no element is found .
|
train
| false
|
55,406
|
@flake8ext
def use_jsonutils(logical_line, filename):
msg = 'N321: jsonutils.%(fun)s must be used instead of json.%(fun)s'
json_check_skipped_patterns = ['neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/etc/xapi.d/plugins/netwrap']
for pattern in json_check_skipped_patterns:
if (pattern in filename):
return
if ('json.' in logical_line):
json_funcs = ['dumps(', 'dump(', 'loads(', 'load(']
for f in json_funcs:
pos = logical_line.find(('json.%s' % f))
if (pos != (-1)):
(yield (pos, (msg % {'fun': f[:(-1)]})))
|
[
"@",
"flake8ext",
"def",
"use_jsonutils",
"(",
"logical_line",
",",
"filename",
")",
":",
"msg",
"=",
"'N321: jsonutils.%(fun)s must be used instead of json.%(fun)s'",
"json_check_skipped_patterns",
"=",
"[",
"'neutron/plugins/ml2/drivers/openvswitch/agent/xenapi/etc/xapi.d/plugins/netwrap'",
"]",
"for",
"pattern",
"in",
"json_check_skipped_patterns",
":",
"if",
"(",
"pattern",
"in",
"filename",
")",
":",
"return",
"if",
"(",
"'json.'",
"in",
"logical_line",
")",
":",
"json_funcs",
"=",
"[",
"'dumps('",
",",
"'dump('",
",",
"'loads('",
",",
"'load('",
"]",
"for",
"f",
"in",
"json_funcs",
":",
"pos",
"=",
"logical_line",
".",
"find",
"(",
"(",
"'json.%s'",
"%",
"f",
")",
")",
"if",
"(",
"pos",
"!=",
"(",
"-",
"1",
")",
")",
":",
"(",
"yield",
"(",
"pos",
",",
"(",
"msg",
"%",
"{",
"'fun'",
":",
"f",
"[",
":",
"(",
"-",
"1",
")",
"]",
"}",
")",
")",
")"
] |
n321 - use jsonutils instead of json .
|
train
| false
|
55,407
|
def addAssemblyCage(derivation, negatives, positives):
addCageGroove(derivation, negatives, positives)
for pegCenterX in derivation.pegCenterXs:
addPositivePeg(derivation, positives, pegCenterX, (- derivation.pegY))
addPositivePeg(derivation, positives, pegCenterX, derivation.pegY)
translate.translateNegativesPositives(negatives, positives, Vector3(0.0, (- derivation.halfSeparationWidth)))
femaleNegatives = []
femalePositives = []
addCageGroove(derivation, femaleNegatives, femalePositives)
for pegCenterX in derivation.pegCenterXs:
addNegativePeg(derivation, femaleNegatives, pegCenterX, (- derivation.pegY))
addNegativePeg(derivation, femaleNegatives, pegCenterX, derivation.pegY)
translate.translateNegativesPositives(femaleNegatives, femalePositives, Vector3(0.0, derivation.halfSeparationWidth))
negatives += femaleNegatives
positives += femalePositives
|
[
"def",
"addAssemblyCage",
"(",
"derivation",
",",
"negatives",
",",
"positives",
")",
":",
"addCageGroove",
"(",
"derivation",
",",
"negatives",
",",
"positives",
")",
"for",
"pegCenterX",
"in",
"derivation",
".",
"pegCenterXs",
":",
"addPositivePeg",
"(",
"derivation",
",",
"positives",
",",
"pegCenterX",
",",
"(",
"-",
"derivation",
".",
"pegY",
")",
")",
"addPositivePeg",
"(",
"derivation",
",",
"positives",
",",
"pegCenterX",
",",
"derivation",
".",
"pegY",
")",
"translate",
".",
"translateNegativesPositives",
"(",
"negatives",
",",
"positives",
",",
"Vector3",
"(",
"0.0",
",",
"(",
"-",
"derivation",
".",
"halfSeparationWidth",
")",
")",
")",
"femaleNegatives",
"=",
"[",
"]",
"femalePositives",
"=",
"[",
"]",
"addCageGroove",
"(",
"derivation",
",",
"femaleNegatives",
",",
"femalePositives",
")",
"for",
"pegCenterX",
"in",
"derivation",
".",
"pegCenterXs",
":",
"addNegativePeg",
"(",
"derivation",
",",
"femaleNegatives",
",",
"pegCenterX",
",",
"(",
"-",
"derivation",
".",
"pegY",
")",
")",
"addNegativePeg",
"(",
"derivation",
",",
"femaleNegatives",
",",
"pegCenterX",
",",
"derivation",
".",
"pegY",
")",
"translate",
".",
"translateNegativesPositives",
"(",
"femaleNegatives",
",",
"femalePositives",
",",
"Vector3",
"(",
"0.0",
",",
"derivation",
".",
"halfSeparationWidth",
")",
")",
"negatives",
"+=",
"femaleNegatives",
"positives",
"+=",
"femalePositives"
] |
add assembly linear bearing cage .
|
train
| false
|
55,408
|
@treeio_login_required
@handle_response_format
def order_invoice_view(request, order_id, response_format='html'):
order = get_object_or_404(SaleOrder, pk=order_id)
if ((not request.user.profile.has_permission(order)) and (not request.user.profile.is_admin('treeio.sales'))):
return user_denied(request, message="You don't have access to this Sale")
ordered_products = order.orderedproduct_set.filter(trash=False)
try:
conf = ModuleSetting.get_for_module('treeio.finance', 'my_company')[0]
my_company = Contact.objects.get(pk=long(conf.value))
except:
my_company = None
return render_to_response('sales/order_invoice_view', {'order': order, 'ordered_products': ordered_products, 'my_company': my_company}, context_instance=RequestContext(request), response_format=response_format)
|
[
"@",
"treeio_login_required",
"@",
"handle_response_format",
"def",
"order_invoice_view",
"(",
"request",
",",
"order_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"order",
"=",
"get_object_or_404",
"(",
"SaleOrder",
",",
"pk",
"=",
"order_id",
")",
"if",
"(",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"has_permission",
"(",
"order",
")",
")",
"and",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"is_admin",
"(",
"'treeio.sales'",
")",
")",
")",
":",
"return",
"user_denied",
"(",
"request",
",",
"message",
"=",
"\"You don't have access to this Sale\"",
")",
"ordered_products",
"=",
"order",
".",
"orderedproduct_set",
".",
"filter",
"(",
"trash",
"=",
"False",
")",
"try",
":",
"conf",
"=",
"ModuleSetting",
".",
"get_for_module",
"(",
"'treeio.finance'",
",",
"'my_company'",
")",
"[",
"0",
"]",
"my_company",
"=",
"Contact",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"long",
"(",
"conf",
".",
"value",
")",
")",
"except",
":",
"my_company",
"=",
"None",
"return",
"render_to_response",
"(",
"'sales/order_invoice_view'",
",",
"{",
"'order'",
":",
"order",
",",
"'ordered_products'",
":",
"ordered_products",
",",
"'my_company'",
":",
"my_company",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] |
order view as invoice .
|
train
| false
|
55,409
|
def getNewRepository():
return ExportRepository()
|
[
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] |
get the repository constructor .
|
train
| false
|
55,410
|
def json_underscore(body, charset='utf-8', **kwargs):
return _underscore_dict(json(body, charset=charset))
|
[
"def",
"json_underscore",
"(",
"body",
",",
"charset",
"=",
"'utf-8'",
",",
"**",
"kwargs",
")",
":",
"return",
"_underscore_dict",
"(",
"json",
"(",
"body",
",",
"charset",
"=",
"charset",
")",
")"
] |
converts json formatted date to native python objects .
|
train
| false
|
55,411
|
def git_hook():
(_, files_modified, _) = run('git diff-index --cached --name-only HEAD')
options = parse_options()
setup_logger(options)
candidates = list(map(str, files_modified))
if candidates:
process_paths(options, candidates=candidates)
|
[
"def",
"git_hook",
"(",
")",
":",
"(",
"_",
",",
"files_modified",
",",
"_",
")",
"=",
"run",
"(",
"'git diff-index --cached --name-only HEAD'",
")",
"options",
"=",
"parse_options",
"(",
")",
"setup_logger",
"(",
"options",
")",
"candidates",
"=",
"list",
"(",
"map",
"(",
"str",
",",
"files_modified",
")",
")",
"if",
"candidates",
":",
"process_paths",
"(",
"options",
",",
"candidates",
"=",
"candidates",
")"
] |
run pylama after git commit .
|
train
| false
|
55,412
|
def role_delete(role_id=None, name=None, profile=None, **connection_args):
kstone = auth(profile, **connection_args)
if name:
for role in kstone.roles.list():
if (role.name == name):
role_id = role.id
break
if (not role_id):
return {'Error': 'Unable to resolve role id'}
role = kstone.roles.get(role_id)
kstone.roles.delete(role)
ret = 'Role ID {0} deleted'.format(role_id)
if name:
ret += ' ({0})'.format(name)
return ret
|
[
"def",
"role_delete",
"(",
"role_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"**",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"**",
"connection_args",
")",
"if",
"name",
":",
"for",
"role",
"in",
"kstone",
".",
"roles",
".",
"list",
"(",
")",
":",
"if",
"(",
"role",
".",
"name",
"==",
"name",
")",
":",
"role_id",
"=",
"role",
".",
"id",
"break",
"if",
"(",
"not",
"role_id",
")",
":",
"return",
"{",
"'Error'",
":",
"'Unable to resolve role id'",
"}",
"role",
"=",
"kstone",
".",
"roles",
".",
"get",
"(",
"role_id",
")",
"kstone",
".",
"roles",
".",
"delete",
"(",
"role",
")",
"ret",
"=",
"'Role ID {0} deleted'",
".",
"format",
"(",
"role_id",
")",
"if",
"name",
":",
"ret",
"+=",
"' ({0})'",
".",
"format",
"(",
"name",
")",
"return",
"ret"
] |
delete a role cli examples: .
|
train
| true
|
55,413
|
def _needs_eeg_average_ref_proj(info):
eeg_sel = pick_types(info, meg=False, eeg=True, ref_meg=False, exclude='bads')
return ((len(eeg_sel) > 0) and (not info['custom_ref_applied']) and (not _has_eeg_average_ref_proj(info['projs'])))
|
[
"def",
"_needs_eeg_average_ref_proj",
"(",
"info",
")",
":",
"eeg_sel",
"=",
"pick_types",
"(",
"info",
",",
"meg",
"=",
"False",
",",
"eeg",
"=",
"True",
",",
"ref_meg",
"=",
"False",
",",
"exclude",
"=",
"'bads'",
")",
"return",
"(",
"(",
"len",
"(",
"eeg_sel",
")",
">",
"0",
")",
"and",
"(",
"not",
"info",
"[",
"'custom_ref_applied'",
"]",
")",
"and",
"(",
"not",
"_has_eeg_average_ref_proj",
"(",
"info",
"[",
"'projs'",
"]",
")",
")",
")"
] |
determine if the eeg needs an averge eeg reference .
|
train
| false
|
55,414
|
@frappe.whitelist()
def add_tag(tag, dt, dn, color=None):
DocTags(dt).add(dn, tag)
return tag
|
[
"@",
"frappe",
".",
"whitelist",
"(",
")",
"def",
"add_tag",
"(",
"tag",
",",
"dt",
",",
"dn",
",",
"color",
"=",
"None",
")",
":",
"DocTags",
"(",
"dt",
")",
".",
"add",
"(",
"dn",
",",
"tag",
")",
"return",
"tag"
] |
adds a new tag to a record .
|
train
| false
|
55,415
|
def CreateBudget(client):
budget_service = client.GetService('BudgetService', version='v201609')
budget = {'name': ('Interplanetary Cruise App Budget #%s' % uuid.uuid4()), 'amount': {'microAmount': '50000000'}, 'deliveryMethod': 'STANDARD', 'isExplicitlyShared': False}
budget_operations = [{'operator': 'ADD', 'operand': budget}]
budget_id = budget_service.mutate(budget_operations)['value'][0]['budgetId']
return budget_id
|
[
"def",
"CreateBudget",
"(",
"client",
")",
":",
"budget_service",
"=",
"client",
".",
"GetService",
"(",
"'BudgetService'",
",",
"version",
"=",
"'v201609'",
")",
"budget",
"=",
"{",
"'name'",
":",
"(",
"'Interplanetary Cruise App Budget #%s'",
"%",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"'amount'",
":",
"{",
"'microAmount'",
":",
"'50000000'",
"}",
",",
"'deliveryMethod'",
":",
"'STANDARD'",
",",
"'isExplicitlyShared'",
":",
"False",
"}",
"budget_operations",
"=",
"[",
"{",
"'operator'",
":",
"'ADD'",
",",
"'operand'",
":",
"budget",
"}",
"]",
"budget_id",
"=",
"budget_service",
".",
"mutate",
"(",
"budget_operations",
")",
"[",
"'value'",
"]",
"[",
"0",
"]",
"[",
"'budgetId'",
"]",
"return",
"budget_id"
] |
creates a budget and returns its budgetid .
|
train
| true
|
55,417
|
def _nova_to_osvif_network(network):
netobj = objects.network.Network(id=network['id'], bridge_interface=network.get_meta('bridge_interface'), subnets=_nova_to_osvif_subnets(network['subnets']))
if (network['bridge'] is not None):
netobj.bridge = network['bridge']
if (network['label'] is not None):
netobj.label = network['label']
if (network.get_meta('mtu') is not None):
netobj.mtu = network.get_meta('mtu')
if (network.get_meta('multi_host') is not None):
netobj.multi_host = network.get_meta('multi_host')
if (network.get_meta('should_create_bridge') is not None):
netobj.should_provide_bridge = network.get_meta('should_create_bridge')
if (network.get_meta('should_create_vlan') is not None):
netobj.should_provide_vlan = network.get_meta('should_create_vlan')
if (network.get_meta('vlan') is None):
raise exception.NovaException((_('Missing vlan number in %s') % network))
netobj.vlan = network.get_meta('vlan')
return netobj
|
[
"def",
"_nova_to_osvif_network",
"(",
"network",
")",
":",
"netobj",
"=",
"objects",
".",
"network",
".",
"Network",
"(",
"id",
"=",
"network",
"[",
"'id'",
"]",
",",
"bridge_interface",
"=",
"network",
".",
"get_meta",
"(",
"'bridge_interface'",
")",
",",
"subnets",
"=",
"_nova_to_osvif_subnets",
"(",
"network",
"[",
"'subnets'",
"]",
")",
")",
"if",
"(",
"network",
"[",
"'bridge'",
"]",
"is",
"not",
"None",
")",
":",
"netobj",
".",
"bridge",
"=",
"network",
"[",
"'bridge'",
"]",
"if",
"(",
"network",
"[",
"'label'",
"]",
"is",
"not",
"None",
")",
":",
"netobj",
".",
"label",
"=",
"network",
"[",
"'label'",
"]",
"if",
"(",
"network",
".",
"get_meta",
"(",
"'mtu'",
")",
"is",
"not",
"None",
")",
":",
"netobj",
".",
"mtu",
"=",
"network",
".",
"get_meta",
"(",
"'mtu'",
")",
"if",
"(",
"network",
".",
"get_meta",
"(",
"'multi_host'",
")",
"is",
"not",
"None",
")",
":",
"netobj",
".",
"multi_host",
"=",
"network",
".",
"get_meta",
"(",
"'multi_host'",
")",
"if",
"(",
"network",
".",
"get_meta",
"(",
"'should_create_bridge'",
")",
"is",
"not",
"None",
")",
":",
"netobj",
".",
"should_provide_bridge",
"=",
"network",
".",
"get_meta",
"(",
"'should_create_bridge'",
")",
"if",
"(",
"network",
".",
"get_meta",
"(",
"'should_create_vlan'",
")",
"is",
"not",
"None",
")",
":",
"netobj",
".",
"should_provide_vlan",
"=",
"network",
".",
"get_meta",
"(",
"'should_create_vlan'",
")",
"if",
"(",
"network",
".",
"get_meta",
"(",
"'vlan'",
")",
"is",
"None",
")",
":",
"raise",
"exception",
".",
"NovaException",
"(",
"(",
"_",
"(",
"'Missing vlan number in %s'",
")",
"%",
"network",
")",
")",
"netobj",
".",
"vlan",
"=",
"network",
".",
"get_meta",
"(",
"'vlan'",
")",
"return",
"netobj"
] |
convert nova network object into os_vif object .
|
train
| false
|
55,418
|
def delete_disk(kwargs=None, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The delete_disk function must be called with -f or --function.')
if ((not kwargs) or ('disk_name' not in kwargs)):
log.error('A disk_name must be specified when deleting a disk.')
return False
conn = get_conn()
disk = conn.ex_get_volume(kwargs.get('disk_name'))
__utils__['cloud.fire_event']('event', 'delete disk', 'salt/cloud/disk/deleting', args={'name': disk.name, 'location': disk.extra['zone'].name, 'size': disk.size}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])
try:
result = conn.destroy_volume(disk)
except ResourceInUseError as exc:
log.error('Disk {0} is in use and must be detached before deleting.\nThe following exception was thrown by libcloud:\n{1}'.format(disk.name, exc), exc_info_on_loglevel=logging.DEBUG)
return False
__utils__['cloud.fire_event']('event', 'deleted disk', 'salt/cloud/disk/deleted', args={'name': disk.name, 'location': disk.extra['zone'].name, 'size': disk.size}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])
return result
|
[
"def",
"delete_disk",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The delete_disk function must be called with -f or --function.'",
")",
"if",
"(",
"(",
"not",
"kwargs",
")",
"or",
"(",
"'disk_name'",
"not",
"in",
"kwargs",
")",
")",
":",
"log",
".",
"error",
"(",
"'A disk_name must be specified when deleting a disk.'",
")",
"return",
"False",
"conn",
"=",
"get_conn",
"(",
")",
"disk",
"=",
"conn",
".",
"ex_get_volume",
"(",
"kwargs",
".",
"get",
"(",
"'disk_name'",
")",
")",
"__utils__",
"[",
"'cloud.fire_event'",
"]",
"(",
"'event'",
",",
"'delete disk'",
",",
"'salt/cloud/disk/deleting'",
",",
"args",
"=",
"{",
"'name'",
":",
"disk",
".",
"name",
",",
"'location'",
":",
"disk",
".",
"extra",
"[",
"'zone'",
"]",
".",
"name",
",",
"'size'",
":",
"disk",
".",
"size",
"}",
",",
"sock_dir",
"=",
"__opts__",
"[",
"'sock_dir'",
"]",
",",
"transport",
"=",
"__opts__",
"[",
"'transport'",
"]",
")",
"try",
":",
"result",
"=",
"conn",
".",
"destroy_volume",
"(",
"disk",
")",
"except",
"ResourceInUseError",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"'Disk {0} is in use and must be detached before deleting.\\nThe following exception was thrown by libcloud:\\n{1}'",
".",
"format",
"(",
"disk",
".",
"name",
",",
"exc",
")",
",",
"exc_info_on_loglevel",
"=",
"logging",
".",
"DEBUG",
")",
"return",
"False",
"__utils__",
"[",
"'cloud.fire_event'",
"]",
"(",
"'event'",
",",
"'deleted disk'",
",",
"'salt/cloud/disk/deleted'",
",",
"args",
"=",
"{",
"'name'",
":",
"disk",
".",
"name",
",",
"'location'",
":",
"disk",
".",
"extra",
"[",
"'zone'",
"]",
".",
"name",
",",
"'size'",
":",
"disk",
".",
"size",
"}",
",",
"sock_dir",
"=",
"__opts__",
"[",
"'sock_dir'",
"]",
",",
"transport",
"=",
"__opts__",
"[",
"'transport'",
"]",
")",
"return",
"result"
] |
permanently delete a persistent disk .
|
train
| true
|
55,420
|
def externals_finder(dirname, filename):
found = False
f = open(filename, 'rt')
for line in iter(f.readline, ''):
parts = line.split()
if (len(parts) == 2):
(kind, length) = parts
data = f.read(int(length))
if ((kind == 'K') and (data == 'svn:externals')):
found = True
elif ((kind == 'V') and found):
f.close()
break
else:
f.close()
return
for line in data.splitlines():
parts = line.split()
if parts:
(yield joinpath(dirname, parts[0]))
|
[
"def",
"externals_finder",
"(",
"dirname",
",",
"filename",
")",
":",
"found",
"=",
"False",
"f",
"=",
"open",
"(",
"filename",
",",
"'rt'",
")",
"for",
"line",
"in",
"iter",
"(",
"f",
".",
"readline",
",",
"''",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
")",
"if",
"(",
"len",
"(",
"parts",
")",
"==",
"2",
")",
":",
"(",
"kind",
",",
"length",
")",
"=",
"parts",
"data",
"=",
"f",
".",
"read",
"(",
"int",
"(",
"length",
")",
")",
"if",
"(",
"(",
"kind",
"==",
"'K'",
")",
"and",
"(",
"data",
"==",
"'svn:externals'",
")",
")",
":",
"found",
"=",
"True",
"elif",
"(",
"(",
"kind",
"==",
"'V'",
")",
"and",
"found",
")",
":",
"f",
".",
"close",
"(",
")",
"break",
"else",
":",
"f",
".",
"close",
"(",
")",
"return",
"for",
"line",
"in",
"data",
".",
"splitlines",
"(",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
")",
"if",
"parts",
":",
"(",
"yield",
"joinpath",
"(",
"dirname",
",",
"parts",
"[",
"0",
"]",
")",
")"
] |
find any svn:externals directories .
|
train
| true
|
55,421
|
def quiet_close(closable):
try:
closable.close()
except Exception:
logger.debug(u'Exception while closing', exc_info=True)
|
[
"def",
"quiet_close",
"(",
"closable",
")",
":",
"try",
":",
"closable",
".",
"close",
"(",
")",
"except",
"Exception",
":",
"logger",
".",
"debug",
"(",
"u'Exception while closing'",
",",
"exc_info",
"=",
"True",
")"
] |
quietly closes a closable object without throwing an exception .
|
train
| false
|
55,423
|
def contracted_edge(G, edge, self_loops=True):
if (not G.has_edge(*edge)):
raise ValueError('Edge {0} does not exist in graph G; cannot contract it'.format(edge))
return contracted_nodes(G, self_loops=self_loops, *edge)
|
[
"def",
"contracted_edge",
"(",
"G",
",",
"edge",
",",
"self_loops",
"=",
"True",
")",
":",
"if",
"(",
"not",
"G",
".",
"has_edge",
"(",
"*",
"edge",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Edge {0} does not exist in graph G; cannot contract it'",
".",
"format",
"(",
"edge",
")",
")",
"return",
"contracted_nodes",
"(",
"G",
",",
"self_loops",
"=",
"self_loops",
",",
"*",
"edge",
")"
] |
returns the graph that results from contracting the specified edge .
|
train
| false
|
55,424
|
def base_vectors(n):
n = (n / np.sqrt(np.square(n).sum(axis=(-1))))
if (abs(n[0]) == 1):
l = np.r_[(n[2], 0, (- n[0]))]
else:
l = np.r_[(0, n[2], (- n[1]))]
l = (l / np.sqrt(np.square(l).sum(axis=(-1))))
m = np.cross(n, l)
return (n, l, m)
|
[
"def",
"base_vectors",
"(",
"n",
")",
":",
"n",
"=",
"(",
"n",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"square",
"(",
"n",
")",
".",
"sum",
"(",
"axis",
"=",
"(",
"-",
"1",
")",
")",
")",
")",
"if",
"(",
"abs",
"(",
"n",
"[",
"0",
"]",
")",
"==",
"1",
")",
":",
"l",
"=",
"np",
".",
"r_",
"[",
"(",
"n",
"[",
"2",
"]",
",",
"0",
",",
"(",
"-",
"n",
"[",
"0",
"]",
")",
")",
"]",
"else",
":",
"l",
"=",
"np",
".",
"r_",
"[",
"(",
"0",
",",
"n",
"[",
"2",
"]",
",",
"(",
"-",
"n",
"[",
"1",
"]",
")",
")",
"]",
"l",
"=",
"(",
"l",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"square",
"(",
"l",
")",
".",
"sum",
"(",
"axis",
"=",
"(",
"-",
"1",
")",
")",
")",
")",
"m",
"=",
"np",
".",
"cross",
"(",
"n",
",",
"l",
")",
"return",
"(",
"n",
",",
"l",
",",
"m",
")"
] |
returns 3 orthognal base vectors .
|
train
| false
|
55,426
|
def instance_tag_delete_all(context, instance_uuid):
return IMPL.instance_tag_delete_all(context, instance_uuid)
|
[
"def",
"instance_tag_delete_all",
"(",
"context",
",",
"instance_uuid",
")",
":",
"return",
"IMPL",
".",
"instance_tag_delete_all",
"(",
"context",
",",
"instance_uuid",
")"
] |
delete all tags from the instance .
|
train
| false
|
55,427
|
def invalidate_star_import_cache(path):
try:
parser_cache_item = parser_cache[path]
except KeyError:
pass
else:
_invalidate_star_import_cache_module(parser_cache_item.parser.module)
|
[
"def",
"invalidate_star_import_cache",
"(",
"path",
")",
":",
"try",
":",
"parser_cache_item",
"=",
"parser_cache",
"[",
"path",
"]",
"except",
"KeyError",
":",
"pass",
"else",
":",
"_invalidate_star_import_cache_module",
"(",
"parser_cache_item",
".",
"parser",
".",
"module",
")"
] |
on success returns true .
|
train
| false
|
55,428
|
def test_system_dynamic():
print 'TODO'
|
[
"def",
"test_system_dynamic",
"(",
")",
":",
"print",
"'TODO'"
] |
URL only a sanity check here .
|
train
| false
|
55,430
|
def test_custom_model_subclass():
@custom_model
def model_a(x, a=1):
return (x * a)
class model_b(model_a, ):
@classmethod
def evaluate(cls, x, a):
return (- super(model_b, cls).evaluate(x, a))
b = model_b()
assert (b.param_names == (u'a',))
assert (b.a == 1)
assert (b(1) == (-1))
sig = signature(model_b.__init__)
assert (list(sig.parameters.keys()) == [u'self', u'a', u'kwargs'])
sig = signature(model_b.__call__)
assert (list(sig.parameters.keys()) == [u'self', u'x', u'model_set_axis'])
|
[
"def",
"test_custom_model_subclass",
"(",
")",
":",
"@",
"custom_model",
"def",
"model_a",
"(",
"x",
",",
"a",
"=",
"1",
")",
":",
"return",
"(",
"x",
"*",
"a",
")",
"class",
"model_b",
"(",
"model_a",
",",
")",
":",
"@",
"classmethod",
"def",
"evaluate",
"(",
"cls",
",",
"x",
",",
"a",
")",
":",
"return",
"(",
"-",
"super",
"(",
"model_b",
",",
"cls",
")",
".",
"evaluate",
"(",
"x",
",",
"a",
")",
")",
"b",
"=",
"model_b",
"(",
")",
"assert",
"(",
"b",
".",
"param_names",
"==",
"(",
"u'a'",
",",
")",
")",
"assert",
"(",
"b",
".",
"a",
"==",
"1",
")",
"assert",
"(",
"b",
"(",
"1",
")",
"==",
"(",
"-",
"1",
")",
")",
"sig",
"=",
"signature",
"(",
"model_b",
".",
"__init__",
")",
"assert",
"(",
"list",
"(",
"sig",
".",
"parameters",
".",
"keys",
"(",
")",
")",
"==",
"[",
"u'self'",
",",
"u'a'",
",",
"u'kwargs'",
"]",
")",
"sig",
"=",
"signature",
"(",
"model_b",
".",
"__call__",
")",
"assert",
"(",
"list",
"(",
"sig",
".",
"parameters",
".",
"keys",
"(",
")",
")",
"==",
"[",
"u'self'",
",",
"u'x'",
",",
"u'model_set_axis'",
"]",
")"
] |
test that custom models can be subclassed .
|
train
| false
|
55,431
|
def get_scores(video):
if isinstance(video, Episode):
return episode_scores
elif isinstance(video, Movie):
return movie_scores
raise ValueError('video must be an instance of Episode or Movie')
|
[
"def",
"get_scores",
"(",
"video",
")",
":",
"if",
"isinstance",
"(",
"video",
",",
"Episode",
")",
":",
"return",
"episode_scores",
"elif",
"isinstance",
"(",
"video",
",",
"Movie",
")",
":",
"return",
"movie_scores",
"raise",
"ValueError",
"(",
"'video must be an instance of Episode or Movie'",
")"
] |
get the scores dict for the given video .
|
train
| true
|
55,433
|
def int_to_str(value, length=2):
try:
int(value)
except:
raise ValueError('expected an integer value')
content = str(value)
while (len(content) < length):
content = ('0' + content)
return content
|
[
"def",
"int_to_str",
"(",
"value",
",",
"length",
"=",
"2",
")",
":",
"try",
":",
"int",
"(",
"value",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'expected an integer value'",
")",
"content",
"=",
"str",
"(",
"value",
")",
"while",
"(",
"len",
"(",
"content",
")",
"<",
"length",
")",
":",
"content",
"=",
"(",
"'0'",
"+",
"content",
")",
"return",
"content"
] |
converts integer to string eg 3 to "03" .
|
train
| false
|
55,434
|
def validate_payload(payload, api_model, check_required=True):
if check_required:
for key in api_model:
if (api_model[key].required and (key not in payload)):
raise ValidationError(field=key, message="Required field '{}' missing".format(key))
for key in payload:
field = api_model[key]
if isinstance(field, fields.List):
field = field.container
data = payload[key]
elif isinstance(field, fields.Nested):
if payload[key]:
validate_payload(payload[key], field.model)
else:
data = [payload[key]]
if (isinstance(field, CustomField) and hasattr(field, 'validate')):
field.payload = payload
for i in data:
if (not field.validate(i)):
raise ValidationError(field=key, message=(field.validation_error % ("'%s'" % key)))
|
[
"def",
"validate_payload",
"(",
"payload",
",",
"api_model",
",",
"check_required",
"=",
"True",
")",
":",
"if",
"check_required",
":",
"for",
"key",
"in",
"api_model",
":",
"if",
"(",
"api_model",
"[",
"key",
"]",
".",
"required",
"and",
"(",
"key",
"not",
"in",
"payload",
")",
")",
":",
"raise",
"ValidationError",
"(",
"field",
"=",
"key",
",",
"message",
"=",
"\"Required field '{}' missing\"",
".",
"format",
"(",
"key",
")",
")",
"for",
"key",
"in",
"payload",
":",
"field",
"=",
"api_model",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"field",
",",
"fields",
".",
"List",
")",
":",
"field",
"=",
"field",
".",
"container",
"data",
"=",
"payload",
"[",
"key",
"]",
"elif",
"isinstance",
"(",
"field",
",",
"fields",
".",
"Nested",
")",
":",
"if",
"payload",
"[",
"key",
"]",
":",
"validate_payload",
"(",
"payload",
"[",
"key",
"]",
",",
"field",
".",
"model",
")",
"else",
":",
"data",
"=",
"[",
"payload",
"[",
"key",
"]",
"]",
"if",
"(",
"isinstance",
"(",
"field",
",",
"CustomField",
")",
"and",
"hasattr",
"(",
"field",
",",
"'validate'",
")",
")",
":",
"field",
".",
"payload",
"=",
"payload",
"for",
"i",
"in",
"data",
":",
"if",
"(",
"not",
"field",
".",
"validate",
"(",
"i",
")",
")",
":",
"raise",
"ValidationError",
"(",
"field",
"=",
"key",
",",
"message",
"=",
"(",
"field",
".",
"validation_error",
"%",
"(",
"\"'%s'\"",
"%",
"key",
")",
")",
")"
] |
validate payload against an api_model .
|
train
| false
|
55,435
|
def serialize_item(collection, item):
if ((item.name is None) or (item.name == '')):
raise exceptions.RuntimeError('name unset for item!')
if (collection.collection_type() in ['mgmtclass']):
filename = ('/var/lib/cobbler/collections/%ses/%s' % (collection.collection_type(), item.name))
else:
filename = ('/var/lib/cobbler/collections/%ss/%s' % (collection.collection_type(), item.name))
_dict = item.to_dict()
if capi.CobblerAPI().settings().serializer_pretty_json:
sort_keys = True
indent = 4
else:
sort_keys = False
indent = None
filename += '.json'
_dict = item.to_dict()
fd = open(filename, 'w+')
data = simplejson.dumps(_dict, encoding='utf-8', sort_keys=sort_keys, indent=indent)
fd.write(data)
fd.close()
|
[
"def",
"serialize_item",
"(",
"collection",
",",
"item",
")",
":",
"if",
"(",
"(",
"item",
".",
"name",
"is",
"None",
")",
"or",
"(",
"item",
".",
"name",
"==",
"''",
")",
")",
":",
"raise",
"exceptions",
".",
"RuntimeError",
"(",
"'name unset for item!'",
")",
"if",
"(",
"collection",
".",
"collection_type",
"(",
")",
"in",
"[",
"'mgmtclass'",
"]",
")",
":",
"filename",
"=",
"(",
"'/var/lib/cobbler/collections/%ses/%s'",
"%",
"(",
"collection",
".",
"collection_type",
"(",
")",
",",
"item",
".",
"name",
")",
")",
"else",
":",
"filename",
"=",
"(",
"'/var/lib/cobbler/collections/%ss/%s'",
"%",
"(",
"collection",
".",
"collection_type",
"(",
")",
",",
"item",
".",
"name",
")",
")",
"_dict",
"=",
"item",
".",
"to_dict",
"(",
")",
"if",
"capi",
".",
"CobblerAPI",
"(",
")",
".",
"settings",
"(",
")",
".",
"serializer_pretty_json",
":",
"sort_keys",
"=",
"True",
"indent",
"=",
"4",
"else",
":",
"sort_keys",
"=",
"False",
"indent",
"=",
"None",
"filename",
"+=",
"'.json'",
"_dict",
"=",
"item",
".",
"to_dict",
"(",
")",
"fd",
"=",
"open",
"(",
"filename",
",",
"'w+'",
")",
"data",
"=",
"simplejson",
".",
"dumps",
"(",
"_dict",
",",
"encoding",
"=",
"'utf-8'",
",",
"sort_keys",
"=",
"sort_keys",
",",
"indent",
"=",
"indent",
")",
"fd",
".",
"write",
"(",
"data",
")",
"fd",
".",
"close",
"(",
")"
] |
save a collection item to file system .
|
train
| false
|
55,436
|
def get_raising_file_and_line(tb=None):
if (not tb):
tb = sys.exc_info()[2]
(filename, lineno, _context, _line) = traceback.extract_tb(tb)[(-1)]
return (filename, lineno)
|
[
"def",
"get_raising_file_and_line",
"(",
"tb",
"=",
"None",
")",
":",
"if",
"(",
"not",
"tb",
")",
":",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"(",
"filename",
",",
"lineno",
",",
"_context",
",",
"_line",
")",
"=",
"traceback",
".",
"extract_tb",
"(",
"tb",
")",
"[",
"(",
"-",
"1",
")",
"]",
"return",
"(",
"filename",
",",
"lineno",
")"
] |
return the file and line number of the statement that raised the tb .
|
train
| false
|
55,437
|
def quitWindows(event=None):
global globalRepositoryDialogListTable
globalRepositoryDialogValues = euclidean.getListTableElements(globalRepositoryDialogListTable)
for globalRepositoryDialogValue in globalRepositoryDialogValues:
quitWindow(globalRepositoryDialogValue.root)
|
[
"def",
"quitWindows",
"(",
"event",
"=",
"None",
")",
":",
"global",
"globalRepositoryDialogListTable",
"globalRepositoryDialogValues",
"=",
"euclidean",
".",
"getListTableElements",
"(",
"globalRepositoryDialogListTable",
")",
"for",
"globalRepositoryDialogValue",
"in",
"globalRepositoryDialogValues",
":",
"quitWindow",
"(",
"globalRepositoryDialogValue",
".",
"root",
")"
] |
quit all windows .
|
train
| false
|
55,439
|
@app.route('/scans/<int:scan_id>/exceptions/', methods=['GET'])
@requires_auth
def list_exceptions(scan_id):
scan_info = get_scan_info_from_id(scan_id)
if (scan_info is None):
abort(404, 'Scan not found')
data = []
all_exceptions = scan_info.w3af_core.exception_handler.get_all_exceptions()
for (exception_id, exception_data) in enumerate(all_exceptions):
data.append(exception_to_json(exception_data, scan_id, exception_id))
return jsonify({'items': data})
|
[
"@",
"app",
".",
"route",
"(",
"'/scans/<int:scan_id>/exceptions/'",
",",
"methods",
"=",
"[",
"'GET'",
"]",
")",
"@",
"requires_auth",
"def",
"list_exceptions",
"(",
"scan_id",
")",
":",
"scan_info",
"=",
"get_scan_info_from_id",
"(",
"scan_id",
")",
"if",
"(",
"scan_info",
"is",
"None",
")",
":",
"abort",
"(",
"404",
",",
"'Scan not found'",
")",
"data",
"=",
"[",
"]",
"all_exceptions",
"=",
"scan_info",
".",
"w3af_core",
".",
"exception_handler",
".",
"get_all_exceptions",
"(",
")",
"for",
"(",
"exception_id",
",",
"exception_data",
")",
"in",
"enumerate",
"(",
"all_exceptions",
")",
":",
"data",
".",
"append",
"(",
"exception_to_json",
"(",
"exception_data",
",",
"scan_id",
",",
"exception_id",
")",
")",
"return",
"jsonify",
"(",
"{",
"'items'",
":",
"data",
"}",
")"
] |
list all exceptions found during a scan :return: a json containing a list of: - exception resource url - the exceptions id - exception string - exception file name - exception line number .
|
train
| false
|
55,440
|
def _check_even_rewrite(func, arg):
return (func(arg).args[0] == (- arg))
|
[
"def",
"_check_even_rewrite",
"(",
"func",
",",
"arg",
")",
":",
"return",
"(",
"func",
"(",
"arg",
")",
".",
"args",
"[",
"0",
"]",
"==",
"(",
"-",
"arg",
")",
")"
] |
checks that the expr has been rewritten using f -> f(x) arg : -x .
|
train
| false
|
55,441
|
def test_hsl_to_rgb_part_3():
assert (hsl_to_rgb(6120, 100, 50) == (255, 0, 0))
assert (hsl_to_rgb((-9660), 100, 50) == (255, 255, 0))
assert (hsl_to_rgb(99840, 100, 50) == (0, 255, 0))
assert (hsl_to_rgb((-900), 100, 50) == (0, 255, 255))
assert (hsl_to_rgb((-104880), 100, 50) == (0, 0, 255))
assert (hsl_to_rgb(2820, 100, 50) == (255, 0, 255))
|
[
"def",
"test_hsl_to_rgb_part_3",
"(",
")",
":",
"assert",
"(",
"hsl_to_rgb",
"(",
"6120",
",",
"100",
",",
"50",
")",
"==",
"(",
"255",
",",
"0",
",",
"0",
")",
")",
"assert",
"(",
"hsl_to_rgb",
"(",
"(",
"-",
"9660",
")",
",",
"100",
",",
"50",
")",
"==",
"(",
"255",
",",
"255",
",",
"0",
")",
")",
"assert",
"(",
"hsl_to_rgb",
"(",
"99840",
",",
"100",
",",
"50",
")",
"==",
"(",
"0",
",",
"255",
",",
"0",
")",
")",
"assert",
"(",
"hsl_to_rgb",
"(",
"(",
"-",
"900",
")",
",",
"100",
",",
"50",
")",
"==",
"(",
"0",
",",
"255",
",",
"255",
")",
")",
"assert",
"(",
"hsl_to_rgb",
"(",
"(",
"-",
"104880",
")",
",",
"100",
",",
"50",
")",
"==",
"(",
"0",
",",
"0",
",",
"255",
")",
")",
"assert",
"(",
"hsl_to_rgb",
"(",
"2820",
",",
"100",
",",
"50",
")",
"==",
"(",
"255",
",",
"0",
",",
"255",
")",
")"
] |
test hsl to rgb color function .
|
train
| false
|
55,442
|
def test_cx_Oracle():
if (('ORACLE_HOME' not in os.environ) and ('ORACLE_INSTANTCLIENT_HOME' not in os.environ)):
raise SkipTest
try:
import cx_Oracle
return
except ImportError as ex:
if ('No module named' in ex.message):
assert_true(False, 'cx_Oracle skipped its build. This happens if env var ORACLE_HOME or ORACLE_INSTANTCLIENT_HOME is not defined. So ignore this test failure if your build does not need to work with an oracle backend.')
|
[
"def",
"test_cx_Oracle",
"(",
")",
":",
"if",
"(",
"(",
"'ORACLE_HOME'",
"not",
"in",
"os",
".",
"environ",
")",
"and",
"(",
"'ORACLE_INSTANTCLIENT_HOME'",
"not",
"in",
"os",
".",
"environ",
")",
")",
":",
"raise",
"SkipTest",
"try",
":",
"import",
"cx_Oracle",
"return",
"except",
"ImportError",
"as",
"ex",
":",
"if",
"(",
"'No module named'",
"in",
"ex",
".",
"message",
")",
":",
"assert_true",
"(",
"False",
",",
"'cx_Oracle skipped its build. This happens if env var ORACLE_HOME or ORACLE_INSTANTCLIENT_HOME is not defined. So ignore this test failure if your build does not need to work with an oracle backend.'",
")"
] |
tests that cx_oracle is built correctly .
|
train
| false
|
55,443
|
def default_channel():
try:
chan = _open_session()
except ssh.SSHException as err:
if (str(err) == 'SSH session not active'):
connections[env.host_string].close()
del connections[env.host_string]
chan = _open_session()
else:
raise
chan.settimeout(0.1)
chan.input_enabled = True
return chan
|
[
"def",
"default_channel",
"(",
")",
":",
"try",
":",
"chan",
"=",
"_open_session",
"(",
")",
"except",
"ssh",
".",
"SSHException",
"as",
"err",
":",
"if",
"(",
"str",
"(",
"err",
")",
"==",
"'SSH session not active'",
")",
":",
"connections",
"[",
"env",
".",
"host_string",
"]",
".",
"close",
"(",
")",
"del",
"connections",
"[",
"env",
".",
"host_string",
"]",
"chan",
"=",
"_open_session",
"(",
")",
"else",
":",
"raise",
"chan",
".",
"settimeout",
"(",
"0.1",
")",
"chan",
".",
"input_enabled",
"=",
"True",
"return",
"chan"
] |
return a channel object based on env .
|
train
| false
|
55,444
|
def global_fixes():
for function in list(globals().values()):
if inspect.isfunction(function):
arguments = inspect.getargspec(function)[0]
if (arguments[:1] != [u'source']):
continue
code = extract_code_from_function(function)
if code:
(yield (code, function))
|
[
"def",
"global_fixes",
"(",
")",
":",
"for",
"function",
"in",
"list",
"(",
"globals",
"(",
")",
".",
"values",
"(",
")",
")",
":",
"if",
"inspect",
".",
"isfunction",
"(",
"function",
")",
":",
"arguments",
"=",
"inspect",
".",
"getargspec",
"(",
"function",
")",
"[",
"0",
"]",
"if",
"(",
"arguments",
"[",
":",
"1",
"]",
"!=",
"[",
"u'source'",
"]",
")",
":",
"continue",
"code",
"=",
"extract_code_from_function",
"(",
"function",
")",
"if",
"code",
":",
"(",
"yield",
"(",
"code",
",",
"function",
")",
")"
] |
yield multiple tuples .
|
train
| false
|
55,445
|
def _memoize(func, *args, **opts):
if opts:
key = (args, frozenset(opts.items()))
else:
key = args
cache = func.cache
try:
result = cache[key]
except KeyError:
result = cache[key] = func(*args, **opts)
return result
|
[
"def",
"_memoize",
"(",
"func",
",",
"*",
"args",
",",
"**",
"opts",
")",
":",
"if",
"opts",
":",
"key",
"=",
"(",
"args",
",",
"frozenset",
"(",
"opts",
".",
"items",
"(",
")",
")",
")",
"else",
":",
"key",
"=",
"args",
"cache",
"=",
"func",
".",
"cache",
"try",
":",
"result",
"=",
"cache",
"[",
"key",
"]",
"except",
"KeyError",
":",
"result",
"=",
"cache",
"[",
"key",
"]",
"=",
"func",
"(",
"*",
"args",
",",
"**",
"opts",
")",
"return",
"result"
] |
implements memoized cache lookups .
|
train
| false
|
55,446
|
def _get_css_imports_cssutils(data, inline=False):
try:
import cssutils
except (ImportError, re.error):
return None
parser = cssutils.CSSParser(loglevel=100, fetcher=(lambda url: (None, '')), validate=False)
if (not inline):
sheet = parser.parseString(data)
return list(cssutils.getUrls(sheet))
else:
urls = []
declaration = parser.parseStyle(data)
for prop in declaration:
for value in prop.propertyValue:
if isinstance(value, cssutils.css.URIValue):
if value.uri:
urls.append(value.uri)
return urls
|
[
"def",
"_get_css_imports_cssutils",
"(",
"data",
",",
"inline",
"=",
"False",
")",
":",
"try",
":",
"import",
"cssutils",
"except",
"(",
"ImportError",
",",
"re",
".",
"error",
")",
":",
"return",
"None",
"parser",
"=",
"cssutils",
".",
"CSSParser",
"(",
"loglevel",
"=",
"100",
",",
"fetcher",
"=",
"(",
"lambda",
"url",
":",
"(",
"None",
",",
"''",
")",
")",
",",
"validate",
"=",
"False",
")",
"if",
"(",
"not",
"inline",
")",
":",
"sheet",
"=",
"parser",
".",
"parseString",
"(",
"data",
")",
"return",
"list",
"(",
"cssutils",
".",
"getUrls",
"(",
"sheet",
")",
")",
"else",
":",
"urls",
"=",
"[",
"]",
"declaration",
"=",
"parser",
".",
"parseStyle",
"(",
"data",
")",
"for",
"prop",
"in",
"declaration",
":",
"for",
"value",
"in",
"prop",
".",
"propertyValue",
":",
"if",
"isinstance",
"(",
"value",
",",
"cssutils",
".",
"css",
".",
"URIValue",
")",
":",
"if",
"value",
".",
"uri",
":",
"urls",
".",
"append",
"(",
"value",
".",
"uri",
")",
"return",
"urls"
] |
return all assets that are referenced in the given css document .
|
train
| false
|
55,447
|
def make_script_path(script):
s_path = None
path = cfg.script_dir.get_path()
if (path and script):
if (script.lower() not in ('none', 'default')):
s_path = os.path.join(path, script)
if (not os.path.exists(s_path)):
s_path = None
return s_path
|
[
"def",
"make_script_path",
"(",
"script",
")",
":",
"s_path",
"=",
"None",
"path",
"=",
"cfg",
".",
"script_dir",
".",
"get_path",
"(",
")",
"if",
"(",
"path",
"and",
"script",
")",
":",
"if",
"(",
"script",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'none'",
",",
"'default'",
")",
")",
":",
"s_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"script",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"s_path",
")",
")",
":",
"s_path",
"=",
"None",
"return",
"s_path"
] |
return full script path .
|
train
| false
|
55,451
|
def InstallDriver(kext_path):
km = objc.KextManager()
cf_kext_path = km.PyStringToCFString(kext_path)
kext_url = km.dll.CFURLCreateWithFileSystemPath(objc.CF_DEFAULT_ALLOCATOR, cf_kext_path, objc.POSIX_PATH_STYLE, True)
status = km.iokit.KextManagerLoadKextWithURL(kext_url, None)
km.dll.CFRelease(kext_url)
km.dll.CFRelease(cf_kext_path)
if (status is not objc.OS_SUCCESS):
raise OSError('Failed to load kext at {0}: {1}'.format(kext_path, status))
|
[
"def",
"InstallDriver",
"(",
"kext_path",
")",
":",
"km",
"=",
"objc",
".",
"KextManager",
"(",
")",
"cf_kext_path",
"=",
"km",
".",
"PyStringToCFString",
"(",
"kext_path",
")",
"kext_url",
"=",
"km",
".",
"dll",
".",
"CFURLCreateWithFileSystemPath",
"(",
"objc",
".",
"CF_DEFAULT_ALLOCATOR",
",",
"cf_kext_path",
",",
"objc",
".",
"POSIX_PATH_STYLE",
",",
"True",
")",
"status",
"=",
"km",
".",
"iokit",
".",
"KextManagerLoadKextWithURL",
"(",
"kext_url",
",",
"None",
")",
"km",
".",
"dll",
".",
"CFRelease",
"(",
"kext_url",
")",
"km",
".",
"dll",
".",
"CFRelease",
"(",
"cf_kext_path",
")",
"if",
"(",
"status",
"is",
"not",
"objc",
".",
"OS_SUCCESS",
")",
":",
"raise",
"OSError",
"(",
"'Failed to load kext at {0}: {1}'",
".",
"format",
"(",
"kext_path",
",",
"status",
")",
")"
] |
calls into the iokit to load a kext by file-system path .
|
train
| true
|
55,453
|
def setup_form_view(view, request, form, *args, **kwargs):
view.request = request
try:
view.request.user = request.user
except AttributeError:
view.request.user = UserFactory()
view.args = args
view.kwargs = kwargs
view.form = form
return view
|
[
"def",
"setup_form_view",
"(",
"view",
",",
"request",
",",
"form",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"view",
".",
"request",
"=",
"request",
"try",
":",
"view",
".",
"request",
".",
"user",
"=",
"request",
".",
"user",
"except",
"AttributeError",
":",
"view",
".",
"request",
".",
"user",
"=",
"UserFactory",
"(",
")",
"view",
".",
"args",
"=",
"args",
"view",
".",
"kwargs",
"=",
"kwargs",
"view",
".",
"form",
"=",
"form",
"return",
"view"
] |
mimic as_view and with forms to skip some of the context .
|
train
| false
|
55,454
|
def parse_bdist_wininst(name):
lower = name.lower()
(base, py_ver) = (None, None)
if lower.endswith('.exe'):
if lower.endswith('.win32.exe'):
base = name[:(-10)]
elif lower.startswith('.win32-py', (-16)):
py_ver = name[(-7):(-4)]
base = name[:(-16)]
return (base, py_ver)
|
[
"def",
"parse_bdist_wininst",
"(",
"name",
")",
":",
"lower",
"=",
"name",
".",
"lower",
"(",
")",
"(",
"base",
",",
"py_ver",
")",
"=",
"(",
"None",
",",
"None",
")",
"if",
"lower",
".",
"endswith",
"(",
"'.exe'",
")",
":",
"if",
"lower",
".",
"endswith",
"(",
"'.win32.exe'",
")",
":",
"base",
"=",
"name",
"[",
":",
"(",
"-",
"10",
")",
"]",
"elif",
"lower",
".",
"startswith",
"(",
"'.win32-py'",
",",
"(",
"-",
"16",
")",
")",
":",
"py_ver",
"=",
"name",
"[",
"(",
"-",
"7",
")",
":",
"(",
"-",
"4",
")",
"]",
"base",
"=",
"name",
"[",
":",
"(",
"-",
"16",
")",
"]",
"return",
"(",
"base",
",",
"py_ver",
")"
] |
return or for possible .
|
train
| false
|
55,456
|
def scrub_text(text):
scrubbed_text = text.rstrip().replace('\n', '\\n').replace(' DCTB ', (' ' * 4))
return scrubbed_text
|
[
"def",
"scrub_text",
"(",
"text",
")",
":",
"scrubbed_text",
"=",
"text",
".",
"rstrip",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\\\n'",
")",
".",
"replace",
"(",
"' DCTB '",
",",
"(",
"' '",
"*",
"4",
")",
")",
"return",
"scrubbed_text"
] |
cleans up text .
|
train
| false
|
55,457
|
def _get_immediate_cls_attr(cls, attrname, strict=False):
if (not issubclass(cls, object)):
return None
for base in cls.__mro__:
_is_declarative_inherits = hasattr(base, '_decl_class_registry')
if ((attrname in base.__dict__) and ((base is cls) or (((base in cls.__bases__) if strict else True) and (not _is_declarative_inherits)))):
return getattr(base, attrname)
else:
return None
|
[
"def",
"_get_immediate_cls_attr",
"(",
"cls",
",",
"attrname",
",",
"strict",
"=",
"False",
")",
":",
"if",
"(",
"not",
"issubclass",
"(",
"cls",
",",
"object",
")",
")",
":",
"return",
"None",
"for",
"base",
"in",
"cls",
".",
"__mro__",
":",
"_is_declarative_inherits",
"=",
"hasattr",
"(",
"base",
",",
"'_decl_class_registry'",
")",
"if",
"(",
"(",
"attrname",
"in",
"base",
".",
"__dict__",
")",
"and",
"(",
"(",
"base",
"is",
"cls",
")",
"or",
"(",
"(",
"(",
"base",
"in",
"cls",
".",
"__bases__",
")",
"if",
"strict",
"else",
"True",
")",
"and",
"(",
"not",
"_is_declarative_inherits",
")",
")",
")",
")",
":",
"return",
"getattr",
"(",
"base",
",",
"attrname",
")",
"else",
":",
"return",
"None"
] |
return an attribute of the class that is either present directly on the class .
|
train
| false
|
55,458
|
def wiki_escape(s):
ret = []
for word in s.split():
if re.match('[A-Z]+[a-z]+[A-Z]', word):
word = ('!%s' % word)
ret.append(word)
return ' '.join(ret)
|
[
"def",
"wiki_escape",
"(",
"s",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"word",
"in",
"s",
".",
"split",
"(",
")",
":",
"if",
"re",
".",
"match",
"(",
"'[A-Z]+[a-z]+[A-Z]'",
",",
"word",
")",
":",
"word",
"=",
"(",
"'!%s'",
"%",
"word",
")",
"ret",
".",
"append",
"(",
"word",
")",
"return",
"' '",
".",
"join",
"(",
"ret",
")"
] |
detect wikisyntax and escape it .
|
train
| false
|
55,459
|
def getaddresses(fieldvalues):
all = COMMASPACE.join(fieldvalues)
a = _AddressList(all)
return a.addresslist
|
[
"def",
"getaddresses",
"(",
"fieldvalues",
")",
":",
"all",
"=",
"COMMASPACE",
".",
"join",
"(",
"fieldvalues",
")",
"a",
"=",
"_AddressList",
"(",
"all",
")",
"return",
"a",
".",
"addresslist"
] |
return a list of for each fieldvalue .
|
train
| true
|
55,461
|
def _extend_external_network_default(core_plugin, net_res, net_db):
if (net_db.external is not None):
net_res[IS_DEFAULT] = net_db.external.is_default
return net_res
|
[
"def",
"_extend_external_network_default",
"(",
"core_plugin",
",",
"net_res",
",",
"net_db",
")",
":",
"if",
"(",
"net_db",
".",
"external",
"is",
"not",
"None",
")",
":",
"net_res",
"[",
"IS_DEFAULT",
"]",
"=",
"net_db",
".",
"external",
".",
"is_default",
"return",
"net_res"
] |
add is_default field to show response .
|
train
| false
|
55,462
|
def modify_node(hostname, username, password, name, connection_limit=None, description=None, dynamic_ratio=None, logging=None, monitor=None, rate_limit=None, ratio=None, session=None, state=None, trans_label=None):
params = {'connection-limit': connection_limit, 'description': description, 'dynamic-ratio': dynamic_ratio, 'logging': logging, 'monitor': monitor, 'rate-limit': rate_limit, 'ratio': ratio, 'session': session, 'state': state}
bigip_session = _build_session(username, password, trans_label)
payload = _loop_payload(params)
payload['name'] = name
try:
response = bigip_session.put((BIG_IP_URL_BASE.format(host=hostname) + '/ltm/node/{name}'.format(name=name)), data=json.dumps(payload))
except requests.exceptions.ConnectionError as e:
return _load_connection_error(hostname, e)
return _load_response(response)
|
[
"def",
"modify_node",
"(",
"hostname",
",",
"username",
",",
"password",
",",
"name",
",",
"connection_limit",
"=",
"None",
",",
"description",
"=",
"None",
",",
"dynamic_ratio",
"=",
"None",
",",
"logging",
"=",
"None",
",",
"monitor",
"=",
"None",
",",
"rate_limit",
"=",
"None",
",",
"ratio",
"=",
"None",
",",
"session",
"=",
"None",
",",
"state",
"=",
"None",
",",
"trans_label",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'connection-limit'",
":",
"connection_limit",
",",
"'description'",
":",
"description",
",",
"'dynamic-ratio'",
":",
"dynamic_ratio",
",",
"'logging'",
":",
"logging",
",",
"'monitor'",
":",
"monitor",
",",
"'rate-limit'",
":",
"rate_limit",
",",
"'ratio'",
":",
"ratio",
",",
"'session'",
":",
"session",
",",
"'state'",
":",
"state",
"}",
"bigip_session",
"=",
"_build_session",
"(",
"username",
",",
"password",
",",
"trans_label",
")",
"payload",
"=",
"_loop_payload",
"(",
"params",
")",
"payload",
"[",
"'name'",
"]",
"=",
"name",
"try",
":",
"response",
"=",
"bigip_session",
".",
"put",
"(",
"(",
"BIG_IP_URL_BASE",
".",
"format",
"(",
"host",
"=",
"hostname",
")",
"+",
"'/ltm/node/{name}'",
".",
"format",
"(",
"name",
"=",
"name",
")",
")",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"return",
"_load_connection_error",
"(",
"hostname",
",",
"e",
")",
"return",
"_load_response",
"(",
"response",
")"
] |
a function to connect to a bigip device and modify an existing node .
|
train
| true
|
55,463
|
def set_edit_mode(request, flag):
if (flag and could_edit(request)):
request.session[EDIT_FLAG_NAME] = True
else:
request.session.pop(EDIT_FLAG_NAME, None)
|
[
"def",
"set_edit_mode",
"(",
"request",
",",
"flag",
")",
":",
"if",
"(",
"flag",
"and",
"could_edit",
"(",
"request",
")",
")",
":",
"request",
".",
"session",
"[",
"EDIT_FLAG_NAME",
"]",
"=",
"True",
"else",
":",
"request",
".",
"session",
".",
"pop",
"(",
"EDIT_FLAG_NAME",
",",
"None",
")"
] |
enable or disable edit mode for the request .
|
train
| false
|
55,465
|
def getVector3RemoveByPrefix(prefix, vector3, xmlElement):
vector3RemoveByPrefix = getVector3ByPrefix(vector3, prefix, xmlElement)
euclidean.removePrefixFromDictionary(xmlElement.attributeDictionary, prefix)
return vector3RemoveByPrefix
|
[
"def",
"getVector3RemoveByPrefix",
"(",
"prefix",
",",
"vector3",
",",
"xmlElement",
")",
":",
"vector3RemoveByPrefix",
"=",
"getVector3ByPrefix",
"(",
"vector3",
",",
"prefix",
",",
"xmlElement",
")",
"euclidean",
".",
"removePrefixFromDictionary",
"(",
"xmlElement",
".",
"attributeDictionary",
",",
"prefix",
")",
"return",
"vector3RemoveByPrefix"
] |
get vector3 from prefix and xml element .
|
train
| false
|
55,466
|
def _escape_jid(jid):
jid = str(jid)
jid = re.sub("'*", '', jid)
return jid
|
[
"def",
"_escape_jid",
"(",
"jid",
")",
":",
"jid",
"=",
"str",
"(",
"jid",
")",
"jid",
"=",
"re",
".",
"sub",
"(",
"\"'*\"",
",",
"''",
",",
"jid",
")",
"return",
"jid"
] |
do proper formatting of the jid .
|
train
| false
|
55,468
|
def unparse_vs(tup):
return '.'.join(map(str, tup))
|
[
"def",
"unparse_vs",
"(",
"tup",
")",
":",
"return",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"tup",
")",
")"
] |
version list to string .
|
train
| false
|
55,470
|
@apply_to_binary_file
def xmlminify(data):
parser = lxml.etree.XMLParser(remove_blank_text=True)
newdata = lxml.etree.XML(data, parser=parser)
return lxml.etree.tostring(newdata, encoding='utf-8', method='xml', xml_declaration=True)
|
[
"@",
"apply_to_binary_file",
"def",
"xmlminify",
"(",
"data",
")",
":",
"parser",
"=",
"lxml",
".",
"etree",
".",
"XMLParser",
"(",
"remove_blank_text",
"=",
"True",
")",
"newdata",
"=",
"lxml",
".",
"etree",
".",
"XML",
"(",
"data",
",",
"parser",
"=",
"parser",
")",
"return",
"lxml",
".",
"etree",
".",
"tostring",
"(",
"newdata",
",",
"encoding",
"=",
"'utf-8'",
",",
"method",
"=",
"'xml'",
",",
"xml_declaration",
"=",
"True",
")"
] |
minify xml files .
|
train
| false
|
55,471
|
def qd(A, B, output='real', lwork=None, sort=None, overwrite_a=False, overwrite_b=False, check_finite=True):
(result, _) = _qd(A, B, output=output, lwork=lwork, sort=sort, overwrite_a=overwrite_a, overwrite_b=overwrite_b, check_finite=check_finite)
return (result[0], result[1], result[(-4)], result[(-3)])
|
[
"def",
"qd",
"(",
"A",
",",
"B",
",",
"output",
"=",
"'real'",
",",
"lwork",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"overwrite_a",
"=",
"False",
",",
"overwrite_b",
"=",
"False",
",",
"check_finite",
"=",
"True",
")",
":",
"(",
"result",
",",
"_",
")",
"=",
"_qd",
"(",
"A",
",",
"B",
",",
"output",
"=",
"output",
",",
"lwork",
"=",
"lwork",
",",
"sort",
"=",
"sort",
",",
"overwrite_a",
"=",
"overwrite_a",
",",
"overwrite_b",
"=",
"overwrite_b",
",",
"check_finite",
"=",
"check_finite",
")",
"return",
"(",
"result",
"[",
"0",
"]",
",",
"result",
"[",
"1",
"]",
",",
"result",
"[",
"(",
"-",
"4",
")",
"]",
",",
"result",
"[",
"(",
"-",
"3",
")",
"]",
")"
] |
qz decomposition for generalized eigenvalues of a pair of matrices .
|
train
| false
|
55,472
|
@pytest.mark.parametrize('stream', ['stdout', 'stderr'])
def test_exit_unsuccessful_output(qtbot, proc, caplog, py_proc, stream):
with caplog.at_level(logging.ERROR):
with qtbot.waitSignal(proc.finished, timeout=10000):
proc.start(*py_proc('\n import sys\n print("test", file=sys.{})\n sys.exit(1)\n '.format(stream)))
assert (len(caplog.records) == 2)
assert (caplog.records[1].msg == 'Process {}:\ntest'.format(stream))
|
[
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'stream'",
",",
"[",
"'stdout'",
",",
"'stderr'",
"]",
")",
"def",
"test_exit_unsuccessful_output",
"(",
"qtbot",
",",
"proc",
",",
"caplog",
",",
"py_proc",
",",
"stream",
")",
":",
"with",
"caplog",
".",
"at_level",
"(",
"logging",
".",
"ERROR",
")",
":",
"with",
"qtbot",
".",
"waitSignal",
"(",
"proc",
".",
"finished",
",",
"timeout",
"=",
"10000",
")",
":",
"proc",
".",
"start",
"(",
"*",
"py_proc",
"(",
"'\\n import sys\\n print(\"test\", file=sys.{})\\n sys.exit(1)\\n '",
".",
"format",
"(",
"stream",
")",
")",
")",
"assert",
"(",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"2",
")",
"assert",
"(",
"caplog",
".",
"records",
"[",
"1",
"]",
".",
"msg",
"==",
"'Process {}:\\ntest'",
".",
"format",
"(",
"stream",
")",
")"
] |
when a process fails .
|
train
| false
|
55,473
|
def generate_replace_result_xml(result_sourcedid, score):
elem = ElementMaker(nsmap={None: 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'})
xml = elem.imsx_POXEnvelopeRequest(elem.imsx_POXHeader(elem.imsx_POXRequestHeaderInfo(elem.imsx_version('V1.0'), elem.imsx_messageIdentifier(str(uuid.uuid4())))), elem.imsx_POXBody(elem.replaceResultRequest(elem.resultRecord(elem.sourcedGUID(elem.sourcedId(result_sourcedid)), elem.result(elem.resultScore(elem.language('en'), elem.textString(str(score))))))))
return etree.tostring(xml, xml_declaration=True, encoding='UTF-8')
|
[
"def",
"generate_replace_result_xml",
"(",
"result_sourcedid",
",",
"score",
")",
":",
"elem",
"=",
"ElementMaker",
"(",
"nsmap",
"=",
"{",
"None",
":",
"'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0'",
"}",
")",
"xml",
"=",
"elem",
".",
"imsx_POXEnvelopeRequest",
"(",
"elem",
".",
"imsx_POXHeader",
"(",
"elem",
".",
"imsx_POXRequestHeaderInfo",
"(",
"elem",
".",
"imsx_version",
"(",
"'V1.0'",
")",
",",
"elem",
".",
"imsx_messageIdentifier",
"(",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
")",
")",
")",
",",
"elem",
".",
"imsx_POXBody",
"(",
"elem",
".",
"replaceResultRequest",
"(",
"elem",
".",
"resultRecord",
"(",
"elem",
".",
"sourcedGUID",
"(",
"elem",
".",
"sourcedId",
"(",
"result_sourcedid",
")",
")",
",",
"elem",
".",
"result",
"(",
"elem",
".",
"resultScore",
"(",
"elem",
".",
"language",
"(",
"'en'",
")",
",",
"elem",
".",
"textString",
"(",
"str",
"(",
"score",
")",
")",
")",
")",
")",
")",
")",
")",
"return",
"etree",
".",
"tostring",
"(",
"xml",
",",
"xml_declaration",
"=",
"True",
",",
"encoding",
"=",
"'UTF-8'",
")"
] |
create the xml document that contains the new score to be sent to the lti consumer .
|
train
| false
|
55,476
|
def find_duplicative_certs(config, domains):
def update_certs_for_domain_matches(candidate_lineage, rv):
'Return cert as identical_names_cert if it matches,\n or subset_names_cert if it matches as subset\n '
(identical_names_cert, subset_names_cert) = rv
candidate_names = set(candidate_lineage.names())
if (candidate_names == set(domains)):
identical_names_cert = candidate_lineage
elif candidate_names.issubset(set(domains)):
if (subset_names_cert is None):
subset_names_cert = candidate_lineage
elif (len(candidate_names) > len(subset_names_cert.names())):
subset_names_cert = candidate_lineage
return (identical_names_cert, subset_names_cert)
return _search_lineages(config, update_certs_for_domain_matches, (None, None))
|
[
"def",
"find_duplicative_certs",
"(",
"config",
",",
"domains",
")",
":",
"def",
"update_certs_for_domain_matches",
"(",
"candidate_lineage",
",",
"rv",
")",
":",
"(",
"identical_names_cert",
",",
"subset_names_cert",
")",
"=",
"rv",
"candidate_names",
"=",
"set",
"(",
"candidate_lineage",
".",
"names",
"(",
")",
")",
"if",
"(",
"candidate_names",
"==",
"set",
"(",
"domains",
")",
")",
":",
"identical_names_cert",
"=",
"candidate_lineage",
"elif",
"candidate_names",
".",
"issubset",
"(",
"set",
"(",
"domains",
")",
")",
":",
"if",
"(",
"subset_names_cert",
"is",
"None",
")",
":",
"subset_names_cert",
"=",
"candidate_lineage",
"elif",
"(",
"len",
"(",
"candidate_names",
")",
">",
"len",
"(",
"subset_names_cert",
".",
"names",
"(",
")",
")",
")",
":",
"subset_names_cert",
"=",
"candidate_lineage",
"return",
"(",
"identical_names_cert",
",",
"subset_names_cert",
")",
"return",
"_search_lineages",
"(",
"config",
",",
"update_certs_for_domain_matches",
",",
"(",
"None",
",",
"None",
")",
")"
] |
find existing certs that duplicate the request .
|
train
| false
|
55,478
|
def make_colorizer(color):
def inner(text):
return colorizer.colorize(color, text)
return inner
|
[
"def",
"make_colorizer",
"(",
"color",
")",
":",
"def",
"inner",
"(",
"text",
")",
":",
"return",
"colorizer",
".",
"colorize",
"(",
"color",
",",
"text",
")",
"return",
"inner"
] |
creates a function that colorizes text with the given color .
|
train
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.