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
35,397
def test_hist_flush(hist, xonsh_builtins): hf = hist.flush() assert (hf is None) xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() hist.append({'inp': 'still alive?', 'rtn': 0, 'out': 'yes'}) hf = hist.flush() assert (hf is not None) while hf.is_alive(): pass with LazyJSON(hist.filename) as lj: assert (len(lj['cmds']) == 1) cmd = lj['cmds'][0] assert (cmd['inp'] == 'still alive?') assert (not cmd.get('out', None))
[ "def", "test_hist_flush", "(", "hist", ",", "xonsh_builtins", ")", ":", "hf", "=", "hist", ".", "flush", "(", ")", "assert", "(", "hf", "is", "None", ")", "xonsh_builtins", ".", "__xonsh_env__", "[", "'HISTCONTROL'", "]", "=", "set", "(", ")", "hist", ".", "append", "(", "{", "'inp'", ":", "'still alive?'", ",", "'rtn'", ":", "0", ",", "'out'", ":", "'yes'", "}", ")", "hf", "=", "hist", ".", "flush", "(", ")", "assert", "(", "hf", "is", "not", "None", ")", "while", "hf", ".", "is_alive", "(", ")", ":", "pass", "with", "LazyJSON", "(", "hist", ".", "filename", ")", "as", "lj", ":", "assert", "(", "len", "(", "lj", "[", "'cmds'", "]", ")", "==", "1", ")", "cmd", "=", "lj", "[", "'cmds'", "]", "[", "0", "]", "assert", "(", "cmd", "[", "'inp'", "]", "==", "'still alive?'", ")", "assert", "(", "not", "cmd", ".", "get", "(", "'out'", ",", "None", ")", ")" ]
verify explicit flushing of the history works .
train
false
35,398
def get_registration_backend(): backend = None backend_class = None registration_backend_string = getattr(facebook_settings, 'FACEBOOK_REGISTRATION_BACKEND', None) if registration_backend_string: backend_class = get_class_from_string(registration_backend_string) if backend_class: backend = backend_class() return backend
[ "def", "get_registration_backend", "(", ")", ":", "backend", "=", "None", "backend_class", "=", "None", "registration_backend_string", "=", "getattr", "(", "facebook_settings", ",", "'FACEBOOK_REGISTRATION_BACKEND'", ",", "None", ")", "if", "registration_backend_string", ":", "backend_class", "=", "get_class_from_string", "(", "registration_backend_string", ")", "if", "backend_class", ":", "backend", "=", "backend_class", "(", ")", "return", "backend" ]
ensures compatability with the new and old version of django registration .
train
false
35,399
def get_public_names(l): return [x for x in l if (x[0] != '_')]
[ "def", "get_public_names", "(", "l", ")", ":", "return", "[", "x", "for", "x", "in", "l", "if", "(", "x", "[", "0", "]", "!=", "'_'", ")", "]" ]
only return names from iterator l without a leading underscore .
train
false
35,400
@should_dump_psutil def stop_psutil_dump(): cancel_thread(SAVE_PSUTIL_PTR) dump_psutil()
[ "@", "should_dump_psutil", "def", "stop_psutil_dump", "(", ")", ":", "cancel_thread", "(", "SAVE_PSUTIL_PTR", ")", "dump_psutil", "(", ")" ]
save profiling information .
train
false
35,401
def format_object(name, object_, docstring=None): template = '.. py:attribute:: ckan.plugins.toolkit.{obj}\n\n{docstring}\n\n' docstring = (docstring or inspect.getdoc(object_)) if (docstring is None): docstring = '' else: docstring = '\n'.join([(' ' + line) for line in docstring.split('\n')]) return template.format(obj=name, docstring=docstring)
[ "def", "format_object", "(", "name", ",", "object_", ",", "docstring", "=", "None", ")", ":", "template", "=", "'.. py:attribute:: ckan.plugins.toolkit.{obj}\\n\\n{docstring}\\n\\n'", "docstring", "=", "(", "docstring", "or", "inspect", ".", "getdoc", "(", "object_", ")", ")", "if", "(", "docstring", "is", "None", ")", ":", "docstring", "=", "''", "else", ":", "docstring", "=", "'\\n'", ".", "join", "(", "[", "(", "' '", "+", "line", ")", "for", "line", "in", "docstring", ".", "split", "(", "'\\n'", ")", "]", ")", "return", "template", ".", "format", "(", "obj", "=", "name", ",", "docstring", "=", "docstring", ")" ]
return a sphinx .
train
false
35,402
def zdt6(individual): g = (1 + (9 * ((sum(individual[1:]) / (len(individual) - 1)) ** 0.25))) f1 = (1 - (exp(((-4) * individual[0])) * (sin(((6 * pi) * individual[0])) ** 6))) f2 = (g * (1 - ((f1 / g) ** 2))) return (f1, f2)
[ "def", "zdt6", "(", "individual", ")", ":", "g", "=", "(", "1", "+", "(", "9", "*", "(", "(", "sum", "(", "individual", "[", "1", ":", "]", ")", "/", "(", "len", "(", "individual", ")", "-", "1", ")", ")", "**", "0.25", ")", ")", ")", "f1", "=", "(", "1", "-", "(", "exp", "(", "(", "(", "-", "4", ")", "*", "individual", "[", "0", "]", ")", ")", "*", "(", "sin", "(", "(", "(", "6", "*", "pi", ")", "*", "individual", "[", "0", "]", ")", ")", "**", "6", ")", ")", ")", "f2", "=", "(", "g", "*", "(", "1", "-", "(", "(", "f1", "/", "g", ")", "**", "2", ")", ")", ")", "return", "(", "f1", ",", "f2", ")" ]
zdt6 multiobjective function .
train
false
35,403
def _resample_stim_channels(stim_data, up, down): stim_data = np.atleast_2d(stim_data) (n_stim_channels, n_samples) = stim_data.shape ratio = (float(up) / down) resampled_n_samples = int(round((n_samples * ratio))) stim_resampled = np.zeros((n_stim_channels, resampled_n_samples)) sample_picks = np.minimum((np.arange(resampled_n_samples) / ratio).astype(int), (n_samples - 1)) windows = zip(sample_picks, np.r_[(sample_picks[1:], n_samples)]) for (window_i, window) in enumerate(windows): for (stim_num, stim) in enumerate(stim_data): nonzero = stim[window[0]:window[1]].nonzero()[0] if (len(nonzero) > 0): val = stim[(window[0] + nonzero[0])] else: val = stim[window[0]] stim_resampled[(stim_num, window_i)] = val return stim_resampled
[ "def", "_resample_stim_channels", "(", "stim_data", ",", "up", ",", "down", ")", ":", "stim_data", "=", "np", ".", "atleast_2d", "(", "stim_data", ")", "(", "n_stim_channels", ",", "n_samples", ")", "=", "stim_data", ".", "shape", "ratio", "=", "(", "float", "(", "up", ")", "/", "down", ")", "resampled_n_samples", "=", "int", "(", "round", "(", "(", "n_samples", "*", "ratio", ")", ")", ")", "stim_resampled", "=", "np", ".", "zeros", "(", "(", "n_stim_channels", ",", "resampled_n_samples", ")", ")", "sample_picks", "=", "np", ".", "minimum", "(", "(", "np", ".", "arange", "(", "resampled_n_samples", ")", "/", "ratio", ")", ".", "astype", "(", "int", ")", ",", "(", "n_samples", "-", "1", ")", ")", "windows", "=", "zip", "(", "sample_picks", ",", "np", ".", "r_", "[", "(", "sample_picks", "[", "1", ":", "]", ",", "n_samples", ")", "]", ")", "for", "(", "window_i", ",", "window", ")", "in", "enumerate", "(", "windows", ")", ":", "for", "(", "stim_num", ",", "stim", ")", "in", "enumerate", "(", "stim_data", ")", ":", "nonzero", "=", "stim", "[", "window", "[", "0", "]", ":", "window", "[", "1", "]", "]", ".", "nonzero", "(", ")", "[", "0", "]", "if", "(", "len", "(", "nonzero", ")", ">", "0", ")", ":", "val", "=", "stim", "[", "(", "window", "[", "0", "]", "+", "nonzero", "[", "0", "]", ")", "]", "else", ":", "val", "=", "stim", "[", "window", "[", "0", "]", "]", "stim_resampled", "[", "(", "stim_num", ",", "window_i", ")", "]", "=", "val", "return", "stim_resampled" ]
resample stim channels .
train
false
35,404
def test_uninstall_gui_scripts(script): pkg_name = 'gui_pkg' pkg_path = create_test_package_with_setup(script, name=pkg_name, version='0.1', entry_points={'gui_scripts': ['test_ = distutils_install']}) script_name = script.bin_path.join('test_') script.pip('install', pkg_path) assert script_name.exists script.pip('uninstall', pkg_name, '-y') assert (not script_name.exists)
[ "def", "test_uninstall_gui_scripts", "(", "script", ")", ":", "pkg_name", "=", "'gui_pkg'", "pkg_path", "=", "create_test_package_with_setup", "(", "script", ",", "name", "=", "pkg_name", ",", "version", "=", "'0.1'", ",", "entry_points", "=", "{", "'gui_scripts'", ":", "[", "'test_ = distutils_install'", "]", "}", ")", "script_name", "=", "script", ".", "bin_path", ".", "join", "(", "'test_'", ")", "script", ".", "pip", "(", "'install'", ",", "pkg_path", ")", "assert", "script_name", ".", "exists", "script", ".", "pip", "(", "'uninstall'", ",", "pkg_name", ",", "'-y'", ")", "assert", "(", "not", "script_name", ".", "exists", ")" ]
make sure that uninstall removes gui scripts .
train
false
35,405
def getRandomWithMods(inputSpace, maxChanges): size = len(inputSpace) ind = np.random.random_integers(0, (size - 1), 1)[0] value = copy.deepcopy(inputSpace[ind]) if (maxChanges == 0): return value return modifyBits(value, maxChanges)
[ "def", "getRandomWithMods", "(", "inputSpace", ",", "maxChanges", ")", ":", "size", "=", "len", "(", "inputSpace", ")", "ind", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "(", "size", "-", "1", ")", ",", "1", ")", "[", "0", "]", "value", "=", "copy", ".", "deepcopy", "(", "inputSpace", "[", "ind", "]", ")", "if", "(", "maxChanges", "==", "0", ")", ":", "return", "value", "return", "modifyBits", "(", "value", ",", "maxChanges", ")" ]
returns a random selection from the inputspace with randomly modified up to maxchanges number of bits .
train
true
35,406
def validate_fasta(input_fasta_fp, mapping_fp, output_dir, tree_fp=None, tree_subset=False, tree_exact_match=False, same_seq_lens=False, all_ids_found=False, suppress_barcode_checks=False, suppress_primer_checks=False): verify_valid_fasta_format(input_fasta_fp) fasta_report = run_fasta_checks(input_fasta_fp, mapping_fp, tree_fp, tree_subset, tree_exact_match, same_seq_lens, all_ids_found, suppress_barcode_checks, suppress_primer_checks) write_log_file(output_dir, input_fasta_fp, fasta_report)
[ "def", "validate_fasta", "(", "input_fasta_fp", ",", "mapping_fp", ",", "output_dir", ",", "tree_fp", "=", "None", ",", "tree_subset", "=", "False", ",", "tree_exact_match", "=", "False", ",", "same_seq_lens", "=", "False", ",", "all_ids_found", "=", "False", ",", "suppress_barcode_checks", "=", "False", ",", "suppress_primer_checks", "=", "False", ")", ":", "verify_valid_fasta_format", "(", "input_fasta_fp", ")", "fasta_report", "=", "run_fasta_checks", "(", "input_fasta_fp", ",", "mapping_fp", ",", "tree_fp", ",", "tree_subset", ",", "tree_exact_match", ",", "same_seq_lens", ",", "all_ids_found", ",", "suppress_barcode_checks", ",", "suppress_primer_checks", ")", "write_log_file", "(", "output_dir", ",", "input_fasta_fp", ",", "fasta_report", ")" ]
main function for validating demultiplexed fasta file input_fasta_fp: fasta filepath mapping_fp: mapping filepath output_dir: output directory tree_fp: newick tree filepath tree_subset: if true .
train
false
35,408
def parse_gs_handle(gs_handle): if gs_handle.startswith('/'): filesystem = gs_handle[1:].split('/', 1)[0] if (filesystem == 'gs'): gs_handle = gs_handle[4:] else: raise BackupValidationException(('Unsupported filesystem: %s' % filesystem)) tokens = gs_handle.split('/', 1) return ((tokens[0], '') if (len(tokens) == 1) else tuple(tokens))
[ "def", "parse_gs_handle", "(", "gs_handle", ")", ":", "if", "gs_handle", ".", "startswith", "(", "'/'", ")", ":", "filesystem", "=", "gs_handle", "[", "1", ":", "]", ".", "split", "(", "'/'", ",", "1", ")", "[", "0", "]", "if", "(", "filesystem", "==", "'gs'", ")", ":", "gs_handle", "=", "gs_handle", "[", "4", ":", "]", "else", ":", "raise", "BackupValidationException", "(", "(", "'Unsupported filesystem: %s'", "%", "filesystem", ")", ")", "tokens", "=", "gs_handle", ".", "split", "(", "'/'", ",", "1", ")", "return", "(", "(", "tokens", "[", "0", "]", ",", "''", ")", "if", "(", "len", "(", "tokens", ")", "==", "1", ")", "else", "tuple", "(", "tokens", ")", ")" ]
splits [/gs/]?bucket_name[/folder]*[/file]? to .
train
false
35,409
def _get_configuration(shop): configuration = cache.get(_get_cache_key(shop)) if (configuration is None): configuration = _cache_shop_configuration(shop) return configuration
[ "def", "_get_configuration", "(", "shop", ")", ":", "configuration", "=", "cache", ".", "get", "(", "_get_cache_key", "(", "shop", ")", ")", "if", "(", "configuration", "is", "None", ")", ":", "configuration", "=", "_cache_shop_configuration", "(", "shop", ")", "return", "configuration" ]
get global or shop specific configuration with caching .
train
false
35,411
def read_uint8(fid): return _unpack_simple(fid, '>u1', np.uint8)
[ "def", "read_uint8", "(", "fid", ")", ":", "return", "_unpack_simple", "(", "fid", ",", "'>u1'", ",", "np", ".", "uint8", ")" ]
read unsigned 8bit integer from bti file .
train
false
35,412
def test_suggested_column_names_with_alias(completer, complete_event): text = u'SELECT u. from users u' position = len(u'SELECT u.') result = set(completer.get_completions(Document(text=text, cursor_position=position), complete_event)) assert (set(result) == set(testdata.columns(u'users')))
[ "def", "test_suggested_column_names_with_alias", "(", "completer", ",", "complete_event", ")", ":", "text", "=", "u'SELECT u. from users u'", "position", "=", "len", "(", "u'SELECT u.'", ")", "result", "=", "set", "(", "completer", ".", "get_completions", "(", "Document", "(", "text", "=", "text", ",", "cursor_position", "=", "position", ")", ",", "complete_event", ")", ")", "assert", "(", "set", "(", "result", ")", "==", "set", "(", "testdata", ".", "columns", "(", "u'users'", ")", ")", ")" ]
suggest column names on table alias and dot .
train
false
35,413
def queue_loop(): global __signaled_, __signaled_first_ while __loop_: __semaphore_.acquire() __signaled_first_ = 0 __signaled_ = 0 queue_dispatcher()
[ "def", "queue_loop", "(", ")", ":", "global", "__signaled_", ",", "__signaled_first_", "while", "__loop_", ":", "__semaphore_", ".", "acquire", "(", ")", "__signaled_first_", "=", "0", "__signaled_", "=", "0", "queue_dispatcher", "(", ")" ]
an infinite loop running the codeintel in a background thread .
train
false
35,414
def CleanseComments(line): commentpos = line.find('//') if ((commentpos != (-1)) and (not IsCppString(line[:commentpos]))): line = line[:commentpos].rstrip() return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
[ "def", "CleanseComments", "(", "line", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "(", "(", "commentpos", "!=", "(", "-", "1", ")", ")", "and", "(", "not", "IsCppString", "(", "line", "[", ":", "commentpos", "]", ")", ")", ")", ":", "line", "=", "line", "[", ":", "commentpos", "]", ".", "rstrip", "(", ")", "return", "_RE_PATTERN_CLEANSE_LINE_C_COMMENTS", ".", "sub", "(", "''", ",", "line", ")" ]
removes //-comments and single-line c-style /* */ comments .
train
true
35,417
def testURL(url='http://www.htmltopdf.org', dest='test-website.pdf'): import urllib pdf = pisa.CreatePDF(urllib.urlopen(url), file(dest, 'wb'), log_warn=1, log_err=1, path=url, link_callback=pisa.pisaLinkLoader(url).getFileName) dumpErrors(pdf) if (not pdf.err): pisa.startViewer(dest)
[ "def", "testURL", "(", "url", "=", "'http://www.htmltopdf.org'", ",", "dest", "=", "'test-website.pdf'", ")", ":", "import", "urllib", "pdf", "=", "pisa", ".", "CreatePDF", "(", "urllib", ".", "urlopen", "(", "url", ")", ",", "file", "(", "dest", ",", "'wb'", ")", ",", "log_warn", "=", "1", ",", "log_err", "=", "1", ",", "path", "=", "url", ",", "link_callback", "=", "pisa", ".", "pisaLinkLoader", "(", "url", ")", ".", "getFileName", ")", "dumpErrors", "(", "pdf", ")", "if", "(", "not", "pdf", ".", "err", ")", ":", "pisa", ".", "startViewer", "(", "dest", ")" ]
loading from an url .
train
false
35,418
@check_job_permission def tasks(request, job): ttypes = request.GET.get('tasktype') tstates = request.GET.get('taskstate') ttext = request.GET.get('tasktext') pagenum = int(request.GET.get('page', 1)) pagenum = (((pagenum > 0) and pagenum) or 1) filters = {'task_types': ((ttypes and set(ttypes.split(','))) or None), 'task_states': ((tstates and set(tstates.split(','))) or None), 'task_text': ttext, 'pagenum': pagenum} jt = get_api(request.user, request.jt) task_list = jt.get_tasks(job.jobId, **filters) filter_params = copy_query_dict(request.GET, ('tasktype', 'taskstate', 'tasktext')).urlencode() return render('tasks.mako', request, {'request': request, 'filter_params': filter_params, 'job': job, 'task_list': task_list, 'tasktype': ttypes, 'taskstate': tstates, 'tasktext': ttext})
[ "@", "check_job_permission", "def", "tasks", "(", "request", ",", "job", ")", ":", "ttypes", "=", "request", ".", "GET", ".", "get", "(", "'tasktype'", ")", "tstates", "=", "request", ".", "GET", ".", "get", "(", "'taskstate'", ")", "ttext", "=", "request", ".", "GET", ".", "get", "(", "'tasktext'", ")", "pagenum", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "'page'", ",", "1", ")", ")", "pagenum", "=", "(", "(", "(", "pagenum", ">", "0", ")", "and", "pagenum", ")", "or", "1", ")", "filters", "=", "{", "'task_types'", ":", "(", "(", "ttypes", "and", "set", "(", "ttypes", ".", "split", "(", "','", ")", ")", ")", "or", "None", ")", ",", "'task_states'", ":", "(", "(", "tstates", "and", "set", "(", "tstates", ".", "split", "(", "','", ")", ")", ")", "or", "None", ")", ",", "'task_text'", ":", "ttext", ",", "'pagenum'", ":", "pagenum", "}", "jt", "=", "get_api", "(", "request", ".", "user", ",", "request", ".", "jt", ")", "task_list", "=", "jt", ".", "get_tasks", "(", "job", ".", "jobId", ",", "**", "filters", ")", "filter_params", "=", "copy_query_dict", "(", "request", ".", "GET", ",", "(", "'tasktype'", ",", "'taskstate'", ",", "'tasktext'", ")", ")", ".", "urlencode", "(", ")", "return", "render", "(", "'tasks.mako'", ",", "request", ",", "{", "'request'", ":", "request", ",", "'filter_params'", ":", "filter_params", ",", "'job'", ":", "job", ",", "'task_list'", ":", "task_list", ",", "'tasktype'", ":", "ttypes", ",", "'taskstate'", ":", "tstates", ",", "'tasktext'", ":", "ttext", "}", ")" ]
we get here from /jobs/job/tasks?filterargs .
train
false
35,419
def make_policy(bucket_name, prefix, allow_get_location=False): bucket_arn = ('arn:aws:s3:::' + bucket_name) prefix_arn = 'arn:aws:s3:::{0}/{1}/*'.format(bucket_name, prefix) structure = {'Version': '2012-10-17', 'Statement': [{'Action': ['s3:ListBucket'], 'Effect': 'Allow', 'Resource': [bucket_arn], 'Condition': {'StringLike': {'s3:prefix': [(prefix + '/*')]}}}, {'Effect': 'Allow', 'Action': ['s3:PutObject', 's3:GetObject'], 'Resource': [prefix_arn]}]} if allow_get_location: structure['Statement'].append({'Action': ['s3:GetBucketLocation'], 'Effect': 'Allow', 'Resource': [bucket_arn]}) return json.dumps(structure, indent=2)
[ "def", "make_policy", "(", "bucket_name", ",", "prefix", ",", "allow_get_location", "=", "False", ")", ":", "bucket_arn", "=", "(", "'arn:aws:s3:::'", "+", "bucket_name", ")", "prefix_arn", "=", "'arn:aws:s3:::{0}/{1}/*'", ".", "format", "(", "bucket_name", ",", "prefix", ")", "structure", "=", "{", "'Version'", ":", "'2012-10-17'", ",", "'Statement'", ":", "[", "{", "'Action'", ":", "[", "'s3:ListBucket'", "]", ",", "'Effect'", ":", "'Allow'", ",", "'Resource'", ":", "[", "bucket_arn", "]", ",", "'Condition'", ":", "{", "'StringLike'", ":", "{", "'s3:prefix'", ":", "[", "(", "prefix", "+", "'/*'", ")", "]", "}", "}", "}", ",", "{", "'Effect'", ":", "'Allow'", ",", "'Action'", ":", "[", "'s3:PutObject'", ",", "'s3:GetObject'", "]", ",", "'Resource'", ":", "[", "prefix_arn", "]", "}", "]", "}", "if", "allow_get_location", ":", "structure", "[", "'Statement'", "]", ".", "append", "(", "{", "'Action'", ":", "[", "'s3:GetBucketLocation'", "]", ",", "'Effect'", ":", "'Allow'", ",", "'Resource'", ":", "[", "bucket_arn", "]", "}", ")", "return", "json", ".", "dumps", "(", "structure", ",", "indent", "=", "2", ")" ]
produces a s3 iam text for selective access of data .
train
false
35,421
def param_show(param=None): ret = _run_varnishadm('param.show', [param]) if ret['retcode']: return False else: result = {} for line in ret['stdout'].split('\n'): m = re.search('^(\\w+)\\s+(.*)$', line) result[m.group(1)] = m.group(2) if param: break return result
[ "def", "param_show", "(", "param", "=", "None", ")", ":", "ret", "=", "_run_varnishadm", "(", "'param.show'", ",", "[", "param", "]", ")", "if", "ret", "[", "'retcode'", "]", ":", "return", "False", "else", ":", "result", "=", "{", "}", "for", "line", "in", "ret", "[", "'stdout'", "]", ".", "split", "(", "'\\n'", ")", ":", "m", "=", "re", ".", "search", "(", "'^(\\\\w+)\\\\s+(.*)$'", ",", "line", ")", "result", "[", "m", ".", "group", "(", "1", ")", "]", "=", "m", ".", "group", "(", "2", ")", "if", "param", ":", "break", "return", "result" ]
show params of varnish cache cli example: .
train
true
35,423
def _read_int(fid): return np.fromfile(fid, '>i4', 1)[0]
[ "def", "_read_int", "(", "fid", ")", ":", "return", "np", ".", "fromfile", "(", "fid", ",", "'>i4'", ",", "1", ")", "[", "0", "]" ]
read a 32-bit integer .
train
false
35,424
def _lookup_dimension(name, templates, namespace, provider): dimension = None if provider: try: dimension = provider.dimension(name, templates=templates) except NoSuchDimensionError: pass else: return dimension if namespace: return namespace.dimension(name, templates=templates) raise NoSuchDimensionError(("Dimension '%s' not found" % name), name=name)
[ "def", "_lookup_dimension", "(", "name", ",", "templates", ",", "namespace", ",", "provider", ")", ":", "dimension", "=", "None", "if", "provider", ":", "try", ":", "dimension", "=", "provider", ".", "dimension", "(", "name", ",", "templates", "=", "templates", ")", "except", "NoSuchDimensionError", ":", "pass", "else", ":", "return", "dimension", "if", "namespace", ":", "return", "namespace", ".", "dimension", "(", "name", ",", "templates", "=", "templates", ")", "raise", "NoSuchDimensionError", "(", "(", "\"Dimension '%s' not found\"", "%", "name", ")", ",", "name", "=", "name", ")" ]
look-up a dimension name in provider and then in namespace .
train
false
35,425
def pop_feedback_message_references(user_id, num_references_to_pop): model = feedback_models.UnsentFeedbackEmailModel.get(user_id) if (num_references_to_pop == len(model.feedback_message_references)): model.delete() else: message_references = model.feedback_message_references[num_references_to_pop:] model.delete() model = feedback_models.UnsentFeedbackEmailModel(id=user_id, feedback_message_references=message_references) model.put() enqueue_feedback_message_batch_email_task(user_id)
[ "def", "pop_feedback_message_references", "(", "user_id", ",", "num_references_to_pop", ")", ":", "model", "=", "feedback_models", ".", "UnsentFeedbackEmailModel", ".", "get", "(", "user_id", ")", "if", "(", "num_references_to_pop", "==", "len", "(", "model", ".", "feedback_message_references", ")", ")", ":", "model", ".", "delete", "(", ")", "else", ":", "message_references", "=", "model", ".", "feedback_message_references", "[", "num_references_to_pop", ":", "]", "model", ".", "delete", "(", ")", "model", "=", "feedback_models", ".", "UnsentFeedbackEmailModel", "(", "id", "=", "user_id", ",", "feedback_message_references", "=", "message_references", ")", "model", ".", "put", "(", ")", "enqueue_feedback_message_batch_email_task", "(", "user_id", ")" ]
pops feedback message references of the given user which have been processed already .
train
false
35,426
def get_scene_exception_by_name(show_name): myDB = db.DBConnection('cache.db') exception_result = myDB.select('SELECT tvdb_id FROM scene_exceptions WHERE LOWER(show_name) = ?', [show_name.lower()]) if exception_result: return int(exception_result[0]['tvdb_id']) all_exception_results = myDB.select('SELECT DISTINCT show_name, tvdb_id FROM scene_exceptions') for cur_exception in all_exception_results: cur_exception_name = cur_exception['show_name'] cur_tvdb_id = int(cur_exception['tvdb_id']) if (show_name.lower() in (cur_exception_name.lower(), helpers.sanitizeSceneName(cur_exception_name).lower().replace('.', ' '))): logger.log(((u'Scene exception lookup got tvdb id ' + str(cur_tvdb_id)) + u', using that'), logger.DEBUG) return cur_tvdb_id return None
[ "def", "get_scene_exception_by_name", "(", "show_name", ")", ":", "myDB", "=", "db", ".", "DBConnection", "(", "'cache.db'", ")", "exception_result", "=", "myDB", ".", "select", "(", "'SELECT tvdb_id FROM scene_exceptions WHERE LOWER(show_name) = ?'", ",", "[", "show_name", ".", "lower", "(", ")", "]", ")", "if", "exception_result", ":", "return", "int", "(", "exception_result", "[", "0", "]", "[", "'tvdb_id'", "]", ")", "all_exception_results", "=", "myDB", ".", "select", "(", "'SELECT DISTINCT show_name, tvdb_id FROM scene_exceptions'", ")", "for", "cur_exception", "in", "all_exception_results", ":", "cur_exception_name", "=", "cur_exception", "[", "'show_name'", "]", "cur_tvdb_id", "=", "int", "(", "cur_exception", "[", "'tvdb_id'", "]", ")", "if", "(", "show_name", ".", "lower", "(", ")", "in", "(", "cur_exception_name", ".", "lower", "(", ")", ",", "helpers", ".", "sanitizeSceneName", "(", "cur_exception_name", ")", ".", "lower", "(", ")", ".", "replace", "(", "'.'", ",", "' '", ")", ")", ")", ":", "logger", ".", "log", "(", "(", "(", "u'Scene exception lookup got tvdb id '", "+", "str", "(", "cur_tvdb_id", ")", ")", "+", "u', using that'", ")", ",", "logger", ".", "DEBUG", ")", "return", "cur_tvdb_id", "return", "None" ]
given a show name .
train
false
35,427
def absolutify(url): site_url = getattr(settings, 'SITE_URL', False) if (not site_url): protocol = settings.PROTOCOL hostname = settings.DOMAIN port = settings.PORT if ((protocol, port) in (('https://', 443), ('http://', 80))): site_url = ''.join(map(str, (protocol, hostname))) else: site_url = ''.join(map(str, (protocol, hostname, ':', port))) return (site_url + url)
[ "def", "absolutify", "(", "url", ")", ":", "site_url", "=", "getattr", "(", "settings", ",", "'SITE_URL'", ",", "False", ")", "if", "(", "not", "site_url", ")", ":", "protocol", "=", "settings", ".", "PROTOCOL", "hostname", "=", "settings", ".", "DOMAIN", "port", "=", "settings", ".", "PORT", "if", "(", "(", "protocol", ",", "port", ")", "in", "(", "(", "'https://'", ",", "443", ")", ",", "(", "'http://'", ",", "80", ")", ")", ")", ":", "site_url", "=", "''", ".", "join", "(", "map", "(", "str", ",", "(", "protocol", ",", "hostname", ")", ")", ")", "else", ":", "site_url", "=", "''", ".", "join", "(", "map", "(", "str", ",", "(", "protocol", ",", "hostname", ",", "':'", ",", "port", ")", ")", ")", "return", "(", "site_url", "+", "url", ")" ]
takes a url and prepends the site_url .
train
true
35,428
@task(ignore_result=True) def send_pending_membership_emails(): from mozillians.groups.models import Group, GroupMembership groups = Group.objects.exclude(curators__isnull=True) groups = groups.filter(groupmembership__status=GroupMembership.PENDING).distinct() for group in groups: pending_memberships = group.groupmembership_set.filter(status=GroupMembership.PENDING) max_pk = pending_memberships.aggregate(max_pk=Max('pk'))['max_pk'] if (max_pk > group.max_reminder): activate('en-us') count = pending_memberships.count() subject = (ungettext('%(count)d outstanding request to join Mozillians group "%(name)s"', '%(count)d outstanding requests to join Mozillians group "%(name)s"', count) % {'count': count, 'name': group.name}) body = render_to_string('groups/email/memberships_pending.txt', {'group': group, 'count': count}) send_mail(subject, body, settings.FROM_NOREPLY, [profile.user.email for profile in group.curators.all()], fail_silently=False) group.max_reminder = max_pk group.save()
[ "@", "task", "(", "ignore_result", "=", "True", ")", "def", "send_pending_membership_emails", "(", ")", ":", "from", "mozillians", ".", "groups", ".", "models", "import", "Group", ",", "GroupMembership", "groups", "=", "Group", ".", "objects", ".", "exclude", "(", "curators__isnull", "=", "True", ")", "groups", "=", "groups", ".", "filter", "(", "groupmembership__status", "=", "GroupMembership", ".", "PENDING", ")", ".", "distinct", "(", ")", "for", "group", "in", "groups", ":", "pending_memberships", "=", "group", ".", "groupmembership_set", ".", "filter", "(", "status", "=", "GroupMembership", ".", "PENDING", ")", "max_pk", "=", "pending_memberships", ".", "aggregate", "(", "max_pk", "=", "Max", "(", "'pk'", ")", ")", "[", "'max_pk'", "]", "if", "(", "max_pk", ">", "group", ".", "max_reminder", ")", ":", "activate", "(", "'en-us'", ")", "count", "=", "pending_memberships", ".", "count", "(", ")", "subject", "=", "(", "ungettext", "(", "'%(count)d outstanding request to join Mozillians group \"%(name)s\"'", ",", "'%(count)d outstanding requests to join Mozillians group \"%(name)s\"'", ",", "count", ")", "%", "{", "'count'", ":", "count", ",", "'name'", ":", "group", ".", "name", "}", ")", "body", "=", "render_to_string", "(", "'groups/email/memberships_pending.txt'", ",", "{", "'group'", ":", "group", ",", "'count'", ":", "count", "}", ")", "send_mail", "(", "subject", ",", "body", ",", "settings", ".", "FROM_NOREPLY", ",", "[", "profile", ".", "user", ".", "email", "for", "profile", "in", "group", ".", "curators", ".", "all", "(", ")", "]", ",", "fail_silently", "=", "False", ")", "group", ".", "max_reminder", "=", "max_pk", "group", ".", "save", "(", ")" ]
for each curated group that has pending memberships that the curators have not yet been emailed about .
train
false
35,431
def verify_iface(iface): try: tmp = init_app('ifconfig', True) if (not (iface in tmp)): return False return True except Exception: return False
[ "def", "verify_iface", "(", "iface", ")", ":", "try", ":", "tmp", "=", "init_app", "(", "'ifconfig'", ",", "True", ")", "if", "(", "not", "(", "iface", "in", "tmp", ")", ")", ":", "return", "False", "return", "True", "except", "Exception", ":", "return", "False" ]
verify that the given interface exists .
train
false
35,432
def add_noise_evoked(evoked, noise, snr, tmin=None, tmax=None): evoked = copy.deepcopy(evoked) tmask = _time_mask(evoked.times, tmin, tmax, sfreq=evoked.info['sfreq']) tmp = (10 * np.log10((np.mean((evoked.data[:, tmask] ** 2).ravel()) / np.mean((noise.data ** 2).ravel())))) noise.data = ((10 ** ((tmp - float(snr)) / 20)) * noise.data) evoked.data += noise.data return evoked
[ "def", "add_noise_evoked", "(", "evoked", ",", "noise", ",", "snr", ",", "tmin", "=", "None", ",", "tmax", "=", "None", ")", ":", "evoked", "=", "copy", ".", "deepcopy", "(", "evoked", ")", "tmask", "=", "_time_mask", "(", "evoked", ".", "times", ",", "tmin", ",", "tmax", ",", "sfreq", "=", "evoked", ".", "info", "[", "'sfreq'", "]", ")", "tmp", "=", "(", "10", "*", "np", ".", "log10", "(", "(", "np", ".", "mean", "(", "(", "evoked", ".", "data", "[", ":", ",", "tmask", "]", "**", "2", ")", ".", "ravel", "(", ")", ")", "/", "np", ".", "mean", "(", "(", "noise", ".", "data", "**", "2", ")", ".", "ravel", "(", ")", ")", ")", ")", ")", "noise", ".", "data", "=", "(", "(", "10", "**", "(", "(", "tmp", "-", "float", "(", "snr", ")", ")", "/", "20", ")", ")", "*", "noise", ".", "data", ")", "evoked", ".", "data", "+=", "noise", ".", "data", "return", "evoked" ]
add noise to evoked object with specified snr .
train
false
35,433
def convert_cell_args(method): def cell_wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) except ValueError: new_args = list(xl_cell_to_rowcol(args[0])) new_args.extend(args[1:]) args = new_args return method(self, *args, **kwargs) return cell_wrapper
[ "def", "convert_cell_args", "(", "method", ")", ":", "def", "cell_wrapper", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "if", "len", "(", "args", ")", ":", "int", "(", "args", "[", "0", "]", ")", "except", "ValueError", ":", "new_args", "=", "list", "(", "xl_cell_to_rowcol", "(", "args", "[", "0", "]", ")", ")", "new_args", ".", "extend", "(", "args", "[", "1", ":", "]", ")", "args", "=", "new_args", "return", "method", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "cell_wrapper" ]
decorator function to convert a1 notation in cell method calls to the default row/col notation .
train
false
35,434
def vb_get_network_adapters(machine_name=None, machine=None): if machine_name: machine = vb_get_box().findMachine(machine_name) network_adapters = [] for i in range(vb_get_max_network_slots()): try: inetwork_adapter = machine.getNetworkAdapter(i) network_adapter = vb_xpcom_to_attribute_dict(inetwork_adapter, 'INetworkAdapter') network_adapter['properties'] = inetwork_adapter.getProperties('') network_adapters.append(network_adapter) except Exception: pass return network_adapters
[ "def", "vb_get_network_adapters", "(", "machine_name", "=", "None", ",", "machine", "=", "None", ")", ":", "if", "machine_name", ":", "machine", "=", "vb_get_box", "(", ")", ".", "findMachine", "(", "machine_name", ")", "network_adapters", "=", "[", "]", "for", "i", "in", "range", "(", "vb_get_max_network_slots", "(", ")", ")", ":", "try", ":", "inetwork_adapter", "=", "machine", ".", "getNetworkAdapter", "(", "i", ")", "network_adapter", "=", "vb_xpcom_to_attribute_dict", "(", "inetwork_adapter", ",", "'INetworkAdapter'", ")", "network_adapter", "[", "'properties'", "]", "=", "inetwork_adapter", ".", "getProperties", "(", "''", ")", "network_adapters", ".", "append", "(", "network_adapter", ")", "except", "Exception", ":", "pass", "return", "network_adapters" ]
a valid machine_name or a machine is needed to make this work! .
train
true
35,436
def get_geocoder_for_service(service): try: return SERVICE_TO_GEOCODER[service.lower()] except KeyError: raise GeocoderNotFound(("Unknown geocoder '%s'; options are: %s" % (service, SERVICE_TO_GEOCODER.keys())))
[ "def", "get_geocoder_for_service", "(", "service", ")", ":", "try", ":", "return", "SERVICE_TO_GEOCODER", "[", "service", ".", "lower", "(", ")", "]", "except", "KeyError", ":", "raise", "GeocoderNotFound", "(", "(", "\"Unknown geocoder '%s'; options are: %s\"", "%", "(", "service", ",", "SERVICE_TO_GEOCODER", ".", "keys", "(", ")", ")", ")", ")" ]
for the service provided .
train
true
35,437
def _selection_scroll(event, params): if (event.step < 0): _change_channel_group((-1), params) elif (event.step > 0): _change_channel_group(1, params)
[ "def", "_selection_scroll", "(", "event", ",", "params", ")", ":", "if", "(", "event", ".", "step", "<", "0", ")", ":", "_change_channel_group", "(", "(", "-", "1", ")", ",", "params", ")", "elif", "(", "event", ".", "step", ">", "0", ")", ":", "_change_channel_group", "(", "1", ",", "params", ")" ]
callback for scroll in selection dialog .
train
false
35,438
def test_xdawn(): Xdawn(n_components=2, correct_overlap='auto', signal_cov=None, reg=None) assert_raises(ValueError, Xdawn, correct_overlap=42)
[ "def", "test_xdawn", "(", ")", ":", "Xdawn", "(", "n_components", "=", "2", ",", "correct_overlap", "=", "'auto'", ",", "signal_cov", "=", "None", ",", "reg", "=", "None", ")", "assert_raises", "(", "ValueError", ",", "Xdawn", ",", "correct_overlap", "=", "42", ")" ]
test init of xdawn .
train
false
35,439
def str_to_dpid(s): if s.lower().startswith('0x'): s = s[2:] s = s.replace('-', '').split('|', 2) a = int(s[0], 16) if (a > 281474976710655): b = (a >> 48) a &= 281474976710655 else: b = 0 if (len(s) == 2): b = int(s[1]) return (a | (b << 48))
[ "def", "str_to_dpid", "(", "s", ")", ":", "if", "s", ".", "lower", "(", ")", ".", "startswith", "(", "'0x'", ")", ":", "s", "=", "s", "[", "2", ":", "]", "s", "=", "s", ".", "replace", "(", "'-'", ",", "''", ")", ".", "split", "(", "'|'", ",", "2", ")", "a", "=", "int", "(", "s", "[", "0", "]", ",", "16", ")", "if", "(", "a", ">", "281474976710655", ")", ":", "b", "=", "(", "a", ">>", "48", ")", "a", "&=", "281474976710655", "else", ":", "b", "=", "0", "if", "(", "len", "(", "s", ")", "==", "2", ")", ":", "b", "=", "int", "(", "s", "[", "1", "]", ")", "return", "(", "a", "|", "(", "b", "<<", "48", ")", ")" ]
convert a dpid in the canonical string form into a long int .
train
false
35,440
def pool_output_length(input_length, pool_size, stride, pad, ignore_border): if ((input_length is None) or (pool_size is None)): return None if ignore_border: output_length = (((input_length + (2 * pad)) - pool_size) + 1) output_length = (((output_length + stride) - 1) // stride) else: assert (pad == 0) if (stride >= pool_size): output_length = (((input_length + stride) - 1) // stride) else: output_length = (max(0, ((((input_length - pool_size) + stride) - 1) // stride)) + 1) return output_length
[ "def", "pool_output_length", "(", "input_length", ",", "pool_size", ",", "stride", ",", "pad", ",", "ignore_border", ")", ":", "if", "(", "(", "input_length", "is", "None", ")", "or", "(", "pool_size", "is", "None", ")", ")", ":", "return", "None", "if", "ignore_border", ":", "output_length", "=", "(", "(", "(", "input_length", "+", "(", "2", "*", "pad", ")", ")", "-", "pool_size", ")", "+", "1", ")", "output_length", "=", "(", "(", "(", "output_length", "+", "stride", ")", "-", "1", ")", "//", "stride", ")", "else", ":", "assert", "(", "pad", "==", "0", ")", "if", "(", "stride", ">=", "pool_size", ")", ":", "output_length", "=", "(", "(", "(", "input_length", "+", "stride", ")", "-", "1", ")", "//", "stride", ")", "else", ":", "output_length", "=", "(", "max", "(", "0", ",", "(", "(", "(", "(", "input_length", "-", "pool_size", ")", "+", "stride", ")", "-", "1", ")", "//", "stride", ")", ")", "+", "1", ")", "return", "output_length" ]
compute the output length of a pooling operator along a single dimension .
train
false
35,441
def test_hsl_to_rgb_part_5(): assert (hsl_to_rgb(120, 100, 50) == (0, 255, 0)) assert (hsl_to_rgb(132, 100, 50) == (0, 255, 51)) assert (hsl_to_rgb(144, 100, 50) == (0, 255, 102)) assert (hsl_to_rgb(156, 100, 50) == (0, 255, 153)) assert (hsl_to_rgb(168, 100, 50) == (0, 255, 204)) assert (hsl_to_rgb(180, 100, 50) == (0, 255, 255)) assert (hsl_to_rgb(192, 100, 50) == (0, 204, 255)) assert (hsl_to_rgb(204, 100, 50) == (0, 153, 255)) assert (hsl_to_rgb(216, 100, 50) == (0, 102, 255)) assert (hsl_to_rgb(228, 100, 50) == (0, 51, 255)) assert (hsl_to_rgb(240, 100, 50) == (0, 0, 255))
[ "def", "test_hsl_to_rgb_part_5", "(", ")", ":", "assert", "(", "hsl_to_rgb", "(", "120", ",", "100", ",", "50", ")", "==", "(", "0", ",", "255", ",", "0", ")", ")", "assert", "(", "hsl_to_rgb", "(", "132", ",", "100", ",", "50", ")", "==", "(", "0", ",", "255", ",", "51", ")", ")", "assert", "(", "hsl_to_rgb", "(", "144", ",", "100", ",", "50", ")", "==", "(", "0", ",", "255", ",", "102", ")", ")", "assert", "(", "hsl_to_rgb", "(", "156", ",", "100", ",", "50", ")", "==", "(", "0", ",", "255", ",", "153", ")", ")", "assert", "(", "hsl_to_rgb", "(", "168", ",", "100", ",", "50", ")", "==", "(", "0", ",", "255", ",", "204", ")", ")", "assert", "(", "hsl_to_rgb", "(", "180", ",", "100", ",", "50", ")", "==", "(", "0", ",", "255", ",", "255", ")", ")", "assert", "(", "hsl_to_rgb", "(", "192", ",", "100", ",", "50", ")", "==", "(", "0", ",", "204", ",", "255", ")", ")", "assert", "(", "hsl_to_rgb", "(", "204", ",", "100", ",", "50", ")", "==", "(", "0", ",", "153", ",", "255", ")", ")", "assert", "(", "hsl_to_rgb", "(", "216", ",", "100", ",", "50", ")", "==", "(", "0", ",", "102", ",", "255", ")", ")", "assert", "(", "hsl_to_rgb", "(", "228", ",", "100", ",", "50", ")", "==", "(", "0", ",", "51", ",", "255", ")", ")", "assert", "(", "hsl_to_rgb", "(", "240", ",", "100", ",", "50", ")", "==", "(", "0", ",", "0", ",", "255", ")", ")" ]
test hsl to rgb color function .
train
false
35,442
def _prepare_tfr(data, decim, pick_ori, Ws, K, source_ori): n_times = data[:, :, ::decim].shape[2] n_freqs = len(Ws) n_sources = K.shape[0] is_free_ori = False if ((source_ori == FIFF.FIFFV_MNE_FREE_ORI) and (pick_ori is None)): is_free_ori = True n_sources //= 3 shape = (n_sources, n_freqs, n_times) return (shape, is_free_ori)
[ "def", "_prepare_tfr", "(", "data", ",", "decim", ",", "pick_ori", ",", "Ws", ",", "K", ",", "source_ori", ")", ":", "n_times", "=", "data", "[", ":", ",", ":", ",", ":", ":", "decim", "]", ".", "shape", "[", "2", "]", "n_freqs", "=", "len", "(", "Ws", ")", "n_sources", "=", "K", ".", "shape", "[", "0", "]", "is_free_ori", "=", "False", "if", "(", "(", "source_ori", "==", "FIFF", ".", "FIFFV_MNE_FREE_ORI", ")", "and", "(", "pick_ori", "is", "None", ")", ")", ":", "is_free_ori", "=", "True", "n_sources", "//=", "3", "shape", "=", "(", "n_sources", ",", "n_freqs", ",", "n_times", ")", "return", "(", "shape", ",", "is_free_ori", ")" ]
prepare tfr source localization .
train
false
35,443
def _compare_entropy(start_slice, end_slice, slice, difference): start_entropy = utils.image_entropy(start_slice) end_entropy = utils.image_entropy(end_slice) if (end_entropy and (abs(((start_entropy / end_entropy) - 1)) < 0.01)): if (difference >= (slice * 2)): return (slice, slice) half_slice = (slice // 2) return (half_slice, (slice - half_slice)) if (start_entropy > end_entropy): return (0, slice) else: return (slice, 0)
[ "def", "_compare_entropy", "(", "start_slice", ",", "end_slice", ",", "slice", ",", "difference", ")", ":", "start_entropy", "=", "utils", ".", "image_entropy", "(", "start_slice", ")", "end_entropy", "=", "utils", ".", "image_entropy", "(", "end_slice", ")", "if", "(", "end_entropy", "and", "(", "abs", "(", "(", "(", "start_entropy", "/", "end_entropy", ")", "-", "1", ")", ")", "<", "0.01", ")", ")", ":", "if", "(", "difference", ">=", "(", "slice", "*", "2", ")", ")", ":", "return", "(", "slice", ",", "slice", ")", "half_slice", "=", "(", "slice", "//", "2", ")", "return", "(", "half_slice", ",", "(", "slice", "-", "half_slice", ")", ")", "if", "(", "start_entropy", ">", "end_entropy", ")", ":", "return", "(", "0", ",", "slice", ")", "else", ":", "return", "(", "slice", ",", "0", ")" ]
calculate the entropy of two slices .
train
true
35,444
def send_confirmation_instructions(user): (confirmation_link, token) = generate_confirmation_link(user) send_mail(config_value('EMAIL_SUBJECT_CONFIRM'), user.email, 'confirmation_instructions', user=user, confirmation_link=confirmation_link) confirm_instructions_sent.send(app._get_current_object(), user=user) return token
[ "def", "send_confirmation_instructions", "(", "user", ")", ":", "(", "confirmation_link", ",", "token", ")", "=", "generate_confirmation_link", "(", "user", ")", "send_mail", "(", "config_value", "(", "'EMAIL_SUBJECT_CONFIRM'", ")", ",", "user", ".", "email", ",", "'confirmation_instructions'", ",", "user", "=", "user", ",", "confirmation_link", "=", "confirmation_link", ")", "confirm_instructions_sent", ".", "send", "(", "app", ".", "_get_current_object", "(", ")", ",", "user", "=", "user", ")", "return", "token" ]
sends the confirmation instructions email for the specified user .
train
true
35,446
def simulate_patch(app, path, **kwargs): return simulate_request(app, 'PATCH', path, **kwargs)
[ "def", "simulate_patch", "(", "app", ",", "path", ",", "**", "kwargs", ")", ":", "return", "simulate_request", "(", "app", ",", "'PATCH'", ",", "path", ",", "**", "kwargs", ")" ]
simulates a patch request to a wsgi application .
train
false
35,448
def _p(pp, name): return ('%s_%s' % (pp, name))
[ "def", "_p", "(", "pp", ",", "name", ")", ":", "return", "(", "'%s_%s'", "%", "(", "pp", ",", "name", ")", ")" ]
make prefix-appended name .
train
false
35,449
def assert_class_equal(left, right, exact=True, obj='Input'): def repr_class(x): if isinstance(x, Index): return x try: return x.__class__.__name__ except AttributeError: return repr(type(x)) if (exact == 'equiv'): if (type(left) != type(right)): types = set([type(left).__name__, type(right).__name__]) if len((types - set(['Int64Index', 'RangeIndex']))): msg = '{0} classes are not equivalent'.format(obj) raise_assert_detail(obj, msg, repr_class(left), repr_class(right)) elif exact: if (type(left) != type(right)): msg = '{0} classes are different'.format(obj) raise_assert_detail(obj, msg, repr_class(left), repr_class(right))
[ "def", "assert_class_equal", "(", "left", ",", "right", ",", "exact", "=", "True", ",", "obj", "=", "'Input'", ")", ":", "def", "repr_class", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "Index", ")", ":", "return", "x", "try", ":", "return", "x", ".", "__class__", ".", "__name__", "except", "AttributeError", ":", "return", "repr", "(", "type", "(", "x", ")", ")", "if", "(", "exact", "==", "'equiv'", ")", ":", "if", "(", "type", "(", "left", ")", "!=", "type", "(", "right", ")", ")", ":", "types", "=", "set", "(", "[", "type", "(", "left", ")", ".", "__name__", ",", "type", "(", "right", ")", ".", "__name__", "]", ")", "if", "len", "(", "(", "types", "-", "set", "(", "[", "'Int64Index'", ",", "'RangeIndex'", "]", ")", ")", ")", ":", "msg", "=", "'{0} classes are not equivalent'", ".", "format", "(", "obj", ")", "raise_assert_detail", "(", "obj", ",", "msg", ",", "repr_class", "(", "left", ")", ",", "repr_class", "(", "right", ")", ")", "elif", "exact", ":", "if", "(", "type", "(", "left", ")", "!=", "type", "(", "right", ")", ")", ":", "msg", "=", "'{0} classes are different'", ".", "format", "(", "obj", ")", "raise_assert_detail", "(", "obj", ",", "msg", ",", "repr_class", "(", "left", ")", ",", "repr_class", "(", "right", ")", ")" ]
checks classes are equal .
train
false
35,450
def item_google_product_category(item, category_paths): category = item.product.get_first_category() if category: if (category.pk in category_paths): return category_paths[category.pk] ancestors = [ancestor.name for ancestor in list(category.get_ancestors())] category_path = CATEGORY_SEPARATOR.join((ancestors + [category.name])) category_paths[category.pk] = category_path return category_path else: return u''
[ "def", "item_google_product_category", "(", "item", ",", "category_paths", ")", ":", "category", "=", "item", ".", "product", ".", "get_first_category", "(", ")", "if", "category", ":", "if", "(", "category", ".", "pk", "in", "category_paths", ")", ":", "return", "category_paths", "[", "category", ".", "pk", "]", "ancestors", "=", "[", "ancestor", ".", "name", "for", "ancestor", "in", "list", "(", "category", ".", "get_ancestors", "(", ")", ")", "]", "category_path", "=", "CATEGORY_SEPARATOR", ".", "join", "(", "(", "ancestors", "+", "[", "category", ".", "name", "]", ")", ")", "category_paths", "[", "category", ".", "pk", "]", "=", "category_path", "return", "category_path", "else", ":", "return", "u''" ]
to have your categories accepted .
train
false
35,451
def _is_text_file(filename): type_of_file = os.popen('file -bi {0}'.format(filename), 'r').read() return type_of_file.startswith('text')
[ "def", "_is_text_file", "(", "filename", ")", ":", "type_of_file", "=", "os", ".", "popen", "(", "'file -bi {0}'", ".", "format", "(", "filename", ")", ",", "'r'", ")", ".", "read", "(", ")", "return", "type_of_file", ".", "startswith", "(", "'text'", ")" ]
checks if a file is a text file .
train
true
35,452
def unimplemented(func): def wrapper(*__args, **__kw): raise NotImplementedError('Method or function "%s" is not implemented', func.__name__) wrapper.__name__ = func.__name__ wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ return wrapper
[ "def", "unimplemented", "(", "func", ")", ":", "def", "wrapper", "(", "*", "__args", ",", "**", "__kw", ")", ":", "raise", "NotImplementedError", "(", "'Method or function \"%s\" is not implemented'", ",", "func", ".", "__name__", ")", "wrapper", ".", "__name__", "=", "func", ".", "__name__", "wrapper", ".", "__dict__", "=", "func", ".", "__dict__", "wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "wrapper" ]
decorator for marking a function or method unimplemented .
train
false
35,453
def l1_loss(tensor, weight=1.0, scope=None): with tf.name_scope(scope, 'L1Loss', [tensor]): weight = tf.convert_to_tensor(weight, dtype=tensor.dtype.base_dtype, name='loss_weight') loss = tf.multiply(weight, tf.reduce_sum(tf.abs(tensor)), name='value') tf.add_to_collection(LOSSES_COLLECTION, loss) return loss
[ "def", "l1_loss", "(", "tensor", ",", "weight", "=", "1.0", ",", "scope", "=", "None", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'L1Loss'", ",", "[", "tensor", "]", ")", ":", "weight", "=", "tf", ".", "convert_to_tensor", "(", "weight", ",", "dtype", "=", "tensor", ".", "dtype", ".", "base_dtype", ",", "name", "=", "'loss_weight'", ")", "loss", "=", "tf", ".", "multiply", "(", "weight", ",", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "tensor", ")", ")", ",", "name", "=", "'value'", ")", "tf", ".", "add_to_collection", "(", "LOSSES_COLLECTION", ",", "loss", ")", "return", "loss" ]
define a l1loss .
train
true
35,455
def string(name, value, expire=None, expireat=None, **connection_args): ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Key already set to defined value'} old_key = __salt__['redis.get_key'](name, **connection_args) if (old_key != value): __salt__['redis.set_key'](name, value, **connection_args) ret['changes'][name] = 'Value updated' ret['comment'] = 'Key updated to new value' if expireat: __salt__['redis.expireat'](name, expireat, **connection_args) ret['changes']['expireat'] = 'Key expires at {0}'.format(expireat) elif expire: __salt__['redis.expire'](name, expire, **connection_args) ret['changes']['expire'] = 'TTL set to {0} seconds'.format(expire) return ret
[ "def", "string", "(", "name", ",", "value", ",", "expire", "=", "None", ",", "expireat", "=", "None", ",", "**", "connection_args", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'Key already set to defined value'", "}", "old_key", "=", "__salt__", "[", "'redis.get_key'", "]", "(", "name", ",", "**", "connection_args", ")", "if", "(", "old_key", "!=", "value", ")", ":", "__salt__", "[", "'redis.set_key'", "]", "(", "name", ",", "value", ",", "**", "connection_args", ")", "ret", "[", "'changes'", "]", "[", "name", "]", "=", "'Value updated'", "ret", "[", "'comment'", "]", "=", "'Key updated to new value'", "if", "expireat", ":", "__salt__", "[", "'redis.expireat'", "]", "(", "name", ",", "expireat", ",", "**", "connection_args", ")", "ret", "[", "'changes'", "]", "[", "'expireat'", "]", "=", "'Key expires at {0}'", ".", "format", "(", "expireat", ")", "elif", "expire", ":", "__salt__", "[", "'redis.expire'", "]", "(", "name", ",", "expire", ",", "**", "connection_args", ")", "ret", "[", "'changes'", "]", "[", "'expire'", "]", "=", "'TTL set to {0} seconds'", ".", "format", "(", "expire", ")", "return", "ret" ]
ensure that the key exists in redis with the value specified name redis key to manage value data to persist in key expire sets time to live for key in seconds expireat sets expiration time for key via unix timestamp .
train
true
35,457
def format_scope_name(scope_name, prefix, suffix): if (prefix is not ''): if (not (prefix[(-1)] == '/')): prefix += '/' if (suffix is not ''): if (not (suffix[0] == '/')): suffix = ('/' + suffix) return ((prefix + scope_name) + suffix)
[ "def", "format_scope_name", "(", "scope_name", ",", "prefix", ",", "suffix", ")", ":", "if", "(", "prefix", "is", "not", "''", ")", ":", "if", "(", "not", "(", "prefix", "[", "(", "-", "1", ")", "]", "==", "'/'", ")", ")", ":", "prefix", "+=", "'/'", "if", "(", "suffix", "is", "not", "''", ")", ":", "if", "(", "not", "(", "suffix", "[", "0", "]", "==", "'/'", ")", ")", ":", "suffix", "=", "(", "'/'", "+", "suffix", ")", "return", "(", "(", "prefix", "+", "scope_name", ")", "+", "suffix", ")" ]
add a predix and a suffix to a scope name .
train
false
35,458
def get_pack_directory(pack_name): packs_base_paths = get_packs_base_paths() for packs_base_path in packs_base_paths: pack_base_path = os.path.join(packs_base_path, quote_unix(pack_name)) pack_base_path = os.path.abspath(pack_base_path) if os.path.isdir(pack_base_path): return pack_base_path return None
[ "def", "get_pack_directory", "(", "pack_name", ")", ":", "packs_base_paths", "=", "get_packs_base_paths", "(", ")", "for", "packs_base_path", "in", "packs_base_paths", ":", "pack_base_path", "=", "os", ".", "path", ".", "join", "(", "packs_base_path", ",", "quote_unix", "(", "pack_name", ")", ")", "pack_base_path", "=", "os", ".", "path", ".", "abspath", "(", "pack_base_path", ")", "if", "os", ".", "path", ".", "isdir", "(", "pack_base_path", ")", ":", "return", "pack_base_path", "return", "None" ]
retrieve a directory for the provided pack .
train
false
35,459
@register.filter def data_uri(thumbnail): try: thumbnail.open('rb') data = thumbnail.read() finally: thumbnail.close() mime_type = (mimetypes.guess_type(str(thumbnail.file))[0] or 'application/octet-stream') data = b64encode(data).decode('utf-8') return 'data:{0};base64,{1}'.format(mime_type, data)
[ "@", "register", ".", "filter", "def", "data_uri", "(", "thumbnail", ")", ":", "try", ":", "thumbnail", ".", "open", "(", "'rb'", ")", "data", "=", "thumbnail", ".", "read", "(", ")", "finally", ":", "thumbnail", ".", "close", "(", ")", "mime_type", "=", "(", "mimetypes", ".", "guess_type", "(", "str", "(", "thumbnail", ".", "file", ")", ")", "[", "0", "]", "or", "'application/octet-stream'", ")", "data", "=", "b64encode", "(", "data", ")", ".", "decode", "(", "'utf-8'", ")", "return", "'data:{0};base64,{1}'", ".", "format", "(", "mime_type", ",", "data", ")" ]
this filter will return the base64 encoded data uri for a given thumbnail object .
train
true
35,463
def _get_data_attribute(dat, attr=None): if (attr == 'class'): val = type(dat).__name__ elif (attr == 'dtype'): val = dtype_info_name(dat.info.dtype) elif (attr == 'shape'): datshape = dat.shape[1:] val = (datshape if datshape else '') else: val = getattr(dat.info, attr) if (val is None): val = '' return str(val)
[ "def", "_get_data_attribute", "(", "dat", ",", "attr", "=", "None", ")", ":", "if", "(", "attr", "==", "'class'", ")", ":", "val", "=", "type", "(", "dat", ")", ".", "__name__", "elif", "(", "attr", "==", "'dtype'", ")", ":", "val", "=", "dtype_info_name", "(", "dat", ".", "info", ".", "dtype", ")", "elif", "(", "attr", "==", "'shape'", ")", ":", "datshape", "=", "dat", ".", "shape", "[", "1", ":", "]", "val", "=", "(", "datshape", "if", "datshape", "else", "''", ")", "else", ":", "val", "=", "getattr", "(", "dat", ".", "info", ",", "attr", ")", "if", "(", "val", "is", "None", ")", ":", "val", "=", "''", "return", "str", "(", "val", ")" ]
get a data object attribute for the attributes info summary method .
train
false
35,464
def _traverse_pagination(response, endpoint, querystring, no_data): results = response.get(u'results', no_data) page = 1 next_page = response.get(u'next') while next_page: page += 1 querystring[u'page'] = page response = endpoint.get(**querystring) results += response.get(u'results', no_data) next_page = response.get(u'next') return results
[ "def", "_traverse_pagination", "(", "response", ",", "endpoint", ",", "querystring", ",", "no_data", ")", ":", "results", "=", "response", ".", "get", "(", "u'results'", ",", "no_data", ")", "page", "=", "1", "next_page", "=", "response", ".", "get", "(", "u'next'", ")", "while", "next_page", ":", "page", "+=", "1", "querystring", "[", "u'page'", "]", "=", "page", "response", "=", "endpoint", ".", "get", "(", "**", "querystring", ")", "results", "+=", "response", ".", "get", "(", "u'results'", ",", "no_data", ")", "next_page", "=", "response", ".", "get", "(", "u'next'", ")", "return", "results" ]
traverse a paginated api response .
train
false
35,466
def _literal_float(f): pat = '[-+]?((\\d*\\.\\d+)|(\\d+\\.?))(eE[-+]?\\d+)?' return bool(regex.match(pat, f))
[ "def", "_literal_float", "(", "f", ")", ":", "pat", "=", "'[-+]?((\\\\d*\\\\.\\\\d+)|(\\\\d+\\\\.?))(eE[-+]?\\\\d+)?'", "return", "bool", "(", "regex", ".", "match", "(", "pat", ",", "f", ")", ")" ]
return true if n can be interpreted as a floating point number .
train
false
35,468
def _split_tree(layout): one_found = False m = None for i in range(len(layout)): if (layout[i] == 1): if one_found: m = i break else: one_found = True if (m is None): m = len(layout) left = [(layout[i] - 1) for i in range(1, m)] rest = ([0] + [layout[i] for i in range(m, len(layout))]) return (left, rest)
[ "def", "_split_tree", "(", "layout", ")", ":", "one_found", "=", "False", "m", "=", "None", "for", "i", "in", "range", "(", "len", "(", "layout", ")", ")", ":", "if", "(", "layout", "[", "i", "]", "==", "1", ")", ":", "if", "one_found", ":", "m", "=", "i", "break", "else", ":", "one_found", "=", "True", "if", "(", "m", "is", "None", ")", ":", "m", "=", "len", "(", "layout", ")", "left", "=", "[", "(", "layout", "[", "i", "]", "-", "1", ")", "for", "i", "in", "range", "(", "1", ",", "m", ")", "]", "rest", "=", "(", "[", "0", "]", "+", "[", "layout", "[", "i", "]", "for", "i", "in", "range", "(", "m", ",", "len", "(", "layout", ")", ")", "]", ")", "return", "(", "left", ",", "rest", ")" ]
return a tuple of two layouts .
train
false
35,469
def health_check(): return (time.time() - int(NamedGlobals.get(PROMO_HEALTH_KEY, default=0)))
[ "def", "health_check", "(", ")", ":", "return", "(", "time", ".", "time", "(", ")", "-", "int", "(", "NamedGlobals", ".", "get", "(", "PROMO_HEALTH_KEY", ",", "default", "=", "0", ")", ")", ")" ]
calculate the number of seconds since promotions were last updated .
train
false
35,471
def generateElementsNamed(list, name): for n in list: if (IElement.providedBy(n) and (n.name == name)): (yield n)
[ "def", "generateElementsNamed", "(", "list", ",", "name", ")", ":", "for", "n", "in", "list", ":", "if", "(", "IElement", ".", "providedBy", "(", "n", ")", "and", "(", "n", ".", "name", "==", "name", ")", ")", ":", "(", "yield", "n", ")" ]
filters element items in a list with matching name .
train
false
35,472
@cors_api_view(['GET']) @permission_classes([AllowAny]) def site_config(request): def serialized_data(cls): as_list = cls(cls.Meta.model.objects.all().order_by('name'), many=True).data return dict(((d['name'], d) for d in as_list)) if (request.GET.get('serializer') == 'commonplace'): data = {'waffle': {'switches': list(waffle.models.Switch.objects.filter(active=True).values_list('name', flat=True))}} else: data = {'settings': get_settings(), 'version': getattr(settings, 'BUILD_ID_JS', ''), 'waffle': {'switches': serialized_data(SwitchSerializer), 'flags': serialized_data(FlagSerializer)}} (fxa_auth_state, fxa_auth_url) = fxa_auth_info() data['fxa'] = {'fxa_auth_state': fxa_auth_state, 'fxa_auth_url': fxa_auth_url} return Response(data)
[ "@", "cors_api_view", "(", "[", "'GET'", "]", ")", "@", "permission_classes", "(", "[", "AllowAny", "]", ")", "def", "site_config", "(", "request", ")", ":", "def", "serialized_data", "(", "cls", ")", ":", "as_list", "=", "cls", "(", "cls", ".", "Meta", ".", "model", ".", "objects", ".", "all", "(", ")", ".", "order_by", "(", "'name'", ")", ",", "many", "=", "True", ")", ".", "data", "return", "dict", "(", "(", "(", "d", "[", "'name'", "]", ",", "d", ")", "for", "d", "in", "as_list", ")", ")", "if", "(", "request", ".", "GET", ".", "get", "(", "'serializer'", ")", "==", "'commonplace'", ")", ":", "data", "=", "{", "'waffle'", ":", "{", "'switches'", ":", "list", "(", "waffle", ".", "models", ".", "Switch", ".", "objects", ".", "filter", "(", "active", "=", "True", ")", ".", "values_list", "(", "'name'", ",", "flat", "=", "True", ")", ")", "}", "}", "else", ":", "data", "=", "{", "'settings'", ":", "get_settings", "(", ")", ",", "'version'", ":", "getattr", "(", "settings", ",", "'BUILD_ID_JS'", ",", "''", ")", ",", "'waffle'", ":", "{", "'switches'", ":", "serialized_data", "(", "SwitchSerializer", ")", ",", "'flags'", ":", "serialized_data", "(", "FlagSerializer", ")", "}", "}", "(", "fxa_auth_state", ",", "fxa_auth_url", ")", "=", "fxa_auth_info", "(", ")", "data", "[", "'fxa'", "]", "=", "{", "'fxa_auth_state'", ":", "fxa_auth_state", ",", "'fxa_auth_url'", ":", "fxa_auth_url", "}", "return", "Response", "(", "data", ")" ]
a resource that is designed to be exposed externally and contains settings or waffle flags that might be relevant to the client app .
train
false
35,476
def updatedb(dt, meta=None): res = frappe.db.sql(u'select issingle from tabDocType where name=%s', (dt,)) if (not res): raise Exception, (u'Wrong doctype "%s" in updatedb' % dt) if (not res[0][0]): tab = DbTable(dt, u'tab', meta) tab.validate() frappe.db.commit() tab.sync() frappe.db.begin()
[ "def", "updatedb", "(", "dt", ",", "meta", "=", "None", ")", ":", "res", "=", "frappe", ".", "db", ".", "sql", "(", "u'select issingle from tabDocType where name=%s'", ",", "(", "dt", ",", ")", ")", "if", "(", "not", "res", ")", ":", "raise", "Exception", ",", "(", "u'Wrong doctype \"%s\" in updatedb'", "%", "dt", ")", "if", "(", "not", "res", "[", "0", "]", "[", "0", "]", ")", ":", "tab", "=", "DbTable", "(", "dt", ",", "u'tab'", ",", "meta", ")", "tab", ".", "validate", "(", ")", "frappe", ".", "db", ".", "commit", "(", ")", "tab", ".", "sync", "(", ")", "frappe", ".", "db", ".", "begin", "(", ")" ]
updates the locate database cli example: .
train
false
35,477
def get_minions(): serv = _get_serv(ret=None) sql = 'select distinct(id) from returns' data = serv.query(sql) ret = [] if data: for jid in data[0]['points']: ret.append(jid[1]) return ret
[ "def", "get_minions", "(", ")", ":", "serv", "=", "_get_serv", "(", "ret", "=", "None", ")", "sql", "=", "'select distinct(id) from returns'", "data", "=", "serv", ".", "query", "(", "sql", ")", "ret", "=", "[", "]", "if", "data", ":", "for", "jid", "in", "data", "[", "0", "]", "[", "'points'", "]", ":", "ret", ".", "append", "(", "jid", "[", "1", "]", ")", "return", "ret" ]
return a list of minions .
train
true
35,479
def emojize(text): pattern = re.compile('(::[a-z0-9\\+\\-_]+::)') def emorepl(match): value = match.group(1) if (value in emojiCodeDict): return emojiCodeDict[value] return pattern.sub(emorepl, text)
[ "def", "emojize", "(", "text", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'(::[a-z0-9\\\\+\\\\-_]+::)'", ")", "def", "emorepl", "(", "match", ")", ":", "value", "=", "match", ".", "group", "(", "1", ")", "if", "(", "value", "in", "emojiCodeDict", ")", ":", "return", "emojiCodeDict", "[", "value", "]", "return", "pattern", ".", "sub", "(", "emorepl", ",", "text", ")" ]
emoji regex .
train
false
35,480
def last(seq): return tail(1, seq)[0]
[ "def", "last", "(", "seq", ")", ":", "return", "tail", "(", "1", ",", "seq", ")", "[", "0", "]" ]
returns the last item in a list .
train
false
35,481
def markup_json(view_fun): def _markup_json(request, *args, **kwargs): request.IS_JSON = (request.GET.get('format') == 'json') if request.IS_JSON: request.JSON_CALLBACK = request.GET.get('callback', '').strip() else: request.JSON_CALLBACK = '' if request.IS_JSON: request.CONTENT_TYPE = ('application/x-javascript' if request.JSON_CALLBACK else 'application/json') else: request.CONTENT_TYPE = 'text/html' if (request.JSON_CALLBACK and (not jsonp_is_valid(request.JSON_CALLBACK))): return HttpResponse(json.dumps({'error': _('Invalid callback function.')}), content_type=request.CONTENT_TYPE, status=400) return view_fun(request, *args, **kwargs) return _markup_json
[ "def", "markup_json", "(", "view_fun", ")", ":", "def", "_markup_json", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "request", ".", "IS_JSON", "=", "(", "request", ".", "GET", ".", "get", "(", "'format'", ")", "==", "'json'", ")", "if", "request", ".", "IS_JSON", ":", "request", ".", "JSON_CALLBACK", "=", "request", ".", "GET", ".", "get", "(", "'callback'", ",", "''", ")", ".", "strip", "(", ")", "else", ":", "request", ".", "JSON_CALLBACK", "=", "''", "if", "request", ".", "IS_JSON", ":", "request", ".", "CONTENT_TYPE", "=", "(", "'application/x-javascript'", "if", "request", ".", "JSON_CALLBACK", "else", "'application/json'", ")", "else", ":", "request", ".", "CONTENT_TYPE", "=", "'text/html'", "if", "(", "request", ".", "JSON_CALLBACK", "and", "(", "not", "jsonp_is_valid", "(", "request", ".", "JSON_CALLBACK", ")", ")", ")", ":", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "{", "'error'", ":", "_", "(", "'Invalid callback function.'", ")", "}", ")", ",", "content_type", "=", "request", ".", "CONTENT_TYPE", ",", "status", "=", "400", ")", "return", "view_fun", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", "return", "_markup_json" ]
marks up the request object with json bits * is_json: whether or not this is a json request * json_callback: the json callback function to wrap with * content_type: the content type to return further .
train
false
35,482
def _key_none_value_callback(option, opt_str, value, parser): _default_to(parser, option.dest, {}) getattr(parser.values, option.dest)[value] = None
[ "def", "_key_none_value_callback", "(", "option", ",", "opt_str", ",", "value", ",", "parser", ")", ":", "_default_to", "(", "parser", ",", "option", ".", "dest", ",", "{", "}", ")", "getattr", "(", "parser", ".", "values", ",", "option", ".", "dest", ")", "[", "value", "]", "=", "None" ]
callback to set key to none .
train
false
35,483
def subtitles_enabled(video): try: parse_result = NameParser().parse(video, cache_result=True) except (InvalidNameException, InvalidShowException): logger.log(u'Not enough information to parse filename into a valid show. Consider add scene exceptions or improve naming for: {0}'.format(video), logger.WARNING) return False if parse_result.show.indexerid: main_db_con = db.DBConnection() sql_results = main_db_con.select('SELECT subtitles FROM tv_shows WHERE indexer_id = ? LIMIT 1', [parse_result.show.indexerid]) return (bool(sql_results[0]['subtitles']) if sql_results else False) else: logger.log(u'Empty indexer ID for: {0}'.format(video), logger.WARNING) return False
[ "def", "subtitles_enabled", "(", "video", ")", ":", "try", ":", "parse_result", "=", "NameParser", "(", ")", ".", "parse", "(", "video", ",", "cache_result", "=", "True", ")", "except", "(", "InvalidNameException", ",", "InvalidShowException", ")", ":", "logger", ".", "log", "(", "u'Not enough information to parse filename into a valid show. Consider add scene exceptions or improve naming for: {0}'", ".", "format", "(", "video", ")", ",", "logger", ".", "WARNING", ")", "return", "False", "if", "parse_result", ".", "show", ".", "indexerid", ":", "main_db_con", "=", "db", ".", "DBConnection", "(", ")", "sql_results", "=", "main_db_con", ".", "select", "(", "'SELECT subtitles FROM tv_shows WHERE indexer_id = ? LIMIT 1'", ",", "[", "parse_result", ".", "show", ".", "indexerid", "]", ")", "return", "(", "bool", "(", "sql_results", "[", "0", "]", "[", "'subtitles'", "]", ")", "if", "sql_results", "else", "False", ")", "else", ":", "logger", ".", "log", "(", "u'Empty indexer ID for: {0}'", ".", "format", "(", "video", ")", ",", "logger", ".", "WARNING", ")", "return", "False" ]
parse video filename to a show to check if it has subtitle enabled .
train
false
35,484
def sparse2full(doc, length): result = np.zeros(length, dtype=np.float32) doc = dict(doc) result[list(doc)] = list(itervalues(doc)) return result
[ "def", "sparse2full", "(", "doc", ",", "length", ")", ":", "result", "=", "np", ".", "zeros", "(", "length", ",", "dtype", "=", "np", ".", "float32", ")", "doc", "=", "dict", "(", "doc", ")", "result", "[", "list", "(", "doc", ")", "]", "=", "list", "(", "itervalues", "(", "doc", ")", ")", "return", "result" ]
convert a document in sparse document format into a dense np array .
train
false
35,486
def vb_wait_for_session_state(xp_session, state='Unlocked', timeout=10, step=None): args = (xp_session, state) wait_for(_check_session_state, timeout=timeout, step=step, default=False, func_args=args)
[ "def", "vb_wait_for_session_state", "(", "xp_session", ",", "state", "=", "'Unlocked'", ",", "timeout", "=", "10", ",", "step", "=", "None", ")", ":", "args", "=", "(", "xp_session", ",", "state", ")", "wait_for", "(", "_check_session_state", ",", "timeout", "=", "timeout", ",", "step", "=", "step", ",", "default", "=", "False", ",", "func_args", "=", "args", ")" ]
waits until a session state has been reached .
train
true
35,487
def test_divisibleby(value, num): return ((value % num) == 0)
[ "def", "test_divisibleby", "(", "value", ",", "num", ")", ":", "return", "(", "(", "value", "%", "num", ")", "==", "0", ")" ]
check if a variable is divisible by a number .
train
false
35,488
def _api_version(profile=None, **connection_args): global _TENANT_ID global _OS_IDENTITY_API_VERSION try: if (float(__salt__['keystone.api_version'](profile=profile, **connection_args).strip('v')) >= 3): _TENANT_ID = 'project_id' _OS_IDENTITY_API_VERSION = 3 except KeyError: pass
[ "def", "_api_version", "(", "profile", "=", "None", ",", "**", "connection_args", ")", ":", "global", "_TENANT_ID", "global", "_OS_IDENTITY_API_VERSION", "try", ":", "if", "(", "float", "(", "__salt__", "[", "'keystone.api_version'", "]", "(", "profile", "=", "profile", ",", "**", "connection_args", ")", ".", "strip", "(", "'v'", ")", ")", ">=", "3", ")", ":", "_TENANT_ID", "=", "'project_id'", "_OS_IDENTITY_API_VERSION", "=", "3", "except", "KeyError", ":", "pass" ]
sets global variables _os_identity_api_version and _tenant_id depending on api version .
train
true
35,489
def _unmunge_zone(zone): return zone.replace('_plus_', '+').replace('_minus_', '-')
[ "def", "_unmunge_zone", "(", "zone", ")", ":", "return", "zone", ".", "replace", "(", "'_plus_'", ",", "'+'", ")", ".", "replace", "(", "'_minus_'", ",", "'-'", ")" ]
undo the time zone name munging done by older versions of pytz .
train
false
35,490
def _item_to_bucket(iterator, item): name = item.get('name') bucket = Bucket(iterator.client, name) bucket._set_properties(item) return bucket
[ "def", "_item_to_bucket", "(", "iterator", ",", "item", ")", ":", "name", "=", "item", ".", "get", "(", "'name'", ")", "bucket", "=", "Bucket", "(", "iterator", ".", "client", ",", "name", ")", "bucket", ".", "_set_properties", "(", "item", ")", "return", "bucket" ]
convert a json bucket to the native object .
train
true
35,491
def pairs_to_dict(response): it = iter(response) return dict(izip(it, it))
[ "def", "pairs_to_dict", "(", "response", ")", ":", "it", "=", "iter", "(", "response", ")", "return", "dict", "(", "izip", "(", "it", ",", "it", ")", ")" ]
create a dict given a list of key/value pairs .
train
false
35,492
def _AddNextStateToQueue(penalty, previous_node, newline, count, p_queue): if (newline and (not previous_node.state.CanSplit())): return count must_split = previous_node.state.MustSplit() if ((not newline) and must_split): return count node = _StateNode(previous_node.state, newline, previous_node) penalty += node.state.AddTokenToState(newline=newline, dry_run=True, must_split=must_split) heapq.heappush(p_queue, _QueueItem(_OrderedPenalty(penalty, count), node)) return (count + 1)
[ "def", "_AddNextStateToQueue", "(", "penalty", ",", "previous_node", ",", "newline", ",", "count", ",", "p_queue", ")", ":", "if", "(", "newline", "and", "(", "not", "previous_node", ".", "state", ".", "CanSplit", "(", ")", ")", ")", ":", "return", "count", "must_split", "=", "previous_node", ".", "state", ".", "MustSplit", "(", ")", "if", "(", "(", "not", "newline", ")", "and", "must_split", ")", ":", "return", "count", "node", "=", "_StateNode", "(", "previous_node", ".", "state", ",", "newline", ",", "previous_node", ")", "penalty", "+=", "node", ".", "state", ".", "AddTokenToState", "(", "newline", "=", "newline", ",", "dry_run", "=", "True", ",", "must_split", "=", "must_split", ")", "heapq", ".", "heappush", "(", "p_queue", ",", "_QueueItem", "(", "_OrderedPenalty", "(", "penalty", ",", "count", ")", ",", "node", ")", ")", "return", "(", "count", "+", "1", ")" ]
add the following state to the analysis queue .
train
false
35,494
def find_p_q(nbits): p = getprime(nbits) while True: q = getprime(nbits) if (not (q == p)): break return (p, q)
[ "def", "find_p_q", "(", "nbits", ")", ":", "p", "=", "getprime", "(", "nbits", ")", "while", "True", ":", "q", "=", "getprime", "(", "nbits", ")", "if", "(", "not", "(", "q", "==", "p", ")", ")", ":", "break", "return", "(", "p", ",", "q", ")" ]
returns a tuple of two different primes of nbits bits .
train
false
35,496
def chist(im): im = (im // 64) (r, g, b) = im.transpose((2, 0, 1)) pixels = (((1 * r) + (4 * g)) + (16 * b)) hist = np.bincount(pixels.ravel(), minlength=64) hist = hist.astype(float) return np.log1p(hist)
[ "def", "chist", "(", "im", ")", ":", "im", "=", "(", "im", "//", "64", ")", "(", "r", ",", "g", ",", "b", ")", "=", "im", ".", "transpose", "(", "(", "2", ",", "0", ",", "1", ")", ")", "pixels", "=", "(", "(", "(", "1", "*", "r", ")", "+", "(", "4", "*", "g", ")", ")", "+", "(", "16", "*", "b", ")", ")", "hist", "=", "np", ".", "bincount", "(", "pixels", ".", "ravel", "(", ")", ",", "minlength", "=", "64", ")", "hist", "=", "hist", ".", "astype", "(", "float", ")", "return", "np", ".", "log1p", "(", "hist", ")" ]
compute color histogram of input image parameters im : ndarray should be an rgb image returns c : ndarray 1-d array of histogram values .
train
false
35,497
def sdm_from_vector(vec, O, K, **opts): (dics, gens) = parallel_dict_from_expr(sympify(vec), **opts) dic = {} for (i, d) in enumerate(dics): for (k, v) in d.items(): dic[((i,) + k)] = K.convert(v) return sdm_from_dict(dic, O)
[ "def", "sdm_from_vector", "(", "vec", ",", "O", ",", "K", ",", "**", "opts", ")", ":", "(", "dics", ",", "gens", ")", "=", "parallel_dict_from_expr", "(", "sympify", "(", "vec", ")", ",", "**", "opts", ")", "dic", "=", "{", "}", "for", "(", "i", ",", "d", ")", "in", "enumerate", "(", "dics", ")", ":", "for", "(", "k", ",", "v", ")", "in", "d", ".", "items", "(", ")", ":", "dic", "[", "(", "(", "i", ",", ")", "+", "k", ")", "]", "=", "K", ".", "convert", "(", "v", ")", "return", "sdm_from_dict", "(", "dic", ",", "O", ")" ]
create an sdm from an iterable of expressions .
train
false
35,498
def collapse_tabs(string, indentation=False, replace=' '): p = [] for x in string.splitlines(): n = ((indentation and (len(x) - len(x.lstrip()))) or 0) p.append((x[:n] + RE_TABS.sub(replace, x[n:]).strip())) return '\n'.join(p)
[ "def", "collapse_tabs", "(", "string", ",", "indentation", "=", "False", ",", "replace", "=", "' '", ")", ":", "p", "=", "[", "]", "for", "x", "in", "string", ".", "splitlines", "(", ")", ":", "n", "=", "(", "(", "indentation", "and", "(", "len", "(", "x", ")", "-", "len", "(", "x", ".", "lstrip", "(", ")", ")", ")", ")", "or", "0", ")", "p", ".", "append", "(", "(", "x", "[", ":", "n", "]", "+", "RE_TABS", ".", "sub", "(", "replace", ",", "x", "[", "n", ":", "]", ")", ".", "strip", "(", ")", ")", ")", "return", "'\\n'", ".", "join", "(", "p", ")" ]
returns a string with tabs replaced by a single space .
train
false
35,499
def Provides(*interfaces): spec = InstanceDeclarations.get(interfaces) if (spec is None): spec = ProvidesClass(*interfaces) InstanceDeclarations[interfaces] = spec return spec
[ "def", "Provides", "(", "*", "interfaces", ")", ":", "spec", "=", "InstanceDeclarations", ".", "get", "(", "interfaces", ")", "if", "(", "spec", "is", "None", ")", ":", "spec", "=", "ProvidesClass", "(", "*", "interfaces", ")", "InstanceDeclarations", "[", "interfaces", "]", "=", "spec", "return", "spec" ]
cache instance declarations instance declarations are shared among instances that have the same declaration .
train
false
35,500
def _get_module_name(path): modulename = path try: modulepath = re.match('(?P<modulepath>.*)\\.models.(?P<name>\\w+)$', path).group('modulepath') module = Module.objects.get(name=modulepath) modulename = _(module.title) except Module.DoesNotExist: pass except AttributeError: pass return modulename
[ "def", "_get_module_name", "(", "path", ")", ":", "modulename", "=", "path", "try", ":", "modulepath", "=", "re", ".", "match", "(", "'(?P<modulepath>.*)\\\\.models.(?P<name>\\\\w+)$'", ",", "path", ")", ".", "group", "(", "'modulepath'", ")", "module", "=", "Module", ".", "objects", ".", "get", "(", "name", "=", "modulepath", ")", "modulename", "=", "_", "(", "module", ".", "title", ")", "except", "Module", ".", "DoesNotExist", ":", "pass", "except", "AttributeError", ":", "pass", "return", "modulename" ]
returns real and translated module name for the given path .
train
false
35,501
def PILTowx(pimg): from wx_loader import wx wimg = wx.EmptyImage(pimg.size[0], pimg.size[1]) wimg.SetData(pimg.convert('RGB').tostring()) return wimg
[ "def", "PILTowx", "(", "pimg", ")", ":", "from", "wx_loader", "import", "wx", "wimg", "=", "wx", ".", "EmptyImage", "(", "pimg", ".", "size", "[", "0", "]", ",", "pimg", ".", "size", "[", "1", "]", ")", "wimg", ".", "SetData", "(", "pimg", ".", "convert", "(", "'RGB'", ")", ".", "tostring", "(", ")", ")", "return", "wimg" ]
convert a pil image to a wx image .
train
true
35,503
def inspect_image(image): status = base_status.copy() try: infos = _get_image_infos(image) try: for k in ['Size']: infos['Human_{0}'.format(k)] = _sizeof_fmt(int(infos[k])) except Exception: pass _valid(status, id_=image, out=infos) except Exception: _invalid(status, id_=image, out=traceback.format_exc(), comment='Image does not exist') return status
[ "def", "inspect_image", "(", "image", ")", ":", "status", "=", "base_status", ".", "copy", "(", ")", "try", ":", "infos", "=", "_get_image_infos", "(", "image", ")", "try", ":", "for", "k", "in", "[", "'Size'", "]", ":", "infos", "[", "'Human_{0}'", ".", "format", "(", "k", ")", "]", "=", "_sizeof_fmt", "(", "int", "(", "infos", "[", "k", "]", ")", ")", "except", "Exception", ":", "pass", "_valid", "(", "status", ",", "id_", "=", "image", ",", "out", "=", "infos", ")", "except", "Exception", ":", "_invalid", "(", "status", ",", "id_", "=", "image", ",", "out", "=", "traceback", ".", "format_exc", "(", ")", ",", "comment", "=", "'Image does not exist'", ")", "return", "status" ]
retrieves image information .
train
false
35,505
def _CalculateWriteOps(composite_indexes, old_entity, new_entity): if ((old_entity is not None) and (old_entity.property_list() == new_entity.property_list()) and (old_entity.raw_property_list() == new_entity.raw_property_list())): return (0, 0) index_writes = _ChangedIndexRows(composite_indexes, old_entity, new_entity) if (old_entity is None): index_writes += 1 return (1, index_writes)
[ "def", "_CalculateWriteOps", "(", "composite_indexes", ",", "old_entity", ",", "new_entity", ")", ":", "if", "(", "(", "old_entity", "is", "not", "None", ")", "and", "(", "old_entity", ".", "property_list", "(", ")", "==", "new_entity", ".", "property_list", "(", ")", ")", "and", "(", "old_entity", ".", "raw_property_list", "(", ")", "==", "new_entity", ".", "raw_property_list", "(", ")", ")", ")", ":", "return", "(", "0", ",", "0", ")", "index_writes", "=", "_ChangedIndexRows", "(", "composite_indexes", ",", "old_entity", ",", "new_entity", ")", "if", "(", "old_entity", "is", "None", ")", ":", "index_writes", "+=", "1", "return", "(", "1", ",", "index_writes", ")" ]
determines number of entity and index writes needed to write new_entity .
train
false
35,506
def quiet_kill(pid): try: os.kill(pid, signal.SIGTERM) except OSError: pass
[ "def", "quiet_kill", "(", "pid", ")", ":", "try", ":", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGTERM", ")", "except", "OSError", ":", "pass" ]
send a sigterm to pid; wont raise an exception if pid is not running .
train
false
35,507
def job_type(): return s3_rest_controller()
[ "def", "job_type", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
job types - restful controller .
train
false
35,508
def dominance_frontiers(G, start): idom = nx.immediate_dominators(G, start) df = {u: set() for u in idom} for u in idom: if (len(G.pred[u]) >= 2): for v in G.pred[u]: if (v in idom): while (v != idom[u]): df[v].add(u) v = idom[v] return df
[ "def", "dominance_frontiers", "(", "G", ",", "start", ")", ":", "idom", "=", "nx", ".", "immediate_dominators", "(", "G", ",", "start", ")", "df", "=", "{", "u", ":", "set", "(", ")", "for", "u", "in", "idom", "}", "for", "u", "in", "idom", ":", "if", "(", "len", "(", "G", ".", "pred", "[", "u", "]", ")", ">=", "2", ")", ":", "for", "v", "in", "G", ".", "pred", "[", "u", "]", ":", "if", "(", "v", "in", "idom", ")", ":", "while", "(", "v", "!=", "idom", "[", "u", "]", ")", ":", "df", "[", "v", "]", ".", "add", "(", "u", ")", "v", "=", "idom", "[", "v", "]", "return", "df" ]
returns the dominance frontiers of all nodes of a directed graph .
train
false
35,509
def _permission_protected_view(request): t = Template('This is a permission protected test. Username is {{ user.username }}. Permissions are {{ user.get_all_permissions }}.', name='Permissions Template') c = Context({'user': request.user}) return HttpResponse(t.render(c))
[ "def", "_permission_protected_view", "(", "request", ")", ":", "t", "=", "Template", "(", "'This is a permission protected test. Username is {{ user.username }}. Permissions are {{ user.get_all_permissions }}.'", ",", "name", "=", "'Permissions Template'", ")", "c", "=", "Context", "(", "{", "'user'", ":", "request", ".", "user", "}", ")", "return", "HttpResponse", "(", "t", ".", "render", "(", "c", ")", ")" ]
a simple view that is permission protected .
train
false
35,510
@shared_task() def unsubscribe_from_basket_task(email, newsletters=[]): if ((not BASKET_ENABLED) or (not waffle.switch_is_active('BASKET_SWITCH_ENABLED'))): return chain((lookup_user_task.subtask((email,)) | unsubscribe_user_task.subtask((newsletters,)))).delay()
[ "@", "shared_task", "(", ")", "def", "unsubscribe_from_basket_task", "(", "email", ",", "newsletters", "=", "[", "]", ")", ":", "if", "(", "(", "not", "BASKET_ENABLED", ")", "or", "(", "not", "waffle", ".", "switch_is_active", "(", "'BASKET_SWITCH_ENABLED'", ")", ")", ")", ":", "return", "chain", "(", "(", "lookup_user_task", ".", "subtask", "(", "(", "email", ",", ")", ")", "|", "unsubscribe_user_task", ".", "subtask", "(", "(", "newsletters", ",", ")", ")", ")", ")", ".", "delay", "(", ")" ]
remove user from basket task .
train
false
35,511
def _get_options(ret=None): defaults = {'level': 'LOG_INFO', 'facility': 'LOG_USER', 'options': []} attrs = {'level': 'level', 'facility': 'facility', 'tag': 'tag', 'options': 'options'} _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__, defaults=defaults) return _options
[ "def", "_get_options", "(", "ret", "=", "None", ")", ":", "defaults", "=", "{", "'level'", ":", "'LOG_INFO'", ",", "'facility'", ":", "'LOG_USER'", ",", "'options'", ":", "[", "]", "}", "attrs", "=", "{", "'level'", ":", "'level'", ",", "'facility'", ":", "'facility'", ",", "'tag'", ":", "'tag'", ",", "'options'", ":", "'options'", "}", "_options", "=", "salt", ".", "returners", ".", "get_returner_options", "(", "__virtualname__", ",", "ret", ",", "attrs", ",", "__salt__", "=", "__salt__", ",", "__opts__", "=", "__opts__", ",", "defaults", "=", "defaults", ")", "return", "_options" ]
get the postgres options from salt .
train
false
35,512
def compile(expression, escape_funcs=None, unescape_funcs=None): return _compile_from_parse_tree(parse_regex(tokenize_regex(expression)), escape_funcs=escape_funcs, unescape_funcs=unescape_funcs)
[ "def", "compile", "(", "expression", ",", "escape_funcs", "=", "None", ",", "unescape_funcs", "=", "None", ")", ":", "return", "_compile_from_parse_tree", "(", "parse_regex", "(", "tokenize_regex", "(", "expression", ")", ")", ",", "escape_funcs", "=", "escape_funcs", ",", "unescape_funcs", "=", "unescape_funcs", ")" ]
compile a c extension module using distutils .
train
true
35,513
def get_file_list(directory, exclude_patterns=None): result = [] if (not directory.endswith('/')): directory = (directory + '/') def include_file(file_path): if (not exclude_patterns): return True for exclude_pattern in exclude_patterns: if fnmatch.fnmatch(file_path, exclude_pattern): return False return True for (dirpath, dirnames, filenames) in os.walk(directory): base_path = dirpath.replace(directory, '') for filename in filenames: if base_path: file_path = os.path.join(base_path, filename) else: file_path = filename if include_file(file_path=file_path): result.append(file_path) return result
[ "def", "get_file_list", "(", "directory", ",", "exclude_patterns", "=", "None", ")", ":", "result", "=", "[", "]", "if", "(", "not", "directory", ".", "endswith", "(", "'/'", ")", ")", ":", "directory", "=", "(", "directory", "+", "'/'", ")", "def", "include_file", "(", "file_path", ")", ":", "if", "(", "not", "exclude_patterns", ")", ":", "return", "True", "for", "exclude_pattern", "in", "exclude_patterns", ":", "if", "fnmatch", ".", "fnmatch", "(", "file_path", ",", "exclude_pattern", ")", ":", "return", "False", "return", "True", "for", "(", "dirpath", ",", "dirnames", ",", "filenames", ")", "in", "os", ".", "walk", "(", "directory", ")", ":", "base_path", "=", "dirpath", ".", "replace", "(", "directory", ",", "''", ")", "for", "filename", "in", "filenames", ":", "if", "base_path", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "filename", ")", "else", ":", "file_path", "=", "filename", "if", "include_file", "(", "file_path", "=", "file_path", ")", ":", "result", ".", "append", "(", "file_path", ")", "return", "result" ]
recurisvely retrieve a list of files in the provided directory .
train
false
35,514
def write_keyval(path, dictionary, type_tag=None, tap_report=None): if os.path.isdir(path): path = os.path.join(path, 'keyval') keyval = open(path, 'a') if (type_tag is None): key_regex = re.compile('^[-\\.\\w]+$') else: if (type_tag not in ('attr', 'perf')): raise ValueError(('Invalid type tag: %s' % type_tag)) escaped_tag = re.escape(type_tag) key_regex = re.compile(('^[-\\.\\w]+\\{%s\\}$' % escaped_tag)) try: for key in sorted(dictionary.keys()): if (not key_regex.search(key)): raise ValueError(('Invalid key: %s' % key)) keyval.write(('%s=%s\n' % (key, dictionary[key]))) finally: keyval.close() if ((tap_report is not None) and tap_report.do_tap_report): tap_report.record_keyval(path, dictionary, type_tag=type_tag)
[ "def", "write_keyval", "(", "path", ",", "dictionary", ",", "type_tag", "=", "None", ",", "tap_report", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'keyval'", ")", "keyval", "=", "open", "(", "path", ",", "'a'", ")", "if", "(", "type_tag", "is", "None", ")", ":", "key_regex", "=", "re", ".", "compile", "(", "'^[-\\\\.\\\\w]+$'", ")", "else", ":", "if", "(", "type_tag", "not", "in", "(", "'attr'", ",", "'perf'", ")", ")", ":", "raise", "ValueError", "(", "(", "'Invalid type tag: %s'", "%", "type_tag", ")", ")", "escaped_tag", "=", "re", ".", "escape", "(", "type_tag", ")", "key_regex", "=", "re", ".", "compile", "(", "(", "'^[-\\\\.\\\\w]+\\\\{%s\\\\}$'", "%", "escaped_tag", ")", ")", "try", ":", "for", "key", "in", "sorted", "(", "dictionary", ".", "keys", "(", ")", ")", ":", "if", "(", "not", "key_regex", ".", "search", "(", "key", ")", ")", ":", "raise", "ValueError", "(", "(", "'Invalid key: %s'", "%", "key", ")", ")", "keyval", ".", "write", "(", "(", "'%s=%s\\n'", "%", "(", "key", ",", "dictionary", "[", "key", "]", ")", ")", ")", "finally", ":", "keyval", ".", "close", "(", ")", "if", "(", "(", "tap_report", "is", "not", "None", ")", "and", "tap_report", ".", "do_tap_report", ")", ":", "tap_report", ".", "record_keyval", "(", "path", ",", "dictionary", ",", "type_tag", "=", "type_tag", ")" ]
write a key-value pair format file out to a file .
train
false
35,515
def argmaxrnd(a, random_seed=None): if (a.ndim > 2): raise ValueError('argmaxrnd only accepts arrays of up to 2 dim') def rndc(x): return random.choice((x == bn.nanmax(x)).nonzero()[0]) random = (np.random if (random_seed is None) else np.random.RandomState(random_seed)) return (rndc(a) if (a.ndim == 1) else np.apply_along_axis(rndc, axis=1, arr=a))
[ "def", "argmaxrnd", "(", "a", ",", "random_seed", "=", "None", ")", ":", "if", "(", "a", ".", "ndim", ">", "2", ")", ":", "raise", "ValueError", "(", "'argmaxrnd only accepts arrays of up to 2 dim'", ")", "def", "rndc", "(", "x", ")", ":", "return", "random", ".", "choice", "(", "(", "x", "==", "bn", ".", "nanmax", "(", "x", ")", ")", ".", "nonzero", "(", ")", "[", "0", "]", ")", "random", "=", "(", "np", ".", "random", "if", "(", "random_seed", "is", "None", ")", "else", "np", ".", "random", ".", "RandomState", "(", "random_seed", ")", ")", "return", "(", "rndc", "(", "a", ")", "if", "(", "a", ".", "ndim", "==", "1", ")", "else", "np", ".", "apply_along_axis", "(", "rndc", ",", "axis", "=", "1", ",", "arr", "=", "a", ")", ")" ]
find the index of the maximum value for a given 1-d numpy array .
train
false
35,516
def createIndexes(tables, ifNotExists=True): errors = [] for table in tables: _dbschema_logger.info('creating indexes for table %s', table._imdbpyName) try: table.addIndexes(ifNotExists) except Exception as e: errors.append(e) continue return errors
[ "def", "createIndexes", "(", "tables", ",", "ifNotExists", "=", "True", ")", ":", "errors", "=", "[", "]", "for", "table", "in", "tables", ":", "_dbschema_logger", ".", "info", "(", "'creating indexes for table %s'", ",", "table", ".", "_imdbpyName", ")", "try", ":", "table", ".", "addIndexes", "(", "ifNotExists", ")", "except", "Exception", "as", "e", ":", "errors", ".", "append", "(", "e", ")", "continue", "return", "errors" ]
create the indexes in the database .
train
false
35,517
def is_proper_module(obj): return (inspect.ismodule(obj) and (obj is sys.modules.get(getattr(obj, '__name__', None))))
[ "def", "is_proper_module", "(", "obj", ")", ":", "return", "(", "inspect", ".", "ismodule", "(", "obj", ")", "and", "(", "obj", "is", "sys", ".", "modules", ".", "get", "(", "getattr", "(", "obj", ",", "'__name__'", ",", "None", ")", ")", ")", ")" ]
returns true if obj can be treated like a garbage collector root .
train
false
35,518
def inv(a): return (~ a)
[ "def", "inv", "(", "a", ")", ":", "return", "(", "~", "a", ")" ]
returns the inverse of a .
train
false
35,519
def require_valid_name(name, name_type, allow_empty=False): if (not isinstance(name, basestring)): raise ValidationError(('%s must be a string.' % name_type)) if (allow_empty and (name == '')): return if ((len(name) > 50) or (len(name) < 1)): raise ValidationError(('The length of %s should be between 1 and 50 characters; received %s' % (name_type, name))) if ((name[0] in string.whitespace) or (name[(-1)] in string.whitespace)): raise ValidationError('Names should not start or end with whitespace.') if re.search('\\s\\s+', name): raise ValidationError(('Adjacent whitespace in %s should be collapsed.' % name_type)) for character in feconf.INVALID_NAME_CHARS: if (character in name): raise ValidationError(('Invalid character %s in %s: %s' % (character, name_type, name)))
[ "def", "require_valid_name", "(", "name", ",", "name_type", ",", "allow_empty", "=", "False", ")", ":", "if", "(", "not", "isinstance", "(", "name", ",", "basestring", ")", ")", ":", "raise", "ValidationError", "(", "(", "'%s must be a string.'", "%", "name_type", ")", ")", "if", "(", "allow_empty", "and", "(", "name", "==", "''", ")", ")", ":", "return", "if", "(", "(", "len", "(", "name", ")", ">", "50", ")", "or", "(", "len", "(", "name", ")", "<", "1", ")", ")", ":", "raise", "ValidationError", "(", "(", "'The length of %s should be between 1 and 50 characters; received %s'", "%", "(", "name_type", ",", "name", ")", ")", ")", "if", "(", "(", "name", "[", "0", "]", "in", "string", ".", "whitespace", ")", "or", "(", "name", "[", "(", "-", "1", ")", "]", "in", "string", ".", "whitespace", ")", ")", ":", "raise", "ValidationError", "(", "'Names should not start or end with whitespace.'", ")", "if", "re", ".", "search", "(", "'\\\\s\\\\s+'", ",", "name", ")", ":", "raise", "ValidationError", "(", "(", "'Adjacent whitespace in %s should be collapsed.'", "%", "name_type", ")", ")", "for", "character", "in", "feconf", ".", "INVALID_NAME_CHARS", ":", "if", "(", "character", "in", "name", ")", ":", "raise", "ValidationError", "(", "(", "'Invalid character %s in %s: %s'", "%", "(", "character", ",", "name_type", ",", "name", ")", ")", ")" ]
generic name validation .
train
false
35,520
def network_acl_exists(network_acl_id=None, name=None, network_acl_name=None, tags=None, region=None, key=None, keyid=None, profile=None): if name: log.warning('boto_vpc.network_acl_exists: name parameter is deprecated use network_acl_name instead.') network_acl_name = name return resource_exists('network_acl', name=network_acl_name, resource_id=network_acl_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "network_acl_exists", "(", "network_acl_id", "=", "None", ",", "name", "=", "None", ",", "network_acl_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "name", ":", "log", ".", "warning", "(", "'boto_vpc.network_acl_exists: name parameter is deprecated use network_acl_name instead.'", ")", "network_acl_name", "=", "name", "return", "resource_exists", "(", "'network_acl'", ",", "name", "=", "network_acl_name", ",", "resource_id", "=", "network_acl_id", ",", "tags", "=", "tags", ",", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")" ]
checks if a network acl exists .
train
true
35,521
@register.simple_tag def hook_output(hook_name): snippets = [fn() for fn in hooks.get_hooks(hook_name)] return mark_safe(u''.join(snippets))
[ "@", "register", ".", "simple_tag", "def", "hook_output", "(", "hook_name", ")", ":", "snippets", "=", "[", "fn", "(", ")", "for", "fn", "in", "hooks", ".", "get_hooks", "(", "hook_name", ")", "]", "return", "mark_safe", "(", "u''", ".", "join", "(", "snippets", ")", ")" ]
example: {% hook_output insert_editor_css %} whenever we have a hook whose functions take no parameters and return a string .
train
false
35,522
def test_forumsread(topic, user): forumsread = ForumsRead() forumsread.user_id = user.id forumsread.forum_id = topic.forum_id forumsread.last_read = datetime.utcnow() forumsread.save() assert (forumsread is not None) forumsread.delete() forumsread = ForumsRead.query.filter_by(forum_id=forumsread.forum_id).first() assert (forumsread is None)
[ "def", "test_forumsread", "(", "topic", ",", "user", ")", ":", "forumsread", "=", "ForumsRead", "(", ")", "forumsread", ".", "user_id", "=", "user", ".", "id", "forumsread", ".", "forum_id", "=", "topic", ".", "forum_id", "forumsread", ".", "last_read", "=", "datetime", ".", "utcnow", "(", ")", "forumsread", ".", "save", "(", ")", "assert", "(", "forumsread", "is", "not", "None", ")", "forumsread", ".", "delete", "(", ")", "forumsread", "=", "ForumsRead", ".", "query", ".", "filter_by", "(", "forum_id", "=", "forumsread", ".", "forum_id", ")", ".", "first", "(", ")", "assert", "(", "forumsread", "is", "None", ")" ]
tests if the forumsread tracker can be saved/edited and deleted with the implemented save and delete methods .
train
false
35,524
def test_upper(value): return unicode(value).isupper()
[ "def", "test_upper", "(", "value", ")", ":", "return", "unicode", "(", "value", ")", ".", "isupper", "(", ")" ]
return true if the variable is uppercased .
train
false
35,525
def _api_retry(name, output, kwargs): value = kwargs.get('value') if ((name is None) or isinstance(name, basestring)): name = kwargs.get('Filedata') if ((name is None) or isinstance(name, basestring)): name = kwargs.get('nzbfile') password = kwargs.get('password') password = (password[0] if isinstance(password, list) else password) nzo_id = retry_job(value, name, password) if nzo_id: if isinstance(nzo_id, list): nzo_id = nzo_id[0] return report(output, keyword='', data={'status': True, 'nzo_id': nzo_id}) else: return report(output, _MSG_NO_ITEM)
[ "def", "_api_retry", "(", "name", ",", "output", ",", "kwargs", ")", ":", "value", "=", "kwargs", ".", "get", "(", "'value'", ")", "if", "(", "(", "name", "is", "None", ")", "or", "isinstance", "(", "name", ",", "basestring", ")", ")", ":", "name", "=", "kwargs", ".", "get", "(", "'Filedata'", ")", "if", "(", "(", "name", "is", "None", ")", "or", "isinstance", "(", "name", ",", "basestring", ")", ")", ":", "name", "=", "kwargs", ".", "get", "(", "'nzbfile'", ")", "password", "=", "kwargs", ".", "get", "(", "'password'", ")", "password", "=", "(", "password", "[", "0", "]", "if", "isinstance", "(", "password", ",", "list", ")", "else", "password", ")", "nzo_id", "=", "retry_job", "(", "value", ",", "name", ",", "password", ")", "if", "nzo_id", ":", "if", "isinstance", "(", "nzo_id", ",", "list", ")", ":", "nzo_id", "=", "nzo_id", "[", "0", "]", "return", "report", "(", "output", ",", "keyword", "=", "''", ",", "data", "=", "{", "'status'", ":", "True", ",", "'nzo_id'", ":", "nzo_id", "}", ")", "else", ":", "return", "report", "(", "output", ",", "_MSG_NO_ITEM", ")" ]
api: accepts name .
train
false