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 |
|---|---|---|---|---|---|
20,637 | @db_api.retry_if_session_inactive()
@db_api.context_manager.writer
def set_quota_usage_dirty(context, resource, tenant_id, dirty=True):
query = db_utils.model_query(context, quota_models.QuotaUsage)
query = query.filter_by(resource=resource).filter_by(tenant_id=tenant_id)
return query.update({'dirty': dirty})
| [
"@",
"db_api",
".",
"retry_if_session_inactive",
"(",
")",
"@",
"db_api",
".",
"context_manager",
".",
"writer",
"def",
"set_quota_usage_dirty",
"(",
"context",
",",
"resource",
",",
"tenant_id",
",",
"dirty",
"=",
"True",
")",
":",
"query",
"=",
"db_utils",
".",
"model_query",
"(",
"context",
",",
"quota_models",
".",
"QuotaUsage",
")",
"query",
"=",
"query",
".",
"filter_by",
"(",
"resource",
"=",
"resource",
")",
".",
"filter_by",
"(",
"tenant_id",
"=",
"tenant_id",
")",
"return",
"query",
".",
"update",
"(",
"{",
"'dirty'",
":",
"dirty",
"}",
")"
] | set quota usage dirty bit for a given resource and tenant . | train | false |
20,639 | def get_exploration_stats(exploration_id, exploration_version):
exploration = exp_services.get_exploration_by_id(exploration_id)
exp_stats = stats_jobs_continuous.StatisticsAggregator.get_statistics(exploration_id, exploration_version)
last_updated = exp_stats['last_updated']
state_hit_counts = exp_stats['state_hit_counts']
return {'improvements': get_state_improvements(exploration_id, exploration_version), 'last_updated': last_updated, 'num_completions': exp_stats['complete_exploration_count'], 'num_starts': exp_stats['start_exploration_count'], 'state_stats': {state_name: {'name': state_name, 'firstEntryCount': (state_hit_counts[state_name]['first_entry_count'] if (state_name in state_hit_counts) else 0), 'totalEntryCount': (state_hit_counts[state_name]['total_entry_count'] if (state_name in state_hit_counts) else 0)} for state_name in exploration.states}}
| [
"def",
"get_exploration_stats",
"(",
"exploration_id",
",",
"exploration_version",
")",
":",
"exploration",
"=",
"exp_services",
".",
"get_exploration_by_id",
"(",
"exploration_id",
")",
"exp_stats",
"=",
"stats_jobs_continuous",
".",
"StatisticsAggregator",
".",
"get_statistics",
"(",
"exploration_id",
",",
"exploration_version",
")",
"last_updated",
"=",
"exp_stats",
"[",
"'last_updated'",
"]",
"state_hit_counts",
"=",
"exp_stats",
"[",
"'state_hit_counts'",
"]",
"return",
"{",
"'improvements'",
":",
"get_state_improvements",
"(",
"exploration_id",
",",
"exploration_version",
")",
",",
"'last_updated'",
":",
"last_updated",
",",
"'num_completions'",
":",
"exp_stats",
"[",
"'complete_exploration_count'",
"]",
",",
"'num_starts'",
":",
"exp_stats",
"[",
"'start_exploration_count'",
"]",
",",
"'state_stats'",
":",
"{",
"state_name",
":",
"{",
"'name'",
":",
"state_name",
",",
"'firstEntryCount'",
":",
"(",
"state_hit_counts",
"[",
"state_name",
"]",
"[",
"'first_entry_count'",
"]",
"if",
"(",
"state_name",
"in",
"state_hit_counts",
")",
"else",
"0",
")",
",",
"'totalEntryCount'",
":",
"(",
"state_hit_counts",
"[",
"state_name",
"]",
"[",
"'total_entry_count'",
"]",
"if",
"(",
"state_name",
"in",
"state_hit_counts",
")",
"else",
"0",
")",
"}",
"for",
"state_name",
"in",
"exploration",
".",
"states",
"}",
"}"
] | returns a dict with state statistics for the given exploration id . | train | false |
20,640 | def quota_get_all_by_project_and_user(context, project_id, user_id):
return IMPL.quota_get_all_by_project_and_user(context, project_id, user_id)
| [
"def",
"quota_get_all_by_project_and_user",
"(",
"context",
",",
"project_id",
",",
"user_id",
")",
":",
"return",
"IMPL",
".",
"quota_get_all_by_project_and_user",
"(",
"context",
",",
"project_id",
",",
"user_id",
")"
] | retrieve all quotas associated with a given project and user . | train | false |
20,641 | def _user_to_uid(user):
if ((user is None) or (user == '')):
return ''
try:
(sid, domain, account_type) = win32security.LookupAccountName(None, user)
except pywinerror as exc:
if (exc.winerror == 1332):
return ''
else:
raise
return win32security.ConvertSidToStringSid(sid)
| [
"def",
"_user_to_uid",
"(",
"user",
")",
":",
"if",
"(",
"(",
"user",
"is",
"None",
")",
"or",
"(",
"user",
"==",
"''",
")",
")",
":",
"return",
"''",
"try",
":",
"(",
"sid",
",",
"domain",
",",
"account_type",
")",
"=",
"win32security",
".",
"LookupAccountName",
"(",
"None",
",",
"user",
")",
"except",
"pywinerror",
"as",
"exc",
":",
"if",
"(",
"exc",
".",
"winerror",
"==",
"1332",
")",
":",
"return",
"''",
"else",
":",
"raise",
"return",
"win32security",
".",
"ConvertSidToStringSid",
"(",
"sid",
")"
] | convert user name to a uid . | train | false |
20,643 | def domain_to_filename(domain):
filename = domain.replace('/', '-')
if (filename[(-1)] == '-'):
filename = filename[:(-1)]
filename += '.txt'
return filename
| [
"def",
"domain_to_filename",
"(",
"domain",
")",
":",
"filename",
"=",
"domain",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
"if",
"(",
"filename",
"[",
"(",
"-",
"1",
")",
"]",
"==",
"'-'",
")",
":",
"filename",
"=",
"filename",
"[",
":",
"(",
"-",
"1",
")",
"]",
"filename",
"+=",
"'.txt'",
"return",
"filename"
] | all / are turned into - . | train | false |
20,644 | @handle_response_format
@treeio_login_required
def set_delete(request, set_id, response_format='html'):
changeset = get_object_or_404(ChangeSet, pk=set_id)
if ((not request.user.profile.has_permission(changeset.object, mode='w')) and (not request.user.profile.is_admin('treeio.changes'))):
return user_denied(request, "You don't have access to this Change Set.", response_format=response_format)
if request.POST:
if ('delete' in request.POST):
if ('trash' in request.POST):
changeset.trash = True
changeset.save()
else:
changeset.delete()
return HttpResponseRedirect(reverse('changes_index'))
elif ('cancel' in request.POST):
return HttpResponseRedirect(reverse('changes_set_view', args=[changeset.id]))
context = _get_default_context(request)
context.update({'changeset': changeset})
return render_to_response('changes/set_delete', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"handle_response_format",
"@",
"treeio_login_required",
"def",
"set_delete",
"(",
"request",
",",
"set_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"changeset",
"=",
"get_object_or_404",
"(",
"ChangeSet",
",",
"pk",
"=",
"set_id",
")",
"if",
"(",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"has_permission",
"(",
"changeset",
".",
"object",
",",
"mode",
"=",
"'w'",
")",
")",
"and",
"(",
"not",
"request",
".",
"user",
".",
"profile",
".",
"is_admin",
"(",
"'treeio.changes'",
")",
")",
")",
":",
"return",
"user_denied",
"(",
"request",
",",
"\"You don't have access to this Change Set.\"",
",",
"response_format",
"=",
"response_format",
")",
"if",
"request",
".",
"POST",
":",
"if",
"(",
"'delete'",
"in",
"request",
".",
"POST",
")",
":",
"if",
"(",
"'trash'",
"in",
"request",
".",
"POST",
")",
":",
"changeset",
".",
"trash",
"=",
"True",
"changeset",
".",
"save",
"(",
")",
"else",
":",
"changeset",
".",
"delete",
"(",
")",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'changes_index'",
")",
")",
"elif",
"(",
"'cancel'",
"in",
"request",
".",
"POST",
")",
":",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'changes_set_view'",
",",
"args",
"=",
"[",
"changeset",
".",
"id",
"]",
")",
")",
"context",
"=",
"_get_default_context",
"(",
"request",
")",
"context",
".",
"update",
"(",
"{",
"'changeset'",
":",
"changeset",
"}",
")",
"return",
"render_to_response",
"(",
"'changes/set_delete'",
",",
"context",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")"
] | changeset delete . | train | false |
20,645 | @memoize
def make_env_key(app_name, key):
key = key.replace('-', '_').replace(' ', '_')
return str('_'.join((x.upper() for x in (app_name, key))))
| [
"@",
"memoize",
"def",
"make_env_key",
"(",
"app_name",
",",
"key",
")",
":",
"key",
"=",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"return",
"str",
"(",
"'_'",
".",
"join",
"(",
"(",
"x",
".",
"upper",
"(",
")",
"for",
"x",
"in",
"(",
"app_name",
",",
"key",
")",
")",
")",
")"
] | creates an environment key-equivalent for the given key . | train | true |
20,647 | def iter_variants(inputs, outputs):
maps = [('i', 'l')]
if (not (('i' in inputs) or ('l' in inputs))):
maps = (maps + [((a + 'dD'), (b + 'fF')) for (a, b) in maps])
for (src, dst) in maps:
new_inputs = inputs
new_outputs = outputs
for (a, b) in zip(src, dst):
new_inputs = new_inputs.replace(a, b)
new_outputs = new_outputs.replace(a, b)
(yield (new_inputs, new_outputs))
| [
"def",
"iter_variants",
"(",
"inputs",
",",
"outputs",
")",
":",
"maps",
"=",
"[",
"(",
"'i'",
",",
"'l'",
")",
"]",
"if",
"(",
"not",
"(",
"(",
"'i'",
"in",
"inputs",
")",
"or",
"(",
"'l'",
"in",
"inputs",
")",
")",
")",
":",
"maps",
"=",
"(",
"maps",
"+",
"[",
"(",
"(",
"a",
"+",
"'dD'",
")",
",",
"(",
"b",
"+",
"'fF'",
")",
")",
"for",
"(",
"a",
",",
"b",
")",
"in",
"maps",
"]",
")",
"for",
"(",
"src",
",",
"dst",
")",
"in",
"maps",
":",
"new_inputs",
"=",
"inputs",
"new_outputs",
"=",
"outputs",
"for",
"(",
"a",
",",
"b",
")",
"in",
"zip",
"(",
"src",
",",
"dst",
")",
":",
"new_inputs",
"=",
"new_inputs",
".",
"replace",
"(",
"a",
",",
"b",
")",
"new_outputs",
"=",
"new_outputs",
".",
"replace",
"(",
"a",
",",
"b",
")",
"(",
"yield",
"(",
"new_inputs",
",",
"new_outputs",
")",
")"
] | generate variants of ufunc signatures . | train | false |
20,648 | @pytest.mark.network
def test_install_using_install_option_and_editable(script, tmpdir):
folder = 'script_folder'
script.scratch_path.join(folder).mkdir()
url = 'git+git://github.com/pypa/pip-test-package'
result = script.pip('install', '-e', ('%s#egg=pip-test-package' % local_checkout(url, tmpdir.join('cache'))), ('--install-option=--script-dir=%s' % folder), expect_stderr=True)
script_file = (((((script.venv / 'src') / 'pip-test-package') / folder) / 'pip-test-package') + script.exe)
assert (script_file in result.files_created)
| [
"@",
"pytest",
".",
"mark",
".",
"network",
"def",
"test_install_using_install_option_and_editable",
"(",
"script",
",",
"tmpdir",
")",
":",
"folder",
"=",
"'script_folder'",
"script",
".",
"scratch_path",
".",
"join",
"(",
"folder",
")",
".",
"mkdir",
"(",
")",
"url",
"=",
"'git+git://github.com/pypa/pip-test-package'",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"'-e'",
",",
"(",
"'%s#egg=pip-test-package'",
"%",
"local_checkout",
"(",
"url",
",",
"tmpdir",
".",
"join",
"(",
"'cache'",
")",
")",
")",
",",
"(",
"'--install-option=--script-dir=%s'",
"%",
"folder",
")",
",",
"expect_stderr",
"=",
"True",
")",
"script_file",
"=",
"(",
"(",
"(",
"(",
"(",
"script",
".",
"venv",
"/",
"'src'",
")",
"/",
"'pip-test-package'",
")",
"/",
"folder",
")",
"/",
"'pip-test-package'",
")",
"+",
"script",
".",
"exe",
")",
"assert",
"(",
"script_file",
"in",
"result",
".",
"files_created",
")"
] | test installing a tool using -e and --install-option . | train | false |
20,649 | def _api_rescan(name, output, kwargs):
scan_jobs(all=False, action=True)
return report(output)
| [
"def",
"_api_rescan",
"(",
"name",
",",
"output",
",",
"kwargs",
")",
":",
"scan_jobs",
"(",
"all",
"=",
"False",
",",
"action",
"=",
"True",
")",
"return",
"report",
"(",
"output",
")"
] | api: accepts output . | train | false |
20,652 | def DisplayUserSecret(user):
secret = _GetUserSecret(user)
print 'user secret={0}'.format(secret)
print 'verification code={0}'.format(_ComputeOTP(secret, 0))
print 'activation URL:', _GetActivationURL(user, secret)
| [
"def",
"DisplayUserSecret",
"(",
"user",
")",
":",
"secret",
"=",
"_GetUserSecret",
"(",
"user",
")",
"print",
"'user secret={0}'",
".",
"format",
"(",
"secret",
")",
"print",
"'verification code={0}'",
".",
"format",
"(",
"_ComputeOTP",
"(",
"secret",
",",
"0",
")",
")",
"print",
"'activation URL:'",
",",
"_GetActivationURL",
"(",
"user",
",",
"secret",
")"
] | gets the user secret from the secrets database and displays it . | train | false |
20,654 | def add_serialization_status_metric(status, hostname):
interval = 10.0
value = 1
return {'tags': ['status:{0}'.format(status)], 'metric': 'datadog.dogstatsd.serialization_status', 'interval': interval, 'device_name': None, 'host': hostname, 'points': [(time(), (value / interval))], 'type': MetricTypes.RATE}
| [
"def",
"add_serialization_status_metric",
"(",
"status",
",",
"hostname",
")",
":",
"interval",
"=",
"10.0",
"value",
"=",
"1",
"return",
"{",
"'tags'",
":",
"[",
"'status:{0}'",
".",
"format",
"(",
"status",
")",
"]",
",",
"'metric'",
":",
"'datadog.dogstatsd.serialization_status'",
",",
"'interval'",
":",
"interval",
",",
"'device_name'",
":",
"None",
",",
"'host'",
":",
"hostname",
",",
"'points'",
":",
"[",
"(",
"time",
"(",
")",
",",
"(",
"value",
"/",
"interval",
")",
")",
"]",
",",
"'type'",
":",
"MetricTypes",
".",
"RATE",
"}"
] | add a metric to track the number of metric serializations . | train | false |
20,657 | def _item_to_blob(iterator, item):
name = item.get('name')
blob = Blob(name, bucket=iterator.bucket)
blob._set_properties(item)
return blob
| [
"def",
"_item_to_blob",
"(",
"iterator",
",",
"item",
")",
":",
"name",
"=",
"item",
".",
"get",
"(",
"'name'",
")",
"blob",
"=",
"Blob",
"(",
"name",
",",
"bucket",
"=",
"iterator",
".",
"bucket",
")",
"blob",
".",
"_set_properties",
"(",
"item",
")",
"return",
"blob"
] | convert a json blob to the native object . | train | true |
20,659 | def get_env_args():
settings = {}
zmq = os.environ.get('ZMQ_PREFIX', None)
if (zmq is not None):
debug(('Found environ var ZMQ_PREFIX=%s' % zmq))
settings['zmq_prefix'] = zmq
return settings
| [
"def",
"get_env_args",
"(",
")",
":",
"settings",
"=",
"{",
"}",
"zmq",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'ZMQ_PREFIX'",
",",
"None",
")",
"if",
"(",
"zmq",
"is",
"not",
"None",
")",
":",
"debug",
"(",
"(",
"'Found environ var ZMQ_PREFIX=%s'",
"%",
"zmq",
")",
")",
"settings",
"[",
"'zmq_prefix'",
"]",
"=",
"zmq",
"return",
"settings"
] | look for options in environment vars . | train | false |
20,660 | def _get(request, post=None):
return opener.open(request, post).read()
| [
"def",
"_get",
"(",
"request",
",",
"post",
"=",
"None",
")",
":",
"return",
"opener",
".",
"open",
"(",
"request",
",",
"post",
")",
".",
"read",
"(",
")"
] | get a node with the specified c{nodeid} as any of the c{class} . | train | false |
20,661 | def libvlc_vlm_stop_media(p_instance, psz_name):
f = (_Cfunctions.get('libvlc_vlm_stop_media', None) or _Cfunction('libvlc_vlm_stop_media', ((1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p))
return f(p_instance, psz_name)
| [
"def",
"libvlc_vlm_stop_media",
"(",
"p_instance",
",",
"psz_name",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_vlm_stop_media'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_vlm_stop_media'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
")",
",",
"None",
",",
"ctypes",
".",
"c_int",
",",
"Instance",
",",
"ctypes",
".",
"c_char_p",
")",
")",
"return",
"f",
"(",
"p_instance",
",",
"psz_name",
")"
] | stop the named broadcast . | train | true |
20,662 | def get_file_from_filediff(context, filediff, interfilediff):
interdiffset = None
key = (u'_diff_files_%s_%s' % (filediff.diffset.id, filediff.id))
if interfilediff:
key += (u'_%s' % interfilediff.id)
interdiffset = interfilediff.diffset
if (key in context):
files = context[key]
else:
assert (u'user' in context)
request = context.get(u'request', None)
files = get_diff_files(filediff.diffset, filediff, interdiffset, interfilediff=interfilediff, request=request)
populate_diff_chunks(files, get_enable_highlighting(context[u'user']), request=request)
context[key] = files
if (not files):
return None
assert (len(files) == 1)
return files[0]
| [
"def",
"get_file_from_filediff",
"(",
"context",
",",
"filediff",
",",
"interfilediff",
")",
":",
"interdiffset",
"=",
"None",
"key",
"=",
"(",
"u'_diff_files_%s_%s'",
"%",
"(",
"filediff",
".",
"diffset",
".",
"id",
",",
"filediff",
".",
"id",
")",
")",
"if",
"interfilediff",
":",
"key",
"+=",
"(",
"u'_%s'",
"%",
"interfilediff",
".",
"id",
")",
"interdiffset",
"=",
"interfilediff",
".",
"diffset",
"if",
"(",
"key",
"in",
"context",
")",
":",
"files",
"=",
"context",
"[",
"key",
"]",
"else",
":",
"assert",
"(",
"u'user'",
"in",
"context",
")",
"request",
"=",
"context",
".",
"get",
"(",
"u'request'",
",",
"None",
")",
"files",
"=",
"get_diff_files",
"(",
"filediff",
".",
"diffset",
",",
"filediff",
",",
"interdiffset",
",",
"interfilediff",
"=",
"interfilediff",
",",
"request",
"=",
"request",
")",
"populate_diff_chunks",
"(",
"files",
",",
"get_enable_highlighting",
"(",
"context",
"[",
"u'user'",
"]",
")",
",",
"request",
"=",
"request",
")",
"context",
"[",
"key",
"]",
"=",
"files",
"if",
"(",
"not",
"files",
")",
":",
"return",
"None",
"assert",
"(",
"len",
"(",
"files",
")",
"==",
"1",
")",
"return",
"files",
"[",
"0",
"]"
] | return the files that corresponds to the filediff/interfilediff . | train | false |
20,663 | def timestampUNIX(value):
if (not isinstance(value, (float, int, long))):
raise TypeError('timestampUNIX(): an integer or float is required')
if (not (0 <= value <= 2147483647)):
raise ValueError('timestampUNIX(): value have to be in 0..2147483647')
return (UNIX_TIMESTAMP_T0 + timedelta(seconds=value))
| [
"def",
"timestampUNIX",
"(",
"value",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"value",
",",
"(",
"float",
",",
"int",
",",
"long",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'timestampUNIX(): an integer or float is required'",
")",
"if",
"(",
"not",
"(",
"0",
"<=",
"value",
"<=",
"2147483647",
")",
")",
":",
"raise",
"ValueError",
"(",
"'timestampUNIX(): value have to be in 0..2147483647'",
")",
"return",
"(",
"UNIX_TIMESTAMP_T0",
"+",
"timedelta",
"(",
"seconds",
"=",
"value",
")",
")"
] | convert an unix timestamp to datetime object . | train | false |
20,664 | def generate_derangements(perm):
p = multiset_permutations(perm)
indices = range(len(perm))
p0 = next(p)
for pi in p:
if all(((pi[i] != p0[i]) for i in indices)):
(yield pi)
| [
"def",
"generate_derangements",
"(",
"perm",
")",
":",
"p",
"=",
"multiset_permutations",
"(",
"perm",
")",
"indices",
"=",
"range",
"(",
"len",
"(",
"perm",
")",
")",
"p0",
"=",
"next",
"(",
"p",
")",
"for",
"pi",
"in",
"p",
":",
"if",
"all",
"(",
"(",
"(",
"pi",
"[",
"i",
"]",
"!=",
"p0",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"indices",
")",
")",
":",
"(",
"yield",
"pi",
")"
] | routine to generate unique derangements . | train | false |
20,666 | def worker_disabled(name, workers=None, profile='default'):
if (workers is None):
workers = []
return _bulk_state('modjk.bulk_disable', name, workers, profile)
| [
"def",
"worker_disabled",
"(",
"name",
",",
"workers",
"=",
"None",
",",
"profile",
"=",
"'default'",
")",
":",
"if",
"(",
"workers",
"is",
"None",
")",
":",
"workers",
"=",
"[",
"]",
"return",
"_bulk_state",
"(",
"'modjk.bulk_disable'",
",",
"name",
",",
"workers",
",",
"profile",
")"
] | disable all the workers in the modjk load balancer example: . | train | true |
20,667 | def _hash_categorical(c, encoding, hash_key):
cat_hashed = hash_array(c.categories.values, encoding, hash_key, categorize=False).astype(np.uint64, copy=False)
return c.rename_categories(cat_hashed).astype(np.uint64)
| [
"def",
"_hash_categorical",
"(",
"c",
",",
"encoding",
",",
"hash_key",
")",
":",
"cat_hashed",
"=",
"hash_array",
"(",
"c",
".",
"categories",
".",
"values",
",",
"encoding",
",",
"hash_key",
",",
"categorize",
"=",
"False",
")",
".",
"astype",
"(",
"np",
".",
"uint64",
",",
"copy",
"=",
"False",
")",
"return",
"c",
".",
"rename_categories",
"(",
"cat_hashed",
")",
".",
"astype",
"(",
"np",
".",
"uint64",
")"
] | hash a categorical by hashing its categories . | train | false |
20,668 | def compute_totp(secret, offset=0):
assert (type(secret) == six.text_type)
assert (type(offset) in six.integer_types)
try:
key = base64.b32decode(secret)
except TypeError:
raise Exception('invalid secret')
interval = (offset + (int(time.time()) // 30))
msg = struct.pack('>Q', interval)
digest = hmac.new(key, msg, hashlib.sha1).digest()
o = (15 & (digest[19] if six.PY3 else ord(digest[19])))
token = ((struct.unpack('>I', digest[o:(o + 4)])[0] & 2147483647) % 1000000)
return u'{0:06d}'.format(token)
| [
"def",
"compute_totp",
"(",
"secret",
",",
"offset",
"=",
"0",
")",
":",
"assert",
"(",
"type",
"(",
"secret",
")",
"==",
"six",
".",
"text_type",
")",
"assert",
"(",
"type",
"(",
"offset",
")",
"in",
"six",
".",
"integer_types",
")",
"try",
":",
"key",
"=",
"base64",
".",
"b32decode",
"(",
"secret",
")",
"except",
"TypeError",
":",
"raise",
"Exception",
"(",
"'invalid secret'",
")",
"interval",
"=",
"(",
"offset",
"+",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"//",
"30",
")",
")",
"msg",
"=",
"struct",
".",
"pack",
"(",
"'>Q'",
",",
"interval",
")",
"digest",
"=",
"hmac",
".",
"new",
"(",
"key",
",",
"msg",
",",
"hashlib",
".",
"sha1",
")",
".",
"digest",
"(",
")",
"o",
"=",
"(",
"15",
"&",
"(",
"digest",
"[",
"19",
"]",
"if",
"six",
".",
"PY3",
"else",
"ord",
"(",
"digest",
"[",
"19",
"]",
")",
")",
")",
"token",
"=",
"(",
"(",
"struct",
".",
"unpack",
"(",
"'>I'",
",",
"digest",
"[",
"o",
":",
"(",
"o",
"+",
"4",
")",
"]",
")",
"[",
"0",
"]",
"&",
"2147483647",
")",
"%",
"1000000",
")",
"return",
"u'{0:06d}'",
".",
"format",
"(",
"token",
")"
] | computes the current totp code . | train | false |
20,669 | @pytest.fixture(scope='session')
def administrate(pootle_content_type):
return _require_permission('administrate', 'Can administrate a TP', pootle_content_type)
| [
"@",
"pytest",
".",
"fixture",
"(",
"scope",
"=",
"'session'",
")",
"def",
"administrate",
"(",
"pootle_content_type",
")",
":",
"return",
"_require_permission",
"(",
"'administrate'",
",",
"'Can administrate a TP'",
",",
"pootle_content_type",
")"
] | require the suggest permission . | train | false |
20,670 | def get_remote_version():
gs_page = requests.get(GETTING_STARTED_URL).text
mdi_download = re.search(DOWNLOAD_LINK, gs_page)
if (not mdi_download):
print 'Unable to find download link'
sys.exit()
return ('https://materialdesignicons.com' + mdi_download.group(1))
| [
"def",
"get_remote_version",
"(",
")",
":",
"gs_page",
"=",
"requests",
".",
"get",
"(",
"GETTING_STARTED_URL",
")",
".",
"text",
"mdi_download",
"=",
"re",
".",
"search",
"(",
"DOWNLOAD_LINK",
",",
"gs_page",
")",
"if",
"(",
"not",
"mdi_download",
")",
":",
"print",
"'Unable to find download link'",
"sys",
".",
"exit",
"(",
")",
"return",
"(",
"'https://materialdesignicons.com'",
"+",
"mdi_download",
".",
"group",
"(",
"1",
")",
")"
] | get current version and download link . | train | false |
20,673 | def verify_dir_has_perm(path, perm, levels=0):
if (not os.path.exists(path)):
raise RuntimeError(('%s does NOT exist!' % path))
path = os.path.normpath(path)
pdepth = len(path.split(os.path.sep))
pathaccess = os.access(path, perm)
if ((not levels) or (not pathaccess)):
return pathaccess
for (root, dirs, files) in os.walk(path):
currentlevel = (len(root.split(os.path.sep)) - pdepth)
if (currentlevel > levels):
break
elif ('.git' in dirs):
dirs.remove('.git')
for file_path in (os.path.join(root, f) for f in (dirs + files)):
if os.path.exists(file_path):
if (not os.access(file_path, perm)):
return False
return True
| [
"def",
"verify_dir_has_perm",
"(",
"path",
",",
"perm",
",",
"levels",
"=",
"0",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"(",
"'%s does NOT exist!'",
"%",
"path",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
"pdepth",
"=",
"len",
"(",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
"pathaccess",
"=",
"os",
".",
"access",
"(",
"path",
",",
"perm",
")",
"if",
"(",
"(",
"not",
"levels",
")",
"or",
"(",
"not",
"pathaccess",
")",
")",
":",
"return",
"pathaccess",
"for",
"(",
"root",
",",
"dirs",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"currentlevel",
"=",
"(",
"len",
"(",
"root",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
")",
"-",
"pdepth",
")",
"if",
"(",
"currentlevel",
">",
"levels",
")",
":",
"break",
"elif",
"(",
"'.git'",
"in",
"dirs",
")",
":",
"dirs",
".",
"remove",
"(",
"'.git'",
")",
"for",
"file_path",
"in",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"f",
")",
"for",
"f",
"in",
"(",
"dirs",
"+",
"files",
")",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"if",
"(",
"not",
"os",
".",
"access",
"(",
"file_path",
",",
"perm",
")",
")",
":",
"return",
"False",
"return",
"True"
] | verify that home directory has perm access for current user . | train | false |
20,674 | def validate_take_with_convert(convert, args, kwargs):
if (isinstance(convert, ndarray) or (convert is None)):
args = ((convert,) + args)
convert = True
validate_take(args, kwargs, max_fname_arg_count=3, method='both')
return convert
| [
"def",
"validate_take_with_convert",
"(",
"convert",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"(",
"isinstance",
"(",
"convert",
",",
"ndarray",
")",
"or",
"(",
"convert",
"is",
"None",
")",
")",
":",
"args",
"=",
"(",
"(",
"convert",
",",
")",
"+",
"args",
")",
"convert",
"=",
"True",
"validate_take",
"(",
"args",
",",
"kwargs",
",",
"max_fname_arg_count",
"=",
"3",
",",
"method",
"=",
"'both'",
")",
"return",
"convert"
] | if this function is called via the numpy library . | train | true |
20,675 | def is_flask_request():
try:
pylons.request.environ
pylons_request_available = True
except TypeError:
pylons_request_available = False
return (flask.request and ((flask.request.environ.get(u'ckan.app') == u'flask_app') or (not pylons_request_available)))
| [
"def",
"is_flask_request",
"(",
")",
":",
"try",
":",
"pylons",
".",
"request",
".",
"environ",
"pylons_request_available",
"=",
"True",
"except",
"TypeError",
":",
"pylons_request_available",
"=",
"False",
"return",
"(",
"flask",
".",
"request",
"and",
"(",
"(",
"flask",
".",
"request",
".",
"environ",
".",
"get",
"(",
"u'ckan.app'",
")",
"==",
"u'flask_app'",
")",
"or",
"(",
"not",
"pylons_request_available",
")",
")",
")"
] | a centralized way to determine whether we are in the context of a request being served by flask or pylons . | train | false |
20,678 | def image_resize_image_medium(base64_source, size=(128, 128), encoding='base64', filetype=None, avoid_if_small=False):
return image_resize_image(base64_source, size, encoding, filetype, avoid_if_small)
| [
"def",
"image_resize_image_medium",
"(",
"base64_source",
",",
"size",
"=",
"(",
"128",
",",
"128",
")",
",",
"encoding",
"=",
"'base64'",
",",
"filetype",
"=",
"None",
",",
"avoid_if_small",
"=",
"False",
")",
":",
"return",
"image_resize_image",
"(",
"base64_source",
",",
"size",
",",
"encoding",
",",
"filetype",
",",
"avoid_if_small",
")"
] | wrapper on image_resize_image . | train | false |
20,679 | def ts_css(text):
return ('<span class="ts">%s</span>' % text)
| [
"def",
"ts_css",
"(",
"text",
")",
":",
"return",
"(",
"'<span class=\"ts\">%s</span>'",
"%",
"text",
")"
] | applies nice css to the type string . | train | false |
20,680 | def _args_from_interpreter_flags():
flag_opt_map = {'debug': 'd', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'py3k_warning': '3'}
args = []
for (flag, opt) in flag_opt_map.items():
v = getattr(sys.flags, flag)
if (v > 0):
args.append(('-' + (opt * v)))
if (getattr(sys.flags, 'hash_randomization') != 0):
args.append('-R')
for opt in sys.warnoptions:
args.append(('-W' + opt))
return args
| [
"def",
"_args_from_interpreter_flags",
"(",
")",
":",
"flag_opt_map",
"=",
"{",
"'debug'",
":",
"'d'",
",",
"'optimize'",
":",
"'O'",
",",
"'dont_write_bytecode'",
":",
"'B'",
",",
"'no_user_site'",
":",
"'s'",
",",
"'no_site'",
":",
"'S'",
",",
"'ignore_environment'",
":",
"'E'",
",",
"'verbose'",
":",
"'v'",
",",
"'bytes_warning'",
":",
"'b'",
",",
"'py3k_warning'",
":",
"'3'",
"}",
"args",
"=",
"[",
"]",
"for",
"(",
"flag",
",",
"opt",
")",
"in",
"flag_opt_map",
".",
"items",
"(",
")",
":",
"v",
"=",
"getattr",
"(",
"sys",
".",
"flags",
",",
"flag",
")",
"if",
"(",
"v",
">",
"0",
")",
":",
"args",
".",
"append",
"(",
"(",
"'-'",
"+",
"(",
"opt",
"*",
"v",
")",
")",
")",
"if",
"(",
"getattr",
"(",
"sys",
".",
"flags",
",",
"'hash_randomization'",
")",
"!=",
"0",
")",
":",
"args",
".",
"append",
"(",
"'-R'",
")",
"for",
"opt",
"in",
"sys",
".",
"warnoptions",
":",
"args",
".",
"append",
"(",
"(",
"'-W'",
"+",
"opt",
")",
")",
"return",
"args"
] | return a list of command-line arguments reproducing the current settings in sys . | train | true |
20,682 | def get_pep0_page(commit=True):
pep0_content = convert_pep0()
(pep0_page, _) = Page.objects.get_or_create(path='dev/peps/')
(pep0000_page, _) = Page.objects.get_or_create(path='dev/peps/pep-0000/')
for page in [pep0_page, pep0000_page]:
page.content = pep0_content
page.content_markup_type = 'html'
page.title = 'PEP 0 -- Index of Python Enhancement Proposals (PEPs)'
page.template_name = PEP_TEMPLATE
if commit:
page.save()
return (pep0_page, pep0000_page)
| [
"def",
"get_pep0_page",
"(",
"commit",
"=",
"True",
")",
":",
"pep0_content",
"=",
"convert_pep0",
"(",
")",
"(",
"pep0_page",
",",
"_",
")",
"=",
"Page",
".",
"objects",
".",
"get_or_create",
"(",
"path",
"=",
"'dev/peps/'",
")",
"(",
"pep0000_page",
",",
"_",
")",
"=",
"Page",
".",
"objects",
".",
"get_or_create",
"(",
"path",
"=",
"'dev/peps/pep-0000/'",
")",
"for",
"page",
"in",
"[",
"pep0_page",
",",
"pep0000_page",
"]",
":",
"page",
".",
"content",
"=",
"pep0_content",
"page",
".",
"content_markup_type",
"=",
"'html'",
"page",
".",
"title",
"=",
"'PEP 0 -- Index of Python Enhancement Proposals (PEPs)'",
"page",
".",
"template_name",
"=",
"PEP_TEMPLATE",
"if",
"commit",
":",
"page",
".",
"save",
"(",
")",
"return",
"(",
"pep0_page",
",",
"pep0000_page",
")"
] | using convert_pep0 above . | train | false |
20,683 | def rt_available(rt_table):
try:
subprocess.check_call([settings.ip, 'route', 'list', 'table', rt_table], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return True
except subprocess.CalledProcessError:
return False
| [
"def",
"rt_available",
"(",
"rt_table",
")",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"settings",
".",
"ip",
",",
"'route'",
",",
"'list'",
",",
"'table'",
",",
"rt_table",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"return",
"True",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"return",
"False"
] | check if specified routing table is defined . | train | false |
20,684 | def resolve_all(x):
while isinstance(x, PDFObjRef):
x = x.resolve()
if isinstance(x, list):
x = [resolve_all(v) for v in x]
elif isinstance(x, dict):
for (k, v) in x.iteritems():
x[k] = resolve_all(v)
return x
| [
"def",
"resolve_all",
"(",
"x",
")",
":",
"while",
"isinstance",
"(",
"x",
",",
"PDFObjRef",
")",
":",
"x",
"=",
"x",
".",
"resolve",
"(",
")",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"x",
"=",
"[",
"resolve_all",
"(",
"v",
")",
"for",
"v",
"in",
"x",
"]",
"elif",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"x",
".",
"iteritems",
"(",
")",
":",
"x",
"[",
"k",
"]",
"=",
"resolve_all",
"(",
"v",
")",
"return",
"x"
] | recursively resolves the given object and all the internals . | train | true |
20,685 | def test_multiple_events_one_timer():
timer_helper(num_handlers=5)
timer_helper(num_handlers=500)
| [
"def",
"test_multiple_events_one_timer",
"(",
")",
":",
"timer_helper",
"(",
"num_handlers",
"=",
"5",
")",
"timer_helper",
"(",
"num_handlers",
"=",
"500",
")"
] | multiple event handlers hooked up to a single timer object . | train | false |
20,686 | def gnome_sort(unsorted):
if (len(unsorted) <= 1):
return unsorted
i = 1
while (i < len(unsorted)):
if (unsorted[(i - 1)] <= unsorted[i]):
i += 1
else:
(unsorted[(i - 1)], unsorted[i]) = (unsorted[i], unsorted[(i - 1)])
i -= 1
if (i == 0):
i = 1
| [
"def",
"gnome_sort",
"(",
"unsorted",
")",
":",
"if",
"(",
"len",
"(",
"unsorted",
")",
"<=",
"1",
")",
":",
"return",
"unsorted",
"i",
"=",
"1",
"while",
"(",
"i",
"<",
"len",
"(",
"unsorted",
")",
")",
":",
"if",
"(",
"unsorted",
"[",
"(",
"i",
"-",
"1",
")",
"]",
"<=",
"unsorted",
"[",
"i",
"]",
")",
":",
"i",
"+=",
"1",
"else",
":",
"(",
"unsorted",
"[",
"(",
"i",
"-",
"1",
")",
"]",
",",
"unsorted",
"[",
"i",
"]",
")",
"=",
"(",
"unsorted",
"[",
"i",
"]",
",",
"unsorted",
"[",
"(",
"i",
"-",
"1",
")",
"]",
")",
"i",
"-=",
"1",
"if",
"(",
"i",
"==",
"0",
")",
":",
"i",
"=",
"1"
] | pure implementation of the gnome sort algorithm in python . | train | false |
20,687 | def make_pre_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''):
lines = html.splitlines()
new_lines = []
for line in lines:
if (len(line) > wrap_limit):
for char in split_on:
if (char in line):
parts = line.split(char)
line = '<wbr>'.join(parts)
break
new_lines.append(line)
return '\n'.join(lines)
| [
"def",
"make_pre_wrappable",
"(",
"html",
",",
"wrap_limit",
"=",
"60",
",",
"split_on",
"=",
"';?&@!$#-/\\\\\"\\''",
")",
":",
"lines",
"=",
"html",
".",
"splitlines",
"(",
")",
"new_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"(",
"len",
"(",
"line",
")",
">",
"wrap_limit",
")",
":",
"for",
"char",
"in",
"split_on",
":",
"if",
"(",
"char",
"in",
"line",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"char",
")",
"line",
"=",
"'<wbr>'",
".",
"join",
"(",
"parts",
")",
"break",
"new_lines",
".",
"append",
"(",
"line",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] | like make_wrappable() but intended for text that will go in a <pre> block . | train | false |
20,688 | def test_runtime_error(objects, tabbed_browser):
tabbed_browser.current_index = 0
tabbed_browser.index_of = RuntimeError
objects.signaller.signal.emit('foo')
assert (objects.signaller.filtered_signal_arg is None)
| [
"def",
"test_runtime_error",
"(",
"objects",
",",
"tabbed_browser",
")",
":",
"tabbed_browser",
".",
"current_index",
"=",
"0",
"tabbed_browser",
".",
"index_of",
"=",
"RuntimeError",
"objects",
".",
"signaller",
".",
"signal",
".",
"emit",
"(",
"'foo'",
")",
"assert",
"(",
"objects",
".",
"signaller",
".",
"filtered_signal_arg",
"is",
"None",
")"
] | test that theres no crash if indexof() raises runtimeerror . | train | false |
20,689 | def obj_to_primitive(obj):
if isinstance(obj, ObjectListBase):
return [obj_to_primitive(x) for x in obj]
elif isinstance(obj, NovaObject):
result = {}
for key in obj.obj_fields:
if (obj.obj_attr_is_set(key) or (key in obj.obj_extra_fields)):
result[key] = obj_to_primitive(getattr(obj, key))
return result
elif isinstance(obj, netaddr.IPAddress):
return str(obj)
elif isinstance(obj, netaddr.IPNetwork):
return str(obj)
else:
return obj
| [
"def",
"obj_to_primitive",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ObjectListBase",
")",
":",
"return",
"[",
"obj_to_primitive",
"(",
"x",
")",
"for",
"x",
"in",
"obj",
"]",
"elif",
"isinstance",
"(",
"obj",
",",
"NovaObject",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"obj",
".",
"obj_fields",
":",
"if",
"(",
"obj",
".",
"obj_attr_is_set",
"(",
"key",
")",
"or",
"(",
"key",
"in",
"obj",
".",
"obj_extra_fields",
")",
")",
":",
"result",
"[",
"key",
"]",
"=",
"obj_to_primitive",
"(",
"getattr",
"(",
"obj",
",",
"key",
")",
")",
"return",
"result",
"elif",
"isinstance",
"(",
"obj",
",",
"netaddr",
".",
"IPAddress",
")",
":",
"return",
"str",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"netaddr",
".",
"IPNetwork",
")",
":",
"return",
"str",
"(",
"obj",
")",
"else",
":",
"return",
"obj"
] | recursively turn an object into a python primitive . | train | false |
20,690 | def upsample_filt(size):
factor = ((size + 1) // 2)
if ((size % 2) == 1):
center = (factor - 1)
else:
center = (factor - 0.5)
og = np.ogrid[:size, :size]
return ((1 - (abs((og[0] - center)) / factor)) * (1 - (abs((og[1] - center)) / factor)))
| [
"def",
"upsample_filt",
"(",
"size",
")",
":",
"factor",
"=",
"(",
"(",
"size",
"+",
"1",
")",
"//",
"2",
")",
"if",
"(",
"(",
"size",
"%",
"2",
")",
"==",
"1",
")",
":",
"center",
"=",
"(",
"factor",
"-",
"1",
")",
"else",
":",
"center",
"=",
"(",
"factor",
"-",
"0.5",
")",
"og",
"=",
"np",
".",
"ogrid",
"[",
":",
"size",
",",
":",
"size",
"]",
"return",
"(",
"(",
"1",
"-",
"(",
"abs",
"(",
"(",
"og",
"[",
"0",
"]",
"-",
"center",
")",
")",
"/",
"factor",
")",
")",
"*",
"(",
"1",
"-",
"(",
"abs",
"(",
"(",
"og",
"[",
"1",
"]",
"-",
"center",
")",
")",
"/",
"factor",
")",
")",
")"
] | make a 2d bilinear kernel suitable for upsampling of the given size . | train | true |
20,691 | def lock_host(func, *args, **kwargs):
def inner(self, *args, **kwargs):
self.host_lock.acquire()
try:
res = func(self, *args, **kwargs)
self.host_lock.release()
except Exception as e:
self.host_lock.release()
raise e
return res
return inner
| [
"def",
"lock_host",
"(",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"self",
".",
"host_lock",
".",
"acquire",
"(",
")",
"try",
":",
"res",
"=",
"func",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"self",
".",
"host_lock",
".",
"release",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"host_lock",
".",
"release",
"(",
")",
"raise",
"e",
"return",
"res",
"return",
"inner"
] | a decorator that acquires a lock before accessing the debugger to avoid api locking related errors with the debugger host . | train | true |
20,692 | def _expand_typestr(p_type):
if re.search('\\bor\\b', p_type):
types = [t.strip() for t in p_type.split('or')]
elif p_type.startswith('{'):
p_type = p_type.replace('{', '[').replace('}', ']')
types = set((type(x).__name__ for x in literal_eval(p_type)))
types = list(types)
else:
types = [p_type]
return types
| [
"def",
"_expand_typestr",
"(",
"p_type",
")",
":",
"if",
"re",
".",
"search",
"(",
"'\\\\bor\\\\b'",
",",
"p_type",
")",
":",
"types",
"=",
"[",
"t",
".",
"strip",
"(",
")",
"for",
"t",
"in",
"p_type",
".",
"split",
"(",
"'or'",
")",
"]",
"elif",
"p_type",
".",
"startswith",
"(",
"'{'",
")",
":",
"p_type",
"=",
"p_type",
".",
"replace",
"(",
"'{'",
",",
"'['",
")",
".",
"replace",
"(",
"'}'",
",",
"']'",
")",
"types",
"=",
"set",
"(",
"(",
"type",
"(",
"x",
")",
".",
"__name__",
"for",
"x",
"in",
"literal_eval",
"(",
"p_type",
")",
")",
")",
"types",
"=",
"list",
"(",
"types",
")",
"else",
":",
"types",
"=",
"[",
"p_type",
"]",
"return",
"types"
] | attempts to interpret the possible types . | train | false |
20,693 | def getLocalAttribute(xmlElement):
for key in xmlElement.attributeDictionary:
if key[:1].isalpha():
value = evaluate.getEvaluatorSplitWords(xmlElement.attributeDictionary[key])
if key.startswith('local.'):
return evaluate.KeyValue(key[len('local.'):], value)
return evaluate.KeyValue(key, value)
return evaluate.KeyValue()
| [
"def",
"getLocalAttribute",
"(",
"xmlElement",
")",
":",
"for",
"key",
"in",
"xmlElement",
".",
"attributeDictionary",
":",
"if",
"key",
"[",
":",
"1",
"]",
".",
"isalpha",
"(",
")",
":",
"value",
"=",
"evaluate",
".",
"getEvaluatorSplitWords",
"(",
"xmlElement",
".",
"attributeDictionary",
"[",
"key",
"]",
")",
"if",
"key",
".",
"startswith",
"(",
"'local.'",
")",
":",
"return",
"evaluate",
".",
"KeyValue",
"(",
"key",
"[",
"len",
"(",
"'local.'",
")",
":",
"]",
",",
"value",
")",
"return",
"evaluate",
".",
"KeyValue",
"(",
"key",
",",
"value",
")",
"return",
"evaluate",
".",
"KeyValue",
"(",
")"
] | get the local attribute if any . | train | false |
20,694 | def MapStateMessage(state):
return {STATE_READ: 'Batch read from file.', STATE_GETTING: 'Querying for batch from server', STATE_GOT: 'Batch successfully fetched.', STATE_ERROR: 'Error while fetching or mapping.'}[state]
| [
"def",
"MapStateMessage",
"(",
"state",
")",
":",
"return",
"{",
"STATE_READ",
":",
"'Batch read from file.'",
",",
"STATE_GETTING",
":",
"'Querying for batch from server'",
",",
"STATE_GOT",
":",
"'Batch successfully fetched.'",
",",
"STATE_ERROR",
":",
"'Error while fetching or mapping.'",
"}",
"[",
"state",
"]"
] | converts a numeric state identifier to a status message . | train | false |
20,696 | def _ls_emr_step_syslogs(fs, log_dir_stream, step_id=None):
matches = _ls_logs(fs, log_dir_stream, _match_emr_step_syslog_path, step_id=step_id)
return sorted(matches, key=_match_sort_key)
| [
"def",
"_ls_emr_step_syslogs",
"(",
"fs",
",",
"log_dir_stream",
",",
"step_id",
"=",
"None",
")",
":",
"matches",
"=",
"_ls_logs",
"(",
"fs",
",",
"log_dir_stream",
",",
"_match_emr_step_syslog_path",
",",
"step_id",
"=",
"step_id",
")",
"return",
"sorted",
"(",
"matches",
",",
"key",
"=",
"_match_sort_key",
")"
] | yield matching step logs . | train | false |
20,697 | def _ipaddress_match(ipname, host_ip):
ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
return (ip == host_ip)
| [
"def",
"_ipaddress_match",
"(",
"ipname",
",",
"host_ip",
")",
":",
"ip",
"=",
"ipaddress",
".",
"ip_address",
"(",
"_to_unicode",
"(",
"ipname",
")",
".",
"rstrip",
"(",
")",
")",
"return",
"(",
"ip",
"==",
"host_ip",
")"
] | exact matching of ip addresses . | train | true |
20,698 | def indefinite_article(word):
return 'a'
| [
"def",
"indefinite_article",
"(",
"word",
")",
":",
"return",
"'a'"
] | returns the indefinite article for a given word . | train | false |
20,699 | @commands(u'cur', u'currency', u'exchange')
@example(u'.cur 20 EUR in USD')
def exchange(bot, trigger):
if (not trigger.group(2)):
return bot.reply(u'No search term. An example: .cur 20 EUR in USD')
match = regex.match(trigger.group(2))
if (not match):
bot.reply(u"Sorry, I didn't understand the input.")
return NOLIMIT
(amount, of, to) = match.groups()
try:
amount = float(amount)
except:
bot.reply(u"Sorry, I didn't understand the input.")
display(bot, amount, of, to)
| [
"@",
"commands",
"(",
"u'cur'",
",",
"u'currency'",
",",
"u'exchange'",
")",
"@",
"example",
"(",
"u'.cur 20 EUR in USD'",
")",
"def",
"exchange",
"(",
"bot",
",",
"trigger",
")",
":",
"if",
"(",
"not",
"trigger",
".",
"group",
"(",
"2",
")",
")",
":",
"return",
"bot",
".",
"reply",
"(",
"u'No search term. An example: .cur 20 EUR in USD'",
")",
"match",
"=",
"regex",
".",
"match",
"(",
"trigger",
".",
"group",
"(",
"2",
")",
")",
"if",
"(",
"not",
"match",
")",
":",
"bot",
".",
"reply",
"(",
"u\"Sorry, I didn't understand the input.\"",
")",
"return",
"NOLIMIT",
"(",
"amount",
",",
"of",
",",
"to",
")",
"=",
"match",
".",
"groups",
"(",
")",
"try",
":",
"amount",
"=",
"float",
"(",
"amount",
")",
"except",
":",
"bot",
".",
"reply",
"(",
"u\"Sorry, I didn't understand the input.\"",
")",
"display",
"(",
"bot",
",",
"amount",
",",
"of",
",",
"to",
")"
] | show the exchange rate between two currencies . | train | false |
20,700 | @verbose
def tfr_morlet(inst, freqs, n_cycles, use_fft=False, return_itc=True, decim=1, n_jobs=1, picks=None, zero_mean=True, average=True, verbose=None):
tfr_params = dict(n_cycles=n_cycles, n_jobs=n_jobs, use_fft=use_fft, zero_mean=zero_mean)
return _tfr_aux('morlet', inst, freqs, decim, return_itc, picks, average, **tfr_params)
| [
"@",
"verbose",
"def",
"tfr_morlet",
"(",
"inst",
",",
"freqs",
",",
"n_cycles",
",",
"use_fft",
"=",
"False",
",",
"return_itc",
"=",
"True",
",",
"decim",
"=",
"1",
",",
"n_jobs",
"=",
"1",
",",
"picks",
"=",
"None",
",",
"zero_mean",
"=",
"True",
",",
"average",
"=",
"True",
",",
"verbose",
"=",
"None",
")",
":",
"tfr_params",
"=",
"dict",
"(",
"n_cycles",
"=",
"n_cycles",
",",
"n_jobs",
"=",
"n_jobs",
",",
"use_fft",
"=",
"use_fft",
",",
"zero_mean",
"=",
"zero_mean",
")",
"return",
"_tfr_aux",
"(",
"'morlet'",
",",
"inst",
",",
"freqs",
",",
"decim",
",",
"return_itc",
",",
"picks",
",",
"average",
",",
"**",
"tfr_params",
")"
] | compute time-frequency representation using morlet wavelets . | train | false |
20,701 | def merge_trees(src, dest):
if (not os.path.exists(src)):
return
elif (not os.path.exists(dest)):
if os.path.isfile(src):
shutil.copy2(src, dest)
else:
shutil.copytree(src, dest, symlinks=True)
return
elif (os.path.isfile(src) and os.path.isfile(dest)):
destfile = open(dest, 'a')
try:
srcfile = open(src)
try:
destfile.write(srcfile.read())
finally:
srcfile.close()
finally:
destfile.close()
elif (os.path.isdir(src) and os.path.isdir(dest)):
for name in os.listdir(src):
merge_trees(os.path.join(src, name), os.path.join(dest, name))
else:
return
| [
"def",
"merge_trees",
"(",
"src",
",",
"dest",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"src",
")",
")",
":",
"return",
"elif",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"src",
")",
":",
"shutil",
".",
"copy2",
"(",
"src",
",",
"dest",
")",
"else",
":",
"shutil",
".",
"copytree",
"(",
"src",
",",
"dest",
",",
"symlinks",
"=",
"True",
")",
"return",
"elif",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"src",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"dest",
")",
")",
":",
"destfile",
"=",
"open",
"(",
"dest",
",",
"'a'",
")",
"try",
":",
"srcfile",
"=",
"open",
"(",
"src",
")",
"try",
":",
"destfile",
".",
"write",
"(",
"srcfile",
".",
"read",
"(",
")",
")",
"finally",
":",
"srcfile",
".",
"close",
"(",
")",
"finally",
":",
"destfile",
".",
"close",
"(",
")",
"elif",
"(",
"os",
".",
"path",
".",
"isdir",
"(",
"src",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"dest",
")",
")",
":",
"for",
"name",
"in",
"os",
".",
"listdir",
"(",
"src",
")",
":",
"merge_trees",
"(",
"os",
".",
"path",
".",
"join",
"(",
"src",
",",
"name",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"name",
")",
")",
"else",
":",
"return"
] | merges a source directory tree at src into a destination tree at dest . | train | false |
20,703 | def _millis_from_datetime(value):
if (value is not None):
return _millis(value)
| [
"def",
"_millis_from_datetime",
"(",
"value",
")",
":",
"if",
"(",
"value",
"is",
"not",
"None",
")",
":",
"return",
"_millis",
"(",
"value",
")"
] | convert non-none datetime to timestamp . | train | false |
20,705 | def _unify_sources_and_hashes(source=None, source_hash=None, sources=None, source_hashes=None):
if (sources is None):
sources = []
if (source_hashes is None):
source_hashes = []
if (source and sources):
return (False, 'source and sources are mutually exclusive', [])
if (source_hash and source_hashes):
return (False, 'source_hash and source_hashes are mutually exclusive', [])
if source:
return (True, '', [(source, source_hash)])
return (True, '', list(zip_longest(sources, source_hashes[:len(sources)])))
| [
"def",
"_unify_sources_and_hashes",
"(",
"source",
"=",
"None",
",",
"source_hash",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"source_hashes",
"=",
"None",
")",
":",
"if",
"(",
"sources",
"is",
"None",
")",
":",
"sources",
"=",
"[",
"]",
"if",
"(",
"source_hashes",
"is",
"None",
")",
":",
"source_hashes",
"=",
"[",
"]",
"if",
"(",
"source",
"and",
"sources",
")",
":",
"return",
"(",
"False",
",",
"'source and sources are mutually exclusive'",
",",
"[",
"]",
")",
"if",
"(",
"source_hash",
"and",
"source_hashes",
")",
":",
"return",
"(",
"False",
",",
"'source_hash and source_hashes are mutually exclusive'",
",",
"[",
"]",
")",
"if",
"source",
":",
"return",
"(",
"True",
",",
"''",
",",
"[",
"(",
"source",
",",
"source_hash",
")",
"]",
")",
"return",
"(",
"True",
",",
"''",
",",
"list",
"(",
"zip_longest",
"(",
"sources",
",",
"source_hashes",
"[",
":",
"len",
"(",
"sources",
")",
"]",
")",
")",
")"
] | silly little function to give us a standard tuple list for sources and source_hashes . | train | true |
20,706 | def complete_rule(rule, cmd):
global rline_mpstate
rule_components = rule.split(' ')
if (len(cmd) == 0):
return rule_expand(rule_components[0], '')
for i in range((len(cmd) - 1)):
if (not rule_match(rule_components[i], cmd[i])):
return []
expanded = rule_expand(rule_components[(len(cmd) - 1)], cmd[(-1)])
return expanded
| [
"def",
"complete_rule",
"(",
"rule",
",",
"cmd",
")",
":",
"global",
"rline_mpstate",
"rule_components",
"=",
"rule",
".",
"split",
"(",
"' '",
")",
"if",
"(",
"len",
"(",
"cmd",
")",
"==",
"0",
")",
":",
"return",
"rule_expand",
"(",
"rule_components",
"[",
"0",
"]",
",",
"''",
")",
"for",
"i",
"in",
"range",
"(",
"(",
"len",
"(",
"cmd",
")",
"-",
"1",
")",
")",
":",
"if",
"(",
"not",
"rule_match",
"(",
"rule_components",
"[",
"i",
"]",
",",
"cmd",
"[",
"i",
"]",
")",
")",
":",
"return",
"[",
"]",
"expanded",
"=",
"rule_expand",
"(",
"rule_components",
"[",
"(",
"len",
"(",
"cmd",
")",
"-",
"1",
")",
"]",
",",
"cmd",
"[",
"(",
"-",
"1",
")",
"]",
")",
"return",
"expanded"
] | complete using one rule . | train | true |
20,708 | def octave_code(expr, assign_to=None, **settings):
return OctaveCodePrinter(settings).doprint(expr, assign_to)
| [
"def",
"octave_code",
"(",
"expr",
",",
"assign_to",
"=",
"None",
",",
"**",
"settings",
")",
":",
"return",
"OctaveCodePrinter",
"(",
"settings",
")",
".",
"doprint",
"(",
"expr",
",",
"assign_to",
")"
] | converts expr to a string of octave code . | train | false |
20,709 | def rm_permissions(obj_name, principal, ace_type='all', obj_type='file'):
dacl = Dacl(obj_name, obj_type)
dacl.rm_ace(principal, ace_type)
dacl.save(obj_name)
return True
| [
"def",
"rm_permissions",
"(",
"obj_name",
",",
"principal",
",",
"ace_type",
"=",
"'all'",
",",
"obj_type",
"=",
"'file'",
")",
":",
"dacl",
"=",
"Dacl",
"(",
"obj_name",
",",
"obj_type",
")",
"dacl",
".",
"rm_ace",
"(",
"principal",
",",
"ace_type",
")",
"dacl",
".",
"save",
"(",
"obj_name",
")",
"return",
"True"
] | remove a users ace from an object . | train | true |
20,710 | def _polar_to_cartesian(theta, r):
x = (r * np.cos(theta))
y = (r * np.sin(theta))
return (x, y)
| [
"def",
"_polar_to_cartesian",
"(",
"theta",
",",
"r",
")",
":",
"x",
"=",
"(",
"r",
"*",
"np",
".",
"cos",
"(",
"theta",
")",
")",
"y",
"=",
"(",
"r",
"*",
"np",
".",
"sin",
"(",
"theta",
")",
")",
"return",
"(",
"x",
",",
"y",
")"
] | transform polar coordinates to cartesian . | train | false |
20,711 | @event(u'manager.config_updated')
@event(u'manager.daemon.started')
def register_web_server(manager):
global web_server, config_hash
if (not manager.is_daemon):
return
config = manager.config.get(u'web_server')
if (get_config_hash(config) == config_hash):
log.debug(u"web server config has'nt changed")
return
config_hash = get_config_hash(config)
web_server_config = prepare_config(config)
stop_server(manager)
if (not web_server_config):
return
log.info(u'Running web server at IP %s:%s', web_server_config[u'bind'], web_server_config[u'port'])
api_app.secret_key = get_secret()
log.info(u'Initiating API')
register_app(u'/api', api_app)
if web_server_config.get(u'web_ui'):
log.info(u'Registering WebUI')
register_web_ui(manager)
web_server = setup_server(web_server_config)
| [
"@",
"event",
"(",
"u'manager.config_updated'",
")",
"@",
"event",
"(",
"u'manager.daemon.started'",
")",
"def",
"register_web_server",
"(",
"manager",
")",
":",
"global",
"web_server",
",",
"config_hash",
"if",
"(",
"not",
"manager",
".",
"is_daemon",
")",
":",
"return",
"config",
"=",
"manager",
".",
"config",
".",
"get",
"(",
"u'web_server'",
")",
"if",
"(",
"get_config_hash",
"(",
"config",
")",
"==",
"config_hash",
")",
":",
"log",
".",
"debug",
"(",
"u\"web server config has'nt changed\"",
")",
"return",
"config_hash",
"=",
"get_config_hash",
"(",
"config",
")",
"web_server_config",
"=",
"prepare_config",
"(",
"config",
")",
"stop_server",
"(",
"manager",
")",
"if",
"(",
"not",
"web_server_config",
")",
":",
"return",
"log",
".",
"info",
"(",
"u'Running web server at IP %s:%s'",
",",
"web_server_config",
"[",
"u'bind'",
"]",
",",
"web_server_config",
"[",
"u'port'",
"]",
")",
"api_app",
".",
"secret_key",
"=",
"get_secret",
"(",
")",
"log",
".",
"info",
"(",
"u'Initiating API'",
")",
"register_app",
"(",
"u'/api'",
",",
"api_app",
")",
"if",
"web_server_config",
".",
"get",
"(",
"u'web_ui'",
")",
":",
"log",
".",
"info",
"(",
"u'Registering WebUI'",
")",
"register_web_ui",
"(",
"manager",
")",
"web_server",
"=",
"setup_server",
"(",
"web_server_config",
")"
] | registers web server and loads api and webui via config . | train | false |
20,712 | def test_unicode_column_names(table_types):
if six.PY2:
t = table_types.Table([[1]], names=(six.text_type('a'),))
assert (t.colnames == ['a'])
t[six.text_type('b')] = 0.0
assert (t.colnames == ['a', 'b'])
| [
"def",
"test_unicode_column_names",
"(",
"table_types",
")",
":",
"if",
"six",
".",
"PY2",
":",
"t",
"=",
"table_types",
".",
"Table",
"(",
"[",
"[",
"1",
"]",
"]",
",",
"names",
"=",
"(",
"six",
".",
"text_type",
"(",
"'a'",
")",
",",
")",
")",
"assert",
"(",
"t",
".",
"colnames",
"==",
"[",
"'a'",
"]",
")",
"t",
"[",
"six",
".",
"text_type",
"(",
"'b'",
")",
"]",
"=",
"0.0",
"assert",
"(",
"t",
".",
"colnames",
"==",
"[",
"'a'",
",",
"'b'",
"]",
")"
] | test that unicode column names are accepted . | train | false |
20,713 | @ultra_slow_test
@requires_freesurfer
@testing.requires_testing_data
def test_watershed_bem():
check_usage(mne_watershed_bem)
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', 'mri')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(mridata_path_new)
if op.exists(op.join(mridata_path, 'T1')):
shutil.copytree(op.join(mridata_path, 'T1'), op.join(mridata_path_new, 'T1'))
if op.exists(op.join(mridata_path, 'T1.mgz')):
shutil.copyfile(op.join(mridata_path, 'T1.mgz'), op.join(mridata_path_new, 'T1.mgz'))
with ArgvSetter(('-d', tempdir, '-s', 'sample', '-o'), disable_stdout=False, disable_stderr=False):
mne_watershed_bem.run()
| [
"@",
"ultra_slow_test",
"@",
"requires_freesurfer",
"@",
"testing",
".",
"requires_testing_data",
"def",
"test_watershed_bem",
"(",
")",
":",
"check_usage",
"(",
"mne_watershed_bem",
")",
"tempdir",
"=",
"_TempDir",
"(",
")",
"mridata_path",
"=",
"op",
".",
"join",
"(",
"subjects_dir",
",",
"'sample'",
",",
"'mri'",
")",
"mridata_path_new",
"=",
"op",
".",
"join",
"(",
"tempdir",
",",
"'sample'",
",",
"'mri'",
")",
"os",
".",
"mkdir",
"(",
"op",
".",
"join",
"(",
"tempdir",
",",
"'sample'",
")",
")",
"os",
".",
"mkdir",
"(",
"mridata_path_new",
")",
"if",
"op",
".",
"exists",
"(",
"op",
".",
"join",
"(",
"mridata_path",
",",
"'T1'",
")",
")",
":",
"shutil",
".",
"copytree",
"(",
"op",
".",
"join",
"(",
"mridata_path",
",",
"'T1'",
")",
",",
"op",
".",
"join",
"(",
"mridata_path_new",
",",
"'T1'",
")",
")",
"if",
"op",
".",
"exists",
"(",
"op",
".",
"join",
"(",
"mridata_path",
",",
"'T1.mgz'",
")",
")",
":",
"shutil",
".",
"copyfile",
"(",
"op",
".",
"join",
"(",
"mridata_path",
",",
"'T1.mgz'",
")",
",",
"op",
".",
"join",
"(",
"mridata_path_new",
",",
"'T1.mgz'",
")",
")",
"with",
"ArgvSetter",
"(",
"(",
"'-d'",
",",
"tempdir",
",",
"'-s'",
",",
"'sample'",
",",
"'-o'",
")",
",",
"disable_stdout",
"=",
"False",
",",
"disable_stderr",
"=",
"False",
")",
":",
"mne_watershed_bem",
".",
"run",
"(",
")"
] | test mne watershed bem . | train | false |
20,715 | def _CreateIndexOnlyQueryResults(results, postfix_props):
new_results = []
for result in results:
new_results.extend(_CreateIndexEntities(result, postfix_props))
return new_results
| [
"def",
"_CreateIndexOnlyQueryResults",
"(",
"results",
",",
"postfix_props",
")",
":",
"new_results",
"=",
"[",
"]",
"for",
"result",
"in",
"results",
":",
"new_results",
".",
"extend",
"(",
"_CreateIndexEntities",
"(",
"result",
",",
"postfix_props",
")",
")",
"return",
"new_results"
] | creates a result set similar to that returned by an index only query . | train | false |
20,716 | def _get_headnode_dict(fixer_list):
head_nodes = collections.defaultdict(list)
every = []
for fixer in fixer_list:
if fixer.pattern:
try:
heads = _get_head_types(fixer.pattern)
except _EveryNode:
every.append(fixer)
else:
for node_type in heads:
head_nodes[node_type].append(fixer)
elif (fixer._accept_type is not None):
head_nodes[fixer._accept_type].append(fixer)
else:
every.append(fixer)
for node_type in chain(pygram.python_grammar.symbol2number.values(), pygram.python_grammar.tokens):
head_nodes[node_type].extend(every)
return dict(head_nodes)
| [
"def",
"_get_headnode_dict",
"(",
"fixer_list",
")",
":",
"head_nodes",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"every",
"=",
"[",
"]",
"for",
"fixer",
"in",
"fixer_list",
":",
"if",
"fixer",
".",
"pattern",
":",
"try",
":",
"heads",
"=",
"_get_head_types",
"(",
"fixer",
".",
"pattern",
")",
"except",
"_EveryNode",
":",
"every",
".",
"append",
"(",
"fixer",
")",
"else",
":",
"for",
"node_type",
"in",
"heads",
":",
"head_nodes",
"[",
"node_type",
"]",
".",
"append",
"(",
"fixer",
")",
"elif",
"(",
"fixer",
".",
"_accept_type",
"is",
"not",
"None",
")",
":",
"head_nodes",
"[",
"fixer",
".",
"_accept_type",
"]",
".",
"append",
"(",
"fixer",
")",
"else",
":",
"every",
".",
"append",
"(",
"fixer",
")",
"for",
"node_type",
"in",
"chain",
"(",
"pygram",
".",
"python_grammar",
".",
"symbol2number",
".",
"values",
"(",
")",
",",
"pygram",
".",
"python_grammar",
".",
"tokens",
")",
":",
"head_nodes",
"[",
"node_type",
"]",
".",
"extend",
"(",
"every",
")",
"return",
"dict",
"(",
"head_nodes",
")"
] | accepts a list of fixers and returns a dictionary of head node type --> fixer list . | train | true |
20,717 | def _config_dir():
return __salt__['config.option']('poudriere.config_dir')
| [
"def",
"_config_dir",
"(",
")",
":",
"return",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'poudriere.config_dir'",
")"
] | return the configuration directory to use . | train | false |
20,718 | def _urlencode(items):
try:
return urllib.urlencode(items)
except UnicodeEncodeError:
return urllib.urlencode([(k, smart_str(v)) for (k, v) in items])
| [
"def",
"_urlencode",
"(",
"items",
")",
":",
"try",
":",
"return",
"urllib",
".",
"urlencode",
"(",
"items",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"urllib",
".",
"urlencode",
"(",
"[",
"(",
"k",
",",
"smart_str",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"items",
"]",
")"
] | a unicode-safe urlencoder . | train | true |
20,719 | def remove_null_handler():
_DULWICH_LOGGER.removeHandler(_NULL_HANDLER)
| [
"def",
"remove_null_handler",
"(",
")",
":",
"_DULWICH_LOGGER",
".",
"removeHandler",
"(",
"_NULL_HANDLER",
")"
] | remove the null handler from the dulwich loggers . | train | false |
20,720 | def _google_voice_sms(phone_number, msg):
try:
_voice.send_sms(phone_number, msg)
except googlevoice.ValidationError:
pass
| [
"def",
"_google_voice_sms",
"(",
"phone_number",
",",
"msg",
")",
":",
"try",
":",
"_voice",
".",
"send_sms",
"(",
"phone_number",
",",
"msg",
")",
"except",
"googlevoice",
".",
"ValidationError",
":",
"pass"
] | sends an sms message to phone_number with a message containing msg . | train | false |
20,721 | def test_write_no_pad():
out = StringIO()
ascii.write(dat, out, Writer=ascii.FixedWidth, delimiter_pad=None)
assert_equal_splitlines(out.getvalue(), '|Col1| Col2|Col3|Col4|\n| 1.2| "hello"| 1| a|\n| 2.4|\'s worlds| 2| 2|\n')
| [
"def",
"test_write_no_pad",
"(",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"ascii",
".",
"write",
"(",
"dat",
",",
"out",
",",
"Writer",
"=",
"ascii",
".",
"FixedWidth",
",",
"delimiter_pad",
"=",
"None",
")",
"assert_equal_splitlines",
"(",
"out",
".",
"getvalue",
"(",
")",
",",
"'|Col1| Col2|Col3|Col4|\\n| 1.2| \"hello\"| 1| a|\\n| 2.4|\\'s worlds| 2| 2|\\n'",
")"
] | write a table as a fixed width table with no padding . | train | false |
20,722 | def matches_schema(pattern, schema, ambiguity_character='*'):
if (len(pattern) != len(schema)):
return 0
for pos in range(len(pattern)):
if ((schema[pos] != ambiguity_character) and (pattern[pos] != ambiguity_character) and (pattern[pos] != schema[pos])):
return 0
return 1
| [
"def",
"matches_schema",
"(",
"pattern",
",",
"schema",
",",
"ambiguity_character",
"=",
"'*'",
")",
":",
"if",
"(",
"len",
"(",
"pattern",
")",
"!=",
"len",
"(",
"schema",
")",
")",
":",
"return",
"0",
"for",
"pos",
"in",
"range",
"(",
"len",
"(",
"pattern",
")",
")",
":",
"if",
"(",
"(",
"schema",
"[",
"pos",
"]",
"!=",
"ambiguity_character",
")",
"and",
"(",
"pattern",
"[",
"pos",
"]",
"!=",
"ambiguity_character",
")",
"and",
"(",
"pattern",
"[",
"pos",
"]",
"!=",
"schema",
"[",
"pos",
"]",
")",
")",
":",
"return",
"0",
"return",
"1"
] | determine whether or not the given pattern matches the schema . | train | false |
20,723 | def compatibility_mode():
setattr(EventsCodes, 'ALL_EVENTS', ALL_EVENTS)
for evname in globals():
if evname.startswith('IN_'):
setattr(EventsCodes, evname, globals()[evname])
global COMPATIBILITY_MODE
COMPATIBILITY_MODE = True
| [
"def",
"compatibility_mode",
"(",
")",
":",
"setattr",
"(",
"EventsCodes",
",",
"'ALL_EVENTS'",
",",
"ALL_EVENTS",
")",
"for",
"evname",
"in",
"globals",
"(",
")",
":",
"if",
"evname",
".",
"startswith",
"(",
"'IN_'",
")",
":",
"setattr",
"(",
"EventsCodes",
",",
"evname",
",",
"globals",
"(",
")",
"[",
"evname",
"]",
")",
"global",
"COMPATIBILITY_MODE",
"COMPATIBILITY_MODE",
"=",
"True"
] | use this function to turn on the compatibility mode . | train | true |
20,724 | def _ValidateString(value, name='unused', max_len=_MAXIMUM_STRING_LENGTH, empty_ok=False, type_exception=TypeError, value_exception=ValueError):
if ((value is None) and empty_ok):
return
if ((value is not None) and (not isinstance(value, basestring))):
raise type_exception(('%s must be a basestring; got %s:' % (name, value.__class__.__name__)))
if ((not value) and (not empty_ok)):
raise value_exception(('%s must not be empty.' % name))
if (len(value.encode('utf-8')) > max_len):
raise value_exception(('%s must be under %d bytes.' % (name, max_len)))
return value
| [
"def",
"_ValidateString",
"(",
"value",
",",
"name",
"=",
"'unused'",
",",
"max_len",
"=",
"_MAXIMUM_STRING_LENGTH",
",",
"empty_ok",
"=",
"False",
",",
"type_exception",
"=",
"TypeError",
",",
"value_exception",
"=",
"ValueError",
")",
":",
"if",
"(",
"(",
"value",
"is",
"None",
")",
"and",
"empty_ok",
")",
":",
"return",
"if",
"(",
"(",
"value",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"value",
",",
"basestring",
")",
")",
")",
":",
"raise",
"type_exception",
"(",
"(",
"'%s must be a basestring; got %s:'",
"%",
"(",
"name",
",",
"value",
".",
"__class__",
".",
"__name__",
")",
")",
")",
"if",
"(",
"(",
"not",
"value",
")",
"and",
"(",
"not",
"empty_ok",
")",
")",
":",
"raise",
"value_exception",
"(",
"(",
"'%s must not be empty.'",
"%",
"name",
")",
")",
"if",
"(",
"len",
"(",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
")",
">",
"max_len",
")",
":",
"raise",
"value_exception",
"(",
"(",
"'%s must be under %d bytes.'",
"%",
"(",
"name",
",",
"max_len",
")",
")",
")",
"return",
"value"
] | raises an exception if value is not a valid string or a subclass thereof . | train | false |
20,725 | def use_astropy_helpers(**kwargs):
global BOOTSTRAPPER
config = BOOTSTRAPPER.config
config.update(**kwargs)
BOOTSTRAPPER = _Bootstrapper(**config)
BOOTSTRAPPER.run()
| [
"def",
"use_astropy_helpers",
"(",
"**",
"kwargs",
")",
":",
"global",
"BOOTSTRAPPER",
"config",
"=",
"BOOTSTRAPPER",
".",
"config",
"config",
".",
"update",
"(",
"**",
"kwargs",
")",
"BOOTSTRAPPER",
"=",
"_Bootstrapper",
"(",
"**",
"config",
")",
"BOOTSTRAPPER",
".",
"run",
"(",
")"
] | ensure that the astropy_helpers module is available and is importable . | train | true |
20,726 | def check_termination(dF, F, dx_norm, x_norm, ratio, ftol, xtol):
ftol_satisfied = ((dF < (ftol * F)) and (ratio > 0.25))
xtol_satisfied = (dx_norm < (xtol * (xtol + x_norm)))
if (ftol_satisfied and xtol_satisfied):
return 4
elif ftol_satisfied:
return 2
elif xtol_satisfied:
return 3
else:
return None
| [
"def",
"check_termination",
"(",
"dF",
",",
"F",
",",
"dx_norm",
",",
"x_norm",
",",
"ratio",
",",
"ftol",
",",
"xtol",
")",
":",
"ftol_satisfied",
"=",
"(",
"(",
"dF",
"<",
"(",
"ftol",
"*",
"F",
")",
")",
"and",
"(",
"ratio",
">",
"0.25",
")",
")",
"xtol_satisfied",
"=",
"(",
"dx_norm",
"<",
"(",
"xtol",
"*",
"(",
"xtol",
"+",
"x_norm",
")",
")",
")",
"if",
"(",
"ftol_satisfied",
"and",
"xtol_satisfied",
")",
":",
"return",
"4",
"elif",
"ftol_satisfied",
":",
"return",
"2",
"elif",
"xtol_satisfied",
":",
"return",
"3",
"else",
":",
"return",
"None"
] | check termination condition for nonlinear least squares . | train | false |
20,728 | @pytest.mark.network
def test_multiple_requirements_files(script, tmpdir):
(other_lib_name, other_lib_version) = ('anyjson', '0.3')
script.scratch_path.join('initools-req.txt').write((textwrap.dedent('\n -e %s@10#egg=INITools-dev\n -r %s-req.txt\n ') % (local_checkout('svn+http://svn.colorstudy.com/INITools/trunk', tmpdir.join('cache')), other_lib_name)))
script.scratch_path.join(('%s-req.txt' % other_lib_name)).write(('%s<=%s' % (other_lib_name, other_lib_version)))
result = script.pip('install', '-r', (script.scratch_path / 'initools-req.txt'))
assert result.files_created[(script.site_packages / other_lib_name)].dir
fn = ('%s-%s-py%s.egg-info' % (other_lib_name, other_lib_version, pyversion))
assert result.files_created[(script.site_packages / fn)].dir
assert (((script.venv / 'src') / 'initools') in result.files_created)
| [
"@",
"pytest",
".",
"mark",
".",
"network",
"def",
"test_multiple_requirements_files",
"(",
"script",
",",
"tmpdir",
")",
":",
"(",
"other_lib_name",
",",
"other_lib_version",
")",
"=",
"(",
"'anyjson'",
",",
"'0.3'",
")",
"script",
".",
"scratch_path",
".",
"join",
"(",
"'initools-req.txt'",
")",
".",
"write",
"(",
"(",
"textwrap",
".",
"dedent",
"(",
"'\\n -e %s@10#egg=INITools-dev\\n -r %s-req.txt\\n '",
")",
"%",
"(",
"local_checkout",
"(",
"'svn+http://svn.colorstudy.com/INITools/trunk'",
",",
"tmpdir",
".",
"join",
"(",
"'cache'",
")",
")",
",",
"other_lib_name",
")",
")",
")",
"script",
".",
"scratch_path",
".",
"join",
"(",
"(",
"'%s-req.txt'",
"%",
"other_lib_name",
")",
")",
".",
"write",
"(",
"(",
"'%s<=%s'",
"%",
"(",
"other_lib_name",
",",
"other_lib_version",
")",
")",
")",
"result",
"=",
"script",
".",
"pip",
"(",
"'install'",
",",
"'-r'",
",",
"(",
"script",
".",
"scratch_path",
"/",
"'initools-req.txt'",
")",
")",
"assert",
"result",
".",
"files_created",
"[",
"(",
"script",
".",
"site_packages",
"/",
"other_lib_name",
")",
"]",
".",
"dir",
"fn",
"=",
"(",
"'%s-%s-py%s.egg-info'",
"%",
"(",
"other_lib_name",
",",
"other_lib_version",
",",
"pyversion",
")",
")",
"assert",
"result",
".",
"files_created",
"[",
"(",
"script",
".",
"site_packages",
"/",
"fn",
")",
"]",
".",
"dir",
"assert",
"(",
"(",
"(",
"script",
".",
"venv",
"/",
"'src'",
")",
"/",
"'initools'",
")",
"in",
"result",
".",
"files_created",
")"
] | test installing from multiple nested requirements files . | train | false |
20,729 | def test_ee_sk_estimator():
check_estimator(EasyEnsemble)
| [
"def",
"test_ee_sk_estimator",
"(",
")",
":",
"check_estimator",
"(",
"EasyEnsemble",
")"
] | test the sklearn estimator compatibility . | train | false |
20,730 | def get_block_device():
cmd = 'lsblk -n -io KNAME -d -e 1,7,11 -l'
devs = __salt__['cmd.run'](cmd).splitlines()
return devs
| [
"def",
"get_block_device",
"(",
")",
":",
"cmd",
"=",
"'lsblk -n -io KNAME -d -e 1,7,11 -l'",
"devs",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"return",
"devs"
] | retrieve a list of disk devices . | train | false |
20,731 | def default_threadable_predictors():
predictors = {'bash': predict_shell, 'csh': predict_shell, 'clear': predict_false, 'cls': predict_false, 'cmd': predict_shell, 'ex': predict_false, 'fish': predict_shell, 'htop': predict_help_ver, 'ksh': predict_shell, 'less': predict_help_ver, 'man': predict_help_ver, 'more': predict_help_ver, 'mvim': predict_help_ver, 'mutt': predict_help_ver, 'nano': predict_help_ver, 'psql': predict_false, 'ranger': predict_help_ver, 'rview': predict_false, 'rvim': predict_false, 'scp': predict_false, 'sh': predict_shell, 'ssh': predict_false, 'startx': predict_false, 'sudo': predict_help_ver, 'tcsh': predict_shell, 'top': predict_help_ver, 'vi': predict_false, 'view': predict_false, 'vim': predict_false, 'vimpager': predict_help_ver, 'weechat': predict_help_ver, 'xo': predict_help_ver, 'xonsh': predict_shell, 'zsh': predict_shell}
return predictors
| [
"def",
"default_threadable_predictors",
"(",
")",
":",
"predictors",
"=",
"{",
"'bash'",
":",
"predict_shell",
",",
"'csh'",
":",
"predict_shell",
",",
"'clear'",
":",
"predict_false",
",",
"'cls'",
":",
"predict_false",
",",
"'cmd'",
":",
"predict_shell",
",",
"'ex'",
":",
"predict_false",
",",
"'fish'",
":",
"predict_shell",
",",
"'htop'",
":",
"predict_help_ver",
",",
"'ksh'",
":",
"predict_shell",
",",
"'less'",
":",
"predict_help_ver",
",",
"'man'",
":",
"predict_help_ver",
",",
"'more'",
":",
"predict_help_ver",
",",
"'mvim'",
":",
"predict_help_ver",
",",
"'mutt'",
":",
"predict_help_ver",
",",
"'nano'",
":",
"predict_help_ver",
",",
"'psql'",
":",
"predict_false",
",",
"'ranger'",
":",
"predict_help_ver",
",",
"'rview'",
":",
"predict_false",
",",
"'rvim'",
":",
"predict_false",
",",
"'scp'",
":",
"predict_false",
",",
"'sh'",
":",
"predict_shell",
",",
"'ssh'",
":",
"predict_false",
",",
"'startx'",
":",
"predict_false",
",",
"'sudo'",
":",
"predict_help_ver",
",",
"'tcsh'",
":",
"predict_shell",
",",
"'top'",
":",
"predict_help_ver",
",",
"'vi'",
":",
"predict_false",
",",
"'view'",
":",
"predict_false",
",",
"'vim'",
":",
"predict_false",
",",
"'vimpager'",
":",
"predict_help_ver",
",",
"'weechat'",
":",
"predict_help_ver",
",",
"'xo'",
":",
"predict_help_ver",
",",
"'xonsh'",
":",
"predict_shell",
",",
"'zsh'",
":",
"predict_shell",
"}",
"return",
"predictors"
] | generates a new defaultdict for known threadable predictors . | train | false |
20,732 | def adjustTimeDelay(lastQueryDuration, lowerStdLimit):
candidate = (1 + int(round(lowerStdLimit)))
if candidate:
kb.delayCandidates = ([candidate] + kb.delayCandidates[:(-1)])
if (all(((x == candidate) for x in kb.delayCandidates)) and (candidate < conf.timeSec)):
conf.timeSec = candidate
infoMsg = 'adjusting time delay to '
infoMsg += ('%d second%s due to good response times' % (conf.timeSec, ('s' if (conf.timeSec > 1) else '')))
logger.info(infoMsg)
| [
"def",
"adjustTimeDelay",
"(",
"lastQueryDuration",
",",
"lowerStdLimit",
")",
":",
"candidate",
"=",
"(",
"1",
"+",
"int",
"(",
"round",
"(",
"lowerStdLimit",
")",
")",
")",
"if",
"candidate",
":",
"kb",
".",
"delayCandidates",
"=",
"(",
"[",
"candidate",
"]",
"+",
"kb",
".",
"delayCandidates",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
"if",
"(",
"all",
"(",
"(",
"(",
"x",
"==",
"candidate",
")",
"for",
"x",
"in",
"kb",
".",
"delayCandidates",
")",
")",
"and",
"(",
"candidate",
"<",
"conf",
".",
"timeSec",
")",
")",
":",
"conf",
".",
"timeSec",
"=",
"candidate",
"infoMsg",
"=",
"'adjusting time delay to '",
"infoMsg",
"+=",
"(",
"'%d second%s due to good response times'",
"%",
"(",
"conf",
".",
"timeSec",
",",
"(",
"'s'",
"if",
"(",
"conf",
".",
"timeSec",
">",
"1",
")",
"else",
"''",
")",
")",
")",
"logger",
".",
"info",
"(",
"infoMsg",
")"
] | provides tip for adjusting time delay in time-based data retrieval . | train | false |
20,734 | @contextlib.contextmanager
def save_current_environment():
original_environ = os.environ.copy()
try:
(yield)
finally:
os.environ.clear()
os.environ.update(original_environ)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"save_current_environment",
"(",
")",
":",
"original_environ",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"try",
":",
"(",
"yield",
")",
"finally",
":",
"os",
".",
"environ",
".",
"clear",
"(",
")",
"os",
".",
"environ",
".",
"update",
"(",
"original_environ",
")"
] | context manager that saves os . | train | false |
20,735 | @contextmanager
def override_options(options):
from django.conf import settings
from sentry.options import default_manager
wrapped = default_manager.store.get
def new_get(key, **kwargs):
try:
return options[key.name]
except KeyError:
return wrapped(key, **kwargs)
new_options = settings.SENTRY_OPTIONS.copy()
new_options.update(options)
with override_settings(SENTRY_OPTIONS=new_options):
with patch.object(default_manager.store, 'get', side_effect=new_get):
(yield)
| [
"@",
"contextmanager",
"def",
"override_options",
"(",
"options",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"from",
"sentry",
".",
"options",
"import",
"default_manager",
"wrapped",
"=",
"default_manager",
".",
"store",
".",
"get",
"def",
"new_get",
"(",
"key",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"options",
"[",
"key",
".",
"name",
"]",
"except",
"KeyError",
":",
"return",
"wrapped",
"(",
"key",
",",
"**",
"kwargs",
")",
"new_options",
"=",
"settings",
".",
"SENTRY_OPTIONS",
".",
"copy",
"(",
")",
"new_options",
".",
"update",
"(",
"options",
")",
"with",
"override_settings",
"(",
"SENTRY_OPTIONS",
"=",
"new_options",
")",
":",
"with",
"patch",
".",
"object",
"(",
"default_manager",
".",
"store",
",",
"'get'",
",",
"side_effect",
"=",
"new_get",
")",
":",
"(",
"yield",
")"
] | a context manager for overriding specific configuration options . | train | false |
20,736 | def get_pgid(path, follow_symlinks=True):
if (not os.path.exists(path)):
return False
if (follow_symlinks and (sys.getwindowsversion().major >= 6)):
path = _resolve_symlink(path)
try:
secdesc = win32security.GetFileSecurity(path, win32security.GROUP_SECURITY_INFORMATION)
except MemoryError:
return 'S-1-1-0'
except pywinerror as exc:
if ((exc.winerror == 1) or (exc.winerror == 50)):
return 'S-1-1-0'
raise
group_sid = secdesc.GetSecurityDescriptorGroup()
return win32security.ConvertSidToStringSid(group_sid)
| [
"def",
"get_pgid",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"return",
"False",
"if",
"(",
"follow_symlinks",
"and",
"(",
"sys",
".",
"getwindowsversion",
"(",
")",
".",
"major",
">=",
"6",
")",
")",
":",
"path",
"=",
"_resolve_symlink",
"(",
"path",
")",
"try",
":",
"secdesc",
"=",
"win32security",
".",
"GetFileSecurity",
"(",
"path",
",",
"win32security",
".",
"GROUP_SECURITY_INFORMATION",
")",
"except",
"MemoryError",
":",
"return",
"'S-1-1-0'",
"except",
"pywinerror",
"as",
"exc",
":",
"if",
"(",
"(",
"exc",
".",
"winerror",
"==",
"1",
")",
"or",
"(",
"exc",
".",
"winerror",
"==",
"50",
")",
")",
":",
"return",
"'S-1-1-0'",
"raise",
"group_sid",
"=",
"secdesc",
".",
"GetSecurityDescriptorGroup",
"(",
")",
"return",
"win32security",
".",
"ConvertSidToStringSid",
"(",
"group_sid",
")"
] | return the id of the primary group that owns a given file this function will return the rarely used primary group of a file . | train | false |
20,737 | def getRotatedWiddershinsQuarterAroundZAxis(vector3):
return Vector3((- vector3.y), vector3.x, vector3.z)
| [
"def",
"getRotatedWiddershinsQuarterAroundZAxis",
"(",
"vector3",
")",
":",
"return",
"Vector3",
"(",
"(",
"-",
"vector3",
".",
"y",
")",
",",
"vector3",
".",
"x",
",",
"vector3",
".",
"z",
")"
] | get vector3 rotated a quarter widdershins turn around z axis . | train | false |
20,738 | def get_W(word_vecs, k=300):
vocab_size = len(word_vecs)
word_idx_map = dict()
W = np.zeros(shape=((vocab_size + 1), k), dtype='float32')
W[0] = np.zeros(k, dtype='float32')
i = 1
for word in word_vecs:
W[i] = word_vecs[word]
word_idx_map[word] = i
i += 1
return (W, word_idx_map)
| [
"def",
"get_W",
"(",
"word_vecs",
",",
"k",
"=",
"300",
")",
":",
"vocab_size",
"=",
"len",
"(",
"word_vecs",
")",
"word_idx_map",
"=",
"dict",
"(",
")",
"W",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"(",
"vocab_size",
"+",
"1",
")",
",",
"k",
")",
",",
"dtype",
"=",
"'float32'",
")",
"W",
"[",
"0",
"]",
"=",
"np",
".",
"zeros",
"(",
"k",
",",
"dtype",
"=",
"'float32'",
")",
"i",
"=",
"1",
"for",
"word",
"in",
"word_vecs",
":",
"W",
"[",
"i",
"]",
"=",
"word_vecs",
"[",
"word",
"]",
"word_idx_map",
"[",
"word",
"]",
"=",
"i",
"i",
"+=",
"1",
"return",
"(",
"W",
",",
"word_idx_map",
")"
] | get word matrix . | train | false |
20,739 | def max_api_window(user):
return _rules_for_user(user)[(-1)][0]
| [
"def",
"max_api_window",
"(",
"user",
")",
":",
"return",
"_rules_for_user",
"(",
"user",
")",
"[",
"(",
"-",
"1",
")",
"]",
"[",
"0",
"]"
] | returns the api time window for the highest limit . | train | false |
20,740 | def find_roots(path, file_sig='*.plug'):
roots = set()
for (root, dirnames, filenames) in os.walk(path, followlinks=True):
for filename in fnmatch.filter(filenames, file_sig):
dir_to_add = os.path.dirname(os.path.join(root, filename))
relative = os.path.relpath(os.path.realpath(dir_to_add), os.path.realpath(path))
for subelement in relative.split(os.path.sep):
if (subelement in ('.', '..')):
continue
if (subelement.startswith('.') or (subelement == '__pycache__')):
log.debug(('Ignore %s' % dir_to_add))
break
else:
roots.add(dir_to_add)
return roots
| [
"def",
"find_roots",
"(",
"path",
",",
"file_sig",
"=",
"'*.plug'",
")",
":",
"roots",
"=",
"set",
"(",
")",
"for",
"(",
"root",
",",
"dirnames",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"path",
",",
"followlinks",
"=",
"True",
")",
":",
"for",
"filename",
"in",
"fnmatch",
".",
"filter",
"(",
"filenames",
",",
"file_sig",
")",
":",
"dir_to_add",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
")",
"relative",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"dir_to_add",
")",
",",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
")",
"for",
"subelement",
"in",
"relative",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"if",
"(",
"subelement",
"in",
"(",
"'.'",
",",
"'..'",
")",
")",
":",
"continue",
"if",
"(",
"subelement",
".",
"startswith",
"(",
"'.'",
")",
"or",
"(",
"subelement",
"==",
"'__pycache__'",
")",
")",
":",
"log",
".",
"debug",
"(",
"(",
"'Ignore %s'",
"%",
"dir_to_add",
")",
")",
"break",
"else",
":",
"roots",
".",
"add",
"(",
"dir_to_add",
")",
"return",
"roots"
] | collects all the paths from path recursively that contains files of type file_sig . | train | false |
20,741 | @with_setup(prepare_stdout, registry.clear)
def test_jsonreport_output_with_unicode_and_bytestring():
with check_jsonreport(u'xunit_unicode_and_bytestring_mixing'):
runner = Runner(feature_name(u'xunit_unicode_and_bytestring_mixing'), enable_jsonreport=True)
runner.run()
| [
"@",
"with_setup",
"(",
"prepare_stdout",
",",
"registry",
".",
"clear",
")",
"def",
"test_jsonreport_output_with_unicode_and_bytestring",
"(",
")",
":",
"with",
"check_jsonreport",
"(",
"u'xunit_unicode_and_bytestring_mixing'",
")",
":",
"runner",
"=",
"Runner",
"(",
"feature_name",
"(",
"u'xunit_unicode_and_bytestring_mixing'",
")",
",",
"enable_jsonreport",
"=",
"True",
")",
"runner",
".",
"run",
"(",
")"
] | test jsonreport output with unicode and bytestring . | train | false |
20,743 | def make_pad_threshold_message(threshold1, threshold2, lower_channel_pressure_threshold, upper_channel_pressure_threshold):
args = (((to_7L5M(threshold1) + to_7L5M(threshold2)) + to_7L5M(lower_channel_pressure_threshold)) + to_7L5M(upper_channel_pressure_threshold))
return make_message(27, args)
| [
"def",
"make_pad_threshold_message",
"(",
"threshold1",
",",
"threshold2",
",",
"lower_channel_pressure_threshold",
",",
"upper_channel_pressure_threshold",
")",
":",
"args",
"=",
"(",
"(",
"(",
"to_7L5M",
"(",
"threshold1",
")",
"+",
"to_7L5M",
"(",
"threshold2",
")",
")",
"+",
"to_7L5M",
"(",
"lower_channel_pressure_threshold",
")",
")",
"+",
"to_7L5M",
"(",
"upper_channel_pressure_threshold",
")",
")",
"return",
"make_message",
"(",
"27",
",",
"args",
")"
] | these parameters determine the lower note threshold and the channel pressure thresholds of the pads . | train | false |
20,745 | def parallel_execute_iter(objects, func, get_deps):
if (get_deps is None):
get_deps = _no_deps
results = Queue()
state = State(objects)
while True:
feed_queue(objects, func, get_deps, results, state)
try:
event = results.get(timeout=0.1)
except Empty:
continue
except thread.error:
raise ShutdownException()
if (event is STOP):
break
(obj, _, exception) = event
if (exception is None):
log.debug(u'Finished processing: {}'.format(obj))
state.finished.add(obj)
else:
log.debug(u'Failed: {}'.format(obj))
state.failed.add(obj)
(yield event)
| [
"def",
"parallel_execute_iter",
"(",
"objects",
",",
"func",
",",
"get_deps",
")",
":",
"if",
"(",
"get_deps",
"is",
"None",
")",
":",
"get_deps",
"=",
"_no_deps",
"results",
"=",
"Queue",
"(",
")",
"state",
"=",
"State",
"(",
"objects",
")",
"while",
"True",
":",
"feed_queue",
"(",
"objects",
",",
"func",
",",
"get_deps",
",",
"results",
",",
"state",
")",
"try",
":",
"event",
"=",
"results",
".",
"get",
"(",
"timeout",
"=",
"0.1",
")",
"except",
"Empty",
":",
"continue",
"except",
"thread",
".",
"error",
":",
"raise",
"ShutdownException",
"(",
")",
"if",
"(",
"event",
"is",
"STOP",
")",
":",
"break",
"(",
"obj",
",",
"_",
",",
"exception",
")",
"=",
"event",
"if",
"(",
"exception",
"is",
"None",
")",
":",
"log",
".",
"debug",
"(",
"u'Finished processing: {}'",
".",
"format",
"(",
"obj",
")",
")",
"state",
".",
"finished",
".",
"add",
"(",
"obj",
")",
"else",
":",
"log",
".",
"debug",
"(",
"u'Failed: {}'",
".",
"format",
"(",
"obj",
")",
")",
"state",
".",
"failed",
".",
"add",
"(",
"obj",
")",
"(",
"yield",
"event",
")"
] | runs func on objects in parallel while ensuring that func is ran on object only after it is ran on all its dependencies . | train | false |
20,746 | def _validate_node_json(node_type, node_dict, errors, user, workflow):
assert isinstance(errors, dict), 'errors must be a dict.'
if (node_type in ACTION_TYPES):
form_class = design_form_by_type(node_type, user, workflow)
else:
form_class = NodeForm
form = form_class(data=node_dict)
if form.is_valid():
for field in form.fields:
errors[field] = []
return True
else:
for field in form.fields:
errors[field] = form[field].errors
return False
| [
"def",
"_validate_node_json",
"(",
"node_type",
",",
"node_dict",
",",
"errors",
",",
"user",
",",
"workflow",
")",
":",
"assert",
"isinstance",
"(",
"errors",
",",
"dict",
")",
",",
"'errors must be a dict.'",
"if",
"(",
"node_type",
"in",
"ACTION_TYPES",
")",
":",
"form_class",
"=",
"design_form_by_type",
"(",
"node_type",
",",
"user",
",",
"workflow",
")",
"else",
":",
"form_class",
"=",
"NodeForm",
"form",
"=",
"form_class",
"(",
"data",
"=",
"node_dict",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"for",
"field",
"in",
"form",
".",
"fields",
":",
"errors",
"[",
"field",
"]",
"=",
"[",
"]",
"return",
"True",
"else",
":",
"for",
"field",
"in",
"form",
".",
"fields",
":",
"errors",
"[",
"field",
"]",
"=",
"form",
"[",
"field",
"]",
".",
"errors",
"return",
"False"
] | validates a single node excluding links . | train | false |
20,747 | def has_environment_marker_support():
try:
return (pkg_resources.parse_version(setuptools.__version__) >= pkg_resources.parse_version('0.7.2'))
except Exception as exc:
sys.stderr.write(("Could not test setuptool's version: %s\n" % exc))
return False
| [
"def",
"has_environment_marker_support",
"(",
")",
":",
"try",
":",
"return",
"(",
"pkg_resources",
".",
"parse_version",
"(",
"setuptools",
".",
"__version__",
")",
">=",
"pkg_resources",
".",
"parse_version",
"(",
"'0.7.2'",
")",
")",
"except",
"Exception",
"as",
"exc",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"(",
"\"Could not test setuptool's version: %s\\n\"",
"%",
"exc",
")",
")",
"return",
"False"
] | tests that setuptools has support for pep-426 environment marker support . | train | false |
20,748 | def _lie_group_remove(coords):
if isinstance(coords, AppliedUndef):
return coords.args[0]
elif coords.is_Add:
subfunc = coords.atoms(AppliedUndef)
if subfunc:
for func in subfunc:
coords = coords.subs(func, 0)
return coords
elif coords.is_Pow:
(base, expr) = coords.as_base_exp()
base = _lie_group_remove(base)
expr = _lie_group_remove(expr)
return (base ** expr)
elif coords.is_Mul:
mulargs = []
coordargs = coords.args
for arg in coordargs:
if (not isinstance(coords, AppliedUndef)):
mulargs.append(_lie_group_remove(arg))
return Mul(*mulargs)
return coords
| [
"def",
"_lie_group_remove",
"(",
"coords",
")",
":",
"if",
"isinstance",
"(",
"coords",
",",
"AppliedUndef",
")",
":",
"return",
"coords",
".",
"args",
"[",
"0",
"]",
"elif",
"coords",
".",
"is_Add",
":",
"subfunc",
"=",
"coords",
".",
"atoms",
"(",
"AppliedUndef",
")",
"if",
"subfunc",
":",
"for",
"func",
"in",
"subfunc",
":",
"coords",
"=",
"coords",
".",
"subs",
"(",
"func",
",",
"0",
")",
"return",
"coords",
"elif",
"coords",
".",
"is_Pow",
":",
"(",
"base",
",",
"expr",
")",
"=",
"coords",
".",
"as_base_exp",
"(",
")",
"base",
"=",
"_lie_group_remove",
"(",
"base",
")",
"expr",
"=",
"_lie_group_remove",
"(",
"expr",
")",
"return",
"(",
"base",
"**",
"expr",
")",
"elif",
"coords",
".",
"is_Mul",
":",
"mulargs",
"=",
"[",
"]",
"coordargs",
"=",
"coords",
".",
"args",
"for",
"arg",
"in",
"coordargs",
":",
"if",
"(",
"not",
"isinstance",
"(",
"coords",
",",
"AppliedUndef",
")",
")",
":",
"mulargs",
".",
"append",
"(",
"_lie_group_remove",
"(",
"arg",
")",
")",
"return",
"Mul",
"(",
"*",
"mulargs",
")",
"return",
"coords"
] | this function is strictly meant for internal use by the lie group ode solving method . | train | false |
20,749 | def agent_auth(transport, username):
agent = paramiko.Agent()
agent_keys = agent.get_keys()
if (len(agent_keys) == 0):
return
for key in agent_keys:
print ('Trying ssh-agent key %s' % hexlify(key.get_fingerprint()))
try:
transport.auth_publickey(username, key)
print '... success!'
return
except paramiko.SSHException:
print '... nope.'
| [
"def",
"agent_auth",
"(",
"transport",
",",
"username",
")",
":",
"agent",
"=",
"paramiko",
".",
"Agent",
"(",
")",
"agent_keys",
"=",
"agent",
".",
"get_keys",
"(",
")",
"if",
"(",
"len",
"(",
"agent_keys",
")",
"==",
"0",
")",
":",
"return",
"for",
"key",
"in",
"agent_keys",
":",
"print",
"(",
"'Trying ssh-agent key %s'",
"%",
"hexlify",
"(",
"key",
".",
"get_fingerprint",
"(",
")",
")",
")",
"try",
":",
"transport",
".",
"auth_publickey",
"(",
"username",
",",
"key",
")",
"print",
"'... success!'",
"return",
"except",
"paramiko",
".",
"SSHException",
":",
"print",
"'... nope.'"
] | attempt to authenticate to the given transport using any of the private keys available from an ssh agent . | train | true |
20,750 | def create_alias(FunctionName, Name, FunctionVersion, Description='', region=None, key=None, keyid=None, profile=None):
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
alias = conn.create_alias(FunctionName=FunctionName, Name=Name, FunctionVersion=FunctionVersion, Description=Description)
if alias:
log.info('The newly created alias name is {0}'.format(alias['Name']))
return {'created': True, 'name': alias['Name']}
else:
log.warning('Alias was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': salt.utils.boto3.get_error(e)}
| [
"def",
"create_alias",
"(",
"FunctionName",
",",
"Name",
",",
"FunctionVersion",
",",
"Description",
"=",
"''",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"alias",
"=",
"conn",
".",
"create_alias",
"(",
"FunctionName",
"=",
"FunctionName",
",",
"Name",
"=",
"Name",
",",
"FunctionVersion",
"=",
"FunctionVersion",
",",
"Description",
"=",
"Description",
")",
"if",
"alias",
":",
"log",
".",
"info",
"(",
"'The newly created alias name is {0}'",
".",
"format",
"(",
"alias",
"[",
"'Name'",
"]",
")",
")",
"return",
"{",
"'created'",
":",
"True",
",",
"'name'",
":",
"alias",
"[",
"'Name'",
"]",
"}",
"else",
":",
"log",
".",
"warning",
"(",
"'Alias was not created'",
")",
"return",
"{",
"'created'",
":",
"False",
"}",
"except",
"ClientError",
"as",
"e",
":",
"return",
"{",
"'created'",
":",
"False",
",",
"'error'",
":",
"salt",
".",
"utils",
".",
"boto3",
".",
"get_error",
"(",
"e",
")",
"}"
] | create a display name for a key . | train | false |
20,751 | def distros_for_location(location, basename, metadata=None):
if basename.endswith('.egg.zip'):
basename = basename[:(-4)]
if (basename.endswith('.egg') and ('-' in basename)):
return [Distribution.from_location(location, basename, metadata)]
if basename.endswith('.exe'):
(win_base, py_ver) = parse_bdist_wininst(basename)
if (win_base is not None):
return interpret_distro_name(location, win_base, metadata, py_ver, BINARY_DIST, 'win32')
for ext in EXTENSIONS:
if basename.endswith(ext):
basename = basename[:(- len(ext))]
return interpret_distro_name(location, basename, metadata)
return []
| [
"def",
"distros_for_location",
"(",
"location",
",",
"basename",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"basename",
".",
"endswith",
"(",
"'.egg.zip'",
")",
":",
"basename",
"=",
"basename",
"[",
":",
"(",
"-",
"4",
")",
"]",
"if",
"(",
"basename",
".",
"endswith",
"(",
"'.egg'",
")",
"and",
"(",
"'-'",
"in",
"basename",
")",
")",
":",
"return",
"[",
"Distribution",
".",
"from_location",
"(",
"location",
",",
"basename",
",",
"metadata",
")",
"]",
"if",
"basename",
".",
"endswith",
"(",
"'.exe'",
")",
":",
"(",
"win_base",
",",
"py_ver",
")",
"=",
"parse_bdist_wininst",
"(",
"basename",
")",
"if",
"(",
"win_base",
"is",
"not",
"None",
")",
":",
"return",
"interpret_distro_name",
"(",
"location",
",",
"win_base",
",",
"metadata",
",",
"py_ver",
",",
"BINARY_DIST",
",",
"'win32'",
")",
"for",
"ext",
"in",
"EXTENSIONS",
":",
"if",
"basename",
".",
"endswith",
"(",
"ext",
")",
":",
"basename",
"=",
"basename",
"[",
":",
"(",
"-",
"len",
"(",
"ext",
")",
")",
"]",
"return",
"interpret_distro_name",
"(",
"location",
",",
"basename",
",",
"metadata",
")",
"return",
"[",
"]"
] | yield egg or source distribution objects based on basename . | train | true |
20,753 | @pytest.mark.django_db
def test_empty_plural_target(af_tutorial_po):
db_unit = _update_translation(af_tutorial_po, 2, {'target': [u'samaka']})
store_unit = af_tutorial_po.file.store.findid(db_unit.getid())
assert (len(store_unit.target.strings) == 2)
db_unit = _update_translation(af_tutorial_po, 2, {'target': u''})
assert (len(store_unit.target.strings) == 2)
| [
"@",
"pytest",
".",
"mark",
".",
"django_db",
"def",
"test_empty_plural_target",
"(",
"af_tutorial_po",
")",
":",
"db_unit",
"=",
"_update_translation",
"(",
"af_tutorial_po",
",",
"2",
",",
"{",
"'target'",
":",
"[",
"u'samaka'",
"]",
"}",
")",
"store_unit",
"=",
"af_tutorial_po",
".",
"file",
".",
"store",
".",
"findid",
"(",
"db_unit",
".",
"getid",
"(",
")",
")",
"assert",
"(",
"len",
"(",
"store_unit",
".",
"target",
".",
"strings",
")",
"==",
"2",
")",
"db_unit",
"=",
"_update_translation",
"(",
"af_tutorial_po",
",",
"2",
",",
"{",
"'target'",
":",
"u''",
"}",
")",
"assert",
"(",
"len",
"(",
"store_unit",
".",
"target",
".",
"strings",
")",
"==",
"2",
")"
] | tests empty plural targets are not deleted . | train | false |
20,754 | def test_syntax_error_for_scenarios_with_no_name():
expect(Feature.from_string).when.called_with(FEATURE20).to.throw(LettuceSyntaxError, 'In the feature "My scenarios have no name", scenarios must have a name, make sure to declare a scenario like this: `Scenario: name of your scenario`')
| [
"def",
"test_syntax_error_for_scenarios_with_no_name",
"(",
")",
":",
"expect",
"(",
"Feature",
".",
"from_string",
")",
".",
"when",
".",
"called_with",
"(",
"FEATURE20",
")",
".",
"to",
".",
"throw",
"(",
"LettuceSyntaxError",
",",
"'In the feature \"My scenarios have no name\", scenarios must have a name, make sure to declare a scenario like this: `Scenario: name of your scenario`'",
")"
] | trying to parse features with unnamed scenarios will cause a syntax error . | train | false |
20,755 | def _inflate_fox_h(g, a):
if (a < 0):
return _inflate_fox_h(_flip_g(g), (- a))
p = S(a.p)
q = S(a.q)
(D, g) = _inflate_g(g, q)
z = g.argument
D /= (((2 * pi) ** ((1 - p) / 2)) * (p ** ((- S(1)) / 2)))
z /= (p ** p)
bs = [((n + 1) / p) for n in range(p)]
return (D, meijerg(g.an, g.aother, g.bm, (list(g.bother) + bs), z))
| [
"def",
"_inflate_fox_h",
"(",
"g",
",",
"a",
")",
":",
"if",
"(",
"a",
"<",
"0",
")",
":",
"return",
"_inflate_fox_h",
"(",
"_flip_g",
"(",
"g",
")",
",",
"(",
"-",
"a",
")",
")",
"p",
"=",
"S",
"(",
"a",
".",
"p",
")",
"q",
"=",
"S",
"(",
"a",
".",
"q",
")",
"(",
"D",
",",
"g",
")",
"=",
"_inflate_g",
"(",
"g",
",",
"q",
")",
"z",
"=",
"g",
".",
"argument",
"D",
"/=",
"(",
"(",
"(",
"2",
"*",
"pi",
")",
"**",
"(",
"(",
"1",
"-",
"p",
")",
"/",
"2",
")",
")",
"*",
"(",
"p",
"**",
"(",
"(",
"-",
"S",
"(",
"1",
")",
")",
"/",
"2",
")",
")",
")",
"z",
"/=",
"(",
"p",
"**",
"p",
")",
"bs",
"=",
"[",
"(",
"(",
"n",
"+",
"1",
")",
"/",
"p",
")",
"for",
"n",
"in",
"range",
"(",
"p",
")",
"]",
"return",
"(",
"D",
",",
"meijerg",
"(",
"g",
".",
"an",
",",
"g",
".",
"aother",
",",
"g",
".",
"bm",
",",
"(",
"list",
"(",
"g",
".",
"bother",
")",
"+",
"bs",
")",
",",
"z",
")",
")"
] | let d denote the integrand in the definition of the g function g . | train | false |
20,756 | def test_parent():
parent = Parent()
t = usertypes.Timer(parent)
assert (t.parent() is parent)
| [
"def",
"test_parent",
"(",
")",
":",
"parent",
"=",
"Parent",
"(",
")",
"t",
"=",
"usertypes",
".",
"Timer",
"(",
"parent",
")",
"assert",
"(",
"t",
".",
"parent",
"(",
")",
"is",
"parent",
")"
] | make sure the parent is set correctly . | train | false |
20,757 | def assert_not_in_html(member, container, **kwargs):
member = markupsafe.escape(member)
return assert_not_in(member, container, **kwargs)
| [
"def",
"assert_not_in_html",
"(",
"member",
",",
"container",
",",
"**",
"kwargs",
")",
":",
"member",
"=",
"markupsafe",
".",
"escape",
"(",
"member",
")",
"return",
"assert_not_in",
"(",
"member",
",",
"container",
",",
"**",
"kwargs",
")"
] | looks for the specified member in markupsafe-escaped html output . | train | false |
20,758 | def logonUser(loginString):
(domain, user, passwd) = loginString.split('\n')
return win32security.LogonUser(user, domain, passwd, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT)
| [
"def",
"logonUser",
"(",
"loginString",
")",
":",
"(",
"domain",
",",
"user",
",",
"passwd",
")",
"=",
"loginString",
".",
"split",
"(",
"'\\n'",
")",
"return",
"win32security",
".",
"LogonUser",
"(",
"user",
",",
"domain",
",",
"passwd",
",",
"win32con",
".",
"LOGON32_LOGON_INTERACTIVE",
",",
"win32con",
".",
"LOGON32_PROVIDER_DEFAULT",
")"
] | login as specified user and return handle . | train | false |
20,759 | def do_terminate_threads(whitelist=list()):
for t in threading.enumerate():
if (not isinstance(t, TerminatableThread)):
continue
if (whitelist and (t not in whitelist)):
continue
t.schedule_termination()
t.stop_and_join()
| [
"def",
"do_terminate_threads",
"(",
"whitelist",
"=",
"list",
"(",
")",
")",
":",
"for",
"t",
"in",
"threading",
".",
"enumerate",
"(",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"t",
",",
"TerminatableThread",
")",
")",
":",
"continue",
"if",
"(",
"whitelist",
"and",
"(",
"t",
"not",
"in",
"whitelist",
")",
")",
":",
"continue",
"t",
".",
"schedule_termination",
"(",
")",
"t",
".",
"stop_and_join",
"(",
")"
] | simple function which terminates all of our threads . | train | false |
20,760 | @memoize_default(None, evaluator_is_first_arg=True)
def find_return_types(evaluator, func):
def search_return_in_docstr(docstr):
for p in DOCSTRING_RETURN_PATTERNS:
match = p.search(docstr)
if match:
return [_strip_rst_role(match.group(1))]
found = []
if (not found):
found = _search_return_in_numpydocstr(docstr)
return found
docstr = func.raw_doc
module = func.get_parent_until()
types = []
for type_str in search_return_in_docstr(docstr):
type_ = _evaluate_for_statement_string(evaluator, type_str, module)
types.extend(type_)
debug.dbg('DOC!!!!!!!!!!!!!! wow types?: %s in %s', types, func)
return types
| [
"@",
"memoize_default",
"(",
"None",
",",
"evaluator_is_first_arg",
"=",
"True",
")",
"def",
"find_return_types",
"(",
"evaluator",
",",
"func",
")",
":",
"def",
"search_return_in_docstr",
"(",
"docstr",
")",
":",
"for",
"p",
"in",
"DOCSTRING_RETURN_PATTERNS",
":",
"match",
"=",
"p",
".",
"search",
"(",
"docstr",
")",
"if",
"match",
":",
"return",
"[",
"_strip_rst_role",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"]",
"found",
"=",
"[",
"]",
"if",
"(",
"not",
"found",
")",
":",
"found",
"=",
"_search_return_in_numpydocstr",
"(",
"docstr",
")",
"return",
"found",
"docstr",
"=",
"func",
".",
"raw_doc",
"module",
"=",
"func",
".",
"get_parent_until",
"(",
")",
"types",
"=",
"[",
"]",
"for",
"type_str",
"in",
"search_return_in_docstr",
"(",
"docstr",
")",
":",
"type_",
"=",
"_evaluate_for_statement_string",
"(",
"evaluator",
",",
"type_str",
",",
"module",
")",
"types",
".",
"extend",
"(",
"type_",
")",
"debug",
".",
"dbg",
"(",
"'DOC!!!!!!!!!!!!!! wow types?: %s in %s'",
",",
"types",
",",
"func",
")",
"return",
"types"
] | determines a set of potential return types for func using docstring hints :type evaluator: jedi . | train | false |
20,763 | def hyper_algorithm(f, x, k, order=4):
g = Function('g')
des = []
sol = None
for (DE, i) in simpleDE(f, x, g, order):
if (DE is not None):
sol = solve_de(f, x, DE, i, g, k)
if sol:
return sol
if (not DE.free_symbols.difference({x})):
des.append(DE)
for DE in des:
sol = _solve_simple(f, x, DE, g, k)
if sol:
return sol
| [
"def",
"hyper_algorithm",
"(",
"f",
",",
"x",
",",
"k",
",",
"order",
"=",
"4",
")",
":",
"g",
"=",
"Function",
"(",
"'g'",
")",
"des",
"=",
"[",
"]",
"sol",
"=",
"None",
"for",
"(",
"DE",
",",
"i",
")",
"in",
"simpleDE",
"(",
"f",
",",
"x",
",",
"g",
",",
"order",
")",
":",
"if",
"(",
"DE",
"is",
"not",
"None",
")",
":",
"sol",
"=",
"solve_de",
"(",
"f",
",",
"x",
",",
"DE",
",",
"i",
",",
"g",
",",
"k",
")",
"if",
"sol",
":",
"return",
"sol",
"if",
"(",
"not",
"DE",
".",
"free_symbols",
".",
"difference",
"(",
"{",
"x",
"}",
")",
")",
":",
"des",
".",
"append",
"(",
"DE",
")",
"for",
"DE",
"in",
"des",
":",
"sol",
"=",
"_solve_simple",
"(",
"f",
",",
"x",
",",
"DE",
",",
"g",
",",
"k",
")",
"if",
"sol",
":",
"return",
"sol"
] | hypergeometric algorithm for computing formal power series . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.