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 |
|---|---|---|---|---|---|
27,297 | def _get_branch_option(**kwargs):
branch = kwargs.get('branch', '')
ret = []
if branch:
log.info("Adding branch '%s'", branch)
ret.append("--branch='{0}'".format(branch))
return ret
| [
"def",
"_get_branch_option",
"(",
"**",
"kwargs",
")",
":",
"branch",
"=",
"kwargs",
".",
"get",
"(",
"'branch'",
",",
"''",
")",
"ret",
"=",
"[",
"]",
"if",
"branch",
":",
"log",
".",
"info",
"(",
"\"Adding branch '%s'\"",
",",
"branch",
")",
"ret",
... | returns a list of --branch option to be used in the yum command . | train | false |
27,299 | def object_id_validator(key, activity_dict, errors, context):
activity_type = activity_dict[('activity_type',)]
if object_id_validators.has_key(activity_type):
object_id = activity_dict[('object_id',)]
return object_id_validators[activity_type](object_id, context)
else:
raise Invalid(('There is no object_id validator for activity type "%s"' % activity_type))
| [
"def",
"object_id_validator",
"(",
"key",
",",
"activity_dict",
",",
"errors",
",",
"context",
")",
":",
"activity_type",
"=",
"activity_dict",
"[",
"(",
"'activity_type'",
",",
")",
"]",
"if",
"object_id_validators",
".",
"has_key",
"(",
"activity_type",
")",
... | validate the object_id value of an activity_dict . | train | false |
27,300 | def getGeometryPath(subName=''):
return getJoinedPath(getFabmetheusUtilitiesPath('geometry'), subName)
| [
"def",
"getGeometryPath",
"(",
"subName",
"=",
"''",
")",
":",
"return",
"getJoinedPath",
"(",
"getFabmetheusUtilitiesPath",
"(",
"'geometry'",
")",
",",
"subName",
")"
] | get the geometry directory path . | train | false |
27,302 | def test_install_folder_using_relative_path(script):
script.scratch_path.join('initools').mkdir()
script.scratch_path.join('initools', 'mock').mkdir()
pkg_path = ((script.scratch_path / 'initools') / 'mock')
pkg_path.join('setup.py').write(mock100_setup_py)
result = script.pip('install', (Path('initools') / 'mock'))
egg_folder = ((script.site_packages / 'mock-100.1-py%s.egg-info') % pyversion)
assert (egg_folder in result.files_created), str(result)
| [
"def",
"test_install_folder_using_relative_path",
"(",
"script",
")",
":",
"script",
".",
"scratch_path",
".",
"join",
"(",
"'initools'",
")",
".",
"mkdir",
"(",
")",
"script",
".",
"scratch_path",
".",
"join",
"(",
"'initools'",
",",
"'mock'",
")",
".",
"mk... | test installing a folder using pip install folder1/folder2 . | train | false |
27,305 | def test_not_browsing_error(hist):
with pytest.raises(ValueError) as error1:
hist.nextitem()
assert (str(error1.value) == 'Currently not browsing history')
with pytest.raises(ValueError) as error2:
hist.previtem()
assert (str(error2.value) == 'Currently not browsing history')
| [
"def",
"test_not_browsing_error",
"(",
"hist",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
"as",
"error1",
":",
"hist",
".",
"nextitem",
"(",
")",
"assert",
"(",
"str",
"(",
"error1",
".",
"value",
")",
"==",
"'Currently not browsing... | test that next/previtem throws a valueerror . | train | false |
27,306 | def encode_region(name):
for (tag, (language, region, iso639, iso3166)) in LANGUAGE_REGION.items():
if (region == name.capitalize()):
return iso3166
| [
"def",
"encode_region",
"(",
"name",
")",
":",
"for",
"(",
"tag",
",",
"(",
"language",
",",
"region",
",",
"iso639",
",",
"iso3166",
")",
")",
"in",
"LANGUAGE_REGION",
".",
"items",
"(",
")",
":",
"if",
"(",
"region",
"==",
"name",
".",
"capitalize"... | returns the region code for the given region name . | train | false |
27,309 | def set_autocommit(autocommit, using=None):
return get_connection(using).set_autocommit(autocommit)
| [
"def",
"set_autocommit",
"(",
"autocommit",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_autocommit",
"(",
"autocommit",
")"
] | set the autocommit status of the connection . | train | false |
27,310 | def xstrip(filename):
while xisabs(filename):
if re.match('\\w:[\\\\/]', filename):
filename = re.sub('^\\w+:[\\\\/]+', '', filename)
elif re.match('[\\\\/]', filename):
filename = re.sub('^[\\\\/]+', '', filename)
return filename
| [
"def",
"xstrip",
"(",
"filename",
")",
":",
"while",
"xisabs",
"(",
"filename",
")",
":",
"if",
"re",
".",
"match",
"(",
"'\\\\w:[\\\\\\\\/]'",
",",
"filename",
")",
":",
"filename",
"=",
"re",
".",
"sub",
"(",
"'^\\\\w+:[\\\\\\\\/]+'",
",",
"''",
",",
... | make relative path out of absolute by stripping prefixes used on linux . | train | false |
27,311 | def print_proto(d, parent=(), indent=0):
for (m, sd) in sorted(d.items(), cmp=(lambda x, y: cmp(x[0], y[0]))):
full_name_l = (parent + (m,))
full_name = '$'.join(full_name_l)
is_message_or_group = (full_name in messages_info)
if is_message_or_group:
print_message(m, sd, parent, indent)
else:
print_proto(sd, full_name_l, indent)
| [
"def",
"print_proto",
"(",
"d",
",",
"parent",
"=",
"(",
")",
",",
"indent",
"=",
"0",
")",
":",
"for",
"(",
"m",
",",
"sd",
")",
"in",
"sorted",
"(",
"d",
".",
"items",
"(",
")",
",",
"cmp",
"=",
"(",
"lambda",
"x",
",",
"y",
":",
"cmp",
... | display all protos . | train | false |
27,313 | def delete_hc(kwargs=None, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The delete_hc function must be called with -f or --function.')
if ((not kwargs) or ('name' not in kwargs)):
log.error('A name must be specified when deleting a health check.')
return False
name = kwargs['name']
conn = get_conn()
__utils__['cloud.fire_event']('event', 'delete health_check', 'salt/cloud/healthcheck/deleting', args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])
try:
result = conn.ex_destroy_healthcheck(conn.ex_get_healthcheck(name))
except ResourceNotFoundError as exc:
log.error('Health check {0} could not be found.\nThe following exception was thrown by libcloud:\n{1}'.format(name, exc), exc_info_on_loglevel=logging.DEBUG)
return False
__utils__['cloud.fire_event']('event', 'deleted health_check', 'salt/cloud/healthcheck/deleted', args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])
return result
| [
"def",
"delete_hc",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The delete_hc function must be called with -f or --function.'",
")",
"if",
"(",
"(",
"not"... | permanently delete a health check . | train | true |
27,314 | def _dotrig(a, b):
return ((a.func == b.func) and ((a.has(TrigonometricFunction) and b.has(TrigonometricFunction)) or (a.has(HyperbolicFunction) and b.has(HyperbolicFunction))))
| [
"def",
"_dotrig",
"(",
"a",
",",
"b",
")",
":",
"return",
"(",
"(",
"a",
".",
"func",
"==",
"b",
".",
"func",
")",
"and",
"(",
"(",
"a",
".",
"has",
"(",
"TrigonometricFunction",
")",
"and",
"b",
".",
"has",
"(",
"TrigonometricFunction",
")",
")"... | helper to tell whether a and b have the same sorts of symbols in them -- no need to test hyperbolic patterns against expressions that have no hyperbolics in them . | train | false |
27,316 | def test_any():
assert (not hug.validate.any(hug.validate.contains_one_of('last', 'year'), hug.validate.contains_one_of('first', 'place'))(TEST_SCHEMA))
assert hug.validate.any(hug.validate.contains_one_of('last', 'year'), hug.validate.contains_one_of('no', 'way'))(TEST_SCHEMA)
| [
"def",
"test_any",
"(",
")",
":",
"assert",
"(",
"not",
"hug",
".",
"validate",
".",
"any",
"(",
"hug",
".",
"validate",
".",
"contains_one_of",
"(",
"'last'",
",",
"'year'",
")",
",",
"hug",
".",
"validate",
".",
"contains_one_of",
"(",
"'first'",
","... | test to ensure hugs any validation function works as expected to combine validators . | train | false |
27,317 | def parse_hl_lines(expr):
if (not expr):
return []
try:
return list(map(int, expr.split()))
except ValueError:
return []
| [
"def",
"parse_hl_lines",
"(",
"expr",
")",
":",
"if",
"(",
"not",
"expr",
")",
":",
"return",
"[",
"]",
"try",
":",
"return",
"list",
"(",
"map",
"(",
"int",
",",
"expr",
".",
"split",
"(",
")",
")",
")",
"except",
"ValueError",
":",
"return",
"[... | support our syntax for emphasizing certain lines of code . | train | false |
27,318 | def source_hashed(source_filename, prepared_options, thumbnail_extension, **kwargs):
source_sha = hashlib.sha1(source_filename.encode(u'utf-8')).digest()
source_hash = base64.urlsafe_b64encode(source_sha[:9]).decode(u'utf-8')
parts = u':'.join(prepared_options[1:])
parts_sha = hashlib.sha1(parts.encode(u'utf-8')).digest()
options_hash = base64.urlsafe_b64encode(parts_sha[:6]).decode(u'utf-8')
return (u'%s_%s_%s.%s' % (source_hash, prepared_options[0], options_hash, thumbnail_extension))
| [
"def",
"source_hashed",
"(",
"source_filename",
",",
"prepared_options",
",",
"thumbnail_extension",
",",
"**",
"kwargs",
")",
":",
"source_sha",
"=",
"hashlib",
".",
"sha1",
"(",
"source_filename",
".",
"encode",
"(",
"u'utf-8'",
")",
")",
".",
"digest",
"(",... | generate a thumbnail filename of the source filename and options separately hashed . | train | true |
27,319 | def timer(*func, **kwargs):
key = kwargs.get('key', None)
test_only = kwargs.get('test_only', True)
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
if (test_only and (not settings.IN_TEST_SUITE)):
return func(*args, **kw)
else:
name = (key if key else ('%s.%s' % (func.__module__, func.__name__)))
with statsd.timer(('timer.%s' % name)):
return func(*args, **kw)
return wrapper
if func:
return decorator(func[0])
return decorator
| [
"def",
"timer",
"(",
"*",
"func",
",",
"**",
"kwargs",
")",
":",
"key",
"=",
"kwargs",
".",
"get",
"(",
"'key'",
",",
"None",
")",
"test_only",
"=",
"kwargs",
".",
"get",
"(",
"'test_only'",
",",
"True",
")",
"def",
"decorator",
"(",
"func",
")",
... | wrapper around dog_stats_api . | train | false |
27,320 | def _set_bundle_properties(bundle, root, namespace):
bundle.name = root.get('name')
| [
"def",
"_set_bundle_properties",
"(",
"bundle",
",",
"root",
",",
"namespace",
")",
":",
"bundle",
".",
"name",
"=",
"root",
".",
"get",
"(",
"'name'",
")"
] | get bundle properties from bundle xml set properties on bundle with attributes from xml etree root . | train | false |
27,324 | def X_n(n, a, x):
(n, a, x) = map(S, [n, a, x])
C = sqrt((2 / a))
return (C * sin((((pi * n) * x) / a)))
| [
"def",
"X_n",
"(",
"n",
",",
"a",
",",
"x",
")",
":",
"(",
"n",
",",
"a",
",",
"x",
")",
"=",
"map",
"(",
"S",
",",
"[",
"n",
",",
"a",
",",
"x",
"]",
")",
"C",
"=",
"sqrt",
"(",
"(",
"2",
"/",
"a",
")",
")",
"return",
"(",
"C",
"... | returns the wavefunction x_{n} for an infinite 1d box n the "principal" quantum number . | train | false |
27,326 | def inspect_response(response, spider):
Shell(spider.crawler).start(response=response)
| [
"def",
"inspect_response",
"(",
"response",
",",
"spider",
")",
":",
"Shell",
"(",
"spider",
".",
"crawler",
")",
".",
"start",
"(",
"response",
"=",
"response",
")"
] | open a shell to inspect the given response . | train | false |
27,327 | @requires_sklearn
def test_gat_plot_diagonal():
gat = _get_data()
gat.plot_diagonal()
del gat.scores_
assert_raises(RuntimeError, gat.plot)
| [
"@",
"requires_sklearn",
"def",
"test_gat_plot_diagonal",
"(",
")",
":",
"gat",
"=",
"_get_data",
"(",
")",
"gat",
".",
"plot_diagonal",
"(",
")",
"del",
"gat",
".",
"scores_",
"assert_raises",
"(",
"RuntimeError",
",",
"gat",
".",
"plot",
")"
] | test gat diagonal plot . | train | false |
27,328 | @pytest.mark.parametrize('parallel', [True, False])
def test_lstrip_whitespace(parallel, read_basic):
text = ('\n 1, 2, DCTB 3\n A, DCTB DCTB B, C\n a, b, c\n' + ' \n')
table = read_basic(text, delimiter=',', parallel=parallel)
expected = Table([['A', 'a'], ['B', 'b'], ['C', 'c']], names=('1', '2', '3'))
assert_table_equal(table, expected)
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'parallel'",
",",
"[",
"True",
",",
"False",
"]",
")",
"def",
"test_lstrip_whitespace",
"(",
"parallel",
",",
"read_basic",
")",
":",
"text",
"=",
"(",
"'\\n 1, 2, DCTB 3\\n A, DCTB DCTB B, C\\n a, ... | test to make sure the reader ignores whitespace at the beginning of fields . | train | false |
27,329 | @utils.arg('host', metavar='<host>', help='Name of host.')
@utils.arg('--target_host', metavar='<target_host>', default=None, help=_('Name of target host. If no host is specified the scheduler will select a target.'))
@utils.arg('--on-shared-storage', dest='on_shared_storage', action='store_true', default=False, help=_('Specifies whether all instances files are on shared storage'), start_version='2.0', end_version='2.13')
@utils.arg('--force', dest='force', action='store_true', default=False, help=_('Force to not verify the scheduler if a host is provided.'), start_version='2.29')
def do_host_evacuate(cs, args):
hypervisors = cs.hypervisors.search(args.host, servers=True)
response = []
for hyper in hypervisors:
if hasattr(hyper, 'servers'):
for server in hyper.servers:
response.append(_server_evacuate(cs, server, args))
utils.print_list(response, ['Server UUID', 'Evacuate Accepted', 'Error Message'])
| [
"@",
"utils",
".",
"arg",
"(",
"'host'",
",",
"metavar",
"=",
"'<host>'",
",",
"help",
"=",
"'Name of host.'",
")",
"@",
"utils",
".",
"arg",
"(",
"'--target_host'",
",",
"metavar",
"=",
"'<target_host>'",
",",
"default",
"=",
"None",
",",
"help",
"=",
... | evacuate all instances from failed host . | train | false |
27,330 | def print_octave_code(expr, **settings):
print(octave_code(expr, **settings))
| [
"def",
"print_octave_code",
"(",
"expr",
",",
"**",
"settings",
")",
":",
"print",
"(",
"octave_code",
"(",
"expr",
",",
"**",
"settings",
")",
")"
] | prints the octave representation of the given expression . | train | false |
27,332 | def update_user_details(backend, details, response, user=None, is_new=False, *args, **kwargs):
if (user is None):
return
changed = False
for (name, value) in six.iteritems(details):
if (not _ignore_field(name, is_new)):
if (value and (value != getattr(user, name, None))):
setattr(user, name, value)
changed = True
if changed:
user.save()
| [
"def",
"update_user_details",
"(",
"backend",
",",
"details",
",",
"response",
",",
"user",
"=",
"None",
",",
"is_new",
"=",
"False",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"user",
"is",
"None",
")",
":",
"return",
"changed",
"="... | update user details using data from provider . | train | false |
27,333 | def sum_signs(exprs):
is_pos = all([expr.is_positive() for expr in exprs])
is_neg = all([expr.is_negative() for expr in exprs])
return (is_pos, is_neg)
| [
"def",
"sum_signs",
"(",
"exprs",
")",
":",
"is_pos",
"=",
"all",
"(",
"[",
"expr",
".",
"is_positive",
"(",
")",
"for",
"expr",
"in",
"exprs",
"]",
")",
"is_neg",
"=",
"all",
"(",
"[",
"expr",
".",
"is_negative",
"(",
")",
"for",
"expr",
"in",
"... | give the sign resulting from summing a list of expressions . | train | false |
27,335 | def equivalent(term1, term2, subs=None):
head_type = type(term1)
if (type(term2) != head_type):
return False
elif (head_type not in (tuple, list)):
try:
return ((term1 is term2) or (term1 == term2))
except:
return False
pot1 = preorder_traversal(term1)
pot2 = preorder_traversal(term2)
subs = ({} if (subs is None) else subs)
for (t1, t2) in zip_longest(pot1, pot2, fillvalue=END):
if ((t1 is END) or (t2 is END)):
return False
elif (ishashable(t2) and (t2 in subs)):
val = subs[t2]
else:
val = t2
try:
if ((t1 is not t2) and (t1 != val)):
return False
except:
return False
return True
| [
"def",
"equivalent",
"(",
"term1",
",",
"term2",
",",
"subs",
"=",
"None",
")",
":",
"head_type",
"=",
"type",
"(",
"term1",
")",
"if",
"(",
"type",
"(",
"term2",
")",
"!=",
"head_type",
")",
":",
"return",
"False",
"elif",
"(",
"head_type",
"not",
... | determine if two terms are equivalent . | train | false |
27,336 | def get_document_content(xml_node):
pretty_indent(xml_node)
return tostring(xml_node, 'utf-8')
| [
"def",
"get_document_content",
"(",
"xml_node",
")",
":",
"pretty_indent",
"(",
"xml_node",
")",
"return",
"tostring",
"(",
"xml_node",
",",
"'utf-8'",
")"
] | print nicely formatted xml to a string . | train | false |
27,337 | def literal_compile(s):
return str(s.compile(compile_kwargs={'literal_binds': True}))
| [
"def",
"literal_compile",
"(",
"s",
")",
":",
"return",
"str",
"(",
"s",
".",
"compile",
"(",
"compile_kwargs",
"=",
"{",
"'literal_binds'",
":",
"True",
"}",
")",
")"
] | compile a sql expression with bind params inlined as literals . | train | false |
27,338 | def get_pid_from_file(program_name, pid_files_dir=None):
pidfile_path = get_pid_path(program_name, pid_files_dir)
if (not os.path.exists(pidfile_path)):
return None
pidfile = open(get_pid_path(program_name, pid_files_dir), 'r')
try:
pid = int(pidfile.readline())
except IOError:
if (not os.path.exists(pidfile_path)):
return None
raise
finally:
pidfile.close()
return pid
| [
"def",
"get_pid_from_file",
"(",
"program_name",
",",
"pid_files_dir",
"=",
"None",
")",
":",
"pidfile_path",
"=",
"get_pid_path",
"(",
"program_name",
",",
"pid_files_dir",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"pidfile_path",
")",
"... | reads the pid from <program_name> . | train | false |
27,339 | def _create_local_srs(host_ref):
create_sr(name_label='Local storage ISO', type='iso', other_config={'i18n-original-value-name_label': 'Local storage ISO', 'i18n-key': 'local-storage-iso'}, physical_size=80000, physical_utilisation=40000, virtual_allocation=80000, host_ref=host_ref)
return create_sr(name_label='Local storage', type='ext', other_config={'i18n-original-value-name_label': 'Local storage', 'i18n-key': 'local-storage'}, physical_size=40000, physical_utilisation=20000, virtual_allocation=10000, host_ref=host_ref)
| [
"def",
"_create_local_srs",
"(",
"host_ref",
")",
":",
"create_sr",
"(",
"name_label",
"=",
"'Local storage ISO'",
",",
"type",
"=",
"'iso'",
",",
"other_config",
"=",
"{",
"'i18n-original-value-name_label'",
":",
"'Local storage ISO'",
",",
"'i18n-key'",
":",
"'loc... | create an sr that looks like the one created on the local disk by default by the xenserver installer . | train | false |
27,340 | def test_conv_str_choices_valid():
param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY)
converted = argparser.type_conv(param, str, 'val1', str_choices=['val1', 'val2'])
assert (converted == 'val1')
| [
"def",
"test_conv_str_choices_valid",
"(",
")",
":",
"param",
"=",
"inspect",
".",
"Parameter",
"(",
"'foo'",
",",
"inspect",
".",
"Parameter",
".",
"POSITIONAL_ONLY",
")",
"converted",
"=",
"argparser",
".",
"type_conv",
"(",
"param",
",",
"str",
",",
"'val... | calling str type with str_choices and valid value . | train | false |
27,341 | def popular_tags_for_model(model, count=10):
content_type = ContentType.objects.get_for_model(model)
return Tag.objects.filter(taggit_taggeditem_items__content_type=content_type).annotate(item_count=Count(u'taggit_taggeditem_items')).order_by(u'-item_count')[:count]
| [
"def",
"popular_tags_for_model",
"(",
"model",
",",
"count",
"=",
"10",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"return",
"Tag",
".",
"objects",
".",
"filter",
"(",
"taggit_taggeditem_items__content_... | return a queryset of the most frequently used tags used on this model class . | train | false |
27,342 | @world.absorb
def wait_for_visible(css_selector, index=0, timeout=GLOBAL_WAIT_FOR_TIMEOUT):
wait_for(func=(lambda _: css_visible(css_selector, index)), timeout=timeout, timeout_msg='Timed out waiting for {} to be visible.'.format(css_selector))
| [
"@",
"world",
".",
"absorb",
"def",
"wait_for_visible",
"(",
"css_selector",
",",
"index",
"=",
"0",
",",
"timeout",
"=",
"GLOBAL_WAIT_FOR_TIMEOUT",
")",
":",
"wait_for",
"(",
"func",
"=",
"(",
"lambda",
"_",
":",
"css_visible",
"(",
"css_selector",
",",
"... | wait for the element to be visible in the dom . | train | false |
27,346 | def addGradientListToDocstring():
def dec(fn):
if (fn.__doc__ is not None):
fn.__doc__ = (fn.__doc__ + str(Gradients.keys()).strip('[').strip(']'))
return fn
return dec
| [
"def",
"addGradientListToDocstring",
"(",
")",
":",
"def",
"dec",
"(",
"fn",
")",
":",
"if",
"(",
"fn",
".",
"__doc__",
"is",
"not",
"None",
")",
":",
"fn",
".",
"__doc__",
"=",
"(",
"fn",
".",
"__doc__",
"+",
"str",
"(",
"Gradients",
".",
"keys",
... | decorator to add list of current pre-defined gradients to the end of a function docstring . | train | false |
27,348 | def sign_file(file_obj, server):
endpoint = get_endpoint(server)
if (not endpoint):
log.info(u'Not signing file {0}: no active endpoint'.format(file_obj.pk))
return
if (not os.path.exists(file_obj.file_path)):
log.info(u"File {0} doesn't exist on disk".format(file_obj.file_path))
return
if (file_obj.version.addon.guid in settings.HOTFIX_ADDON_GUIDS):
log.info(u'Not signing file {0}: addon is a hotfix'.format(file_obj.pk))
return
if file_obj.is_multi_package:
log.info(u'Not signing file {0}: multi-package XPI'.format(file_obj.pk))
return
if (not supports_firefox(file_obj)):
log.info(u'Not signing version {0}: not for a Firefox version we support'.format(file_obj.version.pk))
return
cert_serial_num = unicode(call_signing(file_obj, endpoint))
size = storage.size(file_obj.file_path)
file_obj.update(cert_serial_num=cert_serial_num, hash=file_obj.generate_hash(), is_signed=True, size=size)
log.info(u'Signing complete for file {0}'.format(file_obj.pk))
return file_obj
| [
"def",
"sign_file",
"(",
"file_obj",
",",
"server",
")",
":",
"endpoint",
"=",
"get_endpoint",
"(",
"server",
")",
"if",
"(",
"not",
"endpoint",
")",
":",
"log",
".",
"info",
"(",
"u'Not signing file {0}: no active endpoint'",
".",
"format",
"(",
"file_obj",
... | sign a file . | train | false |
27,349 | def set_serv_parms(service, args):
import _winreg
uargs = []
for arg in args:
uargs.append(unicoder(arg))
try:
key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, (_SERVICE_KEY + service))
_winreg.SetValueEx(key, _SERVICE_PARM, None, _winreg.REG_MULTI_SZ, uargs)
_winreg.CloseKey(key)
except WindowsError:
return False
return True
| [
"def",
"set_serv_parms",
"(",
"service",
",",
"args",
")",
":",
"import",
"_winreg",
"uargs",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"uargs",
".",
"append",
"(",
"unicoder",
"(",
"arg",
")",
")",
"try",
":",
"key",
"=",
"_winreg",
".",
"Cr... | set the service command line parameters in registry . | train | false |
27,350 | @cache_permission
def can_update_translation(user, project):
return check_permission(user, project, 'trans.update_translation')
| [
"@",
"cache_permission",
"def",
"can_update_translation",
"(",
"user",
",",
"project",
")",
":",
"return",
"check_permission",
"(",
"user",
",",
"project",
",",
"'trans.update_translation'",
")"
] | checks whether user can update translation repository . | train | false |
27,351 | def tridi_inverse_iteration(d, e, w, x0=None, rtol=1e-08):
eig_diag = (d - w)
if (x0 is None):
x0 = np.random.randn(len(d))
x_prev = np.zeros_like(x0)
norm_x = np.linalg.norm(x0)
x0 /= norm_x
while (np.linalg.norm((np.abs(x0) - np.abs(x_prev))) > rtol):
x_prev = x0.copy()
tridisolve(eig_diag, e, x0)
norm_x = np.linalg.norm(x0)
x0 /= norm_x
return x0
| [
"def",
"tridi_inverse_iteration",
"(",
"d",
",",
"e",
",",
"w",
",",
"x0",
"=",
"None",
",",
"rtol",
"=",
"1e-08",
")",
":",
"eig_diag",
"=",
"(",
"d",
"-",
"w",
")",
"if",
"(",
"x0",
"is",
"None",
")",
":",
"x0",
"=",
"np",
".",
"random",
".... | perform an inverse iteration . | train | true |
27,352 | def filter_none_values(value):
result = dict([(k, v) for (k, v) in value.items() if (v != 'None')])
return result
| [
"def",
"filter_none_values",
"(",
"value",
")",
":",
"result",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"value",
".",
"items",
"(",
")",
"if",
"(",
"v",
"!=",
"'None'",
")",
"]",
")",
"return",
"re... | filter out string "none" values from the provided dict . | train | false |
27,355 | def _common_path(p1, p2):
while (p1 and p2):
if (p1 == p2):
return p1
if (len(p1) > len(p2)):
p1 = os.path.dirname(p1)
else:
p2 = os.path.dirname(p2)
return ''
| [
"def",
"_common_path",
"(",
"p1",
",",
"p2",
")",
":",
"while",
"(",
"p1",
"and",
"p2",
")",
":",
"if",
"(",
"p1",
"==",
"p2",
")",
":",
"return",
"p1",
"if",
"(",
"len",
"(",
"p1",
")",
">",
"len",
"(",
"p2",
")",
")",
":",
"p1",
"=",
"o... | returns the longest path common to p1 and p2 . | train | false |
27,356 | def mutating(func):
@functools.wraps(func)
def wrapped(self, req, *args, **kwargs):
if req.context.read_only:
msg = _('Read-only access')
LOG.debug(msg)
raise exc.HTTPForbidden(msg, request=req, content_type='text/plain')
return func(self, req, *args, **kwargs)
return wrapped
| [
"def",
"mutating",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"self",
",",
"req",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"req",
".",
"context",
".",
"read_only",
":",
"msg",
"="... | decorator to enforce read-only logic . | train | false |
27,358 | def get_page_instance(context):
possible_names = [PAGE_TEMPLATE_VAR, u'self']
for name in possible_names:
if (name in context):
page = context[name]
if isinstance(page, Page):
return page
| [
"def",
"get_page_instance",
"(",
"context",
")",
":",
"possible_names",
"=",
"[",
"PAGE_TEMPLATE_VAR",
",",
"u'self'",
"]",
"for",
"name",
"in",
"possible_names",
":",
"if",
"(",
"name",
"in",
"context",
")",
":",
"page",
"=",
"context",
"[",
"name",
"]",
... | given a template context . | train | false |
27,359 | def getLoopsFromCorrectMesh(edges, faces, vertexes, z):
remainingEdgeTable = getRemainingEdgeTable(edges, vertexes, z)
remainingValues = remainingEdgeTable.values()
for edge in remainingValues:
if (len(edge.faceIndexes) < 2):
print 'This should never happen, there is a hole in the triangle mesh, each edge should have two faces.'
print edge
print 'Something will still be printed, but there is no guarantee that it will be the correct shape.'
print 'Once the gcode is saved, you should check over the layer with a z of:'
print z
return []
loops = []
while isPathAdded(edges, faces, loops, remainingEdgeTable, vertexes, z):
pass
if euclidean.isLoopListIntersecting(loops):
print 'Warning, the triangle mesh slice intersects itself in getLoopsFromCorrectMesh in triangle_mesh.'
print 'Something will still be printed, but there is no guarantee that it will be the correct shape.'
print 'Once the gcode is saved, you should check over the layer with a z of:'
print z
return []
return loops
| [
"def",
"getLoopsFromCorrectMesh",
"(",
"edges",
",",
"faces",
",",
"vertexes",
",",
"z",
")",
":",
"remainingEdgeTable",
"=",
"getRemainingEdgeTable",
"(",
"edges",
",",
"vertexes",
",",
"z",
")",
"remainingValues",
"=",
"remainingEdgeTable",
".",
"values",
"(",... | get loops from a carve of a correct mesh . | train | false |
27,361 | def create_model_tables(models, **create_table_kwargs):
for m in sort_models_topologically(models):
m.create_table(**create_table_kwargs)
| [
"def",
"create_model_tables",
"(",
"models",
",",
"**",
"create_table_kwargs",
")",
":",
"for",
"m",
"in",
"sort_models_topologically",
"(",
"models",
")",
":",
"m",
".",
"create_table",
"(",
"**",
"create_table_kwargs",
")"
] | create tables for all given models . | train | false |
27,363 | def get_s3_content_and_delete(bucket, path, with_key=False):
if is_botocore():
import botocore.session
session = botocore.session.get_session()
client = session.create_client('s3')
key = client.get_object(Bucket=bucket, Key=path)
content = key['Body'].read()
client.delete_object(Bucket=bucket, Key=path)
else:
import boto
bucket = boto.connect_s3().get_bucket(bucket, validate=False)
key = bucket.get_key(path)
content = key.get_contents_as_string()
bucket.delete_key(path)
return ((content, key) if with_key else content)
| [
"def",
"get_s3_content_and_delete",
"(",
"bucket",
",",
"path",
",",
"with_key",
"=",
"False",
")",
":",
"if",
"is_botocore",
"(",
")",
":",
"import",
"botocore",
".",
"session",
"session",
"=",
"botocore",
".",
"session",
".",
"get_session",
"(",
")",
"cl... | get content from s3 key . | train | false |
27,364 | def logdet_symm(m, check_symm=False):
from scipy import linalg
if check_symm:
if (not np.all((m == m.T))):
raise ValueError('m is not symmetric.')
(c, _) = linalg.cho_factor(m, lower=True)
return (2 * np.sum(np.log(c.diagonal())))
| [
"def",
"logdet_symm",
"(",
"m",
",",
"check_symm",
"=",
"False",
")",
":",
"from",
"scipy",
"import",
"linalg",
"if",
"check_symm",
":",
"if",
"(",
"not",
"np",
".",
"all",
"(",
"(",
"m",
"==",
"m",
".",
"T",
")",
")",
")",
":",
"raise",
"ValueEr... | return log(det(m)) asserting positive definiteness of m . | train | false |
27,365 | def safe_no_dnn_algo_bwd(algo):
if algo:
raise RuntimeError('The option `dnn.conv.algo_bwd` has been removed and should not be used anymore. Please use the options `dnn.conv.algo_bwd_filter` and `dnn.conv.algo_bwd_data` instead.')
return True
| [
"def",
"safe_no_dnn_algo_bwd",
"(",
"algo",
")",
":",
"if",
"algo",
":",
"raise",
"RuntimeError",
"(",
"'The option `dnn.conv.algo_bwd` has been removed and should not be used anymore. Please use the options `dnn.conv.algo_bwd_filter` and `dnn.conv.algo_bwd_data` instead.'",
")",
"return... | make sure the user is not attempting to use dnn . | train | false |
27,366 | def time_to_epoch(t):
if isinstance(t, int):
return t
elif (isinstance(t, tuple) or isinstance(t, time.struct_time)):
return int(time.mktime(t))
elif hasattr(t, 'timetuple'):
return int(time.mktime(t.timetuple()))
elif hasattr(t, 'strftime'):
return int(t.strftime('%s'))
elif (isinstance(t, str) or isinstance(t, unicode)):
try:
if t.startswith('+'):
return (time.time() + int(t[1:]))
return int(t)
except ValueError:
try:
return time.strptime(t)
except ValueError as ex:
debug('Failed to parse date with strptime: %s', ex)
pass
raise S3.Exceptions.ParameterError(("Unable to convert %r to an epoch time. Pass an epoch time. Try `date -d 'now + 1 year' +%%s` (shell) or time.mktime (Python)." % t))
| [
"def",
"time_to_epoch",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"int",
")",
":",
"return",
"t",
"elif",
"(",
"isinstance",
"(",
"t",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"t",
",",
"time",
".",
"struct_time",
")",
")",
":",
"... | convert time specified in a variety of forms into unix epoch time . | train | false |
27,367 | def unique_id(name):
return '{0}-{1}-{2}'.format(name, int(time.time()), random.randint(0, 10000))
| [
"def",
"unique_id",
"(",
"name",
")",
":",
"return",
"'{0}-{1}-{2}'",
".",
"format",
"(",
"name",
",",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"random",
".",
"randint",
"(",
"0",
",",
"10000",
")",
")"
] | generates an unique id . | train | false |
27,369 | def test_basic_call_on_method_registering_without_decorator_coroutine():
class API(object, ):
def __init__(self):
hug.call()(self.hello_world_method)
@asyncio.coroutine
def hello_world_method(self):
return 'Hello World!'
api_instance = API()
assert (loop.run_until_complete(api_instance.hello_world_method()) == 'Hello World!')
assert (hug.test.get(api, '/hello_world_method').data == 'Hello World!')
| [
"def",
"test_basic_call_on_method_registering_without_decorator_coroutine",
"(",
")",
":",
"class",
"API",
"(",
"object",
",",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"hug",
".",
"call",
"(",
")",
"(",
"self",
".",
"hello_world_method",
")",
"@",
... | test to ensure instance method calling via async works as expected . | train | false |
27,371 | def json_to_dict(x):
if (x.find('callback') > (-1)):
pos_lb = x.find('{')
pos_rb = x.find('}')
x = x[pos_lb:(pos_rb + 1)]
try:
if (type(x) != str):
x = x.decode('utf-8')
return json.loads(x, encoding='utf-8')
except:
return x
| [
"def",
"json_to_dict",
"(",
"x",
")",
":",
"if",
"(",
"x",
".",
"find",
"(",
"'callback'",
")",
">",
"(",
"-",
"1",
")",
")",
":",
"pos_lb",
"=",
"x",
".",
"find",
"(",
"'{'",
")",
"pos_rb",
"=",
"x",
".",
"find",
"(",
"'}'",
")",
"x",
"=",... | oauthresponse class cant parse the json data with content-type - text/html and because of a rubbish api . | train | false |
27,372 | def get_framework_by_id(framework_id):
for fw in get_frameworks():
if (fw.get_id() == framework_id):
return fw
return None
| [
"def",
"get_framework_by_id",
"(",
"framework_id",
")",
":",
"for",
"fw",
"in",
"get_frameworks",
"(",
")",
":",
"if",
"(",
"fw",
".",
"get_id",
"(",
")",
"==",
"framework_id",
")",
":",
"return",
"fw",
"return",
"None"
] | return framework instance associated with given id . | train | false |
27,374 | def delete_file(path, fileName=None):
if fileName:
path = os.path.join(path, fileName)
if os.path.isfile(path):
os.remove(path)
| [
"def",
"delete_file",
"(",
"path",
",",
"fileName",
"=",
"None",
")",
":",
"if",
"fileName",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"fileName",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"os",... | delete file from public folder . | train | false |
27,376 | def secure_cookie():
return (request.environ['wsgi.url_scheme'] == 'https')
| [
"def",
"secure_cookie",
"(",
")",
":",
"return",
"(",
"request",
".",
"environ",
"[",
"'wsgi.url_scheme'",
"]",
"==",
"'https'",
")"
] | return true if cookie should have secure attribute . | train | false |
27,377 | def print_tag(tag, decode, outstream=sys.stdout):
outstream.write((('Tagger: ' + decode(tag.tagger)) + '\n'))
outstream.write((('Date: ' + decode(tag.tag_time)) + '\n'))
outstream.write('\n')
outstream.write((decode(tag.message) + '\n'))
outstream.write('\n')
| [
"def",
"print_tag",
"(",
"tag",
",",
"decode",
",",
"outstream",
"=",
"sys",
".",
"stdout",
")",
":",
"outstream",
".",
"write",
"(",
"(",
"(",
"'Tagger: '",
"+",
"decode",
"(",
"tag",
".",
"tagger",
")",
")",
"+",
"'\\n'",
")",
")",
"outstream",
"... | write a human-readable tag . | train | false |
27,378 | def sqrtm(M):
r = real_if_close(expm2((0.5 * logm(M))), 1e-08)
return ((r + r.T) / 2)
| [
"def",
"sqrtm",
"(",
"M",
")",
":",
"r",
"=",
"real_if_close",
"(",
"expm2",
"(",
"(",
"0.5",
"*",
"logm",
"(",
"M",
")",
")",
")",
",",
"1e-08",
")",
"return",
"(",
"(",
"r",
"+",
"r",
".",
"T",
")",
"/",
"2",
")"
] | returns the symmetric semi-definite positive square root of a matrix . | train | false |
27,379 | def distrib_family():
distrib = distrib_id()
if (distrib in ['Debian', 'Ubuntu', 'LinuxMint', 'elementary OS']):
return 'debian'
elif (distrib in ['RHEL', 'CentOS', 'SLES', 'Fedora']):
return 'redhat'
elif (distrib in ['SunOS']):
return 'sun'
elif (distrib in ['Gentoo']):
return 'gentoo'
elif (distrib in ['Arch', 'ManjaroLinux']):
return 'arch'
elif (distrib in ['SUSE']):
return 'suse'
else:
return 'other'
| [
"def",
"distrib_family",
"(",
")",
":",
"distrib",
"=",
"distrib_id",
"(",
")",
"if",
"(",
"distrib",
"in",
"[",
"'Debian'",
",",
"'Ubuntu'",
",",
"'LinuxMint'",
",",
"'elementary OS'",
"]",
")",
":",
"return",
"'debian'",
"elif",
"(",
"distrib",
"in",
"... | get the distribution family . | train | false |
27,380 | def test_mark_done_invariant():
seg = make_segment(1, explicit=True)
with pytest.raises(exception.UserCritical):
seg.mark_done()
| [
"def",
"test_mark_done_invariant",
"(",
")",
":",
"seg",
"=",
"make_segment",
"(",
"1",
",",
"explicit",
"=",
"True",
")",
"with",
"pytest",
".",
"raises",
"(",
"exception",
".",
"UserCritical",
")",
":",
"seg",
".",
"mark_done",
"(",
")"
] | check explicit segments cannot be . | train | false |
27,381 | def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize):
unnumbered = set(G)
if (s is None):
s = random.choice(list(unnumbered))
unnumbered.remove(s)
numbered = set([s])
current_treewidth = (-1)
while unnumbered:
v = _max_cardinality_node(G, unnumbered, numbered)
unnumbered.remove(v)
numbered.add(v)
clique_wanna_be = (set(G[v]) & numbered)
sg = G.subgraph(clique_wanna_be)
if _is_complete_graph(sg):
current_treewidth = max(current_treewidth, len(clique_wanna_be))
if (current_treewidth > treewidth_bound):
raise nx.NetworkXTreewidthBoundExceeded(('treewidth_bound exceeded: %s' % current_treewidth))
else:
(u, w) = _find_missing_edge(sg)
return (u, v, w)
return ()
| [
"def",
"_find_chordality_breaker",
"(",
"G",
",",
"s",
"=",
"None",
",",
"treewidth_bound",
"=",
"sys",
".",
"maxsize",
")",
":",
"unnumbered",
"=",
"set",
"(",
"G",
")",
"if",
"(",
"s",
"is",
"None",
")",
":",
"s",
"=",
"random",
".",
"choice",
"(... | given a graph g . | train | false |
27,382 | def select_template(template_name_list):
not_found = []
for template_name in template_name_list:
try:
return get_template(template_name)
except TemplateDoesNotExist as e:
if (e.args[0] not in not_found):
not_found.append(e.args[0])
continue
raise TemplateDoesNotExist(', '.join(not_found))
| [
"def",
"select_template",
"(",
"template_name_list",
")",
":",
"not_found",
"=",
"[",
"]",
"for",
"template_name",
"in",
"template_name_list",
":",
"try",
":",
"return",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
"as",
"e",
":",
... | try to load one of the given templates . | train | false |
27,383 | def define_service(service_descriptor, module):
class_dict = {'__module__': module.__name__}
class_name = service_descriptor.name.encode('utf-8')
for method_descriptor in (service_descriptor.methods or []):
request_definition = messages.find_definition(method_descriptor.request_type, module)
response_definition = messages.find_definition(method_descriptor.response_type, module)
method_name = method_descriptor.name.encode('utf-8')
def remote_method(self, request):
'Actual service method.'
raise NotImplementedError('Method is not implemented')
remote_method.__name__ = method_name
remote_method_decorator = remote.method(request_definition, response_definition)
class_dict[method_name] = remote_method_decorator(remote_method)
service_class = type(class_name, (remote.Service,), class_dict)
return service_class
| [
"def",
"define_service",
"(",
"service_descriptor",
",",
"module",
")",
":",
"class_dict",
"=",
"{",
"'__module__'",
":",
"module",
".",
"__name__",
"}",
"class_name",
"=",
"service_descriptor",
".",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"method_d... | define a new service proxy . | train | false |
27,384 | def mae(actual, predicted):
return np.mean(ae(actual, predicted))
| [
"def",
"mae",
"(",
"actual",
",",
"predicted",
")",
":",
"return",
"np",
".",
"mean",
"(",
"ae",
"(",
"actual",
",",
"predicted",
")",
")"
] | computes the mean absolute error . | train | false |
27,385 | def get_course_about_section(request, course, section_key):
html_sections = {'short_description', 'description', 'key_dates', 'video', 'course_staff_short', 'course_staff_extended', 'requirements', 'syllabus', 'textbook', 'faq', 'more_info', 'overview', 'effort', 'end_date', 'prerequisites', 'ocw_links'}
if (section_key in html_sections):
try:
loc = course.location.replace(category='about', name=section_key)
field_data_cache = FieldDataCache([], course.id, request.user)
about_module = get_module(request.user, request, loc, field_data_cache, log_if_not_found=False, wrap_xmodule_display=False, static_asset_path=course.static_asset_path, course=course)
html = ''
if (about_module is not None):
try:
html = about_module.render(STUDENT_VIEW).content
except Exception:
html = render_to_string('courseware/error-message.html', None)
log.exception(u'Error rendering course=%s, section_key=%s', course, section_key)
return html
except ItemNotFoundError:
log.warning(u'Missing about section %s in course %s', section_key, course.location.to_deprecated_string())
return None
raise KeyError(('Invalid about key ' + str(section_key)))
| [
"def",
"get_course_about_section",
"(",
"request",
",",
"course",
",",
"section_key",
")",
":",
"html_sections",
"=",
"{",
"'short_description'",
",",
"'description'",
",",
"'key_dates'",
",",
"'video'",
",",
"'course_staff_short'",
",",
"'course_staff_extended'",
","... | this returns the snippet of html to be rendered on the course about page . | train | false |
27,388 | def is_valid_ipv4_prefix(ipv4_prefix):
if (not isinstance(ipv4_prefix, str)):
return False
tokens = ipv4_prefix.split('/')
if (len(tokens) != 2):
return False
return (is_valid_ipv4(tokens[0]) and is_valid_ip_prefix(tokens[1], 32))
| [
"def",
"is_valid_ipv4_prefix",
"(",
"ipv4_prefix",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"ipv4_prefix",
",",
"str",
")",
")",
":",
"return",
"False",
"tokens",
"=",
"ipv4_prefix",
".",
"split",
"(",
"'/'",
")",
"if",
"(",
"len",
"(",
"tokens",
... | returns true if *ipv4_prefix* is a valid prefix with mask . | train | true |
27,389 | def encode_language(name):
for (tag, (language, region, iso639, iso3166)) in LANGUAGE_REGION.items():
if (language == name.capitalize()):
return iso639
| [
"def",
"encode_language",
"(",
"name",
")",
":",
"for",
"(",
"tag",
",",
"(",
"language",
",",
"region",
",",
"iso639",
",",
"iso3166",
")",
")",
"in",
"LANGUAGE_REGION",
".",
"items",
"(",
")",
":",
"if",
"(",
"language",
"==",
"name",
".",
"capital... | returns the language code for the given language name . | train | false |
27,390 | def polygon_bounds(points):
(minx, miny) = (points[0][0], points[0][1])
(maxx, maxy) = (minx, miny)
for p in points:
minx = min(minx, p[0])
maxx = max(maxx, p[0])
miny = min(miny, p[1])
maxy = max(maxy, p[1])
return (minx, miny, (maxx - minx), (maxy - miny))
| [
"def",
"polygon_bounds",
"(",
"points",
")",
":",
"(",
"minx",
",",
"miny",
")",
"=",
"(",
"points",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"points",
"[",
"0",
"]",
"[",
"1",
"]",
")",
"(",
"maxx",
",",
"maxy",
")",
"=",
"(",
"minx",
",",
"miny... | return bounding box of a polygon in form . | train | true |
27,391 | def get_zendesk():
zendesk_url = settings.ZENDESK_URL
zendesk_email = settings.ZENDESK_USER_EMAIL
zendesk_password = settings.ZENDESK_USER_PASSWORD
if ((not zendesk_url) or (not zendesk_email) or (not zendesk_password)):
log.error('Zendesk settings error: please set ZENDESK_URL, ZENDESK_USER_EMAIL and ZENDESK_USER_PASSWORD.')
statsd.incr('questions.zendesk.settingserror')
raise ZendeskSettingsError('Missing Zendesk settings.')
return Zendesk(zendesk_url, zendesk_email, zendesk_password, api_version=2)
| [
"def",
"get_zendesk",
"(",
")",
":",
"zendesk_url",
"=",
"settings",
".",
"ZENDESK_URL",
"zendesk_email",
"=",
"settings",
".",
"ZENDESK_USER_EMAIL",
"zendesk_password",
"=",
"settings",
".",
"ZENDESK_USER_PASSWORD",
"if",
"(",
"(",
"not",
"zendesk_url",
")",
"or"... | instantiate and return a zendesk client . | train | false |
27,392 | def next_month(t):
now = time.localtime(t)
month = (now.tm_mon + 1)
year = now.tm_year
if (month > 12):
month = 1
year += 1
ntime = (year, month, 1, 0, 0, 0, 0, 0, now[8])
return time.mktime(ntime)
| [
"def",
"next_month",
"(",
"t",
")",
":",
"now",
"=",
"time",
".",
"localtime",
"(",
"t",
")",
"month",
"=",
"(",
"now",
".",
"tm_mon",
"+",
"1",
")",
"year",
"=",
"now",
".",
"tm_year",
"if",
"(",
"month",
">",
"12",
")",
":",
"month",
"=",
"... | return timestamp for start of next month . | train | false |
27,393 | def all_timeseries_index_generator(k=10):
make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex]
for make_index_func in make_index_funcs:
(yield make_index_func(k=k))
| [
"def",
"all_timeseries_index_generator",
"(",
"k",
"=",
"10",
")",
":",
"make_index_funcs",
"=",
"[",
"makeDateIndex",
",",
"makePeriodIndex",
",",
"makeTimedeltaIndex",
"]",
"for",
"make_index_func",
"in",
"make_index_funcs",
":",
"(",
"yield",
"make_index_func",
"... | generator which can be iterated over to get instances of all the classes which represent time-seires . | train | false |
27,394 | def test_badapp():
def badapp(environ, start_response):
start_response('200 OK', [])
raise HTTPBadRequest('Do not do this at home.')
newapp = HTTPExceptionHandler(badapp)
assert ('Bad Request' in ''.join(newapp({'HTTP_ACCEPT': 'text/html'}, (lambda a, b, c=None: None))))
| [
"def",
"test_badapp",
"(",
")",
":",
"def",
"badapp",
"(",
"environ",
",",
"start_response",
")",
":",
"start_response",
"(",
"'200 OK'",
",",
"[",
"]",
")",
"raise",
"HTTPBadRequest",
"(",
"'Do not do this at home.'",
")",
"newapp",
"=",
"HTTPExceptionHandler",... | verify that the middleware handles previously-started responses . | train | false |
27,396 | def smembers(key, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return list(server.smembers(key))
| [
"def",
"smembers",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"li... | get members in a redis set cli example: . | train | true |
27,398 | def is_x86_architecture():
if ('86' in platform.machine()):
return True
else:
return False
| [
"def",
"is_x86_architecture",
"(",
")",
":",
"if",
"(",
"'86'",
"in",
"platform",
".",
"machine",
"(",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | return true if the architecture is x86 . | train | false |
27,399 | @jingo.register.function
def showing(query, pager):
format_opts = (pager.start_index(), pager.end_index(), pager.paginator.count)
query = escape(query)
if query:
showing = _(u'Showing {0} - {1} of {2} results for <strong>{3}</strong>').format(*(format_opts + (query,)))
else:
showing = _(u'Showing {0} - {1} of {2} results').format(*format_opts)
return jinja2.Markup(showing)
| [
"@",
"jingo",
".",
"register",
".",
"function",
"def",
"showing",
"(",
"query",
",",
"pager",
")",
":",
"format_opts",
"=",
"(",
"pager",
".",
"start_index",
"(",
")",
",",
"pager",
".",
"end_index",
"(",
")",
",",
"pager",
".",
"paginator",
".",
"co... | writes a string that tells the user what they are seeing in terms of search results . | train | false |
27,403 | def start_flask_app(host, port):
app.run(host=host, port=port)
app.config['DEBUG'] = False
app.config['TESTING'] = False
| [
"def",
"start_flask_app",
"(",
"host",
",",
"port",
")",
":",
"app",
".",
"run",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
")",
"app",
".",
"config",
"[",
"'DEBUG'",
"]",
"=",
"False",
"app",
".",
"config",
"[",
"'TESTING'",
"]",
"=",
"... | runs the server . | train | false |
27,404 | def test_sobel_horizontal():
(i, j) = np.mgrid[(-5):6, (-5):6]
image = (i >= 0).astype(float)
result = (filters.sobel(image) * np.sqrt(2))
i[(np.abs(j) == 5)] = 10000
assert_allclose(result[(i == 0)], 1)
assert np.all((result[(np.abs(i) > 1)] == 0))
| [
"def",
"test_sobel_horizontal",
"(",
")",
":",
"(",
"i",
",",
"j",
")",
"=",
"np",
".",
"mgrid",
"[",
"(",
"-",
"5",
")",
":",
"6",
",",
"(",
"-",
"5",
")",
":",
"6",
"]",
"image",
"=",
"(",
"i",
">=",
"0",
")",
".",
"astype",
"(",
"float... | sobel on a horizontal edge should be a horizontal line . | train | false |
27,405 | def get_precision(currency):
global _cache
if (_cache is None):
_cache = _generate_cache()
return _cache[currency]
| [
"def",
"get_precision",
"(",
"currency",
")",
":",
"global",
"_cache",
"if",
"(",
"_cache",
"is",
"None",
")",
":",
"_cache",
"=",
"_generate_cache",
"(",
")",
"return",
"_cache",
"[",
"currency",
"]"
] | get precision for a given field . | train | false |
27,406 | def _GetMimeType(file_name):
extension_index = file_name.rfind('.')
if (extension_index == (-1)):
extension = ''
else:
extension = file_name[(extension_index + 1):].lower()
if (extension in EXTENSION_BLACKLIST):
raise InvalidAttachmentTypeError(('Extension %s is not supported.' % extension))
mime_type = EXTENSION_MIME_MAP.get(extension, None)
if (mime_type is None):
mime_type = 'application/octet-stream'
return mime_type
| [
"def",
"_GetMimeType",
"(",
"file_name",
")",
":",
"extension_index",
"=",
"file_name",
".",
"rfind",
"(",
"'.'",
")",
"if",
"(",
"extension_index",
"==",
"(",
"-",
"1",
")",
")",
":",
"extension",
"=",
"''",
"else",
":",
"extension",
"=",
"file_name",
... | determine mime-type from file name . | train | false |
27,407 | def test_lwta_yaml():
limited_epoch_train(os.path.join(pylearn2.__path__[0], 'models/tests/lwta.yaml'))
| [
"def",
"test_lwta_yaml",
"(",
")",
":",
"limited_epoch_train",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pylearn2",
".",
"__path__",
"[",
"0",
"]",
",",
"'models/tests/lwta.yaml'",
")",
")"
] | test simple model on random data . | train | false |
27,408 | def monitor_folders(registry, xml_parent, data):
ft = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.fstrigger.triggers.FolderContentTrigger')
ft.set('plugin', 'fstrigger')
mappings = [('path', 'path', ''), ('cron', 'spec', '')]
convert_mapping_to_xml(ft, data, mappings, fail_required=True)
includes = data.get('includes', '')
XML.SubElement(ft, 'includes').text = ','.join(includes)
XML.SubElement(ft, 'excludes').text = data.get('excludes', '')
XML.SubElement(ft, 'excludeCheckLastModificationDate').text = str((not data.get('check-modification-date', True))).lower()
XML.SubElement(ft, 'excludeCheckContent').text = str((not data.get('check-content', True))).lower()
XML.SubElement(ft, 'excludeCheckFewerOrMoreFiles').text = str((not data.get('check-fewer', True))).lower()
| [
"def",
"monitor_folders",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"ft",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'org.jenkinsci.plugins.fstrigger.triggers.FolderContentTrigger'",
")",
"ft",
".",
"set",
"(",
"'plugin'",
",",
"'fstr... | yaml: monitor-folders configure jenkins to monitor folders . | train | false |
27,412 | def absolute_symlink(source_path, target_path):
if (not os.path.isabs(source_path)):
raise ValueError(u'Path for source : {} must be absolute'.format(source_path))
if (not os.path.isabs(target_path)):
raise ValueError(u'Path for link : {} must be absolute'.format(target_path))
if (source_path == target_path):
raise ValueError(u'Path for link is identical to source : {}'.format(source_path))
try:
if os.path.lexists(target_path):
if (os.path.islink(target_path) or os.path.isfile(target_path)):
os.unlink(target_path)
else:
shutil.rmtree(target_path)
safe_mkdir_for(target_path)
os.symlink(source_path, target_path)
except OSError as e:
if (not ((e.errno == errno.EEXIST) or (e.errno == errno.ENOENT))):
raise
| [
"def",
"absolute_symlink",
"(",
"source_path",
",",
"target_path",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"source_path",
")",
")",
":",
"raise",
"ValueError",
"(",
"u'Path for source : {} must be absolute'",
".",
"format",
"(",
"sour... | create a symlink at target pointing to source using the absolute path . | train | true |
27,413 | def srs_output(func, argtypes):
func.argtypes = argtypes
func.restype = c_void_p
func.errcheck = check_srs
return func
| [
"def",
"srs_output",
"(",
"func",
",",
"argtypes",
")",
":",
"func",
".",
"argtypes",
"=",
"argtypes",
"func",
".",
"restype",
"=",
"c_void_p",
"func",
".",
"errcheck",
"=",
"check_srs",
"return",
"func"
] | generates a ctypes prototype for the given function with the given c arguments that returns a pointer to an ogr spatial reference system . | train | false |
27,414 | def cifarnet_arg_scope(weight_decay=0.004):
with slim.arg_scope([slim.conv2d], weights_initializer=tf.truncated_normal_initializer(stddev=0.05), activation_fn=tf.nn.relu):
with slim.arg_scope([slim.fully_connected], biases_initializer=tf.constant_initializer(0.1), weights_initializer=trunc_normal(0.04), weights_regularizer=slim.l2_regularizer(weight_decay), activation_fn=tf.nn.relu) as sc:
return sc
| [
"def",
"cifarnet_arg_scope",
"(",
"weight_decay",
"=",
"0.004",
")",
":",
"with",
"slim",
".",
"arg_scope",
"(",
"[",
"slim",
".",
"conv2d",
"]",
",",
"weights_initializer",
"=",
"tf",
".",
"truncated_normal_initializer",
"(",
"stddev",
"=",
"0.05",
")",
","... | defines the default cifarnet argument scope . | train | false |
27,415 | def _without_most_central_edges(G, most_valuable_edge):
original_num_components = nx.number_connected_components(G)
num_new_components = original_num_components
while (num_new_components <= original_num_components):
edge = most_valuable_edge(G)
G.remove_edge(*edge)
new_components = tuple(nx.connected_components(G))
num_new_components = len(new_components)
return new_components
| [
"def",
"_without_most_central_edges",
"(",
"G",
",",
"most_valuable_edge",
")",
":",
"original_num_components",
"=",
"nx",
".",
"number_connected_components",
"(",
"G",
")",
"num_new_components",
"=",
"original_num_components",
"while",
"(",
"num_new_components",
"<=",
... | returns the connected components of the graph that results from repeatedly removing the most "valuable" edge in the graph . | train | false |
27,417 | def intranges_contain(int_, ranges):
tuple_ = (int_, int_)
pos = bisect.bisect_left(ranges, tuple_)
if (pos > 0):
(left, right) = ranges[(pos - 1)]
if (left <= int_ < right):
return True
if (pos < len(ranges)):
(left, _) = ranges[pos]
if (left == int_):
return True
return False
| [
"def",
"intranges_contain",
"(",
"int_",
",",
"ranges",
")",
":",
"tuple_",
"=",
"(",
"int_",
",",
"int_",
")",
"pos",
"=",
"bisect",
".",
"bisect_left",
"(",
"ranges",
",",
"tuple_",
")",
"if",
"(",
"pos",
">",
"0",
")",
":",
"(",
"left",
",",
"... | determine if int_ falls into one of the ranges in ranges . | train | true |
27,418 | def setDefaultFetcher(fetcher, wrap_exceptions=True):
global _default_fetcher
if ((fetcher is None) or (not wrap_exceptions)):
_default_fetcher = fetcher
else:
_default_fetcher = ExceptionWrappingFetcher(fetcher)
| [
"def",
"setDefaultFetcher",
"(",
"fetcher",
",",
"wrap_exceptions",
"=",
"True",
")",
":",
"global",
"_default_fetcher",
"if",
"(",
"(",
"fetcher",
"is",
"None",
")",
"or",
"(",
"not",
"wrap_exceptions",
")",
")",
":",
"_default_fetcher",
"=",
"fetcher",
"el... | set the default fetcher . | train | true |
27,420 | def comment_requirement(req):
return any(((ign in req) for ign in COMMENT_REQUIREMENTS))
| [
"def",
"comment_requirement",
"(",
"req",
")",
":",
"return",
"any",
"(",
"(",
"(",
"ign",
"in",
"req",
")",
"for",
"ign",
"in",
"COMMENT_REQUIREMENTS",
")",
")"
] | some requirements dont install on all systems . | train | false |
27,421 | def image_snapshot_delete(call=None, kwargs=None):
if (call != 'function'):
raise SaltCloudSystemExit('The image_snapshot_delete function must be called with -f or --function.')
if (kwargs is None):
kwargs = {}
image_id = kwargs.get('image_id', None)
image_name = kwargs.get('image_name', None)
snapshot_id = kwargs.get('snapshot_id', None)
if (snapshot_id is None):
raise SaltCloudSystemExit("The image_snapshot_delete function requires a 'snapshot_id' to be provided.")
if image_id:
if image_name:
log.warning("Both the 'image_id' and 'image_name' arguments were provided. 'image_id' will take precedence.")
elif image_name:
image_id = get_image_id(kwargs={'name': image_name})
else:
raise SaltCloudSystemExit("The image_snapshot_delete function requires either an 'image_id' or a 'image_name' to be provided.")
(server, user, password) = _get_xml_rpc()
auth = ':'.join([user, password])
response = server.one.image.snapshotdelete(auth, int(image_id), int(snapshot_id))
data = {'action': 'image.snapshotdelete', 'deleted': response[0], 'snapshot_id': response[1], 'error_code': response[2]}
return data
| [
"def",
"image_snapshot_delete",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The image_snapshot_delete function must be called with -f or --function.'",
")",
"if... | deletes a snapshot from the image . | train | true |
27,422 | @register.filter(is_safe=False)
def unlocalize(value):
return force_text(value)
| [
"@",
"register",
".",
"filter",
"(",
"is_safe",
"=",
"False",
")",
"def",
"unlocalize",
"(",
"value",
")",
":",
"return",
"force_text",
"(",
"value",
")"
] | forces a value to be rendered as a non-localized value . | train | false |
27,425 | def read_var(*args):
ret = {}
try:
for arg in args:
log.debug('Querying: %s', arg)
cmd = '{0} {1} {2}'.format(_TRAFFICLINE, '-r', arg)
ret[arg] = _subprocess(cmd)
except KeyError:
pass
return ret
| [
"def",
"read_var",
"(",
"*",
"args",
")",
":",
"ret",
"=",
"{",
"}",
"try",
":",
"for",
"arg",
"in",
"args",
":",
"log",
".",
"debug",
"(",
"'Querying: %s'",
",",
"arg",
")",
"cmd",
"=",
"'{0} {1} {2}'",
".",
"format",
"(",
"_TRAFFICLINE",
",",
"'-... | read variable definitions from the traffic_line command . | train | false |
27,426 | def include_enabled_extensions(settings):
from django.db.models.loading import load_app
from django.db import DatabaseError
from reviewboard.extensions.base import get_extension_manager
try:
manager = get_extension_manager()
except DatabaseError:
return
for extension in manager.get_enabled_extensions():
load_app(extension.info.app_name)
| [
"def",
"include_enabled_extensions",
"(",
"settings",
")",
":",
"from",
"django",
".",
"db",
".",
"models",
".",
"loading",
"import",
"load_app",
"from",
"django",
".",
"db",
"import",
"DatabaseError",
"from",
"reviewboard",
".",
"extensions",
".",
"base",
"im... | this adds enabled extensions to the installed_apps cache so that operations like syncdb and evolve will take extensions into consideration . | train | false |
27,427 | @pytest.mark.parametrize('value', ['foo\\bar', 'fo\xc3\xb6\r\nb\xc3\xa4r', 'fo\xc3\xb6\\r\\nb\xc3\xa4r', 'fo\xc3\xb6\r\n\\r\\nb\xc3\xa4r', 'nfo\xc3\xb6\nb\xc3\xa4r', 'nfo\xc3\xb6\\nb\xc3\xa4r', 'fo\xc3\xb6\n\\nb\xc3\xa4r'])
def test_multistringwidget_decompress_strings(value):
widget = MultiStringWidget()
assert (widget.decompress(value) == [value])
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'value'",
",",
"[",
"'foo\\\\bar'",
",",
"'fo\\xc3\\xb6\\r\\nb\\xc3\\xa4r'",
",",
"'fo\\xc3\\xb6\\\\r\\\\nb\\xc3\\xa4r'",
",",
"'fo\\xc3\\xb6\\r\\n\\\\r\\\\nb\\xc3\\xa4r'",
",",
"'nfo\\xc3\\xb6\\nb\\xc3\\xa4r'",
",",
"'nfo... | tests units multistringwidget decompresses string values . | train | false |
27,428 | def add_classifier_layer(net, num_outputs):
net_classifier = Network((net.sizes + [num_outputs]))
net_classifier.weights[:(-1)] = net.weights
net_classifier.biases[:(-1)] = net.biases
return net_classifier
| [
"def",
"add_classifier_layer",
"(",
"net",
",",
"num_outputs",
")",
":",
"net_classifier",
"=",
"Network",
"(",
"(",
"net",
".",
"sizes",
"+",
"[",
"num_outputs",
"]",
")",
")",
"net_classifier",
".",
"weights",
"[",
":",
"(",
"-",
"1",
")",
"]",
"=",
... | return the network net . | train | false |
27,429 | def extract_bits(data, shift, length):
bitmask = (((1 << length) - 1) << shift)
return ((data & bitmask) >> shift)
| [
"def",
"extract_bits",
"(",
"data",
",",
"shift",
",",
"length",
")",
":",
"bitmask",
"=",
"(",
"(",
"(",
"1",
"<<",
"length",
")",
"-",
"1",
")",
"<<",
"shift",
")",
"return",
"(",
"(",
"data",
"&",
"bitmask",
")",
">>",
"shift",
")"
] | extract a portion of a bit string . | train | false |
27,430 | def plane(individual):
return (individual[0],)
| [
"def",
"plane",
"(",
"individual",
")",
":",
"return",
"(",
"individual",
"[",
"0",
"]",
",",
")"
] | plane test objective function . | train | false |
27,431 | def build_header(prim, webdir=''):
try:
uptime = calc_age(sabnzbd.START)
except:
uptime = '-'
if prim:
color = sabnzbd.WEB_COLOR
else:
color = sabnzbd.WEB_COLOR2
if (not color):
color = ''
header = {'T': Ttemplate, 'Tspec': Tspec, 'Tx': Ttemplate, 'version': sabnzbd.__version__, 'paused': (Downloader.do.paused or Downloader.do.postproc), 'pause_int': scheduler.pause_int(), 'paused_all': sabnzbd.PAUSED_ALL, 'uptime': uptime, 'color_scheme': color}
speed_limit = Downloader.do.get_limit()
if (speed_limit <= 0):
speed_limit = 100
speed_limit_abs = Downloader.do.get_limit_abs()
if (speed_limit_abs <= 0):
speed_limit_abs = ''
free1 = diskfree(cfg.download_dir.get_path())
free2 = diskfree(cfg.complete_dir.get_path())
header['helpuri'] = 'https://sabnzbd.org/wiki/'
header['diskspace1'] = ('%.2f' % free1)
header['diskspace2'] = ('%.2f' % free2)
header['diskspace1_norm'] = to_units((free1 * GIGI))
header['diskspace2_norm'] = to_units((free2 * GIGI))
header['diskspacetotal1'] = ('%.2f' % disktotal(cfg.download_dir.get_path()))
header['diskspacetotal2'] = ('%.2f' % disktotal(cfg.complete_dir.get_path()))
header['loadavg'] = loadavg()
header['speedlimit'] = '{1:0.{0}f}'.format(int(((speed_limit % 1) > 0)), speed_limit)
header['speedlimit_abs'] = ('%s' % speed_limit_abs)
header['restart_req'] = sabnzbd.RESTART_REQ
header['have_warnings'] = str(sabnzbd.GUIHANDLER.count())
header['last_warning'] = sabnzbd.GUIHANDLER.last().replace('WARNING', 'WARNING:').replace('ERROR', T('ERROR:'))
header['active_lang'] = cfg.language()
header['my_lcldata'] = sabnzbd.DIR_LCLDATA
header['my_home'] = sabnzbd.DIR_HOME
header['webdir'] = webdir
header['pid'] = os.getpid()
header['finishaction'] = sabnzbd.QUEUECOMPLETE
header['nt'] = sabnzbd.WIN32
header['darwin'] = sabnzbd.DARWIN
header['power_options'] = (sabnzbd.WIN32 or sabnzbd.DARWIN or sabnzbd.LINUX_POWER)
header['session'] = cfg.api_key()
header['quota'] = to_units(BPSMeter.do.quota)
header['have_quota'] = bool((BPSMeter.do.quota > 0.0))
header['left_quota'] = to_units(BPSMeter.do.left)
anfo = ArticleCache.do.cache_info()
header['cache_art'] = str(anfo.article_sum)
header['cache_size'] = format_bytes(anfo.cache_size)
header['cache_max'] = str(anfo.cache_limit)
header['pp_pause_event'] = sabnzbd.scheduler.pp_pause_event()
if sabnzbd.NEW_VERSION:
(header['new_release'], header['new_rel_url']) = sabnzbd.NEW_VERSION
else:
header['new_release'] = ''
header['new_rel_url'] = ''
return header
| [
"def",
"build_header",
"(",
"prim",
",",
"webdir",
"=",
"''",
")",
":",
"try",
":",
"uptime",
"=",
"calc_age",
"(",
"sabnzbd",
".",
"START",
")",
"except",
":",
"uptime",
"=",
"'-'",
"if",
"prim",
":",
"color",
"=",
"sabnzbd",
".",
"WEB_COLOR",
"else... | build a header from a list of fields . | train | false |
27,433 | @plugins.command('new')
@click.argument('plugin_identifier', callback=check_cookiecutter)
@click.option('--template', '-t', type=click.STRING, default='https://github.com/sh4nks/cookiecutter-flaskbb-plugin', help='Path to a cookiecutter template or to a valid git repo.')
def new_plugin(plugin_identifier, template):
out_dir = os.path.join(current_app.root_path, 'plugins', plugin_identifier)
click.secho('[+] Creating new plugin {}'.format(plugin_identifier), fg='cyan')
cookiecutter(template, output_dir=out_dir)
click.secho('[+] Done. Created in {}'.format(out_dir), fg='green', bold=True)
| [
"@",
"plugins",
".",
"command",
"(",
"'new'",
")",
"@",
"click",
".",
"argument",
"(",
"'plugin_identifier'",
",",
"callback",
"=",
"check_cookiecutter",
")",
"@",
"click",
".",
"option",
"(",
"'--template'",
",",
"'-t'",
",",
"type",
"=",
"click",
".",
... | creates a new plugin based on the cookiecutter plugin template . | train | false |
27,434 | def define_enum(enum_descriptor, module_name):
enum_values = (enum_descriptor.values or [])
class_dict = dict(((value.name, value.number) for value in enum_values))
class_dict['__module__'] = module_name
return type(str(enum_descriptor.name), (messages.Enum,), class_dict)
| [
"def",
"define_enum",
"(",
"enum_descriptor",
",",
"module_name",
")",
":",
"enum_values",
"=",
"(",
"enum_descriptor",
".",
"values",
"or",
"[",
"]",
")",
"class_dict",
"=",
"dict",
"(",
"(",
"(",
"value",
".",
"name",
",",
"value",
".",
"number",
")",
... | define enum class from descriptor . | train | false |
27,436 | def get_constr_expr(lh_op, rh_op):
if (rh_op is None):
return lh_op
else:
return sum_expr([lh_op, neg_expr(rh_op)])
| [
"def",
"get_constr_expr",
"(",
"lh_op",
",",
"rh_op",
")",
":",
"if",
"(",
"rh_op",
"is",
"None",
")",
":",
"return",
"lh_op",
"else",
":",
"return",
"sum_expr",
"(",
"[",
"lh_op",
",",
"neg_expr",
"(",
"rh_op",
")",
"]",
")"
] | returns the operator in the constraint . | train | false |
27,437 | def quality(mime_type, ranges):
parsed_ranges = map(parse_media_range, ranges.split(','))
return quality_parsed(mime_type, parsed_ranges)
| [
"def",
"quality",
"(",
"mime_type",
",",
"ranges",
")",
":",
"parsed_ranges",
"=",
"map",
"(",
"parse_media_range",
",",
"ranges",
".",
"split",
"(",
"','",
")",
")",
"return",
"quality_parsed",
"(",
"mime_type",
",",
"parsed_ranges",
")"
] | returns the quality q of a mime-type when compared against the media-ranges in ranges . | train | false |
27,438 | def awscli_initialize(cli):
cli.register('building-command-table.main', add_s3)
cli.register('building-command-table.sync', register_sync_strategies)
| [
"def",
"awscli_initialize",
"(",
"cli",
")",
":",
"cli",
".",
"register",
"(",
"'building-command-table.main'",
",",
"add_s3",
")",
"cli",
".",
"register",
"(",
"'building-command-table.sync'",
",",
"register_sync_strategies",
")"
] | this function is require to use the plugin . | train | false |
27,439 | def is_prerequisite(course_key, prereq_content_key):
return (get_gating_milestone(course_key, prereq_content_key, 'fulfills') is not None)
| [
"def",
"is_prerequisite",
"(",
"course_key",
",",
"prereq_content_key",
")",
":",
"return",
"(",
"get_gating_milestone",
"(",
"course_key",
",",
"prereq_content_key",
",",
"'fulfills'",
")",
"is",
"not",
"None",
")"
] | returns true if there is at least one coursecontentmilestone which the given course content fulfills arguments: course_key : the course key prereq_content_key : the prerequisite content usage key returns: bool: true if the course content fulfills a coursecontentmilestone . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.