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
18,613
def _pofile_or_mofile(f, type, **kwargs): enc = kwargs.get('encoding') if (enc is None): enc = detect_encoding(f, (type == 'mofile')) kls = (((type == 'pofile') and _POFileParser) or _MOFileParser) parser = kls(f, encoding=enc, check_for_duplicates=kwargs.get('check_for_duplicates', False), klass=kwargs.get('klass')) instance = parser.parse() instance.wrapwidth = kwargs.get('wrapwidth', 78) return instance
[ "def", "_pofile_or_mofile", "(", "f", ",", "type", ",", "**", "kwargs", ")", ":", "enc", "=", "kwargs", ".", "get", "(", "'encoding'", ")", "if", "(", "enc", "is", "None", ")", ":", "enc", "=", "detect_encoding", "(", "f", ",", "(", "type", "==", "'mofile'", ")", ")", "kls", "=", "(", "(", "(", "type", "==", "'pofile'", ")", "and", "_POFileParser", ")", "or", "_MOFileParser", ")", "parser", "=", "kls", "(", "f", ",", "encoding", "=", "enc", ",", "check_for_duplicates", "=", "kwargs", ".", "get", "(", "'check_for_duplicates'", ",", "False", ")", ",", "klass", "=", "kwargs", ".", "get", "(", "'klass'", ")", ")", "instance", "=", "parser", ".", "parse", "(", ")", "instance", ".", "wrapwidth", "=", "kwargs", ".", "get", "(", "'wrapwidth'", ",", "78", ")", "return", "instance" ]
internal function used by :func:polib .
train
false
18,614
def unpurge(*packages): if (not packages): return {} old = __salt__['pkg.list_pkgs'](purge_desired=True) ret = {} __salt__['cmd.run'](['dpkg', '--set-selections'], stdin='\\n'.join(['{0} install'.format(x) for x in packages]), python_shell=False, output_loglevel='trace') __context__.pop('pkg.list_pkgs', None) new = __salt__['pkg.list_pkgs'](purge_desired=True) return salt.utils.compare_dicts(old, new)
[ "def", "unpurge", "(", "*", "packages", ")", ":", "if", "(", "not", "packages", ")", ":", "return", "{", "}", "old", "=", "__salt__", "[", "'pkg.list_pkgs'", "]", "(", "purge_desired", "=", "True", ")", "ret", "=", "{", "}", "__salt__", "[", "'cmd.run'", "]", "(", "[", "'dpkg'", ",", "'--set-selections'", "]", ",", "stdin", "=", "'\\\\n'", ".", "join", "(", "[", "'{0} install'", ".", "format", "(", "x", ")", "for", "x", "in", "packages", "]", ")", ",", "python_shell", "=", "False", ",", "output_loglevel", "=", "'trace'", ")", "__context__", ".", "pop", "(", "'pkg.list_pkgs'", ",", "None", ")", "new", "=", "__salt__", "[", "'pkg.list_pkgs'", "]", "(", "purge_desired", "=", "True", ")", "return", "salt", ".", "utils", ".", "compare_dicts", "(", "old", ",", "new", ")" ]
change package selection for each package specified to install cli example: .
train
true
18,615
def countFileChunks(zipinfo, chunksize): (count, extra) = divmod(zipinfo.file_size, chunksize) if (extra > 0): count += 1 return (count or 1)
[ "def", "countFileChunks", "(", "zipinfo", ",", "chunksize", ")", ":", "(", "count", ",", "extra", ")", "=", "divmod", "(", "zipinfo", ".", "file_size", ",", "chunksize", ")", "if", "(", "extra", ">", "0", ")", ":", "count", "+=", "1", "return", "(", "count", "or", "1", ")" ]
count the number of chunks that will result from the given l{zipinfo} .
train
false
18,616
def test_intersect_1(): old = ((10, 10, 10, 10, 10),) new = ((25, 5, 20),) answer = [(((0, slice(0, 10)),), ((1, slice(0, 10)),), ((2, slice(0, 5)),)), (((2, slice(5, 10)),),), (((3, slice(0, 10)),), ((4, slice(0, 10)),))] cross = list(intersect_chunks(old_chunks=old, new_chunks=new)) assert (answer == cross)
[ "def", "test_intersect_1", "(", ")", ":", "old", "=", "(", "(", "10", ",", "10", ",", "10", ",", "10", ",", "10", ")", ",", ")", "new", "=", "(", "(", "25", ",", "5", ",", "20", ")", ",", ")", "answer", "=", "[", "(", "(", "(", "0", ",", "slice", "(", "0", ",", "10", ")", ")", ",", ")", ",", "(", "(", "1", ",", "slice", "(", "0", ",", "10", ")", ")", ",", ")", ",", "(", "(", "2", ",", "slice", "(", "0", ",", "5", ")", ")", ",", ")", ")", ",", "(", "(", "(", "2", ",", "slice", "(", "5", ",", "10", ")", ")", ",", ")", ",", ")", ",", "(", "(", "(", "3", ",", "slice", "(", "0", ",", "10", ")", ")", ",", ")", ",", "(", "(", "4", ",", "slice", "(", "0", ",", "10", ")", ")", ",", ")", ")", "]", "cross", "=", "list", "(", "intersect_chunks", "(", "old_chunks", "=", "old", ",", "new_chunks", "=", "new", ")", ")", "assert", "(", "answer", "==", "cross", ")" ]
convert 1 d chunks .
train
false
18,617
def strip_spaces_and_quotes(value): value = (value.strip() if value else '') if (value and (len(value) > 1) and (value[0] == value[(-1)] == '"')): value = value[1:(-1)] if (not value): value = '' return value
[ "def", "strip_spaces_and_quotes", "(", "value", ")", ":", "value", "=", "(", "value", ".", "strip", "(", ")", "if", "value", "else", "''", ")", "if", "(", "value", "and", "(", "len", "(", "value", ")", ">", "1", ")", "and", "(", "value", "[", "0", "]", "==", "value", "[", "(", "-", "1", ")", "]", "==", "'\"'", ")", ")", ":", "value", "=", "value", "[", "1", ":", "(", "-", "1", ")", "]", "if", "(", "not", "value", ")", ":", "value", "=", "''", "return", "value" ]
remove invalid whitespace and/or single pair of dquotes and return none for empty strings .
train
true
18,618
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
18,619
def _datestamp_to_datetime(datetime_): if isinstance(datetime_, basestring): try: datetime_ = date_str_to_datetime(datetime_) except TypeError: return None except ValueError: return None if (not isinstance(datetime_, datetime.datetime)): return None if (datetime_.tzinfo is not None): return datetime_ datetime_ = datetime_.replace(tzinfo=pytz.utc) datetime_ = datetime_.astimezone(get_display_timezone()) return datetime_
[ "def", "_datestamp_to_datetime", "(", "datetime_", ")", ":", "if", "isinstance", "(", "datetime_", ",", "basestring", ")", ":", "try", ":", "datetime_", "=", "date_str_to_datetime", "(", "datetime_", ")", "except", "TypeError", ":", "return", "None", "except", "ValueError", ":", "return", "None", "if", "(", "not", "isinstance", "(", "datetime_", ",", "datetime", ".", "datetime", ")", ")", ":", "return", "None", "if", "(", "datetime_", ".", "tzinfo", "is", "not", "None", ")", ":", "return", "datetime_", "datetime_", "=", "datetime_", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", "datetime_", "=", "datetime_", ".", "astimezone", "(", "get_display_timezone", "(", ")", ")", "return", "datetime_" ]
converts a datestamp to a datetime .
train
false
18,620
@docstring.dedent_interpd def magnitude_spectrum(x, Fs=None, window=None, pad_to=None, sides=None): return _single_spectrum_helper(x=x, Fs=Fs, window=window, pad_to=pad_to, sides=sides, mode=u'magnitude')
[ "@", "docstring", ".", "dedent_interpd", "def", "magnitude_spectrum", "(", "x", ",", "Fs", "=", "None", ",", "window", "=", "None", ",", "pad_to", "=", "None", ",", "sides", "=", "None", ")", ":", "return", "_single_spectrum_helper", "(", "x", "=", "x", ",", "Fs", "=", "Fs", ",", "window", "=", "window", ",", "pad_to", "=", "pad_to", ",", "sides", "=", "sides", ",", "mode", "=", "u'magnitude'", ")" ]
compute the magnitude of the frequency spectrum of *x* .
train
false
18,622
@register.filter(u'timeuntil', is_safe=False) def timeuntil_filter(value, arg=None): if (not value): return u'' try: return timeuntil(value, arg) except (ValueError, TypeError): return u''
[ "@", "register", ".", "filter", "(", "u'timeuntil'", ",", "is_safe", "=", "False", ")", "def", "timeuntil_filter", "(", "value", ",", "arg", "=", "None", ")", ":", "if", "(", "not", "value", ")", ":", "return", "u''", "try", ":", "return", "timeuntil", "(", "value", ",", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "u''" ]
formats a date as the time until that date .
train
false
18,623
def get_repo_info_tuple_contents(repo_info_tuple): if (len(repo_info_tuple) == 6): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, tool_dependencies) = repo_info_tuple repository_dependencies = None elif (len(repo_info_tuple) == 7): (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies) = repo_info_tuple return (description, repository_clone_url, changeset_revision, ctx_rev, repository_owner, repository_dependencies, tool_dependencies)
[ "def", "get_repo_info_tuple_contents", "(", "repo_info_tuple", ")", ":", "if", "(", "len", "(", "repo_info_tuple", ")", "==", "6", ")", ":", "(", "description", ",", "repository_clone_url", ",", "changeset_revision", ",", "ctx_rev", ",", "repository_owner", ",", "tool_dependencies", ")", "=", "repo_info_tuple", "repository_dependencies", "=", "None", "elif", "(", "len", "(", "repo_info_tuple", ")", "==", "7", ")", ":", "(", "description", ",", "repository_clone_url", ",", "changeset_revision", ",", "ctx_rev", ",", "repository_owner", ",", "repository_dependencies", ",", "tool_dependencies", ")", "=", "repo_info_tuple", "return", "(", "description", ",", "repository_clone_url", ",", "changeset_revision", ",", "ctx_rev", ",", "repository_owner", ",", "repository_dependencies", ",", "tool_dependencies", ")" ]
take care in handling the repo_info_tuple as it evolves over time as new tool shed features are introduced .
train
false
18,624
def _write_header(name, header, required, stream, encoder, strict=False): stream.write_ushort(len(name)) stream.write_utf8_string(name) stream.write_uchar(required) write_pos = stream.tell() stream.write_ulong(0) old_pos = stream.tell() encoder.writeElement(header) new_pos = stream.tell() if strict: stream.seek(write_pos) stream.write_ulong((new_pos - old_pos)) stream.seek(new_pos)
[ "def", "_write_header", "(", "name", ",", "header", ",", "required", ",", "stream", ",", "encoder", ",", "strict", "=", "False", ")", ":", "stream", ".", "write_ushort", "(", "len", "(", "name", ")", ")", "stream", ".", "write_utf8_string", "(", "name", ")", "stream", ".", "write_uchar", "(", "required", ")", "write_pos", "=", "stream", ".", "tell", "(", ")", "stream", ".", "write_ulong", "(", "0", ")", "old_pos", "=", "stream", ".", "tell", "(", ")", "encoder", ".", "writeElement", "(", "header", ")", "new_pos", "=", "stream", ".", "tell", "(", ")", "if", "strict", ":", "stream", ".", "seek", "(", "write_pos", ")", "stream", ".", "write_ulong", "(", "(", "new_pos", "-", "old_pos", ")", ")", "stream", ".", "seek", "(", "new_pos", ")" ]
write amf message header .
train
true
18,626
def dmp_from_sympy(f, u, K): if (not u): return dup_from_sympy(f, K) v = (u - 1) return dmp_strip([dmp_from_sympy(c, v, K) for c in f], u)
[ "def", "dmp_from_sympy", "(", "f", ",", "u", ",", "K", ")", ":", "if", "(", "not", "u", ")", ":", "return", "dup_from_sympy", "(", "f", ",", "K", ")", "v", "=", "(", "u", "-", "1", ")", "return", "dmp_strip", "(", "[", "dmp_from_sympy", "(", "c", ",", "v", ",", "K", ")", "for", "c", "in", "f", "]", ",", "u", ")" ]
convert the ground domain of f from sympy to k .
train
false
18,627
def create_event_dict(start_time, nodes_list): import copy events = {} for node in nodes_list: estimated_threads = node.get(u'num_threads', 1) estimated_memory_gb = node.get(u'estimated_memory_gb', 1.0) runtime_threads = node.get(u'runtime_threads', 0) runtime_memory_gb = node.get(u'runtime_memory_gb', 0.0) node[u'estimated_threads'] = estimated_threads node[u'estimated_memory_gb'] = estimated_memory_gb node[u'runtime_threads'] = runtime_threads node[u'runtime_memory_gb'] = runtime_memory_gb start_node = node finish_node = copy.deepcopy(node) start_node[u'event'] = u'start' finish_node[u'event'] = u'finish' start_delta = (node[u'start'] - start_time).total_seconds() finish_delta = (node[u'finish'] - start_time).total_seconds() if (events.has_key(start_delta) or events.has_key(finish_delta)): err_msg = u'Event logged twice or events started at exact same time!' raise KeyError(err_msg) events[start_delta] = start_node events[finish_delta] = finish_node return events
[ "def", "create_event_dict", "(", "start_time", ",", "nodes_list", ")", ":", "import", "copy", "events", "=", "{", "}", "for", "node", "in", "nodes_list", ":", "estimated_threads", "=", "node", ".", "get", "(", "u'num_threads'", ",", "1", ")", "estimated_memory_gb", "=", "node", ".", "get", "(", "u'estimated_memory_gb'", ",", "1.0", ")", "runtime_threads", "=", "node", ".", "get", "(", "u'runtime_threads'", ",", "0", ")", "runtime_memory_gb", "=", "node", ".", "get", "(", "u'runtime_memory_gb'", ",", "0.0", ")", "node", "[", "u'estimated_threads'", "]", "=", "estimated_threads", "node", "[", "u'estimated_memory_gb'", "]", "=", "estimated_memory_gb", "node", "[", "u'runtime_threads'", "]", "=", "runtime_threads", "node", "[", "u'runtime_memory_gb'", "]", "=", "runtime_memory_gb", "start_node", "=", "node", "finish_node", "=", "copy", ".", "deepcopy", "(", "node", ")", "start_node", "[", "u'event'", "]", "=", "u'start'", "finish_node", "[", "u'event'", "]", "=", "u'finish'", "start_delta", "=", "(", "node", "[", "u'start'", "]", "-", "start_time", ")", ".", "total_seconds", "(", ")", "finish_delta", "=", "(", "node", "[", "u'finish'", "]", "-", "start_time", ")", ".", "total_seconds", "(", ")", "if", "(", "events", ".", "has_key", "(", "start_delta", ")", "or", "events", ".", "has_key", "(", "finish_delta", ")", ")", ":", "err_msg", "=", "u'Event logged twice or events started at exact same time!'", "raise", "KeyError", "(", "err_msg", ")", "events", "[", "start_delta", "]", "=", "start_node", "events", "[", "finish_delta", "]", "=", "finish_node", "return", "events" ]
function to generate a dictionary of event nodes from the nodes list parameters start_time : datetime .
train
false
18,628
def _get_partners(frag_index, part_nodes): return [part_nodes[((frag_index - 1) % len(part_nodes))], part_nodes[((frag_index + 1) % len(part_nodes))]]
[ "def", "_get_partners", "(", "frag_index", ",", "part_nodes", ")", ":", "return", "[", "part_nodes", "[", "(", "(", "frag_index", "-", "1", ")", "%", "len", "(", "part_nodes", ")", ")", "]", ",", "part_nodes", "[", "(", "(", "frag_index", "+", "1", ")", "%", "len", "(", "part_nodes", ")", ")", "]", "]" ]
returns the left and right partners of the node whose index is equal to the given frag_index .
train
false
18,629
def single_char_or_whitespace_or_unicode(argument): if (argument == 'tab'): char = ' DCTB ' elif (argument == 'space'): char = ' ' else: char = single_char_or_unicode(argument) return char
[ "def", "single_char_or_whitespace_or_unicode", "(", "argument", ")", ":", "if", "(", "argument", "==", "'tab'", ")", ":", "char", "=", "' DCTB '", "elif", "(", "argument", "==", "'space'", ")", ":", "char", "=", "' '", "else", ":", "char", "=", "single_char_or_unicode", "(", "argument", ")", "return", "char" ]
as with single_char_or_unicode .
train
false
18,630
def resolve_interpreter(exe): orig_exe = exe python_versions = get_installed_pythons() if (exe in python_versions): exe = python_versions[exe] if (os.path.abspath(exe) != exe): paths = os.environ.get('PATH', '').split(os.pathsep) for path in paths: if os.path.exists(join(path, exe)): exe = join(path, exe) break if (not os.path.exists(exe)): logger.fatal(('The path %s (from --python=%s) does not exist' % (exe, orig_exe))) raise SystemExit(3) if (not is_executable(exe)): logger.fatal(('The path %s (from --python=%s) is not an executable file' % (exe, orig_exe))) raise SystemExit(3) return exe
[ "def", "resolve_interpreter", "(", "exe", ")", ":", "orig_exe", "=", "exe", "python_versions", "=", "get_installed_pythons", "(", ")", "if", "(", "exe", "in", "python_versions", ")", ":", "exe", "=", "python_versions", "[", "exe", "]", "if", "(", "os", ".", "path", ".", "abspath", "(", "exe", ")", "!=", "exe", ")", ":", "paths", "=", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "''", ")", ".", "split", "(", "os", ".", "pathsep", ")", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "exists", "(", "join", "(", "path", ",", "exe", ")", ")", ":", "exe", "=", "join", "(", "path", ",", "exe", ")", "break", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "exe", ")", ")", ":", "logger", ".", "fatal", "(", "(", "'The path %s (from --python=%s) does not exist'", "%", "(", "exe", ",", "orig_exe", ")", ")", ")", "raise", "SystemExit", "(", "3", ")", "if", "(", "not", "is_executable", "(", "exe", ")", ")", ":", "logger", ".", "fatal", "(", "(", "'The path %s (from --python=%s) is not an executable file'", "%", "(", "exe", ",", "orig_exe", ")", ")", ")", "raise", "SystemExit", "(", "3", ")", "return", "exe" ]
if the executable given isnt an absolute path .
train
true
18,633
def insert_fake_data(db, tablename, **kw): column_names = [] column_value_placeholders = [] column_values = [] for (k, v) in kw.items(): column_names.append(k) column_value_placeholders.append('%s') column_values.append(v) column_names = ', '.join(column_names) column_value_placeholders = ', '.join(column_value_placeholders) db.run('INSERT INTO {} ({}) VALUES ({})'.format(tablename, column_names, column_value_placeholders), column_values) return kw
[ "def", "insert_fake_data", "(", "db", ",", "tablename", ",", "**", "kw", ")", ":", "column_names", "=", "[", "]", "column_value_placeholders", "=", "[", "]", "column_values", "=", "[", "]", "for", "(", "k", ",", "v", ")", "in", "kw", ".", "items", "(", ")", ":", "column_names", ".", "append", "(", "k", ")", "column_value_placeholders", ".", "append", "(", "'%s'", ")", "column_values", ".", "append", "(", "v", ")", "column_names", "=", "', '", ".", "join", "(", "column_names", ")", "column_value_placeholders", "=", "', '", ".", "join", "(", "column_value_placeholders", ")", "db", ".", "run", "(", "'INSERT INTO {} ({}) VALUES ({})'", ".", "format", "(", "tablename", ",", "column_names", ",", "column_value_placeholders", ")", ",", "column_values", ")", "return", "kw" ]
insert fake data into the database .
train
false
18,635
def hed2rgb(hed): return combine_stains(hed, rgb_from_hed)
[ "def", "hed2rgb", "(", "hed", ")", ":", "return", "combine_stains", "(", "hed", ",", "rgb_from_hed", ")" ]
haematoxylin-eosin-dab to rgb color space conversion .
train
false
18,636
def _get_value(f, i, values=False): if values: return f.values[i] with catch_warnings(record=True): return f.ix[i]
[ "def", "_get_value", "(", "f", ",", "i", ",", "values", "=", "False", ")", ":", "if", "values", ":", "return", "f", ".", "values", "[", "i", "]", "with", "catch_warnings", "(", "record", "=", "True", ")", ":", "return", "f", ".", "ix", "[", "i", "]" ]
retrieve a keys value from a context item .
train
false
18,637
@evalcontextfilter def do_join(eval_ctx, value, d=u''): if (not eval_ctx.autoescape): return unicode(d).join(imap(unicode, value)) if (not hasattr(d, '__html__')): value = list(value) do_escape = False for (idx, item) in enumerate(value): if hasattr(item, '__html__'): do_escape = True else: value[idx] = unicode(item) if do_escape: d = escape(d) else: d = unicode(d) return d.join(value) return soft_unicode(d).join(imap(soft_unicode, value))
[ "@", "evalcontextfilter", "def", "do_join", "(", "eval_ctx", ",", "value", ",", "d", "=", "u''", ")", ":", "if", "(", "not", "eval_ctx", ".", "autoescape", ")", ":", "return", "unicode", "(", "d", ")", ".", "join", "(", "imap", "(", "unicode", ",", "value", ")", ")", "if", "(", "not", "hasattr", "(", "d", ",", "'__html__'", ")", ")", ":", "value", "=", "list", "(", "value", ")", "do_escape", "=", "False", "for", "(", "idx", ",", "item", ")", "in", "enumerate", "(", "value", ")", ":", "if", "hasattr", "(", "item", ",", "'__html__'", ")", ":", "do_escape", "=", "True", "else", ":", "value", "[", "idx", "]", "=", "unicode", "(", "item", ")", "if", "do_escape", ":", "d", "=", "escape", "(", "d", ")", "else", ":", "d", "=", "unicode", "(", "d", ")", "return", "d", ".", "join", "(", "value", ")", "return", "soft_unicode", "(", "d", ")", ".", "join", "(", "imap", "(", "soft_unicode", ",", "value", ")", ")" ]
return a string which is the concatenation of the strings in the sequence .
train
true
18,638
def n_to_data(n): if (n < 0): raise NetworkXError('Numbers in graph6 format must be non-negative.') if (n <= 62): return [n] if (n <= 258047): return [63, ((n >> 12) & 63), ((n >> 6) & 63), (n & 63)] if (n <= 68719476735): return [63, 63, ((n >> 30) & 63), ((n >> 24) & 63), ((n >> 18) & 63), ((n >> 12) & 63), ((n >> 6) & 63), (n & 63)] raise NetworkXError('Numbers above 68719476735 are not supported by graph6')
[ "def", "n_to_data", "(", "n", ")", ":", "if", "(", "n", "<", "0", ")", ":", "raise", "NetworkXError", "(", "'Numbers in graph6 format must be non-negative.'", ")", "if", "(", "n", "<=", "62", ")", ":", "return", "[", "n", "]", "if", "(", "n", "<=", "258047", ")", ":", "return", "[", "63", ",", "(", "(", "n", ">>", "12", ")", "&", "63", ")", ",", "(", "(", "n", ">>", "6", ")", "&", "63", ")", ",", "(", "n", "&", "63", ")", "]", "if", "(", "n", "<=", "68719476735", ")", ":", "return", "[", "63", ",", "63", ",", "(", "(", "n", ">>", "30", ")", "&", "63", ")", ",", "(", "(", "n", ">>", "24", ")", "&", "63", ")", ",", "(", "(", "n", ">>", "18", ")", "&", "63", ")", ",", "(", "(", "n", ">>", "12", ")", "&", "63", ")", ",", "(", "(", "n", ">>", "6", ")", "&", "63", ")", ",", "(", "n", "&", "63", ")", "]", "raise", "NetworkXError", "(", "'Numbers above 68719476735 are not supported by graph6'", ")" ]
convert an integer to one- .
train
false
18,639
def set_setting(key, val, env=None): return settings.set(key, val, env=env)
[ "def", "set_setting", "(", "key", ",", "val", ",", "env", "=", "None", ")", ":", "return", "settings", ".", "set", "(", "key", ",", "val", ",", "env", "=", "env", ")" ]
set a qutebrowser setting .
train
true
18,640
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
18,641
def _remove_async_tag_url(question_id): return reverse('questions.remove_tag_async', kwargs={'question_id': question_id})
[ "def", "_remove_async_tag_url", "(", "question_id", ")", ":", "return", "reverse", "(", "'questions.remove_tag_async'", ",", "kwargs", "=", "{", "'question_id'", ":", "question_id", "}", ")" ]
return url to remove_tag_async on q .
train
false
18,642
def number_of_edges(G): return G.number_of_edges()
[ "def", "number_of_edges", "(", "G", ")", ":", "return", "G", ".", "number_of_edges", "(", ")" ]
return the number of edges in the graph .
train
false
18,644
def guard_https_ver(): set_https_verification(cfg.enable_https_verification())
[ "def", "guard_https_ver", "(", ")", ":", "set_https_verification", "(", "cfg", ".", "enable_https_verification", "(", ")", ")" ]
callback for change of https verification .
train
false
18,646
def set_virt_disk_driver(self, driver): if (driver in validate.VIRT_DISK_DRIVERS): self.virt_disk_driver = driver else: raise CX(_(('invalid virt disk driver type (%s)' % driver)))
[ "def", "set_virt_disk_driver", "(", "self", ",", "driver", ")", ":", "if", "(", "driver", "in", "validate", ".", "VIRT_DISK_DRIVERS", ")", ":", "self", ".", "virt_disk_driver", "=", "driver", "else", ":", "raise", "CX", "(", "_", "(", "(", "'invalid virt disk driver type (%s)'", "%", "driver", ")", ")", ")" ]
for virt only .
train
false
18,647
def get_conv_output_shape(image_shape, kernel_shape, border_mode, subsample, filter_dilation=None): (bsize, imshp) = (image_shape[0], image_shape[2:]) (nkern, kshp) = (kernel_shape[0], kernel_shape[2:]) if (filter_dilation is None): filter_dilation = numpy.ones(len(subsample), dtype='int') if isinstance(border_mode, tuple): out_shp = tuple((get_conv_shape_1axis(imshp[i], kshp[i], border_mode[i], subsample[i], filter_dilation[i]) for i in range(len(subsample)))) else: out_shp = tuple((get_conv_shape_1axis(imshp[i], kshp[i], border_mode, subsample[i], filter_dilation[i]) for i in range(len(subsample)))) return ((bsize, nkern) + out_shp)
[ "def", "get_conv_output_shape", "(", "image_shape", ",", "kernel_shape", ",", "border_mode", ",", "subsample", ",", "filter_dilation", "=", "None", ")", ":", "(", "bsize", ",", "imshp", ")", "=", "(", "image_shape", "[", "0", "]", ",", "image_shape", "[", "2", ":", "]", ")", "(", "nkern", ",", "kshp", ")", "=", "(", "kernel_shape", "[", "0", "]", ",", "kernel_shape", "[", "2", ":", "]", ")", "if", "(", "filter_dilation", "is", "None", ")", ":", "filter_dilation", "=", "numpy", ".", "ones", "(", "len", "(", "subsample", ")", ",", "dtype", "=", "'int'", ")", "if", "isinstance", "(", "border_mode", ",", "tuple", ")", ":", "out_shp", "=", "tuple", "(", "(", "get_conv_shape_1axis", "(", "imshp", "[", "i", "]", ",", "kshp", "[", "i", "]", ",", "border_mode", "[", "i", "]", ",", "subsample", "[", "i", "]", ",", "filter_dilation", "[", "i", "]", ")", "for", "i", "in", "range", "(", "len", "(", "subsample", ")", ")", ")", ")", "else", ":", "out_shp", "=", "tuple", "(", "(", "get_conv_shape_1axis", "(", "imshp", "[", "i", "]", ",", "kshp", "[", "i", "]", ",", "border_mode", ",", "subsample", "[", "i", "]", ",", "filter_dilation", "[", "i", "]", ")", "for", "i", "in", "range", "(", "len", "(", "subsample", ")", ")", ")", ")", "return", "(", "(", "bsize", ",", "nkern", ")", "+", "out_shp", ")" ]
this function compute the output shape of convolution operation .
train
false
18,648
def service_get(context, service_id=None, backend_match_level=None, **filters): return IMPL.service_get(context, service_id, backend_match_level, **filters)
[ "def", "service_get", "(", "context", ",", "service_id", "=", "None", ",", "backend_match_level", "=", "None", ",", "**", "filters", ")", ":", "return", "IMPL", ".", "service_get", "(", "context", ",", "service_id", ",", "backend_match_level", ",", "**", "filters", ")" ]
return a specific services cli examples: .
train
false
18,649
def SetIfNotEmpty(dict, attr_name, value): if value: dict[attr_name] = value
[ "def", "SetIfNotEmpty", "(", "dict", ",", "attr_name", ",", "value", ")", ":", "if", "value", ":", "dict", "[", "attr_name", "]", "=", "value" ]
if "value" is not empty and non-zero .
train
false
18,650
def reset_gametime(): global GAME_TIME_OFFSET GAME_TIME_OFFSET = runtime() ServerConfig.objects.conf('gametime_offset', GAME_TIME_OFFSET)
[ "def", "reset_gametime", "(", ")", ":", "global", "GAME_TIME_OFFSET", "GAME_TIME_OFFSET", "=", "runtime", "(", ")", "ServerConfig", ".", "objects", ".", "conf", "(", "'gametime_offset'", ",", "GAME_TIME_OFFSET", ")" ]
resets the game time to make it start from the current time .
train
false
18,652
def keypair_delete(name, profile=None): conn = _auth(profile) return conn.keypair_delete(name)
[ "def", "keypair_delete", "(", "name", ",", "profile", "=", "None", ")", ":", "conn", "=", "_auth", "(", "profile", ")", "return", "conn", ".", "keypair_delete", "(", "name", ")" ]
add a keypair to nova cli example: .
train
true
18,653
def assert_equal(x, y, msg=None): if (x == y): return std_msg = ('%s not equal to %s' % (_safe_rep(x), _safe_rep(y))) raise AssertionError(_format_msg(msg, std_msg))
[ "def", "assert_equal", "(", "x", ",", "y", ",", "msg", "=", "None", ")", ":", "if", "(", "x", "==", "y", ")", ":", "return", "std_msg", "=", "(", "'%s not equal to %s'", "%", "(", "_safe_rep", "(", "x", ")", ",", "_safe_rep", "(", "y", ")", ")", ")", "raise", "AssertionError", "(", "_format_msg", "(", "msg", ",", "std_msg", ")", ")" ]
fail if given objects are unequal as determined by the == operator .
train
false
18,654
def remove_targets(Rule, Ids, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(Ids, string_types): Ids = json.loads(Ids) failures = conn.remove_targets(Rule=Rule, Ids=Ids) if (failures and (failures.get('FailedEntryCount', 0) > 0)): return {'failures': failures.get('FailedEntries', 1)} else: return {'failures': None} except ClientError as e: err = __utils__['boto3.get_error'](e) if (e.response.get('Error', {}).get('Code') == 'RuleNotFoundException'): return {'error': 'Rule {0} not found'.format(Rule)} return {'error': __utils__['boto3.get_error'](e)}
[ "def", "remove_targets", "(", "Rule", ",", "Ids", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", "=", "keyid", ",", "profile", "=", "profile", ")", "if", "isinstance", "(", "Ids", ",", "string_types", ")", ":", "Ids", "=", "json", ".", "loads", "(", "Ids", ")", "failures", "=", "conn", ".", "remove_targets", "(", "Rule", "=", "Rule", ",", "Ids", "=", "Ids", ")", "if", "(", "failures", "and", "(", "failures", ".", "get", "(", "'FailedEntryCount'", ",", "0", ")", ">", "0", ")", ")", ":", "return", "{", "'failures'", ":", "failures", ".", "get", "(", "'FailedEntries'", ",", "1", ")", "}", "else", ":", "return", "{", "'failures'", ":", "None", "}", "except", "ClientError", "as", "e", ":", "err", "=", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "if", "(", "e", ".", "response", ".", "get", "(", "'Error'", ",", "{", "}", ")", ".", "get", "(", "'Code'", ")", "==", "'RuleNotFoundException'", ")", ":", "return", "{", "'error'", ":", "'Rule {0} not found'", ".", "format", "(", "Rule", ")", "}", "return", "{", "'error'", ":", "__utils__", "[", "'boto3.get_error'", "]", "(", "e", ")", "}" ]
given a rule name remove the named targets from the target list returns a dictionary describing any failures .
train
true
18,655
def emergencySetup(BearerCapability_presence=0): a = TpPd(pd=3) b = MessageType(mesType=14) packet = (a / b) if (BearerCapability_presence is 1): c = BearerCapabilityHdr(ieiBC=4, eightBitBC=0) packet = (packet / c) return packet
[ "def", "emergencySetup", "(", "BearerCapability_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "3", ")", "b", "=", "MessageType", "(", "mesType", "=", "14", ")", "packet", "=", "(", "a", "/", "b", ")", "if", "(", "BearerCapability_presence", "is", "1", ")", ":", "c", "=", "BearerCapabilityHdr", "(", "ieiBC", "=", "4", ",", "eightBitBC", "=", "0", ")", "packet", "=", "(", "packet", "/", "c", ")", "return", "packet" ]
emergency setup section 9 .
train
true
18,656
def to_epoch_milliseconds(dt): return int(math.floor((1000.0 * epoch_timestamp(dt))))
[ "def", "to_epoch_milliseconds", "(", "dt", ")", ":", "return", "int", "(", "math", ".", "floor", "(", "(", "1000.0", "*", "epoch_timestamp", "(", "dt", ")", ")", ")", ")" ]
returns the number of milliseconds from the epoch to date .
train
false
18,657
def _triage_fnirs_pick(ch, fnirs): if (fnirs is True): return True elif ((ch['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBO) and (fnirs == 'hbo')): return True elif ((ch['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBR) and (fnirs == 'hbr')): return True return False
[ "def", "_triage_fnirs_pick", "(", "ch", ",", "fnirs", ")", ":", "if", "(", "fnirs", "is", "True", ")", ":", "return", "True", "elif", "(", "(", "ch", "[", "'coil_type'", "]", "==", "FIFF", ".", "FIFFV_COIL_FNIRS_HBO", ")", "and", "(", "fnirs", "==", "'hbo'", ")", ")", ":", "return", "True", "elif", "(", "(", "ch", "[", "'coil_type'", "]", "==", "FIFF", ".", "FIFFV_COIL_FNIRS_HBR", ")", "and", "(", "fnirs", "==", "'hbr'", ")", ")", ":", "return", "True", "return", "False" ]
triage an fnirs pick type .
train
false
18,658
def gf_value(f, a): result = 0 for c in f: result *= a result += c return result
[ "def", "gf_value", "(", "f", ",", "a", ")", ":", "result", "=", "0", "for", "c", "in", "f", ":", "result", "*=", "a", "result", "+=", "c", "return", "result" ]
value of polynomial f at a in field r .
train
false
18,660
def _prepare_xml(options=None, state=None): if state: _state = '0' else: _state = '2' xml = "<?xml version='1.0'?>\n<checkresults>\n" if (('service' in options) and (options['service'] != '')): xml += (("<checkresult type='service' checktype='" + str(options['checktype'])) + "'>") xml += (('<hostname>' + cgi.escape(options['hostname'], True)) + '</hostname>') xml += (('<servicename>' + cgi.escape(options['service'], True)) + '</servicename>') else: xml += (("<checkresult type='host' checktype='" + str(options['checktype'])) + "'>") xml += (('<hostname>' + cgi.escape(options['hostname'], True)) + '</hostname>') xml += (('<state>' + _state) + '</state>') if ('output' in options): xml += (('<output>' + cgi.escape(options['output'], True)) + '</output>') xml += '</checkresult>' xml += '\n</checkresults>' return xml
[ "def", "_prepare_xml", "(", "options", "=", "None", ",", "state", "=", "None", ")", ":", "if", "state", ":", "_state", "=", "'0'", "else", ":", "_state", "=", "'2'", "xml", "=", "\"<?xml version='1.0'?>\\n<checkresults>\\n\"", "if", "(", "(", "'service'", "in", "options", ")", "and", "(", "options", "[", "'service'", "]", "!=", "''", ")", ")", ":", "xml", "+=", "(", "(", "\"<checkresult type='service' checktype='\"", "+", "str", "(", "options", "[", "'checktype'", "]", ")", ")", "+", "\"'>\"", ")", "xml", "+=", "(", "(", "'<hostname>'", "+", "cgi", ".", "escape", "(", "options", "[", "'hostname'", "]", ",", "True", ")", ")", "+", "'</hostname>'", ")", "xml", "+=", "(", "(", "'<servicename>'", "+", "cgi", ".", "escape", "(", "options", "[", "'service'", "]", ",", "True", ")", ")", "+", "'</servicename>'", ")", "else", ":", "xml", "+=", "(", "(", "\"<checkresult type='host' checktype='\"", "+", "str", "(", "options", "[", "'checktype'", "]", ")", ")", "+", "\"'>\"", ")", "xml", "+=", "(", "(", "'<hostname>'", "+", "cgi", ".", "escape", "(", "options", "[", "'hostname'", "]", ",", "True", ")", ")", "+", "'</hostname>'", ")", "xml", "+=", "(", "(", "'<state>'", "+", "_state", ")", "+", "'</state>'", ")", "if", "(", "'output'", "in", "options", ")", ":", "xml", "+=", "(", "(", "'<output>'", "+", "cgi", ".", "escape", "(", "options", "[", "'output'", "]", ",", "True", ")", ")", "+", "'</output>'", ")", "xml", "+=", "'</checkresult>'", "xml", "+=", "'\\n</checkresults>'", "return", "xml" ]
get the requests options from salt .
train
false
18,661
def ffill_query_in_range(expr, lower, upper, checkpoints=None, odo_kwargs=None, ts_field=TS_FIELD_NAME): odo_kwargs = (odo_kwargs or {}) (computed_lower, materialized_checkpoints) = get_materialized_checkpoints(checkpoints, expr.fields, lower, odo_kwargs) pred = (expr[ts_field] <= upper) if (computed_lower is not None): pred &= (expr[ts_field] >= computed_lower) raw = pd.concat((materialized_checkpoints, odo(expr[pred], pd.DataFrame, **odo_kwargs)), ignore_index=True) raw.loc[:, ts_field] = raw.loc[:, ts_field].astype('datetime64[ns]') return raw
[ "def", "ffill_query_in_range", "(", "expr", ",", "lower", ",", "upper", ",", "checkpoints", "=", "None", ",", "odo_kwargs", "=", "None", ",", "ts_field", "=", "TS_FIELD_NAME", ")", ":", "odo_kwargs", "=", "(", "odo_kwargs", "or", "{", "}", ")", "(", "computed_lower", ",", "materialized_checkpoints", ")", "=", "get_materialized_checkpoints", "(", "checkpoints", ",", "expr", ".", "fields", ",", "lower", ",", "odo_kwargs", ")", "pred", "=", "(", "expr", "[", "ts_field", "]", "<=", "upper", ")", "if", "(", "computed_lower", "is", "not", "None", ")", ":", "pred", "&=", "(", "expr", "[", "ts_field", "]", ">=", "computed_lower", ")", "raw", "=", "pd", ".", "concat", "(", "(", "materialized_checkpoints", ",", "odo", "(", "expr", "[", "pred", "]", ",", "pd", ".", "DataFrame", ",", "**", "odo_kwargs", ")", ")", ",", "ignore_index", "=", "True", ")", "raw", ".", "loc", "[", ":", ",", "ts_field", "]", "=", "raw", ".", "loc", "[", ":", ",", "ts_field", "]", ".", "astype", "(", "'datetime64[ns]'", ")", "return", "raw" ]
query a blaze expression in a given time range properly forward filling from values that fall before the lower date .
train
true
18,662
def is_args(x): return (type(x) in (tuple, list, set))
[ "def", "is_args", "(", "x", ")", ":", "return", "(", "type", "(", "x", ")", "in", "(", "tuple", ",", "list", ",", "set", ")", ")" ]
is x a traditional iterable? .
train
false
18,663
def sort_apply_nodes(inputs, outputs, cmps): return posort(list_of_nodes(inputs, outputs), *cmps)
[ "def", "sort_apply_nodes", "(", "inputs", ",", "outputs", ",", "cmps", ")", ":", "return", "posort", "(", "list_of_nodes", "(", "inputs", ",", "outputs", ")", ",", "*", "cmps", ")" ]
order a graph of apply nodes according to a list of comparators .
train
false
18,664
def resolve_email_domain(domain): try: answer = dns.resolver.query(domain, 'MX', raise_on_no_answer=False) except dns.resolver.NXDOMAIN: print ('Error: No such domain', domain) return if (answer.rrset is not None): records = sorted(answer, key=(lambda record: record.preference)) print ('This domain has', len(records), 'MX records') for record in records: name = record.exchange.to_text(omit_final_dot=True) print ('Priority', record.preference) resolve_hostname(name) else: print 'This domain has no explicit MX records' print 'Attempting to resolve it as an A, AAAA, or CNAME' resolve_hostname(domain)
[ "def", "resolve_email_domain", "(", "domain", ")", ":", "try", ":", "answer", "=", "dns", ".", "resolver", ".", "query", "(", "domain", ",", "'MX'", ",", "raise_on_no_answer", "=", "False", ")", "except", "dns", ".", "resolver", ".", "NXDOMAIN", ":", "print", "(", "'Error: No such domain'", ",", "domain", ")", "return", "if", "(", "answer", ".", "rrset", "is", "not", "None", ")", ":", "records", "=", "sorted", "(", "answer", ",", "key", "=", "(", "lambda", "record", ":", "record", ".", "preference", ")", ")", "print", "(", "'This domain has'", ",", "len", "(", "records", ")", ",", "'MX records'", ")", "for", "record", "in", "records", ":", "name", "=", "record", ".", "exchange", ".", "to_text", "(", "omit_final_dot", "=", "True", ")", "print", "(", "'Priority'", ",", "record", ".", "preference", ")", "resolve_hostname", "(", "name", ")", "else", ":", "print", "'This domain has no explicit MX records'", "print", "'Attempting to resolve it as an A, AAAA, or CNAME'", "resolve_hostname", "(", "domain", ")" ]
for an email address name@domain find its mail server ip addresses .
train
false
18,665
def package_patch(context, data_dict): _check_access('package_patch', context, data_dict) show_context = {'model': context['model'], 'session': context['session'], 'user': context['user'], 'auth_user_obj': context['auth_user_obj']} package_dict = _get_action('package_show')(show_context, {'id': _get_or_bust(data_dict, 'id')}) patched = dict(package_dict) patched.update(data_dict) patched['id'] = package_dict['id'] return _update.package_update(context, patched)
[ "def", "package_patch", "(", "context", ",", "data_dict", ")", ":", "_check_access", "(", "'package_patch'", ",", "context", ",", "data_dict", ")", "show_context", "=", "{", "'model'", ":", "context", "[", "'model'", "]", ",", "'session'", ":", "context", "[", "'session'", "]", ",", "'user'", ":", "context", "[", "'user'", "]", ",", "'auth_user_obj'", ":", "context", "[", "'auth_user_obj'", "]", "}", "package_dict", "=", "_get_action", "(", "'package_show'", ")", "(", "show_context", ",", "{", "'id'", ":", "_get_or_bust", "(", "data_dict", ",", "'id'", ")", "}", ")", "patched", "=", "dict", "(", "package_dict", ")", "patched", ".", "update", "(", "data_dict", ")", "patched", "[", "'id'", "]", "=", "package_dict", "[", "'id'", "]", "return", "_update", ".", "package_update", "(", "context", ",", "patched", ")" ]
patch a dataset .
train
false
18,666
def isOdd(x): return ((x % 2) == 1)
[ "def", "isOdd", "(", "x", ")", ":", "return", "(", "(", "x", "%", "2", ")", "==", "1", ")" ]
test predicate .
train
false
18,668
def libvlc_media_discoverer_media_list(p_mdis): f = (_Cfunctions.get('libvlc_media_discoverer_media_list', None) or _Cfunction('libvlc_media_discoverer_media_list', ((1,),), class_result(MediaList), ctypes.c_void_p, MediaDiscoverer)) return f(p_mdis)
[ "def", "libvlc_media_discoverer_media_list", "(", "p_mdis", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_discoverer_media_list'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_discoverer_media_list'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "class_result", "(", "MediaList", ")", ",", "ctypes", ".", "c_void_p", ",", "MediaDiscoverer", ")", ")", "return", "f", "(", "p_mdis", ")" ]
get media service discover media list .
train
true
18,669
def is_entity_header(header): return (header.lower() in _entity_headers)
[ "def", "is_entity_header", "(", "header", ")", ":", "return", "(", "header", ".", "lower", "(", ")", "in", "_entity_headers", ")" ]
check if a header is an entity header .
train
false
18,670
def _get_summary(rsync_out): return ('- ' + '\n- '.join([elm for elm in rsync_out.split('\n\n')[(-1)].replace(' ', '\n').split('\n') if elm]))
[ "def", "_get_summary", "(", "rsync_out", ")", ":", "return", "(", "'- '", "+", "'\\n- '", ".", "join", "(", "[", "elm", "for", "elm", "in", "rsync_out", ".", "split", "(", "'\\n\\n'", ")", "[", "(", "-", "1", ")", "]", ".", "replace", "(", "' '", ",", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "if", "elm", "]", ")", ")" ]
get summary from the rsync successfull output .
train
true
18,671
def get_annotated_content_infos(course_id, thread, user, user_info): infos = {} def annotate(content): infos[str(content['id'])] = get_annotated_content_info(course_id, content, user, user_info) for child in ((content.get('children', []) + content.get('endorsed_responses', [])) + content.get('non_endorsed_responses', [])): annotate(child) annotate(thread) return infos
[ "def", "get_annotated_content_infos", "(", "course_id", ",", "thread", ",", "user", ",", "user_info", ")", ":", "infos", "=", "{", "}", "def", "annotate", "(", "content", ")", ":", "infos", "[", "str", "(", "content", "[", "'id'", "]", ")", "]", "=", "get_annotated_content_info", "(", "course_id", ",", "content", ",", "user", ",", "user_info", ")", "for", "child", "in", "(", "(", "content", ".", "get", "(", "'children'", ",", "[", "]", ")", "+", "content", ".", "get", "(", "'endorsed_responses'", ",", "[", "]", ")", ")", "+", "content", ".", "get", "(", "'non_endorsed_responses'", ",", "[", "]", ")", ")", ":", "annotate", "(", "child", ")", "annotate", "(", "thread", ")", "return", "infos" ]
get metadata for a thread and its children .
train
false
18,672
def getSeconds(strTime): try: x = dt.strptime(strTime, '%H:%M:%S') seconds = int(timedelta(hours=x.hour, minutes=x.minute, seconds=x.second).total_seconds()) except ValueError: seconds = 0 if (seconds < 0): seconds = 0 return seconds
[ "def", "getSeconds", "(", "strTime", ")", ":", "try", ":", "x", "=", "dt", ".", "strptime", "(", "strTime", ",", "'%H:%M:%S'", ")", "seconds", "=", "int", "(", "timedelta", "(", "hours", "=", "x", ".", "hour", ",", "minutes", "=", "x", ".", "minute", ",", "seconds", "=", "x", ".", "second", ")", ".", "total_seconds", "(", ")", ")", "except", "ValueError", ":", "seconds", "=", "0", "if", "(", "seconds", "<", "0", ")", ":", "seconds", "=", "0", "return", "seconds" ]
return the duration in seconds of a time string .
train
false
18,673
def _as_percentage_of(cost_micropennies, total_cost_micropennies): if (total_cost_micropennies == 0): return 0 return round(((float(cost_micropennies) / float(total_cost_micropennies)) * 100), 1)
[ "def", "_as_percentage_of", "(", "cost_micropennies", ",", "total_cost_micropennies", ")", ":", "if", "(", "total_cost_micropennies", "==", "0", ")", ":", "return", "0", "return", "round", "(", "(", "(", "float", "(", "cost_micropennies", ")", "/", "float", "(", "total_cost_micropennies", ")", ")", "*", "100", ")", ",", "1", ")" ]
the cost as a percentage of the total cost .
train
false
18,674
def parse_request_start_line(line): try: (method, path, version) = line.split(' ') except ValueError: raise HTTPInputError('Malformed HTTP request line') if (not re.match('^HTTP/1\\.[0-9]$', version)): raise HTTPInputError(('Malformed HTTP version in HTTP Request-Line: %r' % version)) return RequestStartLine(method, path, version)
[ "def", "parse_request_start_line", "(", "line", ")", ":", "try", ":", "(", "method", ",", "path", ",", "version", ")", "=", "line", ".", "split", "(", "' '", ")", "except", "ValueError", ":", "raise", "HTTPInputError", "(", "'Malformed HTTP request line'", ")", "if", "(", "not", "re", ".", "match", "(", "'^HTTP/1\\\\.[0-9]$'", ",", "version", ")", ")", ":", "raise", "HTTPInputError", "(", "(", "'Malformed HTTP version in HTTP Request-Line: %r'", "%", "version", ")", ")", "return", "RequestStartLine", "(", "method", ",", "path", ",", "version", ")" ]
returns a tuple for an http 1 .
train
true
18,675
def _add_basic_options(opt_group): opt_group.add_option('-c', '--conf-path', dest='conf_paths', action='callback', callback=_append_to_conf_paths, default=None, nargs=1, type='string', help='Path to alternate mrjob.conf file to read from') opt_group.add_option('--no-conf', dest='conf_paths', action='store_const', const=[], help="Don't load mrjob.conf even if it's available") opt_group.add_option('-q', '--quiet', dest='quiet', default=None, action='store_true', help="Don't print anything to stderr") opt_group.add_option('-v', '--verbose', dest='verbose', default=None, action='store_true', help='print more messages to stderr')
[ "def", "_add_basic_options", "(", "opt_group", ")", ":", "opt_group", ".", "add_option", "(", "'-c'", ",", "'--conf-path'", ",", "dest", "=", "'conf_paths'", ",", "action", "=", "'callback'", ",", "callback", "=", "_append_to_conf_paths", ",", "default", "=", "None", ",", "nargs", "=", "1", ",", "type", "=", "'string'", ",", "help", "=", "'Path to alternate mrjob.conf file to read from'", ")", "opt_group", ".", "add_option", "(", "'--no-conf'", ",", "dest", "=", "'conf_paths'", ",", "action", "=", "'store_const'", ",", "const", "=", "[", "]", ",", "help", "=", "\"Don't load mrjob.conf even if it's available\"", ")", "opt_group", ".", "add_option", "(", "'-q'", ",", "'--quiet'", ",", "dest", "=", "'quiet'", ",", "default", "=", "None", ",", "action", "=", "'store_true'", ",", "help", "=", "\"Don't print anything to stderr\"", ")", "opt_group", ".", "add_option", "(", "'-v'", ",", "'--verbose'", ",", "dest", "=", "'verbose'", ",", "default", "=", "None", ",", "action", "=", "'store_true'", ",", "help", "=", "'print more messages to stderr'", ")" ]
options for all command line tools .
train
false
18,676
def metadata_summary(plugins, version=None): no_metadata = {} has_metadata = {} supported_by = defaultdict(set) status = defaultdict(set) plugins = list(plugins) all_mods_metadata = return_metadata(plugins) for (name, filename) in plugins: if ((name not in no_metadata) and (name not in has_metadata)): metadata = all_mods_metadata[name] if (metadata is None): no_metadata[name] = filename elif ((version is not None) and (('version' not in metadata) or (StrictVersion(metadata['version']) < StrictVersion(version)))): no_metadata[name] = filename else: has_metadata[name] = filename if (all_mods_metadata[name] is None): supported_by[DEFAULT_METADATA['supported_by']].add(filename) status[DEFAULT_METADATA['status'][0]].add(filename) else: supported_by[all_mods_metadata[name]['supported_by']].add(filename) for one_status in all_mods_metadata[name]['status']: status[one_status].add(filename) return (list(no_metadata.values()), list(has_metadata.values()), supported_by, status)
[ "def", "metadata_summary", "(", "plugins", ",", "version", "=", "None", ")", ":", "no_metadata", "=", "{", "}", "has_metadata", "=", "{", "}", "supported_by", "=", "defaultdict", "(", "set", ")", "status", "=", "defaultdict", "(", "set", ")", "plugins", "=", "list", "(", "plugins", ")", "all_mods_metadata", "=", "return_metadata", "(", "plugins", ")", "for", "(", "name", ",", "filename", ")", "in", "plugins", ":", "if", "(", "(", "name", "not", "in", "no_metadata", ")", "and", "(", "name", "not", "in", "has_metadata", ")", ")", ":", "metadata", "=", "all_mods_metadata", "[", "name", "]", "if", "(", "metadata", "is", "None", ")", ":", "no_metadata", "[", "name", "]", "=", "filename", "elif", "(", "(", "version", "is", "not", "None", ")", "and", "(", "(", "'version'", "not", "in", "metadata", ")", "or", "(", "StrictVersion", "(", "metadata", "[", "'version'", "]", ")", "<", "StrictVersion", "(", "version", ")", ")", ")", ")", ":", "no_metadata", "[", "name", "]", "=", "filename", "else", ":", "has_metadata", "[", "name", "]", "=", "filename", "if", "(", "all_mods_metadata", "[", "name", "]", "is", "None", ")", ":", "supported_by", "[", "DEFAULT_METADATA", "[", "'supported_by'", "]", "]", ".", "add", "(", "filename", ")", "status", "[", "DEFAULT_METADATA", "[", "'status'", "]", "[", "0", "]", "]", ".", "add", "(", "filename", ")", "else", ":", "supported_by", "[", "all_mods_metadata", "[", "name", "]", "[", "'supported_by'", "]", "]", ".", "add", "(", "filename", ")", "for", "one_status", "in", "all_mods_metadata", "[", "name", "]", "[", "'status'", "]", ":", "status", "[", "one_status", "]", ".", "add", "(", "filename", ")", "return", "(", "list", "(", "no_metadata", ".", "values", "(", ")", ")", ",", "list", "(", "has_metadata", ".", "values", "(", ")", ")", ",", "supported_by", ",", "status", ")" ]
compile information about the metadata status for a list of modules :arg plugins: list of plugins to look for .
train
false
18,677
def clear_password(name, runas=None): if ((runas is None) and (not salt.utils.is_windows())): runas = salt.utils.get_user() res = __salt__['cmd.run_all']([__context__['rabbitmqctl'], 'clear_password', name], runas=runas, python_shell=False) msg = 'Password Cleared' return _format_response(res, msg)
[ "def", "clear_password", "(", "name", ",", "runas", "=", "None", ")", ":", "if", "(", "(", "runas", "is", "None", ")", "and", "(", "not", "salt", ".", "utils", ".", "is_windows", "(", ")", ")", ")", ":", "runas", "=", "salt", ".", "utils", ".", "get_user", "(", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "[", "__context__", "[", "'rabbitmqctl'", "]", ",", "'clear_password'", ",", "name", "]", ",", "runas", "=", "runas", ",", "python_shell", "=", "False", ")", "msg", "=", "'Password Cleared'", "return", "_format_response", "(", "res", ",", "msg", ")" ]
removes a users password .
train
false
18,678
def update_preferred_language_codes(user_id, preferred_language_codes): user_settings = get_user_settings(user_id, strict=True) user_settings.preferred_language_codes = preferred_language_codes _save_user_settings(user_settings)
[ "def", "update_preferred_language_codes", "(", "user_id", ",", "preferred_language_codes", ")", ":", "user_settings", "=", "get_user_settings", "(", "user_id", ",", "strict", "=", "True", ")", "user_settings", ".", "preferred_language_codes", "=", "preferred_language_codes", "_save_user_settings", "(", "user_settings", ")" ]
updates preferred_language_codes of user with given user_id .
train
false
18,679
def setting_list(request): if (not test_user_authenticated(request)): return login(request, next='/cobbler_web/setting/list', expired=True) settings = remote.get_settings() skeys = settings.keys() skeys.sort() results = [] for k in skeys: results.append([k, settings[k]]) t = get_template('settings.tmpl') html = t.render(RequestContext(request, {'settings': results, 'version': remote.extended_version(request.session['token'])['version'], 'username': username})) return HttpResponse(html)
[ "def", "setting_list", "(", "request", ")", ":", "if", "(", "not", "test_user_authenticated", "(", "request", ")", ")", ":", "return", "login", "(", "request", ",", "next", "=", "'/cobbler_web/setting/list'", ",", "expired", "=", "True", ")", "settings", "=", "remote", ".", "get_settings", "(", ")", "skeys", "=", "settings", ".", "keys", "(", ")", "skeys", ".", "sort", "(", ")", "results", "=", "[", "]", "for", "k", "in", "skeys", ":", "results", ".", "append", "(", "[", "k", ",", "settings", "[", "k", "]", "]", ")", "t", "=", "get_template", "(", "'settings.tmpl'", ")", "html", "=", "t", ".", "render", "(", "RequestContext", "(", "request", ",", "{", "'settings'", ":", "results", ",", "'version'", ":", "remote", ".", "extended_version", "(", "request", ".", "session", "[", "'token'", "]", ")", "[", "'version'", "]", ",", "'username'", ":", "username", "}", ")", ")", "return", "HttpResponse", "(", "html", ")" ]
this page presents a list of all the settings to the user .
train
false
18,681
def cfarray_to_list(cfarray): count = cf.CFArrayGetCount(cfarray) return [cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i))) for i in range(count)]
[ "def", "cfarray_to_list", "(", "cfarray", ")", ":", "count", "=", "cf", ".", "CFArrayGetCount", "(", "cfarray", ")", "return", "[", "cftype_to_value", "(", "c_void_p", "(", "cf", ".", "CFArrayGetValueAtIndex", "(", "cfarray", ",", "i", ")", ")", ")", "for", "i", "in", "range", "(", "count", ")", "]" ]
convert cfarray to python list .
train
true
18,682
def inc_xattr(path, key, n=1): count = int(get_xattr(path, key)) count += n set_xattr(path, key, str(count))
[ "def", "inc_xattr", "(", "path", ",", "key", ",", "n", "=", "1", ")", ":", "count", "=", "int", "(", "get_xattr", "(", "path", ",", "key", ")", ")", "count", "+=", "n", "set_xattr", "(", "path", ",", "key", ",", "str", "(", "count", ")", ")" ]
increment the value of an xattr .
train
false
18,685
def numpy_array_from_structure(items, fmt, t): (memlen, itemsize, ndim, shape, strides, offset) = t buf = bytearray(memlen) for (j, v) in enumerate(items): struct.pack_into(fmt, buf, (j * itemsize), v) return numpy_array(buffer=buf, shape=shape, strides=strides, dtype=fmt, offset=offset)
[ "def", "numpy_array_from_structure", "(", "items", ",", "fmt", ",", "t", ")", ":", "(", "memlen", ",", "itemsize", ",", "ndim", ",", "shape", ",", "strides", ",", "offset", ")", "=", "t", "buf", "=", "bytearray", "(", "memlen", ")", "for", "(", "j", ",", "v", ")", "in", "enumerate", "(", "items", ")", ":", "struct", ".", "pack_into", "(", "fmt", ",", "buf", ",", "(", "j", "*", "itemsize", ")", ",", "v", ")", "return", "numpy_array", "(", "buffer", "=", "buf", ",", "shape", "=", "shape", ",", "strides", "=", "strides", ",", "dtype", "=", "fmt", ",", "offset", "=", "offset", ")" ]
return numpy_array from the tuple returned by rand_structure() .
train
false
18,687
def l1_l2_regularizer(weight_l1=1.0, weight_l2=1.0, scope=None): def regularizer(tensor): with tf.name_scope(scope, 'L1L2Regularizer', [tensor]): weight_l1_t = tf.convert_to_tensor(weight_l1, dtype=tensor.dtype.base_dtype, name='weight_l1') weight_l2_t = tf.convert_to_tensor(weight_l2, dtype=tensor.dtype.base_dtype, name='weight_l2') reg_l1 = tf.multiply(weight_l1_t, tf.reduce_sum(tf.abs(tensor)), name='value_l1') reg_l2 = tf.multiply(weight_l2_t, tf.nn.l2_loss(tensor), name='value_l2') return tf.add(reg_l1, reg_l2, name='value') return regularizer
[ "def", "l1_l2_regularizer", "(", "weight_l1", "=", "1.0", ",", "weight_l2", "=", "1.0", ",", "scope", "=", "None", ")", ":", "def", "regularizer", "(", "tensor", ")", ":", "with", "tf", ".", "name_scope", "(", "scope", ",", "'L1L2Regularizer'", ",", "[", "tensor", "]", ")", ":", "weight_l1_t", "=", "tf", ".", "convert_to_tensor", "(", "weight_l1", ",", "dtype", "=", "tensor", ".", "dtype", ".", "base_dtype", ",", "name", "=", "'weight_l1'", ")", "weight_l2_t", "=", "tf", ".", "convert_to_tensor", "(", "weight_l2", ",", "dtype", "=", "tensor", ".", "dtype", ".", "base_dtype", ",", "name", "=", "'weight_l2'", ")", "reg_l1", "=", "tf", ".", "multiply", "(", "weight_l1_t", ",", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "tensor", ")", ")", ",", "name", "=", "'value_l1'", ")", "reg_l2", "=", "tf", ".", "multiply", "(", "weight_l2_t", ",", "tf", ".", "nn", ".", "l2_loss", "(", "tensor", ")", ",", "name", "=", "'value_l2'", ")", "return", "tf", ".", "add", "(", "reg_l1", ",", "reg_l2", ",", "name", "=", "'value'", ")", "return", "regularizer" ]
define a l1l2 regularizer .
train
true
18,688
def job_title(): return s3_rest_controller('hrm', 'job_title')
[ "def", "job_title", "(", ")", ":", "return", "s3_rest_controller", "(", "'hrm'", ",", "'job_title'", ")" ]
restful crud controller .
train
false
18,690
def str2gib_size(s): size_in_bytes = str2size(s) return (size_in_bytes // units.Gi)
[ "def", "str2gib_size", "(", "s", ")", ":", "size_in_bytes", "=", "str2size", "(", "s", ")", "return", "(", "size_in_bytes", "//", "units", ".", "Gi", ")" ]
covert size-string to size in gigabytes .
train
false
18,692
def get_filters_for(doctype): config = get_notification_config() return config.get(u'for_doctype').get(doctype, {})
[ "def", "get_filters_for", "(", "doctype", ")", ":", "config", "=", "get_notification_config", "(", ")", "return", "config", ".", "get", "(", "u'for_doctype'", ")", ".", "get", "(", "doctype", ",", "{", "}", ")" ]
get open filters for doctype .
train
false
18,693
@gen.engine def RunOnce(callback): dry_run = options.options.dry_run client_store = ObjectStore.GetInstance(logs_util.UserAnalyticsLogsPaths.SOURCE_LOGS_BUCKET) if options.options.user: users = [options.options.user] else: users = (yield gen.Task(logs_util.ListClientLogUsers, client_store)) examined = 0 for u in users: if ((options.options.start_user is not None) and (u < options.options.start_user)): continue if ((options.options.max_users is not None) and (examined > options.options.max_users)): break examined += 1 (yield gen.Task(HandleOneUser, client_store, u)) if dry_run: logging.warning('dry_run=True: will not upload processed logs files or update registry') callback()
[ "@", "gen", ".", "engine", "def", "RunOnce", "(", "callback", ")", ":", "dry_run", "=", "options", ".", "options", ".", "dry_run", "client_store", "=", "ObjectStore", ".", "GetInstance", "(", "logs_util", ".", "UserAnalyticsLogsPaths", ".", "SOURCE_LOGS_BUCKET", ")", "if", "options", ".", "options", ".", "user", ":", "users", "=", "[", "options", ".", "options", ".", "user", "]", "else", ":", "users", "=", "(", "yield", "gen", ".", "Task", "(", "logs_util", ".", "ListClientLogUsers", ",", "client_store", ")", ")", "examined", "=", "0", "for", "u", "in", "users", ":", "if", "(", "(", "options", ".", "options", ".", "start_user", "is", "not", "None", ")", "and", "(", "u", "<", "options", ".", "options", ".", "start_user", ")", ")", ":", "continue", "if", "(", "(", "options", ".", "options", ".", "max_users", "is", "not", "None", ")", "and", "(", "examined", ">", "options", ".", "options", ".", "max_users", ")", ")", ":", "break", "examined", "+=", "1", "(", "yield", "gen", ".", "Task", "(", "HandleOneUser", ",", "client_store", ",", "u", ")", ")", "if", "dry_run", ":", "logging", ".", "warning", "(", "'dry_run=True: will not upload processed logs files or update registry'", ")", "callback", "(", ")" ]
find last successful run .
train
false
18,694
def _bytes_from_json(value, field): if _not_null(value, field): return base64.decodestring(_to_bytes(value))
[ "def", "_bytes_from_json", "(", "value", ",", "field", ")", ":", "if", "_not_null", "(", "value", ",", "field", ")", ":", "return", "base64", ".", "decodestring", "(", "_to_bytes", "(", "value", ")", ")" ]
base64-decode value .
train
false
18,695
@task @cmdopts([('suite=', 's', 'Test suite to run'), ('coverage', 'c', 'Run test under coverage')]) @timed def test_js_run(options): options.mode = 'run' test_js(options)
[ "@", "task", "@", "cmdopts", "(", "[", "(", "'suite='", ",", "'s'", ",", "'Test suite to run'", ")", ",", "(", "'coverage'", ",", "'c'", ",", "'Run test under coverage'", ")", "]", ")", "@", "timed", "def", "test_js_run", "(", "options", ")", ":", "options", ".", "mode", "=", "'run'", "test_js", "(", "options", ")" ]
run the javascript tests and print results to the console .
train
false
18,696
def _combine_flaky_annotation(flaky1, flaky2): return _FlakyAnnotation(jira_keys=(flaky1.jira_keys | flaky2.jira_keys), max_runs=max(flaky1.max_runs, flaky2.max_runs), min_passes=max(flaky1.min_passes, flaky2.min_passes))
[ "def", "_combine_flaky_annotation", "(", "flaky1", ",", "flaky2", ")", ":", "return", "_FlakyAnnotation", "(", "jira_keys", "=", "(", "flaky1", ".", "jira_keys", "|", "flaky2", ".", "jira_keys", ")", ",", "max_runs", "=", "max", "(", "flaky1", ".", "max_runs", ",", "flaky2", ".", "max_runs", ")", ",", "min_passes", "=", "max", "(", "flaky1", ".", "min_passes", ",", "flaky2", ".", "min_passes", ")", ")" ]
combine two flaky annotations .
train
false
18,697
def show_growth(limit=10, peak_stats={}, shortnames=True): gc.collect() stats = typestats(shortnames=shortnames) deltas = {} for (name, count) in iteritems(stats): old_count = peak_stats.get(name, 0) if (count > old_count): deltas[name] = (count - old_count) peak_stats[name] = count deltas = sorted(deltas.items(), key=operator.itemgetter(1), reverse=True) if limit: deltas = deltas[:limit] if deltas: width = max((len(name) for (name, count) in deltas)) for (name, delta) in deltas: print ('%-*s%9d %+9d' % (width, name, stats[name], delta))
[ "def", "show_growth", "(", "limit", "=", "10", ",", "peak_stats", "=", "{", "}", ",", "shortnames", "=", "True", ")", ":", "gc", ".", "collect", "(", ")", "stats", "=", "typestats", "(", "shortnames", "=", "shortnames", ")", "deltas", "=", "{", "}", "for", "(", "name", ",", "count", ")", "in", "iteritems", "(", "stats", ")", ":", "old_count", "=", "peak_stats", ".", "get", "(", "name", ",", "0", ")", "if", "(", "count", ">", "old_count", ")", ":", "deltas", "[", "name", "]", "=", "(", "count", "-", "old_count", ")", "peak_stats", "[", "name", "]", "=", "count", "deltas", "=", "sorted", "(", "deltas", ".", "items", "(", ")", ",", "key", "=", "operator", ".", "itemgetter", "(", "1", ")", ",", "reverse", "=", "True", ")", "if", "limit", ":", "deltas", "=", "deltas", "[", ":", "limit", "]", "if", "deltas", ":", "width", "=", "max", "(", "(", "len", "(", "name", ")", "for", "(", "name", ",", "count", ")", "in", "deltas", ")", ")", "for", "(", "name", ",", "delta", ")", "in", "deltas", ":", "print", "(", "'%-*s%9d %+9d'", "%", "(", "width", ",", "name", ",", "stats", "[", "name", "]", ",", "delta", ")", ")" ]
show the increase in peak object counts since last call .
train
false
18,698
def getHostKeyAlgorithms(host, options): knownHosts = KnownHostsFile.fromPath(FilePath((options['known-hosts'] or os.path.expanduser(_KNOWN_HOSTS)))) keyTypes = [] for entry in knownHosts.iterentries(): if entry.matchesHost(host): if (entry.keyType not in keyTypes): keyTypes.append(entry.keyType) return (keyTypes or None)
[ "def", "getHostKeyAlgorithms", "(", "host", ",", "options", ")", ":", "knownHosts", "=", "KnownHostsFile", ".", "fromPath", "(", "FilePath", "(", "(", "options", "[", "'known-hosts'", "]", "or", "os", ".", "path", ".", "expanduser", "(", "_KNOWN_HOSTS", ")", ")", ")", ")", "keyTypes", "=", "[", "]", "for", "entry", "in", "knownHosts", ".", "iterentries", "(", ")", ":", "if", "entry", ".", "matchesHost", "(", "host", ")", ":", "if", "(", "entry", ".", "keyType", "not", "in", "keyTypes", ")", ":", "keyTypes", ".", "append", "(", "entry", ".", "keyType", ")", "return", "(", "keyTypes", "or", "None", ")" ]
look in known_hosts for a key corresponding to c{host} .
train
false
18,700
def get_stored_primary_server_name(db): if ('last_primary_server' in db.collection_names()): stored_primary_server = db.last_primary_server.find_one()['server'] else: stored_primary_server = None return stored_primary_server
[ "def", "get_stored_primary_server_name", "(", "db", ")", ":", "if", "(", "'last_primary_server'", "in", "db", ".", "collection_names", "(", ")", ")", ":", "stored_primary_server", "=", "db", ".", "last_primary_server", ".", "find_one", "(", ")", "[", "'server'", "]", "else", ":", "stored_primary_server", "=", "None", "return", "stored_primary_server" ]
get the stored primary server name from db .
train
false
18,702
def rnn_test(f): f = keras_test(f) return pytest.mark.parametrize('layer_class', [recurrent.SimpleRNN, recurrent.GRU, recurrent.LSTM])(f)
[ "def", "rnn_test", "(", "f", ")", ":", "f", "=", "keras_test", "(", "f", ")", "return", "pytest", ".", "mark", ".", "parametrize", "(", "'layer_class'", ",", "[", "recurrent", ".", "SimpleRNN", ",", "recurrent", ".", "GRU", ",", "recurrent", ".", "LSTM", "]", ")", "(", "f", ")" ]
all the recurrent layers share the same interface .
train
false
18,703
def deployed(name, jboss_config, salt_source=None): log.debug(' ======================== STATE: jboss7.deployed (name: %s) ', name) ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} comment = '' (validate_success, validate_comment) = __validate_arguments(jboss_config, salt_source) if (not validate_success): return _error(ret, validate_comment) (resolved_source, get_artifact_comment) = __get_artifact(salt_source) log.debug('resolved_source=%s', resolved_source) log.debug('get_artifact_comment=%s', get_artifact_comment) comment = __append_comment(new_comment=get_artifact_comment, current_comment=comment) if (resolved_source is None): return _error(ret, get_artifact_comment) (find_success, deployment, find_comment) = __find_deployment(jboss_config, salt_source) if (not find_success): return _error(ret, find_comment) log.debug('deployment=%s', deployment) if (deployment is not None): __salt__['jboss7.undeploy'](jboss_config, deployment) ret['changes']['undeployed'] = deployment deploy_result = __salt__['jboss7.deploy'](jboss_config=jboss_config, source_file=resolved_source) log.debug('deploy_result=%s', str(deploy_result)) if deploy_result['success']: comment = __append_comment(new_comment='Deployment completed.', current_comment=comment) ret['comment'] = comment ret['changes']['deployed'] = resolved_source else: comment = __append_comment(new_comment="Deployment failed\nreturn code={retcode}\nstdout='{stdout}'\nstderr='{stderr}".format(**deploy_result), current_comment=comment) return _error(ret, comment) return ret
[ "def", "deployed", "(", "name", ",", "jboss_config", ",", "salt_source", "=", "None", ")", ":", "log", ".", "debug", "(", "' ======================== STATE: jboss7.deployed (name: %s) '", ",", "name", ")", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "comment", "=", "''", "(", "validate_success", ",", "validate_comment", ")", "=", "__validate_arguments", "(", "jboss_config", ",", "salt_source", ")", "if", "(", "not", "validate_success", ")", ":", "return", "_error", "(", "ret", ",", "validate_comment", ")", "(", "resolved_source", ",", "get_artifact_comment", ")", "=", "__get_artifact", "(", "salt_source", ")", "log", ".", "debug", "(", "'resolved_source=%s'", ",", "resolved_source", ")", "log", ".", "debug", "(", "'get_artifact_comment=%s'", ",", "get_artifact_comment", ")", "comment", "=", "__append_comment", "(", "new_comment", "=", "get_artifact_comment", ",", "current_comment", "=", "comment", ")", "if", "(", "resolved_source", "is", "None", ")", ":", "return", "_error", "(", "ret", ",", "get_artifact_comment", ")", "(", "find_success", ",", "deployment", ",", "find_comment", ")", "=", "__find_deployment", "(", "jboss_config", ",", "salt_source", ")", "if", "(", "not", "find_success", ")", ":", "return", "_error", "(", "ret", ",", "find_comment", ")", "log", ".", "debug", "(", "'deployment=%s'", ",", "deployment", ")", "if", "(", "deployment", "is", "not", "None", ")", ":", "__salt__", "[", "'jboss7.undeploy'", "]", "(", "jboss_config", ",", "deployment", ")", "ret", "[", "'changes'", "]", "[", "'undeployed'", "]", "=", "deployment", "deploy_result", "=", "__salt__", "[", "'jboss7.deploy'", "]", "(", "jboss_config", "=", "jboss_config", ",", "source_file", "=", "resolved_source", ")", "log", ".", "debug", "(", "'deploy_result=%s'", ",", "str", "(", "deploy_result", ")", ")", "if", "deploy_result", "[", "'success'", "]", ":", "comment", "=", "__append_comment", "(", "new_comment", "=", "'Deployment completed.'", ",", "current_comment", "=", "comment", ")", "ret", "[", "'comment'", "]", "=", "comment", "ret", "[", "'changes'", "]", "[", "'deployed'", "]", "=", "resolved_source", "else", ":", "comment", "=", "__append_comment", "(", "new_comment", "=", "\"Deployment failed\\nreturn code={retcode}\\nstdout='{stdout}'\\nstderr='{stderr}\"", ".", "format", "(", "**", "deploy_result", ")", ",", "current_comment", "=", "comment", ")", "return", "_error", "(", "ret", ",", "comment", ")", "return", "ret" ]
ensure the website has been deployed .
train
true
18,704
@csrf_exempt @require_POST @permission_required('wiki.add_revisionakismetsubmission') def submit_akismet_spam(request): submission = RevisionAkismetSubmission(sender=request.user, type='spam') data = RevisionAkismetSubmissionSpamForm(data=request.POST, instance=submission, request=request) if data.is_valid(): data.save() revision = data.cleaned_data['revision'] akismet_revisions = RevisionAkismetSubmission.objects.filter(revision=revision).order_by('id').values('sender__username', 'sent', 'type') data = [{'sender': rev['sender__username'], 'sent': format_date_time(value=rev['sent'], format='datetime', request=request)[0], 'type': rev['type']} for rev in akismet_revisions] return HttpResponse(json.dumps(data, sort_keys=True), content_type='application/json; charset=utf-8', status=201) return HttpResponseBadRequest()
[ "@", "csrf_exempt", "@", "require_POST", "@", "permission_required", "(", "'wiki.add_revisionakismetsubmission'", ")", "def", "submit_akismet_spam", "(", "request", ")", ":", "submission", "=", "RevisionAkismetSubmission", "(", "sender", "=", "request", ".", "user", ",", "type", "=", "'spam'", ")", "data", "=", "RevisionAkismetSubmissionSpamForm", "(", "data", "=", "request", ".", "POST", ",", "instance", "=", "submission", ",", "request", "=", "request", ")", "if", "data", ".", "is_valid", "(", ")", ":", "data", ".", "save", "(", ")", "revision", "=", "data", ".", "cleaned_data", "[", "'revision'", "]", "akismet_revisions", "=", "RevisionAkismetSubmission", ".", "objects", ".", "filter", "(", "revision", "=", "revision", ")", ".", "order_by", "(", "'id'", ")", ".", "values", "(", "'sender__username'", ",", "'sent'", ",", "'type'", ")", "data", "=", "[", "{", "'sender'", ":", "rev", "[", "'sender__username'", "]", ",", "'sent'", ":", "format_date_time", "(", "value", "=", "rev", "[", "'sent'", "]", ",", "format", "=", "'datetime'", ",", "request", "=", "request", ")", "[", "0", "]", ",", "'type'", ":", "rev", "[", "'type'", "]", "}", "for", "rev", "in", "akismet_revisions", "]", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ")", ",", "content_type", "=", "'application/json; charset=utf-8'", ",", "status", "=", "201", ")", "return", "HttpResponseBadRequest", "(", ")" ]
creates spam akismet record for revision .
train
false
18,705
def build_log_presenters(service_names, monochrome): prefix_width = max_name_width(service_names) def no_color(text): return text for color_func in cycle(([no_color] if monochrome else colors.rainbow())): (yield LogPresenter(prefix_width, color_func))
[ "def", "build_log_presenters", "(", "service_names", ",", "monochrome", ")", ":", "prefix_width", "=", "max_name_width", "(", "service_names", ")", "def", "no_color", "(", "text", ")", ":", "return", "text", "for", "color_func", "in", "cycle", "(", "(", "[", "no_color", "]", "if", "monochrome", "else", "colors", ".", "rainbow", "(", ")", ")", ")", ":", "(", "yield", "LogPresenter", "(", "prefix_width", ",", "color_func", ")", ")" ]
return an iterable of functions .
train
true
18,708
def vcs_upload(): if (env.deploy_tool == u'git'): remote_path = (u'ssh://%s@%s%s' % (env.user, env.host_string, env.repo_path)) if (not exists(env.repo_path)): run((u'mkdir -p %s' % env.repo_path)) with cd(env.repo_path): run(u'git init --bare') local((u'git push -f %s master' % remote_path)) with cd(env.repo_path): run((u'GIT_WORK_TREE=%s git checkout -f master' % env.proj_path)) run((u'GIT_WORK_TREE=%s git reset --hard' % env.proj_path)) elif (env.deploy_tool == u'hg'): remote_path = (u'ssh://%s@%s/%s' % (env.user, env.host_string, env.repo_path)) with cd(env.repo_path): if (not exists((u'%s/.hg' % env.repo_path))): run(u'hg init') print(env.repo_path) with fab_settings(warn_only=True): push = local((u'hg push -f %s' % remote_path)) if (push.return_code == 255): abort() run(u'hg update')
[ "def", "vcs_upload", "(", ")", ":", "if", "(", "env", ".", "deploy_tool", "==", "u'git'", ")", ":", "remote_path", "=", "(", "u'ssh://%s@%s%s'", "%", "(", "env", ".", "user", ",", "env", ".", "host_string", ",", "env", ".", "repo_path", ")", ")", "if", "(", "not", "exists", "(", "env", ".", "repo_path", ")", ")", ":", "run", "(", "(", "u'mkdir -p %s'", "%", "env", ".", "repo_path", ")", ")", "with", "cd", "(", "env", ".", "repo_path", ")", ":", "run", "(", "u'git init --bare'", ")", "local", "(", "(", "u'git push -f %s master'", "%", "remote_path", ")", ")", "with", "cd", "(", "env", ".", "repo_path", ")", ":", "run", "(", "(", "u'GIT_WORK_TREE=%s git checkout -f master'", "%", "env", ".", "proj_path", ")", ")", "run", "(", "(", "u'GIT_WORK_TREE=%s git reset --hard'", "%", "env", ".", "proj_path", ")", ")", "elif", "(", "env", ".", "deploy_tool", "==", "u'hg'", ")", ":", "remote_path", "=", "(", "u'ssh://%s@%s/%s'", "%", "(", "env", ".", "user", ",", "env", ".", "host_string", ",", "env", ".", "repo_path", ")", ")", "with", "cd", "(", "env", ".", "repo_path", ")", ":", "if", "(", "not", "exists", "(", "(", "u'%s/.hg'", "%", "env", ".", "repo_path", ")", ")", ")", ":", "run", "(", "u'hg init'", ")", "print", "(", "env", ".", "repo_path", ")", "with", "fab_settings", "(", "warn_only", "=", "True", ")", ":", "push", "=", "local", "(", "(", "u'hg push -f %s'", "%", "remote_path", ")", ")", "if", "(", "push", ".", "return_code", "==", "255", ")", ":", "abort", "(", ")", "run", "(", "u'hg update'", ")" ]
uploads the project with the selected vcs tool .
train
false
18,709
def new(rsa_key): return PKCS115_SigScheme(rsa_key)
[ "def", "new", "(", "rsa_key", ")", ":", "return", "PKCS115_SigScheme", "(", "rsa_key", ")" ]
create a new cmac object .
train
false
18,710
def irshift(a, b): a >>= b return a
[ "def", "irshift", "(", "a", ",", "b", ")", ":", "a", ">>=", "b", "return", "a" ]
same as a >>= b .
train
false
18,712
def ks_test(timeseries): hour_ago = (time() - 3600) ten_minutes_ago = (time() - 600) reference = scipy.array([x[1] for x in timeseries if ((x[0] >= hour_ago) and (x[0] < ten_minutes_ago))]) probe = scipy.array([x[1] for x in timeseries if (x[0] >= ten_minutes_ago)]) if ((reference.size < 20) or (probe.size < 20)): return False (ks_d, ks_p_value) = scipy.stats.ks_2samp(reference, probe) if ((ks_p_value < 0.05) and (ks_d > 0.5)): adf = sm.tsa.stattools.adfuller(reference, 10) if (adf[1] < 0.05): return True return False
[ "def", "ks_test", "(", "timeseries", ")", ":", "hour_ago", "=", "(", "time", "(", ")", "-", "3600", ")", "ten_minutes_ago", "=", "(", "time", "(", ")", "-", "600", ")", "reference", "=", "scipy", ".", "array", "(", "[", "x", "[", "1", "]", "for", "x", "in", "timeseries", "if", "(", "(", "x", "[", "0", "]", ">=", "hour_ago", ")", "and", "(", "x", "[", "0", "]", "<", "ten_minutes_ago", ")", ")", "]", ")", "probe", "=", "scipy", ".", "array", "(", "[", "x", "[", "1", "]", "for", "x", "in", "timeseries", "if", "(", "x", "[", "0", "]", ">=", "ten_minutes_ago", ")", "]", ")", "if", "(", "(", "reference", ".", "size", "<", "20", ")", "or", "(", "probe", ".", "size", "<", "20", ")", ")", ":", "return", "False", "(", "ks_d", ",", "ks_p_value", ")", "=", "scipy", ".", "stats", ".", "ks_2samp", "(", "reference", ",", "probe", ")", "if", "(", "(", "ks_p_value", "<", "0.05", ")", "and", "(", "ks_d", ">", "0.5", ")", ")", ":", "adf", "=", "sm", ".", "tsa", ".", "stattools", ".", "adfuller", "(", "reference", ",", "10", ")", "if", "(", "adf", "[", "1", "]", "<", "0.05", ")", ":", "return", "True", "return", "False" ]
a timeseries is anomalous if 2 sample kolmogorov-smirnov test indicates that data distribution for last 10 minutes is different from last hour .
train
false
18,713
def _start_machine(machine, session): try: return machine.launchVMProcess(session, '', '') except Exception as e: log.debug(e.message, exc_info=True) return None
[ "def", "_start_machine", "(", "machine", ",", "session", ")", ":", "try", ":", "return", "machine", ".", "launchVMProcess", "(", "session", ",", "''", ",", "''", ")", "except", "Exception", "as", "e", ":", "log", ".", "debug", "(", "e", ".", "message", ",", "exc_info", "=", "True", ")", "return", "None" ]
helper to try and start machines .
train
true
18,714
def test_gmail_missing_trash(constants, monkeypatch): folder_base = [(('\\HasNoChildren',), '/', u'INBOX'), (('\\Noselect', '\\HasChildren'), '/', u'[Gmail]'), (('\\HasNoChildren', '\\All'), '/', u'[Gmail]/All Mail'), (('\\HasNoChildren', '\\Drafts'), '/', u'[Gmail]/Drafts'), (('\\HasNoChildren', '\\Important'), '/', u'[Gmail]/Important'), (('\\HasNoChildren', '\\Sent'), '/', u'[Gmail]/Sent Mail'), (('\\HasNoChildren', '\\Junk'), '/', u'[Gmail]/Spam'), (('\\Flagged', '\\HasNoChildren'), '/', u'[Gmail]/Starred'), (('\\HasNoChildren',), '/', u'reference')] check_missing_generic('trash', folder_base, localized_folder_names['trash'], 'gmail', constants, monkeypatch)
[ "def", "test_gmail_missing_trash", "(", "constants", ",", "monkeypatch", ")", ":", "folder_base", "=", "[", "(", "(", "'\\\\HasNoChildren'", ",", ")", ",", "'/'", ",", "u'INBOX'", ")", ",", "(", "(", "'\\\\Noselect'", ",", "'\\\\HasChildren'", ")", ",", "'/'", ",", "u'[Gmail]'", ")", ",", "(", "(", "'\\\\HasNoChildren'", ",", "'\\\\All'", ")", ",", "'/'", ",", "u'[Gmail]/All Mail'", ")", ",", "(", "(", "'\\\\HasNoChildren'", ",", "'\\\\Drafts'", ")", ",", "'/'", ",", "u'[Gmail]/Drafts'", ")", ",", "(", "(", "'\\\\HasNoChildren'", ",", "'\\\\Important'", ")", ",", "'/'", ",", "u'[Gmail]/Important'", ")", ",", "(", "(", "'\\\\HasNoChildren'", ",", "'\\\\Sent'", ")", ",", "'/'", ",", "u'[Gmail]/Sent Mail'", ")", ",", "(", "(", "'\\\\HasNoChildren'", ",", "'\\\\Junk'", ")", ",", "'/'", ",", "u'[Gmail]/Spam'", ")", ",", "(", "(", "'\\\\Flagged'", ",", "'\\\\HasNoChildren'", ")", ",", "'/'", ",", "u'[Gmail]/Starred'", ")", ",", "(", "(", "'\\\\HasNoChildren'", ",", ")", ",", "'/'", ",", "u'reference'", ")", "]", "check_missing_generic", "(", "'trash'", ",", "folder_base", ",", "localized_folder_names", "[", "'trash'", "]", ",", "'gmail'", ",", "constants", ",", "monkeypatch", ")" ]
test that we can label their folder when they dont have a folder labeled trash .
train
false
18,715
def update_password(user, password): user.password = encrypt_password(password) _datastore.put(user) send_password_reset_notice(user) password_reset.send(app._get_current_object(), user=user)
[ "def", "update_password", "(", "user", ",", "password", ")", ":", "user", ".", "password", "=", "encrypt_password", "(", "password", ")", "_datastore", ".", "put", "(", "user", ")", "send_password_reset_notice", "(", "user", ")", "password_reset", ".", "send", "(", "app", ".", "_get_current_object", "(", ")", ",", "user", "=", "user", ")" ]
update the specified users password .
train
true
18,716
def test_write_no_bookend(): out = StringIO() ascii.write(dat, out, Writer=ascii.FixedWidth, bookend=False) assert_equal_splitlines(out.getvalue(), 'Col1 | Col2 | Col3 | Col4\n 1.2 | "hello" | 1 | a\n 2.4 | \'s worlds | 2 | 2\n')
[ "def", "test_write_no_bookend", "(", ")", ":", "out", "=", "StringIO", "(", ")", "ascii", ".", "write", "(", "dat", ",", "out", ",", "Writer", "=", "ascii", ".", "FixedWidth", ",", "bookend", "=", "False", ")", "assert_equal_splitlines", "(", "out", ".", "getvalue", "(", ")", ",", "'Col1 | Col2 | Col3 | Col4\\n 1.2 | \"hello\" | 1 | a\\n 2.4 | \\'s worlds | 2 | 2\\n'", ")" ]
write a table as a fixed width table with no bookend .
train
false
18,717
def stop_time_service(): return __salt__['service.stop']('w32time')
[ "def", "stop_time_service", "(", ")", ":", "return", "__salt__", "[", "'service.stop'", "]", "(", "'w32time'", ")" ]
stop the windows time service :return: true if successful .
train
false
18,718
def _load_bitmap(filename): basedir = os.path.join(rcParams[u'datapath'], u'images') bmpFilename = os.path.normpath(os.path.join(basedir, filename)) if (not os.path.exists(bmpFilename)): raise IOError((u'Could not find bitmap file "%s"; dying' % bmpFilename)) bmp = wx.Bitmap(bmpFilename) return bmp
[ "def", "_load_bitmap", "(", "filename", ")", ":", "basedir", "=", "os", ".", "path", ".", "join", "(", "rcParams", "[", "u'datapath'", "]", ",", "u'images'", ")", "bmpFilename", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "basedir", ",", "filename", ")", ")", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "bmpFilename", ")", ")", ":", "raise", "IOError", "(", "(", "u'Could not find bitmap file \"%s\"; dying'", "%", "bmpFilename", ")", ")", "bmp", "=", "wx", ".", "Bitmap", "(", "bmpFilename", ")", "return", "bmp" ]
load a bitmap file from the backends/images subdirectory in which the matplotlib library is installed .
train
true
18,720
def direct_format_text(text): return text.replace('\n', '\\n').replace('\r', '\\r')
[ "def", "direct_format_text", "(", "text", ")", ":", "return", "text", ".", "replace", "(", "'\\n'", ",", "'\\\\n'", ")", ".", "replace", "(", "'\\r'", ",", "'\\\\r'", ")" ]
transform special chars in text to have only one line .
train
false
18,722
def group_by_min_key(input_list): key = itemgetter(0) value = itemgetter(1) res_dict_1 = {} for (key, group) in groupby(input_list, key): res_dict_1[key] = [value(x) for x in group] key = itemgetter(1) value = itemgetter(0) res_dict_2 = {} for (key, group) in groupby(input_list, key): res_dict_2[key] = [value(x) for x in group] if (len(res_dict_1) > len(res_dict_2)): return (res_dict_2, 1) else: return (res_dict_1, 0)
[ "def", "group_by_min_key", "(", "input_list", ")", ":", "key", "=", "itemgetter", "(", "0", ")", "value", "=", "itemgetter", "(", "1", ")", "res_dict_1", "=", "{", "}", "for", "(", "key", ",", "group", ")", "in", "groupby", "(", "input_list", ",", "key", ")", ":", "res_dict_1", "[", "key", "]", "=", "[", "value", "(", "x", ")", "for", "x", "in", "group", "]", "key", "=", "itemgetter", "(", "1", ")", "value", "=", "itemgetter", "(", "0", ")", "res_dict_2", "=", "{", "}", "for", "(", "key", ",", "group", ")", "in", "groupby", "(", "input_list", ",", "key", ")", ":", "res_dict_2", "[", "key", "]", "=", "[", "value", "(", "x", ")", "for", "x", "in", "group", "]", "if", "(", "len", "(", "res_dict_1", ")", ">", "len", "(", "res_dict_2", ")", ")", ":", "return", "(", "res_dict_2", ",", "1", ")", "else", ":", "return", "(", "res_dict_1", ",", "0", ")" ]
this function takes a list with tuples of length two inside: [ .
train
false
18,723
def isnat(obj): if (obj.dtype.kind not in ('m', 'M')): raise ValueError('%s is not a numpy datetime or timedelta') return (obj.view(int64_dtype) == iNaT)
[ "def", "isnat", "(", "obj", ")", ":", "if", "(", "obj", ".", "dtype", ".", "kind", "not", "in", "(", "'m'", ",", "'M'", ")", ")", ":", "raise", "ValueError", "(", "'%s is not a numpy datetime or timedelta'", ")", "return", "(", "obj", ".", "view", "(", "int64_dtype", ")", "==", "iNaT", ")" ]
check if a value is np .
train
true
18,724
@bp.route('/<int:uid>/like', methods=('POST',)) @require_user def like(uid): like = LikeTopic.query.filter_by(account_id=g.user.id, topic_id=uid).first() if like: db.session.delete(like) db.session.commit() return jsonify(status='ok', action='cancel') like = LikeTopic(account_id=g.user.id, topic_id=uid) db.session.add(like) db.session.commit() return jsonify(status='ok', action='like')
[ "@", "bp", ".", "route", "(", "'/<int:uid>/like'", ",", "methods", "=", "(", "'POST'", ",", ")", ")", "@", "require_user", "def", "like", "(", "uid", ")", ":", "like", "=", "LikeTopic", ".", "query", ".", "filter_by", "(", "account_id", "=", "g", ".", "user", ".", "id", ",", "topic_id", "=", "uid", ")", ".", "first", "(", ")", "if", "like", ":", "db", ".", "session", ".", "delete", "(", "like", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "jsonify", "(", "status", "=", "'ok'", ",", "action", "=", "'cancel'", ")", "like", "=", "LikeTopic", "(", "account_id", "=", "g", ".", "user", ".", "id", ",", "topic_id", "=", "uid", ")", "db", ".", "session", ".", "add", "(", "like", ")", "db", ".", "session", ".", "commit", "(", ")", "return", "jsonify", "(", "status", "=", "'ok'", ",", "action", "=", "'like'", ")" ]
like a topic .
train
false
18,726
def mx_match(mx_domains, match_domains): match_domains = [(d.replace('.', '[.]').replace('*', '.*') + '$') for d in match_domains] for mx_domain in mx_domains: if (mx_domain[(-1)] == '.'): mx_domain = mx_domain[:(-1)] def match_filter(x): return re.match(x, mx_domain) if any((match_filter(m) for m in match_domains)): return True return False
[ "def", "mx_match", "(", "mx_domains", ",", "match_domains", ")", ":", "match_domains", "=", "[", "(", "d", ".", "replace", "(", "'.'", ",", "'[.]'", ")", ".", "replace", "(", "'*'", ",", "'.*'", ")", "+", "'$'", ")", "for", "d", "in", "match_domains", "]", "for", "mx_domain", "in", "mx_domains", ":", "if", "(", "mx_domain", "[", "(", "-", "1", ")", "]", "==", "'.'", ")", ":", "mx_domain", "=", "mx_domain", "[", ":", "(", "-", "1", ")", "]", "def", "match_filter", "(", "x", ")", ":", "return", "re", ".", "match", "(", "x", ",", "mx_domain", ")", "if", "any", "(", "(", "match_filter", "(", "m", ")", "for", "m", "in", "match_domains", ")", ")", ":", "return", "True", "return", "False" ]
return true if any of the mx_domains matches an mx_domain in match_domains .
train
false
18,728
def Semidef(n, name=None): var = SemidefUpperTri(n, name) fill_mat = Constant(upper_tri_to_full(n)) return cvxtypes.reshape()((fill_mat * var), n, n)
[ "def", "Semidef", "(", "n", ",", "name", "=", "None", ")", ":", "var", "=", "SemidefUpperTri", "(", "n", ",", "name", ")", "fill_mat", "=", "Constant", "(", "upper_tri_to_full", "(", "n", ")", ")", "return", "cvxtypes", ".", "reshape", "(", ")", "(", "(", "fill_mat", "*", "var", ")", ",", "n", ",", "n", ")" ]
an expression representing a positive semidefinite matrix .
train
false
18,729
def drop_table(model, keyspaces=None, connections=None): context = _get_context(keyspaces, connections) for (connection, keyspace) in context: with query.ContextQuery(model, keyspace=keyspace) as m: _drop_table(m, connection=connection)
[ "def", "drop_table", "(", "model", ",", "keyspaces", "=", "None", ",", "connections", "=", "None", ")", ":", "context", "=", "_get_context", "(", "keyspaces", ",", "connections", ")", "for", "(", "connection", ",", "keyspace", ")", "in", "context", ":", "with", "query", ".", "ContextQuery", "(", "model", ",", "keyspace", "=", "keyspace", ")", "as", "m", ":", "_drop_table", "(", "m", ",", "connection", "=", "connection", ")" ]
drops the table indicated by the model .
train
true
18,730
def makedirs_count(path, count=0): (head, tail) = os.path.split(path) if (not tail): (head, tail) = os.path.split(head) if (head and tail and (not os.path.exists(head))): count = makedirs_count(head, count) if (tail == os.path.curdir): return try: os.mkdir(path) except OSError as e: if ((e.errno != errno.EEXIST) or (not os.path.isdir(path))): raise else: count += 1 return count
[ "def", "makedirs_count", "(", "path", ",", "count", "=", "0", ")", ":", "(", "head", ",", "tail", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "(", "not", "tail", ")", ":", "(", "head", ",", "tail", ")", "=", "os", ".", "path", ".", "split", "(", "head", ")", "if", "(", "head", "and", "tail", "and", "(", "not", "os", ".", "path", ".", "exists", "(", "head", ")", ")", ")", ":", "count", "=", "makedirs_count", "(", "head", ",", "count", ")", "if", "(", "tail", "==", "os", ".", "path", ".", "curdir", ")", ":", "return", "try", ":", "os", ".", "mkdir", "(", "path", ")", "except", "OSError", "as", "e", ":", "if", "(", "(", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ")", "or", "(", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ")", ")", ":", "raise", "else", ":", "count", "+=", "1", "return", "count" ]
same as os .
train
false
18,732
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
this function gets called when the proxy starts up .
train
false
18,733
def set_if_set(dct, key, value): if (value is not UNSET): dct[key] = value
[ "def", "set_if_set", "(", "dct", ",", "key", ",", "value", ")", ":", "if", "(", "value", "is", "not", "UNSET", ")", ":", "dct", "[", "key", "]", "=", "value" ]
sets key in dct to value unless value is unset .
train
false
18,734
def stSpectralEntropy(X, numOfShortBlocks=10): L = len(X) Eol = numpy.sum((X ** 2)) subWinLength = int(numpy.floor((L / numOfShortBlocks))) if (L != (subWinLength * numOfShortBlocks)): X = X[0:(subWinLength * numOfShortBlocks)] subWindows = X.reshape(subWinLength, numOfShortBlocks, order='F').copy() s = (numpy.sum((subWindows ** 2), axis=0) / (Eol + eps)) En = (- numpy.sum((s * numpy.log2((s + eps))))) return En
[ "def", "stSpectralEntropy", "(", "X", ",", "numOfShortBlocks", "=", "10", ")", ":", "L", "=", "len", "(", "X", ")", "Eol", "=", "numpy", ".", "sum", "(", "(", "X", "**", "2", ")", ")", "subWinLength", "=", "int", "(", "numpy", ".", "floor", "(", "(", "L", "/", "numOfShortBlocks", ")", ")", ")", "if", "(", "L", "!=", "(", "subWinLength", "*", "numOfShortBlocks", ")", ")", ":", "X", "=", "X", "[", "0", ":", "(", "subWinLength", "*", "numOfShortBlocks", ")", "]", "subWindows", "=", "X", ".", "reshape", "(", "subWinLength", ",", "numOfShortBlocks", ",", "order", "=", "'F'", ")", ".", "copy", "(", ")", "s", "=", "(", "numpy", ".", "sum", "(", "(", "subWindows", "**", "2", ")", ",", "axis", "=", "0", ")", "/", "(", "Eol", "+", "eps", ")", ")", "En", "=", "(", "-", "numpy", ".", "sum", "(", "(", "s", "*", "numpy", ".", "log2", "(", "(", "s", "+", "eps", ")", ")", ")", ")", ")", "return", "En" ]
computes the spectral entropy .
train
false
18,735
def get_port_stats(port): cnts = defaultdict(int) for c in psutil.net_connections(): c_port = c.laddr[1] if (c_port != port): continue status = c.status.lower() cnts[status] += 1 return cnts
[ "def", "get_port_stats", "(", "port", ")", ":", "cnts", "=", "defaultdict", "(", "int", ")", "for", "c", "in", "psutil", ".", "net_connections", "(", ")", ":", "c_port", "=", "c", ".", "laddr", "[", "1", "]", "if", "(", "c_port", "!=", "port", ")", ":", "continue", "status", "=", "c", ".", "status", ".", "lower", "(", ")", "cnts", "[", "status", "]", "+=", "1", "return", "cnts" ]
iterate over connections and count states for specified port .
train
true
18,736
def copy_perms(parent): for d in frappe.get_all(u'DocPerm', fields=u'*', filters=dict(parent=parent)): custom_perm = frappe.new_doc(u'Custom DocPerm') custom_perm.update(d) custom_perm.insert(ignore_permissions=True)
[ "def", "copy_perms", "(", "parent", ")", ":", "for", "d", "in", "frappe", ".", "get_all", "(", "u'DocPerm'", ",", "fields", "=", "u'*'", ",", "filters", "=", "dict", "(", "parent", "=", "parent", ")", ")", ":", "custom_perm", "=", "frappe", ".", "new_doc", "(", "u'Custom DocPerm'", ")", "custom_perm", ".", "update", "(", "d", ")", "custom_perm", ".", "insert", "(", "ignore_permissions", "=", "True", ")" ]
copy all docperm in to custom docperm for the given document .
train
false
18,737
def new_finder(paths=None, parent=None): widget = Finder(parent=parent) widget.search_for((paths or u'')) return widget
[ "def", "new_finder", "(", "paths", "=", "None", ",", "parent", "=", "None", ")", ":", "widget", "=", "Finder", "(", "parent", "=", "parent", ")", "widget", ".", "search_for", "(", "(", "paths", "or", "u''", ")", ")", "return", "widget" ]
create a finder widget .
train
false
18,739
def make_list(value): return list(value)
[ "def", "make_list", "(", "value", ")", ":", "return", "list", "(", "value", ")" ]
returns the value turned into a list .
train
false