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
23,903
def _get_config_fname(): directory = _get_vispy_app_dir() if (directory is None): return None fname = op.join(directory, 'vispy.json') if (os.environ.get('_VISPY_CONFIG_TESTING', None) is not None): fname = op.join(_TempDir(), 'vispy.json') return fname
[ "def", "_get_config_fname", "(", ")", ":", "directory", "=", "_get_vispy_app_dir", "(", ")", "if", "(", "directory", "is", "None", ")", ":", "return", "None", "fname", "=", "op", ".", "join", "(", "directory", ",", "'vispy.json'", ")", "if", "(", "os", ".", "environ", ".", "get", "(", "'_VISPY_CONFIG_TESTING'", ",", "None", ")", "is", "not", "None", ")", ":", "fname", "=", "op", ".", "join", "(", "_TempDir", "(", ")", ",", "'vispy.json'", ")", "return", "fname" ]
helper for the vispy config file .
train
true
23,904
@register_canonicalize @gof.local_optimizer([Elemwise]) def local_useless_composite(node): if ((not isinstance(node.op, Elemwise)) or (not isinstance(node.op.scalar_op, scalar.Composite))): return comp = node.op.scalar_op idx = [i for (i, o_extern) in enumerate(node.outputs) if o_extern.clients] if (len(idx) < len(node.outputs)): new_outputs = [comp.outputs[i] for i in idx] c = scalar.Composite(inputs=comp.inputs, outputs=new_outputs) e = Elemwise(scalar_op=c)(return_list=True, *node.inputs) return dict(zip([node.outputs[i] for i in idx], e))
[ "@", "register_canonicalize", "@", "gof", ".", "local_optimizer", "(", "[", "Elemwise", "]", ")", "def", "local_useless_composite", "(", "node", ")", ":", "if", "(", "(", "not", "isinstance", "(", "node", ".", "op", ",", "Elemwise", ")", ")", "or", "(", "not", "isinstance", "(", "node", ".", "op", ".", "scalar_op", ",", "scalar", ".", "Composite", ")", ")", ")", ":", "return", "comp", "=", "node", ".", "op", ".", "scalar_op", "idx", "=", "[", "i", "for", "(", "i", ",", "o_extern", ")", "in", "enumerate", "(", "node", ".", "outputs", ")", "if", "o_extern", ".", "clients", "]", "if", "(", "len", "(", "idx", ")", "<", "len", "(", "node", ".", "outputs", ")", ")", ":", "new_outputs", "=", "[", "comp", ".", "outputs", "[", "i", "]", "for", "i", "in", "idx", "]", "c", "=", "scalar", ".", "Composite", "(", "inputs", "=", "comp", ".", "inputs", ",", "outputs", "=", "new_outputs", ")", "e", "=", "Elemwise", "(", "scalar_op", "=", "c", ")", "(", "return_list", "=", "True", ",", "*", "node", ".", "inputs", ")", "return", "dict", "(", "zip", "(", "[", "node", ".", "outputs", "[", "i", "]", "for", "i", "in", "idx", "]", ",", "e", ")", ")" ]
for elemwise composite that have multiple outputs .
train
false
23,907
def pre_hook(config): cmd = config.pre_hook if (cmd and (cmd not in pre_hook.already)): logger.info('Running pre-hook command: %s', cmd) _run_hook(cmd) pre_hook.already.add(cmd) elif cmd: logger.info('Pre-hook command already run, skipping: %s', cmd)
[ "def", "pre_hook", "(", "config", ")", ":", "cmd", "=", "config", ".", "pre_hook", "if", "(", "cmd", "and", "(", "cmd", "not", "in", "pre_hook", ".", "already", ")", ")", ":", "logger", ".", "info", "(", "'Running pre-hook command: %s'", ",", "cmd", ")", "_run_hook", "(", "cmd", ")", "pre_hook", ".", "already", ".", "add", "(", "cmd", ")", "elif", "cmd", ":", "logger", ".", "info", "(", "'Pre-hook command already run, skipping: %s'", ",", "cmd", ")" ]
run pre-hook if its defined and hasnt been run .
train
false
23,908
def stop_service(service_name): os_cmd = ['/usr/bin/openstack-service', 'stop', service_name] return (__salt__['cmd.retcode'](os_cmd) == 0)
[ "def", "stop_service", "(", "service_name", ")", ":", "os_cmd", "=", "[", "'/usr/bin/openstack-service'", ",", "'stop'", ",", "service_name", "]", "return", "(", "__salt__", "[", "'cmd.retcode'", "]", "(", "os_cmd", ")", "==", "0", ")" ]
stop openstack service immediately cli example: .
train
false
23,909
@register_opt() @local_optimizer([GpuFromHost]) def local_gpu_elemwise_1(node): if isinstance(node.op, GpuFromHost): (host_i,) = node.inputs if (host_i.owner and isinstance(host_i.owner.op, tensor.Elemwise) and (len(host_i.owner.outputs) == 1) and (len(host_i.clients) == 1) and dtype_in_elemwise_supported(node.op)): elemwise_node = host_i.owner if isinstance(elemwise_node.op.scalar_op, Erfinv): new_op = GpuElemwise(erfinv_gpu) elif isinstance(elemwise_node.op.scalar_op, Erfcx): new_op = GpuElemwise(erfcx_gpu) else: try: new_op = GpuElemwise(elemwise_node.op.scalar_op) except SupportCodeError: return False if all([(i.dtype == 'float32') for i in elemwise_node.inputs]): gpu_elemwise = new_op(*[as_cuda_ndarray_variable(i) for i in elemwise_node.inputs]) gpu_elemwise = split_huge_add_or_mul(gpu_elemwise.owner) if (not gpu_elemwise): return False return [gpu_elemwise.outputs[0]] return False
[ "@", "register_opt", "(", ")", "@", "local_optimizer", "(", "[", "GpuFromHost", "]", ")", "def", "local_gpu_elemwise_1", "(", "node", ")", ":", "if", "isinstance", "(", "node", ".", "op", ",", "GpuFromHost", ")", ":", "(", "host_i", ",", ")", "=", "node", ".", "inputs", "if", "(", "host_i", ".", "owner", "and", "isinstance", "(", "host_i", ".", "owner", ".", "op", ",", "tensor", ".", "Elemwise", ")", "and", "(", "len", "(", "host_i", ".", "owner", ".", "outputs", ")", "==", "1", ")", "and", "(", "len", "(", "host_i", ".", "clients", ")", "==", "1", ")", "and", "dtype_in_elemwise_supported", "(", "node", ".", "op", ")", ")", ":", "elemwise_node", "=", "host_i", ".", "owner", "if", "isinstance", "(", "elemwise_node", ".", "op", ".", "scalar_op", ",", "Erfinv", ")", ":", "new_op", "=", "GpuElemwise", "(", "erfinv_gpu", ")", "elif", "isinstance", "(", "elemwise_node", ".", "op", ".", "scalar_op", ",", "Erfcx", ")", ":", "new_op", "=", "GpuElemwise", "(", "erfcx_gpu", ")", "else", ":", "try", ":", "new_op", "=", "GpuElemwise", "(", "elemwise_node", ".", "op", ".", "scalar_op", ")", "except", "SupportCodeError", ":", "return", "False", "if", "all", "(", "[", "(", "i", ".", "dtype", "==", "'float32'", ")", "for", "i", "in", "elemwise_node", ".", "inputs", "]", ")", ":", "gpu_elemwise", "=", "new_op", "(", "*", "[", "as_cuda_ndarray_variable", "(", "i", ")", "for", "i", "in", "elemwise_node", ".", "inputs", "]", ")", "gpu_elemwise", "=", "split_huge_add_or_mul", "(", "gpu_elemwise", ".", "owner", ")", "if", "(", "not", "gpu_elemwise", ")", ":", "return", "False", "return", "[", "gpu_elemwise", ".", "outputs", "[", "0", "]", "]", "return", "False" ]
gpu_from_host) -> gpuelemwise(gpu_from_host) .
train
false
23,910
@pytest.fixture() def _temp_analyze_files(tmpdir): orig_img = tmpdir.join(u'orig.img') orig_hdr = tmpdir.join(u'orig.hdr') orig_img.open(u'w+').close() orig_hdr.open(u'w+').close() return (str(orig_img), str(orig_hdr))
[ "@", "pytest", ".", "fixture", "(", ")", "def", "_temp_analyze_files", "(", "tmpdir", ")", ":", "orig_img", "=", "tmpdir", ".", "join", "(", "u'orig.img'", ")", "orig_hdr", "=", "tmpdir", ".", "join", "(", "u'orig.hdr'", ")", "orig_img", ".", "open", "(", "u'w+'", ")", ".", "close", "(", ")", "orig_hdr", ".", "open", "(", "u'w+'", ")", ".", "close", "(", ")", "return", "(", "str", "(", "orig_img", ")", ",", "str", "(", "orig_hdr", ")", ")" ]
generate temporary analyze file pair .
train
false
23,911
def containsAny(str, set): return (1 in [(c in str) for c in set])
[ "def", "containsAny", "(", "str", ",", "set", ")", ":", "return", "(", "1", "in", "[", "(", "c", "in", "str", ")", "for", "c", "in", "set", "]", ")" ]
check whether str contains any of the chars in set .
train
false
23,913
@statfunc def quantiles(x, qlist=(2.5, 25, 50, 75, 97.5), transform=(lambda x: x)): x = transform(x.copy()) if (x.ndim > 1): sx = np.sort(x.T).T else: sx = np.sort(x) try: quants = [sx[int(((len(sx) * q) / 100.0))] for q in qlist] return dict(zip(qlist, quants)) except IndexError: _log.warning('Too few elements for quantile calculation')
[ "@", "statfunc", "def", "quantiles", "(", "x", ",", "qlist", "=", "(", "2.5", ",", "25", ",", "50", ",", "75", ",", "97.5", ")", ",", "transform", "=", "(", "lambda", "x", ":", "x", ")", ")", ":", "x", "=", "transform", "(", "x", ".", "copy", "(", ")", ")", "if", "(", "x", ".", "ndim", ">", "1", ")", ":", "sx", "=", "np", ".", "sort", "(", "x", ".", "T", ")", ".", "T", "else", ":", "sx", "=", "np", ".", "sort", "(", "x", ")", "try", ":", "quants", "=", "[", "sx", "[", "int", "(", "(", "(", "len", "(", "sx", ")", "*", "q", ")", "/", "100.0", ")", ")", "]", "for", "q", "in", "qlist", "]", "return", "dict", "(", "zip", "(", "qlist", ",", "quants", ")", ")", "except", "IndexError", ":", "_log", ".", "warning", "(", "'Too few elements for quantile calculation'", ")" ]
compute rowwise array quantiles on an input .
train
false
23,915
def check_hms_ranges(h, m, s): _check_hour_range(h) _check_minute_range(m) _check_second_range(s) return None
[ "def", "check_hms_ranges", "(", "h", ",", "m", ",", "s", ")", ":", "_check_hour_range", "(", "h", ")", "_check_minute_range", "(", "m", ")", "_check_second_range", "(", "s", ")", "return", "None" ]
checks that the given hour .
train
false
23,916
def _get_blob_file_index_key_name(creation_handle): if (len(creation_handle) < _DATASTORE_MAX_PROPERTY_SIZE): return creation_handle return hashlib.sha512(creation_handle).hexdigest()
[ "def", "_get_blob_file_index_key_name", "(", "creation_handle", ")", ":", "if", "(", "len", "(", "creation_handle", ")", "<", "_DATASTORE_MAX_PROPERTY_SIZE", ")", ":", "return", "creation_handle", "return", "hashlib", ".", "sha512", "(", "creation_handle", ")", ".", "hexdigest", "(", ")" ]
get key name for a __blobfileindex__ entity .
train
false
23,917
def avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True): return _functions.thnn.AvgPool2d(kernel_size, stride, padding, ceil_mode, count_include_pad)(input)
[ "def", "avg_pool2d", "(", "input", ",", "kernel_size", ",", "stride", "=", "None", ",", "padding", "=", "0", ",", "ceil_mode", "=", "False", ",", "count_include_pad", "=", "True", ")", ":", "return", "_functions", ".", "thnn", ".", "AvgPool2d", "(", "kernel_size", ",", "stride", ",", "padding", ",", "ceil_mode", ",", "count_include_pad", ")", "(", "input", ")" ]
applies 2d average-pooling operation in kh x kw regions by step size dh x dw steps .
train
false
23,918
def bayes_mvs(data, alpha=0.9): (m, v, s) = mvsdist(data) if ((alpha >= 1) or (alpha <= 0)): raise ValueError(('0 < alpha < 1 is required, but alpha=%s was given.' % alpha)) m_res = Mean(m.mean(), m.interval(alpha)) v_res = Variance(v.mean(), v.interval(alpha)) s_res = Std_dev(s.mean(), s.interval(alpha)) return (m_res, v_res, s_res)
[ "def", "bayes_mvs", "(", "data", ",", "alpha", "=", "0.9", ")", ":", "(", "m", ",", "v", ",", "s", ")", "=", "mvsdist", "(", "data", ")", "if", "(", "(", "alpha", ">=", "1", ")", "or", "(", "alpha", "<=", "0", ")", ")", ":", "raise", "ValueError", "(", "(", "'0 < alpha < 1 is required, but alpha=%s was given.'", "%", "alpha", ")", ")", "m_res", "=", "Mean", "(", "m", ".", "mean", "(", ")", ",", "m", ".", "interval", "(", "alpha", ")", ")", "v_res", "=", "Variance", "(", "v", ".", "mean", "(", ")", ",", "v", ".", "interval", "(", "alpha", ")", ")", "s_res", "=", "Std_dev", "(", "s", ".", "mean", "(", ")", ",", "s", ".", "interval", "(", "alpha", ")", ")", "return", "(", "m_res", ",", "v_res", ",", "s_res", ")" ]
bayesian confidence intervals for the mean .
train
false
23,919
def filter_insignificant(chunk, tag_suffixes=('DT', 'CC', 'PRP$', 'PRP')): good = [] for (word, tag) in chunk: ok = True for suffix in tag_suffixes: if tag.endswith(suffix): ok = False break if ok: good.append((word, tag)) return good
[ "def", "filter_insignificant", "(", "chunk", ",", "tag_suffixes", "=", "(", "'DT'", ",", "'CC'", ",", "'PRP$'", ",", "'PRP'", ")", ")", ":", "good", "=", "[", "]", "for", "(", "word", ",", "tag", ")", "in", "chunk", ":", "ok", "=", "True", "for", "suffix", "in", "tag_suffixes", ":", "if", "tag", ".", "endswith", "(", "suffix", ")", ":", "ok", "=", "False", "break", "if", "ok", ":", "good", ".", "append", "(", "(", "word", ",", "tag", ")", ")", "return", "good" ]
filter out insignificant tuples from a chunk of text .
train
false
23,921
@builtin(u'Title-case text (ignore tags)', titlecase, apply_func_to_html_text) def replace_titlecase_ignore_tags(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs): return apply_func_to_html_text(match, titlecase)
[ "@", "builtin", "(", "u'Title-case text (ignore tags)'", ",", "titlecase", ",", "apply_func_to_html_text", ")", "def", "replace_titlecase_ignore_tags", "(", "match", ",", "number", ",", "file_name", ",", "metadata", ",", "dictionaries", ",", "data", ",", "functions", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "apply_func_to_html_text", "(", "match", ",", "titlecase", ")" ]
title-case matched text .
train
false
23,923
def signal_number_to_name(signum): signal_to_name_map = dict(((k, v) for (v, k) in six.iteritems(signal.__dict__) if v.startswith(u'SIG'))) return signal_to_name_map.get(signum, u'UNKNOWN')
[ "def", "signal_number_to_name", "(", "signum", ")", ":", "signal_to_name_map", "=", "dict", "(", "(", "(", "k", ",", "v", ")", "for", "(", "v", ",", "k", ")", "in", "six", ".", "iteritems", "(", "signal", ".", "__dict__", ")", "if", "v", ".", "startswith", "(", "u'SIG'", ")", ")", ")", "return", "signal_to_name_map", ".", "get", "(", "signum", ",", "u'UNKNOWN'", ")" ]
given an os signal number .
train
false
23,924
def compose_types(a, *cs): if (not cs): return a mcls = ((a,) + cs) return type(('compose_types(%s)' % ', '.join(map(attrgetter('__name__'), mcls))), mcls, {})
[ "def", "compose_types", "(", "a", ",", "*", "cs", ")", ":", "if", "(", "not", "cs", ")", ":", "return", "a", "mcls", "=", "(", "(", "a", ",", ")", "+", "cs", ")", "return", "type", "(", "(", "'compose_types(%s)'", "%", "', '", ".", "join", "(", "map", "(", "attrgetter", "(", "'__name__'", ")", ",", "mcls", ")", ")", ")", ",", "mcls", ",", "{", "}", ")" ]
compose multiple classes together .
train
true
23,925
def read_dev_agreement_required(f): def decorator(f): @functools.wraps(f) def wrapper(request, *args, **kw): if (not request.user.read_dev_agreement): return redirect('submit.app') return f(request, *args, **kw) return wrapper return decorator(f)
[ "def", "read_dev_agreement_required", "(", "f", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "request", ",", "*", "args", ",", "**", "kw", ")", ":", "if", "(", "not", "request", ".", "user", ".", "read_dev_agreement", ")", ":", "return", "redirect", "(", "'submit.app'", ")", "return", "f", "(", "request", ",", "*", "args", ",", "**", "kw", ")", "return", "wrapper", "return", "decorator", "(", "f", ")" ]
decorator that checks if the user has read the dev agreement .
train
false
23,927
def p_declaration_2(t): pass
[ "def", "p_declaration_2", "(", "t", ")", ":", "pass" ]
declaration : declaration_specifiers semi .
train
false
23,928
def removeDuplicates(variable): oldList = variable.split(os.pathsep) newList = [] for i in oldList: if (i not in newList): newList.append(i) newVariable = os.pathsep.join(newList) return newVariable
[ "def", "removeDuplicates", "(", "variable", ")", ":", "oldList", "=", "variable", ".", "split", "(", "os", ".", "pathsep", ")", "newList", "=", "[", "]", "for", "i", "in", "oldList", ":", "if", "(", "i", "not", "in", "newList", ")", ":", "newList", ".", "append", "(", "i", ")", "newVariable", "=", "os", ".", "pathsep", ".", "join", "(", "newList", ")", "return", "newVariable" ]
remove duplicate values of an environment variable .
train
false
23,931
def import_pyside(): from PySide import QtGui, QtCore, QtSvg return (QtCore, QtGui, QtSvg, QT_API_PYSIDE)
[ "def", "import_pyside", "(", ")", ":", "from", "PySide", "import", "QtGui", ",", "QtCore", ",", "QtSvg", "return", "(", "QtCore", ",", "QtGui", ",", "QtSvg", ",", "QT_API_PYSIDE", ")" ]
import pyside importerrors raised within this function are non-recoverable .
train
false
23,932
def vocabulary_list(context, data_dict): _check_access('vocabulary_list', context, data_dict) model = context['model'] vocabulary_objects = model.Session.query(model.Vocabulary).all() return model_dictize.vocabulary_list_dictize(vocabulary_objects, context)
[ "def", "vocabulary_list", "(", "context", ",", "data_dict", ")", ":", "_check_access", "(", "'vocabulary_list'", ",", "context", ",", "data_dict", ")", "model", "=", "context", "[", "'model'", "]", "vocabulary_objects", "=", "model", ".", "Session", ".", "query", "(", "model", ".", "Vocabulary", ")", ".", "all", "(", ")", "return", "model_dictize", ".", "vocabulary_list_dictize", "(", "vocabulary_objects", ",", "context", ")" ]
return a list of all the sites tag vocabularies .
train
false
23,933
def reload_localzone(): global _cache_tz _cache_tz = pytz.timezone(get_localzone_name())
[ "def", "reload_localzone", "(", ")", ":", "global", "_cache_tz", "_cache_tz", "=", "pytz", ".", "timezone", "(", "get_localzone_name", "(", ")", ")" ]
reload the cached localzone .
train
false
23,934
def exec_python_rc(*args, **kwargs): (cmdargs, kwargs) = __wrap_python(args, kwargs) return exec_command_rc(*cmdargs, **kwargs)
[ "def", "exec_python_rc", "(", "*", "args", ",", "**", "kwargs", ")", ":", "(", "cmdargs", ",", "kwargs", ")", "=", "__wrap_python", "(", "args", ",", "kwargs", ")", "return", "exec_command_rc", "(", "*", "cmdargs", ",", "**", "kwargs", ")" ]
wrap running python script in a subprocess .
train
true
23,935
def get_raw(previous, current, property_name): return current[property_name]
[ "def", "get_raw", "(", "previous", ",", "current", ",", "property_name", ")", ":", "return", "current", "[", "property_name", "]" ]
returns the vanilla raw property value .
train
false
23,937
def no_fsl_course_data(): return (not ((u'FSL_COURSE_DATA' in os.environ) and os.path.isdir(os.path.abspath(os.environ[u'FSL_COURSE_DATA']))))
[ "def", "no_fsl_course_data", "(", ")", ":", "return", "(", "not", "(", "(", "u'FSL_COURSE_DATA'", "in", "os", ".", "environ", ")", "and", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "environ", "[", "u'FSL_COURSE_DATA'", "]", ")", ")", ")", ")" ]
check if fsl_course data is present .
train
false
23,938
def in6_ismnladdr(str): return in6_isincluded(str, 'ff01::', 16)
[ "def", "in6_ismnladdr", "(", "str", ")", ":", "return", "in6_isincluded", "(", "str", ",", "'ff01::'", ",", "16", ")" ]
returns true if address belongs to node-local multicast address space as defined in rfc .
train
false
23,939
def test_surf2bem(): check_usage(mne_surf2bem)
[ "def", "test_surf2bem", "(", ")", ":", "check_usage", "(", "mne_surf2bem", ")" ]
test mne surf2bem .
train
false
23,940
def test_atomic_download_failure(pd, seg): pd.create(seg) e = Exception('Anything') with pytest.raises(Exception) as err: with pd.download(seg): raise e assert (err.value is e) assert (not pd.is_running(seg)) assert (not pd.contains(seg))
[ "def", "test_atomic_download_failure", "(", "pd", ",", "seg", ")", ":", "pd", ".", "create", "(", "seg", ")", "e", "=", "Exception", "(", "'Anything'", ")", "with", "pytest", ".", "raises", "(", "Exception", ")", "as", "err", ":", "with", "pd", ".", "download", "(", "seg", ")", ":", "raise", "e", "assert", "(", "err", ".", "value", "is", "e", ")", "assert", "(", "not", "pd", ".", "is_running", "(", "seg", ")", ")", "assert", "(", "not", "pd", ".", "contains", "(", "seg", ")", ")" ]
ensure a raised exception doesnt move wal into place .
train
false
23,942
def sql_indexes(app, style, connection): output = [] for model in models.get_models(app, include_auto_created=True): output.extend(connection.creation.sql_indexes_for_model(model, style)) return output
[ "def", "sql_indexes", "(", "app", ",", "style", ",", "connection", ")", ":", "output", "=", "[", "]", "for", "model", "in", "models", ".", "get_models", "(", "app", ",", "include_auto_created", "=", "True", ")", ":", "output", ".", "extend", "(", "connection", ".", "creation", ".", "sql_indexes_for_model", "(", "model", ",", "style", ")", ")", "return", "output" ]
returns a list of the create index sql statements for all models in the given app .
train
false
23,943
def coiterate(iterator): return _theCooperator.coiterate(iterator)
[ "def", "coiterate", "(", "iterator", ")", ":", "return", "_theCooperator", ".", "coiterate", "(", "iterator", ")" ]
cooperatively iterate over the given iterator .
train
false
23,944
@tx.atomic def remove_vote(obj, user): obj_type = apps.get_model('contenttypes', 'ContentType').objects.get_for_model(obj) with advisory_lock('vote-{}-{}'.format(obj_type.id, obj.id)): qs = Vote.objects.filter(content_type=obj_type, object_id=obj.id, user=user) if (not qs.exists()): return qs.delete() (votes, _) = Votes.objects.get_or_create(content_type=obj_type, object_id=obj.id) votes.count = (F('count') - 1) votes.save()
[ "@", "tx", ".", "atomic", "def", "remove_vote", "(", "obj", ",", "user", ")", ":", "obj_type", "=", "apps", ".", "get_model", "(", "'contenttypes'", ",", "'ContentType'", ")", ".", "objects", ".", "get_for_model", "(", "obj", ")", "with", "advisory_lock", "(", "'vote-{}-{}'", ".", "format", "(", "obj_type", ".", "id", ",", "obj", ".", "id", ")", ")", ":", "qs", "=", "Vote", ".", "objects", ".", "filter", "(", "content_type", "=", "obj_type", ",", "object_id", "=", "obj", ".", "id", ",", "user", "=", "user", ")", "if", "(", "not", "qs", ".", "exists", "(", ")", ")", ":", "return", "qs", ".", "delete", "(", ")", "(", "votes", ",", "_", ")", "=", "Votes", ".", "objects", ".", "get_or_create", "(", "content_type", "=", "obj_type", ",", "object_id", "=", "obj", ".", "id", ")", "votes", ".", "count", "=", "(", "F", "(", "'count'", ")", "-", "1", ")", "votes", ".", "save", "(", ")" ]
remove an user vote from an object .
train
false
23,945
def _method_magic_marker(magic_kind): validate_type(magic_kind) def magic_deco(arg): call = (lambda f, *a, **k: f(*a, **k)) if callable(arg): func = arg name = func.__name__ retval = decorator(call, func) record_magic(magics, magic_kind, name, name) elif isinstance(arg, str): name = arg def mark(func, *a, **kw): record_magic(magics, magic_kind, name, func.__name__) return decorator(call, func) retval = mark else: raise TypeError('Decorator can only be called with string or function') return retval magic_deco.__doc__ = _docstring_template.format('method', magic_kind) return magic_deco
[ "def", "_method_magic_marker", "(", "magic_kind", ")", ":", "validate_type", "(", "magic_kind", ")", "def", "magic_deco", "(", "arg", ")", ":", "call", "=", "(", "lambda", "f", ",", "*", "a", ",", "**", "k", ":", "f", "(", "*", "a", ",", "**", "k", ")", ")", "if", "callable", "(", "arg", ")", ":", "func", "=", "arg", "name", "=", "func", ".", "__name__", "retval", "=", "decorator", "(", "call", ",", "func", ")", "record_magic", "(", "magics", ",", "magic_kind", ",", "name", ",", "name", ")", "elif", "isinstance", "(", "arg", ",", "str", ")", ":", "name", "=", "arg", "def", "mark", "(", "func", ",", "*", "a", ",", "**", "kw", ")", ":", "record_magic", "(", "magics", ",", "magic_kind", ",", "name", ",", "func", ".", "__name__", ")", "return", "decorator", "(", "call", ",", "func", ")", "retval", "=", "mark", "else", ":", "raise", "TypeError", "(", "'Decorator can only be called with string or function'", ")", "return", "retval", "magic_deco", ".", "__doc__", "=", "_docstring_template", ".", "format", "(", "'method'", ",", "magic_kind", ")", "return", "magic_deco" ]
decorator factory for methods in magics subclasses .
train
true
23,946
def ccf(x, y, unbiased=True): cvf = ccovf(x, y, unbiased=unbiased, demean=True) return (cvf / (np.std(x) * np.std(y)))
[ "def", "ccf", "(", "x", ",", "y", ",", "unbiased", "=", "True", ")", ":", "cvf", "=", "ccovf", "(", "x", ",", "y", ",", "unbiased", "=", "unbiased", ",", "demean", "=", "True", ")", "return", "(", "cvf", "/", "(", "np", ".", "std", "(", "x", ")", "*", "np", ".", "std", "(", "y", ")", ")", ")" ]
cross-correlation function for 1d parameters x .
train
false
23,948
def test_redirected_stream(httpbin): with open(BIN_FILE_PATH, 'rb') as f: env = TestEnvironment(stdout_isatty=False, stdin_isatty=False, stdin=f) r = http('--pretty=none', '--stream', '--verbose', 'GET', (httpbin.url + '/get'), env=env) assert (BIN_FILE_CONTENT in r)
[ "def", "test_redirected_stream", "(", "httpbin", ")", ":", "with", "open", "(", "BIN_FILE_PATH", ",", "'rb'", ")", "as", "f", ":", "env", "=", "TestEnvironment", "(", "stdout_isatty", "=", "False", ",", "stdin_isatty", "=", "False", ",", "stdin", "=", "f", ")", "r", "=", "http", "(", "'--pretty=none'", ",", "'--stream'", ",", "'--verbose'", ",", "'GET'", ",", "(", "httpbin", ".", "url", "+", "'/get'", ")", ",", "env", "=", "env", ")", "assert", "(", "BIN_FILE_CONTENT", "in", "r", ")" ]
test that --stream works with non-prettified redirected terminal output .
train
false
23,951
def strip_folders(path): unc = (sabnzbd.WIN32 and (path.startswith('//') or path.startswith('\\\\'))) f = path.strip('/').split('/') if (path.strip()[0] in '/\\'): f.insert(0, '') def strip_all(x): ' Strip all leading/trailing underscores also dots for Windows ' x = x.strip().strip('_') if sabnzbd.WIN32: x = x.strip('.') x = x.strip() return x path = os.path.normpath('/'.join([strip_all(x) for x in f])) if unc: return ('\\' + path) else: return path
[ "def", "strip_folders", "(", "path", ")", ":", "unc", "=", "(", "sabnzbd", ".", "WIN32", "and", "(", "path", ".", "startswith", "(", "'//'", ")", "or", "path", ".", "startswith", "(", "'\\\\\\\\'", ")", ")", ")", "f", "=", "path", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "if", "(", "path", ".", "strip", "(", ")", "[", "0", "]", "in", "'/\\\\'", ")", ":", "f", ".", "insert", "(", "0", ",", "''", ")", "def", "strip_all", "(", "x", ")", ":", "x", "=", "x", ".", "strip", "(", ")", ".", "strip", "(", "'_'", ")", "if", "sabnzbd", ".", "WIN32", ":", "x", "=", "x", ".", "strip", "(", "'.'", ")", "x", "=", "x", ".", "strip", "(", ")", "return", "x", "path", "=", "os", ".", "path", ".", "normpath", "(", "'/'", ".", "join", "(", "[", "strip_all", "(", "x", ")", "for", "x", "in", "f", "]", ")", ")", "if", "unc", ":", "return", "(", "'\\\\'", "+", "path", ")", "else", ":", "return", "path" ]
return path without leading and trailing spaces and underscores in each element for windows .
train
false
23,952
@require_authorized_admin @dynamic_settings def edit_facility_user(request, ds, facility_user_id): user_being_edited = (get_object_or_404(FacilityUser, id=facility_user_id) or None) title = (_('Edit user %(username)s') % {'username': user_being_edited.username}) return _facility_user(request, user_being_edited=user_being_edited, is_teacher=user_being_edited.is_teacher, title=title)
[ "@", "require_authorized_admin", "@", "dynamic_settings", "def", "edit_facility_user", "(", "request", ",", "ds", ",", "facility_user_id", ")", ":", "user_being_edited", "=", "(", "get_object_or_404", "(", "FacilityUser", ",", "id", "=", "facility_user_id", ")", "or", "None", ")", "title", "=", "(", "_", "(", "'Edit user %(username)s'", ")", "%", "{", "'username'", ":", "user_being_edited", ".", "username", "}", ")", "return", "_facility_user", "(", "request", ",", "user_being_edited", "=", "user_being_edited", ",", "is_teacher", "=", "user_being_edited", ".", "is_teacher", ",", "title", "=", "title", ")" ]
if users have permission to add a user .
train
false
23,953
def import_translations(lang, path): clear_cache() full_dict = get_full_dict(lang) full_dict.update(get_translation_dict_from_file(path, lang, u'import')) for app in frappe.get_all_apps(True): write_translations_file(app, lang, full_dict)
[ "def", "import_translations", "(", "lang", ",", "path", ")", ":", "clear_cache", "(", ")", "full_dict", "=", "get_full_dict", "(", "lang", ")", "full_dict", ".", "update", "(", "get_translation_dict_from_file", "(", "path", ",", "lang", ",", "u'import'", ")", ")", "for", "app", "in", "frappe", ".", "get_all_apps", "(", "True", ")", ":", "write_translations_file", "(", "app", ",", "lang", ",", "full_dict", ")" ]
update translated strings .
train
false
23,955
def save_cache(data, config): dpath = config.get('cache', 'cache_dir') try: cache = open('/'.join([dpath, 'inventory']), 'w') cache.write(json.dumps(data)) cache.close() except IOError as e: pass
[ "def", "save_cache", "(", "data", ",", "config", ")", ":", "dpath", "=", "config", ".", "get", "(", "'cache'", ",", "'cache_dir'", ")", "try", ":", "cache", "=", "open", "(", "'/'", ".", "join", "(", "[", "dpath", ",", "'inventory'", "]", ")", ",", "'w'", ")", "cache", ".", "write", "(", "json", ".", "dumps", "(", "data", ")", ")", "cache", ".", "close", "(", ")", "except", "IOError", "as", "e", ":", "pass" ]
saves item to cache .
train
false
23,956
@utils.arg('server', metavar='<server>', help=_('Name or ID of server.')) def do_list_secgroup(cs, args): server = _find_server(cs, args.server) groups = server.list_security_group() _print_secgroups(groups)
[ "@", "utils", ".", "arg", "(", "'server'", ",", "metavar", "=", "'<server>'", ",", "help", "=", "_", "(", "'Name or ID of server.'", ")", ")", "def", "do_list_secgroup", "(", "cs", ",", "args", ")", ":", "server", "=", "_find_server", "(", "cs", ",", "args", ".", "server", ")", "groups", "=", "server", ".", "list_security_group", "(", ")", "_print_secgroups", "(", "groups", ")" ]
list security group(s) of a server .
train
false
23,958
def test_against_pytpm_doc_example(): fk5_in = SkyCoord(u'12h22m54.899s', u'15d49m20.57s', frame=FK5(equinox=u'J2000')) pytpm_out = BarycentricTrueEcliptic(lon=(178.78256462 * u.deg), lat=(16.7597002513 * u.deg), equinox=u'J2000') astropy_out = fk5_in.transform_to(pytpm_out) assert (pytpm_out.separation(astropy_out) < (1 * u.arcmin))
[ "def", "test_against_pytpm_doc_example", "(", ")", ":", "fk5_in", "=", "SkyCoord", "(", "u'12h22m54.899s'", ",", "u'15d49m20.57s'", ",", "frame", "=", "FK5", "(", "equinox", "=", "u'J2000'", ")", ")", "pytpm_out", "=", "BarycentricTrueEcliptic", "(", "lon", "=", "(", "178.78256462", "*", "u", ".", "deg", ")", ",", "lat", "=", "(", "16.7597002513", "*", "u", ".", "deg", ")", ",", "equinox", "=", "u'J2000'", ")", "astropy_out", "=", "fk5_in", ".", "transform_to", "(", "pytpm_out", ")", "assert", "(", "pytpm_out", ".", "separation", "(", "astropy_out", ")", "<", "(", "1", "*", "u", ".", "arcmin", ")", ")" ]
check that astropys ecliptic systems give answers consistent with pytpm currently this is only testing against the example given in the pytpm docs .
train
false
23,960
def _ValidateUpdateFollower(tester, user_cookie, op_dict, foll_dict): validator = tester.validator (user_id, device_id) = tester.GetIdsFromCookie(user_cookie) viewpoint_id = foll_dict['viewpoint_id'] has_viewed_seq = ('viewed_seq' in foll_dict) if has_viewed_seq: update_seq = validator.GetModelObject(Viewpoint, viewpoint_id).update_seq old_viewed_seq = validator.GetModelObject(Follower, DBKey(user_id, viewpoint_id)).viewed_seq if (foll_dict['viewed_seq'] > update_seq): foll_dict['viewed_seq'] = update_seq if (foll_dict['viewed_seq'] < old_viewed_seq): del foll_dict['viewed_seq'] foll_dict['user_id'] = user_id follower = validator.ValidateUpdateDBObject(Follower, **foll_dict) invalidate = {'viewpoints': [{'viewpoint_id': viewpoint_id, 'get_attributes': True}]} if (has_viewed_seq and ('labels' not in foll_dict)): invalidate = None validator.ValidateNotification('update_follower', user_id, op_dict, invalidate, viewpoint_id=viewpoint_id, seq_num_pair=(None, (follower.viewed_seq if has_viewed_seq else None)))
[ "def", "_ValidateUpdateFollower", "(", "tester", ",", "user_cookie", ",", "op_dict", ",", "foll_dict", ")", ":", "validator", "=", "tester", ".", "validator", "(", "user_id", ",", "device_id", ")", "=", "tester", ".", "GetIdsFromCookie", "(", "user_cookie", ")", "viewpoint_id", "=", "foll_dict", "[", "'viewpoint_id'", "]", "has_viewed_seq", "=", "(", "'viewed_seq'", "in", "foll_dict", ")", "if", "has_viewed_seq", ":", "update_seq", "=", "validator", ".", "GetModelObject", "(", "Viewpoint", ",", "viewpoint_id", ")", ".", "update_seq", "old_viewed_seq", "=", "validator", ".", "GetModelObject", "(", "Follower", ",", "DBKey", "(", "user_id", ",", "viewpoint_id", ")", ")", ".", "viewed_seq", "if", "(", "foll_dict", "[", "'viewed_seq'", "]", ">", "update_seq", ")", ":", "foll_dict", "[", "'viewed_seq'", "]", "=", "update_seq", "if", "(", "foll_dict", "[", "'viewed_seq'", "]", "<", "old_viewed_seq", ")", ":", "del", "foll_dict", "[", "'viewed_seq'", "]", "foll_dict", "[", "'user_id'", "]", "=", "user_id", "follower", "=", "validator", ".", "ValidateUpdateDBObject", "(", "Follower", ",", "**", "foll_dict", ")", "invalidate", "=", "{", "'viewpoints'", ":", "[", "{", "'viewpoint_id'", ":", "viewpoint_id", ",", "'get_attributes'", ":", "True", "}", "]", "}", "if", "(", "has_viewed_seq", "and", "(", "'labels'", "not", "in", "foll_dict", ")", ")", ":", "invalidate", "=", "None", "validator", ".", "ValidateNotification", "(", "'update_follower'", ",", "user_id", ",", "op_dict", ",", "invalidate", ",", "viewpoint_id", "=", "viewpoint_id", ",", "seq_num_pair", "=", "(", "None", ",", "(", "follower", ".", "viewed_seq", "if", "has_viewed_seq", "else", "None", ")", ")", ")" ]
validates the results of a call to update_follower .
train
false
23,961
def tracked_branch(branch=None, config=None): if (config is None): config = gitcfg.current() if (branch is None): branch = current_branch() if (branch is None): return None remote = config.get((u'branch.%s.remote' % branch)) if (not remote): return None merge_ref = config.get((u'branch.%s.merge' % branch)) if (not merge_ref): return None refs_heads = u'refs/heads/' if merge_ref.startswith(refs_heads): return ((remote + u'/') + merge_ref[len(refs_heads):]) return None
[ "def", "tracked_branch", "(", "branch", "=", "None", ",", "config", "=", "None", ")", ":", "if", "(", "config", "is", "None", ")", ":", "config", "=", "gitcfg", ".", "current", "(", ")", "if", "(", "branch", "is", "None", ")", ":", "branch", "=", "current_branch", "(", ")", "if", "(", "branch", "is", "None", ")", ":", "return", "None", "remote", "=", "config", ".", "get", "(", "(", "u'branch.%s.remote'", "%", "branch", ")", ")", "if", "(", "not", "remote", ")", ":", "return", "None", "merge_ref", "=", "config", ".", "get", "(", "(", "u'branch.%s.merge'", "%", "branch", ")", ")", "if", "(", "not", "merge_ref", ")", ":", "return", "None", "refs_heads", "=", "u'refs/heads/'", "if", "merge_ref", ".", "startswith", "(", "refs_heads", ")", ":", "return", "(", "(", "remote", "+", "u'/'", ")", "+", "merge_ref", "[", "len", "(", "refs_heads", ")", ":", "]", ")", "return", "None" ]
return the remote branch associated with branch .
train
false
23,963
def _guess_content_type(url): OCTET_STREAM = 'application/octet-stream' n = url.rfind('.') if (n == (-1)): return OCTET_STREAM return mimetypes.types_map.get(url[n:].lower(), OCTET_STREAM)
[ "def", "_guess_content_type", "(", "url", ")", ":", "OCTET_STREAM", "=", "'application/octet-stream'", "n", "=", "url", ".", "rfind", "(", "'.'", ")", "if", "(", "n", "==", "(", "-", "1", ")", ")", ":", "return", "OCTET_STREAM", "return", "mimetypes", ".", "types_map", ".", "get", "(", "url", "[", "n", ":", "]", ".", "lower", "(", ")", ",", "OCTET_STREAM", ")" ]
guess content type by url .
train
true
23,964
def validate_choice(value, choices): if ((choices is not None) and (value not in choices)): names = u', '.join((repr(c) for c in choices)) raise ValueError((u'must be one of %s, not %s.' % (names, value)))
[ "def", "validate_choice", "(", "value", ",", "choices", ")", ":", "if", "(", "(", "choices", "is", "not", "None", ")", "and", "(", "value", "not", "in", "choices", ")", ")", ":", "names", "=", "u', '", ".", "join", "(", "(", "repr", "(", "c", ")", "for", "c", "in", "choices", ")", ")", "raise", "ValueError", "(", "(", "u'must be one of %s, not %s.'", "%", "(", "names", ",", "value", ")", ")", ")" ]
validate that value is one of the choices normally called in :meth:~mopidy .
train
false
23,965
def parseAvailable(available_text): return [s.strip() for s in available_text.split(',')]
[ "def", "parseAvailable", "(", "available_text", ")", ":", "return", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "available_text", ".", "split", "(", "','", ")", "]" ]
parse an available: lines data str -> [str] .
train
false
23,967
def tf_idf(vectors=[], base=2.71828): df = {} for v in vectors: for f in v: if (v[f] != 0): df[f] = ((df[f] + 1) if (f in df) else 1.0) n = len(vectors) s = dict.__setitem__ for v in vectors: for f in v: s(v, f, (v[f] * log((n / df[f]), base))) return vectors
[ "def", "tf_idf", "(", "vectors", "=", "[", "]", ",", "base", "=", "2.71828", ")", ":", "df", "=", "{", "}", "for", "v", "in", "vectors", ":", "for", "f", "in", "v", ":", "if", "(", "v", "[", "f", "]", "!=", "0", ")", ":", "df", "[", "f", "]", "=", "(", "(", "df", "[", "f", "]", "+", "1", ")", "if", "(", "f", "in", "df", ")", "else", "1.0", ")", "n", "=", "len", "(", "vectors", ")", "s", "=", "dict", ".", "__setitem__", "for", "v", "in", "vectors", ":", "for", "f", "in", "v", ":", "s", "(", "v", ",", "f", ",", "(", "v", "[", "f", "]", "*", "log", "(", "(", "n", "/", "df", "[", "f", "]", ")", ",", "base", ")", ")", ")", "return", "vectors" ]
calculates tf * idf on the vector feature weights .
train
false
23,968
def sanitize_file_name_unicode(name, substitute='_'): if isbytestring(name): return sanitize_file_name(name, substitute=substitute, as_unicode=True) chars = [(substitute if (c in _filename_sanitize_unicode) else c) for c in name] one = u''.join(chars) one = re.sub('\\s', ' ', one).strip() (bname, ext) = os.path.splitext(one) one = re.sub('^\\.+$', '_', bname) one = one.replace('..', substitute) one += ext if (one and (one[(-1)] in ('.', ' '))): one = (one[:(-1)] + '_') if one.startswith('.'): one = ('_' + one[1:]) return one
[ "def", "sanitize_file_name_unicode", "(", "name", ",", "substitute", "=", "'_'", ")", ":", "if", "isbytestring", "(", "name", ")", ":", "return", "sanitize_file_name", "(", "name", ",", "substitute", "=", "substitute", ",", "as_unicode", "=", "True", ")", "chars", "=", "[", "(", "substitute", "if", "(", "c", "in", "_filename_sanitize_unicode", ")", "else", "c", ")", "for", "c", "in", "name", "]", "one", "=", "u''", ".", "join", "(", "chars", ")", "one", "=", "re", ".", "sub", "(", "'\\\\s'", ",", "' '", ",", "one", ")", ".", "strip", "(", ")", "(", "bname", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "one", ")", "one", "=", "re", ".", "sub", "(", "'^\\\\.+$'", ",", "'_'", ",", "bname", ")", "one", "=", "one", ".", "replace", "(", "'..'", ",", "substitute", ")", "one", "+=", "ext", "if", "(", "one", "and", "(", "one", "[", "(", "-", "1", ")", "]", "in", "(", "'.'", ",", "' '", ")", ")", ")", ":", "one", "=", "(", "one", "[", ":", "(", "-", "1", ")", "]", "+", "'_'", ")", "if", "one", ".", "startswith", "(", "'.'", ")", ":", "one", "=", "(", "'_'", "+", "one", "[", "1", ":", "]", ")", "return", "one" ]
sanitize the filename name .
train
false
23,970
def _get_pb_likelihood(likelihood): likelihood_pb = image_annotator_pb2.Likelihood.Name(likelihood) return Likelihood[likelihood_pb]
[ "def", "_get_pb_likelihood", "(", "likelihood", ")", ":", "likelihood_pb", "=", "image_annotator_pb2", ".", "Likelihood", ".", "Name", "(", "likelihood", ")", "return", "Likelihood", "[", "likelihood_pb", "]" ]
convert protobuf likelihood integer value to likelihood enum .
train
false
23,971
def addElementToListTableIfNotThere(element, key, listTable): if (key in listTable): elements = listTable[key] if (element not in elements): elements.append(element) else: listTable[key] = [element]
[ "def", "addElementToListTableIfNotThere", "(", "element", ",", "key", ",", "listTable", ")", ":", "if", "(", "key", "in", "listTable", ")", ":", "elements", "=", "listTable", "[", "key", "]", "if", "(", "element", "not", "in", "elements", ")", ":", "elements", ".", "append", "(", "element", ")", "else", ":", "listTable", "[", "key", "]", "=", "[", "element", "]" ]
add the value to the lists .
train
false
23,972
def getInfoBuild(): try: build = autoclass('android.os.Build') version = autoclass('android.os.Build$VERSION') deviceName = build.DEVICE manufacturer = build.MANUFACTURER model = build.MODEL product = build.PRODUCT bootloaderVersion = build.BOOTLOADER hardware = build.HARDWARE try: serial = build.SERIAL except Exception as e: serial = None radioVersion = build.getRadioVersion() return {'deviceName': deviceName, 'manufacturer': manufacturer, 'model': model, 'product': product, 'bootloaderVersion': bootloaderVersion, 'hardware': hardware, 'serial': serial, 'radioVersion': radioVersion, 'release': '{0} ({1})'.format(version.RELEASE, version.CODENAME)} except Exception as e: return {'deviceName': None, 'manufacturer': None, 'model': None, 'product': None, 'bootloaderVersion': None, 'hardware': None, 'serial': None, 'radioVersion': None, 'release': None}
[ "def", "getInfoBuild", "(", ")", ":", "try", ":", "build", "=", "autoclass", "(", "'android.os.Build'", ")", "version", "=", "autoclass", "(", "'android.os.Build$VERSION'", ")", "deviceName", "=", "build", ".", "DEVICE", "manufacturer", "=", "build", ".", "MANUFACTURER", "model", "=", "build", ".", "MODEL", "product", "=", "build", ".", "PRODUCT", "bootloaderVersion", "=", "build", ".", "BOOTLOADER", "hardware", "=", "build", ".", "HARDWARE", "try", ":", "serial", "=", "build", ".", "SERIAL", "except", "Exception", "as", "e", ":", "serial", "=", "None", "radioVersion", "=", "build", ".", "getRadioVersion", "(", ")", "return", "{", "'deviceName'", ":", "deviceName", ",", "'manufacturer'", ":", "manufacturer", ",", "'model'", ":", "model", ",", "'product'", ":", "product", ",", "'bootloaderVersion'", ":", "bootloaderVersion", ",", "'hardware'", ":", "hardware", ",", "'serial'", ":", "serial", ",", "'radioVersion'", ":", "radioVersion", ",", "'release'", ":", "'{0} ({1})'", ".", "format", "(", "version", ".", "RELEASE", ",", "version", ".", "CODENAME", ")", "}", "except", "Exception", "as", "e", ":", "return", "{", "'deviceName'", ":", "None", ",", "'manufacturer'", ":", "None", ",", "'model'", ":", "None", ",", "'product'", ":", "None", ",", "'bootloaderVersion'", ":", "None", ",", "'hardware'", ":", "None", ",", "'serial'", ":", "None", ",", "'radioVersion'", ":", "None", ",", "'release'", ":", "None", "}" ]
returns {devicename: .
train
false
23,973
def save_process(MAVExpLastGraph): from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx from MAVProxy.modules.lib.wxgrapheditor import GraphDialog app = wx.App(False) frame = GraphDialog('Graph Editor', MAVExpLastGraph, save_callback) frame.ShowModal() frame.Destroy()
[ "def", "save_process", "(", "MAVExpLastGraph", ")", ":", "from", "MAVProxy", ".", "modules", ".", "lib", "import", "wx_processguard", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "wx_loader", "import", "wx", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "wxgrapheditor", "import", "GraphDialog", "app", "=", "wx", ".", "App", "(", "False", ")", "frame", "=", "GraphDialog", "(", "'Graph Editor'", ",", "MAVExpLastGraph", ",", "save_callback", ")", "frame", ".", "ShowModal", "(", ")", "frame", ".", "Destroy", "(", ")" ]
process for saving a graph .
train
true
23,974
def _is_dense_variable(x): if (not isinstance(x, gof.Variable)): raise NotImplementedError('this function should only be called on *variables* (of type sparse.SparseType or tensor.TensorType, for instance), not ', x) return isinstance(x.type, tensor.TensorType)
[ "def", "_is_dense_variable", "(", "x", ")", ":", "if", "(", "not", "isinstance", "(", "x", ",", "gof", ".", "Variable", ")", ")", ":", "raise", "NotImplementedError", "(", "'this function should only be called on *variables* (of type sparse.SparseType or tensor.TensorType, for instance), not '", ",", "x", ")", "return", "isinstance", "(", "x", ".", "type", ",", "tensor", ".", "TensorType", ")" ]
returns boolean true if x is a l{tensor .
train
false
23,975
def diop_general_sum_of_even_powers(eq, limit=1): (var, coeff, diop_type) = classify_diop(eq, _dict=False) if (diop_type == 'general_sum_of_even_powers'): for k in coeff.keys(): if (k.is_Pow and coeff[k]): p = k.exp return _diop_general_sum_of_even_powers(var, p, (- coeff[1]), limit)
[ "def", "diop_general_sum_of_even_powers", "(", "eq", ",", "limit", "=", "1", ")", ":", "(", "var", ",", "coeff", ",", "diop_type", ")", "=", "classify_diop", "(", "eq", ",", "_dict", "=", "False", ")", "if", "(", "diop_type", "==", "'general_sum_of_even_powers'", ")", ":", "for", "k", "in", "coeff", ".", "keys", "(", ")", ":", "if", "(", "k", ".", "is_Pow", "and", "coeff", "[", "k", "]", ")", ":", "p", "=", "k", ".", "exp", "return", "_diop_general_sum_of_even_powers", "(", "var", ",", "p", ",", "(", "-", "coeff", "[", "1", "]", ")", ",", "limit", ")" ]
solves the equation x_{1}^e + x_{2}^e + .
train
false
23,977
def exec_command_rc(*cmdargs, **kwargs): if ('encoding' in kwargs): kwargs.pop('encoding') return subprocess.call(cmdargs, **kwargs)
[ "def", "exec_command_rc", "(", "*", "cmdargs", ",", "**", "kwargs", ")", ":", "if", "(", "'encoding'", "in", "kwargs", ")", ":", "kwargs", ".", "pop", "(", "'encoding'", ")", "return", "subprocess", ".", "call", "(", "cmdargs", ",", "**", "kwargs", ")" ]
return the exit code of the command specified by the passed positional arguments .
train
false
23,978
def _flag(s, pos=0): m = opt2_regex.match(s, pos) return m
[ "def", "_flag", "(", "s", ",", "pos", "=", "0", ")", ":", "m", "=", "opt2_regex", ".", "match", "(", "s", ",", "pos", ")", "return", "m" ]
get the next free flag .
train
false
23,979
def estimate_spectral_norm_diff(A, B, its=20): from scipy.sparse.linalg import aslinearoperator A = aslinearoperator(A) B = aslinearoperator(B) (m, n) = A.shape matvec1 = (lambda x: A.matvec(x)) matveca1 = (lambda x: A.rmatvec(x)) matvec2 = (lambda x: B.matvec(x)) matveca2 = (lambda x: B.rmatvec(x)) if _is_real(A): return backend.idd_diffsnorm(m, n, matveca1, matveca2, matvec1, matvec2, its=its) else: return backend.idz_diffsnorm(m, n, matveca1, matveca2, matvec1, matvec2, its=its)
[ "def", "estimate_spectral_norm_diff", "(", "A", ",", "B", ",", "its", "=", "20", ")", ":", "from", "scipy", ".", "sparse", ".", "linalg", "import", "aslinearoperator", "A", "=", "aslinearoperator", "(", "A", ")", "B", "=", "aslinearoperator", "(", "B", ")", "(", "m", ",", "n", ")", "=", "A", ".", "shape", "matvec1", "=", "(", "lambda", "x", ":", "A", ".", "matvec", "(", "x", ")", ")", "matveca1", "=", "(", "lambda", "x", ":", "A", ".", "rmatvec", "(", "x", ")", ")", "matvec2", "=", "(", "lambda", "x", ":", "B", ".", "matvec", "(", "x", ")", ")", "matveca2", "=", "(", "lambda", "x", ":", "B", ".", "rmatvec", "(", "x", ")", ")", "if", "_is_real", "(", "A", ")", ":", "return", "backend", ".", "idd_diffsnorm", "(", "m", ",", "n", ",", "matveca1", ",", "matveca2", ",", "matvec1", ",", "matvec2", ",", "its", "=", "its", ")", "else", ":", "return", "backend", ".", "idz_diffsnorm", "(", "m", ",", "n", ",", "matveca1", ",", "matveca2", ",", "matvec1", ",", "matvec2", ",", "its", "=", "its", ")" ]
estimate spectral norm of the difference of two matrices by the randomized power method .
train
false
23,980
def get_read_trace(): return copy.deepcopy(_read_trace)
[ "def", "get_read_trace", "(", ")", ":", "return", "copy", ".", "deepcopy", "(", "_read_trace", ")" ]
return a traceback of the attempted read formats for the last call to ~astropy .
train
false
23,981
def mountvolume(volume, server=None, username=None, password=None): finder = _getfinder() args = {} attrs = {} if password: args['PASS'] = password if username: args['USER'] = username if server: args['SRVR'] = server args['----'] = volume (_reply, args, attrs) = finder.send('aevt', 'mvol', args, attrs) if ('errn' in args): raise Error, aetools.decodeerror(args) if ('----' in args): return args['----']
[ "def", "mountvolume", "(", "volume", ",", "server", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "finder", "=", "_getfinder", "(", ")", "args", "=", "{", "}", "attrs", "=", "{", "}", "if", "password", ":", "args", "[", "'PASS'", "]", "=", "password", "if", "username", ":", "args", "[", "'USER'", "]", "=", "username", "if", "server", ":", "args", "[", "'SRVR'", "]", "=", "server", "args", "[", "'----'", "]", "=", "volume", "(", "_reply", ",", "args", ",", "attrs", ")", "=", "finder", ".", "send", "(", "'aevt'", ",", "'mvol'", ",", "args", ",", "attrs", ")", "if", "(", "'errn'", "in", "args", ")", ":", "raise", "Error", ",", "aetools", ".", "decodeerror", "(", "args", ")", "if", "(", "'----'", "in", "args", ")", ":", "return", "args", "[", "'----'", "]" ]
mount a volume .
train
false
23,983
def _unmap(data, count, inds, fill=0): if (len(data.shape) == 1): ret = np.empty((count,), dtype=np.float32) ret.fill(fill) ret[inds] = data else: ret = np.empty(((count,) + data.shape[1:]), dtype=np.float32) ret.fill(fill) ret[inds, :] = data return ret
[ "def", "_unmap", "(", "data", ",", "count", ",", "inds", ",", "fill", "=", "0", ")", ":", "if", "(", "len", "(", "data", ".", "shape", ")", "==", "1", ")", ":", "ret", "=", "np", ".", "empty", "(", "(", "count", ",", ")", ",", "dtype", "=", "np", ".", "float32", ")", "ret", ".", "fill", "(", "fill", ")", "ret", "[", "inds", "]", "=", "data", "else", ":", "ret", "=", "np", ".", "empty", "(", "(", "(", "count", ",", ")", "+", "data", ".", "shape", "[", "1", ":", "]", ")", ",", "dtype", "=", "np", ".", "float32", ")", "ret", ".", "fill", "(", "fill", ")", "ret", "[", "inds", ",", ":", "]", "=", "data", "return", "ret" ]
unmap a subset of item back to the original set of items .
train
false
23,987
def resource_list(name): def make_responder(list_all): def responder(): return app.response_class(json_generator(list_all(), root=name, expand=is_expand()), mimetype='application/json') responder.__name__ = 'all_{0}'.format(name) return responder return make_responder
[ "def", "resource_list", "(", "name", ")", ":", "def", "make_responder", "(", "list_all", ")", ":", "def", "responder", "(", ")", ":", "return", "app", ".", "response_class", "(", "json_generator", "(", "list_all", "(", ")", ",", "root", "=", "name", ",", "expand", "=", "is_expand", "(", ")", ")", ",", "mimetype", "=", "'application/json'", ")", "responder", ".", "__name__", "=", "'all_{0}'", ".", "format", "(", "name", ")", "return", "responder", "return", "make_responder" ]
decorates a function to handle restful http request for a list of resources .
train
false
23,988
def LSPI_policy(fMap, Ts, R, discountFactor, initpolicy=None, maxIters=20): if (initpolicy is None): (policy, _) = randomPolicy(Ts) else: policy = initpolicy while (maxIters > 0): Qs = LSTD_Qvalues(Ts, policy, R, fMap, discountFactor) newpolicy = greedyQPolicy(Qs) if (sum(ravel(abs((newpolicy - policy)))) < 0.001): return (policy, collapsedTransitions(Ts, policy)) policy = newpolicy maxIters -= 1 return (policy, collapsedTransitions(Ts, policy))
[ "def", "LSPI_policy", "(", "fMap", ",", "Ts", ",", "R", ",", "discountFactor", ",", "initpolicy", "=", "None", ",", "maxIters", "=", "20", ")", ":", "if", "(", "initpolicy", "is", "None", ")", ":", "(", "policy", ",", "_", ")", "=", "randomPolicy", "(", "Ts", ")", "else", ":", "policy", "=", "initpolicy", "while", "(", "maxIters", ">", "0", ")", ":", "Qs", "=", "LSTD_Qvalues", "(", "Ts", ",", "policy", ",", "R", ",", "fMap", ",", "discountFactor", ")", "newpolicy", "=", "greedyQPolicy", "(", "Qs", ")", "if", "(", "sum", "(", "ravel", "(", "abs", "(", "(", "newpolicy", "-", "policy", ")", ")", ")", ")", "<", "0.001", ")", ":", "return", "(", "policy", ",", "collapsedTransitions", "(", "Ts", ",", "policy", ")", ")", "policy", "=", "newpolicy", "maxIters", "-=", "1", "return", "(", "policy", ",", "collapsedTransitions", "(", "Ts", ",", "policy", ")", ")" ]
lspi is like policy iteration .
train
false
23,989
def cb(pkt): global clients_APs, APs, args, sniff_daemon_running if sniff_daemon_running: "\n We're adding the AP and channel to the deauth list at time of creation\n rather than updating on the fly in order to avoid costly for loops\n that require a lock.\n " if pkt.haslayer(Dot11): if (pkt.addr1 and pkt.addr2): if args.accesspoint: if (args.accesspoint not in [pkt.addr1, pkt.addr2]): return if (pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp)): APs_add(clients_APs, APs, pkt, args.channel) if noise_filter(args.skip, pkt.addr1, pkt.addr2): return if (pkt.type in [1, 2]): clients_APs_add(clients_APs, pkt.addr1, pkt.addr2)
[ "def", "cb", "(", "pkt", ")", ":", "global", "clients_APs", ",", "APs", ",", "args", ",", "sniff_daemon_running", "if", "sniff_daemon_running", ":", "if", "pkt", ".", "haslayer", "(", "Dot11", ")", ":", "if", "(", "pkt", ".", "addr1", "and", "pkt", ".", "addr2", ")", ":", "if", "args", ".", "accesspoint", ":", "if", "(", "args", ".", "accesspoint", "not", "in", "[", "pkt", ".", "addr1", ",", "pkt", ".", "addr2", "]", ")", ":", "return", "if", "(", "pkt", ".", "haslayer", "(", "Dot11Beacon", ")", "or", "pkt", ".", "haslayer", "(", "Dot11ProbeResp", ")", ")", ":", "APs_add", "(", "clients_APs", ",", "APs", ",", "pkt", ",", "args", ".", "channel", ")", "if", "noise_filter", "(", "args", ".", "skip", ",", "pkt", ".", "addr1", ",", "pkt", ".", "addr2", ")", ":", "return", "if", "(", "pkt", ".", "type", "in", "[", "1", ",", "2", "]", ")", ":", "clients_APs_add", "(", "clients_APs", ",", "pkt", ".", "addr1", ",", "pkt", ".", "addr2", ")" ]
look for dot11 packets that arent to or from broadcast address .
train
false
23,990
def _check_cg(cg_term, expr, length, sign=None): matches = cg_term.match(expr) if (matches is None): return if (sign is not None): if (not isinstance(sign, tuple)): raise TypeError('sign must be a tuple') if (not (sign[0] == sign[1].subs(matches))): return if (len(matches) == length): return matches
[ "def", "_check_cg", "(", "cg_term", ",", "expr", ",", "length", ",", "sign", "=", "None", ")", ":", "matches", "=", "cg_term", ".", "match", "(", "expr", ")", "if", "(", "matches", "is", "None", ")", ":", "return", "if", "(", "sign", "is", "not", "None", ")", ":", "if", "(", "not", "isinstance", "(", "sign", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "'sign must be a tuple'", ")", "if", "(", "not", "(", "sign", "[", "0", "]", "==", "sign", "[", "1", "]", ".", "subs", "(", "matches", ")", ")", ")", ":", "return", "if", "(", "len", "(", "matches", ")", "==", "length", ")", ":", "return", "matches" ]
checks whether a term matches the given expression .
train
false
23,991
def defer(fn, *args, **kwargs): deferred.defer(fn, *args, **kwargs)
[ "def", "defer", "(", "fn", ",", "*", "args", ",", "**", "kwargs", ")", ":", "deferred", ".", "defer", "(", "fn", ",", "*", "args", ",", "**", "kwargs", ")" ]
defers a callable for execution later .
train
false
23,992
def create_resource(): task_schema = get_task_schema() partial_task_schema = _get_partial_task_schema() deserializer = RequestDeserializer(task_schema) serializer = ResponseSerializer(task_schema, partial_task_schema) controller = TasksController() return wsgi.Resource(controller, deserializer, serializer)
[ "def", "create_resource", "(", ")", ":", "task_schema", "=", "get_task_schema", "(", ")", "partial_task_schema", "=", "_get_partial_task_schema", "(", ")", "deserializer", "=", "RequestDeserializer", "(", "task_schema", ")", "serializer", "=", "ResponseSerializer", "(", "task_schema", ",", "partial_task_schema", ")", "controller", "=", "TasksController", "(", ")", "return", "wsgi", ".", "Resource", "(", "controller", ",", "deserializer", ",", "serializer", ")" ]
create the wsgi resource for this controller .
train
false
23,994
def _api_key_patch_add(conn, apiKey, pvlist): response = conn.update_api_key(apiKey=apiKey, patchOperations=_api_key_patchops('add', pvlist)) return response
[ "def", "_api_key_patch_add", "(", "conn", ",", "apiKey", ",", "pvlist", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "_api_key_patchops", "(", "'add'", ",", "pvlist", ")", ")", "return", "response" ]
the add patch operation for a list of tuples on an apikey resource list path .
train
true
23,995
def db_monodb(httprequest=None): httprequest = (httprequest or request.httprequest) dbs = db_list(True, httprequest) db_session = httprequest.session.db if (db_session in dbs): return db_session if (len(dbs) == 1): return dbs[0] return None
[ "def", "db_monodb", "(", "httprequest", "=", "None", ")", ":", "httprequest", "=", "(", "httprequest", "or", "request", ".", "httprequest", ")", "dbs", "=", "db_list", "(", "True", ",", "httprequest", ")", "db_session", "=", "httprequest", ".", "session", ".", "db", "if", "(", "db_session", "in", "dbs", ")", ":", "return", "db_session", "if", "(", "len", "(", "dbs", ")", "==", "1", ")", ":", "return", "dbs", "[", "0", "]", "return", "None" ]
magic function to find the current database .
train
false
23,996
def _WriteSimpleXMLElement(outfile, name, value, indent): value_str = _StrOrUnicode(value) if isinstance(value, bool): value_str = value_str.lower() safe_value_str = _MakeXMLSafe(value_str) outfile.write(('%s<%s>%s</%s>\n' % (indent, name, safe_value_str, name)))
[ "def", "_WriteSimpleXMLElement", "(", "outfile", ",", "name", ",", "value", ",", "indent", ")", ":", "value_str", "=", "_StrOrUnicode", "(", "value", ")", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "value_str", "=", "value_str", ".", "lower", "(", ")", "safe_value_str", "=", "_MakeXMLSafe", "(", "value_str", ")", "outfile", ".", "write", "(", "(", "'%s<%s>%s</%s>\\n'", "%", "(", "indent", ",", "name", ",", "safe_value_str", ",", "name", ")", ")", ")" ]
writes a simple xml element .
train
false
23,997
def _upstart_services(): if HAS_UPSTART: return [os.path.basename(name)[:(-5)] for name in glob.glob('/etc/init/*.conf')] else: return []
[ "def", "_upstart_services", "(", ")", ":", "if", "HAS_UPSTART", ":", "return", "[", "os", ".", "path", ".", "basename", "(", "name", ")", "[", ":", "(", "-", "5", ")", "]", "for", "name", "in", "glob", ".", "glob", "(", "'/etc/init/*.conf'", ")", "]", "else", ":", "return", "[", "]" ]
return list of upstart services .
train
false
23,998
def _coerce_field_name(field_name, field_index): if callable(field_name): if (field_name.__name__ == '<lambda>'): return ('lambda' + str(field_index)) else: return field_name.__name__ return field_name
[ "def", "_coerce_field_name", "(", "field_name", ",", "field_index", ")", ":", "if", "callable", "(", "field_name", ")", ":", "if", "(", "field_name", ".", "__name__", "==", "'<lambda>'", ")", ":", "return", "(", "'lambda'", "+", "str", "(", "field_index", ")", ")", "else", ":", "return", "field_name", ".", "__name__", "return", "field_name" ]
coerce a field_name to a string .
train
false
23,999
def test_quadratic(Chart, datas): chart = Chart(interpolate='quadratic') chart = make_data(chart, datas) assert chart.render()
[ "def", "test_quadratic", "(", "Chart", ",", "datas", ")", ":", "chart", "=", "Chart", "(", "interpolate", "=", "'quadratic'", ")", "chart", "=", "make_data", "(", "chart", ",", "datas", ")", "assert", "chart", ".", "render", "(", ")" ]
test quadratic interpolation .
train
false
24,002
@requires_img_lib() def test_read_write_image(): fname = op.join(temp_dir, 'out.png') im1 = load_crate() imsave(fname, im1, format='png') with warnings.catch_warnings(record=True): im2 = imread(fname) assert_allclose(im1, im2)
[ "@", "requires_img_lib", "(", ")", "def", "test_read_write_image", "(", ")", ":", "fname", "=", "op", ".", "join", "(", "temp_dir", ",", "'out.png'", ")", "im1", "=", "load_crate", "(", ")", "imsave", "(", "fname", ",", "im1", ",", "format", "=", "'png'", ")", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", ":", "im2", "=", "imread", "(", "fname", ")", "assert_allclose", "(", "im1", ",", "im2", ")" ]
test reading and writing of images .
train
false
24,003
def register_view_op_c_code(type, code, version=()): ViewOp.c_code_and_version[type] = (code, version)
[ "def", "register_view_op_c_code", "(", "type", ",", "code", ",", "version", "=", "(", ")", ")", ":", "ViewOp", ".", "c_code_and_version", "[", "type", "]", "=", "(", "code", ",", "version", ")" ]
tell viewop how to generate c code for a theano type .
train
false
24,004
def _do_interp_dots(inst, interpolation, goods_idx, bads_idx): from ..io.base import BaseRaw from ..epochs import BaseEpochs from ..evoked import Evoked if isinstance(inst, BaseRaw): inst._data[bads_idx] = interpolation.dot(inst._data[goods_idx]) elif isinstance(inst, BaseEpochs): inst._data[:, bads_idx, :] = np.einsum('ij,xjy->xiy', interpolation, inst._data[:, goods_idx, :]) elif isinstance(inst, Evoked): inst.data[bads_idx] = interpolation.dot(inst.data[goods_idx]) else: raise ValueError('Inputs of type {0} are not supported'.format(type(inst)))
[ "def", "_do_interp_dots", "(", "inst", ",", "interpolation", ",", "goods_idx", ",", "bads_idx", ")", ":", "from", ".", ".", "io", ".", "base", "import", "BaseRaw", "from", ".", ".", "epochs", "import", "BaseEpochs", "from", ".", ".", "evoked", "import", "Evoked", "if", "isinstance", "(", "inst", ",", "BaseRaw", ")", ":", "inst", ".", "_data", "[", "bads_idx", "]", "=", "interpolation", ".", "dot", "(", "inst", ".", "_data", "[", "goods_idx", "]", ")", "elif", "isinstance", "(", "inst", ",", "BaseEpochs", ")", ":", "inst", ".", "_data", "[", ":", ",", "bads_idx", ",", ":", "]", "=", "np", ".", "einsum", "(", "'ij,xjy->xiy'", ",", "interpolation", ",", "inst", ".", "_data", "[", ":", ",", "goods_idx", ",", ":", "]", ")", "elif", "isinstance", "(", "inst", ",", "Evoked", ")", ":", "inst", ".", "data", "[", "bads_idx", "]", "=", "interpolation", ".", "dot", "(", "inst", ".", "data", "[", "goods_idx", "]", ")", "else", ":", "raise", "ValueError", "(", "'Inputs of type {0} are not supported'", ".", "format", "(", "type", "(", "inst", ")", ")", ")" ]
dot product of channel mapping matrix to channel data .
train
false
24,005
def _has_access_to_course(user, access_level, course_key): if ((user is None) or (not user.is_authenticated())): debug('Deny: no user or anon user') return ACCESS_DENIED if ((not in_preview_mode()) and is_masquerading_as_student(user, course_key)): return ACCESS_DENIED if GlobalStaff().has_user(user): debug('Allow: user.is_staff') return ACCESS_GRANTED if (access_level not in ('staff', 'instructor')): log.debug('Error in access._has_access_to_course access_level=%s unknown', access_level) debug('Deny: unknown access level') return ACCESS_DENIED staff_access = (CourseStaffRole(course_key).has_user(user) or OrgStaffRole(course_key.org).has_user(user)) if (staff_access and (access_level == 'staff')): debug('Allow: user has course staff access') return ACCESS_GRANTED instructor_access = (CourseInstructorRole(course_key).has_user(user) or OrgInstructorRole(course_key.org).has_user(user)) if (instructor_access and (access_level in ('staff', 'instructor'))): debug('Allow: user has course instructor access') return ACCESS_GRANTED debug('Deny: user did not have correct access') return ACCESS_DENIED
[ "def", "_has_access_to_course", "(", "user", ",", "access_level", ",", "course_key", ")", ":", "if", "(", "(", "user", "is", "None", ")", "or", "(", "not", "user", ".", "is_authenticated", "(", ")", ")", ")", ":", "debug", "(", "'Deny: no user or anon user'", ")", "return", "ACCESS_DENIED", "if", "(", "(", "not", "in_preview_mode", "(", ")", ")", "and", "is_masquerading_as_student", "(", "user", ",", "course_key", ")", ")", ":", "return", "ACCESS_DENIED", "if", "GlobalStaff", "(", ")", ".", "has_user", "(", "user", ")", ":", "debug", "(", "'Allow: user.is_staff'", ")", "return", "ACCESS_GRANTED", "if", "(", "access_level", "not", "in", "(", "'staff'", ",", "'instructor'", ")", ")", ":", "log", ".", "debug", "(", "'Error in access._has_access_to_course access_level=%s unknown'", ",", "access_level", ")", "debug", "(", "'Deny: unknown access level'", ")", "return", "ACCESS_DENIED", "staff_access", "=", "(", "CourseStaffRole", "(", "course_key", ")", ".", "has_user", "(", "user", ")", "or", "OrgStaffRole", "(", "course_key", ".", "org", ")", ".", "has_user", "(", "user", ")", ")", "if", "(", "staff_access", "and", "(", "access_level", "==", "'staff'", ")", ")", ":", "debug", "(", "'Allow: user has course staff access'", ")", "return", "ACCESS_GRANTED", "instructor_access", "=", "(", "CourseInstructorRole", "(", "course_key", ")", ".", "has_user", "(", "user", ")", "or", "OrgInstructorRole", "(", "course_key", ".", "org", ")", ".", "has_user", "(", "user", ")", ")", "if", "(", "instructor_access", "and", "(", "access_level", "in", "(", "'staff'", ",", "'instructor'", ")", ")", ")", ":", "debug", "(", "'Allow: user has course instructor access'", ")", "return", "ACCESS_GRANTED", "debug", "(", "'Deny: user did not have correct access'", ")", "return", "ACCESS_DENIED" ]
returns true if the given user has access_level access to the course with the given course_key .
train
false
24,007
def test_compound_gates(): circuit = ((((YGate(0) * ZGate(0)) * XGate(0)) * HadamardGate(0)) * Qubit('00')) answer = represent(circuit, nqubits=2) assert (Matrix([(I / sqrt(2)), (I / sqrt(2)), 0, 0]) == answer)
[ "def", "test_compound_gates", "(", ")", ":", "circuit", "=", "(", "(", "(", "(", "YGate", "(", "0", ")", "*", "ZGate", "(", "0", ")", ")", "*", "XGate", "(", "0", ")", ")", "*", "HadamardGate", "(", "0", ")", ")", "*", "Qubit", "(", "'00'", ")", ")", "answer", "=", "represent", "(", "circuit", ",", "nqubits", "=", "2", ")", "assert", "(", "Matrix", "(", "[", "(", "I", "/", "sqrt", "(", "2", ")", ")", ",", "(", "I", "/", "sqrt", "(", "2", ")", ")", ",", "0", ",", "0", "]", ")", "==", "answer", ")" ]
test a compound gate representation .
train
false
24,009
def whats_this_helper(desc, include_more_link=False): title = desc.name help_url = desc.help if (not help_url): help_url = ('help://search?' + urlencode({'id': desc.qualified_name})) description = desc.description template = ['<h3>{0}</h3>'.format(escape(title))] if description: template.append('<p>{0}</p>'.format(escape(description))) if (help_url and include_more_link): template.append("<a href='{0}'>more...</a>".format(escape(help_url))) return '\n'.join(template)
[ "def", "whats_this_helper", "(", "desc", ",", "include_more_link", "=", "False", ")", ":", "title", "=", "desc", ".", "name", "help_url", "=", "desc", ".", "help", "if", "(", "not", "help_url", ")", ":", "help_url", "=", "(", "'help://search?'", "+", "urlencode", "(", "{", "'id'", ":", "desc", ".", "qualified_name", "}", ")", ")", "description", "=", "desc", ".", "description", "template", "=", "[", "'<h3>{0}</h3>'", ".", "format", "(", "escape", "(", "title", ")", ")", "]", "if", "description", ":", "template", ".", "append", "(", "'<p>{0}</p>'", ".", "format", "(", "escape", "(", "description", ")", ")", ")", "if", "(", "help_url", "and", "include_more_link", ")", ":", "template", ".", "append", "(", "\"<a href='{0}'>more...</a>\"", ".", "format", "(", "escape", "(", "help_url", ")", ")", ")", "return", "'\\n'", ".", "join", "(", "template", ")" ]
a whats this text construction helper .
train
false
24,012
def _get_exif_orientation(exif): exif_dict = piexif.load(exif) return exif_dict['0th'].get(piexif.ImageIFD.Orientation)
[ "def", "_get_exif_orientation", "(", "exif", ")", ":", "exif_dict", "=", "piexif", ".", "load", "(", "exif", ")", "return", "exif_dict", "[", "'0th'", "]", ".", "get", "(", "piexif", ".", "ImageIFD", ".", "Orientation", ")" ]
return the orientation value for the given image object .
train
false
24,013
def ascendant_addresses_to_globs(address_mapper, ascendant_addresses): pattern = address_mapper.build_pattern patterns = [join(f, pattern) for f in _recursive_dirname(ascendant_addresses.directory)] return PathGlobs.create_from_specs(u'', patterns)
[ "def", "ascendant_addresses_to_globs", "(", "address_mapper", ",", "ascendant_addresses", ")", ":", "pattern", "=", "address_mapper", ".", "build_pattern", "patterns", "=", "[", "join", "(", "f", ",", "pattern", ")", "for", "f", "in", "_recursive_dirname", "(", "ascendant_addresses", ".", "directory", ")", "]", "return", "PathGlobs", ".", "create_from_specs", "(", "u''", ",", "patterns", ")" ]
given an ascendantaddresses object .
train
false
24,014
def ifnotequal(parser, token): return do_ifequal(parser, token, True)
[ "def", "ifnotequal", "(", "parser", ",", "token", ")", ":", "return", "do_ifequal", "(", "parser", ",", "token", ",", "True", ")" ]
output the contents of the block if the two arguments are not equal .
train
false
24,015
def panel_index(time, panels, names=None): if (names is None): names = ['time', 'panel'] (time, panels) = _ensure_like_indices(time, panels) return MultiIndex.from_arrays([time, panels], sortorder=None, names=names)
[ "def", "panel_index", "(", "time", ",", "panels", ",", "names", "=", "None", ")", ":", "if", "(", "names", "is", "None", ")", ":", "names", "=", "[", "'time'", ",", "'panel'", "]", "(", "time", ",", "panels", ")", "=", "_ensure_like_indices", "(", "time", ",", "panels", ")", "return", "MultiIndex", ".", "from_arrays", "(", "[", "time", ",", "panels", "]", ",", "sortorder", "=", "None", ",", "names", "=", "names", ")" ]
returns a multi-index suitable for a panel-like dataframe parameters time : array-like time index .
train
true
24,016
def update_progress(opts, progress, progress_iter, out): try: progress_outputter = salt.loader.outputters(opts)[out] except KeyError: log.warning('Progress outputter not available.') return False progress_outputter(progress, progress_iter)
[ "def", "update_progress", "(", "opts", ",", "progress", ",", "progress_iter", ",", "out", ")", ":", "try", ":", "progress_outputter", "=", "salt", ".", "loader", ".", "outputters", "(", "opts", ")", "[", "out", "]", "except", "KeyError", ":", "log", ".", "warning", "(", "'Progress outputter not available.'", ")", "return", "False", "progress_outputter", "(", "progress", ",", "progress_iter", ")" ]
update the progress iterator for the given outputter .
train
true
24,017
def markers(): print(('Available markers: \n - ' + '\n - '.join(_marker_types)))
[ "def", "markers", "(", ")", ":", "print", "(", "(", "'Available markers: \\n - '", "+", "'\\n - '", ".", "join", "(", "_marker_types", ")", ")", ")" ]
prints a list of valid marker types for scatter() returns: none .
train
false
24,018
def _resolve_aliases(bindings): for (var, value) in bindings.items(): while (isinstance(value, Variable) and (value in bindings)): value = bindings[var] = bindings[value]
[ "def", "_resolve_aliases", "(", "bindings", ")", ":", "for", "(", "var", ",", "value", ")", "in", "bindings", ".", "items", "(", ")", ":", "while", "(", "isinstance", "(", "value", ",", "Variable", ")", "and", "(", "value", "in", "bindings", ")", ")", ":", "value", "=", "bindings", "[", "var", "]", "=", "bindings", "[", "value", "]" ]
replace any bound aliased vars with their binding; and replace any unbound aliased vars with their representative var .
train
false
24,019
def alterDataBit(bit, state): global dataReg if (state == 0): dataReg = (dataReg & (~ (2 ** bit))) else: dataReg = (dataReg | (2 ** bit)) port.DlPortWritePortUchar(baseAddress, dataReg)
[ "def", "alterDataBit", "(", "bit", ",", "state", ")", ":", "global", "dataReg", "if", "(", "state", "==", "0", ")", ":", "dataReg", "=", "(", "dataReg", "&", "(", "~", "(", "2", "**", "bit", ")", ")", ")", "else", ":", "dataReg", "=", "(", "dataReg", "|", "(", "2", "**", "bit", ")", ")", "port", ".", "DlPortWritePortUchar", "(", "baseAddress", ",", "dataReg", ")" ]
toggle any data register bit to the state given .
train
false
24,020
def metadef_resource_type_get(context, resource_type_name, session=None): session = (session or get_session()) return metadef_resource_type_api.get(context, resource_type_name, session)
[ "def", "metadef_resource_type_get", "(", "context", ",", "resource_type_name", ",", "session", "=", "None", ")", ":", "session", "=", "(", "session", "or", "get_session", "(", ")", ")", "return", "metadef_resource_type_api", ".", "get", "(", "context", ",", "resource_type_name", ",", "session", ")" ]
get a resource type .
train
false
24,021
def substitutetype(ty): ty = ty.replace('std::', '') ty = re.sub('(.*)<(.*)>', '\\1< \\2 >', ty) return ty
[ "def", "substitutetype", "(", "ty", ")", ":", "ty", "=", "ty", ".", "replace", "(", "'std::'", ",", "''", ")", "ty", "=", "re", ".", "sub", "(", "'(.*)<(.*)>'", ",", "'\\\\1< \\\\2 >'", ",", "ty", ")", "return", "ty" ]
fix types to match the standard format in the final docs .
train
false
24,022
def xml_to_unicode(raw, verbose=False, strip_encoding_pats=False, resolve_entities=False, assume_utf8=False): if (not raw): return (u'', None) (raw, encoding) = detect_xml_encoding(raw, verbose=verbose, assume_utf8=assume_utf8) if (not isinstance(raw, unicode)): raw = raw.decode(encoding, u'replace') if strip_encoding_pats: raw = strip_encoding_declarations(raw) if resolve_entities: raw = substitute_entites(raw) return (raw, encoding)
[ "def", "xml_to_unicode", "(", "raw", ",", "verbose", "=", "False", ",", "strip_encoding_pats", "=", "False", ",", "resolve_entities", "=", "False", ",", "assume_utf8", "=", "False", ")", ":", "if", "(", "not", "raw", ")", ":", "return", "(", "u''", ",", "None", ")", "(", "raw", ",", "encoding", ")", "=", "detect_xml_encoding", "(", "raw", ",", "verbose", "=", "verbose", ",", "assume_utf8", "=", "assume_utf8", ")", "if", "(", "not", "isinstance", "(", "raw", ",", "unicode", ")", ")", ":", "raw", "=", "raw", ".", "decode", "(", "encoding", ",", "u'replace'", ")", "if", "strip_encoding_pats", ":", "raw", "=", "strip_encoding_declarations", "(", "raw", ")", "if", "resolve_entities", ":", "raw", "=", "substitute_entites", "(", "raw", ")", "return", "(", "raw", ",", "encoding", ")" ]
force conversion of byte string to unicode .
train
false
24,023
def get_html_help_exe(): if (os.name == 'nt'): hhc_base = 'C:\\Program Files%s\\HTML Help Workshop\\hhc.exe' for hhc_exe in ((hhc_base % ''), (hhc_base % ' (x86)')): if osp.isfile(hhc_exe): return hhc_exe else: return
[ "def", "get_html_help_exe", "(", ")", ":", "if", "(", "os", ".", "name", "==", "'nt'", ")", ":", "hhc_base", "=", "'C:\\\\Program Files%s\\\\HTML Help Workshop\\\\hhc.exe'", "for", "hhc_exe", "in", "(", "(", "hhc_base", "%", "''", ")", ",", "(", "hhc_base", "%", "' (x86)'", ")", ")", ":", "if", "osp", ".", "isfile", "(", "hhc_exe", ")", ":", "return", "hhc_exe", "else", ":", "return" ]
return html help workshop executable path .
train
false
24,024
def default_ssl_validate(): return SSL_VALIDATE.get()
[ "def", "default_ssl_validate", "(", ")", ":", "return", "SSL_VALIDATE", ".", "get", "(", ")" ]
choose whether hue should validate certificates received from the server .
train
false
24,025
def _get_comparison_spec(pkgver): match = re.match('^([<>])?(=)?([^<>=]+)$', pkgver) if (not match): raise CommandExecutionError("Invalid version specification '{0}'.".format(pkgver)) (gt_lt, eq, verstr) = match.groups() oper = (gt_lt or '') oper += (eq or '') if (oper in ('=', '')): oper = '==' return (oper, verstr)
[ "def", "_get_comparison_spec", "(", "pkgver", ")", ":", "match", "=", "re", ".", "match", "(", "'^([<>])?(=)?([^<>=]+)$'", ",", "pkgver", ")", "if", "(", "not", "match", ")", ":", "raise", "CommandExecutionError", "(", "\"Invalid version specification '{0}'.\"", ".", "format", "(", "pkgver", ")", ")", "(", "gt_lt", ",", "eq", ",", "verstr", ")", "=", "match", ".", "groups", "(", ")", "oper", "=", "(", "gt_lt", "or", "''", ")", "oper", "+=", "(", "eq", "or", "''", ")", "if", "(", "oper", "in", "(", "'='", ",", "''", ")", ")", ":", "oper", "=", "'=='", "return", "(", "oper", ",", "verstr", ")" ]
return a tuple containing the comparison operator and the version .
train
false
24,026
def _get_translations(): ctx = _request_ctx_stack.top if (ctx is None): return None if ('babel' not in ctx.app.extensions): return None translations = getattr(ctx, 'wtforms_translations', None) if (translations is None): dirname = messages_path() translations = support.Translations.load(dirname, [get_locale()], domain='wtforms') ctx.wtforms_translations = translations return translations
[ "def", "_get_translations", "(", ")", ":", "ctx", "=", "_request_ctx_stack", ".", "top", "if", "(", "ctx", "is", "None", ")", ":", "return", "None", "if", "(", "'babel'", "not", "in", "ctx", ".", "app", ".", "extensions", ")", ":", "return", "None", "translations", "=", "getattr", "(", "ctx", ",", "'wtforms_translations'", ",", "None", ")", "if", "(", "translations", "is", "None", ")", ":", "dirname", "=", "messages_path", "(", ")", "translations", "=", "support", ".", "Translations", ".", "load", "(", "dirname", ",", "[", "get_locale", "(", ")", "]", ",", "domain", "=", "'wtforms'", ")", "ctx", ".", "wtforms_translations", "=", "translations", "return", "translations" ]
returns the correct gettext translations .
train
false
24,027
def assert_has_paths(test_case, expected_paths, parent_path): missing_paths = [] for path in expected_paths: if (not parent_path.preauthChild(path).exists()): missing_paths.append(path) if missing_paths: test_case.fail('Missing paths: {}'.format(missing_paths))
[ "def", "assert_has_paths", "(", "test_case", ",", "expected_paths", ",", "parent_path", ")", ":", "missing_paths", "=", "[", "]", "for", "path", "in", "expected_paths", ":", "if", "(", "not", "parent_path", ".", "preauthChild", "(", "path", ")", ".", "exists", "(", ")", ")", ":", "missing_paths", ".", "append", "(", "path", ")", "if", "missing_paths", ":", "test_case", ".", "fail", "(", "'Missing paths: {}'", ".", "format", "(", "missing_paths", ")", ")" ]
fail if any of the expected_paths are not existing relative paths of parent_path .
train
false
24,028
def get_sentiment_entities(service, document): (sentiments, entities) = analyze_document(service, document) score = sentiments.get('score') return (score, entities)
[ "def", "get_sentiment_entities", "(", "service", ",", "document", ")", ":", "(", "sentiments", ",", "entities", ")", "=", "analyze_document", "(", "service", ",", "document", ")", "score", "=", "sentiments", ".", "get", "(", "'score'", ")", "return", "(", "score", ",", "entities", ")" ]
compute the overall sentiment volume in the document .
train
false
24,029
@deprecated def get_master(): try: import xmlrpc.client as xmlrpcclient except ImportError: import xmlrpclib as xmlrpcclient uri = os.environ['ROS_MASTER_URI'] return xmlrpcclient.ServerProxy(uri)
[ "@", "deprecated", "def", "get_master", "(", ")", ":", "try", ":", "import", "xmlrpc", ".", "client", "as", "xmlrpcclient", "except", "ImportError", ":", "import", "xmlrpclib", "as", "xmlrpcclient", "uri", "=", "os", ".", "environ", "[", "'ROS_MASTER_URI'", "]", "return", "xmlrpcclient", ".", "ServerProxy", "(", "uri", ")" ]
provides the minion with the name of its master .
train
false
24,030
def warning_msg(text): msg(colorize(('Warning: ' + str(text)), 'yellow'))
[ "def", "warning_msg", "(", "text", ")", ":", "msg", "(", "colorize", "(", "(", "'Warning: '", "+", "str", "(", "text", ")", ")", ",", "'yellow'", ")", ")" ]
colorize warning message with prefix .
train
false
24,031
def check_n_jobs(n_jobs, allow_cuda=False): if (not isinstance(n_jobs, int)): if (not allow_cuda): raise ValueError('n_jobs must be an integer') elif ((not isinstance(n_jobs, string_types)) or (n_jobs != 'cuda')): raise ValueError('n_jobs must be an integer, or "cuda"') elif _force_serial: n_jobs = 1 logger.info('... MNE_FORCE_SERIAL set. Processing in forced serial mode.') elif (n_jobs <= 0): try: import multiprocessing n_cores = multiprocessing.cpu_count() n_jobs = min(((n_cores + n_jobs) + 1), n_cores) if (n_jobs <= 0): raise ValueError(("If n_jobs has a negative value it must not be less than the number of CPUs present. You've got %s CPUs" % n_cores)) except ImportError: if (n_jobs != 1): warn('multiprocessing not installed. Cannot run in parallel.') n_jobs = 1 return n_jobs
[ "def", "check_n_jobs", "(", "n_jobs", ",", "allow_cuda", "=", "False", ")", ":", "if", "(", "not", "isinstance", "(", "n_jobs", ",", "int", ")", ")", ":", "if", "(", "not", "allow_cuda", ")", ":", "raise", "ValueError", "(", "'n_jobs must be an integer'", ")", "elif", "(", "(", "not", "isinstance", "(", "n_jobs", ",", "string_types", ")", ")", "or", "(", "n_jobs", "!=", "'cuda'", ")", ")", ":", "raise", "ValueError", "(", "'n_jobs must be an integer, or \"cuda\"'", ")", "elif", "_force_serial", ":", "n_jobs", "=", "1", "logger", ".", "info", "(", "'... MNE_FORCE_SERIAL set. Processing in forced serial mode.'", ")", "elif", "(", "n_jobs", "<=", "0", ")", ":", "try", ":", "import", "multiprocessing", "n_cores", "=", "multiprocessing", ".", "cpu_count", "(", ")", "n_jobs", "=", "min", "(", "(", "(", "n_cores", "+", "n_jobs", ")", "+", "1", ")", ",", "n_cores", ")", "if", "(", "n_jobs", "<=", "0", ")", ":", "raise", "ValueError", "(", "(", "\"If n_jobs has a negative value it must not be less than the number of CPUs present. You've got %s CPUs\"", "%", "n_cores", ")", ")", "except", "ImportError", ":", "if", "(", "n_jobs", "!=", "1", ")", ":", "warn", "(", "'multiprocessing not installed. Cannot run in parallel.'", ")", "n_jobs", "=", "1", "return", "n_jobs" ]
check n_jobs in particular for negative values .
train
false
24,033
def CreateSigningKeyset(name): return _CreateKeyset(name, keyinfo.SIGN_AND_VERIFY, keyinfo.HMAC_SHA1)
[ "def", "CreateSigningKeyset", "(", "name", ")", ":", "return", "_CreateKeyset", "(", "name", ",", "keyinfo", ".", "SIGN_AND_VERIFY", ",", "keyinfo", ".", "HMAC_SHA1", ")" ]
returns a keyczar keyset to be used for signing and signature verification .
train
false
24,036
@memoized def getColor(value, default=None): if isinstance(value, Color): return value value = str(value).strip().lower() if ((value == 'transparent') or (value == 'none')): return default if (value in COLOR_BY_NAME): return COLOR_BY_NAME[value] if (value.startswith('#') and (len(value) == 4)): value = (((((('#' + value[1]) + value[1]) + value[2]) + value[2]) + value[3]) + value[3]) elif rgb_re.search(value): (r, g, b) = [int(x) for x in rgb_re.search(value).groups()] value = ('#%02x%02x%02x' % (r, g, b)) else: pass return toColor(value, default)
[ "@", "memoized", "def", "getColor", "(", "value", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "Color", ")", ":", "return", "value", "value", "=", "str", "(", "value", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "(", "(", "value", "==", "'transparent'", ")", "or", "(", "value", "==", "'none'", ")", ")", ":", "return", "default", "if", "(", "value", "in", "COLOR_BY_NAME", ")", ":", "return", "COLOR_BY_NAME", "[", "value", "]", "if", "(", "value", ".", "startswith", "(", "'#'", ")", "and", "(", "len", "(", "value", ")", "==", "4", ")", ")", ":", "value", "=", "(", "(", "(", "(", "(", "(", "'#'", "+", "value", "[", "1", "]", ")", "+", "value", "[", "1", "]", ")", "+", "value", "[", "2", "]", ")", "+", "value", "[", "2", "]", ")", "+", "value", "[", "3", "]", ")", "+", "value", "[", "3", "]", ")", "elif", "rgb_re", ".", "search", "(", "value", ")", ":", "(", "r", ",", "g", ",", "b", ")", "=", "[", "int", "(", "x", ")", "for", "x", "in", "rgb_re", ".", "search", "(", "value", ")", ".", "groups", "(", ")", "]", "value", "=", "(", "'#%02x%02x%02x'", "%", "(", "r", ",", "g", ",", "b", ")", ")", "else", ":", "pass", "return", "toColor", "(", "value", ",", "default", ")" ]
convert to color value .
train
true
24,038
def follow_portion(twitter, screen_name, cursor=(-1), followers=True): kwargs = dict(screen_name=screen_name, cursor=cursor) if followers: t = twitter.followers.ids(**kwargs) else: t = twitter.friends.ids(**kwargs) return (t['ids'], t['next_cursor'])
[ "def", "follow_portion", "(", "twitter", ",", "screen_name", ",", "cursor", "=", "(", "-", "1", ")", ",", "followers", "=", "True", ")", ":", "kwargs", "=", "dict", "(", "screen_name", "=", "screen_name", ",", "cursor", "=", "cursor", ")", "if", "followers", ":", "t", "=", "twitter", ".", "followers", ".", "ids", "(", "**", "kwargs", ")", "else", ":", "t", "=", "twitter", ".", "friends", ".", "ids", "(", "**", "kwargs", ")", "return", "(", "t", "[", "'ids'", "]", ",", "t", "[", "'next_cursor'", "]", ")" ]
get a portion of followers/following for a user .
train
false