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 |
|---|---|---|---|---|---|
31,907 | def unbake_lazy_loaders():
strategies.LazyLoader._strategy_keys[:] = []
BakedLazyLoader._strategy_keys[:] = []
properties.RelationshipProperty.strategy_for(lazy='select')(strategies.LazyLoader)
properties.RelationshipProperty.strategy_for(lazy=True)(strategies.LazyLoader)
properties.RelationshipProperty.strategy_for(lazy='baked_select')(BakedLazyLoader)
assert strategies.LazyLoader._strategy_keys
| [
"def",
"unbake_lazy_loaders",
"(",
")",
":",
"strategies",
".",
"LazyLoader",
".",
"_strategy_keys",
"[",
":",
"]",
"=",
"[",
"]",
"BakedLazyLoader",
".",
"_strategy_keys",
"[",
":",
"]",
"=",
"[",
"]",
"properties",
".",
"RelationshipProperty",
".",
"strate... | disable the use of baked queries for all lazyloaders systemwide . | train | false |
31,908 | def _track_update_email_opt_in(user_id, organization, opt_in):
event_name = ('edx.bi.user.org_email.opted_in' if opt_in else 'edx.bi.user.org_email.opted_out')
tracking_context = tracker.get_tracker().resolve_context()
analytics.track(user_id, event_name, {'category': 'communication', 'label': organization}, context={'ip': tracking_context.get('ip'), 'Google Analytics': {'clientId': tracking_context.get('client_id')}})
| [
"def",
"_track_update_email_opt_in",
"(",
"user_id",
",",
"organization",
",",
"opt_in",
")",
":",
"event_name",
"=",
"(",
"'edx.bi.user.org_email.opted_in'",
"if",
"opt_in",
"else",
"'edx.bi.user.org_email.opted_out'",
")",
"tracking_context",
"=",
"tracker",
".",
"get... | track an email opt-in preference change . | train | false |
31,909 | def get_color_dict():
return _color_dict.copy()
| [
"def",
"get_color_dict",
"(",
")",
":",
"return",
"_color_dict",
".",
"copy",
"(",
")"
] | returns a dictionary of colours using the provided values as keys . | train | false |
31,910 | def get_xls(columns, data):
stream = StringIO.StringIO()
workbook = xlwt.Workbook()
sheet = workbook.add_sheet(_(u'Sheet 1'))
dateformat = xlwt.easyxf(num_format_str=(frappe.defaults.get_global_default(u'date_format') or u'yyyy-mm-dd'))
bold = xlwt.easyxf(u'font: bold 1')
for (i, col) in enumerate(columns):
sheet.write(0, i, col.label, bold)
for (i, row) in enumerate(data):
for (j, df) in enumerate(columns):
f = None
val = row[columns[j].fieldname]
if isinstance(val, (datetime.datetime, datetime.date)):
f = dateformat
if f:
sheet.write((i + 1), j, val, f)
else:
sheet.write((i + 1), j, frappe.format(val, df, row))
workbook.save(stream)
stream.seek(0)
return stream.read()
| [
"def",
"get_xls",
"(",
"columns",
",",
"data",
")",
":",
"stream",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"workbook",
"=",
"xlwt",
".",
"Workbook",
"(",
")",
"sheet",
"=",
"workbook",
".",
"add_sheet",
"(",
"_",
"(",
"u'Sheet 1'",
")",
")",
"dat... | convert data to xls . | train | false |
31,911 | def get_variables_in_module(module, collection=tf.GraphKeys.TRAINABLE_VARIABLES):
return get_variables_in_scope(module.var_scope, collection=collection)
| [
"def",
"get_variables_in_module",
"(",
"module",
",",
"collection",
"=",
"tf",
".",
"GraphKeys",
".",
"TRAINABLE_VARIABLES",
")",
":",
"return",
"get_variables_in_scope",
"(",
"module",
".",
"var_scope",
",",
"collection",
"=",
"collection",
")"
] | returns tuple of tf . | train | false |
31,912 | def _check_if_pyc(fname):
from imp import find_module
from os.path import realpath, dirname, basename, splitext
filepath = realpath(fname)
dirpath = dirname(filepath)
module_name = splitext(basename(filepath))[0]
try:
(fileobj, fullpath, (_, _, pytype)) = find_module(module_name, [dirpath])
except ImportError:
raise IOError('Cannot find config file. Path maybe incorrect! : {0}'.format(filepath))
return (pytype, fileobj, fullpath)
| [
"def",
"_check_if_pyc",
"(",
"fname",
")",
":",
"from",
"imp",
"import",
"find_module",
"from",
"os",
".",
"path",
"import",
"realpath",
",",
"dirname",
",",
"basename",
",",
"splitext",
"filepath",
"=",
"realpath",
"(",
"fname",
")",
"dirpath",
"=",
"dirn... | return true if the extension is . | train | false |
31,913 | def get_all_filters():
for name in FILTERS:
(yield name)
for (name, _) in find_plugin_filters():
(yield name)
| [
"def",
"get_all_filters",
"(",
")",
":",
"for",
"name",
"in",
"FILTERS",
":",
"(",
"yield",
"name",
")",
"for",
"(",
"name",
",",
"_",
")",
"in",
"find_plugin_filters",
"(",
")",
":",
"(",
"yield",
"name",
")"
] | return a generator of all filter names . | train | false |
31,915 | def FromReferenceProperty(value):
assert isinstance(value, entity_pb.PropertyValue)
assert value.has_referencevalue()
ref = value.referencevalue()
key = Key()
key_ref = key._Key__reference
key_ref.set_app(ref.app())
SetNamespace(key_ref, ref.name_space())
for pathelem in ref.pathelement_list():
key_ref.mutable_path().add_element().CopyFrom(pathelem)
return key
| [
"def",
"FromReferenceProperty",
"(",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"entity_pb",
".",
"PropertyValue",
")",
"assert",
"value",
".",
"has_referencevalue",
"(",
")",
"ref",
"=",
"value",
".",
"referencevalue",
"(",
")",
"key",
"=... | converts a reference propertyvalue to a key . | train | false |
31,916 | def k_corona(G, k, core_number=None):
def func(v, k, c):
return ((c[v] == k) and (k == sum((1 for w in G[v] if (c[w] >= k)))))
return _core_subgraph(G, func, k, core_number)
| [
"def",
"k_corona",
"(",
"G",
",",
"k",
",",
"core_number",
"=",
"None",
")",
":",
"def",
"func",
"(",
"v",
",",
"k",
",",
"c",
")",
":",
"return",
"(",
"(",
"c",
"[",
"v",
"]",
"==",
"k",
")",
"and",
"(",
"k",
"==",
"sum",
"(",
"(",
"1",
... | return the k-corona of g . | train | false |
31,918 | def create_datastore_write_config(mapreduce_spec):
force_writes = parse_bool(mapreduce_spec.params.get('force_writes', 'false'))
if force_writes:
return datastore_rpc.Configuration(force_writes=force_writes)
else:
return datastore_rpc.Configuration()
| [
"def",
"create_datastore_write_config",
"(",
"mapreduce_spec",
")",
":",
"force_writes",
"=",
"parse_bool",
"(",
"mapreduce_spec",
".",
"params",
".",
"get",
"(",
"'force_writes'",
",",
"'false'",
")",
")",
"if",
"force_writes",
":",
"return",
"datastore_rpc",
"."... | creates datastore config to use in write operations . | train | true |
31,919 | def combine_common_sections(data):
sections = []
sections_dict = {}
for each in data:
if (each[u'label'] not in sections_dict):
sections_dict[each[u'label']] = each
sections.append(each)
else:
sections_dict[each[u'label']][u'items'] += each[u'items']
return sections
| [
"def",
"combine_common_sections",
"(",
"data",
")",
":",
"sections",
"=",
"[",
"]",
"sections_dict",
"=",
"{",
"}",
"for",
"each",
"in",
"data",
":",
"if",
"(",
"each",
"[",
"u'label'",
"]",
"not",
"in",
"sections_dict",
")",
":",
"sections_dict",
"[",
... | combine sections declared in separate apps . | train | false |
31,921 | def _cluster_has_pending_steps(steps):
return any(((step.status.state == 'PENDING') for step in steps))
| [
"def",
"_cluster_has_pending_steps",
"(",
"steps",
")",
":",
"return",
"any",
"(",
"(",
"(",
"step",
".",
"status",
".",
"state",
"==",
"'PENDING'",
")",
"for",
"step",
"in",
"steps",
")",
")"
] | does *cluster* have any steps in the pending state? . | train | false |
31,922 | def sort_sample_ids_by_mapping_value(mapping_file, field, field_type_f=float):
(data, headers, comments) = parse_mapping_file(mapping_file)
try:
column = headers.index(field)
except ValueError:
raise ValueError(('Column (%s) not found in mapping file headers:\n %s' % (field, ' '.join(headers))))
results = [(e[0], field_type_f(e[column])) for e in data]
results.sort(key=itemgetter(1))
return results
| [
"def",
"sort_sample_ids_by_mapping_value",
"(",
"mapping_file",
",",
"field",
",",
"field_type_f",
"=",
"float",
")",
":",
"(",
"data",
",",
"headers",
",",
"comments",
")",
"=",
"parse_mapping_file",
"(",
"mapping_file",
")",
"try",
":",
"column",
"=",
"heade... | return list of sample ids sorted by ascending value from mapping file . | train | false |
31,923 | def skipIfNotFramework(framework):
key = 'DIGITS_TEST_FRAMEWORK'
if ((key in os.environ) and (os.environ[key] != framework)):
raise unittest.SkipTest(('Skipping because %s is "%s" and not "%s"' % (key, os.environ[key], framework)))
| [
"def",
"skipIfNotFramework",
"(",
"framework",
")",
":",
"key",
"=",
"'DIGITS_TEST_FRAMEWORK'",
"if",
"(",
"(",
"key",
"in",
"os",
".",
"environ",
")",
"and",
"(",
"os",
".",
"environ",
"[",
"key",
"]",
"!=",
"framework",
")",
")",
":",
"raise",
"unitt... | raises skiptest if digits_test_framework is set to something other than framework . | train | false |
31,924 | def drop_empty_translationprojects(apps, schema_editor):
Directory = apps.get_model(u'pootle_app.Directory')
TP = apps.get_model(u'pootle_translationproject.TranslationProject')
for tp in TP.objects.all():
if (not Directory.objects.filter(pootle_path=tp.pootle_path).exists()):
tp.delete()
| [
"def",
"drop_empty_translationprojects",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Directory",
"=",
"apps",
".",
"get_model",
"(",
"u'pootle_app.Directory'",
")",
"TP",
"=",
"apps",
".",
"get_model",
"(",
"u'pootle_translationproject.TranslationProject'",
")",
"fo... | drop tps with no directories . | train | false |
31,925 | def is_graphical(sequence, method='eg'):
if (method == 'eg'):
valid = is_valid_degree_sequence_erdos_gallai(list(sequence))
elif (method == 'hh'):
valid = is_valid_degree_sequence_havel_hakimi(list(sequence))
else:
msg = "`method` must be 'eg' or 'hh'"
raise nx.NetworkXException(msg)
return valid
| [
"def",
"is_graphical",
"(",
"sequence",
",",
"method",
"=",
"'eg'",
")",
":",
"if",
"(",
"method",
"==",
"'eg'",
")",
":",
"valid",
"=",
"is_valid_degree_sequence_erdos_gallai",
"(",
"list",
"(",
"sequence",
")",
")",
"elif",
"(",
"method",
"==",
"'hh'",
... | returns true if sequence is a valid degree sequence . | train | false |
31,926 | def preseed_package(pkg_name, preseed):
for (q_name, _) in preseed.items():
(q_type, q_answer) = _
run_as_root(('echo "%(pkg_name)s %(q_name)s %(q_type)s %(q_answer)s" | debconf-set-selections' % locals()))
| [
"def",
"preseed_package",
"(",
"pkg_name",
",",
"preseed",
")",
":",
"for",
"(",
"q_name",
",",
"_",
")",
"in",
"preseed",
".",
"items",
"(",
")",
":",
"(",
"q_type",
",",
"q_answer",
")",
"=",
"_",
"run_as_root",
"(",
"(",
"'echo \"%(pkg_name)s %(q_name... | enable unattended package installation by preseeding debconf parameters . | train | true |
31,927 | def _base64_to_hex(identity, check_if_fingerprint=True):
missing_padding = (len(identity) % 4)
identity += ('=' * missing_padding)
try:
identity_decoded = base64.b64decode(stem.util.str_tools._to_bytes(identity))
except (TypeError, binascii.Error):
raise ValueError(("Unable to decode identity string '%s'" % identity))
fingerprint = binascii.b2a_hex(identity_decoded).upper()
if stem.prereq.is_python_3():
fingerprint = stem.util.str_tools._to_unicode(fingerprint)
if check_if_fingerprint:
if (not stem.util.tor_tools.is_valid_fingerprint(fingerprint)):
raise ValueError(("Decoded '%s' to be '%s', which isn't a valid fingerprint" % (identity, fingerprint)))
return fingerprint
| [
"def",
"_base64_to_hex",
"(",
"identity",
",",
"check_if_fingerprint",
"=",
"True",
")",
":",
"missing_padding",
"=",
"(",
"len",
"(",
"identity",
")",
"%",
"4",
")",
"identity",
"+=",
"(",
"'='",
"*",
"missing_padding",
")",
"try",
":",
"identity_decoded",
... | decodes a base64 value to hex . | train | false |
31,928 | def all_pairs_bellman_ford_path(G, cutoff=None, weight='weight'):
path = single_source_bellman_ford_path
return {n: path(G, n, cutoff=cutoff, weight=weight) for n in G}
| [
"def",
"all_pairs_bellman_ford_path",
"(",
"G",
",",
"cutoff",
"=",
"None",
",",
"weight",
"=",
"'weight'",
")",
":",
"path",
"=",
"single_source_bellman_ford_path",
"return",
"{",
"n",
":",
"path",
"(",
"G",
",",
"n",
",",
"cutoff",
"=",
"cutoff",
",",
... | compute shortest paths between all nodes in a weighted graph . | train | false |
31,929 | def srcroute_enable(rt_table, ipaddr):
run(settings.ip, 'rule', 'add', 'from', ipaddr, 'table', rt_table)
run(settings.ip, 'route', 'flush', 'cache')
| [
"def",
"srcroute_enable",
"(",
"rt_table",
",",
"ipaddr",
")",
":",
"run",
"(",
"settings",
".",
"ip",
",",
"'rule'",
",",
"'add'",
",",
"'from'",
",",
"ipaddr",
",",
"'table'",
",",
"rt_table",
")",
"run",
"(",
"settings",
".",
"ip",
",",
"'route'",
... | enable routing policy for specified source ip address . | train | false |
31,931 | def translate_js(js, HEADER=DEFAULT_HEADER, use_compilation_plan=False):
if (use_compilation_plan and (not ('//' in js)) and (not ('/*' in js))):
return translate_js_with_compilation_plan(js, HEADER=HEADER)
parser = pyjsparser.PyJsParser()
parsed = parser.parse(js)
translating_nodes.clean_stacks()
return (HEADER + translating_nodes.trans(parsed))
| [
"def",
"translate_js",
"(",
"js",
",",
"HEADER",
"=",
"DEFAULT_HEADER",
",",
"use_compilation_plan",
"=",
"False",
")",
":",
"if",
"(",
"use_compilation_plan",
"and",
"(",
"not",
"(",
"'//'",
"in",
"js",
")",
")",
"and",
"(",
"not",
"(",
"'/*'",
"in",
... | js has to be a javascript source code . | train | true |
31,932 | def __TimeZoneKeyNameWorkaround(name):
try:
return name[:name.index('\x00')]
except ValueError:
return name
| [
"def",
"__TimeZoneKeyNameWorkaround",
"(",
"name",
")",
":",
"try",
":",
"return",
"name",
"[",
":",
"name",
".",
"index",
"(",
"'\\x00'",
")",
"]",
"except",
"ValueError",
":",
"return",
"name"
] | it may be a bug in vista . | train | false |
31,933 | def dist_is_editable(dist):
for path_item in sys.path:
egg_link = os.path.join(path_item, (dist.project_name + '.egg-link'))
if os.path.isfile(egg_link):
return True
return False
| [
"def",
"dist_is_editable",
"(",
"dist",
")",
":",
"for",
"path_item",
"in",
"sys",
".",
"path",
":",
"egg_link",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path_item",
",",
"(",
"dist",
".",
"project_name",
"+",
"'.egg-link'",
")",
")",
"if",
"os",
"... | is distribution an editable install? . | train | true |
31,934 | def config_read_reseller_options(conf, defaults):
reseller_prefix_opt = conf.get('reseller_prefix', 'AUTH').split(',')
reseller_prefixes = []
for prefix in [pre.strip() for pre in reseller_prefix_opt if pre.strip()]:
if (prefix == "''"):
prefix = ''
prefix = append_underscore(prefix)
if (prefix not in reseller_prefixes):
reseller_prefixes.append(prefix)
if (len(reseller_prefixes) == 0):
reseller_prefixes.append('')
associated_options = {}
for prefix in reseller_prefixes:
associated_options[prefix] = dict(defaults)
associated_options[prefix].update(config_read_prefixed_options(conf, '', defaults))
prefix_name = (prefix if (prefix != '') else "''")
associated_options[prefix].update(config_read_prefixed_options(conf, prefix_name, defaults))
return (reseller_prefixes, associated_options)
| [
"def",
"config_read_reseller_options",
"(",
"conf",
",",
"defaults",
")",
":",
"reseller_prefix_opt",
"=",
"conf",
".",
"get",
"(",
"'reseller_prefix'",
",",
"'AUTH'",
")",
".",
"split",
"(",
"','",
")",
"reseller_prefixes",
"=",
"[",
"]",
"for",
"prefix",
"... | read reseller_prefix option and associated options from configuration reads the reseller_prefix option . | train | false |
31,935 | def make_null_event_date_events(all_sids, timestamp):
return pd.DataFrame({'sid': all_sids, 'timestamp': timestamp, 'event_date': pd.Timestamp('NaT'), 'float': (-9999.0), 'int': (-9999), 'datetime': pd.Timestamp('1980'), 'string': 'should be ignored'})
| [
"def",
"make_null_event_date_events",
"(",
"all_sids",
",",
"timestamp",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"{",
"'sid'",
":",
"all_sids",
",",
"'timestamp'",
":",
"timestamp",
",",
"'event_date'",
":",
"pd",
".",
"Timestamp",
"(",
"'NaT'",
")"... | make an event with a null event_date for all sids . | train | false |
31,936 | def plotHistogram(freqCounts, title='On-Times Histogram', xLabel='On-Time'):
import pylab
pylab.ion()
pylab.figure()
pylab.bar((numpy.arange(len(freqCounts)) - 0.5), freqCounts)
pylab.title(title)
pylab.xlabel(xLabel)
| [
"def",
"plotHistogram",
"(",
"freqCounts",
",",
"title",
"=",
"'On-Times Histogram'",
",",
"xLabel",
"=",
"'On-Time'",
")",
":",
"import",
"pylab",
"pylab",
".",
"ion",
"(",
")",
"pylab",
".",
"figure",
"(",
")",
"pylab",
".",
"bar",
"(",
"(",
"numpy",
... | this is usually used to display a histogram of the on-times encountered in a particular output . | train | true |
31,938 | def asnumpy(a, stream=None):
if isinstance(a, ndarray):
return a.get(stream=stream)
else:
return numpy.asarray(a)
| [
"def",
"asnumpy",
"(",
"a",
",",
"stream",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"ndarray",
")",
":",
"return",
"a",
".",
"get",
"(",
"stream",
"=",
"stream",
")",
"else",
":",
"return",
"numpy",
".",
"asarray",
"(",
"a",
")"
... | returns an array on the host memory from an arbitrary source array . | train | false |
31,939 | def is_prereg_admin(user):
if (user is not None):
return (PREREG_ADMIN_TAG in getattr(user, 'system_tags', []))
return False
| [
"def",
"is_prereg_admin",
"(",
"user",
")",
":",
"if",
"(",
"user",
"is",
"not",
"None",
")",
":",
"return",
"(",
"PREREG_ADMIN_TAG",
"in",
"getattr",
"(",
"user",
",",
"'system_tags'",
",",
"[",
"]",
")",
")",
"return",
"False"
] | returns true if user has reviewer permissions . | train | false |
31,940 | @pytest.mark.skipif("sys.platform == 'win32'")
@pytest.mark.network
def test_check_submodule_addition(script):
(module_path, submodule_path) = _create_test_package_with_submodule(script)
install_result = script.pip('install', '-e', (('git+' + module_path) + '#egg=version_pkg'))
assert ((script.venv / 'src/version-pkg/testpkg/static/testfile') in install_result.files_created)
_change_test_package_submodule(script, submodule_path)
_pull_in_submodule_changes_to_module(script, module_path)
update_result = script.pip('install', '-e', (('git+' + module_path) + '#egg=version_pkg'), '--upgrade', expect_error=True)
assert ((script.venv / 'src/version-pkg/testpkg/static/testfile2') in update_result.files_created)
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"\"sys.platform == 'win32'\"",
")",
"@",
"pytest",
".",
"mark",
".",
"network",
"def",
"test_check_submodule_addition",
"(",
"script",
")",
":",
"(",
"module_path",
",",
"submodule_path",
")",
"=",
"_create_test_pa... | submodules are pulled in on install and updated on upgrade . | train | false |
31,941 | def test_column_aggregate(T1):
for masked in (False, True):
tg = Table(T1, masked=masked).group_by('a')
tga = tg['c'].groups.aggregate(np.sum)
assert (tga.pformat() == [' c ', '----', ' 0.0', ' 6.0', '22.0'])
| [
"def",
"test_column_aggregate",
"(",
"T1",
")",
":",
"for",
"masked",
"in",
"(",
"False",
",",
"True",
")",
":",
"tg",
"=",
"Table",
"(",
"T1",
",",
"masked",
"=",
"masked",
")",
".",
"group_by",
"(",
"'a'",
")",
"tga",
"=",
"tg",
"[",
"'c'",
"]"... | aggregate a single table column . | train | false |
31,943 | def long_to_datetime(x):
days = (x // 86400000000)
x -= (days * 86400000000)
seconds = (x // 1000000)
x -= (seconds * 1000000)
return (datetime.min + timedelta(days=days, seconds=seconds, microseconds=x))
| [
"def",
"long_to_datetime",
"(",
"x",
")",
":",
"days",
"=",
"(",
"x",
"//",
"86400000000",
")",
"x",
"-=",
"(",
"days",
"*",
"86400000000",
")",
"seconds",
"=",
"(",
"x",
"//",
"1000000",
")",
"x",
"-=",
"(",
"seconds",
"*",
"1000000",
")",
"return... | converts a long integer representing the number of microseconds since datetime . | train | false |
31,945 | def get_error_statistics():
return get_statistics('E')
| [
"def",
"get_error_statistics",
"(",
")",
":",
"return",
"get_statistics",
"(",
"'E'",
")"
] | get error statistics . | train | false |
31,947 | def mc_compute_stationary(P):
return MarkovChain(P).stationary_distributions
| [
"def",
"mc_compute_stationary",
"(",
"P",
")",
":",
"return",
"MarkovChain",
"(",
"P",
")",
".",
"stationary_distributions"
] | computes stationary distributions of p . | train | false |
31,948 | def _medcouple_1d(y):
y = np.squeeze(np.asarray(y))
if (y.ndim != 1):
raise ValueError('y must be squeezable to a 1-d array')
y = np.sort(y)
n = y.shape[0]
if ((n % 2) == 0):
mf = ((y[((n // 2) - 1)] + y[(n // 2)]) / 2)
else:
mf = y[((n - 1) // 2)]
z = (y - mf)
lower = z[(z <= 0.0)]
upper = z[(z >= 0.0)]
upper = upper[:, None]
standardization = (upper - lower)
is_zero = np.logical_and((lower == 0.0), (upper == 0.0))
standardization[is_zero] = np.inf
spread = (upper + lower)
return np.median((spread / standardization))
| [
"def",
"_medcouple_1d",
"(",
"y",
")",
":",
"y",
"=",
"np",
".",
"squeeze",
"(",
"np",
".",
"asarray",
"(",
"y",
")",
")",
"if",
"(",
"y",
".",
"ndim",
"!=",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'y must be squeezable to a 1-d array'",
")",
"y"... | calculates the medcouple robust measure of skew . | train | false |
31,949 | def output():
return s3_rest_controller()
| [
"def",
"output",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | appends string_ to the response . | train | false |
31,950 | def is_valid_module(filename):
if (not filename.endswith('.py')):
return False
if (filename == '__init__.py'):
return True
for prefix in IGNORED_PREFIXES:
if filename.startswith(prefix):
return False
return True
| [
"def",
"is_valid_module",
"(",
"filename",
")",
":",
"if",
"(",
"not",
"filename",
".",
"endswith",
"(",
"'.py'",
")",
")",
":",
"return",
"False",
"if",
"(",
"filename",
"==",
"'__init__.py'",
")",
":",
"return",
"True",
"for",
"prefix",
"in",
"IGNORED_... | determines if a filename is a valid python module . | train | false |
31,952 | def url_join(base, url, allow_fragments=True):
if isinstance(base, tuple):
base = url_unparse(base)
if isinstance(url, tuple):
url = url_unparse(url)
(base, url) = normalize_string_tuple((base, url))
s = make_literal_wrapper(base)
if (not base):
return url
if (not url):
return base
(bscheme, bnetloc, bpath, bquery, bfragment) = url_parse(base, allow_fragments=allow_fragments)
(scheme, netloc, path, query, fragment) = url_parse(url, bscheme, allow_fragments)
if (scheme != bscheme):
return url
if netloc:
return url_unparse((scheme, netloc, path, query, fragment))
netloc = bnetloc
if (path[:1] == s('/')):
segments = path.split(s('/'))
elif (not path):
segments = bpath.split(s('/'))
if (not query):
query = bquery
else:
segments = (bpath.split(s('/'))[:(-1)] + path.split(s('/')))
if (segments[(-1)] == s('.')):
segments[(-1)] = s('')
segments = [segment for segment in segments if (segment != s('.'))]
while 1:
i = 1
n = (len(segments) - 1)
while (i < n):
if ((segments[i] == s('..')) and (segments[(i - 1)] not in (s(''), s('..')))):
del segments[(i - 1):(i + 1)]
break
i += 1
else:
break
unwanted_marker = [s(''), s('..')]
while (segments[:2] == unwanted_marker):
del segments[1]
path = s('/').join(segments)
return url_unparse((scheme, netloc, path, query, fragment))
| [
"def",
"url_join",
"(",
"base",
",",
"url",
",",
"allow_fragments",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"base",
",",
"tuple",
")",
":",
"base",
"=",
"url_unparse",
"(",
"base",
")",
"if",
"isinstance",
"(",
"url",
",",
"tuple",
")",
":",
... | convenience method for joining parts of a url any leading and trailing / characters are removed . | train | true |
31,953 | def format_percent(number, format=None):
return get_i18n().format_percent(number, format)
| [
"def",
"format_percent",
"(",
"number",
",",
"format",
"=",
"None",
")",
":",
"return",
"get_i18n",
"(",
")",
".",
"format_percent",
"(",
"number",
",",
"format",
")"
] | see :meth:i18n . | train | false |
31,954 | def example_number(region_code):
return example_number_for_type(region_code, PhoneNumberType.FIXED_LINE)
| [
"def",
"example_number",
"(",
"region_code",
")",
":",
"return",
"example_number_for_type",
"(",
"region_code",
",",
"PhoneNumberType",
".",
"FIXED_LINE",
")"
] | gets a valid number for the specified region . | train | false |
31,956 | def is_archive_file(name):
archives = ('.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.pybundle')
ext = splitext(name)[1].lower()
if (ext in archives):
return True
return False
| [
"def",
"is_archive_file",
"(",
"name",
")",
":",
"archives",
"=",
"(",
"'.zip'",
",",
"'.tar.gz'",
",",
"'.tar.bz2'",
",",
"'.tgz'",
",",
"'.tar'",
",",
"'.pybundle'",
")",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
".",
"lower",
"(",
"... | return true if name is a considered as an archive file . | train | true |
31,959 | def test_rgb_to_hsl_part_12():
assert (rgb_to_hsl(153, 102, 153) == (300, 20, 50))
assert (rgb_to_hsl(204, 51, 204) == (300, 60, 50))
assert (rgb_to_hsl(255, 0, 255) == (300, 100, 50))
| [
"def",
"test_rgb_to_hsl_part_12",
"(",
")",
":",
"assert",
"(",
"rgb_to_hsl",
"(",
"153",
",",
"102",
",",
"153",
")",
"==",
"(",
"300",
",",
"20",
",",
"50",
")",
")",
"assert",
"(",
"rgb_to_hsl",
"(",
"204",
",",
"51",
",",
"204",
")",
"==",
"(... | test rgb to hsl color function . | train | false |
31,960 | def list_configured_members(lbn, profile='default'):
config = dump_config(profile)
try:
ret = config['worker.{0}.balance_workers'.format(lbn)]
except KeyError:
return []
return [_f for _f in ret.strip().split(',') if _f]
| [
"def",
"list_configured_members",
"(",
"lbn",
",",
"profile",
"=",
"'default'",
")",
":",
"config",
"=",
"dump_config",
"(",
"profile",
")",
"try",
":",
"ret",
"=",
"config",
"[",
"'worker.{0}.balance_workers'",
".",
"format",
"(",
"lbn",
")",
"]",
"except",... | return a list of member workers from the configuration files cli examples: . | train | true |
31,962 | def write_varint(outfile, value):
if (value == 0):
outfile.write(ZERO_BYTE)
return 1
written_bytes = 0
while (value > 0):
to_write = (value & 127)
value = (value >> 7)
if (value > 0):
to_write |= 128
outfile.write(byte(to_write))
written_bytes += 1
return written_bytes
| [
"def",
"write_varint",
"(",
"outfile",
",",
"value",
")",
":",
"if",
"(",
"value",
"==",
"0",
")",
":",
"outfile",
".",
"write",
"(",
"ZERO_BYTE",
")",
"return",
"1",
"written_bytes",
"=",
"0",
"while",
"(",
"value",
">",
"0",
")",
":",
"to_write",
... | writes a varint to a file . | train | false |
31,964 | def epoch(dttm):
return ((int(time.mktime(dttm.timetuple())) * 1000),)
| [
"def",
"epoch",
"(",
"dttm",
")",
":",
"return",
"(",
"(",
"int",
"(",
"time",
".",
"mktime",
"(",
"dttm",
".",
"timetuple",
"(",
")",
")",
")",
"*",
"1000",
")",
",",
")"
] | date/time converted to seconds since epoch . | train | false |
31,965 | @asyncio.coroutine
def auth_middleware(app, handler):
if (app['hass'].http.api_password is None):
@asyncio.coroutine
def no_auth_middleware_handler(request):
'Auth middleware to approve all requests.'
request[KEY_AUTHENTICATED] = True
return handler(request)
return no_auth_middleware_handler
@asyncio.coroutine
def auth_middleware_handler(request):
'Auth middleware to check authentication.'
authenticated = False
if ((HTTP_HEADER_HA_AUTH in request.headers) and validate_password(request, request.headers[HTTP_HEADER_HA_AUTH])):
authenticated = True
elif ((DATA_API_PASSWORD in request.GET) and validate_password(request, request.GET[DATA_API_PASSWORD])):
authenticated = True
elif is_trusted_ip(request):
authenticated = True
request[KEY_AUTHENTICATED] = authenticated
return handler(request)
return auth_middleware_handler
| [
"@",
"asyncio",
".",
"coroutine",
"def",
"auth_middleware",
"(",
"app",
",",
"handler",
")",
":",
"if",
"(",
"app",
"[",
"'hass'",
"]",
".",
"http",
".",
"api_password",
"is",
"None",
")",
":",
"@",
"asyncio",
".",
"coroutine",
"def",
"no_auth_middleware... | authentication middleware . | train | false |
31,966 | def process_xmodule_assets():
sh('xmodule_assets common/static/xmodule')
print(' DCTB DCTB Finished processing xmodule assets.')
| [
"def",
"process_xmodule_assets",
"(",
")",
":",
"sh",
"(",
"'xmodule_assets common/static/xmodule'",
")",
"print",
"(",
"' DCTB DCTB Finished processing xmodule assets.'",
")"
] | process xmodule static assets . | train | false |
31,967 | def default_navigator_config_dir():
return get_config_root()
| [
"def",
"default_navigator_config_dir",
"(",
")",
":",
"return",
"get_config_root",
"(",
")"
] | get from usual main hue config directory . | train | false |
31,968 | def load_ipython_extension(ip):
warnings.warn('The rmagic extension in IPython has moved to `rpy2.ipython`, please see `rpy2` documentation.')
| [
"def",
"load_ipython_extension",
"(",
"ip",
")",
":",
"warnings",
".",
"warn",
"(",
"'The rmagic extension in IPython has moved to `rpy2.ipython`, please see `rpy2` documentation.'",
")"
] | load the extension in ipython . | train | false |
31,969 | def get_solidity():
if (get_compiler_path() is None):
return None
return solc_wrapper
| [
"def",
"get_solidity",
"(",
")",
":",
"if",
"(",
"get_compiler_path",
"(",
")",
"is",
"None",
")",
":",
"return",
"None",
"return",
"solc_wrapper"
] | return the singleton used to interact with the solc compiler . | train | false |
31,970 | @contextmanager
def use_venv(pyversion):
pyversion = str(pyversion)
if (pyversion == '2'):
(yield)
elif (pyversion == '3'):
oldvenv = env.virtualenv
env.virtualenv = 'virtualenv -p /usr/bin/python3'
(yield)
env.virtualenv = oldvenv
else:
raise ValueError(("pyversion must be one of '2' or '3', not %s" % pyversion))
| [
"@",
"contextmanager",
"def",
"use_venv",
"(",
"pyversion",
")",
":",
"pyversion",
"=",
"str",
"(",
"pyversion",
")",
"if",
"(",
"pyversion",
"==",
"'2'",
")",
":",
"(",
"yield",
")",
"elif",
"(",
"pyversion",
"==",
"'3'",
")",
":",
"oldvenv",
"=",
"... | change make_virtualenv to use a given cmd pyversion should be 2 or 3 . | train | false |
31,971 | def list_api_opts():
return [(g, copy.deepcopy(o)) for (g, o) in _api_opts]
| [
"def",
"list_api_opts",
"(",
")",
":",
"return",
"[",
"(",
"g",
",",
"copy",
".",
"deepcopy",
"(",
"o",
")",
")",
"for",
"(",
"g",
",",
"o",
")",
"in",
"_api_opts",
"]"
] | return a list of oslo_config options available in glance api service . | train | false |
31,972 | def get_hash_str(base_str):
if isinstance(base_str, six.text_type):
base_str = base_str.encode('utf-8')
return hashlib.md5(base_str).hexdigest()
| [
"def",
"get_hash_str",
"(",
"base_str",
")",
":",
"if",
"isinstance",
"(",
"base_str",
",",
"six",
".",
"text_type",
")",
":",
"base_str",
"=",
"base_str",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"hashlib",
".",
"md5",
"(",
"base_str",
")",
".",
... | returns string that represents md5 hash of base_str . | train | false |
31,973 | def ord(char):
if isinstance(char, unicodeT):
return __builtin__.ord(char)
return __builtin__.ord(to_unicode(char, 'utf-8'))
| [
"def",
"ord",
"(",
"char",
")",
":",
"if",
"isinstance",
"(",
"char",
",",
"unicodeT",
")",
":",
"return",
"__builtin__",
".",
"ord",
"(",
"char",
")",
"return",
"__builtin__",
".",
"ord",
"(",
"to_unicode",
"(",
"char",
",",
"'utf-8'",
")",
")"
] | returns unicode id for utf8 or unicode *char* character suppose that *char* is an utf-8 or unicode character only . | train | false |
31,974 | def user_has_perm(user, perm, obj=None, cache='user'):
project = _get_object_project(obj)
if (not project):
return False
return (perm in get_user_project_permissions(user, project, cache=cache))
| [
"def",
"user_has_perm",
"(",
"user",
",",
"perm",
",",
"obj",
"=",
"None",
",",
"cache",
"=",
"'user'",
")",
":",
"project",
"=",
"_get_object_project",
"(",
"obj",
")",
"if",
"(",
"not",
"project",
")",
":",
"return",
"False",
"return",
"(",
"perm",
... | cache param determines how memberships are calculated trying to reuse the existing data in cache . | train | false |
31,975 | def get_next_downloadable_changeset_revision(repository, repo, after_changeset_revision):
changeset_revisions = [revision[1] for revision in get_metadata_revisions(repository, repo)]
if (len(changeset_revisions) == 1):
changeset_revision = changeset_revisions[0]
if (changeset_revision == after_changeset_revision):
return after_changeset_revision
found_after_changeset_revision = False
for changeset in repo.changelog:
changeset_revision = str(repo.changectx(changeset))
if found_after_changeset_revision:
if (changeset_revision in changeset_revisions):
return changeset_revision
elif ((not found_after_changeset_revision) and (changeset_revision == after_changeset_revision)):
found_after_changeset_revision = True
return None
| [
"def",
"get_next_downloadable_changeset_revision",
"(",
"repository",
",",
"repo",
",",
"after_changeset_revision",
")",
":",
"changeset_revisions",
"=",
"[",
"revision",
"[",
"1",
"]",
"for",
"revision",
"in",
"get_metadata_revisions",
"(",
"repository",
",",
"repo",... | return the installable changeset_revision in the repository changelog after the changeset to which after_changeset_revision refers . | train | false |
31,976 | def create_class_from_element_tree(target_class, tree, namespace=None, tag=None):
if (namespace is None):
namespace = target_class.c_namespace
if (tag is None):
tag = target_class.c_tag
if (tree.tag == ('{%s}%s' % (namespace, tag))):
target = target_class()
target.harvest_element_tree(tree)
return target
else:
return None
| [
"def",
"create_class_from_element_tree",
"(",
"target_class",
",",
"tree",
",",
"namespace",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"(",
"namespace",
"is",
"None",
")",
":",
"namespace",
"=",
"target_class",
".",
"c_namespace",
"if",
"(",
"t... | instantiates the class and populates members according to the tree . | train | true |
31,979 | def is_zoom_parameter(parameter):
return hasattr(parameter, 'zoom')
| [
"def",
"is_zoom_parameter",
"(",
"parameter",
")",
":",
"return",
"hasattr",
"(",
"parameter",
",",
"'zoom'",
")"
] | returns true for parameters . | train | false |
31,980 | def get_prefix(ctx, args, search=True):
if getattr(args, u'name', None):
if (u'/' in args.name):
raise CondaValueError((u"'/' not allowed in environment name: %s" % args.name), getattr(args, u'json', False))
if (args.name == ROOT_ENV_NAME):
return ctx.root_dir
if search:
return locate_prefix_by_name(ctx, args.name)
else:
return join(ctx.envs_dirs[0], args.name)
elif getattr(args, u'prefix', None):
return abspath(expanduser(args.prefix))
else:
return ctx.default_prefix
| [
"def",
"get_prefix",
"(",
"ctx",
",",
"args",
",",
"search",
"=",
"True",
")",
":",
"if",
"getattr",
"(",
"args",
",",
"u'name'",
",",
"None",
")",
":",
"if",
"(",
"u'/'",
"in",
"args",
".",
"name",
")",
":",
"raise",
"CondaValueError",
"(",
"(",
... | get the prefix to operate in args: ctx: the context of conda args: the argparse args from the command line search: whether search for prefix returns: the prefix raises: condaenvironmentnotfounderror if the prefix is invalid . | train | false |
31,981 | def luv2rgb(luv):
return xyz2rgb(luv2xyz(luv))
| [
"def",
"luv2rgb",
"(",
"luv",
")",
":",
"return",
"xyz2rgb",
"(",
"luv2xyz",
"(",
"luv",
")",
")"
] | luv to rgb color space conversion . | train | false |
31,982 | def _region_code_for_short_number_from_region_list(numobj, region_codes):
if (len(region_codes) == 0):
return None
elif (len(region_codes) == 1):
return region_codes[0]
national_number = national_significant_number(numobj)
for region_code in region_codes:
metadata = PhoneMetadata.short_metadata_for_region(region_code)
if ((metadata is not None) and _is_number_matching_desc(national_number, metadata.short_code)):
return region_code
return None
| [
"def",
"_region_code_for_short_number_from_region_list",
"(",
"numobj",
",",
"region_codes",
")",
":",
"if",
"(",
"len",
"(",
"region_codes",
")",
"==",
"0",
")",
":",
"return",
"None",
"elif",
"(",
"len",
"(",
"region_codes",
")",
"==",
"1",
")",
":",
"re... | helper method to get the region code for a given phone number . | train | true |
31,983 | @pipeline.mutator_stage
def apply_choices(session, task):
if task.skip:
return
if task.apply:
task.apply_metadata()
plugins.send('import_task_apply', session=session, task=task)
task.add(session.lib)
| [
"@",
"pipeline",
".",
"mutator_stage",
"def",
"apply_choices",
"(",
"session",
",",
"task",
")",
":",
"if",
"task",
".",
"skip",
":",
"return",
"if",
"task",
".",
"apply",
":",
"task",
".",
"apply_metadata",
"(",
")",
"plugins",
".",
"send",
"(",
"'imp... | a coroutine for applying changes to albums and singletons during the autotag process . | train | false |
31,984 | @profiler.trace
def remove_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None):
manager = keystoneclient(request, admin=True).roles
if (VERSIONS.active < 3):
return manager.remove_user_role(user, role, project)
else:
return manager.revoke(role, user=user, project=project, group=group, domain=domain)
| [
"@",
"profiler",
".",
"trace",
"def",
"remove_tenant_user_role",
"(",
"request",
",",
"project",
"=",
"None",
",",
"user",
"=",
"None",
",",
"role",
"=",
"None",
",",
"group",
"=",
"None",
",",
"domain",
"=",
"None",
")",
":",
"manager",
"=",
"keystone... | removes a given single role for a user from a tenant . | train | true |
31,985 | def coordinate_to_tuple(coordinate):
(col, row) = coordinate_from_string(coordinate)
return (row, _COL_STRING_CACHE[col])
| [
"def",
"coordinate_to_tuple",
"(",
"coordinate",
")",
":",
"(",
"col",
",",
"row",
")",
"=",
"coordinate_from_string",
"(",
"coordinate",
")",
"return",
"(",
"row",
",",
"_COL_STRING_CACHE",
"[",
"col",
"]",
")"
] | convert an excel style coordinate to tuple . | train | false |
31,987 | def getFloatListFromBracketedString(bracketedString):
if (not getIsBracketed(bracketedString)):
return None
bracketedString = bracketedString.strip().replace('[', '').replace(']', '').replace('(', '').replace(')', '')
if (len(bracketedString) < 1):
return []
splitLine = bracketedString.split(',')
floatList = []
for word in splitLine:
evaluatedFloat = euclidean.getFloatFromValue(word)
if (evaluatedFloat != None):
floatList.append(evaluatedFloat)
return floatList
| [
"def",
"getFloatListFromBracketedString",
"(",
"bracketedString",
")",
":",
"if",
"(",
"not",
"getIsBracketed",
"(",
"bracketedString",
")",
")",
":",
"return",
"None",
"bracketedString",
"=",
"bracketedString",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"'['"... | get list from a bracketed string . | train | false |
31,989 | def is_debian():
return os.path.exists(u'/usr/bin/apt-get')
| [
"def",
"is_debian",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"u'/usr/bin/apt-get'",
")"
] | is it debian? . | train | false |
31,990 | def test_topic_update_read(database, user, topic):
forumsread = ForumsRead.query.filter((ForumsRead.user_id == user.id), (ForumsRead.forum_id == topic.forum_id)).first()
with current_app.test_request_context():
login_user(user)
assert current_user.is_authenticated
assert topic.update_read(current_user, topic.forum, forumsread)
assert (not topic.update_read(current_user, topic.forum, forumsread))
post = Post(content='Test Content')
post.save(topic=topic, user=user)
forumsread = ForumsRead.query.filter((ForumsRead.user_id == user.id), (ForumsRead.forum_id == topic.forum_id)).first()
flaskbb_config['TRACKER_LENGTH'] = 0
assert (not topic.update_read(current_user, topic.forum, forumsread))
flaskbb_config['TRACKER_LENGTH'] = 1
assert topic.update_read(current_user, topic.forum, forumsread)
logout_user()
assert (not current_user.is_authenticated)
assert (not topic.update_read(current_user, topic.forum, forumsread))
| [
"def",
"test_topic_update_read",
"(",
"database",
",",
"user",
",",
"topic",
")",
":",
"forumsread",
"=",
"ForumsRead",
".",
"query",
".",
"filter",
"(",
"(",
"ForumsRead",
".",
"user_id",
"==",
"user",
".",
"id",
")",
",",
"(",
"ForumsRead",
".",
"forum... | tests the update read method if the topic is unread/read . | train | false |
31,991 | def get_cwidth(string):
return _CHAR_SIZES_CACHE[string]
| [
"def",
"get_cwidth",
"(",
"string",
")",
":",
"return",
"_CHAR_SIZES_CACHE",
"[",
"string",
"]"
] | return width of a string . | train | false |
31,993 | def flocker_container_agent_main():
def deployer_factory(cluster_uuid, **kwargs):
return ApplicationNodeDeployer(**kwargs)
service_factory = AgentServiceFactory(deployer_factory=deployer_factory).get_service
agent_script = AgentScript(service_factory=service_factory)
pr = cProfile.Profile(clock)
signal.signal(signal.SIGUSR1, partial(enable_profiling, pr))
signal.signal(signal.SIGUSR2, partial(disable_profiling, pr, 'container'))
return FlockerScriptRunner(script=agent_script, options=ContainerAgentOptions()).main()
| [
"def",
"flocker_container_agent_main",
"(",
")",
":",
"def",
"deployer_factory",
"(",
"cluster_uuid",
",",
"**",
"kwargs",
")",
":",
"return",
"ApplicationNodeDeployer",
"(",
"**",
"kwargs",
")",
"service_factory",
"=",
"AgentServiceFactory",
"(",
"deployer_factory",
... | implementation of the flocker-container-agent command line script . | train | false |
31,994 | def spdiags(data, diags, m, n, format=None):
return dia_matrix((data, diags), shape=(m, n)).asformat(format)
| [
"def",
"spdiags",
"(",
"data",
",",
"diags",
",",
"m",
",",
"n",
",",
"format",
"=",
"None",
")",
":",
"return",
"dia_matrix",
"(",
"(",
"data",
",",
"diags",
")",
",",
"shape",
"=",
"(",
"m",
",",
"n",
")",
")",
".",
"asformat",
"(",
"format",... | return a sparse matrix from diagonals . | train | false |
31,997 | def tunnel_connection(socket, addr, server, keyfile=None, password=None, paramiko=None, timeout=60):
(new_url, tunnel) = open_tunnel(addr, server, keyfile=keyfile, password=password, paramiko=paramiko, timeout=timeout)
socket.connect(new_url)
return tunnel
| [
"def",
"tunnel_connection",
"(",
"socket",
",",
"addr",
",",
"server",
",",
"keyfile",
"=",
"None",
",",
"password",
"=",
"None",
",",
"paramiko",
"=",
"None",
",",
"timeout",
"=",
"60",
")",
":",
"(",
"new_url",
",",
"tunnel",
")",
"=",
"open_tunnel",... | connect a socket to an address via an ssh tunnel . | train | true |
31,999 | def _txt2obj(backend, name):
name = name.encode('ascii')
obj = backend._lib.OBJ_txt2obj(name, 1)
backend.openssl_assert((obj != backend._ffi.NULL))
return obj
| [
"def",
"_txt2obj",
"(",
"backend",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"encode",
"(",
"'ascii'",
")",
"obj",
"=",
"backend",
".",
"_lib",
".",
"OBJ_txt2obj",
"(",
"name",
",",
"1",
")",
"backend",
".",
"openssl_assert",
"(",
"(",
"obj",
... | converts a python string with an asn . | train | false |
32,000 | def log_file(msg, filename='game.log'):
def callback(filehandle, msg):
'Writing to file and flushing result'
msg = ('\n%s [-] %s' % (timeformat(), msg.strip()))
filehandle.write(msg)
filehandle.flush()
def errback(failure):
'Catching errors to normal log'
log_trace()
filehandle = _open_log_file(filename)
if filehandle:
deferToThread(callback, filehandle, msg).addErrback(errback)
| [
"def",
"log_file",
"(",
"msg",
",",
"filename",
"=",
"'game.log'",
")",
":",
"def",
"callback",
"(",
"filehandle",
",",
"msg",
")",
":",
"msg",
"=",
"(",
"'\\n%s [-] %s'",
"%",
"(",
"timeformat",
"(",
")",
",",
"msg",
".",
"strip",
"(",
")",
")",
"... | arbitrary file logger using threads . | train | false |
32,002 | def validate_reserved_names(value):
if (value in settings.DEIS_RESERVED_NAMES):
raise ValidationError(u'{} is a reserved name.'.format(value))
| [
"def",
"validate_reserved_names",
"(",
"value",
")",
":",
"if",
"(",
"value",
"in",
"settings",
".",
"DEIS_RESERVED_NAMES",
")",
":",
"raise",
"ValidationError",
"(",
"u'{} is a reserved name.'",
".",
"format",
"(",
"value",
")",
")"
] | a value cannot use some reserved names . | train | false |
32,004 | def rule(value):
def add_attribute(function):
if (not hasattr(function, u'rule')):
function.rule = []
function.rule.append(value)
return function
return add_attribute
| [
"def",
"rule",
"(",
"value",
")",
":",
"def",
"add_attribute",
"(",
"function",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"function",
",",
"u'rule'",
")",
")",
":",
"function",
".",
"rule",
"=",
"[",
"]",
"function",
".",
"rule",
".",
"append",
"... | helper to build a firewall rule . | train | false |
32,005 | def _register_core_blueprints(app):
def is_blueprint(mm):
return isinstance(mm, Blueprint)
for (loader, name, _) in pkgutil.iter_modules(['ckan/views'], 'ckan.views.'):
module = loader.find_module(name).load_module(name)
for blueprint in inspect.getmembers(module, is_blueprint):
app.register_blueprint(blueprint[1])
log.debug(u'Registered core blueprint: {0!r}'.format(blueprint[0]))
| [
"def",
"_register_core_blueprints",
"(",
"app",
")",
":",
"def",
"is_blueprint",
"(",
"mm",
")",
":",
"return",
"isinstance",
"(",
"mm",
",",
"Blueprint",
")",
"for",
"(",
"loader",
",",
"name",
",",
"_",
")",
"in",
"pkgutil",
".",
"iter_modules",
"(",
... | register all blueprints defined in the views folder . | train | false |
32,006 | def is_iter(iterable):
return hasattr(iterable, '__iter__')
| [
"def",
"is_iter",
"(",
"iterable",
")",
":",
"return",
"hasattr",
"(",
"iterable",
",",
"'__iter__'",
")"
] | checks if an object behaves iterably . | train | false |
32,007 | def _should_validate_sub_attributes(attribute, sub_attr):
validate = attribute.get('validate')
return (validate and isinstance(sub_attr, collections.Iterable) and any([(k.startswith('type:dict') and v) for (k, v) in six.iteritems(validate)]))
| [
"def",
"_should_validate_sub_attributes",
"(",
"attribute",
",",
"sub_attr",
")",
":",
"validate",
"=",
"attribute",
".",
"get",
"(",
"'validate'",
")",
"return",
"(",
"validate",
"and",
"isinstance",
"(",
"sub_attr",
",",
"collections",
".",
"Iterable",
")",
... | verify that sub-attributes are iterable and should be validated . | train | false |
32,008 | def _sorted_attrs(elem):
singles = []
lists = []
for (attrname, child) in sorted(elem.__dict__.items(), key=(lambda kv: kv[0])):
if (child is None):
continue
if isinstance(child, list):
lists.extend(child)
else:
singles.append(child)
return (x for x in (singles + lists) if isinstance(x, TreeElement))
| [
"def",
"_sorted_attrs",
"(",
"elem",
")",
":",
"singles",
"=",
"[",
"]",
"lists",
"=",
"[",
"]",
"for",
"(",
"attrname",
",",
"child",
")",
"in",
"sorted",
"(",
"elem",
".",
"__dict__",
".",
"items",
"(",
")",
",",
"key",
"=",
"(",
"lambda",
"kv"... | get a flat list of elems attributes . | train | false |
32,009 | @gen.engine
def Grep(args, callback):
assert (len(args) >= 2)
pattern = re.compile(args[0])
files = args[1:]
bucket = store = None
for f in files:
resolved = store_utils.ParseFullPath(f)
assert (resolved is not None), ('Cannot determine bucket from %s' % f)
(b, path) = resolved
assert ((bucket is None) or (bucket == b)), 'Input files must all be in the same bucket'
if (store is None):
bucket = b
store = ObjectStore.GetInstance(bucket)
contents = (yield gen.Task(store_utils.GetFileContents, store, path))
for line in contents.split('\n'):
if pattern.search(line):
print ('%s:%s' % (f, line))
callback()
| [
"@",
"gen",
".",
"engine",
"def",
"Grep",
"(",
"args",
",",
"callback",
")",
":",
"assert",
"(",
"len",
"(",
"args",
")",
">=",
"2",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"args",
"[",
"0",
"]",
")",
"files",
"=",
"args",
"[",
"1",
"... | grep a set of files . | train | false |
32,010 | def vector_from_matrix(v_as_matrix):
return [row[0] for row in v_as_matrix]
| [
"def",
"vector_from_matrix",
"(",
"v_as_matrix",
")",
":",
"return",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"v_as_matrix",
"]"
] | returns the n x 1 matrix as a list of values . | train | false |
32,011 | @shared_task(bind=True)
def add_replaced(self, x, y):
raise self.replace(add.s(x, y))
| [
"@",
"shared_task",
"(",
"bind",
"=",
"True",
")",
"def",
"add_replaced",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"raise",
"self",
".",
"replace",
"(",
"add",
".",
"s",
"(",
"x",
",",
"y",
")",
")"
] | add two numbers . | train | false |
32,013 | def to_iso8601(when):
return when.strftime(boto.utils.ISO8601_MS)
| [
"def",
"to_iso8601",
"(",
"when",
")",
":",
"return",
"when",
".",
"strftime",
"(",
"boto",
".",
"utils",
".",
"ISO8601_MS",
")"
] | convert a datetime to iso8601 format . | train | false |
32,014 | def round_to_scale(number, precision):
if (precision < 1):
return round_to_float(number, precision)
return round_to_int(number, precision)
| [
"def",
"round_to_scale",
"(",
"number",
",",
"precision",
")",
":",
"if",
"(",
"precision",
"<",
"1",
")",
":",
"return",
"round_to_float",
"(",
"number",
",",
"precision",
")",
"return",
"round_to_int",
"(",
"number",
",",
"precision",
")"
] | round a number or a float to a precision . | train | true |
32,015 | def _compute_hash(get_deps_dict, hash, rospack=None):
from roslib.msgs import MsgSpec
from roslib.srvs import SrvSpec
spec = get_deps_dict['spec']
if isinstance(spec, MsgSpec):
hash.update(compute_md5_text(get_deps_dict, spec, rospack=rospack).encode())
elif isinstance(spec, SrvSpec):
hash.update(compute_md5_text(get_deps_dict, spec.request, rospack=rospack).encode())
hash.update(compute_md5_text(get_deps_dict, spec.response, rospack=rospack).encode())
else:
raise Exception(('[%s] is not a message or service' % spec))
return hash.hexdigest()
| [
"def",
"_compute_hash",
"(",
"get_deps_dict",
",",
"hash",
",",
"rospack",
"=",
"None",
")",
":",
"from",
"roslib",
".",
"msgs",
"import",
"MsgSpec",
"from",
"roslib",
".",
"srvs",
"import",
"SrvSpec",
"spec",
"=",
"get_deps_dict",
"[",
"'spec'",
"]",
"if"... | subroutine of compute_md5() . | train | false |
32,016 | def _check_dep_visibility(target, dep, targets):
if (dep not in targets):
console.error_exit(('Target %s:%s depends on %s:%s, but it is missing, exit...' % (target_id[0], target_id[1], dep[0], dep[1])))
if (target[0] == dep[0]):
return
d = targets[dep]
visibility = getattr(d, 'visibility', 'PUBLIC')
if (visibility == 'PUBLIC'):
return
if (target not in visibility):
console.error_exit(('%s:%s is not allowed to depend on %s because of visibility.' % (target[0], target[1], d.fullname)))
| [
"def",
"_check_dep_visibility",
"(",
"target",
",",
"dep",
",",
"targets",
")",
":",
"if",
"(",
"dep",
"not",
"in",
"targets",
")",
":",
"console",
".",
"error_exit",
"(",
"(",
"'Target %s:%s depends on %s:%s, but it is missing, exit...'",
"%",
"(",
"target_id",
... | check whether target is able to depend on dep . | train | false |
32,017 | def get_run_root(*append):
return __get_root(*append)
| [
"def",
"get_run_root",
"(",
"*",
"append",
")",
":",
"return",
"__get_root",
"(",
"*",
"append",
")"
] | returns the run time root directory . | train | false |
32,018 | def with_metaclasses(metaclasses, *bases):
return six.with_metaclass(compose_types(*metaclasses), *bases)
| [
"def",
"with_metaclasses",
"(",
"metaclasses",
",",
"*",
"bases",
")",
":",
"return",
"six",
".",
"with_metaclass",
"(",
"compose_types",
"(",
"*",
"metaclasses",
")",
",",
"*",
"bases",
")"
] | make a class inheriting from bases whose metaclass inherits from all of metaclasses . | train | false |
32,019 | def show_calendar(month, date, rel):
month = random_rainbow(month)
date = ' '.join([cycle_color(i) for i in date.split(' ')])
today = str(int(os.popen("date +'%d'").read().strip()))
printNicely(month)
printNicely(date)
for line in rel:
ary = line.split(' ')
ary = lmap((lambda x: (color_func(c['CAL']['today'])(x) if (x == today) else color_func(c['CAL']['days'])(x))), ary)
printNicely(' '.join(ary))
| [
"def",
"show_calendar",
"(",
"month",
",",
"date",
",",
"rel",
")",
":",
"month",
"=",
"random_rainbow",
"(",
"month",
")",
"date",
"=",
"' '",
".",
"join",
"(",
"[",
"cycle_color",
"(",
"i",
")",
"for",
"i",
"in",
"date",
".",
"split",
"(",
"' '",... | show the calendar in rainbow mode . | train | false |
32,020 | def is_image_mutable(context, image):
if context.is_admin:
return True
if ((image.owner is None) or (context.owner is None)):
return False
return (image.owner == context.owner)
| [
"def",
"is_image_mutable",
"(",
"context",
",",
"image",
")",
":",
"if",
"context",
".",
"is_admin",
":",
"return",
"True",
"if",
"(",
"(",
"image",
".",
"owner",
"is",
"None",
")",
"or",
"(",
"context",
".",
"owner",
"is",
"None",
")",
")",
":",
"... | return true if the image is mutable in this context . | train | false |
32,021 | def delete_rax_cbs(args):
print ("--- Cleaning Cloud Block Storage matching '%s'" % args.match_re)
for region in pyrax.identity.services.network.regions:
cbs = pyrax.connect_to_cloud_blockstorage(region=region)
for volume in cbs.list():
if re.search(args.match_re, volume.name):
prompt_and_delete(volume, ('Delete matching %s? [y/n]: ' % volume), args.assumeyes)
| [
"def",
"delete_rax_cbs",
"(",
"args",
")",
":",
"print",
"(",
"\"--- Cleaning Cloud Block Storage matching '%s'\"",
"%",
"args",
".",
"match_re",
")",
"for",
"region",
"in",
"pyrax",
".",
"identity",
".",
"services",
".",
"network",
".",
"regions",
":",
"cbs",
... | function for deleting cloud networks . | train | false |
32,022 | def validate_removal_semver(removal_version):
if (removal_version is None):
raise MissingRemovalVersionError(u'The removal version must be provided.')
if (not isinstance(removal_version, six.string_types)):
raise BadRemovalVersionError(u'The removal_version must be a version string.')
try:
v = Version(removal_version)
if (len(v.base_version.split(u'.')) != 3):
raise BadRemovalVersionError(u'The given removal version {} is not a valid version: {}'.format(removal_version, removal_version))
return v
except InvalidVersion as e:
raise BadRemovalVersionError(u'The given removal version {} is not a valid version: {}'.format(removal_version, e))
| [
"def",
"validate_removal_semver",
"(",
"removal_version",
")",
":",
"if",
"(",
"removal_version",
"is",
"None",
")",
":",
"raise",
"MissingRemovalVersionError",
"(",
"u'The removal version must be provided.'",
")",
"if",
"(",
"not",
"isinstance",
"(",
"removal_version",... | validates that removal_version is a valid semver . | train | false |
32,024 | def get_latest_file_attachments(file_attachments):
file_attachment_histories = FileAttachmentHistory.objects.filter(file_attachments__in=file_attachments)
latest = {data[u'id']: data[u'latest_revision'] for data in file_attachment_histories.values(u'id', u'latest_revision')}
return [f for f in file_attachments if ((not f.is_from_diff) and (f.attachment_revision == latest[f.attachment_history_id]))]
| [
"def",
"get_latest_file_attachments",
"(",
"file_attachments",
")",
":",
"file_attachment_histories",
"=",
"FileAttachmentHistory",
".",
"objects",
".",
"filter",
"(",
"file_attachments__in",
"=",
"file_attachments",
")",
"latest",
"=",
"{",
"data",
"[",
"u'id'",
"]",... | filter the list of file attachments to only return the latest revisions . | train | false |
32,025 | @require_chanmsg
@require_privilege(OP, u'You are not a channel operator.')
@commands(u'showmask')
def show_mask(bot, trigger):
mask = bot.db.get_channel_value(trigger.sender, u'topic_mask')
mask = (mask or default_mask(trigger))
bot.say(mask)
| [
"@",
"require_chanmsg",
"@",
"require_privilege",
"(",
"OP",
",",
"u'You are not a channel operator.'",
")",
"@",
"commands",
"(",
"u'showmask'",
")",
"def",
"show_mask",
"(",
"bot",
",",
"trigger",
")",
":",
"mask",
"=",
"bot",
".",
"db",
".",
"get_channel_va... | show the topic mask for the current channel . | train | false |
32,026 | def _core_subgraph(G, k_filter, k=None, core=None):
if (core is None):
core = core_number(G)
if (k is None):
k = max(core.values())
nodes = (v for v in core if k_filter(v, k, core))
return G.subgraph(nodes).copy()
| [
"def",
"_core_subgraph",
"(",
"G",
",",
"k_filter",
",",
"k",
"=",
"None",
",",
"core",
"=",
"None",
")",
":",
"if",
"(",
"core",
"is",
"None",
")",
":",
"core",
"=",
"core_number",
"(",
"G",
")",
"if",
"(",
"k",
"is",
"None",
")",
":",
"k",
... | returns the subgraph induced by nodes passing filter k_filter . | train | false |
32,027 | def deprecate_module_with_proxy(module_name, module_dict, deprecated_attributes=None):
def _ModuleProxy(module, depr):
'Return a wrapped object that warns about deprecated accesses'
class Wrapper(object, ):
def __getattr__(self, attr):
if ((depr is None) or (attr in depr)):
warnings.warn(('Property %s is deprecated' % attr))
return getattr(module, attr)
def __setattr__(self, attr, value):
if ((depr is None) or (attr in depr)):
warnings.warn(('Property %s is deprecated' % attr))
return setattr(module, attr, value)
return Wrapper()
deprecated_import(module_name)
deprs = set()
for key in (deprecated_attributes or module_dict):
if key.startswith('_'):
continue
if (callable(module_dict[key]) and (not isbuiltin(module_dict[key]))):
module_dict[key] = deprecated(module_dict[key])
else:
deprs.add(key)
sys.modules[module_name] = _ModuleProxy(sys.modules[module_name], (deprs or None))
| [
"def",
"deprecate_module_with_proxy",
"(",
"module_name",
",",
"module_dict",
",",
"deprecated_attributes",
"=",
"None",
")",
":",
"def",
"_ModuleProxy",
"(",
"module",
",",
"depr",
")",
":",
"class",
"Wrapper",
"(",
"object",
",",
")",
":",
"def",
"__getattr_... | usage: deprecate_module_with_proxy(__name__ . | train | true |
32,028 | def test_ncr_init():
ncr = NeighbourhoodCleaningRule(random_state=RND_SEED)
assert_equal(ncr.n_neighbors, 3)
assert_equal(ncr.n_jobs, 1)
assert_equal(ncr.random_state, RND_SEED)
| [
"def",
"test_ncr_init",
"(",
")",
":",
"ncr",
"=",
"NeighbourhoodCleaningRule",
"(",
"random_state",
"=",
"RND_SEED",
")",
"assert_equal",
"(",
"ncr",
".",
"n_neighbors",
",",
"3",
")",
"assert_equal",
"(",
"ncr",
".",
"n_jobs",
",",
"1",
")",
"assert_equal"... | test the initialisation of the object . | train | false |
32,029 | def SetLabel(*labels):
def Decorator(f):
function_labels = getattr(f, 'labels', set())
f.labels = function_labels.union(set(labels))
return f
return Decorator
| [
"def",
"SetLabel",
"(",
"*",
"labels",
")",
":",
"def",
"Decorator",
"(",
"f",
")",
":",
"function_labels",
"=",
"getattr",
"(",
"f",
",",
"'labels'",
",",
"set",
"(",
")",
")",
"f",
".",
"labels",
"=",
"function_labels",
".",
"union",
"(",
"set",
... | sets a label on a function so we can run tests with different types . | train | false |
32,030 | def iscsi_logout(target_name=None):
if target_name:
cmd = ('iscsiadm --mode node --logout -T %s' % target_name)
else:
cmd = 'iscsiadm --mode node --logout all'
output = utils.system_output(cmd)
target_logout = ''
if ('successful' in output):
target_logout = target_name
return target_logout
| [
"def",
"iscsi_logout",
"(",
"target_name",
"=",
"None",
")",
":",
"if",
"target_name",
":",
"cmd",
"=",
"(",
"'iscsiadm --mode node --logout -T %s'",
"%",
"target_name",
")",
"else",
":",
"cmd",
"=",
"'iscsiadm --mode node --logout all'",
"output",
"=",
"utils",
"... | logout from a target . | train | false |
32,031 | @with_setup(prepare_stdout)
def test_output_snippets_with_groups_within_double_quotes_colorful():
runner = Runner(feature_name('double-quoted-snippet'), verbosity=3, no_color=False)
runner.run()
assert_stdout_lines(u'\n\x1b[1;37mFeature: double-quoted snippet proposal \x1b[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:1\x1b[0m\n\n\x1b[1;37m Scenario: Propose matched groups \x1b[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:2\x1b[0m\n\x1b[0;33m Given I have "stuff here" and "more @#$%\u02c6& bizar sutff h3r3" \x1b[1;30m# tests/functional/output_features/double-quoted-snippet/double-quoted-snippet.feature:3\x1b[0m\n\n\x1b[1;37m1 feature (\x1b[0;31m0 passed\x1b[1;37m)\x1b[0m\n\x1b[1;37m1 scenario (\x1b[0;31m0 passed\x1b[1;37m)\x1b[0m\n\x1b[1;37m1 step (\x1b[0;33m1 undefined\x1b[1;37m, \x1b[1;32m0 passed\x1b[1;37m)\x1b[0m\n\n\x1b[0;33mYou can implement step definitions for undefined steps with these snippets:\n\n# -*- coding: utf-8 -*-\nfrom lettuce import step\n\n@step(u\'Given I have "([^"]*)" and "([^"]*)"\')\ndef given_i_have_group1_and_group2(step, group1, group2):\n assert False, \'This step must be implemented\'\x1b[0m\n')
| [
"@",
"with_setup",
"(",
"prepare_stdout",
")",
"def",
"test_output_snippets_with_groups_within_double_quotes_colorful",
"(",
")",
":",
"runner",
"=",
"Runner",
"(",
"feature_name",
"(",
"'double-quoted-snippet'",
")",
",",
"verbosity",
"=",
"3",
",",
"no_color",
"=",
... | testing that the proposed snippet is clever enough to identify groups within double quotes . | train | false |
32,033 | def post_to_custom_auth_form(request):
pipeline_data = request.session.pop('tpa_custom_auth_entry_data', None)
if (not pipeline_data):
raise Http404
data = {'post_url': pipeline_data['post_url'], 'data': pipeline_data['data'], 'hmac': pipeline_data['hmac']}
return render(request, 'third_party_auth/post_custom_auth_entry.html', data)
| [
"def",
"post_to_custom_auth_form",
"(",
"request",
")",
":",
"pipeline_data",
"=",
"request",
".",
"session",
".",
"pop",
"(",
"'tpa_custom_auth_entry_data'",
",",
"None",
")",
"if",
"(",
"not",
"pipeline_data",
")",
":",
"raise",
"Http404",
"data",
"=",
"{",
... | redirect to a custom login/register page . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.