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
15,445
def _pecl(command, defaults=False): cmdline = 'pecl {0}'.format(command) if salt.utils.is_true(defaults): cmdline = (("yes ''" + ' | ') + cmdline) ret = __salt__['cmd.run_all'](cmdline, python_shell=True) if (ret['retcode'] == 0): return ret['stdout'] else: log.error('Problem running pecl. Is php-pear installed?') return ''
[ "def", "_pecl", "(", "command", ",", "defaults", "=", "False", ")", ":", "cmdline", "=", "'pecl {0}'", ".", "format", "(", "command", ")", "if", "salt", ".", "utils", ".", "is_true", "(", "defaults", ")", ":", "cmdline", "=", "(", "(", "\"yes ''\"", "+", "' | '", ")", "+", "cmdline", ")", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmdline", ",", "python_shell", "=", "True", ")", "if", "(", "ret", "[", "'retcode'", "]", "==", "0", ")", ":", "return", "ret", "[", "'stdout'", "]", "else", ":", "log", ".", "error", "(", "'Problem running pecl. Is php-pear installed?'", ")", "return", "''" ]
execute the command passed with pecl .
train
true
15,446
def test_bad_proj(): raw = read_raw_fif(raw_fname, preload=True) events = read_events(event_fname) picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads') picks = picks[2:9:3] _check_warnings(raw, events, picks) raw.pick_channels([raw.ch_names[ii] for ii in picks]) _check_warnings(raw, events) raw.info.normalize_proj() _check_warnings(raw, events, count=0) raw = read_raw_fif(raw_fname, preload=True).pick_types(meg=False, eeg=True) raw.set_eeg_reference() _check_warnings(raw, events, count=0) raw.info['bads'] = raw.ch_names[:10] _check_warnings(raw, events, count=0)
[ "def", "test_bad_proj", "(", ")", ":", "raw", "=", "read_raw_fif", "(", "raw_fname", ",", "preload", "=", "True", ")", "events", "=", "read_events", "(", "event_fname", ")", "picks", "=", "pick_types", "(", "raw", ".", "info", ",", "meg", "=", "True", ",", "stim", "=", "False", ",", "ecg", "=", "False", ",", "eog", "=", "False", ",", "exclude", "=", "'bads'", ")", "picks", "=", "picks", "[", "2", ":", "9", ":", "3", "]", "_check_warnings", "(", "raw", ",", "events", ",", "picks", ")", "raw", ".", "pick_channels", "(", "[", "raw", ".", "ch_names", "[", "ii", "]", "for", "ii", "in", "picks", "]", ")", "_check_warnings", "(", "raw", ",", "events", ")", "raw", ".", "info", ".", "normalize_proj", "(", ")", "_check_warnings", "(", "raw", ",", "events", ",", "count", "=", "0", ")", "raw", "=", "read_raw_fif", "(", "raw_fname", ",", "preload", "=", "True", ")", ".", "pick_types", "(", "meg", "=", "False", ",", "eeg", "=", "True", ")", "raw", ".", "set_eeg_reference", "(", ")", "_check_warnings", "(", "raw", ",", "events", ",", "count", "=", "0", ")", "raw", ".", "info", "[", "'bads'", "]", "=", "raw", ".", "ch_names", "[", ":", "10", "]", "_check_warnings", "(", "raw", ",", "events", ",", "count", "=", "0", ")" ]
test dealing with bad projection application .
train
false
15,447
def GetPrettyBytes(bytes_num, significant_digits=0): byte_prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E'] for i in range(0, 7): exp = (i * 10) if (bytes_num < (1 << (exp + 10))): if (i == 0): formatted_bytes = str(bytes_num) else: formatted_bytes = ('%.*f' % (significant_digits, ((bytes_num * 1.0) / (1 << exp)))) if (formatted_bytes != '1'): plural = 's' else: plural = '' return ('%s %sByte%s' % (formatted_bytes, byte_prefixes[i], plural)) logging.error('Number too high to convert: %d', bytes_num) return 'Alot'
[ "def", "GetPrettyBytes", "(", "bytes_num", ",", "significant_digits", "=", "0", ")", ":", "byte_prefixes", "=", "[", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ",", "'P'", ",", "'E'", "]", "for", "i", "in", "range", "(", "0", ",", "7", ")", ":", "exp", "=", "(", "i", "*", "10", ")", "if", "(", "bytes_num", "<", "(", "1", "<<", "(", "exp", "+", "10", ")", ")", ")", ":", "if", "(", "i", "==", "0", ")", ":", "formatted_bytes", "=", "str", "(", "bytes_num", ")", "else", ":", "formatted_bytes", "=", "(", "'%.*f'", "%", "(", "significant_digits", ",", "(", "(", "bytes_num", "*", "1.0", ")", "/", "(", "1", "<<", "exp", ")", ")", ")", ")", "if", "(", "formatted_bytes", "!=", "'1'", ")", ":", "plural", "=", "'s'", "else", ":", "plural", "=", "''", "return", "(", "'%s %sByte%s'", "%", "(", "formatted_bytes", ",", "byte_prefixes", "[", "i", "]", ",", "plural", ")", ")", "logging", ".", "error", "(", "'Number too high to convert: %d'", ",", "bytes_num", ")", "return", "'Alot'" ]
get a pretty print view of the given number of bytes .
train
false
15,448
def get_schedules(profile='pagerduty', subdomain=None, api_key=None): return _list_items('schedules', 'id', profile=profile, subdomain=subdomain, api_key=api_key)
[ "def", "get_schedules", "(", "profile", "=", "'pagerduty'", ",", "subdomain", "=", "None", ",", "api_key", "=", "None", ")", ":", "return", "_list_items", "(", "'schedules'", ",", "'id'", ",", "profile", "=", "profile", ",", "subdomain", "=", "subdomain", ",", "api_key", "=", "api_key", ")" ]
list schedules belonging to this account cli example: salt myminion pagerduty .
train
true
15,449
def validateOpfJsonValue(value, opfJsonSchemaFilename): jsonSchemaPath = os.path.join(os.path.dirname(__file__), 'jsonschema', opfJsonSchemaFilename) jsonhelpers.validate(value, schemaPath=jsonSchemaPath) return
[ "def", "validateOpfJsonValue", "(", "value", ",", "opfJsonSchemaFilename", ")", ":", "jsonSchemaPath", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'jsonschema'", ",", "opfJsonSchemaFilename", ")", "jsonhelpers", ".", "validate", "(", "value", ",", "schemaPath", "=", "jsonSchemaPath", ")", "return" ]
validate a python object against an opf json schema file target: target python object to validate opfjsonschemafilename: opf json schema filename containing the json schema object .
train
true
15,450
def select_backend(name): try: mod = __import__(name, fromlist=public_api) except ImportError: raise except Exception as e: import sys from zmq.utils.sixcerpt import reraise exc_info = sys.exc_info() reraise(ImportError, ImportError(('Importing %s failed with %s' % (name, e))), exc_info[2]) ns = {} for key in public_api: ns[key] = getattr(mod, key) return ns
[ "def", "select_backend", "(", "name", ")", ":", "try", ":", "mod", "=", "__import__", "(", "name", ",", "fromlist", "=", "public_api", ")", "except", "ImportError", ":", "raise", "except", "Exception", "as", "e", ":", "import", "sys", "from", "zmq", ".", "utils", ".", "sixcerpt", "import", "reraise", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "reraise", "(", "ImportError", ",", "ImportError", "(", "(", "'Importing %s failed with %s'", "%", "(", "name", ",", "e", ")", ")", ")", ",", "exc_info", "[", "2", "]", ")", "ns", "=", "{", "}", "for", "key", "in", "public_api", ":", "ns", "[", "key", "]", "=", "getattr", "(", "mod", ",", "key", ")", "return", "ns" ]
select the pyzmq backend .
train
false
15,451
@db_api.retry_if_session_inactive() def _ensure_external_network_default_value_callback(resource, event, trigger, context, request, network): is_default = request.get(IS_DEFAULT, False) if ((event in (events.BEFORE_CREATE, events.BEFORE_UPDATE)) and is_default): obj = context.session.query(ext_net_models.ExternalNetwork).filter_by(is_default=True).first() if (obj and (network['id'] != obj.network_id)): raise exceptions.DefaultExternalNetworkExists(net_id=obj.network_id) obj = context.session.query(ext_net_models.ExternalNetwork).filter_by(network_id=network['id']) obj.update({IS_DEFAULT: is_default})
[ "@", "db_api", ".", "retry_if_session_inactive", "(", ")", "def", "_ensure_external_network_default_value_callback", "(", "resource", ",", "event", ",", "trigger", ",", "context", ",", "request", ",", "network", ")", ":", "is_default", "=", "request", ".", "get", "(", "IS_DEFAULT", ",", "False", ")", "if", "(", "(", "event", "in", "(", "events", ".", "BEFORE_CREATE", ",", "events", ".", "BEFORE_UPDATE", ")", ")", "and", "is_default", ")", ":", "obj", "=", "context", ".", "session", ".", "query", "(", "ext_net_models", ".", "ExternalNetwork", ")", ".", "filter_by", "(", "is_default", "=", "True", ")", ".", "first", "(", ")", "if", "(", "obj", "and", "(", "network", "[", "'id'", "]", "!=", "obj", ".", "network_id", ")", ")", ":", "raise", "exceptions", ".", "DefaultExternalNetworkExists", "(", "net_id", "=", "obj", ".", "network_id", ")", "obj", "=", "context", ".", "session", ".", "query", "(", "ext_net_models", ".", "ExternalNetwork", ")", ".", "filter_by", "(", "network_id", "=", "network", "[", "'id'", "]", ")", "obj", ".", "update", "(", "{", "IS_DEFAULT", ":", "is_default", "}", ")" ]
ensure the is_default db field matches the create/update request .
train
false
15,453
def _MakeViewpointMetadataDict(viewpoint, follower, obj_store): metadata_dict = viewpoint.MakeMetadataDict(follower) if ('cover_photo' in metadata_dict): _AddPhotoUrls(obj_store, metadata_dict['cover_photo']) return metadata_dict
[ "def", "_MakeViewpointMetadataDict", "(", "viewpoint", ",", "follower", ",", "obj_store", ")", ":", "metadata_dict", "=", "viewpoint", ".", "MakeMetadataDict", "(", "follower", ")", "if", "(", "'cover_photo'", "in", "metadata_dict", ")", ":", "_AddPhotoUrls", "(", "obj_store", ",", "metadata_dict", "[", "'cover_photo'", "]", ")", "return", "metadata_dict" ]
returns a viewpoint metadata dictionary appropriate for a service query response .
train
false
15,457
def test_scientific_notation(): loaded = load('a: {a: 1e3, b: 1.E4, c: -1e-3, d: 2.3e+4, e: .2e4, f: 23.53e1, g: 32284.2e+9, h: 2.333993939e-3}') assert isinstance(loaded['a']['a'], float) assert isinstance(loaded['a']['b'], float) assert isinstance(loaded['a']['c'], float) assert isinstance(loaded['a']['d'], float) assert isinstance(loaded['a']['e'], float) assert isinstance(loaded['a']['f'], float) assert isinstance(loaded['a']['g'], float) assert isinstance(loaded['a']['h'], float)
[ "def", "test_scientific_notation", "(", ")", ":", "loaded", "=", "load", "(", "'a: {a: 1e3, b: 1.E4, c: -1e-3, d: 2.3e+4, e: .2e4, f: 23.53e1, g: 32284.2e+9, h: 2.333993939e-3}'", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'a'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'b'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'c'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'d'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'e'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'f'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'g'", "]", ",", "float", ")", "assert", "isinstance", "(", "loaded", "[", "'a'", "]", "[", "'h'", "]", ",", "float", ")" ]
test if yaml parses scientific notation as floats .
train
false
15,460
def getvalue(name, default): return getattr(settings, name, default)
[ "def", "getvalue", "(", "name", ",", "default", ")", ":", "return", "getattr", "(", "settings", ",", "name", ",", "default", ")" ]
returns setting from django settings with default value .
train
false
15,461
def error_override(self, msg): self.exit(2, msg=None)
[ "def", "error_override", "(", "self", ",", "msg", ")", ":", "self", ".", "exit", "(", "2", ",", "msg", "=", "None", ")" ]
hack to keep optionparser from writing to sys .
train
false
15,462
def packets_for_stream(fobj, offset): pcap = dpkt.pcap.Reader(fobj) pcapiter = iter(pcap) (ts, raw) = pcapiter.next() fobj.seek(offset) for p in next_connection_packets(pcapiter, linktype=pcap.datalink()): (yield p)
[ "def", "packets_for_stream", "(", "fobj", ",", "offset", ")", ":", "pcap", "=", "dpkt", ".", "pcap", ".", "Reader", "(", "fobj", ")", "pcapiter", "=", "iter", "(", "pcap", ")", "(", "ts", ",", "raw", ")", "=", "pcapiter", ".", "next", "(", ")", "fobj", ".", "seek", "(", "offset", ")", "for", "p", "in", "next_connection_packets", "(", "pcapiter", ",", "linktype", "=", "pcap", ".", "datalink", "(", ")", ")", ":", "(", "yield", "p", ")" ]
open a pcap .
train
false
15,464
def _isASCII(s): for c in s: if (ord(c) > 127): return False return True
[ "def", "_isASCII", "(", "s", ")", ":", "for", "c", "in", "s", ":", "if", "(", "ord", "(", "c", ")", ">", "127", ")", ":", "return", "False", "return", "True" ]
true if s consists entirely of ascii characters .
train
false
15,467
def get_image_path(name, default='not_found.png'): for img_path in IMG_PATH: full_path = osp.join(img_path, name) if osp.isfile(full_path): return osp.abspath(full_path) if (default is not None): return osp.abspath(osp.join(img_path, default))
[ "def", "get_image_path", "(", "name", ",", "default", "=", "'not_found.png'", ")", ":", "for", "img_path", "in", "IMG_PATH", ":", "full_path", "=", "osp", ".", "join", "(", "img_path", ",", "name", ")", "if", "osp", ".", "isfile", "(", "full_path", ")", ":", "return", "osp", ".", "abspath", "(", "full_path", ")", "if", "(", "default", "is", "not", "None", ")", ":", "return", "osp", ".", "abspath", "(", "osp", ".", "join", "(", "img_path", ",", "default", ")", ")" ]
return image absolute path .
train
true
15,468
def num_cpus(): try: return psutil.cpu_count() except AttributeError: return psutil.NUM_CPUS
[ "def", "num_cpus", "(", ")", ":", "try", ":", "return", "psutil", ".", "cpu_count", "(", ")", "except", "AttributeError", ":", "return", "psutil", ".", "NUM_CPUS" ]
detects the number of cpus on a system .
train
false
15,469
def stringify(pkgs): try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc)
[ "def", "stringify", "(", "pkgs", ")", ":", "try", ":", "for", "key", "in", "pkgs", ":", "pkgs", "[", "key", "]", "=", "','", ".", "join", "(", "pkgs", "[", "key", "]", ")", "except", "AttributeError", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")" ]
takes a dict of package name/version information and joins each list of installed versions into a string .
train
true
15,470
def pixel_print(pixel): (r, g, b) = pixel[:3] if (c['24BIT'] is True): sys.stdout.write(('\x1b[48;2;%d;%d;%dm \x1b[0m' % (r, g, b))) else: ansicolor = rgb2short(r, g, b) sys.stdout.write(('\x1b[48;5;%sm \x1b[0m' % ansicolor))
[ "def", "pixel_print", "(", "pixel", ")", ":", "(", "r", ",", "g", ",", "b", ")", "=", "pixel", "[", ":", "3", "]", "if", "(", "c", "[", "'24BIT'", "]", "is", "True", ")", ":", "sys", ".", "stdout", ".", "write", "(", "(", "'\\x1b[48;2;%d;%d;%dm \\x1b[0m'", "%", "(", "r", ",", "g", ",", "b", ")", ")", ")", "else", ":", "ansicolor", "=", "rgb2short", "(", "r", ",", "g", ",", "b", ")", "sys", ".", "stdout", ".", "write", "(", "(", "'\\x1b[48;5;%sm \\x1b[0m'", "%", "ansicolor", ")", ")" ]
print a pixel with given ansi color .
train
false
15,471
def EbookIterator(*args, **kwargs): from calibre.ebooks.oeb.iterator.book import EbookIterator return EbookIterator(*args, **kwargs)
[ "def", "EbookIterator", "(", "*", "args", ",", "**", "kwargs", ")", ":", "from", "calibre", ".", "ebooks", ".", "oeb", ".", "iterator", ".", "book", "import", "EbookIterator", "return", "EbookIterator", "(", "*", "args", ",", "**", "kwargs", ")" ]
for backwards compatibility .
train
false
15,472
def select_n_frame(frame, columns, n, method, keep): from pandas.core.series import Series if (not is_list_like(columns)): columns = [columns] columns = list(columns) ser = getattr(frame[columns[0]], method)(n, keep=keep) if isinstance(ser, Series): ser = ser.to_frame() return ser.merge(frame, on=columns[0], left_index=True)[frame.columns]
[ "def", "select_n_frame", "(", "frame", ",", "columns", ",", "n", ",", "method", ",", "keep", ")", ":", "from", "pandas", ".", "core", ".", "series", "import", "Series", "if", "(", "not", "is_list_like", "(", "columns", ")", ")", ":", "columns", "=", "[", "columns", "]", "columns", "=", "list", "(", "columns", ")", "ser", "=", "getattr", "(", "frame", "[", "columns", "[", "0", "]", "]", ",", "method", ")", "(", "n", ",", "keep", "=", "keep", ")", "if", "isinstance", "(", "ser", ",", "Series", ")", ":", "ser", "=", "ser", ".", "to_frame", "(", ")", "return", "ser", ".", "merge", "(", "frame", ",", "on", "=", "columns", "[", "0", "]", ",", "left_index", "=", "True", ")", "[", "frame", ".", "columns", "]" ]
implement n largest/smallest for pandas dataframe parameters frame : pandas .
train
false
15,474
def ordered_permutation_regex(sentence): sentence = _RE_REF.sub('\\1', sentence) sentence = _RE_REF_LANG.sub('\\1', sentence) sentence = _RE_SELF_REF.sub('', sentence) words = sentence.split() combinations = itertools.product((True, False), repeat=len(words)) solution = [] for combination in combinations: comb = [] for (iword, word) in enumerate(words): if combination[iword]: comb.append(word) elif comb: break if comb: solution.append((_PREFIX + ('[0-9]*%s*%s(?=\\W|$)+' % (_NUM_SEP, re_escape(' '.join(comb)).rstrip('\\'))))) regex = '|'.join(sorted(set(solution), key=(lambda o: len(o)), reverse=True)) return regex
[ "def", "ordered_permutation_regex", "(", "sentence", ")", ":", "sentence", "=", "_RE_REF", ".", "sub", "(", "'\\\\1'", ",", "sentence", ")", "sentence", "=", "_RE_REF_LANG", ".", "sub", "(", "'\\\\1'", ",", "sentence", ")", "sentence", "=", "_RE_SELF_REF", ".", "sub", "(", "''", ",", "sentence", ")", "words", "=", "sentence", ".", "split", "(", ")", "combinations", "=", "itertools", ".", "product", "(", "(", "True", ",", "False", ")", ",", "repeat", "=", "len", "(", "words", ")", ")", "solution", "=", "[", "]", "for", "combination", "in", "combinations", ":", "comb", "=", "[", "]", "for", "(", "iword", ",", "word", ")", "in", "enumerate", "(", "words", ")", ":", "if", "combination", "[", "iword", "]", ":", "comb", ".", "append", "(", "word", ")", "elif", "comb", ":", "break", "if", "comb", ":", "solution", ".", "append", "(", "(", "_PREFIX", "+", "(", "'[0-9]*%s*%s(?=\\\\W|$)+'", "%", "(", "_NUM_SEP", ",", "re_escape", "(", "' '", ".", "join", "(", "comb", ")", ")", ".", "rstrip", "(", "'\\\\'", ")", ")", ")", ")", ")", "regex", "=", "'|'", ".", "join", "(", "sorted", "(", "set", "(", "solution", ")", ",", "key", "=", "(", "lambda", "o", ":", "len", "(", "o", ")", ")", ",", "reverse", "=", "True", ")", ")", "return", "regex" ]
builds a regex that matches ordered permutations of a sentences words .
train
false
15,475
def regex_escape(string): return re.escape(string)
[ "def", "regex_escape", "(", "string", ")", ":", "return", "re", ".", "escape", "(", "string", ")" ]
escape all regular expressions special characters from string .
train
false
15,476
def post_match(view, name, style, first, second, center, bfr, threshold): if (first is not None): open_bracket = bfr[first.begin:first.end] if (open_bracket not in SPECIAL_KEYWORDS): open_bracket_stripped = open_bracket.strip() if (open_bracket_stripped not in NORMAL_KEYWORDS): m = RE_DEF.match(open_bracket) if m: first = first.move((first.begin + m.start(1)), (first.begin + m.end(1))) else: m = RE_KEYWORD.match(open_bracket) if m: first = first.move((first.begin + m.end(1)), first.end) return (first, second, style)
[ "def", "post_match", "(", "view", ",", "name", ",", "style", ",", "first", ",", "second", ",", "center", ",", "bfr", ",", "threshold", ")", ":", "if", "(", "first", "is", "not", "None", ")", ":", "open_bracket", "=", "bfr", "[", "first", ".", "begin", ":", "first", ".", "end", "]", "if", "(", "open_bracket", "not", "in", "SPECIAL_KEYWORDS", ")", ":", "open_bracket_stripped", "=", "open_bracket", ".", "strip", "(", ")", "if", "(", "open_bracket_stripped", "not", "in", "NORMAL_KEYWORDS", ")", ":", "m", "=", "RE_DEF", ".", "match", "(", "open_bracket", ")", "if", "m", ":", "first", "=", "first", ".", "move", "(", "(", "first", ".", "begin", "+", "m", ".", "start", "(", "1", ")", ")", ",", "(", "first", ".", "begin", "+", "m", ".", "end", "(", "1", ")", ")", ")", "else", ":", "m", "=", "RE_KEYWORD", ".", "match", "(", "open_bracket", ")", "if", "m", ":", "first", "=", "first", ".", "move", "(", "(", "first", ".", "begin", "+", "m", ".", "end", "(", "1", ")", ")", ",", "first", ".", "end", ")", "return", "(", "first", ",", "second", ",", "style", ")" ]
ensure that backticks that do not contribute inside the inline or block regions are not highlighted .
train
false
15,477
@conf.commands.register def wireshark(pktlist): f = get_temp_file() wrpcap(f, pktlist) subprocess.Popen([conf.prog.wireshark, '-r', f])
[ "@", "conf", ".", "commands", ".", "register", "def", "wireshark", "(", "pktlist", ")", ":", "f", "=", "get_temp_file", "(", ")", "wrpcap", "(", "f", ",", "pktlist", ")", "subprocess", ".", "Popen", "(", "[", "conf", ".", "prog", ".", "wireshark", ",", "'-r'", ",", "f", "]", ")" ]
run wireshark on a list of packets .
train
false
15,480
@api_versions.wraps('2.0', '2.9') @utils.arg('keypair', metavar='<keypair>', help=_('Name of keypair.')) def do_keypair_show(cs, args): keypair = _find_keypair(cs, args.keypair) _print_keypair(keypair)
[ "@", "api_versions", ".", "wraps", "(", "'2.0'", ",", "'2.9'", ")", "@", "utils", ".", "arg", "(", "'keypair'", ",", "metavar", "=", "'<keypair>'", ",", "help", "=", "_", "(", "'Name of keypair.'", ")", ")", "def", "do_keypair_show", "(", "cs", ",", "args", ")", ":", "keypair", "=", "_find_keypair", "(", "cs", ",", "args", ".", "keypair", ")", "_print_keypair", "(", "keypair", ")" ]
show details about the given keypair .
train
false
15,481
def ordlist(s): return map(ord, s)
[ "def", "ordlist", "(", "s", ")", ":", "return", "map", "(", "ord", ",", "s", ")" ]
ordlist(s) -> list turns a string into a list of the corresponding ascii values .
train
false
15,483
def _introspectRoute(route, exampleByIdentifier, schema_store): result = {} try: user_documentation = route.attributes['user_documentation'] except KeyError: raise SphinxError('Undocumented route: {}'.format(route)) result['description'] = prepare_docstring(user_documentation.text) result['header'] = user_documentation.header result['section'] = user_documentation.section inputSchema = route.attributes.get('inputSchema', None) outputSchema = route.attributes.get('outputSchema', None) if inputSchema: result['input'] = _parseSchema(inputSchema, schema_store) result['input_schema'] = inputSchema if outputSchema: result['output'] = _parseSchema(outputSchema, schema_store) result['output_schema'] = outputSchema examples = user_documentation.examples result['examples'] = list((Example.fromDictionary(exampleByIdentifier(identifier)) for identifier in examples)) return result
[ "def", "_introspectRoute", "(", "route", ",", "exampleByIdentifier", ",", "schema_store", ")", ":", "result", "=", "{", "}", "try", ":", "user_documentation", "=", "route", ".", "attributes", "[", "'user_documentation'", "]", "except", "KeyError", ":", "raise", "SphinxError", "(", "'Undocumented route: {}'", ".", "format", "(", "route", ")", ")", "result", "[", "'description'", "]", "=", "prepare_docstring", "(", "user_documentation", ".", "text", ")", "result", "[", "'header'", "]", "=", "user_documentation", ".", "header", "result", "[", "'section'", "]", "=", "user_documentation", ".", "section", "inputSchema", "=", "route", ".", "attributes", ".", "get", "(", "'inputSchema'", ",", "None", ")", "outputSchema", "=", "route", ".", "attributes", ".", "get", "(", "'outputSchema'", ",", "None", ")", "if", "inputSchema", ":", "result", "[", "'input'", "]", "=", "_parseSchema", "(", "inputSchema", ",", "schema_store", ")", "result", "[", "'input_schema'", "]", "=", "inputSchema", "if", "outputSchema", ":", "result", "[", "'output'", "]", "=", "_parseSchema", "(", "outputSchema", ",", "schema_store", ")", "result", "[", "'output_schema'", "]", "=", "outputSchema", "examples", "=", "user_documentation", ".", "examples", "result", "[", "'examples'", "]", "=", "list", "(", "(", "Example", ".", "fromDictionary", "(", "exampleByIdentifier", "(", "identifier", ")", ")", "for", "identifier", "in", "examples", ")", ")", "return", "result" ]
given a l{kleinroute} .
train
false
15,484
def set_maintenance(start=None, end=None): if (not database): return None start = (parse(start) if start else timezone.now()) end = (parse(end) if end else (start + timedelta(1))) if (not start.tzinfo): start = start.replace(tzinfo=pytz.UTC) if (not end.tzinfo): end = end.replace(tzinfo=pytz.UTC) if (start > end): start = (end - timedelta(1)) unset_maintenance() database.maintenance.insert({'maintenance': True, 'start': start.isoformat(), 'end': end.isoformat()})
[ "def", "set_maintenance", "(", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "(", "not", "database", ")", ":", "return", "None", "start", "=", "(", "parse", "(", "start", ")", "if", "start", "else", "timezone", ".", "now", "(", ")", ")", "end", "=", "(", "parse", "(", "end", ")", "if", "end", "else", "(", "start", "+", "timedelta", "(", "1", ")", ")", ")", "if", "(", "not", "start", ".", "tzinfo", ")", ":", "start", "=", "start", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")", "if", "(", "not", "end", ".", "tzinfo", ")", ":", "end", "=", "end", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")", "if", "(", "start", ">", "end", ")", ":", "start", "=", "(", "end", "-", "timedelta", "(", "1", ")", ")", "unset_maintenance", "(", ")", "database", ".", "maintenance", ".", "insert", "(", "{", "'maintenance'", ":", "True", ",", "'start'", ":", "start", ".", "isoformat", "(", ")", ",", "'end'", ":", "end", ".", "isoformat", "(", ")", "}", ")" ]
put a member into recovering state if value is true .
train
false
15,485
def dfs_labeled_edges(G, source=None): if (source is None): nodes = G else: nodes = [source] visited = set() for start in nodes: if (start in visited): continue (yield (start, start, 'forward')) visited.add(start) stack = [(start, iter(G[start]))] while stack: (parent, children) = stack[(-1)] try: child = next(children) if (child in visited): (yield (parent, child, 'nontree')) else: (yield (parent, child, 'forward')) visited.add(child) stack.append((child, iter(G[child]))) except StopIteration: stack.pop() if stack: (yield (stack[(-1)][0], parent, 'reverse')) (yield (start, start, 'reverse'))
[ "def", "dfs_labeled_edges", "(", "G", ",", "source", "=", "None", ")", ":", "if", "(", "source", "is", "None", ")", ":", "nodes", "=", "G", "else", ":", "nodes", "=", "[", "source", "]", "visited", "=", "set", "(", ")", "for", "start", "in", "nodes", ":", "if", "(", "start", "in", "visited", ")", ":", "continue", "(", "yield", "(", "start", ",", "start", ",", "'forward'", ")", ")", "visited", ".", "add", "(", "start", ")", "stack", "=", "[", "(", "start", ",", "iter", "(", "G", "[", "start", "]", ")", ")", "]", "while", "stack", ":", "(", "parent", ",", "children", ")", "=", "stack", "[", "(", "-", "1", ")", "]", "try", ":", "child", "=", "next", "(", "children", ")", "if", "(", "child", "in", "visited", ")", ":", "(", "yield", "(", "parent", ",", "child", ",", "'nontree'", ")", ")", "else", ":", "(", "yield", "(", "parent", ",", "child", ",", "'forward'", ")", ")", "visited", ".", "add", "(", "child", ")", "stack", ".", "append", "(", "(", "child", ",", "iter", "(", "G", "[", "child", "]", ")", ")", ")", "except", "StopIteration", ":", "stack", ".", "pop", "(", ")", "if", "stack", ":", "(", "yield", "(", "stack", "[", "(", "-", "1", ")", "]", "[", "0", "]", ",", "parent", ",", "'reverse'", ")", ")", "(", "yield", "(", "start", ",", "start", ",", "'reverse'", ")", ")" ]
produce edges in a depth-first-search labeled by type .
train
true
15,486
@app.template_filter('localize_dt_obj') def localize_dt_obj(dt, tzname): localized_dt = timezone(tzname).localize(dt) return localized_dt
[ "@", "app", ".", "template_filter", "(", "'localize_dt_obj'", ")", "def", "localize_dt_obj", "(", "dt", ",", "tzname", ")", ":", "localized_dt", "=", "timezone", "(", "tzname", ")", ".", "localize", "(", "dt", ")", "return", "localized_dt" ]
accepts a datetime object and a timezone name .
train
false
15,488
def _server_group_count_members_by_user(context, group, user_id): return group.count_members_by_user(user_id)
[ "def", "_server_group_count_members_by_user", "(", "context", ",", "group", ",", "user_id", ")", ":", "return", "group", ".", "count_members_by_user", "(", "user_id", ")" ]
helper method to avoid referencing objects .
train
false
15,489
def format_history_for_queue(): slotinfo = [] history_items = get_active_history() for item in history_items: slot = {'nzo_id': item['nzo_id'], 'bookmark': '', 'filename': xml_name(item['name']), 'loaded': False, 'stages': item['stage_log'], 'status': item['status'], 'bytes': item['bytes'], 'size': item['size']} slotinfo.append(slot) return slotinfo
[ "def", "format_history_for_queue", "(", ")", ":", "slotinfo", "=", "[", "]", "history_items", "=", "get_active_history", "(", ")", "for", "item", "in", "history_items", ":", "slot", "=", "{", "'nzo_id'", ":", "item", "[", "'nzo_id'", "]", ",", "'bookmark'", ":", "''", ",", "'filename'", ":", "xml_name", "(", "item", "[", "'name'", "]", ")", ",", "'loaded'", ":", "False", ",", "'stages'", ":", "item", "[", "'stage_log'", "]", ",", "'status'", ":", "item", "[", "'status'", "]", ",", "'bytes'", ":", "item", "[", "'bytes'", "]", ",", "'size'", ":", "item", "[", "'size'", "]", "}", "slotinfo", ".", "append", "(", "slot", ")", "return", "slotinfo" ]
retrieves the information on currently active history items .
train
false
15,492
def convert_json_to_df(results_url): with closing(urlopen(results_url)) as resp: res = json.loads(resp.read()) timings = res.get('timings') if (not timings): return res = [x for x in timings if x.get('succeeded')] df = pd.DataFrame(res) df = df.set_index('name') return df
[ "def", "convert_json_to_df", "(", "results_url", ")", ":", "with", "closing", "(", "urlopen", "(", "results_url", ")", ")", "as", "resp", ":", "res", "=", "json", ".", "loads", "(", "resp", ".", "read", "(", ")", ")", "timings", "=", "res", ".", "get", "(", "'timings'", ")", "if", "(", "not", "timings", ")", ":", "return", "res", "=", "[", "x", "for", "x", "in", "timings", "if", "x", ".", "get", "(", "'succeeded'", ")", "]", "df", "=", "pd", ".", "DataFrame", "(", "res", ")", "df", "=", "df", ".", "set_index", "(", "'name'", ")", "return", "df" ]
retrieve json results file from url and return df df contains timings for all successful vbenchmarks .
train
false
15,494
def set_parameters(version=None, binary_path=None, config_file=None, *args, **kwargs): if binary_path: set_binary_path(binary_path) if config_file: set_config_file(config_file) if version: version = _determine_config_version(__SYSLOG_NG_BINARY_PATH) write_version(version) return _format_return_data(0)
[ "def", "set_parameters", "(", "version", "=", "None", ",", "binary_path", "=", "None", ",", "config_file", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "binary_path", ":", "set_binary_path", "(", "binary_path", ")", "if", "config_file", ":", "set_config_file", "(", "config_file", ")", "if", "version", ":", "version", "=", "_determine_config_version", "(", "__SYSLOG_NG_BINARY_PATH", ")", "write_version", "(", "version", ")", "return", "_format_return_data", "(", "0", ")" ]
sets variables .
train
true
15,496
def get_c_declare(r, name, sub): if (any([getattr(c.op, 'check_input', config.check_input) for (c, _) in r.clients if (not isinstance(c, string_types))]) or (r.owner and getattr(r.owner.op, 'check_input', config.check_input))): c_declare = r.type.c_declare(name, sub, True) else: c_declare = r.type.c_declare(name, sub, False) pre = ('\n PyObject* py_%(name)s;\n ' % locals()) return (pre + c_declare)
[ "def", "get_c_declare", "(", "r", ",", "name", ",", "sub", ")", ":", "if", "(", "any", "(", "[", "getattr", "(", "c", ".", "op", ",", "'check_input'", ",", "config", ".", "check_input", ")", "for", "(", "c", ",", "_", ")", "in", "r", ".", "clients", "if", "(", "not", "isinstance", "(", "c", ",", "string_types", ")", ")", "]", ")", "or", "(", "r", ".", "owner", "and", "getattr", "(", "r", ".", "owner", ".", "op", ",", "'check_input'", ",", "config", ".", "check_input", ")", ")", ")", ":", "c_declare", "=", "r", ".", "type", ".", "c_declare", "(", "name", ",", "sub", ",", "True", ")", "else", ":", "c_declare", "=", "r", ".", "type", ".", "c_declare", "(", "name", ",", "sub", ",", "False", ")", "pre", "=", "(", "'\\n PyObject* py_%(name)s;\\n '", "%", "locals", "(", ")", ")", "return", "(", "pre", "+", "c_declare", ")" ]
wrapper around c_declare that declares py_name .
train
false
15,497
def assert_nD(array, ndim, arg_name='image'): array = np.asanyarray(array) msg_incorrect_dim = 'The parameter `%s` must be a %s-dimensional array' msg_empty_array = 'The parameter `%s` cannot be an empty array' if isinstance(ndim, int): ndim = [ndim] if (array.size == 0): raise ValueError((msg_empty_array % arg_name)) if (not (array.ndim in ndim)): raise ValueError((msg_incorrect_dim % (arg_name, '-or-'.join([str(n) for n in ndim]))))
[ "def", "assert_nD", "(", "array", ",", "ndim", ",", "arg_name", "=", "'image'", ")", ":", "array", "=", "np", ".", "asanyarray", "(", "array", ")", "msg_incorrect_dim", "=", "'The parameter `%s` must be a %s-dimensional array'", "msg_empty_array", "=", "'The parameter `%s` cannot be an empty array'", "if", "isinstance", "(", "ndim", ",", "int", ")", ":", "ndim", "=", "[", "ndim", "]", "if", "(", "array", ".", "size", "==", "0", ")", ":", "raise", "ValueError", "(", "(", "msg_empty_array", "%", "arg_name", ")", ")", "if", "(", "not", "(", "array", ".", "ndim", "in", "ndim", ")", ")", ":", "raise", "ValueError", "(", "(", "msg_incorrect_dim", "%", "(", "arg_name", ",", "'-or-'", ".", "join", "(", "[", "str", "(", "n", ")", "for", "n", "in", "ndim", "]", ")", ")", ")", ")" ]
verify an array meets the desired ndims and array isnt empty .
train
false
15,498
def grand_average(all_evoked, interpolate_bads=True): if (not all((isinstance(e, Evoked) for e in all_evoked))): raise ValueError('Not all the elements in list are evoked data') all_evoked = [e.copy() for e in all_evoked] if interpolate_bads: all_evoked = [(e.interpolate_bads() if (len(e.info['bads']) > 0) else e) for e in all_evoked] equalize_channels(all_evoked) grand_average = combine_evoked(all_evoked, weights='equal') grand_average.nave = len(all_evoked) grand_average.comment = ('Grand average (n = %d)' % grand_average.nave) return grand_average
[ "def", "grand_average", "(", "all_evoked", ",", "interpolate_bads", "=", "True", ")", ":", "if", "(", "not", "all", "(", "(", "isinstance", "(", "e", ",", "Evoked", ")", "for", "e", "in", "all_evoked", ")", ")", ")", ":", "raise", "ValueError", "(", "'Not all the elements in list are evoked data'", ")", "all_evoked", "=", "[", "e", ".", "copy", "(", ")", "for", "e", "in", "all_evoked", "]", "if", "interpolate_bads", ":", "all_evoked", "=", "[", "(", "e", ".", "interpolate_bads", "(", ")", "if", "(", "len", "(", "e", ".", "info", "[", "'bads'", "]", ")", ">", "0", ")", "else", "e", ")", "for", "e", "in", "all_evoked", "]", "equalize_channels", "(", "all_evoked", ")", "grand_average", "=", "combine_evoked", "(", "all_evoked", ",", "weights", "=", "'equal'", ")", "grand_average", ".", "nave", "=", "len", "(", "all_evoked", ")", "grand_average", ".", "comment", "=", "(", "'Grand average (n = %d)'", "%", "grand_average", ".", "nave", ")", "return", "grand_average" ]
make grand average of a list evoked data .
train
false
15,499
def crawl(links=[], domains=[], delay=20.0, parse=HTMLLinkParser().parse, sort=FIFO, method=DEPTH, **kwargs): crawler = Crawler(links, domains, delay, parse, sort) bind(crawler, 'visit', (lambda crawler, link, source=None: setattr(crawler, 'crawled', (link, source)))) while (not crawler.done): crawler.crawled = (None, None) crawler.crawl(method, **kwargs) (yield crawler.crawled)
[ "def", "crawl", "(", "links", "=", "[", "]", ",", "domains", "=", "[", "]", ",", "delay", "=", "20.0", ",", "parse", "=", "HTMLLinkParser", "(", ")", ".", "parse", ",", "sort", "=", "FIFO", ",", "method", "=", "DEPTH", ",", "**", "kwargs", ")", ":", "crawler", "=", "Crawler", "(", "links", ",", "domains", ",", "delay", ",", "parse", ",", "sort", ")", "bind", "(", "crawler", ",", "'visit'", ",", "(", "lambda", "crawler", ",", "link", ",", "source", "=", "None", ":", "setattr", "(", "crawler", ",", "'crawled'", ",", "(", "link", ",", "source", ")", ")", ")", ")", "while", "(", "not", "crawler", ".", "done", ")", ":", "crawler", ".", "crawled", "=", "(", "None", ",", "None", ")", "crawler", ".", "crawl", "(", "method", ",", "**", "kwargs", ")", "(", "yield", "crawler", ".", "crawled", ")" ]
returns a generator that yields -tuples of visited pages .
train
false
15,500
def registry_cache(): filename = registry_cache_filename() log.debug('Loading widget registry cache (%r).', filename) if os.path.exists(filename): try: with open(filename, 'rb') as f: return pickle.load(f) except Exception: log.error('Could not load registry cache.', exc_info=True) return {}
[ "def", "registry_cache", "(", ")", ":", "filename", "=", "registry_cache_filename", "(", ")", "log", ".", "debug", "(", "'Loading widget registry cache (%r).'", ",", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "try", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "return", "pickle", ".", "load", "(", "f", ")", "except", "Exception", ":", "log", ".", "error", "(", "'Could not load registry cache.'", ",", "exc_info", "=", "True", ")", "return", "{", "}" ]
return the registry cache dictionary .
train
false
15,504
def evaluate_object(obj, params): if isinstance(obj, basestring): return parse_string(obj, params) elif isinstance(obj, list): new_list = [] for item in obj: new_list.append(evaluate_object(item, params)) return new_list elif isinstance(obj, dict): new_dict = {} for key in obj: new_dict[key] = evaluate_object(obj[key], params) return new_dict else: return copy.deepcopy(obj)
[ "def", "evaluate_object", "(", "obj", ",", "params", ")", ":", "if", "isinstance", "(", "obj", ",", "basestring", ")", ":", "return", "parse_string", "(", "obj", ",", "params", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "new_list", "=", "[", "]", "for", "item", "in", "obj", ":", "new_list", ".", "append", "(", "evaluate_object", "(", "item", ",", "params", ")", ")", "return", "new_list", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "new_dict", "=", "{", "}", "for", "key", "in", "obj", ":", "new_dict", "[", "key", "]", "=", "evaluate_object", "(", "obj", "[", "key", "]", ",", "params", ")", "return", "new_dict", "else", ":", "return", "copy", ".", "deepcopy", "(", "obj", ")" ]
returns a copy of obj after parsing strings in it using params .
train
false
15,507
def output_subprocess_Popen(command, **params): if (('stdout' in params) or ('stderr' in params)): raise TypeError("don't use stderr or stdout with output_subprocess_Popen") params['stdout'] = subprocess.PIPE params['stderr'] = subprocess.PIPE p = subprocess_Popen(command, **params) out = p.communicate() return (out + (p.returncode,))
[ "def", "output_subprocess_Popen", "(", "command", ",", "**", "params", ")", ":", "if", "(", "(", "'stdout'", "in", "params", ")", "or", "(", "'stderr'", "in", "params", ")", ")", ":", "raise", "TypeError", "(", "\"don't use stderr or stdout with output_subprocess_Popen\"", ")", "params", "[", "'stdout'", "]", "=", "subprocess", ".", "PIPE", "params", "[", "'stderr'", "]", "=", "subprocess", ".", "PIPE", "p", "=", "subprocess_Popen", "(", "command", ",", "**", "params", ")", "out", "=", "p", ".", "communicate", "(", ")", "return", "(", "out", "+", "(", "p", ".", "returncode", ",", ")", ")" ]
calls subprocess_popen .
train
false
15,508
def save_stats_to_file(model): model_name = model._meta.model_name date = datetime.strptime(model.date, '%Y-%m-%d') path = u'{addon_id}/{date.year}/{date.month:02}/'.format(addon_id=model.addon_id, date=date) name_tpl = u'{date.year}_{date.month:02}_{date.day:02}_{model_name}.json' name = name_tpl.format(date=date, model_name=model_name) filepath = os.path.join(path, name) storage.save(filepath, ContentFile(serialize_stats(model)))
[ "def", "save_stats_to_file", "(", "model", ")", ":", "model_name", "=", "model", ".", "_meta", ".", "model_name", "date", "=", "datetime", ".", "strptime", "(", "model", ".", "date", ",", "'%Y-%m-%d'", ")", "path", "=", "u'{addon_id}/{date.year}/{date.month:02}/'", ".", "format", "(", "addon_id", "=", "model", ".", "addon_id", ",", "date", "=", "date", ")", "name_tpl", "=", "u'{date.year}_{date.month:02}_{date.day:02}_{model_name}.json'", "name", "=", "name_tpl", ".", "format", "(", "date", "=", "date", ",", "model_name", "=", "model_name", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "storage", ".", "save", "(", "filepath", ",", "ContentFile", "(", "serialize_stats", "(", "model", ")", ")", ")" ]
save the given model to a file on the disc .
train
false
15,509
def _run(mode, verbose, force, args, prefargs, watcher): prefs = PimpPreferences(**prefargs) if watcher: prefs.setWatcher(watcher) rv = prefs.check() if rv: sys.stdout.write(rv) db = PimpDatabase(prefs) db.appendURL(prefs.pimpDatabase) if (mode == 'dump'): db.dump(sys.stdout) elif (mode == 'list'): if (not args): args = db.listnames() print ('%-20.20s DCTB %s' % ('Package', 'Description')) print for pkgname in args: pkg = db.find(pkgname) if pkg: description = pkg.shortdescription() pkgname = pkg.fullname() else: description = 'Error: no such package' print ('%-20.20s DCTB %s' % (pkgname, description)) if verbose: print ' DCTB Home page: DCTB ', pkg.homepage() try: print ' DCTB Download URL: DCTB ', pkg.downloadURL() except KeyError: pass description = pkg.description() description = '\n DCTB DCTB DCTB DCTB DCTB '.join(description.splitlines()) print (' DCTB Description: DCTB %s' % description) elif (mode == 'status'): if (not args): args = db.listnames() print ('%-20.20s DCTB %s DCTB %s' % ('Package', 'Installed', 'Message')) print for pkgname in args: pkg = db.find(pkgname) if pkg: (status, msg) = pkg.installed() pkgname = pkg.fullname() else: status = 'error' msg = 'No such package' print ('%-20.20s DCTB %-9.9s DCTB %s' % (pkgname, status, msg)) if (verbose and (status == 'no')): prereq = pkg.prerequisites() for (pkg, msg) in prereq: if (not pkg): pkg = '' else: pkg = pkg.fullname() print ('%-20.20s DCTB Requirement: %s %s' % ('', pkg, msg)) elif (mode == 'install'): if (not args): print 'Please specify packages to install' sys.exit(1) inst = PimpInstaller(db) for pkgname in args: pkg = db.find(pkgname) if (not pkg): print ('%s: No such package' % pkgname) continue (list, messages) = inst.prepareInstall(pkg, force) if (messages and (not force)): print ('%s: Not installed:' % pkgname) for m in messages: print ' DCTB ', m else: if verbose: output = sys.stdout else: output = None messages = inst.install(list, output) if messages: print ('%s: Not installed:' % pkgname) for m in messages: print ' DCTB ', m
[ "def", "_run", "(", "mode", ",", "verbose", ",", "force", ",", "args", ",", "prefargs", ",", "watcher", ")", ":", "prefs", "=", "PimpPreferences", "(", "**", "prefargs", ")", "if", "watcher", ":", "prefs", ".", "setWatcher", "(", "watcher", ")", "rv", "=", "prefs", ".", "check", "(", ")", "if", "rv", ":", "sys", ".", "stdout", ".", "write", "(", "rv", ")", "db", "=", "PimpDatabase", "(", "prefs", ")", "db", ".", "appendURL", "(", "prefs", ".", "pimpDatabase", ")", "if", "(", "mode", "==", "'dump'", ")", ":", "db", ".", "dump", "(", "sys", ".", "stdout", ")", "elif", "(", "mode", "==", "'list'", ")", ":", "if", "(", "not", "args", ")", ":", "args", "=", "db", ".", "listnames", "(", ")", "print", "(", "'%-20.20s DCTB %s'", "%", "(", "'Package'", ",", "'Description'", ")", ")", "print", "for", "pkgname", "in", "args", ":", "pkg", "=", "db", ".", "find", "(", "pkgname", ")", "if", "pkg", ":", "description", "=", "pkg", ".", "shortdescription", "(", ")", "pkgname", "=", "pkg", ".", "fullname", "(", ")", "else", ":", "description", "=", "'Error: no such package'", "print", "(", "'%-20.20s DCTB %s'", "%", "(", "pkgname", ",", "description", ")", ")", "if", "verbose", ":", "print", "' DCTB Home page: DCTB '", ",", "pkg", ".", "homepage", "(", ")", "try", ":", "print", "' DCTB Download URL: DCTB '", ",", "pkg", ".", "downloadURL", "(", ")", "except", "KeyError", ":", "pass", "description", "=", "pkg", ".", "description", "(", ")", "description", "=", "'\\n DCTB DCTB DCTB DCTB DCTB '", ".", "join", "(", "description", ".", "splitlines", "(", ")", ")", "print", "(", "' DCTB Description: DCTB %s'", "%", "description", ")", "elif", "(", "mode", "==", "'status'", ")", ":", "if", "(", "not", "args", ")", ":", "args", "=", "db", ".", "listnames", "(", ")", "print", "(", "'%-20.20s DCTB %s DCTB %s'", "%", "(", "'Package'", ",", "'Installed'", ",", "'Message'", ")", ")", "print", "for", "pkgname", "in", "args", ":", "pkg", "=", "db", ".", "find", "(", "pkgname", ")", "if", "pkg", ":", "(", "status", ",", "msg", ")", "=", "pkg", ".", "installed", "(", ")", "pkgname", "=", "pkg", ".", "fullname", "(", ")", "else", ":", "status", "=", "'error'", "msg", "=", "'No such package'", "print", "(", "'%-20.20s DCTB %-9.9s DCTB %s'", "%", "(", "pkgname", ",", "status", ",", "msg", ")", ")", "if", "(", "verbose", "and", "(", "status", "==", "'no'", ")", ")", ":", "prereq", "=", "pkg", ".", "prerequisites", "(", ")", "for", "(", "pkg", ",", "msg", ")", "in", "prereq", ":", "if", "(", "not", "pkg", ")", ":", "pkg", "=", "''", "else", ":", "pkg", "=", "pkg", ".", "fullname", "(", ")", "print", "(", "'%-20.20s DCTB Requirement: %s %s'", "%", "(", "''", ",", "pkg", ",", "msg", ")", ")", "elif", "(", "mode", "==", "'install'", ")", ":", "if", "(", "not", "args", ")", ":", "print", "'Please specify packages to install'", "sys", ".", "exit", "(", "1", ")", "inst", "=", "PimpInstaller", "(", "db", ")", "for", "pkgname", "in", "args", ":", "pkg", "=", "db", ".", "find", "(", "pkgname", ")", "if", "(", "not", "pkg", ")", ":", "print", "(", "'%s: No such package'", "%", "pkgname", ")", "continue", "(", "list", ",", "messages", ")", "=", "inst", ".", "prepareInstall", "(", "pkg", ",", "force", ")", "if", "(", "messages", "and", "(", "not", "force", ")", ")", ":", "print", "(", "'%s: Not installed:'", "%", "pkgname", ")", "for", "m", "in", "messages", ":", "print", "' DCTB '", ",", "m", "else", ":", "if", "verbose", ":", "output", "=", "sys", ".", "stdout", "else", ":", "output", "=", "None", "messages", "=", "inst", ".", "install", "(", "list", ",", "output", ")", "if", "messages", ":", "print", "(", "'%s: Not installed:'", "%", "pkgname", ")", "for", "m", "in", "messages", ":", "print", "' DCTB '", ",", "m" ]
please dont use .
train
false
15,510
def dup_extract(f, g, K): fc = dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc, gc) if (not K.is_one(gcd)): f = dup_quo_ground(f, gcd, K) g = dup_quo_ground(g, gcd, K) return (gcd, f, g)
[ "def", "dup_extract", "(", "f", ",", "g", ",", "K", ")", ":", "fc", "=", "dup_content", "(", "f", ",", "K", ")", "gc", "=", "dup_content", "(", "g", ",", "K", ")", "gcd", "=", "K", ".", "gcd", "(", "fc", ",", "gc", ")", "if", "(", "not", "K", ".", "is_one", "(", "gcd", ")", ")", ":", "f", "=", "dup_quo_ground", "(", "f", ",", "gcd", ",", "K", ")", "g", "=", "dup_quo_ground", "(", "g", ",", "gcd", ",", "K", ")", "return", "(", "gcd", ",", "f", ",", "g", ")" ]
extract common content from a pair of polynomials in k[x] .
train
false
15,513
def out_of_date(original, derived): return ((not os.path.exists(derived)) or (os.path.exists(original) and (os.stat(derived).st_mtime < os.stat(original).st_mtime)))
[ "def", "out_of_date", "(", "original", ",", "derived", ")", ":", "return", "(", "(", "not", "os", ".", "path", ".", "exists", "(", "derived", ")", ")", "or", "(", "os", ".", "path", ".", "exists", "(", "original", ")", "and", "(", "os", ".", "stat", "(", "derived", ")", ".", "st_mtime", "<", "os", ".", "stat", "(", "original", ")", ".", "st_mtime", ")", ")", ")" ]
returns true if derivative is out-of-date wrt original .
train
true
15,514
def set_current_canvas(canvas): canvas.context._do_CURRENT_command = True if (canvasses and (canvasses[(-1)]() is canvas)): return cc = [c() for c in canvasses if (c() is not None)] while (canvas in cc): cc.remove(canvas) cc.append(canvas) canvasses[:] = [weakref.ref(c) for c in cc]
[ "def", "set_current_canvas", "(", "canvas", ")", ":", "canvas", ".", "context", ".", "_do_CURRENT_command", "=", "True", "if", "(", "canvasses", "and", "(", "canvasses", "[", "(", "-", "1", ")", "]", "(", ")", "is", "canvas", ")", ")", ":", "return", "cc", "=", "[", "c", "(", ")", "for", "c", "in", "canvasses", "if", "(", "c", "(", ")", "is", "not", "None", ")", "]", "while", "(", "canvas", "in", "cc", ")", ":", "cc", ".", "remove", "(", "canvas", ")", "cc", ".", "append", "(", "canvas", ")", "canvasses", "[", ":", "]", "=", "[", "weakref", ".", "ref", "(", "c", ")", "for", "c", "in", "cc", "]" ]
make a canvas active .
train
true
15,515
@do def upload_python_packages(scratch_directory, target_bucket, top_level, output, error): check_call(['python', 'setup.py', 'sdist', '--dist-dir={}'.format(scratch_directory.path), 'bdist_wheel', '--dist-dir={}'.format(scratch_directory.path)], cwd=top_level.path, stdout=output, stderr=error) files = set([f.basename() for f in scratch_directory.children()]) (yield Effect(UploadToS3Recursively(source_path=scratch_directory, target_bucket=target_bucket, target_key='python', files=files)))
[ "@", "do", "def", "upload_python_packages", "(", "scratch_directory", ",", "target_bucket", ",", "top_level", ",", "output", ",", "error", ")", ":", "check_call", "(", "[", "'python'", ",", "'setup.py'", ",", "'sdist'", ",", "'--dist-dir={}'", ".", "format", "(", "scratch_directory", ".", "path", ")", ",", "'bdist_wheel'", ",", "'--dist-dir={}'", ".", "format", "(", "scratch_directory", ".", "path", ")", "]", ",", "cwd", "=", "top_level", ".", "path", ",", "stdout", "=", "output", ",", "stderr", "=", "error", ")", "files", "=", "set", "(", "[", "f", ".", "basename", "(", ")", "for", "f", "in", "scratch_directory", ".", "children", "(", ")", "]", ")", "(", "yield", "Effect", "(", "UploadToS3Recursively", "(", "source_path", "=", "scratch_directory", ",", "target_bucket", "=", "target_bucket", ",", "target_key", "=", "'python'", ",", "files", "=", "files", ")", ")", ")" ]
the repository contains source distributions and binary distributions for flocker .
train
false
15,516
def followed_by(username, number=(-1), etag=None): return (gh.followed_by(username, number, etag) if username else [])
[ "def", "followed_by", "(", "username", ",", "number", "=", "(", "-", "1", ")", ",", "etag", "=", "None", ")", ":", "return", "(", "gh", ".", "followed_by", "(", "username", ",", "number", ",", "etag", ")", "if", "username", "else", "[", "]", ")" ]
list the people username follows .
train
false
15,520
def partial_max(a): return a.max(axis=(1, 2))
[ "def", "partial_max", "(", "a", ")", ":", "return", "a", ".", "max", "(", "axis", "=", "(", "1", ",", "2", ")", ")" ]
a: a 4d theano tensor returns b .
train
false
15,521
def guess_idnumber(string): ret = [] matches = list(_idnum.finditer(string)) for match in matches: result = match.groupdict() switch_count = 0 switch_letter_count = 0 letter_count = 0 last_letter = None last = _LETTER for c in result['uuid']: if (c in '0123456789'): ci = _DIGIT elif (c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'): ci = _LETTER if (c != last_letter): switch_letter_count += 1 last_letter = c letter_count += 1 else: ci = _OTHER if (ci != last): switch_count += 1 last = ci switch_ratio = (float(switch_count) / len(result['uuid'])) letters_ratio = ((float(switch_letter_count) / letter_count) if (letter_count > 0) else 1) if ((switch_ratio > 0.4) and (letters_ratio > 0.4)): ret.append(match.span()) return ret
[ "def", "guess_idnumber", "(", "string", ")", ":", "ret", "=", "[", "]", "matches", "=", "list", "(", "_idnum", ".", "finditer", "(", "string", ")", ")", "for", "match", "in", "matches", ":", "result", "=", "match", ".", "groupdict", "(", ")", "switch_count", "=", "0", "switch_letter_count", "=", "0", "letter_count", "=", "0", "last_letter", "=", "None", "last", "=", "_LETTER", "for", "c", "in", "result", "[", "'uuid'", "]", ":", "if", "(", "c", "in", "'0123456789'", ")", ":", "ci", "=", "_DIGIT", "elif", "(", "c", "in", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ")", ":", "ci", "=", "_LETTER", "if", "(", "c", "!=", "last_letter", ")", ":", "switch_letter_count", "+=", "1", "last_letter", "=", "c", "letter_count", "+=", "1", "else", ":", "ci", "=", "_OTHER", "if", "(", "ci", "!=", "last", ")", ":", "switch_count", "+=", "1", "last", "=", "ci", "switch_ratio", "=", "(", "float", "(", "switch_count", ")", "/", "len", "(", "result", "[", "'uuid'", "]", ")", ")", "letters_ratio", "=", "(", "(", "float", "(", "switch_letter_count", ")", "/", "letter_count", ")", "if", "(", "letter_count", ">", "0", ")", "else", "1", ")", "if", "(", "(", "switch_ratio", ">", "0.4", ")", "and", "(", "letters_ratio", ">", "0.4", ")", ")", ":", "ret", ".", "append", "(", "match", ".", "span", "(", ")", ")", "return", "ret" ]
guess id number function .
train
false
15,523
def check_word_has_not_meaning(word): has_number = False has_letter = False for i in xrange(10): if (str(i) in word): has_number = True break try: int(word) except Exception as e: has_letter = True if ((len(word) > 3) and has_letter and has_number): return True else: return False
[ "def", "check_word_has_not_meaning", "(", "word", ")", ":", "has_number", "=", "False", "has_letter", "=", "False", "for", "i", "in", "xrange", "(", "10", ")", ":", "if", "(", "str", "(", "i", ")", "in", "word", ")", ":", "has_number", "=", "True", "break", "try", ":", "int", "(", "word", ")", "except", "Exception", "as", "e", ":", "has_letter", "=", "True", "if", "(", "(", "len", "(", "word", ")", ">", "3", ")", "and", "has_letter", "and", "has_number", ")", ":", "return", "True", "else", ":", "return", "False" ]
return true .
train
false
15,524
def pick(seq, func, maxobj=None): maxscore = None for obj in seq: score = func(obj) if ((maxscore is None) or (maxscore < score)): (maxscore, maxobj) = (score, obj) return maxobj
[ "def", "pick", "(", "seq", ",", "func", ",", "maxobj", "=", "None", ")", ":", "maxscore", "=", "None", "for", "obj", "in", "seq", ":", "score", "=", "func", "(", "obj", ")", "if", "(", "(", "maxscore", "is", "None", ")", "or", "(", "maxscore", "<", "score", ")", ")", ":", "(", "maxscore", ",", "maxobj", ")", "=", "(", "score", ",", "obj", ")", "return", "maxobj" ]
picks the object obj where func has the highest value .
train
true
15,525
def define_plugin_entries(groups): result = dict() for (group, modules) in groups: tempo = [] for (module_name, names) in modules: tempo.extend([define_plugin_entry(name, module_name) for name in names]) result[group] = tempo return result
[ "def", "define_plugin_entries", "(", "groups", ")", ":", "result", "=", "dict", "(", ")", "for", "(", "group", ",", "modules", ")", "in", "groups", ":", "tempo", "=", "[", "]", "for", "(", "module_name", ",", "names", ")", "in", "modules", ":", "tempo", ".", "extend", "(", "[", "define_plugin_entry", "(", "name", ",", "module_name", ")", "for", "name", "in", "names", "]", ")", "result", "[", "group", "]", "=", "tempo", "return", "result" ]
helper to all groups for plugins .
train
true
15,526
def start_new_thread(function, args, kwargs={}): if (type(args) != type(tuple())): raise TypeError('2nd arg must be a tuple') if (type(kwargs) != type(dict())): raise TypeError('3rd arg must be a dict') global _main _main = False try: function(*args, **kwargs) except SystemExit: pass except: _traceback.print_exc() _main = True global _interrupt if _interrupt: _interrupt = False raise KeyboardInterrupt
[ "def", "start_new_thread", "(", "function", ",", "args", ",", "kwargs", "=", "{", "}", ")", ":", "if", "(", "type", "(", "args", ")", "!=", "type", "(", "tuple", "(", ")", ")", ")", ":", "raise", "TypeError", "(", "'2nd arg must be a tuple'", ")", "if", "(", "type", "(", "kwargs", ")", "!=", "type", "(", "dict", "(", ")", ")", ")", ":", "raise", "TypeError", "(", "'3rd arg must be a dict'", ")", "global", "_main", "_main", "=", "False", "try", ":", "function", "(", "*", "args", ",", "**", "kwargs", ")", "except", "SystemExit", ":", "pass", "except", ":", "_traceback", ".", "print_exc", "(", ")", "_main", "=", "True", "global", "_interrupt", "if", "_interrupt", ":", "_interrupt", "=", "False", "raise", "KeyboardInterrupt" ]
dummy implementation of _thread .
train
true
15,527
def _create_dot_graph(graph, show_connectinfo=False, simple_form=True): logger.debug(u'creating dot graph') pklgraph = nx.DiGraph() for edge in graph.edges(): data = graph.get_edge_data(*edge) srcname = get_print_name(edge[0], simple_form=simple_form) destname = get_print_name(edge[1], simple_form=simple_form) if show_connectinfo: pklgraph.add_edge(srcname, destname, l=str(data[u'connect'])) else: pklgraph.add_edge(srcname, destname) return pklgraph
[ "def", "_create_dot_graph", "(", "graph", ",", "show_connectinfo", "=", "False", ",", "simple_form", "=", "True", ")", ":", "logger", ".", "debug", "(", "u'creating dot graph'", ")", "pklgraph", "=", "nx", ".", "DiGraph", "(", ")", "for", "edge", "in", "graph", ".", "edges", "(", ")", ":", "data", "=", "graph", ".", "get_edge_data", "(", "*", "edge", ")", "srcname", "=", "get_print_name", "(", "edge", "[", "0", "]", ",", "simple_form", "=", "simple_form", ")", "destname", "=", "get_print_name", "(", "edge", "[", "1", "]", ",", "simple_form", "=", "simple_form", ")", "if", "show_connectinfo", ":", "pklgraph", ".", "add_edge", "(", "srcname", ",", "destname", ",", "l", "=", "str", "(", "data", "[", "u'connect'", "]", ")", ")", "else", ":", "pklgraph", ".", "add_edge", "(", "srcname", ",", "destname", ")", "return", "pklgraph" ]
create a graph that can be pickled .
train
false
15,528
def fitness_calculator(genome): assert isinstance(genome, MutableSeq), 'Expected MutableSeq for a genome.' regular_seq = genome.toseq() return int(str(regular_seq))
[ "def", "fitness_calculator", "(", "genome", ")", ":", "assert", "isinstance", "(", "genome", ",", "MutableSeq", ")", ",", "'Expected MutableSeq for a genome.'", "regular_seq", "=", "genome", ".", "toseq", "(", ")", "return", "int", "(", "str", "(", "regular_seq", ")", ")" ]
calculate fitness for testing purposes .
train
false
15,529
def get_descendant_ids(root_id): children = Page.objects.filter(parent=root_id).values_list(u'pk', flat=True) for child_id in children.iterator(): (yield child_id) for descendant_id in get_descendant_ids(child_id): (yield descendant_id)
[ "def", "get_descendant_ids", "(", "root_id", ")", ":", "children", "=", "Page", ".", "objects", ".", "filter", "(", "parent", "=", "root_id", ")", ".", "values_list", "(", "u'pk'", ",", "flat", "=", "True", ")", "for", "child_id", "in", "children", ".", "iterator", "(", ")", ":", "(", "yield", "child_id", ")", "for", "descendant_id", "in", "get_descendant_ids", "(", "child_id", ")", ":", "(", "yield", "descendant_id", ")" ]
returns the a generator of primary keys which represent descendants of the given page id .
train
false
15,531
def CDL3LINESTRIKE(barDs, count): return call_talib_with_ohlc(barDs, count, talib.CDL3LINESTRIKE)
[ "def", "CDL3LINESTRIKE", "(", "barDs", ",", "count", ")", ":", "return", "call_talib_with_ohlc", "(", "barDs", ",", "count", ",", "talib", ".", "CDL3LINESTRIKE", ")" ]
three-line strike .
train
false
15,533
def fticks_log(sp, logf, idp_entity_id, user_id, secret, assertion): csum = hmac.new(secret, digestmod=hashlib.sha1) csum.update(user_id) ac = assertion.AuthnStatement[0].AuthnContext[0] info = {'TS': time.time(), 'RP': sp.entity_id, 'AP': idp_entity_id, 'PN': csum.hexdigest(), 'AM': ac.AuthnContextClassRef.text} logf.info((FTICKS_FORMAT % '#'.join([('%s=%s' % (a, v)) for (a, v) in info])))
[ "def", "fticks_log", "(", "sp", ",", "logf", ",", "idp_entity_id", ",", "user_id", ",", "secret", ",", "assertion", ")", ":", "csum", "=", "hmac", ".", "new", "(", "secret", ",", "digestmod", "=", "hashlib", ".", "sha1", ")", "csum", ".", "update", "(", "user_id", ")", "ac", "=", "assertion", ".", "AuthnStatement", "[", "0", "]", ".", "AuthnContext", "[", "0", "]", "info", "=", "{", "'TS'", ":", "time", ".", "time", "(", ")", ",", "'RP'", ":", "sp", ".", "entity_id", ",", "'AP'", ":", "idp_entity_id", ",", "'PN'", ":", "csum", ".", "hexdigest", "(", ")", ",", "'AM'", ":", "ac", ".", "AuthnContextClassRef", ".", "text", "}", "logf", ".", "info", "(", "(", "FTICKS_FORMAT", "%", "'#'", ".", "join", "(", "[", "(", "'%s=%s'", "%", "(", "a", ",", "v", ")", ")", "for", "(", "a", ",", "v", ")", "in", "info", "]", ")", ")", ")" ]
f-ticks/ federationidentifier / version * # allowed attributes: ts the login time stamp rp the relying party entityid ap the asserting party entityid pn a sha256-hash of the local principal name and a unique key am the authentication method urn .
train
false
15,534
def email_error_information(): expected_info = ['created', 'sent_to', 'email', 'number_sent', 'requester'] return {info: None for info in expected_info}
[ "def", "email_error_information", "(", ")", ":", "expected_info", "=", "[", "'created'", ",", "'sent_to'", ",", "'email'", ",", "'number_sent'", ",", "'requester'", "]", "return", "{", "info", ":", "None", "for", "info", "in", "expected_info", "}" ]
returns email information marked as none .
train
false
15,535
def p_statement_list_1(t): pass
[ "def", "p_statement_list_1", "(", "t", ")", ":", "pass" ]
statement_list : statement .
train
false
15,536
def parse_function_signature(code): m = re.search((('^\\s*' + re_func_decl) + '\\s*{'), code, re.M) if (m is None): print code raise Exception('Failed to parse function signature. Full code is printed above.') (rtype, name, args) = m.groups()[:3] if ((args == 'void') or (args.strip() == '')): args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] return (name, args, rtype)
[ "def", "parse_function_signature", "(", "code", ")", ":", "m", "=", "re", ".", "search", "(", "(", "(", "'^\\\\s*'", "+", "re_func_decl", ")", "+", "'\\\\s*{'", ")", ",", "code", ",", "re", ".", "M", ")", "if", "(", "m", "is", "None", ")", ":", "print", "code", "raise", "Exception", "(", "'Failed to parse function signature. Full code is printed above.'", ")", "(", "rtype", ",", "name", ",", "args", ")", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "if", "(", "(", "args", "==", "'void'", ")", "or", "(", "args", ".", "strip", "(", ")", "==", "''", ")", ")", ":", "args", "=", "[", "]", "else", ":", "args", "=", "[", "tuple", "(", "arg", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ")", "for", "arg", "in", "args", ".", "split", "(", "','", ")", "]", "return", "(", "name", ",", "args", ",", "rtype", ")" ]
return the name .
train
true
15,537
def display_action(parser, token): return DisplayAction.handle_token(parser, token)
[ "def", "display_action", "(", "parser", ",", "token", ")", ":", "return", "DisplayAction", ".", "handle_token", "(", "parser", ",", "token", ")" ]
renders the template for the action description {% display_action action %} .
train
false
15,540
@not_implemented_for('undirected') def number_weakly_connected_components(G): return len(list(weakly_connected_components(G)))
[ "@", "not_implemented_for", "(", "'undirected'", ")", "def", "number_weakly_connected_components", "(", "G", ")", ":", "return", "len", "(", "list", "(", "weakly_connected_components", "(", "G", ")", ")", ")" ]
return the number of weakly connected components in g .
train
false
15,541
@pytest.mark.skipif(u'not PY3_4 or sys.platform == "win32" or sys.platform.startswith("gnu0")') def test_multiprocessing_forkserver(): import multiprocessing ctx = multiprocessing.get_context(u'forkserver') pool = ctx.Pool(1) result = pool.map(_square, [1, 2, 3, 4, 5]) pool.close() pool.join() assert (result == [1, 4, 9, 16, 25])
[ "@", "pytest", ".", "mark", ".", "skipif", "(", "u'not PY3_4 or sys.platform == \"win32\" or sys.platform.startswith(\"gnu0\")'", ")", "def", "test_multiprocessing_forkserver", "(", ")", ":", "import", "multiprocessing", "ctx", "=", "multiprocessing", ".", "get_context", "(", "u'forkserver'", ")", "pool", "=", "ctx", ".", "Pool", "(", "1", ")", "result", "=", "pool", ".", "map", "(", "_square", ",", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", "]", ")", "pool", ".", "close", "(", ")", "pool", ".", "join", "(", ")", "assert", "(", "result", "==", "[", "1", ",", "4", ",", "9", ",", "16", ",", "25", "]", ")" ]
test that using multiprocessing with forkserver works .
train
false
15,542
def _get_report_choice(key): import doctest return {DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF, DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF, DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF, DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE, DOCTEST_REPORT_CHOICE_NONE: 0}[key]
[ "def", "_get_report_choice", "(", "key", ")", ":", "import", "doctest", "return", "{", "DOCTEST_REPORT_CHOICE_UDIFF", ":", "doctest", ".", "REPORT_UDIFF", ",", "DOCTEST_REPORT_CHOICE_CDIFF", ":", "doctest", ".", "REPORT_CDIFF", ",", "DOCTEST_REPORT_CHOICE_NDIFF", ":", "doctest", ".", "REPORT_NDIFF", ",", "DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE", ":", "doctest", ".", "REPORT_ONLY_FIRST_FAILURE", ",", "DOCTEST_REPORT_CHOICE_NONE", ":", "0", "}", "[", "key", "]" ]
this function returns the actual doctest module flag value .
train
false
15,543
def col_scale(x, s): if (x.format == 'csc'): return ColScaleCSC()(x, s) elif (x.format == 'csr'): return RowScaleCSC()(x.T, s).T else: raise NotImplementedError()
[ "def", "col_scale", "(", "x", ",", "s", ")", ":", "if", "(", "x", ".", "format", "==", "'csc'", ")", ":", "return", "ColScaleCSC", "(", ")", "(", "x", ",", "s", ")", "elif", "(", "x", ".", "format", "==", "'csr'", ")", ":", "return", "RowScaleCSC", "(", ")", "(", "x", ".", "T", ",", "s", ")", ".", "T", "else", ":", "raise", "NotImplementedError", "(", ")" ]
scale each columns of a sparse matrix by the corresponding element of a dense vector .
train
false
15,544
def reduce_abs_inequalities(exprs, gen): return And(*[reduce_abs_inequality(expr, rel, gen) for (expr, rel) in exprs])
[ "def", "reduce_abs_inequalities", "(", "exprs", ",", "gen", ")", ":", "return", "And", "(", "*", "[", "reduce_abs_inequality", "(", "expr", ",", "rel", ",", "gen", ")", "for", "(", "expr", ",", "rel", ")", "in", "exprs", "]", ")" ]
reduce a system of inequalities with nested absolute values .
train
false
15,545
def _assert_labels_equal(labels_a, labels_b, ignore_pos=False): for (label_a, label_b) in zip(labels_a, labels_b): assert_array_equal(label_a.vertices, label_b.vertices) assert_true((label_a.name == label_b.name)) assert_true((label_a.hemi == label_b.hemi)) if (not ignore_pos): assert_array_equal(label_a.pos, label_b.pos)
[ "def", "_assert_labels_equal", "(", "labels_a", ",", "labels_b", ",", "ignore_pos", "=", "False", ")", ":", "for", "(", "label_a", ",", "label_b", ")", "in", "zip", "(", "labels_a", ",", "labels_b", ")", ":", "assert_array_equal", "(", "label_a", ".", "vertices", ",", "label_b", ".", "vertices", ")", "assert_true", "(", "(", "label_a", ".", "name", "==", "label_b", ".", "name", ")", ")", "assert_true", "(", "(", "label_a", ".", "hemi", "==", "label_b", ".", "hemi", ")", ")", "if", "(", "not", "ignore_pos", ")", ":", "assert_array_equal", "(", "label_a", ".", "pos", ",", "label_b", ".", "pos", ")" ]
make sure two sets of labels are equal .
train
false
15,546
@login_required def done(request): ctx = {'version': version, 'last_login': request.session.get('social_auth_last_login_backend')} return render_to_response('done.html', ctx, RequestContext(request))
[ "@", "login_required", "def", "done", "(", "request", ")", ":", "ctx", "=", "{", "'version'", ":", "version", ",", "'last_login'", ":", "request", ".", "session", ".", "get", "(", "'social_auth_last_login_backend'", ")", "}", "return", "render_to_response", "(", "'done.html'", ",", "ctx", ",", "RequestContext", "(", "request", ")", ")" ]
login complete view .
train
false
15,547
def _bson_to_dict(data, opts): try: obj_size = _UNPACK_INT(data[:4])[0] except struct.error as exc: raise InvalidBSON(str(exc)) if (obj_size != len(data)): raise InvalidBSON('invalid object size') if (data[(obj_size - 1):obj_size] != '\x00'): raise InvalidBSON('bad eoo') try: if _raw_document_class(opts.document_class): return opts.document_class(data, opts) return _elements_to_dict(data, 4, (obj_size - 1), opts) except InvalidBSON: raise except Exception: (_, exc_value, exc_tb) = sys.exc_info() reraise(InvalidBSON, exc_value, exc_tb)
[ "def", "_bson_to_dict", "(", "data", ",", "opts", ")", ":", "try", ":", "obj_size", "=", "_UNPACK_INT", "(", "data", "[", ":", "4", "]", ")", "[", "0", "]", "except", "struct", ".", "error", "as", "exc", ":", "raise", "InvalidBSON", "(", "str", "(", "exc", ")", ")", "if", "(", "obj_size", "!=", "len", "(", "data", ")", ")", ":", "raise", "InvalidBSON", "(", "'invalid object size'", ")", "if", "(", "data", "[", "(", "obj_size", "-", "1", ")", ":", "obj_size", "]", "!=", "'\\x00'", ")", ":", "raise", "InvalidBSON", "(", "'bad eoo'", ")", "try", ":", "if", "_raw_document_class", "(", "opts", ".", "document_class", ")", ":", "return", "opts", ".", "document_class", "(", "data", ",", "opts", ")", "return", "_elements_to_dict", "(", "data", ",", "4", ",", "(", "obj_size", "-", "1", ")", ",", "opts", ")", "except", "InvalidBSON", ":", "raise", "except", "Exception", ":", "(", "_", ",", "exc_value", ",", "exc_tb", ")", "=", "sys", ".", "exc_info", "(", ")", "reraise", "(", "InvalidBSON", ",", "exc_value", ",", "exc_tb", ")" ]
decode a bson string to document_class .
train
true
15,548
def rand_text(length, bad='', chars=allchars): return rand_base(length, bad, chars)
[ "def", "rand_text", "(", "length", ",", "bad", "=", "''", ",", "chars", "=", "allchars", ")", ":", "return", "rand_base", "(", "length", ",", "bad", ",", "chars", ")" ]
generate random string for websites .
train
false
15,549
def str_to_hex(string): return ':'.join((x.encode('hex') for x in string))
[ "def", "str_to_hex", "(", "string", ")", ":", "return", "':'", ".", "join", "(", "(", "x", ".", "encode", "(", "'hex'", ")", "for", "x", "in", "string", ")", ")" ]
returns a string in readable hex encoding .
train
false
15,550
def apply_network_settings(**settings): if ('require_reboot' not in settings): settings['require_reboot'] = False if ('apply_hostname' not in settings): settings['apply_hostname'] = False hostname_res = True if (settings['apply_hostname'] in _CONFIG_TRUE): if ('hostname' in settings): hostname_res = __salt__['network.mod_hostname'](settings['hostname']) else: log.warning('The network state sls is trying to apply hostname changes but no hostname is defined.') hostname_res = False res = True if (settings['require_reboot'] in _CONFIG_TRUE): log.warning('The network state sls is requiring a reboot of the system to properly apply network configuration.') res = True else: res = __salt__['service.restart']('network') return (hostname_res and res)
[ "def", "apply_network_settings", "(", "**", "settings", ")", ":", "if", "(", "'require_reboot'", "not", "in", "settings", ")", ":", "settings", "[", "'require_reboot'", "]", "=", "False", "if", "(", "'apply_hostname'", "not", "in", "settings", ")", ":", "settings", "[", "'apply_hostname'", "]", "=", "False", "hostname_res", "=", "True", "if", "(", "settings", "[", "'apply_hostname'", "]", "in", "_CONFIG_TRUE", ")", ":", "if", "(", "'hostname'", "in", "settings", ")", ":", "hostname_res", "=", "__salt__", "[", "'network.mod_hostname'", "]", "(", "settings", "[", "'hostname'", "]", ")", "else", ":", "log", ".", "warning", "(", "'The network state sls is trying to apply hostname changes but no hostname is defined.'", ")", "hostname_res", "=", "False", "res", "=", "True", "if", "(", "settings", "[", "'require_reboot'", "]", "in", "_CONFIG_TRUE", ")", ":", "log", ".", "warning", "(", "'The network state sls is requiring a reboot of the system to properly apply network configuration.'", ")", "res", "=", "True", "else", ":", "res", "=", "__salt__", "[", "'service.restart'", "]", "(", "'network'", ")", "return", "(", "hostname_res", "and", "res", ")" ]
apply global network configuration .
train
true
15,552
def test_ascii(): raw = read_raw_brainvision(vhdr_path, event_id=event_id) tempdir = _TempDir() ascii_vhdr_path = op.join(tempdir, op.split(vhdr_path)[(-1)]) shutil.copy(vhdr_path.replace('.vhdr', '.vmrk'), ascii_vhdr_path.replace('.vhdr', '.vmrk')) skipping = False with open(ascii_vhdr_path, 'wb') as fout: with open(vhdr_path, 'rb') as fin: for line in fin: if line.startswith('DataFormat'): line = 'DataFormat=ASCII\n' elif line.startswith('DataFile='): line = 'DataFile=test.dat\n' elif line.startswith('[Binary Infos]'): skipping = True fout.write('[ASCII Infos]\nDecimalSymbol=.\nSkipLines=1\nSkipColumns=0\n\n') elif (skipping and line.startswith('[')): skipping = False if (not skipping): fout.write(line) (data, times) = raw[:] with open(ascii_vhdr_path.replace('.vhdr', '.dat'), 'wb') as fid: fid.write((' '.join((ch_name.encode('ASCII') for ch_name in raw.ch_names)) + '\n')) fid.write('\n'.join((' '.join((('%.3f' % dd) for dd in d)) for d in (data[:(-1)].T / raw._cals[:(-1)])))) raw = read_raw_brainvision(ascii_vhdr_path, event_id=event_id) (data_new, times_new) = raw[:] assert_allclose(data_new, data, atol=1e-15) assert_allclose(times_new, times)
[ "def", "test_ascii", "(", ")", ":", "raw", "=", "read_raw_brainvision", "(", "vhdr_path", ",", "event_id", "=", "event_id", ")", "tempdir", "=", "_TempDir", "(", ")", "ascii_vhdr_path", "=", "op", ".", "join", "(", "tempdir", ",", "op", ".", "split", "(", "vhdr_path", ")", "[", "(", "-", "1", ")", "]", ")", "shutil", ".", "copy", "(", "vhdr_path", ".", "replace", "(", "'.vhdr'", ",", "'.vmrk'", ")", ",", "ascii_vhdr_path", ".", "replace", "(", "'.vhdr'", ",", "'.vmrk'", ")", ")", "skipping", "=", "False", "with", "open", "(", "ascii_vhdr_path", ",", "'wb'", ")", "as", "fout", ":", "with", "open", "(", "vhdr_path", ",", "'rb'", ")", "as", "fin", ":", "for", "line", "in", "fin", ":", "if", "line", ".", "startswith", "(", "'DataFormat'", ")", ":", "line", "=", "'DataFormat=ASCII\\n'", "elif", "line", ".", "startswith", "(", "'DataFile='", ")", ":", "line", "=", "'DataFile=test.dat\\n'", "elif", "line", ".", "startswith", "(", "'[Binary Infos]'", ")", ":", "skipping", "=", "True", "fout", ".", "write", "(", "'[ASCII Infos]\\nDecimalSymbol=.\\nSkipLines=1\\nSkipColumns=0\\n\\n'", ")", "elif", "(", "skipping", "and", "line", ".", "startswith", "(", "'['", ")", ")", ":", "skipping", "=", "False", "if", "(", "not", "skipping", ")", ":", "fout", ".", "write", "(", "line", ")", "(", "data", ",", "times", ")", "=", "raw", "[", ":", "]", "with", "open", "(", "ascii_vhdr_path", ".", "replace", "(", "'.vhdr'", ",", "'.dat'", ")", ",", "'wb'", ")", "as", "fid", ":", "fid", ".", "write", "(", "(", "' '", ".", "join", "(", "(", "ch_name", ".", "encode", "(", "'ASCII'", ")", "for", "ch_name", "in", "raw", ".", "ch_names", ")", ")", "+", "'\\n'", ")", ")", "fid", ".", "write", "(", "'\\n'", ".", "join", "(", "(", "' '", ".", "join", "(", "(", "(", "'%.3f'", "%", "dd", ")", "for", "dd", "in", "d", ")", ")", "for", "d", "in", "(", "data", "[", ":", "(", "-", "1", ")", "]", ".", "T", "/", "raw", ".", "_cals", "[", ":", "(", "-", "1", ")", "]", ")", ")", ")", ")", "raw", "=", "read_raw_brainvision", "(", "ascii_vhdr_path", ",", "event_id", "=", "event_id", ")", "(", "data_new", ",", "times_new", ")", "=", "raw", "[", ":", "]", "assert_allclose", "(", "data_new", ",", "data", ",", "atol", "=", "1e-15", ")", "assert_allclose", "(", "times_new", ",", "times", ")" ]
test an ascii-only string .
train
false
15,556
def create_issue(**kwargs): owner = kwargs.pop('owner', None) if (owner is None): owner = UserFactory.create() project = kwargs.pop('project', None) if (project is None): project = ProjectFactory.create(owner=owner) defaults = {'project': project, 'owner': owner, 'status': IssueStatusFactory.create(project=project), 'milestone': MilestoneFactory.create(project=project), 'priority': PriorityFactory.create(project=project), 'severity': SeverityFactory.create(project=project), 'type': IssueTypeFactory.create(project=project)} defaults.update(kwargs) return IssueFactory.create(**defaults)
[ "def", "create_issue", "(", "**", "kwargs", ")", ":", "owner", "=", "kwargs", ".", "pop", "(", "'owner'", ",", "None", ")", "if", "(", "owner", "is", "None", ")", ":", "owner", "=", "UserFactory", ".", "create", "(", ")", "project", "=", "kwargs", ".", "pop", "(", "'project'", ",", "None", ")", "if", "(", "project", "is", "None", ")", ":", "project", "=", "ProjectFactory", ".", "create", "(", "owner", "=", "owner", ")", "defaults", "=", "{", "'project'", ":", "project", ",", "'owner'", ":", "owner", ",", "'status'", ":", "IssueStatusFactory", ".", "create", "(", "project", "=", "project", ")", ",", "'milestone'", ":", "MilestoneFactory", ".", "create", "(", "project", "=", "project", ")", ",", "'priority'", ":", "PriorityFactory", ".", "create", "(", "project", "=", "project", ")", ",", "'severity'", ":", "SeverityFactory", ".", "create", "(", "project", "=", "project", ")", ",", "'type'", ":", "IssueTypeFactory", ".", "create", "(", "project", "=", "project", ")", "}", "defaults", ".", "update", "(", "kwargs", ")", "return", "IssueFactory", ".", "create", "(", "**", "defaults", ")" ]
create an issue and along with its dependencies .
train
false
15,557
def extract_rfc2822_addresses(text): if (not text): return [] candidates = address_pattern.findall(ustr(text).encode('utf-8')) return filter(try_coerce_ascii, candidates)
[ "def", "extract_rfc2822_addresses", "(", "text", ")", ":", "if", "(", "not", "text", ")", ":", "return", "[", "]", "candidates", "=", "address_pattern", ".", "findall", "(", "ustr", "(", "text", ")", ".", "encode", "(", "'utf-8'", ")", ")", "return", "filter", "(", "try_coerce_ascii", ",", "candidates", ")" ]
returns a list of valid rfc2822 addresses that can be found in source .
train
false
15,559
def sanitise_redirect_url(redirect_to): is_valid = True if ((not redirect_to) or (' ' in redirect_to)): is_valid = False elif ('//' in redirect_to): allowed_domains = getattr(settings, 'ALLOWED_EXTERNAL_OPENID_REDIRECT_DOMAINS', []) (s, netloc, p, q, f) = urlsplit(redirect_to) if netloc: if (netloc.find(':') != (-1)): (netloc, _) = netloc.split(':', 1) if (netloc not in allowed_domains): is_valid = False if (not is_valid): redirect_to = settings.LOGIN_REDIRECT_URL return redirect_to
[ "def", "sanitise_redirect_url", "(", "redirect_to", ")", ":", "is_valid", "=", "True", "if", "(", "(", "not", "redirect_to", ")", "or", "(", "' '", "in", "redirect_to", ")", ")", ":", "is_valid", "=", "False", "elif", "(", "'//'", "in", "redirect_to", ")", ":", "allowed_domains", "=", "getattr", "(", "settings", ",", "'ALLOWED_EXTERNAL_OPENID_REDIRECT_DOMAINS'", ",", "[", "]", ")", "(", "s", ",", "netloc", ",", "p", ",", "q", ",", "f", ")", "=", "urlsplit", "(", "redirect_to", ")", "if", "netloc", ":", "if", "(", "netloc", ".", "find", "(", "':'", ")", "!=", "(", "-", "1", ")", ")", ":", "(", "netloc", ",", "_", ")", "=", "netloc", ".", "split", "(", "':'", ",", "1", ")", "if", "(", "netloc", "not", "in", "allowed_domains", ")", ":", "is_valid", "=", "False", "if", "(", "not", "is_valid", ")", ":", "redirect_to", "=", "settings", ".", "LOGIN_REDIRECT_URL", "return", "redirect_to" ]
sanitise the redirection url .
train
false
15,561
def task_create_flocker_pool_file(): return sequence([run('mkdir -p /var/opt/flocker'), run('truncate --size 10G /var/opt/flocker/pool-vdev'), run('ZFS_MODULE_LOADING=yes zpool create flocker /var/opt/flocker/pool-vdev')])
[ "def", "task_create_flocker_pool_file", "(", ")", ":", "return", "sequence", "(", "[", "run", "(", "'mkdir -p /var/opt/flocker'", ")", ",", "run", "(", "'truncate --size 10G /var/opt/flocker/pool-vdev'", ")", ",", "run", "(", "'ZFS_MODULE_LOADING=yes zpool create flocker /var/opt/flocker/pool-vdev'", ")", "]", ")" ]
create a file-back zfs pool for flocker .
train
false
15,562
def send_arp_reply(reply_to, mac, src_mac=None, src_ip=None): arpp = reply_to.parsed.find('arp') mac = EthAddr(mac) if (src_mac is None): src_mac = reply_to.connection.eth_addr elif (src_mac is True): src_mac = reply_to.connection.ports[reply_to.port].hw_addr else: src_mac = EthAddr(src_mac) r = arp() r.opcode = r.REPLY r.hwdst = arpp.hwsrc r.protodst = arpp.protosrc r.hwsrc = EthAddr(src_mac) r.protosrc = (IPAddr('0.0.0.0') if (src_ip is None) else IPAddr(src_ip)) e = ethernet(type=ethernet.ARP_TYPE, src=src_mac, dst=r.hwdst) e.payload = r msg = of.ofp_packet_out() msg.data = e.pack() msg.actions.append(of.ofp_action_output(port=reply_to.port)) msg.in_port = of.OFPP_NONE reply_to.connection.send(msg)
[ "def", "send_arp_reply", "(", "reply_to", ",", "mac", ",", "src_mac", "=", "None", ",", "src_ip", "=", "None", ")", ":", "arpp", "=", "reply_to", ".", "parsed", ".", "find", "(", "'arp'", ")", "mac", "=", "EthAddr", "(", "mac", ")", "if", "(", "src_mac", "is", "None", ")", ":", "src_mac", "=", "reply_to", ".", "connection", ".", "eth_addr", "elif", "(", "src_mac", "is", "True", ")", ":", "src_mac", "=", "reply_to", ".", "connection", ".", "ports", "[", "reply_to", ".", "port", "]", ".", "hw_addr", "else", ":", "src_mac", "=", "EthAddr", "(", "src_mac", ")", "r", "=", "arp", "(", ")", "r", ".", "opcode", "=", "r", ".", "REPLY", "r", ".", "hwdst", "=", "arpp", ".", "hwsrc", "r", ".", "protodst", "=", "arpp", ".", "protosrc", "r", ".", "hwsrc", "=", "EthAddr", "(", "src_mac", ")", "r", ".", "protosrc", "=", "(", "IPAddr", "(", "'0.0.0.0'", ")", "if", "(", "src_ip", "is", "None", ")", "else", "IPAddr", "(", "src_ip", ")", ")", "e", "=", "ethernet", "(", "type", "=", "ethernet", ".", "ARP_TYPE", ",", "src", "=", "src_mac", ",", "dst", "=", "r", ".", "hwdst", ")", "e", ".", "payload", "=", "r", "msg", "=", "of", ".", "ofp_packet_out", "(", ")", "msg", ".", "data", "=", "e", ".", "pack", "(", ")", "msg", ".", "actions", ".", "append", "(", "of", ".", "ofp_action_output", "(", "port", "=", "reply_to", ".", "port", ")", ")", "msg", ".", "in_port", "=", "of", ".", "OFPP_NONE", "reply_to", ".", "connection", ".", "send", "(", "msg", ")" ]
send an arp reply .
train
false
15,564
def display_timestamps_pair_compact(time_m_2): if (len(time_m_2) == 0): return '(empty)' time_m_2 = np.array(time_m_2) low = time_m_2[:, 0].mean() high = time_m_2[:, 1].mean() low = max(low, 0) if (high < 0): logger.warn('Harmless warning: upper-bound on clock skew is negative: (%s, %s). Please let Greg know about this.', low, high) return '{}-{}'.format(display_timestamp(low), display_timestamp(high))
[ "def", "display_timestamps_pair_compact", "(", "time_m_2", ")", ":", "if", "(", "len", "(", "time_m_2", ")", "==", "0", ")", ":", "return", "'(empty)'", "time_m_2", "=", "np", ".", "array", "(", "time_m_2", ")", "low", "=", "time_m_2", "[", ":", ",", "0", "]", ".", "mean", "(", ")", "high", "=", "time_m_2", "[", ":", ",", "1", "]", ".", "mean", "(", ")", "low", "=", "max", "(", "low", ",", "0", ")", "if", "(", "high", "<", "0", ")", ":", "logger", ".", "warn", "(", "'Harmless warning: upper-bound on clock skew is negative: (%s, %s). Please let Greg know about this.'", ",", "low", ",", "high", ")", "return", "'{}-{}'", ".", "format", "(", "display_timestamp", "(", "low", ")", ",", "display_timestamp", "(", "high", ")", ")" ]
takes a list of the following form: [ .
train
true
15,565
def parselinenos(spec, total): items = list() parts = spec.split(',') for part in parts: try: begend = part.strip().split('-') if (len(begend) > 2): raise ValueError if (len(begend) == 1): items.append((int(begend[0]) - 1)) else: start = (((begend[0] == '') and 0) or (int(begend[0]) - 1)) end = (((begend[1] == '') and total) or int(begend[1])) items.extend(xrange(start, end)) except Exception: raise ValueError(('invalid line number spec: %r' % spec)) return items
[ "def", "parselinenos", "(", "spec", ",", "total", ")", ":", "items", "=", "list", "(", ")", "parts", "=", "spec", ".", "split", "(", "','", ")", "for", "part", "in", "parts", ":", "try", ":", "begend", "=", "part", ".", "strip", "(", ")", ".", "split", "(", "'-'", ")", "if", "(", "len", "(", "begend", ")", ">", "2", ")", ":", "raise", "ValueError", "if", "(", "len", "(", "begend", ")", "==", "1", ")", ":", "items", ".", "append", "(", "(", "int", "(", "begend", "[", "0", "]", ")", "-", "1", ")", ")", "else", ":", "start", "=", "(", "(", "(", "begend", "[", "0", "]", "==", "''", ")", "and", "0", ")", "or", "(", "int", "(", "begend", "[", "0", "]", ")", "-", "1", ")", ")", "end", "=", "(", "(", "(", "begend", "[", "1", "]", "==", "''", ")", "and", "total", ")", "or", "int", "(", "begend", "[", "1", "]", ")", ")", "items", ".", "extend", "(", "xrange", "(", "start", ",", "end", ")", ")", "except", "Exception", ":", "raise", "ValueError", "(", "(", "'invalid line number spec: %r'", "%", "spec", ")", ")", "return", "items" ]
parse a line number spec and return a list of wanted line numbers .
train
false
15,566
def mackinnonp(teststat, regression='c', N=1, lags=None): maxstat = eval(('tau_max_' + regression)) minstat = eval(('tau_min_' + regression)) starstat = eval(('tau_star_' + regression)) if (teststat > maxstat[(N - 1)]): return 1.0 elif (teststat < minstat[(N - 1)]): return 0.0 if (teststat <= starstat[(N - 1)]): tau_coef = eval((((('tau_' + regression) + '_smallp[') + str((N - 1))) + ']')) else: tau_coef = eval((((('tau_' + regression) + '_largep[') + str((N - 1))) + ']')) return norm.cdf(polyval(tau_coef[::(-1)], teststat))
[ "def", "mackinnonp", "(", "teststat", ",", "regression", "=", "'c'", ",", "N", "=", "1", ",", "lags", "=", "None", ")", ":", "maxstat", "=", "eval", "(", "(", "'tau_max_'", "+", "regression", ")", ")", "minstat", "=", "eval", "(", "(", "'tau_min_'", "+", "regression", ")", ")", "starstat", "=", "eval", "(", "(", "'tau_star_'", "+", "regression", ")", ")", "if", "(", "teststat", ">", "maxstat", "[", "(", "N", "-", "1", ")", "]", ")", ":", "return", "1.0", "elif", "(", "teststat", "<", "minstat", "[", "(", "N", "-", "1", ")", "]", ")", ":", "return", "0.0", "if", "(", "teststat", "<=", "starstat", "[", "(", "N", "-", "1", ")", "]", ")", ":", "tau_coef", "=", "eval", "(", "(", "(", "(", "(", "'tau_'", "+", "regression", ")", "+", "'_smallp['", ")", "+", "str", "(", "(", "N", "-", "1", ")", ")", ")", "+", "']'", ")", ")", "else", ":", "tau_coef", "=", "eval", "(", "(", "(", "(", "(", "'tau_'", "+", "regression", ")", "+", "'_largep['", ")", "+", "str", "(", "(", "N", "-", "1", ")", ")", ")", "+", "']'", ")", ")", "return", "norm", ".", "cdf", "(", "polyval", "(", "tau_coef", "[", ":", ":", "(", "-", "1", ")", "]", ",", "teststat", ")", ")" ]
returns mackinnons approximate p-value for teststat .
train
false
15,567
def reap_children(recursive=False): if recursive: children = psutil.Process().children(recursive=True) else: children = [] subprocs = _subprocesses_started.copy() _subprocesses_started.clear() for subp in subprocs: try: subp.terminate() except OSError as err: if (err.errno != errno.ESRCH): raise if subp.stdout: subp.stdout.close() if subp.stderr: subp.stderr.close() try: if subp.stdin: subp.stdin.close() finally: try: subp.wait() except OSError as err: if (err.errno != errno.ECHILD): raise if children: for p in children: try: p.terminate() except psutil.NoSuchProcess: pass (gone, alive) = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT) for p in alive: warn(("couldn't terminate process %r; attempting kill()" % p)) try: p.kill() except psutil.NoSuchProcess: pass (_, alive) = psutil.wait_procs(alive, timeout=GLOBAL_TIMEOUT) if alive: for p in alive: warn(('process %r survived kill()' % p))
[ "def", "reap_children", "(", "recursive", "=", "False", ")", ":", "if", "recursive", ":", "children", "=", "psutil", ".", "Process", "(", ")", ".", "children", "(", "recursive", "=", "True", ")", "else", ":", "children", "=", "[", "]", "subprocs", "=", "_subprocesses_started", ".", "copy", "(", ")", "_subprocesses_started", ".", "clear", "(", ")", "for", "subp", "in", "subprocs", ":", "try", ":", "subp", ".", "terminate", "(", ")", "except", "OSError", "as", "err", ":", "if", "(", "err", ".", "errno", "!=", "errno", ".", "ESRCH", ")", ":", "raise", "if", "subp", ".", "stdout", ":", "subp", ".", "stdout", ".", "close", "(", ")", "if", "subp", ".", "stderr", ":", "subp", ".", "stderr", ".", "close", "(", ")", "try", ":", "if", "subp", ".", "stdin", ":", "subp", ".", "stdin", ".", "close", "(", ")", "finally", ":", "try", ":", "subp", ".", "wait", "(", ")", "except", "OSError", "as", "err", ":", "if", "(", "err", ".", "errno", "!=", "errno", ".", "ECHILD", ")", ":", "raise", "if", "children", ":", "for", "p", "in", "children", ":", "try", ":", "p", ".", "terminate", "(", ")", "except", "psutil", ".", "NoSuchProcess", ":", "pass", "(", "gone", ",", "alive", ")", "=", "psutil", ".", "wait_procs", "(", "children", ",", "timeout", "=", "GLOBAL_TIMEOUT", ")", "for", "p", "in", "alive", ":", "warn", "(", "(", "\"couldn't terminate process %r; attempting kill()\"", "%", "p", ")", ")", "try", ":", "p", ".", "kill", "(", ")", "except", "psutil", ".", "NoSuchProcess", ":", "pass", "(", "_", ",", "alive", ")", "=", "psutil", ".", "wait_procs", "(", "alive", ",", "timeout", "=", "GLOBAL_TIMEOUT", ")", "if", "alive", ":", "for", "p", "in", "alive", ":", "warn", "(", "(", "'process %r survived kill()'", "%", "p", ")", ")" ]
when a child process dies .
train
false
15,569
@_docstring('labels', browse=True) def browse_labels(release=None, includes=[], limit=None, offset=None): valid_includes = VALID_BROWSE_INCLUDES['labels'] params = {'release': release} return _browse_impl('label', includes, valid_includes, limit, offset, params)
[ "@", "_docstring", "(", "'labels'", ",", "browse", "=", "True", ")", "def", "browse_labels", "(", "release", "=", "None", ",", "includes", "=", "[", "]", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "valid_includes", "=", "VALID_BROWSE_INCLUDES", "[", "'labels'", "]", "params", "=", "{", "'release'", ":", "release", "}", "return", "_browse_impl", "(", "'label'", ",", "includes", ",", "valid_includes", ",", "limit", ",", "offset", ",", "params", ")" ]
get all labels linked to a relase .
train
false
15,570
def migration_get_in_progress_by_instance(context, instance_uuid, migration_type=None): return IMPL.migration_get_in_progress_by_instance(context, instance_uuid, migration_type)
[ "def", "migration_get_in_progress_by_instance", "(", "context", ",", "instance_uuid", ",", "migration_type", "=", "None", ")", ":", "return", "IMPL", ".", "migration_get_in_progress_by_instance", "(", "context", ",", "instance_uuid", ",", "migration_type", ")" ]
finds all migrations of an instance in progress .
train
false
15,572
def _get_profile(self): if (not hasattr(self, u'_profile')): self._profile = Profile.objects.get_or_create(user=self)[0] self._profile.user = self if (self._profile.extra_data is None): self._profile.extra_data = {} return self._profile
[ "def", "_get_profile", "(", "self", ")", ":", "if", "(", "not", "hasattr", "(", "self", ",", "u'_profile'", ")", ")", ":", "self", ".", "_profile", "=", "Profile", ".", "objects", ".", "get_or_create", "(", "user", "=", "self", ")", "[", "0", "]", "self", ".", "_profile", ".", "user", "=", "self", "if", "(", "self", ".", "_profile", ".", "extra_data", "is", "None", ")", ":", "self", ".", "_profile", ".", "extra_data", "=", "{", "}", "return", "self", ".", "_profile" ]
get the profile for the user .
train
false
15,573
def run_all_local(): file_name = os.path.join(os.path.dirname(__file__), 'resources/wakeupcat.jpg') detect_labels(file_name) file_name = os.path.join(os.path.dirname(__file__), 'resources/landmark.jpg') detect_landmarks(file_name) file_name = os.path.join(os.path.dirname(__file__), 'resources/face_no_surprise.jpg') detect_faces(file_name) file_name = os.path.join(os.path.dirname(__file__), 'resources/logos.png') detect_logos(file_name) file_name = os.path.join(os.path.dirname(__file__), 'resources/wakeupcat.jpg') detect_safe_search(file_name) " TODO: Uncomment when https://goo.gl/c47YwV is fixed\n file_name = os.path.join(\n os.path.dirname(__file__),\n 'resources/text.jpg')\n detect_text(file_name)\n " file_name = os.path.join(os.path.dirname(__file__), 'resources/landmark.jpg') detect_properties(file_name)
[ "def", "run_all_local", "(", ")", ":", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'resources/wakeupcat.jpg'", ")", "detect_labels", "(", "file_name", ")", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'resources/landmark.jpg'", ")", "detect_landmarks", "(", "file_name", ")", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'resources/face_no_surprise.jpg'", ")", "detect_faces", "(", "file_name", ")", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'resources/logos.png'", ")", "detect_logos", "(", "file_name", ")", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'resources/wakeupcat.jpg'", ")", "detect_safe_search", "(", "file_name", ")", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'resources/landmark.jpg'", ")", "detect_properties", "(", "file_name", ")" ]
runs all available detection operations on the local resources .
train
false
15,575
def IsStrCanonicalInt(string): if (type(string) is str): if string: if (string == '0'): return True if (string[0] == '-'): string = string[1:] if (not string): return False if ('1' <= string[0] <= '9'): return string.isdigit() return False
[ "def", "IsStrCanonicalInt", "(", "string", ")", ":", "if", "(", "type", "(", "string", ")", "is", "str", ")", ":", "if", "string", ":", "if", "(", "string", "==", "'0'", ")", ":", "return", "True", "if", "(", "string", "[", "0", "]", "==", "'-'", ")", ":", "string", "=", "string", "[", "1", ":", "]", "if", "(", "not", "string", ")", ":", "return", "False", "if", "(", "'1'", "<=", "string", "[", "0", "]", "<=", "'9'", ")", ":", "return", "string", ".", "isdigit", "(", ")", "return", "False" ]
returns true if |string| is in its canonical integer form .
train
false
15,576
def swap_xapi_host(url, host_addr): temp_url = urlparse.urlparse(url) temp_netloc = temp_url.netloc.replace(temp_url.hostname, ('%s' % host_addr)) replaced = temp_url._replace(netloc=temp_netloc) return urlparse.urlunparse(replaced)
[ "def", "swap_xapi_host", "(", "url", ",", "host_addr", ")", ":", "temp_url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "temp_netloc", "=", "temp_url", ".", "netloc", ".", "replace", "(", "temp_url", ".", "hostname", ",", "(", "'%s'", "%", "host_addr", ")", ")", "replaced", "=", "temp_url", ".", "_replace", "(", "netloc", "=", "temp_netloc", ")", "return", "urlparse", ".", "urlunparse", "(", "replaced", ")" ]
replace the xenserver address present in url with host_addr .
train
false
15,577
def _label2rgb_avg(label_field, image, bg_label=0, bg_color=(0, 0, 0)): out = np.zeros_like(image) labels = np.unique(label_field) bg = (labels == bg_label) if bg.any(): labels = labels[(labels != bg_label)] out[bg] = bg_color for label in labels: mask = (label_field == label).nonzero() color = image[mask].mean(axis=0) out[mask] = color return out
[ "def", "_label2rgb_avg", "(", "label_field", ",", "image", ",", "bg_label", "=", "0", ",", "bg_color", "=", "(", "0", ",", "0", ",", "0", ")", ")", ":", "out", "=", "np", ".", "zeros_like", "(", "image", ")", "labels", "=", "np", ".", "unique", "(", "label_field", ")", "bg", "=", "(", "labels", "==", "bg_label", ")", "if", "bg", ".", "any", "(", ")", ":", "labels", "=", "labels", "[", "(", "labels", "!=", "bg_label", ")", "]", "out", "[", "bg", "]", "=", "bg_color", "for", "label", "in", "labels", ":", "mask", "=", "(", "label_field", "==", "label", ")", ".", "nonzero", "(", ")", "color", "=", "image", "[", "mask", "]", ".", "mean", "(", "axis", "=", "0", ")", "out", "[", "mask", "]", "=", "color", "return", "out" ]
visualise each segment in label_field with its mean color in image .
train
false
15,579
@pytest.fixture def templates_project0(request, templates, project0): from pootle_translationproject.models import TranslationProject return TranslationProject.objects.get(language=templates, project=project0)
[ "@", "pytest", ".", "fixture", "def", "templates_project0", "(", "request", ",", "templates", ",", "project0", ")", ":", "from", "pootle_translationproject", ".", "models", "import", "TranslationProject", "return", "TranslationProject", ".", "objects", ".", "get", "(", "language", "=", "templates", ",", "project", "=", "project0", ")" ]
require the templates/project0/ translation project .
train
false
15,580
def _isLeft(a, b, c): return ((((b[0] - a[0]) * (c[1] - a[1])) - ((b[1] - a[1]) * (c[0] - a[0]))) > 0)
[ "def", "_isLeft", "(", "a", ",", "b", ",", "c", ")", ":", "return", "(", "(", "(", "(", "b", "[", "0", "]", "-", "a", "[", "0", "]", ")", "*", "(", "c", "[", "1", "]", "-", "a", "[", "1", "]", ")", ")", "-", "(", "(", "b", "[", "1", "]", "-", "a", "[", "1", "]", ")", "*", "(", "c", "[", "0", "]", "-", "a", "[", "0", "]", ")", ")", ")", ">", "0", ")" ]
check if c is left of the infinite line from a to b .
train
false
15,581
def delete_share_doc(node, wname): db = share_db() sharejs_uuid = get_sharejs_uuid(node, wname) db['docs'].remove({'_id': sharejs_uuid}) db['docs_ops'].remove({'name': sharejs_uuid}) wiki_key = to_mongo_key(wname) del node.wiki_private_uuids[wiki_key] node.save()
[ "def", "delete_share_doc", "(", "node", ",", "wname", ")", ":", "db", "=", "share_db", "(", ")", "sharejs_uuid", "=", "get_sharejs_uuid", "(", "node", ",", "wname", ")", "db", "[", "'docs'", "]", ".", "remove", "(", "{", "'_id'", ":", "sharejs_uuid", "}", ")", "db", "[", "'docs_ops'", "]", ".", "remove", "(", "{", "'name'", ":", "sharejs_uuid", "}", ")", "wiki_key", "=", "to_mongo_key", "(", "wname", ")", "del", "node", ".", "wiki_private_uuids", "[", "wiki_key", "]", "node", ".", "save", "(", ")" ]
deletes share document and removes namespace from model .
train
false
15,582
def missing_newline(physical_line): if (physical_line.rstrip() == physical_line): return (len(physical_line), 'W292 no newline at end of file')
[ "def", "missing_newline", "(", "physical_line", ")", ":", "if", "(", "physical_line", ".", "rstrip", "(", ")", "==", "physical_line", ")", ":", "return", "(", "len", "(", "physical_line", ")", ",", "'W292 no newline at end of file'", ")" ]
jcr: the last line should have a newline .
train
false
15,583
def readWavFile(filename): try: (sampleRate, data) = wavfile.read(filename) except Exception: if (os.path.exists(filename) and os.path.isfile(filename)): core.wait(0.01, 0) try: (sampleRate, data) = wavfile.read(filename) except Exception: msg = 'Failed to open wav sound file "%s"' raise SoundFileError((msg % filename)) if (data.dtype != 'int16'): msg = 'expected `int16` data in .wav file %s' raise AttributeError((msg % filename)) if ((len(data.shape) == 2) and (data.shape[1] == 2)): data = data.transpose() data = data[0] return (data, sampleRate)
[ "def", "readWavFile", "(", "filename", ")", ":", "try", ":", "(", "sampleRate", ",", "data", ")", "=", "wavfile", ".", "read", "(", "filename", ")", "except", "Exception", ":", "if", "(", "os", ".", "path", ".", "exists", "(", "filename", ")", "and", "os", ".", "path", ".", "isfile", "(", "filename", ")", ")", ":", "core", ".", "wait", "(", "0.01", ",", "0", ")", "try", ":", "(", "sampleRate", ",", "data", ")", "=", "wavfile", ".", "read", "(", "filename", ")", "except", "Exception", ":", "msg", "=", "'Failed to open wav sound file \"%s\"'", "raise", "SoundFileError", "(", "(", "msg", "%", "filename", ")", ")", "if", "(", "data", ".", "dtype", "!=", "'int16'", ")", ":", "msg", "=", "'expected `int16` data in .wav file %s'", "raise", "AttributeError", "(", "(", "msg", "%", "filename", ")", ")", "if", "(", "(", "len", "(", "data", ".", "shape", ")", "==", "2", ")", "and", "(", "data", ".", "shape", "[", "1", "]", "==", "2", ")", ")", ":", "data", "=", "data", ".", "transpose", "(", ")", "data", "=", "data", "[", "0", "]", "return", "(", "data", ",", "sampleRate", ")" ]
return as read from a wav file .
train
false
15,585
def get_last_line(txt): lines = txt.split('\n') n = (len(lines) - 1) while ((n >= 0) and (not lines[n].strip('\r DCTB '))): n = (n - 1) line = lines[n].strip('\r DCTB ') if (len(line) >= 150): line = (line[:147] + '...') return line
[ "def", "get_last_line", "(", "txt", ")", ":", "lines", "=", "txt", ".", "split", "(", "'\\n'", ")", "n", "=", "(", "len", "(", "lines", ")", "-", "1", ")", "while", "(", "(", "n", ">=", "0", ")", "and", "(", "not", "lines", "[", "n", "]", ".", "strip", "(", "'\\r DCTB '", ")", ")", ")", ":", "n", "=", "(", "n", "-", "1", ")", "line", "=", "lines", "[", "n", "]", ".", "strip", "(", "'\\r DCTB '", ")", "if", "(", "len", "(", "line", ")", ">=", "150", ")", ":", "line", "=", "(", "line", "[", ":", "147", "]", "+", "'...'", ")", "return", "line" ]
return last non-empty line of a text .
train
false
15,586
@frappe.whitelist() def get_desk_assets(build_version): data = get_context({u'for_mobile': True}) assets = [{u'type': u'js', u'data': u''}, {u'type': u'css', u'data': u''}] if (build_version != data[u'build_version']): for path in data[u'include_js']: with open(os.path.join(frappe.local.sites_path, path), u'r') as f: assets[0][u'data'] = ((assets[0][u'data'] + u'\n') + unicode(f.read(), u'utf-8')) for path in data[u'include_css']: with open(os.path.join(frappe.local.sites_path, path), u'r') as f: assets[1][u'data'] = ((assets[1][u'data'] + u'\n') + unicode(f.read(), u'utf-8')) return {u'build_version': data[u'build_version'], u'boot': data[u'boot'], u'assets': assets}
[ "@", "frappe", ".", "whitelist", "(", ")", "def", "get_desk_assets", "(", "build_version", ")", ":", "data", "=", "get_context", "(", "{", "u'for_mobile'", ":", "True", "}", ")", "assets", "=", "[", "{", "u'type'", ":", "u'js'", ",", "u'data'", ":", "u''", "}", ",", "{", "u'type'", ":", "u'css'", ",", "u'data'", ":", "u''", "}", "]", "if", "(", "build_version", "!=", "data", "[", "u'build_version'", "]", ")", ":", "for", "path", "in", "data", "[", "u'include_js'", "]", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "frappe", ".", "local", ".", "sites_path", ",", "path", ")", ",", "u'r'", ")", "as", "f", ":", "assets", "[", "0", "]", "[", "u'data'", "]", "=", "(", "(", "assets", "[", "0", "]", "[", "u'data'", "]", "+", "u'\\n'", ")", "+", "unicode", "(", "f", ".", "read", "(", ")", ",", "u'utf-8'", ")", ")", "for", "path", "in", "data", "[", "u'include_css'", "]", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "frappe", ".", "local", ".", "sites_path", ",", "path", ")", ",", "u'r'", ")", "as", "f", ":", "assets", "[", "1", "]", "[", "u'data'", "]", "=", "(", "(", "assets", "[", "1", "]", "[", "u'data'", "]", "+", "u'\\n'", ")", "+", "unicode", "(", "f", ".", "read", "(", ")", ",", "u'utf-8'", ")", ")", "return", "{", "u'build_version'", ":", "data", "[", "u'build_version'", "]", ",", "u'boot'", ":", "data", "[", "u'boot'", "]", ",", "u'assets'", ":", "assets", "}" ]
get desk assets to be loaded for mobile app .
train
false
15,587
def items_to_report_element(items, item_type): n = len(items) text = pluralize(n, item_type) if (n == 0): return text else: detail = u'\n'.join((str(x) for x in items)) return (text, detail)
[ "def", "items_to_report_element", "(", "items", ",", "item_type", ")", ":", "n", "=", "len", "(", "items", ")", "text", "=", "pluralize", "(", "n", ",", "item_type", ")", "if", "(", "n", "==", "0", ")", ":", "return", "text", "else", ":", "detail", "=", "u'\\n'", ".", "join", "(", "(", "str", "(", "x", ")", "for", "x", "in", "items", ")", ")", "return", "(", "text", ",", "detail", ")" ]
converts an iterable of items to a pair .
train
true
15,590
def check_service_url_with_proxy_campaign(service_url, campaign_url): regex = ((('^' + settings.DOMAIN) + 'login/?\\?next=') + campaign_url) return re.match(regex, service_url)
[ "def", "check_service_url_with_proxy_campaign", "(", "service_url", ",", "campaign_url", ")", ":", "regex", "=", "(", "(", "(", "'^'", "+", "settings", ".", "DOMAIN", ")", "+", "'login/?\\\\?next='", ")", "+", "campaign_url", ")", "return", "re", ".", "match", "(", "regex", ",", "service_url", ")" ]
check if service url belongs to proxy campaigns: osf preprints and branded ones .
train
false
15,591
def get_bin_seeds(X, bin_size, min_bin_freq=1): bin_sizes = defaultdict(int) for point in X: binned_point = np.round((point / bin_size)) bin_sizes[tuple(binned_point)] += 1 bin_seeds = np.array([point for (point, freq) in six.iteritems(bin_sizes) if (freq >= min_bin_freq)], dtype=np.float32) if (len(bin_seeds) == len(X)): warnings.warn(('Binning data failed with provided bin_size=%f, using data points as seeds.' % bin_size)) return X bin_seeds = (bin_seeds * bin_size) return bin_seeds
[ "def", "get_bin_seeds", "(", "X", ",", "bin_size", ",", "min_bin_freq", "=", "1", ")", ":", "bin_sizes", "=", "defaultdict", "(", "int", ")", "for", "point", "in", "X", ":", "binned_point", "=", "np", ".", "round", "(", "(", "point", "/", "bin_size", ")", ")", "bin_sizes", "[", "tuple", "(", "binned_point", ")", "]", "+=", "1", "bin_seeds", "=", "np", ".", "array", "(", "[", "point", "for", "(", "point", ",", "freq", ")", "in", "six", ".", "iteritems", "(", "bin_sizes", ")", "if", "(", "freq", ">=", "min_bin_freq", ")", "]", ",", "dtype", "=", "np", ".", "float32", ")", "if", "(", "len", "(", "bin_seeds", ")", "==", "len", "(", "X", ")", ")", ":", "warnings", ".", "warn", "(", "(", "'Binning data failed with provided bin_size=%f, using data points as seeds.'", "%", "bin_size", ")", ")", "return", "X", "bin_seeds", "=", "(", "bin_seeds", "*", "bin_size", ")", "return", "bin_seeds" ]
finds seeds for mean_shift .
train
false