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 |
|---|---|---|---|---|---|
51,857 | def _get_old_package_license_ids(migrate_engine):
old_ids = {}
select_licenses = 'SELECT id, license_id FROM package;'
q = migrate_engine.execute(select_licenses)
for (id, license_id) in q:
old_ids[id] = license_id
return old_ids
| [
"def",
"_get_old_package_license_ids",
"(",
"migrate_engine",
")",
":",
"old_ids",
"=",
"{",
"}",
"select_licenses",
"=",
"'SELECT id, license_id FROM package;'",
"q",
"=",
"migrate_engine",
".",
"execute",
"(",
"select_licenses",
")",
"for",
"(",
"id",
",",
"licens... | returns a dict of old license ids . | train | false |
51,860 | def get_disks(vm_):
with _get_xapi_session() as xapi:
disk = {}
vm_uuid = _get_label_uuid(xapi, 'VM', vm_)
if (vm_uuid is False):
return False
for vbd in xapi.VM.get_VBDs(vm_uuid):
dev = xapi.VBD.get_device(vbd)
if (not dev):
continue
prop = xapi.VBD.get_runtime_properties(vbd)
disk[dev] = {'backend': prop['backend'], 'type': prop['device-type'], 'protocol': prop['protocol']}
return disk
| [
"def",
"get_disks",
"(",
"vm_",
")",
":",
"with",
"_get_xapi_session",
"(",
")",
"as",
"xapi",
":",
"disk",
"=",
"{",
"}",
"vm_uuid",
"=",
"_get_label_uuid",
"(",
"xapi",
",",
"'VM'",
",",
"vm_",
")",
"if",
"(",
"vm_uuid",
"is",
"False",
")",
":",
... | return the disks of a named vm cli example: . | train | true |
51,861 | def decode_der(obj_class, binstr):
der = obj_class()
der.decode(binstr)
return der
| [
"def",
"decode_der",
"(",
"obj_class",
",",
"binstr",
")",
":",
"der",
"=",
"obj_class",
"(",
")",
"der",
".",
"decode",
"(",
"binstr",
")",
"return",
"der"
] | instantiate a der object class . | train | false |
51,862 | def _instrumented_test_render(self, *args, **data):
with _MAKO_LOCK:
def mako_callable_(context, *args, **kwargs):
template_rendered.send(sender=self, template=self, context=context)
return self.original_callable_[(-1)](context, *args, **kwargs)
if hasattr(self, 'original_callable_'):
self.original_callable_.append(self.callable_)
else:
self.original_callable_ = [self.callable_]
self.callable_ = mako_callable_
try:
response = runtime._render(self, self.original_callable_[(-1)], args, data)
finally:
self.callable_ = self.original_callable_.pop()
return response
| [
"def",
"_instrumented_test_render",
"(",
"self",
",",
"*",
"args",
",",
"**",
"data",
")",
":",
"with",
"_MAKO_LOCK",
":",
"def",
"mako_callable_",
"(",
"context",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"template_rendered",
".",
"send",
"(",
"s... | an instrumented template render method . | train | false |
51,864 | def find_full_path(path_to_file):
for (subdir, dirs, files) in os.walk('.'):
full = os.path.relpath(os.path.join(subdir, path_to_file))
if os.path.exists(full):
return full
| [
"def",
"find_full_path",
"(",
"path_to_file",
")",
":",
"for",
"(",
"subdir",
",",
"dirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"'.'",
")",
":",
"full",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"join",
"(",... | find the full path where we only have a relative path from somewhere in the tree . | train | false |
51,867 | def aifile_list(request, page=None):
if (not test_user_authenticated(request)):
return login(request, next='/cobbler_web/aifile/list', expired=True)
aifiles = remote.get_autoinstall_templates(request.session['token'])
aifile_list = []
for aifile in aifiles:
aifile_list.append((aifile, 'editable'))
t = get_template('aifile_list.tmpl')
html = t.render(RequestContext(request, {'what': 'aifile', 'ai_files': aifile_list, 'version': remote.extended_version(request.session['token'])['version'], 'username': username, 'item_count': len(aifile_list[0])}))
return HttpResponse(html)
| [
"def",
"aifile_list",
"(",
"request",
",",
"page",
"=",
"None",
")",
":",
"if",
"(",
"not",
"test_user_authenticated",
"(",
"request",
")",
")",
":",
"return",
"login",
"(",
"request",
",",
"next",
"=",
"'/cobbler_web/aifile/list'",
",",
"expired",
"=",
"T... | list all automatic os installation templates and link to their edit pages . | train | false |
51,868 | def upload_project(local_dir=None, remote_dir='', use_sudo=False):
runner = ((use_sudo and sudo) or run)
local_dir = (local_dir or os.getcwd())
local_dir = local_dir.rstrip(os.sep)
(local_path, local_name) = os.path.split(local_dir)
tar_file = ('%s.tar.gz' % local_name)
target_tar = os.path.join(remote_dir, tar_file)
tmp_folder = mkdtemp()
try:
tar_path = os.path.join(tmp_folder, tar_file)
local(('tar -czf %s -C %s %s' % (tar_path, local_path, local_name)))
put(tar_path, target_tar, use_sudo=use_sudo)
with cd(remote_dir):
try:
runner(('tar -xzf %s' % tar_file))
finally:
runner(('rm -f %s' % tar_file))
finally:
local(('rm -rf %s' % tmp_folder))
| [
"def",
"upload_project",
"(",
"local_dir",
"=",
"None",
",",
"remote_dir",
"=",
"''",
",",
"use_sudo",
"=",
"False",
")",
":",
"runner",
"=",
"(",
"(",
"use_sudo",
"and",
"sudo",
")",
"or",
"run",
")",
"local_dir",
"=",
"(",
"local_dir",
"or",
"os",
... | upload the current project to a remote system via tar/gzip . | train | false |
51,869 | def _TestAuthViewfinderUser(action, tester, user_dict, device_dict=None, user_cookie=None):
if ('email' in user_dict):
ident_dict = {'key': ('Email:%s' % user_dict['email']), 'authority': 'Viewfinder'}
else:
ident_dict = {'key': ('Phone:%s' % user_dict['phone']), 'authority': 'Viewfinder'}
response = _AuthViewfinderUser(tester, action, user_dict, ident_dict, device_dict, user_cookie)
cookie_user_dict = tester.DecodeUserCookie(tester.GetCookieFromResponse(response))
if ((action != 'link') and (not ((action == 'login') and ('password' in user_dict)))):
assert ('confirm_time' in cookie_user_dict), cookie_user_dict
else:
assert ('confirm_time' not in cookie_user_dict), cookie_user_dict
return auth_test._ValidateAuthUser(tester, action, user_dict, ident_dict, device_dict, user_cookie, response)
| [
"def",
"_TestAuthViewfinderUser",
"(",
"action",
",",
"tester",
",",
"user_dict",
",",
"device_dict",
"=",
"None",
",",
"user_cookie",
"=",
"None",
")",
":",
"if",
"(",
"'email'",
"in",
"user_dict",
")",
":",
"ident_dict",
"=",
"{",
"'key'",
":",
"(",
"'... | called by the servicetester in order to test login/viewfinder . | train | false |
51,870 | def start_cycle():
dg['cyc'] = init_cycle()
dg['cache'] = {}
dg['humanize_unsupported'] = False
| [
"def",
"start_cycle",
"(",
")",
":",
"dg",
"[",
"'cyc'",
"]",
"=",
"init_cycle",
"(",
")",
"dg",
"[",
"'cache'",
"]",
"=",
"{",
"}",
"dg",
"[",
"'humanize_unsupported'",
"]",
"=",
"False"
] | notify from rainbow . | train | false |
51,871 | @synchronized(NZB_LOCK)
def backup_exists(filename):
path = cfg.nzb_backup_dir.get_path()
return (path and os.path.exists(os.path.join(path, (filename + '.gz'))))
| [
"@",
"synchronized",
"(",
"NZB_LOCK",
")",
"def",
"backup_exists",
"(",
"filename",
")",
":",
"path",
"=",
"cfg",
".",
"nzb_backup_dir",
".",
"get_path",
"(",
")",
"return",
"(",
"path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
... | return true if backup exists and no_dupes is set . | train | false |
51,873 | @missing_name
def decoratedFunction():
return None
| [
"@",
"missing_name",
"def",
"decoratedFunction",
"(",
")",
":",
"return",
"None"
] | decoratedfunction docstring . | train | false |
51,874 | def krogh_interpolate(xi, yi, x, der=0, axis=0):
P = KroghInterpolator(xi, yi, axis=axis)
if (der == 0):
return P(x)
elif _isscalar(der):
return P.derivative(x, der=der)
else:
return P.derivatives(x, der=(np.amax(der) + 1))[der]
| [
"def",
"krogh_interpolate",
"(",
"xi",
",",
"yi",
",",
"x",
",",
"der",
"=",
"0",
",",
"axis",
"=",
"0",
")",
":",
"P",
"=",
"KroghInterpolator",
"(",
"xi",
",",
"yi",
",",
"axis",
"=",
"axis",
")",
"if",
"(",
"der",
"==",
"0",
")",
":",
"ret... | convenience function for polynomial interpolation . | train | false |
51,875 | def make_violin_rugplot(vals, pdf_max, distance, color='#1f77b4'):
return graph_objs.Scatter(y=vals, x=([((- pdf_max) - distance)] * len(vals)), marker=graph_objs.Marker(color=color, symbol='line-ew-open'), mode='markers', name='', showlegend=False, hoverinfo='y')
| [
"def",
"make_violin_rugplot",
"(",
"vals",
",",
"pdf_max",
",",
"distance",
",",
"color",
"=",
"'#1f77b4'",
")",
":",
"return",
"graph_objs",
".",
"Scatter",
"(",
"y",
"=",
"vals",
",",
"x",
"=",
"(",
"[",
"(",
"(",
"-",
"pdf_max",
")",
"-",
"distanc... | returns a rugplot fig for a violin plot . | train | false |
51,876 | def update_downtime(guest, instance, olddowntime, downtime_steps, elapsed):
LOG.debug('Current %(dt)s elapsed %(elapsed)d steps %(steps)s', {'dt': olddowntime, 'elapsed': elapsed, 'steps': downtime_steps}, instance=instance)
thisstep = None
for step in downtime_steps:
if (elapsed > step[0]):
thisstep = step
if (thisstep is None):
LOG.debug('No current step', instance=instance)
return olddowntime
if (thisstep[1] == olddowntime):
LOG.debug('Downtime does not need to change', instance=instance)
return olddowntime
LOG.info(_LI('Increasing downtime to %(downtime)d ms after %(waittime)d sec elapsed time'), {'downtime': thisstep[1], 'waittime': thisstep[0]}, instance=instance)
try:
guest.migrate_configure_max_downtime(thisstep[1])
except libvirt.libvirtError as e:
LOG.warning(_LW('Unable to increase max downtime to %(time)dms: %(e)s'), {'time': thisstep[1], 'e': e}, instance=instance)
return thisstep[1]
| [
"def",
"update_downtime",
"(",
"guest",
",",
"instance",
",",
"olddowntime",
",",
"downtime_steps",
",",
"elapsed",
")",
":",
"LOG",
".",
"debug",
"(",
"'Current %(dt)s elapsed %(elapsed)d steps %(steps)s'",
",",
"{",
"'dt'",
":",
"olddowntime",
",",
"'elapsed'",
... | update max downtime if needed . | train | false |
51,878 | def cm(value):
return dpi2px(value, 'cm')
| [
"def",
"cm",
"(",
"value",
")",
":",
"return",
"dpi2px",
"(",
"value",
",",
"'cm'",
")"
] | convert from centimeters to pixels . | train | false |
51,879 | def get_br_int_port_name(prefix, port_id):
return ('%si-%s' % (prefix, port_id))[:constants.DEVICE_NAME_MAX_LEN]
| [
"def",
"get_br_int_port_name",
"(",
"prefix",
",",
"port_id",
")",
":",
"return",
"(",
"'%si-%s'",
"%",
"(",
"prefix",
",",
"port_id",
")",
")",
"[",
":",
"constants",
".",
"DEVICE_NAME_MAX_LEN",
"]"
] | return the ovs port name for the given port id . | train | false |
51,882 | def discretize_integrate_1D(model, x_range):
from scipy.integrate import quad
x = np.arange((x_range[0] - 0.5), (x_range[1] + 0.5))
values = np.array([])
for i in range((x.size - 1)):
values = np.append(values, quad(model, x[i], x[(i + 1)])[0])
return values
| [
"def",
"discretize_integrate_1D",
"(",
"model",
",",
"x_range",
")",
":",
"from",
"scipy",
".",
"integrate",
"import",
"quad",
"x",
"=",
"np",
".",
"arange",
"(",
"(",
"x_range",
"[",
"0",
"]",
"-",
"0.5",
")",
",",
"(",
"x_range",
"[",
"1",
"]",
"... | discretize model by integrating numerically the model over the bin . | train | false |
51,885 | def setup_streams_fixtures(testcase):
testcase.mock_tracker = scaffold.MockTracker()
testcase.stream_file_paths = dict(stdin=tempfile.mktemp(), stdout=tempfile.mktemp(), stderr=tempfile.mktemp())
testcase.stream_files_by_name = dict(((name, FakeFileDescriptorStringIO()) for name in ['stdin', 'stdout', 'stderr']))
testcase.stream_files_by_path = dict(((testcase.stream_file_paths[name], testcase.stream_files_by_name[name]) for name in ['stdin', 'stdout', 'stderr']))
scaffold.mock('os.dup2', tracker=testcase.mock_tracker)
| [
"def",
"setup_streams_fixtures",
"(",
"testcase",
")",
":",
"testcase",
".",
"mock_tracker",
"=",
"scaffold",
".",
"MockTracker",
"(",
")",
"testcase",
".",
"stream_file_paths",
"=",
"dict",
"(",
"stdin",
"=",
"tempfile",
".",
"mktemp",
"(",
")",
",",
"stdou... | set up common test fixtures for standard streams . | train | false |
51,886 | def update_vouch_flags_action():
def update_vouch_flags(modeladmin, request, queryset):
for profile in queryset:
vouches_received = profile.vouches_received.count()
profile.can_vouch = (vouches_received >= settings.CAN_VOUCH_THRESHOLD)
profile.is_vouched = (vouches_received > 0)
profile.save()
update_vouch_flags.short_description = 'Update vouch flags'
return update_vouch_flags
| [
"def",
"update_vouch_flags_action",
"(",
")",
":",
"def",
"update_vouch_flags",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
")",
":",
"for",
"profile",
"in",
"queryset",
":",
"vouches_received",
"=",
"profile",
".",
"vouches_received",
".",
"count",
"(",... | update can_vouch . | train | false |
51,889 | def md5sum_file(file_name):
f = open(file_name)
digest = md5sum_str(f.read())
f.close()
return digest
| [
"def",
"md5sum_file",
"(",
"file_name",
")",
":",
"f",
"=",
"open",
"(",
"file_name",
")",
"digest",
"=",
"md5sum_str",
"(",
"f",
".",
"read",
"(",
")",
")",
"f",
".",
"close",
"(",
")",
"return",
"digest"
] | calculate md5sum of the file . | train | false |
51,890 | def _zero_volume(path, volume_size):
bs = units.Mi
direct_flags = ('oflag=direct',)
sync_flags = ()
remaining_bytes = volume_size
while remaining_bytes:
zero_blocks = (remaining_bytes // bs)
seek_blocks = ((volume_size - remaining_bytes) // bs)
zero_cmd = ('dd', ('bs=%s' % bs), 'if=/dev/zero', ('of=%s' % path), ('seek=%s' % seek_blocks), ('count=%s' % zero_blocks))
zero_cmd += direct_flags
zero_cmd += sync_flags
if zero_blocks:
utils.execute(run_as_root=True, *zero_cmd)
remaining_bytes %= bs
bs //= units.Ki
direct_flags = ()
sync_flags = ('conv=fdatasync',)
| [
"def",
"_zero_volume",
"(",
"path",
",",
"volume_size",
")",
":",
"bs",
"=",
"units",
".",
"Mi",
"direct_flags",
"=",
"(",
"'oflag=direct'",
",",
")",
"sync_flags",
"=",
"(",
")",
"remaining_bytes",
"=",
"volume_size",
"while",
"remaining_bytes",
":",
"zero_... | write zeros over the specified path . | train | false |
51,891 | def attr_ne(accessing_obj, accessed_obj, *args, **kwargs):
return attr(accessing_obj, accessed_obj, *args, **{'compare': 'ne'})
| [
"def",
"attr_ne",
"(",
"accessing_obj",
",",
"accessed_obj",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"attr",
"(",
"accessing_obj",
",",
"accessed_obj",
",",
"*",
"args",
",",
"**",
"{",
"'compare'",
":",
"'ne'",
"}",
")"
] | usage: attr_gt only true if access_objs attribute != the value given . | train | false |
51,893 | @cache_permission
def can_see_repository_status(user, project):
return (can_commit_translation(user, project) or can_update_translation(user, project))
| [
"@",
"cache_permission",
"def",
"can_see_repository_status",
"(",
"user",
",",
"project",
")",
":",
"return",
"(",
"can_commit_translation",
"(",
"user",
",",
"project",
")",
"or",
"can_update_translation",
"(",
"user",
",",
"project",
")",
")"
] | checks whether user can view repository status . | train | false |
51,897 | def tidy_cli(arguments):
TidyCommandLine().execute_cli(arguments)
| [
"def",
"tidy_cli",
"(",
"arguments",
")",
":",
"TidyCommandLine",
"(",
")",
".",
"execute_cli",
"(",
"arguments",
")"
] | executes tidy similarly as from the command line . | train | false |
51,898 | def _resolve_looppart(parts, asspath, context):
asspath = asspath[:]
index = asspath.pop(0)
for part in parts:
if (part is YES):
continue
if (not hasattr(part, 'itered')):
continue
try:
itered = part.itered()
except TypeError:
continue
for stmt in itered:
try:
assigned = stmt.getitem(index, context)
except (AttributeError, IndexError):
continue
except TypeError:
continue
if (not asspath):
(yield assigned)
elif (assigned is YES):
break
else:
try:
for infered in _resolve_looppart(assigned.infer(context), asspath, context):
(yield infered)
except InferenceError:
break
| [
"def",
"_resolve_looppart",
"(",
"parts",
",",
"asspath",
",",
"context",
")",
":",
"asspath",
"=",
"asspath",
"[",
":",
"]",
"index",
"=",
"asspath",
".",
"pop",
"(",
"0",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"(",
"part",
"is",
"YES",
")"... | recursive function to resolve multiple assignments on loops . | train | false |
51,899 | def lookup_group_plugin(group_type=None):
if (group_type is None):
return _default_group_plugin
return _group_plugins.get(group_type, (_default_organization_plugin if (group_type == 'organization') else _default_group_plugin))
| [
"def",
"lookup_group_plugin",
"(",
"group_type",
"=",
"None",
")",
":",
"if",
"(",
"group_type",
"is",
"None",
")",
":",
"return",
"_default_group_plugin",
"return",
"_group_plugins",
".",
"get",
"(",
"group_type",
",",
"(",
"_default_organization_plugin",
"if",
... | returns the form plugin associated with the given group type . | train | false |
51,900 | def setup_firewall():
from fabtools.require.shorewall import firewall, started
zones = [{'name': 'fw', 'type': 'firewall'}, {'name': 'net', 'type': 'ipv4'}, {'name': 'vz', 'type': 'ipv4'}]
interfaces = [{'zone': 'net', 'interface': 'eth0', 'options': 'proxyarp=1'}, {'zone': 'vz', 'interface': 'venet0', 'options': 'routeback,arp_filter=0'}]
masq = [{'interface': 'eth0', 'source': '192.168.1.0/24'}]
policy = [{'source': '$FW', 'dest': 'net', 'policy': 'ACCEPT'}, {'source': '$FW', 'dest': 'vz', 'policy': 'ACCEPT'}, {'source': 'vz', 'dest': 'net', 'policy': 'ACCEPT'}, {'source': 'net', 'dest': 'all', 'policy': 'DROP', 'log_level': 'info'}, {'source': 'all', 'dest': 'all', 'policy': 'REJECT', 'log_level': 'info'}]
firewall(zones=zones, interfaces=interfaces, policy=policy, masq=masq)
started()
| [
"def",
"setup_firewall",
"(",
")",
":",
"from",
"fabtools",
".",
"require",
".",
"shorewall",
"import",
"firewall",
",",
"started",
"zones",
"=",
"[",
"{",
"'name'",
":",
"'fw'",
",",
"'type'",
":",
"'firewall'",
"}",
",",
"{",
"'name'",
":",
"'net'",
... | shorewall config . | train | false |
51,901 | def arg_byref(args, offset=(-1)):
return args[offset]._obj.value
| [
"def",
"arg_byref",
"(",
"args",
",",
"offset",
"=",
"(",
"-",
"1",
")",
")",
":",
"return",
"args",
"[",
"offset",
"]",
".",
"_obj",
".",
"value"
] | returns the pointer arguments by-reference value . | train | false |
51,902 | def index_satisfying(iterable, condition):
for (i, x) in enumerate(iterable):
if condition(x):
return i
try:
return (i + 1)
except NameError:
raise ValueError('iterable must be non-empty')
| [
"def",
"index_satisfying",
"(",
"iterable",
",",
"condition",
")",
":",
"for",
"(",
"i",
",",
"x",
")",
"in",
"enumerate",
"(",
"iterable",
")",
":",
"if",
"condition",
"(",
"x",
")",
":",
"return",
"i",
"try",
":",
"return",
"(",
"i",
"+",
"1",
... | returns the index of the first element in iterable that satisfies the given condition . | train | false |
51,903 | def test_gnb_priors():
clf = GaussianNB(priors=np.array([0.3, 0.7])).fit(X, y)
assert_array_almost_equal(clf.predict_proba([[(-0.1), (-0.1)]]), np.array([[0.825303662161683, 0.174696337838317]]), 8)
assert_array_equal(clf.class_prior_, np.array([0.3, 0.7]))
| [
"def",
"test_gnb_priors",
"(",
")",
":",
"clf",
"=",
"GaussianNB",
"(",
"priors",
"=",
"np",
".",
"array",
"(",
"[",
"0.3",
",",
"0.7",
"]",
")",
")",
".",
"fit",
"(",
"X",
",",
"y",
")",
"assert_array_almost_equal",
"(",
"clf",
".",
"predict_proba",... | test whether the class prior override is properly used . | train | false |
51,904 | def getJumpPoint(begin, end, loop, runningJumpSpace):
segment = (begin - end)
segmentLength = abs(segment)
if (segmentLength == 0.0):
return begin
segment /= segmentLength
distancePoint = DistancePoint(begin, loop, runningJumpSpace, segment)
if (distancePoint.distance == runningJumpSpace):
return distancePoint.point
effectiveDistance = distancePoint.distance
jumpPoint = distancePoint.point
segmentLeft = complex(0.7071067811865476, (-0.7071067811865476))
distancePoint = DistancePoint(begin, loop, runningJumpSpace, segmentLeft)
distancePoint.distance *= 0.5
if (distancePoint.distance > effectiveDistance):
effectiveDistance = distancePoint.distance
jumpPoint = distancePoint.point
segmentRight = complex(0.7071067811865476, 0.7071067811865476)
distancePoint = DistancePoint(begin, loop, runningJumpSpace, segmentRight)
distancePoint.distance *= 0.5
if (distancePoint.distance > effectiveDistance):
effectiveDistance = distancePoint.distance
jumpPoint = distancePoint.point
return jumpPoint
| [
"def",
"getJumpPoint",
"(",
"begin",
",",
"end",
",",
"loop",
",",
"runningJumpSpace",
")",
":",
"segment",
"=",
"(",
"begin",
"-",
"end",
")",
"segmentLength",
"=",
"abs",
"(",
"segment",
")",
"if",
"(",
"segmentLength",
"==",
"0.0",
")",
":",
"return... | get running jump point inside loop . | train | false |
51,906 | def iter_blocks(course):
def visit(block):
' get child blocks '
(yield block)
for child in block.get_children():
for descendant in visit(child):
(yield descendant)
return visit(course)
| [
"def",
"iter_blocks",
"(",
"course",
")",
":",
"def",
"visit",
"(",
"block",
")",
":",
"(",
"yield",
"block",
")",
"for",
"child",
"in",
"block",
".",
"get_children",
"(",
")",
":",
"for",
"descendant",
"in",
"visit",
"(",
"child",
")",
":",
"(",
"... | returns an iterator over all of the blocks in a course . | train | false |
51,908 | def _calculate_num_threads(batch_size, shuffle):
if shuffle:
return min(10, int(round(math.sqrt(batch_size))))
else:
return 1
| [
"def",
"_calculate_num_threads",
"(",
"batch_size",
",",
"shuffle",
")",
":",
"if",
"shuffle",
":",
"return",
"min",
"(",
"10",
",",
"int",
"(",
"round",
"(",
"math",
".",
"sqrt",
"(",
"batch_size",
")",
")",
")",
")",
"else",
":",
"return",
"1"
] | calculates an appropriate number of threads for creating this database . | train | false |
51,909 | def reverseNameFromIPv6Address(address):
fullHex = ''.join((('%02x' % (ord(c),)) for c in socket.inet_pton(socket.AF_INET6, address)))
tokens = (list(reversed(fullHex)) + ['ip6', 'arpa', ''])
return '.'.join(tokens)
| [
"def",
"reverseNameFromIPv6Address",
"(",
"address",
")",
":",
"fullHex",
"=",
"''",
".",
"join",
"(",
"(",
"(",
"'%02x'",
"%",
"(",
"ord",
"(",
"c",
")",
",",
")",
")",
"for",
"c",
"in",
"socket",
".",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
... | return a reverse domain name for the given ipv6 address . | train | false |
51,910 | def energy_corrections(perturbation, n, a=10, mass=0.5):
(x, _a) = var('x _a')
Vnm = (lambda n, m, a: Integral(((X_n(n, a, x) * X_n(m, a, x)) * perturbation.subs({_a: a})), (x, 0, a)).n())
return (E_n(n, a, mass).evalf(), Vnm(n, n, a).evalf(), (((Vnm(n, (n - 1), a) ** 2) / (E_n(n, a, mass) - E_n((n - 1), a, mass))) + ((Vnm(n, (n + 1), a) ** 2) / (E_n(n, a, mass) - E_n((n + 1), a, mass)))).evalf())
| [
"def",
"energy_corrections",
"(",
"perturbation",
",",
"n",
",",
"a",
"=",
"10",
",",
"mass",
"=",
"0.5",
")",
":",
"(",
"x",
",",
"_a",
")",
"=",
"var",
"(",
"'x _a'",
")",
"Vnm",
"=",
"(",
"lambda",
"n",
",",
"m",
",",
"a",
":",
"Integral",
... | calculating first two order corrections due to perturbation theory and returns tuple where zero element is unperturbated energy . | train | false |
51,911 | def get_pickleable_exception(exc):
nearest = find_nearest_pickleable_exception(exc)
if nearest:
return nearest
try:
pickle.dumps(deepcopy(exc))
except Exception:
return UnpickleableExceptionWrapper.from_exception(exc)
return exc
| [
"def",
"get_pickleable_exception",
"(",
"exc",
")",
":",
"nearest",
"=",
"find_nearest_pickleable_exception",
"(",
"exc",
")",
"if",
"nearest",
":",
"return",
"nearest",
"try",
":",
"pickle",
".",
"dumps",
"(",
"deepcopy",
"(",
"exc",
")",
")",
"except",
"Ex... | make sure exception is pickleable . | train | false |
51,912 | def add_arguments(parser):
adder = (getattr(parser, 'add_argument', None) or getattr(parser, 'add_option'))
adder('-l', '--log-level', default=logging.INFO, type=log_level, help='Set log level (DEBUG, INFO, WARNING, ERROR)')
| [
"def",
"add_arguments",
"(",
"parser",
")",
":",
"adder",
"=",
"(",
"getattr",
"(",
"parser",
",",
"'add_argument'",
",",
"None",
")",
"or",
"getattr",
"(",
"parser",
",",
"'add_option'",
")",
")",
"adder",
"(",
"'-l'",
",",
"'--log-level'",
",",
"defaul... | add arguments to an argumentparser or optionparser for purposes of grabbing a logging level . | train | true |
51,914 | def send_tarball(tarball):
wrapper = FileWrapper(tarball)
response = HttpResponse(wrapper, content_type='application/x-tgz')
response['Content-Disposition'] = ('attachment; filename=%s' % os.path.basename(tarball.name.encode('utf-8')))
response['Content-Length'] = os.path.getsize(tarball.name)
return response
| [
"def",
"send_tarball",
"(",
"tarball",
")",
":",
"wrapper",
"=",
"FileWrapper",
"(",
"tarball",
")",
"response",
"=",
"HttpResponse",
"(",
"wrapper",
",",
"content_type",
"=",
"'application/x-tgz'",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"(",
... | renders a tarball to response . | train | false |
51,915 | def create_exploration_summary(exploration_id, contributor_id_to_add):
exploration = get_exploration_by_id(exploration_id)
exp_summary = compute_summary_of_exploration(exploration, contributor_id_to_add)
save_exploration_summary(exp_summary)
| [
"def",
"create_exploration_summary",
"(",
"exploration_id",
",",
"contributor_id_to_add",
")",
":",
"exploration",
"=",
"get_exploration_by_id",
"(",
"exploration_id",
")",
"exp_summary",
"=",
"compute_summary_of_exploration",
"(",
"exploration",
",",
"contributor_id_to_add",... | create summary of an exploration and store in datastore . | train | false |
51,916 | @step('I use the log record configuration')
def step_use_log_record_configuration(context):
assert context.table, 'REQUIRE: context.table'
context.table.require_columns(['property', 'value'])
for row in context.table.rows:
property_name = row['property']
value = row['value']
if (property_name == 'format'):
context.log_record_format = value
elif (property_name == 'datefmt'):
context.log_record_datefmt = value
else:
raise KeyError(('Unknown property=%s' % property_name))
| [
"@",
"step",
"(",
"'I use the log record configuration'",
")",
"def",
"step_use_log_record_configuration",
"(",
"context",
")",
":",
"assert",
"context",
".",
"table",
",",
"'REQUIRE: context.table'",
"context",
".",
"table",
".",
"require_columns",
"(",
"[",
"'proper... | define log record configuration parameters . | train | true |
51,917 | def is_allowed_country(country_object, context=None):
if (context and context.get('allowed_countries')):
allowed_countries = context.get('allowed_countries')
return ((country_object.name.lower() in allowed_countries) or (country_object.alpha2.lower() in allowed_countries))
return True
| [
"def",
"is_allowed_country",
"(",
"country_object",
",",
"context",
"=",
"None",
")",
":",
"if",
"(",
"context",
"and",
"context",
".",
"get",
"(",
"'allowed_countries'",
")",
")",
":",
"allowed_countries",
"=",
"context",
".",
"get",
"(",
"'allowed_countries'... | check if country is allowed . | train | false |
51,918 | @utils.arg('--all-tenants', dest='all_tenants', metavar='<0|1>', nargs='?', type=int, const=1, default=int(strutils.bool_from_string(os.environ.get('ALL_TENANTS', 'false'), True)), help=_('Display information from all tenants (Admin only).'))
@deprecated_network
def do_secgroup_list(cs, args):
search_opts = {'all_tenants': args.all_tenants}
columns = ['Id', 'Name', 'Description']
if args.all_tenants:
columns.append('Tenant_ID')
groups = cs.security_groups.list(search_opts=search_opts)
utils.print_list(groups, columns)
| [
"@",
"utils",
".",
"arg",
"(",
"'--all-tenants'",
",",
"dest",
"=",
"'all_tenants'",
",",
"metavar",
"=",
"'<0|1>'",
",",
"nargs",
"=",
"'?'",
",",
"type",
"=",
"int",
",",
"const",
"=",
"1",
",",
"default",
"=",
"int",
"(",
"strutils",
".",
"bool_fr... | list security groups for the current tenant . | train | false |
51,919 | def img_to_graph(img, mask=None, return_as=sparse.coo_matrix, dtype=None):
img = np.atleast_3d(img)
(n_x, n_y, n_z) = img.shape
return _to_graph(n_x, n_y, n_z, mask, img, return_as, dtype)
| [
"def",
"img_to_graph",
"(",
"img",
",",
"mask",
"=",
"None",
",",
"return_as",
"=",
"sparse",
".",
"coo_matrix",
",",
"dtype",
"=",
"None",
")",
":",
"img",
"=",
"np",
".",
"atleast_3d",
"(",
"img",
")",
"(",
"n_x",
",",
"n_y",
",",
"n_z",
")",
"... | graph of the pixel-to-pixel gradient connections edges are weighted with the gradient values . | train | false |
51,920 | def get_closest(word, possibilities, n=3, cutoff=0.6, fallback_to_first=True):
possibilities = list(possibilities)
try:
return get_close_matches(word, possibilities, n, cutoff)[0]
except IndexError:
if fallback_to_first:
return possibilities[0]
| [
"def",
"get_closest",
"(",
"word",
",",
"possibilities",
",",
"n",
"=",
"3",
",",
"cutoff",
"=",
"0.6",
",",
"fallback_to_first",
"=",
"True",
")",
":",
"possibilities",
"=",
"list",
"(",
"possibilities",
")",
"try",
":",
"return",
"get_close_matches",
"("... | returns closest match or just first from possibilities . | train | false |
51,921 | def iter_markdown_lines(markdown_html):
warnings.warn(u'reviewboard.reviews.markdown_utils.iter_markdown_lines is deprecated. Please use djblets.markdown.iter_markdown_lines.', DeprecationWarning)
return djblets_markdown.iter_markdown_lines(markdown_html)
| [
"def",
"iter_markdown_lines",
"(",
"markdown_html",
")",
":",
"warnings",
".",
"warn",
"(",
"u'reviewboard.reviews.markdown_utils.iter_markdown_lines is deprecated. Please use djblets.markdown.iter_markdown_lines.'",
",",
"DeprecationWarning",
")",
"return",
"djblets_markdown",
".",
... | iterates over lines of markdown . | train | false |
51,922 | def user_domain_match(A, B):
A = A.lower()
B = B.lower()
if (not (liberal_is_HDN(A) and liberal_is_HDN(B))):
if (A == B):
return True
return False
initial_dot = B.startswith('.')
if (initial_dot and A.endswith(B)):
return True
if ((not initial_dot) and (A == B)):
return True
return False
| [
"def",
"user_domain_match",
"(",
"A",
",",
"B",
")",
":",
"A",
"=",
"A",
".",
"lower",
"(",
")",
"B",
"=",
"B",
".",
"lower",
"(",
")",
"if",
"(",
"not",
"(",
"liberal_is_HDN",
"(",
"A",
")",
"and",
"liberal_is_HDN",
"(",
"B",
")",
")",
")",
... | for blocking/accepting domains . | train | true |
51,924 | @mock_ec2
def test_eip_allocate_invalid_domain():
conn = boto.connect_ec2(u'the_key', u'the_secret')
with assert_raises(EC2ResponseError) as cm:
conn.allocate_address(domain=u'bogus')
cm.exception.code.should.equal(u'InvalidParameterValue')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
| [
"@",
"mock_ec2",
"def",
"test_eip_allocate_invalid_domain",
"(",
")",
":",
"conn",
"=",
"boto",
".",
"connect_ec2",
"(",
"u'the_key'",
",",
"u'the_secret'",
")",
"with",
"assert_raises",
"(",
"EC2ResponseError",
")",
"as",
"cm",
":",
"conn",
".",
"allocate_addre... | allocate eip invalid domain . | train | false |
51,925 | def get_conf():
if (_CORE_SITE_DICT is None):
_parse_core_site()
return _CORE_SITE_DICT
| [
"def",
"get_conf",
"(",
")",
":",
"if",
"(",
"_CORE_SITE_DICT",
"is",
"None",
")",
":",
"_parse_core_site",
"(",
")",
"return",
"_CORE_SITE_DICT"
] | get_conf() -> confparse object for core-site . | train | false |
51,927 | def authentication_required(url, authenticator, abort_on):
realm = authenticator.realm()
if realm:
msg = '<b>{}</b> says:<br/>{}'.format(html.escape(url.toDisplayString()), html.escape(realm))
else:
msg = '<b>{}</b> needs authentication'.format(html.escape(url.toDisplayString()))
answer = message.ask(title='Authentication required', text=msg, mode=usertypes.PromptMode.user_pwd, abort_on=abort_on)
if (answer is not None):
authenticator.setUser(answer.user)
authenticator.setPassword(answer.password)
return answer
| [
"def",
"authentication_required",
"(",
"url",
",",
"authenticator",
",",
"abort_on",
")",
":",
"realm",
"=",
"authenticator",
".",
"realm",
"(",
")",
"if",
"realm",
":",
"msg",
"=",
"'<b>{}</b> says:<br/>{}'",
".",
"format",
"(",
"html",
".",
"escape",
"(",
... | ask a prompt for an authentication question . | train | false |
51,928 | def _cmp_recformats(f1, f2):
if ((f1[0] == 'a') and (f2[0] == 'a')):
return cmp(int(f1[1:]), int(f2[1:]))
else:
(f1, f2) = (NUMPY2FITS[f1], NUMPY2FITS[f2])
return cmp(FORMATORDER.index(f1), FORMATORDER.index(f2))
| [
"def",
"_cmp_recformats",
"(",
"f1",
",",
"f2",
")",
":",
"if",
"(",
"(",
"f1",
"[",
"0",
"]",
"==",
"'a'",
")",
"and",
"(",
"f2",
"[",
"0",
"]",
"==",
"'a'",
")",
")",
":",
"return",
"cmp",
"(",
"int",
"(",
"f1",
"[",
"1",
":",
"]",
")",... | compares two numpy recformats using the ordering given by formatorder . | train | false |
51,929 | def mark_sender():
try:
mid = request.args[0]
except:
raise SyntaxError
mtable = s3db.msg_message
stable = s3db.msg_sender
srecord = db((mtable.id == mid)).select(mtable.from_address, limitby=(0, 1)).first()
sender = srecord.from_address
record = db((stable.sender == sender)).select(stable.id, limitby=(0, 1)).first()
if record:
args = 'update'
else:
args = 'create'
url = URL(f='sender', args=args, vars=dict(sender=sender))
redirect(url)
| [
"def",
"mark_sender",
"(",
")",
":",
"try",
":",
"mid",
"=",
"request",
".",
"args",
"[",
"0",
"]",
"except",
":",
"raise",
"SyntaxError",
"mtable",
"=",
"s3db",
".",
"msg_message",
"stable",
"=",
"s3db",
".",
"msg_sender",
"srecord",
"=",
"db",
"(",
... | assign priority to the given sender . | train | false |
51,931 | def _parallel_pairwise(X, Y, func, n_jobs, **kwds):
if (n_jobs < 0):
n_jobs = max(((cpu_count() + 1) + n_jobs), 1)
if (Y is None):
Y = X
if (n_jobs == 1):
return func(X, Y, **kwds)
fd = delayed(func)
ret = Parallel(n_jobs=n_jobs, verbose=0)((fd(X, Y[s], **kwds) for s in gen_even_slices(Y.shape[0], n_jobs)))
return np.hstack(ret)
| [
"def",
"_parallel_pairwise",
"(",
"X",
",",
"Y",
",",
"func",
",",
"n_jobs",
",",
"**",
"kwds",
")",
":",
"if",
"(",
"n_jobs",
"<",
"0",
")",
":",
"n_jobs",
"=",
"max",
"(",
"(",
"(",
"cpu_count",
"(",
")",
"+",
"1",
")",
"+",
"n_jobs",
")",
... | break the pairwise matrix in n_jobs even slices and compute them in parallel . | train | false |
51,933 | @handle_response_format
@treeio_login_required
@_process_mass_form
def index_sent(request, response_format='html'):
query = (Q(reply_to__isnull=True) & Q(author=request.user.profile.get_contact()))
if request.GET:
query = (query & _get_filter_query(request.GET))
objects = Object.filter_by_request(request, Message.objects.filter(query))
else:
objects = Object.filter_by_request(request, Message.objects.filter(query))
filters = FilterForm(request.user.profile, 'title', request.GET)
context = _get_default_context(request)
context.update({'filters': filters, 'messages': objects})
return render_to_response('messaging/index_sent', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"@",
"_process_mass_form",
"def",
"index_sent",
"(",
"request",
",",
"response_format",
"=",
"'html'",
")",
":",
"query",
"=",
"(",
"Q",
"(",
"reply_to__isnull",
"=",
"True",
")",
"&",
"Q",
"(",
"aut... | sent messages index page . | train | false |
51,935 | def p_command_stop(p):
p[0] = ('STOP',)
| [
"def",
"p_command_stop",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"(",
"'STOP'",
",",
")"
] | command : stop . | train | false |
51,936 | def _validate_resource(resource):
try:
if (resource is not None):
resource = resourceprep(resource)
if (not resource):
raise InvalidJID(u'Resource must not be 0 bytes')
if (len(resource) > 1023):
raise InvalidJID(u'Resource must be less than 1024 bytes')
return resource
except stringprep_profiles.StringPrepError:
raise InvalidJID(u'Invalid resource')
| [
"def",
"_validate_resource",
"(",
"resource",
")",
":",
"try",
":",
"if",
"(",
"resource",
"is",
"not",
"None",
")",
":",
"resource",
"=",
"resourceprep",
"(",
"resource",
")",
"if",
"(",
"not",
"resource",
")",
":",
"raise",
"InvalidJID",
"(",
"u'Resour... | validate the resource portion of a jid . | train | false |
51,937 | @flake8ext
def no_translate_debug_logs(logical_line, filename):
for hint in _all_hints:
if logical_line.startswith(('LOG.debug(%s(' % hint)):
(yield (0, "N319 Don't translate debug level logs"))
| [
"@",
"flake8ext",
"def",
"no_translate_debug_logs",
"(",
"logical_line",
",",
"filename",
")",
":",
"for",
"hint",
"in",
"_all_hints",
":",
"if",
"logical_line",
".",
"startswith",
"(",
"(",
"'LOG.debug(%s('",
"%",
"hint",
")",
")",
":",
"(",
"yield",
"(",
... | n319 - check for log . | train | false |
51,939 | def wait_for_debugger(pid):
with log.waitfor('Waiting for debugger') as l:
while (tracer(pid) is None):
time.sleep(0.01)
l.success()
| [
"def",
"wait_for_debugger",
"(",
"pid",
")",
":",
"with",
"log",
".",
"waitfor",
"(",
"'Waiting for debugger'",
")",
"as",
"l",
":",
"while",
"(",
"tracer",
"(",
"pid",
")",
"is",
"None",
")",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"l",
".",
... | wait_for_debugger -> none sleeps until the process with pid pid is being traced . | train | false |
51,940 | def f1_score(y_real, y_pred):
return fbeta_score(y_real, y_pred, 1)
| [
"def",
"f1_score",
"(",
"y_real",
",",
"y_pred",
")",
":",
"return",
"fbeta_score",
"(",
"y_real",
",",
"y_pred",
",",
"1",
")"
] | compute f1 score the f1 score can be interpreted as a weighted average of the precision and recall . | train | false |
51,942 | def install_middleware():
name = u'raven.contrib.django.middleware.SentryMiddleware'
all_names = (name, u'raven.contrib.django.middleware.SentryLogMiddleware')
with settings_lock:
middleware_attr = (u'MIDDLEWARE' if (getattr(settings, u'MIDDLEWARE', None) is not None) else u'MIDDLEWARE_CLASSES')
middleware = (getattr(settings, middleware_attr, ()) or ())
if set(all_names).isdisjoint(set(middleware)):
setattr(settings, middleware_attr, (type(middleware)((name,)) + middleware))
| [
"def",
"install_middleware",
"(",
")",
":",
"name",
"=",
"u'raven.contrib.django.middleware.SentryMiddleware'",
"all_names",
"=",
"(",
"name",
",",
"u'raven.contrib.django.middleware.SentryLogMiddleware'",
")",
"with",
"settings_lock",
":",
"middleware_attr",
"=",
"(",
"u'M... | force installation of sentrymiddlware if its not explicitly present . | train | false |
51,943 | def latest_records(resource, layout, list_id, limit, list_fields, orderby):
(datalist, numrows, ids) = resource.datalist(fields=list_fields, start=None, limit=limit, list_id=list_id, orderby=orderby, layout=layout)
if (numrows == 0):
table = resource.table
available_records = current.db((table.deleted != True))
if available_records.select(table._id, limitby=(0, 1)).first():
msg = DIV(S3CRUD.crud_string(resource.tablename, 'msg_no_match'), _class='empty')
else:
msg = DIV(S3CRUD.crud_string(resource.tablename, 'msg_list_empty'), _class='empty')
data = msg
else:
data = datalist.html()
return data
| [
"def",
"latest_records",
"(",
"resource",
",",
"layout",
",",
"list_id",
",",
"limit",
",",
"list_fields",
",",
"orderby",
")",
":",
"(",
"datalist",
",",
"numrows",
",",
"ids",
")",
"=",
"resource",
".",
"datalist",
"(",
"fields",
"=",
"list_fields",
",... | display a datalist of the latest records for a resource . | train | false |
51,945 | def _blocklist_json(request):
(items, _) = get_items(groupby='id')
plugins = get_plugins()
issuerCertBlocks = BlocklistIssuerCert.objects.all()
gfxs = BlocklistGfx.objects.all()
ca = None
try:
ca = BlocklistCA.objects.all()[0]
ca = base64.b64encode(ca.data.encode('utf-8'))
except IndexError:
pass
last_update = int(round((time.time() * 1000)))
results = {'last_update': last_update, 'certificates': certificates_to_json(issuerCertBlocks), 'addons': addons_to_json(items), 'plugins': plugins_to_json(plugins), 'gfx': gfxs_to_json(gfxs), 'ca': ca}
return JsonResponse(results)
| [
"def",
"_blocklist_json",
"(",
"request",
")",
":",
"(",
"items",
",",
"_",
")",
"=",
"get_items",
"(",
"groupby",
"=",
"'id'",
")",
"plugins",
"=",
"get_plugins",
"(",
")",
"issuerCertBlocks",
"=",
"BlocklistIssuerCert",
".",
"objects",
".",
"all",
"(",
... | export the whole blocklist in json . | train | false |
51,946 | def _getFriends():
path = os.path.expanduser((('~/Library/Application Support/Skype/' + getUserName()) + '/main.db'))
with contextlib.closing(sqlite3.connect(path).cursor()) as db:
db.execute('SELECT skypename,fullname,displayname FROM Contacts WHERE type=1 AND is_permanent=1')
return db.fetchall()
| [
"def",
"_getFriends",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"(",
"(",
"'~/Library/Application Support/Skype/'",
"+",
"getUserName",
"(",
")",
")",
"+",
"'/main.db'",
")",
")",
"with",
"contextlib",
".",
"closing",
"(",
"sql... | get friends from skype database :return: list of tuples of friends . | train | false |
51,947 | def assert_has_text_matching(output, expression):
match = re.search(expression, output)
assert (match is not None), ("No text matching expression '%s' was found in output file." % expression)
| [
"def",
"assert_has_text_matching",
"(",
"output",
",",
"expression",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"expression",
",",
"output",
")",
"assert",
"(",
"match",
"is",
"not",
"None",
")",
",",
"(",
"\"No text matching expression '%s' was found in ... | asserts the specified output contains text matching the regular expression specified by the argument expression . | train | false |
51,948 | def view_entries(search_query=None):
query = Entry.select().order_by(Entry.timestamp.desc())
if search_query:
query = query.where(Entry.content.contains(search_query))
for entry in query:
timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p')
print timestamp
print ('=' * len(timestamp))
print entry.content
print 'n) next entry'
print 'd) delete entry'
print 'q) return to main menu'
action = raw_input('Choice? (Ndq) ').lower().strip()
if (action == 'q'):
break
elif (action == 'd'):
entry.delete_instance()
break
| [
"def",
"view_entries",
"(",
"search_query",
"=",
"None",
")",
":",
"query",
"=",
"Entry",
".",
"select",
"(",
")",
".",
"order_by",
"(",
"Entry",
".",
"timestamp",
".",
"desc",
"(",
")",
")",
"if",
"search_query",
":",
"query",
"=",
"query",
".",
"wh... | view previous entries . | train | true |
51,949 | def extract_valid_args(args, func, startidx=0):
func_args = inspect.getargspec(func).args[startidx:]
return dict(((k, v) for (k, v) in list(vars(args).items()) if (k in func_args)))
| [
"def",
"extract_valid_args",
"(",
"args",
",",
"func",
",",
"startidx",
"=",
"0",
")",
":",
"func_args",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
".",
"args",
"[",
"startidx",
":",
"]",
"return",
"dict",
"(",
"(",
"(",
"k",
",",
"v",
")... | given a namespace of argparser args . | train | false |
51,950 | def friendly_number(number, base=1000, decimals=0, suffix='', powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
count = 0
number = float(number)
while ((number > base) and (count < len(powers))):
number /= base
count += 1
if decimals:
fmt = ('%%.%df%%s%%s' % decimals)
else:
number = round(number)
fmt = '%d%s%s'
return (fmt % (number, powers[count], suffix))
| [
"def",
"friendly_number",
"(",
"number",
",",
"base",
"=",
"1000",
",",
"decimals",
"=",
"0",
",",
"suffix",
"=",
"''",
",",
"powers",
"=",
"[",
"''",
",",
"'k'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
"'P'",
",",
"'E'",
",",
"'Z'",
",",
"'Y'... | format a number as friendly text . | train | false |
51,953 | def addElementToListTable(element, key, listTable):
if (key in listTable):
listTable[key].append(element)
else:
listTable[key] = [element]
| [
"def",
"addElementToListTable",
"(",
"element",
",",
"key",
",",
"listTable",
")",
":",
"if",
"(",
"key",
"in",
"listTable",
")",
":",
"listTable",
"[",
"key",
"]",
".",
"append",
"(",
"element",
")",
"else",
":",
"listTable",
"[",
"key",
"]",
"=",
"... | add an element to the list table . | train | false |
51,954 | def server_update(s_name, s_ip, **connection_args):
altered = False
cur_server = _server_get(s_name, **connection_args)
if (cur_server is None):
return False
alt_server = NSServer()
alt_server.set_name(s_name)
if (cur_server.get_ipaddress() != s_ip):
alt_server.set_ipaddress(s_ip)
altered = True
if (altered is False):
return False
nitro = _connect(**connection_args)
if (nitro is None):
return False
ret = True
try:
NSServer.update(nitro, alt_server)
except NSNitroError as error:
log.debug('netscaler module error - NSServer.update() failed: {0}'.format(error))
ret = False
_disconnect(nitro)
return ret
| [
"def",
"server_update",
"(",
"s_name",
",",
"s_ip",
",",
"**",
"connection_args",
")",
":",
"altered",
"=",
"False",
"cur_server",
"=",
"_server_get",
"(",
"s_name",
",",
"**",
"connection_args",
")",
"if",
"(",
"cur_server",
"is",
"None",
")",
":",
"retur... | update a servers attributes cli example: . | train | true |
51,956 | def parse_version(*args):
v = None
if (len(args) == 1):
a = args[0]
if isinstance(a, tuple):
v = '.'.join((str(x) for x in a))
else:
v = str(a)
else:
v = '.'.join((str(a) for a in args))
if v.startswith('v'):
v = v[1:]
try:
return pkg_resources.SetuptoolsVersion(v)
except AttributeError:
return pkg_resources.parse_version(v)
| [
"def",
"parse_version",
"(",
"*",
"args",
")",
":",
"v",
"=",
"None",
"if",
"(",
"len",
"(",
"args",
")",
"==",
"1",
")",
":",
"a",
"=",
"args",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"a",
",",
"tuple",
")",
":",
"v",
"=",
"'.'",
".",
"joi... | returns a sortable version arguments: args -- a string . | train | false |
51,957 | def boto_supports_kms_key_id():
return (hasattr(boto, 'Version') and (LooseVersion(boto.Version) >= LooseVersion('2.39.0')))
| [
"def",
"boto_supports_kms_key_id",
"(",
")",
":",
"return",
"(",
"hasattr",
"(",
"boto",
",",
"'Version'",
")",
"and",
"(",
"LooseVersion",
"(",
"boto",
".",
"Version",
")",
">=",
"LooseVersion",
"(",
"'2.39.0'",
")",
")",
")"
] | check if boto library supports kms_key_ids returns: true if version is equal to or higher then the version needed . | train | false |
51,958 | def test_cnn_init():
cnn = CondensedNearestNeighbour(random_state=RND_SEED)
assert_equal(cnn.n_seeds_S, 1)
assert_equal(cnn.n_jobs, 1)
| [
"def",
"test_cnn_init",
"(",
")",
":",
"cnn",
"=",
"CondensedNearestNeighbour",
"(",
"random_state",
"=",
"RND_SEED",
")",
"assert_equal",
"(",
"cnn",
".",
"n_seeds_S",
",",
"1",
")",
"assert_equal",
"(",
"cnn",
".",
"n_jobs",
",",
"1",
")"
] | test the initialisation of the object . | train | false |
51,959 | def for_signed_dtypes(name='dtype'):
return for_dtypes(_signed_dtypes, name=name)
| [
"def",
"for_signed_dtypes",
"(",
"name",
"=",
"'dtype'",
")",
":",
"return",
"for_dtypes",
"(",
"_signed_dtypes",
",",
"name",
"=",
"name",
")"
] | decorator that checks the fixture with signed dtypes . | train | false |
51,961 | def _parse_nav_steps(arg_str):
COMMAND_ALIASES = [('LOGIN', _parse_login)]
if (not arg_str):
arg_str = ''
words = arg_str.split(' ')
for (name, callback) in COMMAND_ALIASES:
if (words[0] == name):
return callback(*words[1:])
commands = arg_str.split('|')
parsed_commands = reduce((lambda x, y: ((x + [y]) if y else x)), map(_parse_command, commands), [])
runhandler = '_command_handler'
return {'runhandler': runhandler, 'args': {'commands': parsed_commands}}
| [
"def",
"_parse_nav_steps",
"(",
"arg_str",
")",
":",
"COMMAND_ALIASES",
"=",
"[",
"(",
"'LOGIN'",
",",
"_parse_login",
")",
"]",
"if",
"(",
"not",
"arg_str",
")",
":",
"arg_str",
"=",
"''",
"words",
"=",
"arg_str",
".",
"split",
"(",
"' '",
")",
"for",... | heres how to specify the navigation steps: 1 . | train | false |
51,962 | def test_all_logarithmic(Chart):
chart = Chart(logarithmic=True)
chart.add('1', [1, 30, 8, 199, (-23)])
chart.add('2', [87, 42, 0.9, 189, 81])
assert chart.render()
| [
"def",
"test_all_logarithmic",
"(",
"Chart",
")",
":",
"chart",
"=",
"Chart",
"(",
"logarithmic",
"=",
"True",
")",
"chart",
".",
"add",
"(",
"'1'",
",",
"[",
"1",
",",
"30",
",",
"8",
",",
"199",
",",
"(",
"-",
"23",
")",
"]",
")",
"chart",
".... | test logarithmic view rendering . | train | false |
51,965 | def pipeline_factory(loader, global_conf, **local_conf):
pipeline = local_conf[cfg.CONF.auth_strategy]
pipeline = pipeline.split()
filters = [loader.get_filter(n) for n in pipeline[:(-1)]]
app = loader.get_app(pipeline[(-1)])
filters.reverse()
for filter in filters:
app = filter(app)
return app
| [
"def",
"pipeline_factory",
"(",
"loader",
",",
"global_conf",
",",
"**",
"local_conf",
")",
":",
"pipeline",
"=",
"local_conf",
"[",
"cfg",
".",
"CONF",
".",
"auth_strategy",
"]",
"pipeline",
"=",
"pipeline",
".",
"split",
"(",
")",
"filters",
"=",
"[",
... | create a paste pipeline based on the auth_strategy config option . | train | false |
51,966 | def crt(a_values, modulo_values):
m = 1
x = 0
for modulo in modulo_values:
m *= modulo
for (m_i, a_i) in zip(modulo_values, a_values):
M_i = (m // m_i)
inv = inverse(M_i, m_i)
x = ((x + ((a_i * M_i) * inv)) % m)
return x
| [
"def",
"crt",
"(",
"a_values",
",",
"modulo_values",
")",
":",
"m",
"=",
"1",
"x",
"=",
"0",
"for",
"modulo",
"in",
"modulo_values",
":",
"m",
"*=",
"modulo",
"for",
"(",
"m_i",
",",
"a_i",
")",
"in",
"zip",
"(",
"modulo_values",
",",
"a_values",
"... | chinese remainder theorem . | train | false |
51,967 | def test_filefind():
f = tempfile.NamedTemporaryFile()
alt_dirs = paths.get_ipython_dir()
t = path.filefind(f.name, alt_dirs)
| [
"def",
"test_filefind",
"(",
")",
":",
"f",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"alt_dirs",
"=",
"paths",
".",
"get_ipython_dir",
"(",
")",
"t",
"=",
"path",
".",
"filefind",
"(",
"f",
".",
"name",
",",
"alt_dirs",
")"
] | various tests for filefind . | train | false |
51,968 | def is_called_from_pytest():
return getattr(matplotlib, u'_called_from_pytest', False)
| [
"def",
"is_called_from_pytest",
"(",
")",
":",
"return",
"getattr",
"(",
"matplotlib",
",",
"u'_called_from_pytest'",
",",
"False",
")"
] | returns whether the call was done from pytest . | train | false |
51,971 | def bootstrap_statistic(data, stats_fn, num_samples):
return [stats_fn(bootstrap_sample(data)) for _ in range(num_samples)]
| [
"def",
"bootstrap_statistic",
"(",
"data",
",",
"stats_fn",
",",
"num_samples",
")",
":",
"return",
"[",
"stats_fn",
"(",
"bootstrap_sample",
"(",
"data",
")",
")",
"for",
"_",
"in",
"range",
"(",
"num_samples",
")",
"]"
] | evaluates stats_fn on num_samples bootstrap samples from data . | train | false |
51,972 | def resolveMUITimeZone(spec):
pattern = re.compile('@(?P<dllname>.*),-(?P<index>\\d+)(?:;(?P<comment>.*))?')
matcher = pattern.match(spec)
assert matcher, 'Could not parse MUI spec'
try:
handle = DLLCache[matcher.groupdict()['dllname']]
result = win32api.LoadString(handle, int(matcher.groupdict()['index']))
except win32api.error as e:
result = None
return result
| [
"def",
"resolveMUITimeZone",
"(",
"spec",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'@(?P<dllname>.*),-(?P<index>\\\\d+)(?:;(?P<comment>.*))?'",
")",
"matcher",
"=",
"pattern",
".",
"match",
"(",
"spec",
")",
"assert",
"matcher",
",",
"'Could not parse M... | resolve a multilingual user interface resource for the time zone name . | train | false |
51,974 | def keyspaces():
sys = _sys_mgr()
return sys.list_keyspaces()
| [
"def",
"keyspaces",
"(",
")",
":",
"sys",
"=",
"_sys_mgr",
"(",
")",
"return",
"sys",
".",
"list_keyspaces",
"(",
")"
] | return existing keyspaces cli example: . | train | false |
51,975 | def strip_boolean_result(method, exc_type=None, exc_str=None, fail_ret=None):
@wraps(method)
def wrapped(*args, **kwargs):
ret = method(*args, **kwargs)
if ret[0]:
if (len(ret) == 2):
return ret[1]
else:
return ret[1:]
else:
if exc_type:
raise exc_type((exc_str or 'call failed'))
return fail_ret
return wrapped
| [
"def",
"strip_boolean_result",
"(",
"method",
",",
"exc_type",
"=",
"None",
",",
"exc_str",
"=",
"None",
",",
"fail_ret",
"=",
"None",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"ret... | translate methods return value for stripping off success flag . | train | true |
51,976 | def _list_from_layouttuple(tk, ltuple):
ltuple = tk.splitlist(ltuple)
res = []
indx = 0
while (indx < len(ltuple)):
name = ltuple[indx]
opts = {}
res.append((name, opts))
indx += 1
while (indx < len(ltuple)):
(opt, val) = ltuple[indx:(indx + 2)]
if (not opt.startswith('-')):
break
opt = opt[1:]
indx += 2
if (opt == 'children'):
val = _list_from_layouttuple(tk, val)
opts[opt] = val
return res
| [
"def",
"_list_from_layouttuple",
"(",
"tk",
",",
"ltuple",
")",
":",
"ltuple",
"=",
"tk",
".",
"splitlist",
"(",
"ltuple",
")",
"res",
"=",
"[",
"]",
"indx",
"=",
"0",
"while",
"(",
"indx",
"<",
"len",
"(",
"ltuple",
")",
")",
":",
"name",
"=",
"... | construct a list from the tuple returned by ttk::layout . | train | false |
51,979 | def freezedicts(obj):
if isinstance(obj, (list, tuple)):
return type(obj)([freezedicts(sub) for sub in obj])
if isinstance(obj, dict):
return frozenset(six.iteritems(obj))
return obj
| [
"def",
"freezedicts",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"type",
"(",
"obj",
")",
"(",
"[",
"freezedicts",
"(",
"sub",
")",
"for",
"sub",
"in",
"obj",
"]",
")",
"if",
"... | recursively iterate over obj . | train | false |
51,980 | def val_load(db):
dbname = (db + u'.db')
if (not os.access(dbname, os.R_OK)):
sys.exit((u'Cannot read file: %s' % dbname))
else:
db_in = shelve.open(db)
from nltk.sem import Valuation
val = Valuation(db_in)
return val
| [
"def",
"val_load",
"(",
"db",
")",
":",
"dbname",
"=",
"(",
"db",
"+",
"u'.db'",
")",
"if",
"(",
"not",
"os",
".",
"access",
"(",
"dbname",
",",
"os",
".",
"R_OK",
")",
")",
":",
"sys",
".",
"exit",
"(",
"(",
"u'Cannot read file: %s'",
"%",
"dbna... | load a valuation from a persistent database . | train | false |
51,981 | def task_absent(name):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
task = __salt__['kapacitor.get_task'](name)
if task:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Task would have been deleted'
else:
result = __salt__['kapacitor.delete_task'](name)
ret['result'] = result['success']
if (not ret['result']):
ret['comment'] = 'Could not disable task'
if result.get('stderr'):
ret['comment'] += ('\n' + result['stderr'])
return ret
ret['comment'] = 'Task was deleted'
ret['changes'][name] = 'deleted'
else:
ret['comment'] = 'Task does not exist'
return ret
| [
"def",
"task_absent",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"task",
"=",
"__salt__",
"[",
"'kapacitor.get_task'",
"]",
"(",
"nam... | ensure that a task is absent from kapacitor . | train | true |
51,982 | def _B(slot):
return (slot * 2)
| [
"def",
"_B",
"(",
"slot",
")",
":",
"return",
"(",
"slot",
"*",
"2",
")"
] | convert slot to byte boundary . | train | false |
51,983 | def cms_post_age(row):
if hasattr(row, 'cms_post'):
row = row.cms_post
try:
date = row.date
except:
return messages['NONE']
now = request.utcnow
age = (now - date)
if (age < timedelta(days=2)):
return 1
elif (age < timedelta(days=7)):
return 2
else:
return 3
| [
"def",
"cms_post_age",
"(",
"row",
")",
":",
"if",
"hasattr",
"(",
"row",
",",
"'cms_post'",
")",
":",
"row",
"=",
"row",
".",
"cms_post",
"try",
":",
"date",
"=",
"row",
".",
"date",
"except",
":",
"return",
"messages",
"[",
"'NONE'",
"]",
"now",
... | the age of the post - used for colour-coding markers of alerts & incidents . | train | false |
51,984 | def run_2to3(files, fixer_names=None, options=None, explicit=None):
if (not files):
return
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
class DistutilsRefactoringTool(RefactoringTool, ):
def log_error(self, msg, *args, **kw):
log.error(msg, *args)
def log_message(self, msg, *args):
log.info(msg, *args)
def log_debug(self, msg, *args):
log.debug(msg, *args)
if (fixer_names is None):
fixer_names = get_fixers_from_package('lib2to3.fixes')
r = DistutilsRefactoringTool(fixer_names, options=options)
r.refactor(files, write=True)
| [
"def",
"run_2to3",
"(",
"files",
",",
"fixer_names",
"=",
"None",
",",
"options",
"=",
"None",
",",
"explicit",
"=",
"None",
")",
":",
"if",
"(",
"not",
"files",
")",
":",
"return",
"from",
"lib2to3",
".",
"refactor",
"import",
"RefactoringTool",
",",
... | invoke 2to3 on a list of python files . | train | false |
51,987 | def get_visible_columns(data, table_meta, df):
columns = []
doc = (data[0] or frappe.new_doc(df.options))
def add_column(col_df):
return (is_visible(col_df, doc) and column_has_value(data, col_df.get(u'fieldname')))
if df.get(u'visible_columns'):
for col_df in df.get(u'visible_columns'):
docfield = table_meta.get_field(col_df.get(u'fieldname'))
if (not docfield):
continue
newdf = docfield.as_dict().copy()
newdf.update(col_df)
if add_column(newdf):
columns.append(newdf)
else:
for col_df in table_meta.fields:
if add_column(col_df):
columns.append(col_df)
return columns
| [
"def",
"get_visible_columns",
"(",
"data",
",",
"table_meta",
",",
"df",
")",
":",
"columns",
"=",
"[",
"]",
"doc",
"=",
"(",
"data",
"[",
"0",
"]",
"or",
"frappe",
".",
"new_doc",
"(",
"df",
".",
"options",
")",
")",
"def",
"add_column",
"(",
"col... | returns list of visible columns based on print_hide and if all columns have value . | train | false |
51,989 | def is_invertible(polynomial, threshold=1.0):
eigvals = np.linalg.eigvals(companion_matrix(polynomial))
return np.all((np.abs(eigvals) < threshold))
| [
"def",
"is_invertible",
"(",
"polynomial",
",",
"threshold",
"=",
"1.0",
")",
":",
"eigvals",
"=",
"np",
".",
"linalg",
".",
"eigvals",
"(",
"companion_matrix",
"(",
"polynomial",
")",
")",
"return",
"np",
".",
"all",
"(",
"(",
"np",
".",
"abs",
"(",
... | determine if a polynomial is invertible . | train | false |
51,990 | def test_installer(args, plugin, config, temp_dir):
backup = _create_backup(config, temp_dir)
names_match = (plugin.get_all_names() == plugin.get_all_names_answer())
if names_match:
logger.info('get_all_names test succeeded')
else:
logger.error('get_all_names test failed for config %s', config)
domains = list(plugin.get_testable_domain_names())
success = test_deploy_cert(plugin, temp_dir, domains)
if (success and args.enhance):
success = test_enhancements(plugin, domains)
good_rollback = test_rollback(plugin, config, backup)
return (names_match and success and good_rollback)
| [
"def",
"test_installer",
"(",
"args",
",",
"plugin",
",",
"config",
",",
"temp_dir",
")",
":",
"backup",
"=",
"_create_backup",
"(",
"config",
",",
"temp_dir",
")",
"names_match",
"=",
"(",
"plugin",
".",
"get_all_names",
"(",
")",
"==",
"plugin",
".",
"... | tests plugin as an installer . | train | false |
51,991 | def ver_str(version):
return '.'.join(map(str, version))
| [
"def",
"ver_str",
"(",
"version",
")",
":",
"return",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"version",
")",
")"
] | version tuple as string . | train | false |
51,992 | def plot_mnist_digit(image):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.matshow(image, cmap=matplotlib.cm.binary)
plt.xticks(np.array([]))
plt.yticks(np.array([]))
plt.show()
| [
"def",
"plot_mnist_digit",
"(",
"image",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"1",
",",
"1",
",",
"1",
")",
"ax",
".",
"matshow",
"(",
"image",
",",
"cmap",
"=",
"matplotlib",
".",
"cm",... | plot a single mnist image . | train | false |
51,994 | def _serialize_buffer(buffer, array_serialization=None):
if (array_serialization == 'binary'):
return buffer.ravel().tostring()
elif (array_serialization == 'base64'):
return {'storage_type': 'base64', 'buffer': base64.b64encode(buffer).decode('ascii')}
raise ValueError("The array serialization method should be 'binary' or 'base64'.")
| [
"def",
"_serialize_buffer",
"(",
"buffer",
",",
"array_serialization",
"=",
"None",
")",
":",
"if",
"(",
"array_serialization",
"==",
"'binary'",
")",
":",
"return",
"buffer",
".",
"ravel",
"(",
")",
".",
"tostring",
"(",
")",
"elif",
"(",
"array_serializati... | serialize a numpy array . | train | true |
51,996 | def skip_on_broken_permissions(test_method):
@wraps(test_method)
def wrapper(case, *args, **kwargs):
test_file = FilePath(case.mktemp())
test_file.touch()
test_file.chmod(0)
permissions = test_file.getPermissions()
test_file.chmod(511)
if (permissions != Permissions(0)):
raise SkipTest("Can't run test on filesystem with broken permissions.")
return test_method(case, *args, **kwargs)
return wrapper
| [
"def",
"skip_on_broken_permissions",
"(",
"test_method",
")",
":",
"@",
"wraps",
"(",
"test_method",
")",
"def",
"wrapper",
"(",
"case",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"test_file",
"=",
"FilePath",
"(",
"case",
".",
"mktemp",
"(",
")",
... | skips the wrapped test when the temporary directory is on a filesystem with broken permissions . | train | false |
51,997 | @login_required
def resetrepo(request):
if (request.method != 'POST'):
return HttpResponseNotAllowed(['POST'])
view_helpers.SvnRepository(request.user.username).reset()
view_helpers.unset_mission_completed(request.user.get_profile(), 'svn_checkout')
view_helpers.unset_mission_completed(request.user.get_profile(), 'svn_diff')
view_helpers.unset_mission_completed(request.user.get_profile(), 'svn_commit')
if ('stay_on_this_page' in request.GET):
return HttpResponseRedirect(reverse('svn_main_page'))
else:
return HttpResponseRedirect(reverse('svn_checkout'))
| [
"@",
"login_required",
"def",
"resetrepo",
"(",
"request",
")",
":",
"if",
"(",
"request",
".",
"method",
"!=",
"'POST'",
")",
":",
"return",
"HttpResponseNotAllowed",
"(",
"[",
"'POST'",
"]",
")",
"view_helpers",
".",
"SvnRepository",
"(",
"request",
".",
... | reset a users mission repository and mark steps as uncompleted . | train | false |
52,000 | def loadApplication(filename, kind, passphrase=None):
if (kind == 'python'):
application = sob.loadValueFromFile(filename, 'application', passphrase)
else:
application = sob.load(filename, kind, passphrase)
return application
| [
"def",
"loadApplication",
"(",
"filename",
",",
"kind",
",",
"passphrase",
"=",
"None",
")",
":",
"if",
"(",
"kind",
"==",
"'python'",
")",
":",
"application",
"=",
"sob",
".",
"loadValueFromFile",
"(",
"filename",
",",
"'application'",
",",
"passphrase",
... | load application from a given file . | train | false |
52,003 | def add_views_to_dataset_resources(context, dataset_dict, view_types=[], create_datastore_views=False):
created_views = []
for resource_dict in dataset_dict.get('resources', []):
new_views = add_views_to_resource(context, resource_dict, dataset_dict, view_types, create_datastore_views)
created_views.extend(new_views)
return created_views
| [
"def",
"add_views_to_dataset_resources",
"(",
"context",
",",
"dataset_dict",
",",
"view_types",
"=",
"[",
"]",
",",
"create_datastore_views",
"=",
"False",
")",
":",
"created_views",
"=",
"[",
"]",
"for",
"resource_dict",
"in",
"dataset_dict",
".",
"get",
"(",
... | creates the provided views on all resources of the provided dataset views to create are provided as a list of view_types . | train | false |
52,004 | def remove_value(module):
consul_api = get_consul_api(module)
key = module.params.get('key')
value = module.params.get('value')
(index, existing) = consul_api.kv.get(key, recurse=module.params.get('recurse'))
changed = (existing != None)
if (changed and (not module.check_mode)):
consul_api.kv.delete(key, module.params.get('recurse'))
module.exit_json(changed=changed, index=index, key=key, data=existing)
| [
"def",
"remove_value",
"(",
"module",
")",
":",
"consul_api",
"=",
"get_consul_api",
"(",
"module",
")",
"key",
"=",
"module",
".",
"params",
".",
"get",
"(",
"'key'",
")",
"value",
"=",
"module",
".",
"params",
".",
"get",
"(",
"'value'",
")",
"(",
... | remove the value associated with the given key . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.