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
24,574
@contextmanager def flock(lockfile, shared=False): fcntl.flock(lockfile, (fcntl.LOCK_SH if shared else fcntl.LOCK_EX)) try: (yield) finally: fcntl.flock(lockfile, fcntl.LOCK_UN)
[ "@", "contextmanager", "def", "flock", "(", "lockfile", ",", "shared", "=", "False", ")", ":", "fcntl", ".", "flock", "(", "lockfile", ",", "(", "fcntl", ".", "LOCK_SH", "if", "shared", "else", "fcntl", ".", "LOCK_EX", ")", ")", "try", ":", "(", "yield", ")", "finally", ":", "fcntl", ".", "flock", "(", "lockfile", ",", "fcntl", ".", "LOCK_UN", ")" ]
lock a file object using flock(2) for the duration of a with statement .
train
false
24,575
def parse_rarefaction(lines): col_headers = [] comments = [] rarefaction_data = [] rarefaction_fns = [] for line in lines: if (line[0] == '#'): comments.append(line) elif (line[0] == ' DCTB '): col_headers = map(strip, line.split(' DCTB ')) else: (rarefaction_fn, data) = parse_rarefaction_record(line) rarefaction_fns.append(rarefaction_fn) rarefaction_data.append(data) return (col_headers, comments, rarefaction_fns, rarefaction_data)
[ "def", "parse_rarefaction", "(", "lines", ")", ":", "col_headers", "=", "[", "]", "comments", "=", "[", "]", "rarefaction_data", "=", "[", "]", "rarefaction_fns", "=", "[", "]", "for", "line", "in", "lines", ":", "if", "(", "line", "[", "0", "]", "==", "'#'", ")", ":", "comments", ".", "append", "(", "line", ")", "elif", "(", "line", "[", "0", "]", "==", "' DCTB '", ")", ":", "col_headers", "=", "map", "(", "strip", ",", "line", ".", "split", "(", "' DCTB '", ")", ")", "else", ":", "(", "rarefaction_fn", ",", "data", ")", "=", "parse_rarefaction_record", "(", "line", ")", "rarefaction_fns", ".", "append", "(", "rarefaction_fn", ")", "rarefaction_data", ".", "append", "(", "data", ")", "return", "(", "col_headers", ",", "comments", ",", "rarefaction_fns", ",", "rarefaction_data", ")" ]
function for parsing rarefaction files specifically for use in make_rarefaction_plots .
train
false
24,576
def _find_library(lib, path): for d in path[::(-1)]: real_lib = os.path.join(d, lib) if os.path.exists(real_lib): return real_lib
[ "def", "_find_library", "(", "lib", ",", "path", ")", ":", "for", "d", "in", "path", "[", ":", ":", "(", "-", "1", ")", "]", ":", "real_lib", "=", "os", ".", "path", ".", "join", "(", "d", ",", "lib", ")", "if", "os", ".", "path", ".", "exists", "(", "real_lib", ")", ":", "return", "real_lib" ]
find a library .
train
true
24,578
def _saferepr(obj): repr = py.io.saferepr(obj) if py.builtin._istext(repr): t = py.builtin.text else: t = py.builtin.bytes return repr.replace(t('\n'), t('\\n'))
[ "def", "_saferepr", "(", "obj", ")", ":", "repr", "=", "py", ".", "io", ".", "saferepr", "(", "obj", ")", "if", "py", ".", "builtin", ".", "_istext", "(", "repr", ")", ":", "t", "=", "py", ".", "builtin", ".", "text", "else", ":", "t", "=", "py", ".", "builtin", ".", "bytes", "return", "repr", ".", "replace", "(", "t", "(", "'\\n'", ")", ",", "t", "(", "'\\\\n'", ")", ")" ]
get a safe repr of an object for assertion error messages .
train
true
24,580
def batch_generator_old(data, target, BATCH_SIZE, shuffle=False): np.random.seed() idx = np.arange(data.shape[0]) if shuffle: np.random.shuffle(idx) idx_2 = np.array(idx) while (BATCH_SIZE > len(idx)): idx_2 = np.concatenate((idx_2, idx)) del idx while True: ctr = 0 (yield (np.array(data[idx_2[ctr:(ctr + BATCH_SIZE)]]), np.array(target[idx_2[ctr:(ctr + BATCH_SIZE)]]))) ctr += BATCH_SIZE if (ctr >= data.shape[0]): ctr -= data.shape[0]
[ "def", "batch_generator_old", "(", "data", ",", "target", ",", "BATCH_SIZE", ",", "shuffle", "=", "False", ")", ":", "np", ".", "random", ".", "seed", "(", ")", "idx", "=", "np", ".", "arange", "(", "data", ".", "shape", "[", "0", "]", ")", "if", "shuffle", ":", "np", ".", "random", ".", "shuffle", "(", "idx", ")", "idx_2", "=", "np", ".", "array", "(", "idx", ")", "while", "(", "BATCH_SIZE", ">", "len", "(", "idx", ")", ")", ":", "idx_2", "=", "np", ".", "concatenate", "(", "(", "idx_2", ",", "idx", ")", ")", "del", "idx", "while", "True", ":", "ctr", "=", "0", "(", "yield", "(", "np", ".", "array", "(", "data", "[", "idx_2", "[", "ctr", ":", "(", "ctr", "+", "BATCH_SIZE", ")", "]", "]", ")", ",", "np", ".", "array", "(", "target", "[", "idx_2", "[", "ctr", ":", "(", "ctr", "+", "BATCH_SIZE", ")", "]", "]", ")", ")", ")", "ctr", "+=", "BATCH_SIZE", "if", "(", "ctr", ">=", "data", ".", "shape", "[", "0", "]", ")", ":", "ctr", "-=", "data", ".", "shape", "[", "0", "]" ]
just a simple batch iterator .
train
false
24,581
def parse_gntp(data, password=None, debug=False): match = re.match('GNTP/(?P<version>\\d+\\.\\d+) (?P<messagetype>REGISTER|NOTIFY|SUBSCRIBE|\\-OK|\\-ERROR)', data, re.IGNORECASE) if (not match): if debug: print '----' print self.data print '----' raise ParseError('INVALID_GNTP_INFO') info = match.groupdict() if (info['messagetype'] == 'REGISTER'): return GNTPRegister(data, password=password) elif (info['messagetype'] == 'NOTIFY'): return GNTPNotice(data, password=password) elif (info['messagetype'] == 'SUBSCRIBE'): return GNTPSubscribe(data, password=password) elif (info['messagetype'] == '-OK'): return GNTPOK(data) elif (info['messagetype'] == '-ERROR'): return GNTPError(data) if debug: print info raise ParseError('INVALID_GNTP_MESSAGE')
[ "def", "parse_gntp", "(", "data", ",", "password", "=", "None", ",", "debug", "=", "False", ")", ":", "match", "=", "re", ".", "match", "(", "'GNTP/(?P<version>\\\\d+\\\\.\\\\d+) (?P<messagetype>REGISTER|NOTIFY|SUBSCRIBE|\\\\-OK|\\\\-ERROR)'", ",", "data", ",", "re", ".", "IGNORECASE", ")", "if", "(", "not", "match", ")", ":", "if", "debug", ":", "print", "'----'", "print", "self", ".", "data", "print", "'----'", "raise", "ParseError", "(", "'INVALID_GNTP_INFO'", ")", "info", "=", "match", ".", "groupdict", "(", ")", "if", "(", "info", "[", "'messagetype'", "]", "==", "'REGISTER'", ")", ":", "return", "GNTPRegister", "(", "data", ",", "password", "=", "password", ")", "elif", "(", "info", "[", "'messagetype'", "]", "==", "'NOTIFY'", ")", ":", "return", "GNTPNotice", "(", "data", ",", "password", "=", "password", ")", "elif", "(", "info", "[", "'messagetype'", "]", "==", "'SUBSCRIBE'", ")", ":", "return", "GNTPSubscribe", "(", "data", ",", "password", "=", "password", ")", "elif", "(", "info", "[", "'messagetype'", "]", "==", "'-OK'", ")", ":", "return", "GNTPOK", "(", "data", ")", "elif", "(", "info", "[", "'messagetype'", "]", "==", "'-ERROR'", ")", ":", "return", "GNTPError", "(", "data", ")", "if", "debug", ":", "print", "info", "raise", "ParseError", "(", "'INVALID_GNTP_MESSAGE'", ")" ]
attempt to parse a message as a gntp message .
train
false
24,588
def nltk_download_corpus(resource_path): from nltk.data import find from nltk import download from os.path import split (_, corpus_name) = split(resource_path) if (not resource_path.endswith('/')): resource_path = (resource_path + '/') downloaded = False try: find(resource_path) except LookupError: download(corpus_name) downloaded = True return downloaded
[ "def", "nltk_download_corpus", "(", "resource_path", ")", ":", "from", "nltk", ".", "data", "import", "find", "from", "nltk", "import", "download", "from", "os", ".", "path", "import", "split", "(", "_", ",", "corpus_name", ")", "=", "split", "(", "resource_path", ")", "if", "(", "not", "resource_path", ".", "endswith", "(", "'/'", ")", ")", ":", "resource_path", "=", "(", "resource_path", "+", "'/'", ")", "downloaded", "=", "False", "try", ":", "find", "(", "resource_path", ")", "except", "LookupError", ":", "download", "(", "corpus_name", ")", "downloaded", "=", "True", "return", "downloaded" ]
download the specified nltk corpus file unless it has already been downloaded .
train
false
24,589
def reset(): _runtime.reset()
[ "def", "reset", "(", ")", ":", "_runtime", ".", "reset", "(", ")" ]
clear the registry .
train
false
24,590
def _killBackref(receiver, senderkey): receiverkey = id(receiver) set = sendersBack.get(receiverkey, ()) while (senderkey in set): try: set.remove(senderkey) except: break if (not set): try: del sendersBack[receiverkey] except KeyError: pass return True
[ "def", "_killBackref", "(", "receiver", ",", "senderkey", ")", ":", "receiverkey", "=", "id", "(", "receiver", ")", "set", "=", "sendersBack", ".", "get", "(", "receiverkey", ",", "(", ")", ")", "while", "(", "senderkey", "in", "set", ")", ":", "try", ":", "set", ".", "remove", "(", "senderkey", ")", "except", ":", "break", "if", "(", "not", "set", ")", ":", "try", ":", "del", "sendersBack", "[", "receiverkey", "]", "except", "KeyError", ":", "pass", "return", "True" ]
do the actual removal of back reference from receiver to senderkey .
train
true
24,591
def _create_schedule(jsonf=None): day = ((60 * 60) * 24) if (jsonf is None): jsonf = _sched_json_file try: data = json.loads(open(jsonf).read()) except IOError: return OrderedDict() d = OrderedDict() for (gsis_id, info) in data.get('games', []): d[gsis_id] = info last_updated = datetime.datetime.utcfromtimestamp(data.get('time', 0)) if ((datetime.datetime.utcnow() - last_updated).total_seconds() >= day): if os.access(jsonf, os.W_OK): import nflgame.live import nflgame.update_sched (year, week) = nflgame.live.current_year_and_week() phase = nflgame.live._cur_season_phase nflgame.update_sched.update_week(d, year, phase, week) nflgame.update_sched.write_schedule(jsonf, d) last_updated = datetime.datetime.now() return (d, last_updated)
[ "def", "_create_schedule", "(", "jsonf", "=", "None", ")", ":", "day", "=", "(", "(", "60", "*", "60", ")", "*", "24", ")", "if", "(", "jsonf", "is", "None", ")", ":", "jsonf", "=", "_sched_json_file", "try", ":", "data", "=", "json", ".", "loads", "(", "open", "(", "jsonf", ")", ".", "read", "(", ")", ")", "except", "IOError", ":", "return", "OrderedDict", "(", ")", "d", "=", "OrderedDict", "(", ")", "for", "(", "gsis_id", ",", "info", ")", "in", "data", ".", "get", "(", "'games'", ",", "[", "]", ")", ":", "d", "[", "gsis_id", "]", "=", "info", "last_updated", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "data", ".", "get", "(", "'time'", ",", "0", ")", ")", "if", "(", "(", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "-", "last_updated", ")", ".", "total_seconds", "(", ")", ">=", "day", ")", ":", "if", "os", ".", "access", "(", "jsonf", ",", "os", ".", "W_OK", ")", ":", "import", "nflgame", ".", "live", "import", "nflgame", ".", "update_sched", "(", "year", ",", "week", ")", "=", "nflgame", ".", "live", ".", "current_year_and_week", "(", ")", "phase", "=", "nflgame", ".", "live", ".", "_cur_season_phase", "nflgame", ".", "update_sched", ".", "update_week", "(", "d", ",", "year", ",", "phase", ",", "week", ")", "nflgame", ".", "update_sched", ".", "write_schedule", "(", "jsonf", ",", "d", ")", "last_updated", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "return", "(", "d", ",", "last_updated", ")" ]
returns an ordered dict of schedule data from the schedule .
train
false
24,594
def test_badoptimization_opt_err(): @gof.local_optimizer([theano.tensor.add]) def insert_bigger_b_add(node): if (node.op == theano.tensor.add): inputs = list(node.inputs) if (inputs[(-1)].owner is None): inputs[(-1)] = theano.tensor.concatenate((inputs[(-1)], inputs[(-1)])) return [node.op(*inputs)] return False edb = gof.EquilibriumDB() edb.register('insert_bigger_b_add', insert_bigger_b_add, 'all') opt = edb.query('+all') a = theano.tensor.dvector() b = theano.tensor.dvector() f = theano.function([a, b], (a + b), mode=debugmode.DebugMode(optimizer=opt)) try: f([1.0, 2.0, 3.0], [2, 3, 4]) except Exception as e: assert ('insert_bigger_b_add' in exc_message(e)) return assert False
[ "def", "test_badoptimization_opt_err", "(", ")", ":", "@", "gof", ".", "local_optimizer", "(", "[", "theano", ".", "tensor", ".", "add", "]", ")", "def", "insert_bigger_b_add", "(", "node", ")", ":", "if", "(", "node", ".", "op", "==", "theano", ".", "tensor", ".", "add", ")", ":", "inputs", "=", "list", "(", "node", ".", "inputs", ")", "if", "(", "inputs", "[", "(", "-", "1", ")", "]", ".", "owner", "is", "None", ")", ":", "inputs", "[", "(", "-", "1", ")", "]", "=", "theano", ".", "tensor", ".", "concatenate", "(", "(", "inputs", "[", "(", "-", "1", ")", "]", ",", "inputs", "[", "(", "-", "1", ")", "]", ")", ")", "return", "[", "node", ".", "op", "(", "*", "inputs", ")", "]", "return", "False", "edb", "=", "gof", ".", "EquilibriumDB", "(", ")", "edb", ".", "register", "(", "'insert_bigger_b_add'", ",", "insert_bigger_b_add", ",", "'all'", ")", "opt", "=", "edb", ".", "query", "(", "'+all'", ")", "a", "=", "theano", ".", "tensor", ".", "dvector", "(", ")", "b", "=", "theano", ".", "tensor", ".", "dvector", "(", ")", "f", "=", "theano", ".", "function", "(", "[", "a", ",", "b", "]", ",", "(", "a", "+", "b", ")", ",", "mode", "=", "debugmode", ".", "DebugMode", "(", "optimizer", "=", "opt", ")", ")", "try", ":", "f", "(", "[", "1.0", ",", "2.0", ",", "3.0", "]", ",", "[", "2", ",", "3", ",", "4", "]", ")", "except", "Exception", "as", "e", ":", "assert", "(", "'insert_bigger_b_add'", "in", "exc_message", "(", "e", ")", ")", "return", "assert", "False" ]
this variant of test_badoptimization() replace the working code with a new apply node that will raise an error .
train
false
24,596
@handle_response_format @treeio_login_required def queue_add(request, response_format='html'): if (not request.user.profile.is_admin('treeio.services')): return user_denied(request, message="You don't have administrator access to the Service Support module") if request.POST: if ('cancel' not in request.POST): queue = TicketQueue() form = QueueForm(request.user.profile, request.POST, instance=queue) if form.is_valid(): queue = form.save() queue.set_user_from_request(request) return HttpResponseRedirect(reverse('services_queue_view', args=[queue.id])) else: return HttpResponseRedirect(reverse('services_settings_view')) else: form = QueueForm(request.user.profile) context = _get_default_context(request) context.update({'form': form}) return render_to_response('services/queue_add', context, context_instance=RequestContext(request), response_format=response_format)
[ "@", "handle_response_format", "@", "treeio_login_required", "def", "queue_add", "(", "request", ",", "response_format", "=", "'html'", ")", ":", "if", "(", "not", "request", ".", "user", ".", "profile", ".", "is_admin", "(", "'treeio.services'", ")", ")", ":", "return", "user_denied", "(", "request", ",", "message", "=", "\"You don't have administrator access to the Service Support module\"", ")", "if", "request", ".", "POST", ":", "if", "(", "'cancel'", "not", "in", "request", ".", "POST", ")", ":", "queue", "=", "TicketQueue", "(", ")", "form", "=", "QueueForm", "(", "request", ".", "user", ".", "profile", ",", "request", ".", "POST", ",", "instance", "=", "queue", ")", "if", "form", ".", "is_valid", "(", ")", ":", "queue", "=", "form", ".", "save", "(", ")", "queue", ".", "set_user_from_request", "(", "request", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'services_queue_view'", ",", "args", "=", "[", "queue", ".", "id", "]", ")", ")", "else", ":", "return", "HttpResponseRedirect", "(", "reverse", "(", "'services_settings_view'", ")", ")", "else", ":", "form", "=", "QueueForm", "(", "request", ".", "user", ".", "profile", ")", "context", "=", "_get_default_context", "(", "request", ")", "context", ".", "update", "(", "{", "'form'", ":", "form", "}", ")", "return", "render_to_response", "(", "'services/queue_add'", ",", "context", ",", "context_instance", "=", "RequestContext", "(", "request", ")", ",", "response_format", "=", "response_format", ")" ]
queue add .
train
false
24,598
def test_consistency_randomstreams(): seed = 12345 n_samples = 5 n_streams = 12 n_substreams = 7 test_use_cuda = [False] if cuda_available: test_use_cuda.append(True) for use_cuda in test_use_cuda: samples = [] rng = MRG_RandomStreams(seed=seed, use_cuda=use_cuda) for i in range(n_streams): stream_samples = [] u = rng.uniform(size=(n_substreams,), nstreams=n_substreams) f = theano.function([], u) for j in range(n_samples): s = f() stream_samples.append(s) stream_samples = numpy.array(stream_samples) stream_samples = stream_samples.T.flatten() samples.append(stream_samples) samples = numpy.array(samples).flatten() assert numpy.allclose(samples, java_samples)
[ "def", "test_consistency_randomstreams", "(", ")", ":", "seed", "=", "12345", "n_samples", "=", "5", "n_streams", "=", "12", "n_substreams", "=", "7", "test_use_cuda", "=", "[", "False", "]", "if", "cuda_available", ":", "test_use_cuda", ".", "append", "(", "True", ")", "for", "use_cuda", "in", "test_use_cuda", ":", "samples", "=", "[", "]", "rng", "=", "MRG_RandomStreams", "(", "seed", "=", "seed", ",", "use_cuda", "=", "use_cuda", ")", "for", "i", "in", "range", "(", "n_streams", ")", ":", "stream_samples", "=", "[", "]", "u", "=", "rng", ".", "uniform", "(", "size", "=", "(", "n_substreams", ",", ")", ",", "nstreams", "=", "n_substreams", ")", "f", "=", "theano", ".", "function", "(", "[", "]", ",", "u", ")", "for", "j", "in", "range", "(", "n_samples", ")", ":", "s", "=", "f", "(", ")", "stream_samples", ".", "append", "(", "s", ")", "stream_samples", "=", "numpy", ".", "array", "(", "stream_samples", ")", "stream_samples", "=", "stream_samples", ".", "T", ".", "flatten", "(", ")", "samples", ".", "append", "(", "stream_samples", ")", "samples", "=", "numpy", ".", "array", "(", "samples", ")", ".", "flatten", "(", ")", "assert", "numpy", ".", "allclose", "(", "samples", ",", "java_samples", ")" ]
verify that the random numbers generated by mrg_randomstreams are the same as the reference implementation by lecuyer et al .
train
false
24,599
def _dlog(c, e, p): p += 2 l = len(str(c)) f = ((e + l) - ((e + l) >= 1)) if (p > 0): k = ((e + p) - f) if (k >= 0): c *= (10 ** k) else: c = _div_nearest(c, (10 ** (- k))) log_d = _ilog(c, (10 ** p)) else: log_d = 0 if f: extra = (len(str(abs(f))) - 1) if ((p + extra) >= 0): f_log_ten = _div_nearest((f * _log10_digits((p + extra))), (10 ** extra)) else: f_log_ten = 0 else: f_log_ten = 0 return _div_nearest((f_log_ten + log_d), 100)
[ "def", "_dlog", "(", "c", ",", "e", ",", "p", ")", ":", "p", "+=", "2", "l", "=", "len", "(", "str", "(", "c", ")", ")", "f", "=", "(", "(", "e", "+", "l", ")", "-", "(", "(", "e", "+", "l", ")", ">=", "1", ")", ")", "if", "(", "p", ">", "0", ")", ":", "k", "=", "(", "(", "e", "+", "p", ")", "-", "f", ")", "if", "(", "k", ">=", "0", ")", ":", "c", "*=", "(", "10", "**", "k", ")", "else", ":", "c", "=", "_div_nearest", "(", "c", ",", "(", "10", "**", "(", "-", "k", ")", ")", ")", "log_d", "=", "_ilog", "(", "c", ",", "(", "10", "**", "p", ")", ")", "else", ":", "log_d", "=", "0", "if", "f", ":", "extra", "=", "(", "len", "(", "str", "(", "abs", "(", "f", ")", ")", ")", "-", "1", ")", "if", "(", "(", "p", "+", "extra", ")", ">=", "0", ")", ":", "f_log_ten", "=", "_div_nearest", "(", "(", "f", "*", "_log10_digits", "(", "(", "p", "+", "extra", ")", ")", ")", ",", "(", "10", "**", "extra", ")", ")", "else", ":", "f_log_ten", "=", "0", "else", ":", "f_log_ten", "=", "0", "return", "_div_nearest", "(", "(", "f_log_ten", "+", "log_d", ")", ",", "100", ")" ]
given integers c .
train
false
24,600
@pytest.mark.hasgpu def test_copy_transpose(shape_inp, backend_pair_dtype): (shape, (name, inp_gen)) = shape_inp (ng, nc) = backend_pair_dtype np_inp = inp_gen(shape).astype(nc.default_dtype) ndims = len(shape) axes = ([None] + list(itt.permutations(range(ndims), ndims))) axes.remove(tuple(range(ndims))) for (be, ax) in itt.product([ng, nc], axes): be_inp = be.array(np_inp) np_trans = np.transpose(np_inp, axes=ax) be_trans = be.zeros(np_trans.shape) be.copy_transpose(be_inp, be_trans, axes=ax) assert tensors_allclose(np_trans, be_trans)
[ "@", "pytest", ".", "mark", ".", "hasgpu", "def", "test_copy_transpose", "(", "shape_inp", ",", "backend_pair_dtype", ")", ":", "(", "shape", ",", "(", "name", ",", "inp_gen", ")", ")", "=", "shape_inp", "(", "ng", ",", "nc", ")", "=", "backend_pair_dtype", "np_inp", "=", "inp_gen", "(", "shape", ")", ".", "astype", "(", "nc", ".", "default_dtype", ")", "ndims", "=", "len", "(", "shape", ")", "axes", "=", "(", "[", "None", "]", "+", "list", "(", "itt", ".", "permutations", "(", "range", "(", "ndims", ")", ",", "ndims", ")", ")", ")", "axes", ".", "remove", "(", "tuple", "(", "range", "(", "ndims", ")", ")", ")", "for", "(", "be", ",", "ax", ")", "in", "itt", ".", "product", "(", "[", "ng", ",", "nc", "]", ",", "axes", ")", ":", "be_inp", "=", "be", ".", "array", "(", "np_inp", ")", "np_trans", "=", "np", ".", "transpose", "(", "np_inp", ",", "axes", "=", "ax", ")", "be_trans", "=", "be", ".", "zeros", "(", "np_trans", ".", "shape", ")", "be", ".", "copy_transpose", "(", "be_inp", ",", "be_trans", ",", "axes", "=", "ax", ")", "assert", "tensors_allclose", "(", "np_trans", ",", "be_trans", ")" ]
parameterized test case .
train
false
24,601
def setup_bravia(config, pin, hass, add_devices): host = config.get(CONF_HOST) name = config.get(CONF_NAME) if (pin is None): request_configuration(config, hass, add_devices) return else: mac = _get_mac_address(host) if (mac is not None): mac = mac.decode('utf8') if (host in _CONFIGURING): request_id = _CONFIGURING.pop(host) configurator = get_component('configurator') configurator.request_done(request_id) _LOGGER.info('Discovery configuration done!') if (not _config_from_file(hass.config.path(BRAVIA_CONFIG_FILE), {host: {'pin': pin, 'host': host, 'mac': mac}})): _LOGGER.error('failed to save config file') add_devices([BraviaTVDevice(host, mac, name, pin)])
[ "def", "setup_bravia", "(", "config", ",", "pin", ",", "hass", ",", "add_devices", ")", ":", "host", "=", "config", ".", "get", "(", "CONF_HOST", ")", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "if", "(", "pin", "is", "None", ")", ":", "request_configuration", "(", "config", ",", "hass", ",", "add_devices", ")", "return", "else", ":", "mac", "=", "_get_mac_address", "(", "host", ")", "if", "(", "mac", "is", "not", "None", ")", ":", "mac", "=", "mac", ".", "decode", "(", "'utf8'", ")", "if", "(", "host", "in", "_CONFIGURING", ")", ":", "request_id", "=", "_CONFIGURING", ".", "pop", "(", "host", ")", "configurator", "=", "get_component", "(", "'configurator'", ")", "configurator", ".", "request_done", "(", "request_id", ")", "_LOGGER", ".", "info", "(", "'Discovery configuration done!'", ")", "if", "(", "not", "_config_from_file", "(", "hass", ".", "config", ".", "path", "(", "BRAVIA_CONFIG_FILE", ")", ",", "{", "host", ":", "{", "'pin'", ":", "pin", ",", "'host'", ":", "host", ",", "'mac'", ":", "mac", "}", "}", ")", ")", ":", "_LOGGER", ".", "error", "(", "'failed to save config file'", ")", "add_devices", "(", "[", "BraviaTVDevice", "(", "host", ",", "mac", ",", "name", ",", "pin", ")", "]", ")" ]
setup a sony bravia tv based on host parameter .
train
false
24,602
def assertNotReading(testCase, reactor, transport): if IReactorFDSet.providedBy(reactor): testCase.assertNotIn(transport, reactor.getReaders()) else: testCase.assertFalse(transport.reading)
[ "def", "assertNotReading", "(", "testCase", ",", "reactor", ",", "transport", ")", ":", "if", "IReactorFDSet", ".", "providedBy", "(", "reactor", ")", ":", "testCase", ".", "assertNotIn", "(", "transport", ",", "reactor", ".", "getReaders", "(", ")", ")", "else", ":", "testCase", ".", "assertFalse", "(", "transport", ".", "reading", ")" ]
use the given test to assert that the given transport is i{not} actively reading in the given reactor .
train
false
24,603
def make_hybi07_frame_dwim(buf): if isinstance(buf, str): return make_hybi07_frame(buf, opcode=2) elif isinstance(buf, unicode): return make_hybi07_frame(buf.encode('utf-8'), opcode=1) else: raise TypeError('In binary support mode, frame data must be either str or unicode')
[ "def", "make_hybi07_frame_dwim", "(", "buf", ")", ":", "if", "isinstance", "(", "buf", ",", "str", ")", ":", "return", "make_hybi07_frame", "(", "buf", ",", "opcode", "=", "2", ")", "elif", "isinstance", "(", "buf", ",", "unicode", ")", ":", "return", "make_hybi07_frame", "(", "buf", ".", "encode", "(", "'utf-8'", ")", ",", "opcode", "=", "1", ")", "else", ":", "raise", "TypeError", "(", "'In binary support mode, frame data must be either str or unicode'", ")" ]
make a hybi-07 frame with binary or text data according to the type of buf .
train
false
24,604
def get_xml_version(version): if (version is None): return 1 return int(version.split('.')[0])
[ "def", "get_xml_version", "(", "version", ")", ":", "if", "(", "version", "is", "None", ")", ":", "return", "1", "return", "int", "(", "version", ".", "split", "(", "'.'", ")", "[", "0", "]", ")" ]
determines which xml schema to use based on the client api version .
train
false
24,605
@login_required @require_POST def mark_ready_for_l10n_revision(request, document_slug, revision_id): revision = get_object_or_404(Revision, pk=revision_id, document__slug=document_slug) if (not revision.document.allows(request.user, 'mark_ready_for_l10n')): raise PermissionDenied if revision.can_be_readied_for_localization(): revision.is_ready_for_localization = True revision.readied_for_localization = datetime.now() revision.readied_for_localization_by = request.user revision.save() ReadyRevisionEvent(revision).fire(exclude=request.user) return HttpResponse(json.dumps({'message': revision_id})) return HttpResponseBadRequest()
[ "@", "login_required", "@", "require_POST", "def", "mark_ready_for_l10n_revision", "(", "request", ",", "document_slug", ",", "revision_id", ")", ":", "revision", "=", "get_object_or_404", "(", "Revision", ",", "pk", "=", "revision_id", ",", "document__slug", "=", "document_slug", ")", "if", "(", "not", "revision", ".", "document", ".", "allows", "(", "request", ".", "user", ",", "'mark_ready_for_l10n'", ")", ")", ":", "raise", "PermissionDenied", "if", "revision", ".", "can_be_readied_for_localization", "(", ")", ":", "revision", ".", "is_ready_for_localization", "=", "True", "revision", ".", "readied_for_localization", "=", "datetime", ".", "now", "(", ")", "revision", ".", "readied_for_localization_by", "=", "request", ".", "user", "revision", ".", "save", "(", ")", "ReadyRevisionEvent", "(", "revision", ")", ".", "fire", "(", "exclude", "=", "request", ".", "user", ")", "return", "HttpResponse", "(", "json", ".", "dumps", "(", "{", "'message'", ":", "revision_id", "}", ")", ")", "return", "HttpResponseBadRequest", "(", ")" ]
mark a revision as ready for l10n .
train
false
24,606
def DNSServiceQueryRecord(flags=0, interfaceIndex=kDNSServiceInterfaceIndexAny, fullname=_NO_DEFAULT, rrtype=_NO_DEFAULT, rrclass=kDNSServiceClass_IN, callBack=None): _NO_DEFAULT.check(fullname) _NO_DEFAULT.check(rrtype) @_DNSServiceQueryRecordReply def _callback(sdRef, flags, interfaceIndex, errorCode, fullname, rrtype, rrclass, rdlen, rdata, ttl, context): if (callBack is not None): rdata = _length_and_void_p_to_string(rdlen, rdata) callBack(sdRef, flags, interfaceIndex, errorCode, fullname.decode(), rrtype, rrclass, rdata, ttl) _global_lock.acquire() try: sdRef = _DNSServiceQueryRecord(flags, interfaceIndex, fullname, rrtype, rrclass, _callback, None) finally: _global_lock.release() sdRef._add_callback(_callback) return sdRef
[ "def", "DNSServiceQueryRecord", "(", "flags", "=", "0", ",", "interfaceIndex", "=", "kDNSServiceInterfaceIndexAny", ",", "fullname", "=", "_NO_DEFAULT", ",", "rrtype", "=", "_NO_DEFAULT", ",", "rrclass", "=", "kDNSServiceClass_IN", ",", "callBack", "=", "None", ")", ":", "_NO_DEFAULT", ".", "check", "(", "fullname", ")", "_NO_DEFAULT", ".", "check", "(", "rrtype", ")", "@", "_DNSServiceQueryRecordReply", "def", "_callback", "(", "sdRef", ",", "flags", ",", "interfaceIndex", ",", "errorCode", ",", "fullname", ",", "rrtype", ",", "rrclass", ",", "rdlen", ",", "rdata", ",", "ttl", ",", "context", ")", ":", "if", "(", "callBack", "is", "not", "None", ")", ":", "rdata", "=", "_length_and_void_p_to_string", "(", "rdlen", ",", "rdata", ")", "callBack", "(", "sdRef", ",", "flags", ",", "interfaceIndex", ",", "errorCode", ",", "fullname", ".", "decode", "(", ")", ",", "rrtype", ",", "rrclass", ",", "rdata", ",", "ttl", ")", "_global_lock", ".", "acquire", "(", ")", "try", ":", "sdRef", "=", "_DNSServiceQueryRecord", "(", "flags", ",", "interfaceIndex", ",", "fullname", ",", "rrtype", ",", "rrclass", ",", "_callback", ",", "None", ")", "finally", ":", "_global_lock", ".", "release", "(", ")", "sdRef", ".", "_add_callback", "(", "_callback", ")", "return", "sdRef" ]
query for an arbitrary dns record .
train
false
24,607
def set_https_port(port=443): _current = global_settings() if (_current['Global Settings']['HTTP_PORT']['VALUE'] == port): return True _xml = '<RIBCL VERSION="2.0">\n <LOGIN USER_LOGIN="adminname" PASSWORD="password">\n <RIB_INFO MODE="write">\n <MOD_GLOBAL_SETTINGS>\n <HTTPS_PORT value="{0}"/>\n </MOD_GLOBAL_SETTINGS>\n </RIB_INFO>\n </LOGIN>\n </RIBCL>'.format(port) return __execute_cmd('Set_HTTPS_Port', _xml)
[ "def", "set_https_port", "(", "port", "=", "443", ")", ":", "_current", "=", "global_settings", "(", ")", "if", "(", "_current", "[", "'Global Settings'", "]", "[", "'HTTP_PORT'", "]", "[", "'VALUE'", "]", "==", "port", ")", ":", "return", "True", "_xml", "=", "'<RIBCL VERSION=\"2.0\">\\n <LOGIN USER_LOGIN=\"adminname\" PASSWORD=\"password\">\\n <RIB_INFO MODE=\"write\">\\n <MOD_GLOBAL_SETTINGS>\\n <HTTPS_PORT value=\"{0}\"/>\\n </MOD_GLOBAL_SETTINGS>\\n </RIB_INFO>\\n </LOGIN>\\n </RIBCL>'", ".", "format", "(", "port", ")", "return", "__execute_cmd", "(", "'Set_HTTPS_Port'", ",", "_xml", ")" ]
configure the port https should listen on cli example: .
train
true
24,608
def str2css(sourcestring, colors=None, title='', markup='css', header=None, footer=None, linenumbers=0, form=None): if (markup.lower() not in ['css', 'xhtml']): markup = 'css' stringIO = StringIO.StringIO() parse = Parser(sourcestring, colors=colors, title=title, out=stringIO, markup=markup, header=header, footer=footer, linenumbers=linenumbers) parse.format(form) stringIO.seek(0) if (form != None): return (parse._sendCSSStyle(external=1), stringIO.read()) else: return (None, stringIO.read())
[ "def", "str2css", "(", "sourcestring", ",", "colors", "=", "None", ",", "title", "=", "''", ",", "markup", "=", "'css'", ",", "header", "=", "None", ",", "footer", "=", "None", ",", "linenumbers", "=", "0", ",", "form", "=", "None", ")", ":", "if", "(", "markup", ".", "lower", "(", ")", "not", "in", "[", "'css'", ",", "'xhtml'", "]", ")", ":", "markup", "=", "'css'", "stringIO", "=", "StringIO", ".", "StringIO", "(", ")", "parse", "=", "Parser", "(", "sourcestring", ",", "colors", "=", "colors", ",", "title", "=", "title", ",", "out", "=", "stringIO", ",", "markup", "=", "markup", ",", "header", "=", "header", ",", "footer", "=", "footer", ",", "linenumbers", "=", "linenumbers", ")", "parse", ".", "format", "(", "form", ")", "stringIO", ".", "seek", "(", "0", ")", "if", "(", "form", "!=", "None", ")", ":", "return", "(", "parse", ".", "_sendCSSStyle", "(", "external", "=", "1", ")", ",", "stringIO", ".", "read", "(", ")", ")", "else", ":", "return", "(", "None", ",", "stringIO", ".", "read", "(", ")", ")" ]
converts a code string to colorized css/html .
train
false
24,609
def random_population(genome_alphabet, genome_size, num_organisms, fitness_calculator): all_orgs = [] letter_rand = random.Random() if isinstance(genome_alphabet.letters[0], str): if (sys.version_info[0] == 3): alphabet_type = 'u' else: alphabet_type = 'c' elif isinstance(genome_alphabet.letters[0], int): alphabet_type = 'i' elif isinstance(genome_alphabet.letters[0], float): alphabet_type = 'd' else: raise ValueError(('Alphabet type is unsupported: %s' % genome_alphabet.letters)) for org_num in range(num_organisms): new_genome = MutableSeq(array.array(alphabet_type), genome_alphabet) for gene_num in range(genome_size): new_gene = letter_rand.choice(genome_alphabet.letters) new_genome.append(new_gene) all_orgs.append(Organism(new_genome, fitness_calculator)) return all_orgs
[ "def", "random_population", "(", "genome_alphabet", ",", "genome_size", ",", "num_organisms", ",", "fitness_calculator", ")", ":", "all_orgs", "=", "[", "]", "letter_rand", "=", "random", ".", "Random", "(", ")", "if", "isinstance", "(", "genome_alphabet", ".", "letters", "[", "0", "]", ",", "str", ")", ":", "if", "(", "sys", ".", "version_info", "[", "0", "]", "==", "3", ")", ":", "alphabet_type", "=", "'u'", "else", ":", "alphabet_type", "=", "'c'", "elif", "isinstance", "(", "genome_alphabet", ".", "letters", "[", "0", "]", ",", "int", ")", ":", "alphabet_type", "=", "'i'", "elif", "isinstance", "(", "genome_alphabet", ".", "letters", "[", "0", "]", ",", "float", ")", ":", "alphabet_type", "=", "'d'", "else", ":", "raise", "ValueError", "(", "(", "'Alphabet type is unsupported: %s'", "%", "genome_alphabet", ".", "letters", ")", ")", "for", "org_num", "in", "range", "(", "num_organisms", ")", ":", "new_genome", "=", "MutableSeq", "(", "array", ".", "array", "(", "alphabet_type", ")", ",", "genome_alphabet", ")", "for", "gene_num", "in", "range", "(", "genome_size", ")", ":", "new_gene", "=", "letter_rand", ".", "choice", "(", "genome_alphabet", ".", "letters", ")", "new_genome", ".", "append", "(", "new_gene", ")", "all_orgs", ".", "append", "(", "Organism", "(", "new_genome", ",", "fitness_calculator", ")", ")", "return", "all_orgs" ]
generate a population of individuals with randomly set genomes .
train
false
24,610
@library.global_function def format_comment(rev, previous_revision=None): prev_rev = getattr(rev, 'previous_revision', previous_revision) if (prev_rev is None): prev_rev = rev.previous comment = bugize_text((rev.comment if rev.comment else '')) if (prev_rev and (prev_rev.slug != rev.slug)): comment += (jinja2.Markup('<span class="slug-change"><span>%s</span> <i class="icon-long-arrow-right" aria-hidden="true"></i> <span>%s</span></span>') % (prev_rev.slug, rev.slug)) return comment
[ "@", "library", ".", "global_function", "def", "format_comment", "(", "rev", ",", "previous_revision", "=", "None", ")", ":", "prev_rev", "=", "getattr", "(", "rev", ",", "'previous_revision'", ",", "previous_revision", ")", "if", "(", "prev_rev", "is", "None", ")", ":", "prev_rev", "=", "rev", ".", "previous", "comment", "=", "bugize_text", "(", "(", "rev", ".", "comment", "if", "rev", ".", "comment", "else", "''", ")", ")", "if", "(", "prev_rev", "and", "(", "prev_rev", ".", "slug", "!=", "rev", ".", "slug", ")", ")", ":", "comment", "+=", "(", "jinja2", ".", "Markup", "(", "'<span class=\"slug-change\"><span>%s</span> <i class=\"icon-long-arrow-right\" aria-hidden=\"true\"></i> <span>%s</span></span>'", ")", "%", "(", "prev_rev", ".", "slug", ",", "rev", ".", "slug", ")", ")", "return", "comment" ]
massages revision comment content after the fact .
train
false
24,613
def get_loadavg(): if (platform.system() == 'Linux'): return open('/proc/loadavg').read().split()[:3] else: command = 'uptime' process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) stdout = process.communicate()[0].strip() output = re.split('[\\s,]+', stdout) return output[(-3):]
[ "def", "get_loadavg", "(", ")", ":", "if", "(", "platform", ".", "system", "(", ")", "==", "'Linux'", ")", ":", "return", "open", "(", "'/proc/loadavg'", ")", ".", "read", "(", ")", ".", "split", "(", ")", "[", ":", "3", "]", "else", ":", "command", "=", "'uptime'", "process", "=", "subprocess", ".", "Popen", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "shell", "=", "True", ")", "stdout", "=", "process", ".", "communicate", "(", ")", "[", "0", "]", ".", "strip", "(", ")", "output", "=", "re", ".", "split", "(", "'[\\\\s,]+'", ",", "stdout", ")", "return", "output", "[", "(", "-", "3", ")", ":", "]" ]
get the load average for a unix-like system .
train
false
24,614
def identifier(s): return ((u'"' + s.replace(u'"', u'""').replace(u'\x00', '')) + u'"')
[ "def", "identifier", "(", "s", ")", ":", "return", "(", "(", "u'\"'", "+", "s", ".", "replace", "(", "u'\"'", ",", "u'\"\"'", ")", ".", "replace", "(", "u'\\x00'", ",", "''", ")", ")", "+", "u'\"'", ")" ]
return s as a quoted postgres identifier .
train
false
24,616
def get_app_user(app, name): q = Queue() def get_user_id(): user = find_user(app.db, name) q.put(user.id) app.io_loop.add_callback(get_user_id) user_id = q.get(timeout=2) return app.users[user_id]
[ "def", "get_app_user", "(", "app", ",", "name", ")", ":", "q", "=", "Queue", "(", ")", "def", "get_user_id", "(", ")", ":", "user", "=", "find_user", "(", "app", ".", "db", ",", "name", ")", "q", ".", "put", "(", "user", ".", "id", ")", "app", ".", "io_loop", ".", "add_callback", "(", "get_user_id", ")", "user_id", "=", "q", ".", "get", "(", "timeout", "=", "2", ")", "return", "app", ".", "users", "[", "user_id", "]" ]
get the user object from the main thread needed for access to the spawner .
train
false
24,617
def split_symbols_custom(predicate): def _split_symbols(tokens, local_dict, global_dict): result = [] split = False split_previous = False for tok in tokens: if split_previous: split_previous = False continue split_previous = False if ((tok[0] == NAME) and (tok[1] == 'Symbol')): split = True elif (split and (tok[0] == NAME)): symbol = tok[1][1:(-1)] if predicate(symbol): for char in symbol: if ((char in local_dict) or (char in global_dict)): del result[(-2):] result.extend([(NAME, ('%s' % char)), (NAME, 'Symbol'), (OP, '(')]) else: result.extend([(NAME, ("'%s'" % char)), (OP, ')'), (NAME, 'Symbol'), (OP, '(')]) del result[(-2):] split = False split_previous = True continue else: split = False result.append(tok) return result return _split_symbols
[ "def", "split_symbols_custom", "(", "predicate", ")", ":", "def", "_split_symbols", "(", "tokens", ",", "local_dict", ",", "global_dict", ")", ":", "result", "=", "[", "]", "split", "=", "False", "split_previous", "=", "False", "for", "tok", "in", "tokens", ":", "if", "split_previous", ":", "split_previous", "=", "False", "continue", "split_previous", "=", "False", "if", "(", "(", "tok", "[", "0", "]", "==", "NAME", ")", "and", "(", "tok", "[", "1", "]", "==", "'Symbol'", ")", ")", ":", "split", "=", "True", "elif", "(", "split", "and", "(", "tok", "[", "0", "]", "==", "NAME", ")", ")", ":", "symbol", "=", "tok", "[", "1", "]", "[", "1", ":", "(", "-", "1", ")", "]", "if", "predicate", "(", "symbol", ")", ":", "for", "char", "in", "symbol", ":", "if", "(", "(", "char", "in", "local_dict", ")", "or", "(", "char", "in", "global_dict", ")", ")", ":", "del", "result", "[", "(", "-", "2", ")", ":", "]", "result", ".", "extend", "(", "[", "(", "NAME", ",", "(", "'%s'", "%", "char", ")", ")", ",", "(", "NAME", ",", "'Symbol'", ")", ",", "(", "OP", ",", "'('", ")", "]", ")", "else", ":", "result", ".", "extend", "(", "[", "(", "NAME", ",", "(", "\"'%s'\"", "%", "char", ")", ")", ",", "(", "OP", ",", "')'", ")", ",", "(", "NAME", ",", "'Symbol'", ")", ",", "(", "OP", ",", "'('", ")", "]", ")", "del", "result", "[", "(", "-", "2", ")", ":", "]", "split", "=", "False", "split_previous", "=", "True", "continue", "else", ":", "split", "=", "False", "result", ".", "append", "(", "tok", ")", "return", "result", "return", "_split_symbols" ]
creates a transformation that splits symbol names .
train
false
24,618
def _Constructor(cls, ptr=_internal_guard): if (ptr == _internal_guard): raise VLCException('(INTERNAL) ctypes class. You should get references for this class through methods of the LibVLC API.') if ((ptr is None) or (ptr == 0)): return None return _Cobject(cls, ctypes.c_void_p(ptr))
[ "def", "_Constructor", "(", "cls", ",", "ptr", "=", "_internal_guard", ")", ":", "if", "(", "ptr", "==", "_internal_guard", ")", ":", "raise", "VLCException", "(", "'(INTERNAL) ctypes class. You should get references for this class through methods of the LibVLC API.'", ")", "if", "(", "(", "ptr", "is", "None", ")", "or", "(", "ptr", "==", "0", ")", ")", ":", "return", "None", "return", "_Cobject", "(", "cls", ",", "ctypes", ".", "c_void_p", "(", "ptr", ")", ")" ]
new wrapper from ctypes .
train
true
24,620
def release(): return uname()[2]
[ "def", "release", "(", ")", ":", "return", "uname", "(", ")", "[", "2", "]" ]
yaml: release add release build configuration requires the jenkins :jenkins-wiki:release plugin <release+plugin> .
train
false
24,621
def get_opcounter_rate(name): master_rate = get_rate(name) repl_rate = get_rate(name.replace('opcounters_', 'opcountersRepl_')) return (master_rate + repl_rate)
[ "def", "get_opcounter_rate", "(", "name", ")", ":", "master_rate", "=", "get_rate", "(", "name", ")", "repl_rate", "=", "get_rate", "(", "name", ".", "replace", "(", "'opcounters_'", ",", "'opcountersRepl_'", ")", ")", "return", "(", "master_rate", "+", "repl_rate", ")" ]
return change over time for an opcounter metric .
train
false
24,624
def validate_idp(idp, protocol, assertion): remote_id_parameter = get_remote_id_parameter(protocol) if ((not remote_id_parameter) or (not idp['remote_ids'])): LOG.debug('Impossible to identify the IdP %s ', idp['id']) return try: idp_remote_identifier = assertion[remote_id_parameter] except KeyError: msg = _('Could not find Identity Provider identifier in environment') raise exception.ValidationError(msg) if (idp_remote_identifier not in idp['remote_ids']): msg = _('Incoming identity provider identifier not included among the accepted identifiers.') raise exception.Forbidden(msg)
[ "def", "validate_idp", "(", "idp", ",", "protocol", ",", "assertion", ")", ":", "remote_id_parameter", "=", "get_remote_id_parameter", "(", "protocol", ")", "if", "(", "(", "not", "remote_id_parameter", ")", "or", "(", "not", "idp", "[", "'remote_ids'", "]", ")", ")", ":", "LOG", ".", "debug", "(", "'Impossible to identify the IdP %s '", ",", "idp", "[", "'id'", "]", ")", "return", "try", ":", "idp_remote_identifier", "=", "assertion", "[", "remote_id_parameter", "]", "except", "KeyError", ":", "msg", "=", "_", "(", "'Could not find Identity Provider identifier in environment'", ")", "raise", "exception", ".", "ValidationError", "(", "msg", ")", "if", "(", "idp_remote_identifier", "not", "in", "idp", "[", "'remote_ids'", "]", ")", ":", "msg", "=", "_", "(", "'Incoming identity provider identifier not included among the accepted identifiers.'", ")", "raise", "exception", ".", "Forbidden", "(", "msg", ")" ]
the idp providing the assertion should be registered for the mapping .
train
false
24,626
def _regex_instance_filter(query, filters): model = models.Instance (safe_regex_filter, db_regexp_op) = _get_regexp_ops(CONF.database.connection) for filter_name in filters: try: column_attr = getattr(model, filter_name) except AttributeError: continue if ('property' == type(column_attr).__name__): continue filter_val = filters[filter_name] if (not isinstance(filter_val, six.string_types)): filter_val = str(filter_val) if (db_regexp_op == 'LIKE'): query = query.filter(column_attr.op(db_regexp_op)(((u'%' + filter_val) + u'%'))) else: filter_val = safe_regex_filter(filter_val) query = query.filter(column_attr.op(db_regexp_op)(filter_val)) return query
[ "def", "_regex_instance_filter", "(", "query", ",", "filters", ")", ":", "model", "=", "models", ".", "Instance", "(", "safe_regex_filter", ",", "db_regexp_op", ")", "=", "_get_regexp_ops", "(", "CONF", ".", "database", ".", "connection", ")", "for", "filter_name", "in", "filters", ":", "try", ":", "column_attr", "=", "getattr", "(", "model", ",", "filter_name", ")", "except", "AttributeError", ":", "continue", "if", "(", "'property'", "==", "type", "(", "column_attr", ")", ".", "__name__", ")", ":", "continue", "filter_val", "=", "filters", "[", "filter_name", "]", "if", "(", "not", "isinstance", "(", "filter_val", ",", "six", ".", "string_types", ")", ")", ":", "filter_val", "=", "str", "(", "filter_val", ")", "if", "(", "db_regexp_op", "==", "'LIKE'", ")", ":", "query", "=", "query", ".", "filter", "(", "column_attr", ".", "op", "(", "db_regexp_op", ")", "(", "(", "(", "u'%'", "+", "filter_val", ")", "+", "u'%'", ")", ")", ")", "else", ":", "filter_val", "=", "safe_regex_filter", "(", "filter_val", ")", "query", "=", "query", ".", "filter", "(", "column_attr", ".", "op", "(", "db_regexp_op", ")", "(", "filter_val", ")", ")", "return", "query" ]
applies regular expression filtering to an instance query .
train
false
24,628
def cg_creating_from_src(cg_id=None, cgsnapshot_id=None): subq = sql.select([models.ConsistencyGroup]).where(and_((~ models.ConsistencyGroup.deleted), (models.ConsistencyGroup.status == 'creating'))).alias('cg2') if cg_id: match_id = (subq.c.source_cgid == cg_id) elif cgsnapshot_id: match_id = (subq.c.cgsnapshot_id == cgsnapshot_id) else: msg = _('cg_creating_from_src must be called with cg_id or cgsnapshot_id parameter.') raise exception.ProgrammingError(reason=msg) return sql.exists([subq]).where(match_id)
[ "def", "cg_creating_from_src", "(", "cg_id", "=", "None", ",", "cgsnapshot_id", "=", "None", ")", ":", "subq", "=", "sql", ".", "select", "(", "[", "models", ".", "ConsistencyGroup", "]", ")", ".", "where", "(", "and_", "(", "(", "~", "models", ".", "ConsistencyGroup", ".", "deleted", ")", ",", "(", "models", ".", "ConsistencyGroup", ".", "status", "==", "'creating'", ")", ")", ")", ".", "alias", "(", "'cg2'", ")", "if", "cg_id", ":", "match_id", "=", "(", "subq", ".", "c", ".", "source_cgid", "==", "cg_id", ")", "elif", "cgsnapshot_id", ":", "match_id", "=", "(", "subq", ".", "c", ".", "cgsnapshot_id", "==", "cgsnapshot_id", ")", "else", ":", "msg", "=", "_", "(", "'cg_creating_from_src must be called with cg_id or cgsnapshot_id parameter.'", ")", "raise", "exception", ".", "ProgrammingError", "(", "reason", "=", "msg", ")", "return", "sql", ".", "exists", "(", "[", "subq", "]", ")", ".", "where", "(", "match_id", ")" ]
return a filter to check if a cg is being used as creation source .
train
false
24,629
def trainGradientBoosting(features, n_estimators): [X, Y] = listOfFeatures2Matrix(features) rf = sklearn.ensemble.GradientBoostingClassifier(n_estimators=n_estimators) rf.fit(X, Y) return rf
[ "def", "trainGradientBoosting", "(", "features", ",", "n_estimators", ")", ":", "[", "X", ",", "Y", "]", "=", "listOfFeatures2Matrix", "(", "features", ")", "rf", "=", "sklearn", ".", "ensemble", ".", "GradientBoostingClassifier", "(", "n_estimators", "=", "n_estimators", ")", "rf", ".", "fit", "(", "X", ",", "Y", ")", "return", "rf" ]
train a gradient boosting classifier note: this function is simply a wrapper to the sklearn functionality for svm training see function trainsvm_feature() to use a wrapper on both the feature extraction and the svm training processes .
train
false
24,630
def is_current_user_admin(): return (os.environ.get('USER_IS_ADMIN', '0') == '1')
[ "def", "is_current_user_admin", "(", ")", ":", "return", "(", "os", ".", "environ", ".", "get", "(", "'USER_IS_ADMIN'", ",", "'0'", ")", "==", "'1'", ")" ]
returns true if the user on whose behalf the request was made is an admin .
train
false
24,631
def get_pid_cpu(pid): cmd = ('ps -o cpuid -L -p %s' % pid) cpu_pid = system_output(cmd) if (not cpu_pid): return [] return list(set([_.strip() for _ in cpu_pid.splitlines()]))
[ "def", "get_pid_cpu", "(", "pid", ")", ":", "cmd", "=", "(", "'ps -o cpuid -L -p %s'", "%", "pid", ")", "cpu_pid", "=", "system_output", "(", "cmd", ")", "if", "(", "not", "cpu_pid", ")", ":", "return", "[", "]", "return", "list", "(", "set", "(", "[", "_", ".", "strip", "(", ")", "for", "_", "in", "cpu_pid", ".", "splitlines", "(", ")", "]", ")", ")" ]
get the process used cpus .
train
false
24,632
def legislature_to_number(leg): l = leg.lower().split('-') return ('%sLeg/%s%s' % (l[0][0:2], l[1][0], l[2][0]))
[ "def", "legislature_to_number", "(", "leg", ")", ":", "l", "=", "leg", ".", "lower", "(", ")", ".", "split", "(", "'-'", ")", "return", "(", "'%sLeg/%s%s'", "%", "(", "l", "[", "0", "]", "[", "0", ":", "2", "]", ",", "l", "[", "1", "]", "[", "0", "]", ",", "l", "[", "2", "]", "[", "0", "]", ")", ")" ]
takes a full session and splits it down to the values for formatdocument .
train
false
24,633
def party_members(path, zk_hosts, min_nodes=1, blocking=False): zk = _get_zk_conn(zk_hosts) party = kazoo.recipe.party.ShallowParty(zk, path) if blocking: barrier = kazoo.recipe.barrier.DoubleBarrier(zk, path, min_nodes) barrier.enter() party = kazoo.recipe.party.ShallowParty(zk, path) barrier.leave() return list(party)
[ "def", "party_members", "(", "path", ",", "zk_hosts", ",", "min_nodes", "=", "1", ",", "blocking", "=", "False", ")", ":", "zk", "=", "_get_zk_conn", "(", "zk_hosts", ")", "party", "=", "kazoo", ".", "recipe", ".", "party", ".", "ShallowParty", "(", "zk", ",", "path", ")", "if", "blocking", ":", "barrier", "=", "kazoo", ".", "recipe", ".", "barrier", ".", "DoubleBarrier", "(", "zk", ",", "path", ",", "min_nodes", ")", "barrier", ".", "enter", "(", ")", "party", "=", "kazoo", ".", "recipe", ".", "party", ".", "ShallowParty", "(", "zk", ",", "path", ")", "barrier", ".", "leave", "(", ")", "return", "list", "(", "party", ")" ]
get the list of identifiers in a particular party .
train
false
24,634
def _split_comment(lineno, comment): return [((lineno + index), line) for (index, line) in enumerate(comment.splitlines())]
[ "def", "_split_comment", "(", "lineno", ",", "comment", ")", ":", "return", "[", "(", "(", "lineno", "+", "index", ")", ",", "line", ")", "for", "(", "index", ",", "line", ")", "in", "enumerate", "(", "comment", ".", "splitlines", "(", ")", ")", "]" ]
return the multiline comment at lineno split into a list of comment line numbers and the accompanying comment line .
train
true
24,635
def gen_authzr(authz_status, domain, challs, statuses, combos=True): challbs = tuple((chall_to_challb(chall, status) for (chall, status) in six.moves.zip(challs, statuses))) authz_kwargs = {'identifier': messages.Identifier(typ=messages.IDENTIFIER_FQDN, value=domain), 'challenges': challbs} if combos: authz_kwargs.update({'combinations': gen_combos(challbs)}) if (authz_status == messages.STATUS_VALID): authz_kwargs.update({'status': authz_status, 'expires': (datetime.datetime.now() + datetime.timedelta(days=31))}) else: authz_kwargs.update({'status': authz_status}) return messages.AuthorizationResource(uri='https://trusted.ca/new-authz-resource', new_cert_uri='https://trusted.ca/new-cert', body=messages.Authorization(**authz_kwargs))
[ "def", "gen_authzr", "(", "authz_status", ",", "domain", ",", "challs", ",", "statuses", ",", "combos", "=", "True", ")", ":", "challbs", "=", "tuple", "(", "(", "chall_to_challb", "(", "chall", ",", "status", ")", "for", "(", "chall", ",", "status", ")", "in", "six", ".", "moves", ".", "zip", "(", "challs", ",", "statuses", ")", ")", ")", "authz_kwargs", "=", "{", "'identifier'", ":", "messages", ".", "Identifier", "(", "typ", "=", "messages", ".", "IDENTIFIER_FQDN", ",", "value", "=", "domain", ")", ",", "'challenges'", ":", "challbs", "}", "if", "combos", ":", "authz_kwargs", ".", "update", "(", "{", "'combinations'", ":", "gen_combos", "(", "challbs", ")", "}", ")", "if", "(", "authz_status", "==", "messages", ".", "STATUS_VALID", ")", ":", "authz_kwargs", ".", "update", "(", "{", "'status'", ":", "authz_status", ",", "'expires'", ":", "(", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "days", "=", "31", ")", ")", "}", ")", "else", ":", "authz_kwargs", ".", "update", "(", "{", "'status'", ":", "authz_status", "}", ")", "return", "messages", ".", "AuthorizationResource", "(", "uri", "=", "'https://trusted.ca/new-authz-resource'", ",", "new_cert_uri", "=", "'https://trusted.ca/new-cert'", ",", "body", "=", "messages", ".", "Authorization", "(", "**", "authz_kwargs", ")", ")" ]
generate an authorization resource .
train
false
24,636
def walkthroughTest(vm, prompt=Prompt): installPexpect(vm, prompt) vm.sendline('sudo -n python ~/mininet/mininet/test/test_walkthrough.py -v')
[ "def", "walkthroughTest", "(", "vm", ",", "prompt", "=", "Prompt", ")", ":", "installPexpect", "(", "vm", ",", "prompt", ")", "vm", ".", "sendline", "(", "'sudo -n python ~/mininet/mininet/test/test_walkthrough.py -v'", ")" ]
test mininet walkthrough .
train
false
24,638
def test_string_truncation_warning(): t = table.Table([['aa', 'bb']], names=['a']) with catch_warnings() as w: from inspect import currentframe, getframeinfo t['a'][1] = 'cc' assert (len(w) == 0) t['a'][:] = 'dd' assert (len(w) == 0) with catch_warnings() as w: frameinfo = getframeinfo(currentframe()) t['a'][0] = 'eee' assert (t['a'][0] == 'ee') assert (len(w) == 1) assert ('truncated right side string(s) longer than 2 character(s)' in str(w[0].message)) assert (w[0].lineno == (frameinfo.lineno + 1)) assert (w[0].category is table.StringTruncateWarning) assert ('test_column' in w[0].filename) with catch_warnings() as w: t['a'][:] = ['ff', 'ggg'] assert np.all((t['a'] == ['ff', 'gg'])) assert (len(w) == 1) assert ('truncated right side string(s) longer than 2 character(s)' in str(w[0].message))
[ "def", "test_string_truncation_warning", "(", ")", ":", "t", "=", "table", ".", "Table", "(", "[", "[", "'aa'", ",", "'bb'", "]", "]", ",", "names", "=", "[", "'a'", "]", ")", "with", "catch_warnings", "(", ")", "as", "w", ":", "from", "inspect", "import", "currentframe", ",", "getframeinfo", "t", "[", "'a'", "]", "[", "1", "]", "=", "'cc'", "assert", "(", "len", "(", "w", ")", "==", "0", ")", "t", "[", "'a'", "]", "[", ":", "]", "=", "'dd'", "assert", "(", "len", "(", "w", ")", "==", "0", ")", "with", "catch_warnings", "(", ")", "as", "w", ":", "frameinfo", "=", "getframeinfo", "(", "currentframe", "(", ")", ")", "t", "[", "'a'", "]", "[", "0", "]", "=", "'eee'", "assert", "(", "t", "[", "'a'", "]", "[", "0", "]", "==", "'ee'", ")", "assert", "(", "len", "(", "w", ")", "==", "1", ")", "assert", "(", "'truncated right side string(s) longer than 2 character(s)'", "in", "str", "(", "w", "[", "0", "]", ".", "message", ")", ")", "assert", "(", "w", "[", "0", "]", ".", "lineno", "==", "(", "frameinfo", ".", "lineno", "+", "1", ")", ")", "assert", "(", "w", "[", "0", "]", ".", "category", "is", "table", ".", "StringTruncateWarning", ")", "assert", "(", "'test_column'", "in", "w", "[", "0", "]", ".", "filename", ")", "with", "catch_warnings", "(", ")", "as", "w", ":", "t", "[", "'a'", "]", "[", ":", "]", "=", "[", "'ff'", ",", "'ggg'", "]", "assert", "np", ".", "all", "(", "(", "t", "[", "'a'", "]", "==", "[", "'ff'", ",", "'gg'", "]", ")", ")", "assert", "(", "len", "(", "w", ")", "==", "1", ")", "assert", "(", "'truncated right side string(s) longer than 2 character(s)'", "in", "str", "(", "w", "[", "0", "]", ".", "message", ")", ")" ]
test warnings associated with in-place assignment to a string column that results in truncation of the right hand side .
train
false
24,639
def p_field_req(p): if (len(p) == 2): p[0] = (p[1] == 'required') elif (len(p) == 1): p[0] = False
[ "def", "p_field_req", "(", "p", ")", ":", "if", "(", "len", "(", "p", ")", "==", "2", ")", ":", "p", "[", "0", "]", "=", "(", "p", "[", "1", "]", "==", "'required'", ")", "elif", "(", "len", "(", "p", ")", "==", "1", ")", ":", "p", "[", "0", "]", "=", "False" ]
field_req : required | optional .
train
false
24,641
def update_instance(instance): if ((not instance.config_drive) and required_by(instance)): instance.config_drive = True
[ "def", "update_instance", "(", "instance", ")", ":", "if", "(", "(", "not", "instance", ".", "config_drive", ")", "and", "required_by", "(", "instance", ")", ")", ":", "instance", ".", "config_drive", "=", "True" ]
update the instance config_drive setting if necessary the image or configuration file settings may override the default instance setting .
train
false
24,642
def etraceback(prep, exc_info): out = '' for line in traceback.format_exception(exc_info[0], exc_info[1], exc_info[2]): out += ('%s: %s' % (prep, line)) return out
[ "def", "etraceback", "(", "prep", ",", "exc_info", ")", ":", "out", "=", "''", "for", "line", "in", "traceback", ".", "format_exception", "(", "exc_info", "[", "0", "]", ",", "exc_info", "[", "1", "]", ",", "exc_info", "[", "2", "]", ")", ":", "out", "+=", "(", "'%s: %s'", "%", "(", "prep", ",", "line", ")", ")", "return", "out" ]
enhanced traceback formats traceback into lines "prep: line name: line" .
train
false
24,645
def test_saturate(): assert (saturate('#000', 20) == '#000') assert (saturate('#fff', 20) == '#fff') assert (saturate('#8a8', 100) == '#3f3') assert (saturate('#855', 20) == '#9e3f3f')
[ "def", "test_saturate", "(", ")", ":", "assert", "(", "saturate", "(", "'#000'", ",", "20", ")", "==", "'#000'", ")", "assert", "(", "saturate", "(", "'#fff'", ",", "20", ")", "==", "'#fff'", ")", "assert", "(", "saturate", "(", "'#8a8'", ",", "100", ")", "==", "'#3f3'", ")", "assert", "(", "saturate", "(", "'#855'", ",", "20", ")", "==", "'#9e3f3f'", ")" ]
test color saturation function .
train
false
24,646
def i18n_patterns(*urls, **kwargs): if (not settings.USE_I18N): return list(urls) prefix_default_language = kwargs.pop('prefix_default_language', True) assert (not kwargs), ('Unexpected kwargs for i18n_patterns(): %s' % kwargs) return [LocaleRegexURLResolver(list(urls), prefix_default_language=prefix_default_language)]
[ "def", "i18n_patterns", "(", "*", "urls", ",", "**", "kwargs", ")", ":", "if", "(", "not", "settings", ".", "USE_I18N", ")", ":", "return", "list", "(", "urls", ")", "prefix_default_language", "=", "kwargs", ".", "pop", "(", "'prefix_default_language'", ",", "True", ")", "assert", "(", "not", "kwargs", ")", ",", "(", "'Unexpected kwargs for i18n_patterns(): %s'", "%", "kwargs", ")", "return", "[", "LocaleRegexURLResolver", "(", "list", "(", "urls", ")", ",", "prefix_default_language", "=", "prefix_default_language", ")", "]" ]
adds the language code prefix to every url pattern within this function .
train
false
24,647
def addFacesByMeldedConvexLoops(faces, indexedLoops): if (len(indexedLoops) < 2): return for indexedLoopsIndex in xrange((len(indexedLoops) - 2)): FaceGenerator(faces, indexedLoops[indexedLoopsIndex], indexedLoops[(indexedLoopsIndex + 1)]) indexedLoopBottom = indexedLoops[(-2)] indexedLoopTop = indexedLoops[(-1)] if (len(indexedLoopTop) < 1): indexedLoopTop = indexedLoops[0] FaceGenerator(faces, indexedLoopBottom, indexedLoopTop)
[ "def", "addFacesByMeldedConvexLoops", "(", "faces", ",", "indexedLoops", ")", ":", "if", "(", "len", "(", "indexedLoops", ")", "<", "2", ")", ":", "return", "for", "indexedLoopsIndex", "in", "xrange", "(", "(", "len", "(", "indexedLoops", ")", "-", "2", ")", ")", ":", "FaceGenerator", "(", "faces", ",", "indexedLoops", "[", "indexedLoopsIndex", "]", ",", "indexedLoops", "[", "(", "indexedLoopsIndex", "+", "1", ")", "]", ")", "indexedLoopBottom", "=", "indexedLoops", "[", "(", "-", "2", ")", "]", "indexedLoopTop", "=", "indexedLoops", "[", "(", "-", "1", ")", "]", "if", "(", "len", "(", "indexedLoopTop", ")", "<", "1", ")", ":", "indexedLoopTop", "=", "indexedLoops", "[", "0", "]", "FaceGenerator", "(", "faces", ",", "indexedLoopBottom", ",", "indexedLoopTop", ")" ]
add faces from melded loops .
train
false
24,648
def get_permalink_ids_iter(self): permalink_id_key = self.settings['PERMALINK_ID_METADATA_KEY'] permalink_ids_raw = self.metadata.get(permalink_id_key, '') for permalink_id in permalink_ids_raw.split(','): if permalink_id: (yield permalink_id.strip())
[ "def", "get_permalink_ids_iter", "(", "self", ")", ":", "permalink_id_key", "=", "self", ".", "settings", "[", "'PERMALINK_ID_METADATA_KEY'", "]", "permalink_ids_raw", "=", "self", ".", "metadata", ".", "get", "(", "permalink_id_key", ",", "''", ")", "for", "permalink_id", "in", "permalink_ids_raw", ".", "split", "(", "','", ")", ":", "if", "permalink_id", ":", "(", "yield", "permalink_id", ".", "strip", "(", ")", ")" ]
method to get permalink ids from content .
train
true
24,649
def test_regression_5209(): time = Time(u'2015-01-01') moon = get_moon(time) new_coord = SkyCoord([moon]) assert_quantity_allclose(new_coord[0].distance, moon.distance)
[ "def", "test_regression_5209", "(", ")", ":", "time", "=", "Time", "(", "u'2015-01-01'", ")", "moon", "=", "get_moon", "(", "time", ")", "new_coord", "=", "SkyCoord", "(", "[", "moon", "]", ")", "assert_quantity_allclose", "(", "new_coord", "[", "0", "]", ".", "distance", ",", "moon", ".", "distance", ")" ]
check that distances are not lost on skycoord init .
train
false
24,651
def parse_timezone(text): if (not (text[0] in '+-')): raise ValueError(('Timezone must start with + or - (%(text)s)' % vars())) sign = text[:1] offset = int(text[1:]) if (sign == '-'): offset = (- offset) unnecessary_negative_timezone = ((offset >= 0) and (sign == '-')) signum = (((offset < 0) and (-1)) or 1) offset = abs(offset) hours = int((offset / 100)) minutes = (offset % 100) return ((signum * ((hours * 3600) + (minutes * 60))), unnecessary_negative_timezone)
[ "def", "parse_timezone", "(", "text", ")", ":", "if", "(", "not", "(", "text", "[", "0", "]", "in", "'+-'", ")", ")", ":", "raise", "ValueError", "(", "(", "'Timezone must start with + or - (%(text)s)'", "%", "vars", "(", ")", ")", ")", "sign", "=", "text", "[", ":", "1", "]", "offset", "=", "int", "(", "text", "[", "1", ":", "]", ")", "if", "(", "sign", "==", "'-'", ")", ":", "offset", "=", "(", "-", "offset", ")", "unnecessary_negative_timezone", "=", "(", "(", "offset", ">=", "0", ")", "and", "(", "sign", "==", "'-'", ")", ")", "signum", "=", "(", "(", "(", "offset", "<", "0", ")", "and", "(", "-", "1", ")", ")", "or", "1", ")", "offset", "=", "abs", "(", "offset", ")", "hours", "=", "int", "(", "(", "offset", "/", "100", ")", ")", "minutes", "=", "(", "offset", "%", "100", ")", "return", "(", "(", "signum", "*", "(", "(", "hours", "*", "3600", ")", "+", "(", "minutes", "*", "60", ")", ")", ")", ",", "unnecessary_negative_timezone", ")" ]
parses iso 8601 time zone specs into tzinfo offsets .
train
false
24,652
def show_all_categories(call=None): if (call == 'action'): raise SaltCloudSystemExit('The show_all_categories function must be called with -f or --function.') conn = get_conn(service='SoftLayer_Product_Package') categories = [] for category in conn.getCategories(id=50): categories.append(category['categoryCode']) return {'category_codes': categories}
[ "def", "show_all_categories", "(", "call", "=", "None", ")", ":", "if", "(", "call", "==", "'action'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The show_all_categories function must be called with -f or --function.'", ")", "conn", "=", "get_conn", "(", "service", "=", "'SoftLayer_Product_Package'", ")", "categories", "=", "[", "]", "for", "category", "in", "conn", ".", "getCategories", "(", "id", "=", "50", ")", ":", "categories", ".", "append", "(", "category", "[", "'categoryCode'", "]", ")", "return", "{", "'category_codes'", ":", "categories", "}" ]
return a dict of all available categories on the cloud provider .
train
true
24,653
def _make_safe_search_from_pb(safe_search): return SafeSearchAnnotation.from_pb(safe_search)
[ "def", "_make_safe_search_from_pb", "(", "safe_search", ")", ":", "return", "SafeSearchAnnotation", ".", "from_pb", "(", "safe_search", ")" ]
create safesearchannotation object from a protobuf response .
train
false
24,654
def get_previous_repository_reviews(app, repository, changeset_revision): repo = hg_util.get_repo_for_repository(app, repository=repository, repo_path=None, create=False) reviewed_revision_hashes = [review.changeset_revision for review in repository.reviews] previous_reviews_dict = odict() for changeset in hg_util.reversed_upper_bounded_changelog(repo, changeset_revision): previous_changeset_revision = str(repo.changectx(changeset)) if (previous_changeset_revision in reviewed_revision_hashes): (previous_rev, previous_changeset_revision_label) = hg_util.get_rev_label_from_changeset_revision(repo, previous_changeset_revision) revision_reviews = get_reviews_by_repository_id_changeset_revision(app, app.security.encode_id(repository.id), previous_changeset_revision) previous_reviews_dict[previous_changeset_revision] = dict(changeset_revision_label=previous_changeset_revision_label, reviews=revision_reviews) return previous_reviews_dict
[ "def", "get_previous_repository_reviews", "(", "app", ",", "repository", ",", "changeset_revision", ")", ":", "repo", "=", "hg_util", ".", "get_repo_for_repository", "(", "app", ",", "repository", "=", "repository", ",", "repo_path", "=", "None", ",", "create", "=", "False", ")", "reviewed_revision_hashes", "=", "[", "review", ".", "changeset_revision", "for", "review", "in", "repository", ".", "reviews", "]", "previous_reviews_dict", "=", "odict", "(", ")", "for", "changeset", "in", "hg_util", ".", "reversed_upper_bounded_changelog", "(", "repo", ",", "changeset_revision", ")", ":", "previous_changeset_revision", "=", "str", "(", "repo", ".", "changectx", "(", "changeset", ")", ")", "if", "(", "previous_changeset_revision", "in", "reviewed_revision_hashes", ")", ":", "(", "previous_rev", ",", "previous_changeset_revision_label", ")", "=", "hg_util", ".", "get_rev_label_from_changeset_revision", "(", "repo", ",", "previous_changeset_revision", ")", "revision_reviews", "=", "get_reviews_by_repository_id_changeset_revision", "(", "app", ",", "app", ".", "security", ".", "encode_id", "(", "repository", ".", "id", ")", ",", "previous_changeset_revision", ")", "previous_reviews_dict", "[", "previous_changeset_revision", "]", "=", "dict", "(", "changeset_revision_label", "=", "previous_changeset_revision_label", ",", "reviews", "=", "revision_reviews", ")", "return", "previous_reviews_dict" ]
return an ordered dictionary of repository reviews up to and including the received changeset revision .
train
false
24,657
def new_limit(): ArticleCache.do.new_limit(cfg.cache_limit.get_int())
[ "def", "new_limit", "(", ")", ":", "ArticleCache", ".", "do", ".", "new_limit", "(", "cfg", ".", "cache_limit", ".", "get_int", "(", ")", ")" ]
callback for article cache changes .
train
false
24,658
def elasticsearch_client(conf): es_conn_conf = build_es_conn_config(conf) auth = Auth() es_conn_conf['http_auth'] = auth(host=es_conn_conf['es_host'], username=es_conn_conf['es_username'], password=es_conn_conf['es_password'], aws_region=es_conn_conf['aws_region'], boto_profile=es_conn_conf['boto_profile']) return Elasticsearch(host=es_conn_conf['es_host'], port=es_conn_conf['es_port'], url_prefix=es_conn_conf['es_url_prefix'], use_ssl=es_conn_conf['use_ssl'], verify_certs=es_conn_conf['verify_certs'], connection_class=RequestsHttpConnection, http_auth=es_conn_conf['http_auth'], timeout=es_conn_conf['es_conn_timeout'], send_get_body_as=es_conn_conf['send_get_body_as'])
[ "def", "elasticsearch_client", "(", "conf", ")", ":", "es_conn_conf", "=", "build_es_conn_config", "(", "conf", ")", "auth", "=", "Auth", "(", ")", "es_conn_conf", "[", "'http_auth'", "]", "=", "auth", "(", "host", "=", "es_conn_conf", "[", "'es_host'", "]", ",", "username", "=", "es_conn_conf", "[", "'es_username'", "]", ",", "password", "=", "es_conn_conf", "[", "'es_password'", "]", ",", "aws_region", "=", "es_conn_conf", "[", "'aws_region'", "]", ",", "boto_profile", "=", "es_conn_conf", "[", "'boto_profile'", "]", ")", "return", "Elasticsearch", "(", "host", "=", "es_conn_conf", "[", "'es_host'", "]", ",", "port", "=", "es_conn_conf", "[", "'es_port'", "]", ",", "url_prefix", "=", "es_conn_conf", "[", "'es_url_prefix'", "]", ",", "use_ssl", "=", "es_conn_conf", "[", "'use_ssl'", "]", ",", "verify_certs", "=", "es_conn_conf", "[", "'verify_certs'", "]", ",", "connection_class", "=", "RequestsHttpConnection", ",", "http_auth", "=", "es_conn_conf", "[", "'http_auth'", "]", ",", "timeout", "=", "es_conn_conf", "[", "'es_conn_timeout'", "]", ",", "send_get_body_as", "=", "es_conn_conf", "[", "'send_get_body_as'", "]", ")" ]
returns an elasticsearch instance configured using an es_conn_config .
train
false
24,660
def _parse(template): parser = Parser(template) parser.parse_expression() parts = parser.parts remainder = parser.string[parser.pos:] if remainder: parts.append(remainder) return Expression(parts)
[ "def", "_parse", "(", "template", ")", ":", "parser", "=", "Parser", "(", "template", ")", "parser", ".", "parse_expression", "(", ")", "parts", "=", "parser", ".", "parts", "remainder", "=", "parser", ".", "string", "[", "parser", ".", "pos", ":", "]", "if", "remainder", ":", "parts", ".", "append", "(", "remainder", ")", "return", "Expression", "(", "parts", ")" ]
parse metadata yaml .
train
true
24,661
def get_load(jid): query = 'SELECT load FROM salt.jids WHERE jid = ?;' ret = {} try: data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_load', [jid]) if data: load = data[0].get('load') if load: ret = json.loads(load) except CommandExecutionError: log.critical('Could not get load from jids table.') raise except Exception as e: log.critical('Unexpected error while getting load from jids: {0}'.format(str(e))) raise return ret
[ "def", "get_load", "(", "jid", ")", ":", "query", "=", "'SELECT load FROM salt.jids WHERE jid = ?;'", "ret", "=", "{", "}", "try", ":", "data", "=", "__salt__", "[", "'cassandra_cql.cql_query_with_prepare'", "]", "(", "query", ",", "'get_load'", ",", "[", "jid", "]", ")", "if", "data", ":", "load", "=", "data", "[", "0", "]", ".", "get", "(", "'load'", ")", "if", "load", ":", "ret", "=", "json", ".", "loads", "(", "load", ")", "except", "CommandExecutionError", ":", "log", ".", "critical", "(", "'Could not get load from jids table.'", ")", "raise", "except", "Exception", "as", "e", ":", "log", ".", "critical", "(", "'Unexpected error while getting load from jids: {0}'", ".", "format", "(", "str", "(", "e", ")", ")", ")", "raise", "return", "ret" ]
return the load from a specified jid .
train
false
24,663
def HaveGoodGUI(): return ('pywin.framework.startup' in sys.modules)
[ "def", "HaveGoodGUI", "(", ")", ":", "return", "(", "'pywin.framework.startup'", "in", "sys", ".", "modules", ")" ]
returns true if we currently have a good gui available .
train
false
24,665
def get_examples(section_div, examples_class): example = section_div.find('div', attrs={'class': examples_class}) if example: return example.text.strip() return
[ "def", "get_examples", "(", "section_div", ",", "examples_class", ")", ":", "example", "=", "section_div", ".", "find", "(", "'div'", ",", "attrs", "=", "{", "'class'", ":", "examples_class", "}", ")", "if", "example", ":", "return", "example", ".", "text", ".", "strip", "(", ")", "return" ]
parse and return the examples of the documentation topic .
train
false
24,668
def factorial_notation(tokens, local_dict, global_dict): result = [] prevtoken = '' for (toknum, tokval) in tokens: if (toknum == OP): op = tokval if (op == '!!'): if ((prevtoken == '!') or (prevtoken == '!!')): raise TokenError result = _add_factorial_tokens('factorial2', result) elif (op == '!'): if ((prevtoken == '!') or (prevtoken == '!!')): raise TokenError result = _add_factorial_tokens('factorial', result) else: result.append((OP, op)) else: result.append((toknum, tokval)) prevtoken = tokval return result
[ "def", "factorial_notation", "(", "tokens", ",", "local_dict", ",", "global_dict", ")", ":", "result", "=", "[", "]", "prevtoken", "=", "''", "for", "(", "toknum", ",", "tokval", ")", "in", "tokens", ":", "if", "(", "toknum", "==", "OP", ")", ":", "op", "=", "tokval", "if", "(", "op", "==", "'!!'", ")", ":", "if", "(", "(", "prevtoken", "==", "'!'", ")", "or", "(", "prevtoken", "==", "'!!'", ")", ")", ":", "raise", "TokenError", "result", "=", "_add_factorial_tokens", "(", "'factorial2'", ",", "result", ")", "elif", "(", "op", "==", "'!'", ")", ":", "if", "(", "(", "prevtoken", "==", "'!'", ")", "or", "(", "prevtoken", "==", "'!!'", ")", ")", ":", "raise", "TokenError", "result", "=", "_add_factorial_tokens", "(", "'factorial'", ",", "result", ")", "else", ":", "result", ".", "append", "(", "(", "OP", ",", "op", ")", ")", "else", ":", "result", ".", "append", "(", "(", "toknum", ",", "tokval", ")", ")", "prevtoken", "=", "tokval", "return", "result" ]
allows standard notation for factorial .
train
false
24,669
@cmd def test_process(): install() sh(('%s -m unittest -v psutil.tests.test_process' % PYTHON))
[ "@", "cmd", "def", "test_process", "(", ")", ":", "install", "(", ")", "sh", "(", "(", "'%s -m unittest -v psutil.tests.test_process'", "%", "PYTHON", ")", ")" ]
run process tests .
train
false
24,674
def _split_line(s, parts): out = {} start = 0 for (name, length) in parts: out[name] = s[start:(start + length)].strip() start += length del out['_'] return out
[ "def", "_split_line", "(", "s", ",", "parts", ")", ":", "out", "=", "{", "}", "start", "=", "0", "for", "(", "name", ",", "length", ")", "in", "parts", ":", "out", "[", "name", "]", "=", "s", "[", "start", ":", "(", "start", "+", "length", ")", "]", ".", "strip", "(", ")", "start", "+=", "length", "del", "out", "[", "'_'", "]", "return", "out" ]
parameters s: string fixed-length string to split parts: list of pairs used to break up string .
train
true
24,675
def _remove_unsupported_archs(_config_vars): if ('CC' in os.environ): return _config_vars if (re.search('-arch\\s+ppc', _config_vars['CFLAGS']) is not None): status = os.system(("echo 'int main{};' | '%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null" % (_config_vars['CC'].replace("'", '\'"\'"\''),))) if status: for cv in _UNIVERSAL_CONFIG_VARS: if ((cv in _config_vars) and (cv not in os.environ)): flags = _config_vars[cv] flags = re.sub('-arch\\s+ppc\\w*\\s', ' ', flags) _save_modified_value(_config_vars, cv, flags) return _config_vars
[ "def", "_remove_unsupported_archs", "(", "_config_vars", ")", ":", "if", "(", "'CC'", "in", "os", ".", "environ", ")", ":", "return", "_config_vars", "if", "(", "re", ".", "search", "(", "'-arch\\\\s+ppc'", ",", "_config_vars", "[", "'CFLAGS'", "]", ")", "is", "not", "None", ")", ":", "status", "=", "os", ".", "system", "(", "(", "\"echo 'int main{};' | '%s' -c -arch ppc -x c -o /dev/null /dev/null 2>/dev/null\"", "%", "(", "_config_vars", "[", "'CC'", "]", ".", "replace", "(", "\"'\"", ",", "'\\'\"\\'\"\\''", ")", ",", ")", ")", ")", "if", "status", ":", "for", "cv", "in", "_UNIVERSAL_CONFIG_VARS", ":", "if", "(", "(", "cv", "in", "_config_vars", ")", "and", "(", "cv", "not", "in", "os", ".", "environ", ")", ")", ":", "flags", "=", "_config_vars", "[", "cv", "]", "flags", "=", "re", ".", "sub", "(", "'-arch\\\\s+ppc\\\\w*\\\\s'", ",", "' '", ",", "flags", ")", "_save_modified_value", "(", "_config_vars", ",", "cv", ",", "flags", ")", "return", "_config_vars" ]
remove any unsupported archs from config vars .
train
false
24,676
def force_reload(name): cmd = ['service', name, 'force-reload'] return (not __salt__['cmd.retcode'](cmd, python_shell=False))
[ "def", "force_reload", "(", "name", ")", ":", "cmd", "=", "[", "'service'", ",", "name", ",", "'force-reload'", "]", "return", "(", "not", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", ")" ]
force-reload the named service cli example: .
train
false
24,677
def libvlc_media_parse(p_md): f = (_Cfunctions.get('libvlc_media_parse', None) or _Cfunction('libvlc_media_parse', ((1,),), None, None, Media)) return f(p_md)
[ "def", "libvlc_media_parse", "(", "p_md", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_parse'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_parse'", ",", "(", "(", "1", ",", ")", ",", ")", ",", "None", ",", "None", ",", "Media", ")", ")", "return", "f", "(", "p_md", ")" ]
parse a media .
train
false
24,678
def make_traceback(exc_info, source_hint=None): (exc_type, exc_value, tb) = exc_info if isinstance(exc_value, TemplateSyntaxError): exc_info = translate_syntax_error(exc_value, source_hint) initial_skip = 0 else: initial_skip = 1 return translate_exception(exc_info, initial_skip)
[ "def", "make_traceback", "(", "exc_info", ",", "source_hint", "=", "None", ")", ":", "(", "exc_type", ",", "exc_value", ",", "tb", ")", "=", "exc_info", "if", "isinstance", "(", "exc_value", ",", "TemplateSyntaxError", ")", ":", "exc_info", "=", "translate_syntax_error", "(", "exc_value", ",", "source_hint", ")", "initial_skip", "=", "0", "else", ":", "initial_skip", "=", "1", "return", "translate_exception", "(", "exc_info", ",", "initial_skip", ")" ]
creates a processed traceback object from the exc_info .
train
true
24,679
@register.tag('capture') def do_capture(parser, token): bits = token.split_contents() if (len(bits) != 3): raise template.TemplateSyntaxError("'capture' node requires `as (variable name)`.") nodelist = parser.parse(('endcapture',)) parser.delete_first_token() return CaptureNode(nodelist, bits[2])
[ "@", "register", ".", "tag", "(", "'capture'", ")", "def", "do_capture", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "(", "len", "(", "bits", ")", "!=", "3", ")", ":", "raise", "template", ".", "TemplateSyntaxError", "(", "\"'capture' node requires `as (variable name)`.\"", ")", "nodelist", "=", "parser", ".", "parse", "(", "(", "'endcapture'", ",", ")", ")", "parser", ".", "delete_first_token", "(", ")", "return", "CaptureNode", "(", "nodelist", ",", "bits", "[", "2", "]", ")" ]
captures content into a context variable .
train
false
24,681
def _FindIndexToUse(query, indexes): if (not query.has_kind()): return None index_list = __IndexListForQuery(query) if (index_list == []): return None index_match = index_list[0] for index in indexes: if index_match.Equals(index.definition()): return index raise apiproxy_errors.ApplicationError(datastore_pb.Error.NEED_INDEX, 'Query requires an index')
[ "def", "_FindIndexToUse", "(", "query", ",", "indexes", ")", ":", "if", "(", "not", "query", ".", "has_kind", "(", ")", ")", ":", "return", "None", "index_list", "=", "__IndexListForQuery", "(", "query", ")", "if", "(", "index_list", "==", "[", "]", ")", ":", "return", "None", "index_match", "=", "index_list", "[", "0", "]", "for", "index", "in", "indexes", ":", "if", "index_match", ".", "Equals", "(", "index", ".", "definition", "(", ")", ")", ":", "return", "index", "raise", "apiproxy_errors", ".", "ApplicationError", "(", "datastore_pb", ".", "Error", ".", "NEED_INDEX", ",", "'Query requires an index'", ")" ]
matches the query with one of the composite indexes .
train
false
24,682
@contextlib.contextmanager def _refcounting(type_): gc.collect() refcount = len(objgraph.by_type(type_)) (yield refcount) gc.collect() assert (len(objgraph.by_type(type_)) <= refcount), 'More {0!r} objects still in memory than before.'
[ "@", "contextlib", ".", "contextmanager", "def", "_refcounting", "(", "type_", ")", ":", "gc", ".", "collect", "(", ")", "refcount", "=", "len", "(", "objgraph", ".", "by_type", "(", "type_", ")", ")", "(", "yield", "refcount", ")", "gc", ".", "collect", "(", ")", "assert", "(", "len", "(", "objgraph", ".", "by_type", "(", "type_", ")", ")", "<=", "refcount", ")", ",", "'More {0!r} objects still in memory than before.'" ]
perform the body of a with statement with reference counting for the given type --raises an assertion error if there are more unfreed objects of the given type than when we entered the with statement .
train
false
24,684
def getDistanceToLine(begin, end, point): pointMinusBegin = (point - begin) if (begin == end): return abs(pointMinusBegin) endMinusBegin = (end - begin) return (abs(endMinusBegin.cross(pointMinusBegin)) / abs(endMinusBegin))
[ "def", "getDistanceToLine", "(", "begin", ",", "end", ",", "point", ")", ":", "pointMinusBegin", "=", "(", "point", "-", "begin", ")", "if", "(", "begin", "==", "end", ")", ":", "return", "abs", "(", "pointMinusBegin", ")", "endMinusBegin", "=", "(", "end", "-", "begin", ")", "return", "(", "abs", "(", "endMinusBegin", ".", "cross", "(", "pointMinusBegin", ")", ")", "/", "abs", "(", "endMinusBegin", ")", ")" ]
get the distance from a vector3 point to an infinite line .
train
false
24,689
def MakeFrames(): preg = nsfg.ReadFemPreg() live = preg[(preg.outcome == 1)] firsts = live[(live.birthord == 1)] others = live[(live.birthord != 1)] assert (len(live) == 9148) assert (len(firsts) == 4413) assert (len(others) == 4735) return (live, firsts, others)
[ "def", "MakeFrames", "(", ")", ":", "preg", "=", "nsfg", ".", "ReadFemPreg", "(", ")", "live", "=", "preg", "[", "(", "preg", ".", "outcome", "==", "1", ")", "]", "firsts", "=", "live", "[", "(", "live", ".", "birthord", "==", "1", ")", "]", "others", "=", "live", "[", "(", "live", ".", "birthord", "!=", "1", ")", "]", "assert", "(", "len", "(", "live", ")", "==", "9148", ")", "assert", "(", "len", "(", "firsts", ")", "==", "4413", ")", "assert", "(", "len", "(", "others", ")", "==", "4735", ")", "return", "(", "live", ",", "firsts", ",", "others", ")" ]
reads pregnancy data and partitions first babies and others .
train
false
24,692
def parseAttributes(attrStr=None): attrs = {} if (attrStr is not None): for token in attrStr.split(): if ('=' in token): (key, value) = token.split('=', 1) else: (key, value) = (token, 1) attrs[key] = value return attrs
[ "def", "parseAttributes", "(", "attrStr", "=", "None", ")", ":", "attrs", "=", "{", "}", "if", "(", "attrStr", "is", "not", "None", ")", ":", "for", "token", "in", "attrStr", ".", "split", "(", ")", ":", "if", "(", "'='", "in", "token", ")", ":", "(", "key", ",", "value", ")", "=", "token", ".", "split", "(", "'='", ",", "1", ")", "else", ":", "(", "key", ",", "value", ")", "=", "(", "token", ",", "1", ")", "attrs", "[", "key", "]", "=", "value", "return", "attrs" ]
parse the given attributes string into an attribute dict .
train
false
24,695
def _get_elem_at_rank(rank, data, n_negative, n_zeros): if (rank < n_negative): return data[rank] if ((rank - n_negative) < n_zeros): return 0 return data[(rank - n_zeros)]
[ "def", "_get_elem_at_rank", "(", "rank", ",", "data", ",", "n_negative", ",", "n_zeros", ")", ":", "if", "(", "rank", "<", "n_negative", ")", ":", "return", "data", "[", "rank", "]", "if", "(", "(", "rank", "-", "n_negative", ")", "<", "n_zeros", ")", ":", "return", "0", "return", "data", "[", "(", "rank", "-", "n_zeros", ")", "]" ]
find the value in data augmented with n_zeros for the given rank .
train
false
24,697
def req_job_run(r, **attr): if r.interactive: if r.id: current.s3task.async('req_add_from_template', [r.id], {'user_id': current.auth.user.id}) current.session.confirmation = current.T('Request added') r.component_id = None redirect(r.url(method=''))
[ "def", "req_job_run", "(", "r", ",", "**", "attr", ")", ":", "if", "r", ".", "interactive", ":", "if", "r", ".", "id", ":", "current", ".", "s3task", ".", "async", "(", "'req_add_from_template'", ",", "[", "r", ".", "id", "]", ",", "{", "'user_id'", ":", "current", ".", "auth", ".", "user", ".", "id", "}", ")", "current", ".", "session", ".", "confirmation", "=", "current", ".", "T", "(", "'Request added'", ")", "r", ".", "component_id", "=", "None", "redirect", "(", "r", ".", "url", "(", "method", "=", "''", ")", ")" ]
restful method to run a job now .
train
false
24,698
def renewal_filename_for_lineagename(config, lineagename): return (os.path.join(config.renewal_configs_dir, lineagename) + '.conf')
[ "def", "renewal_filename_for_lineagename", "(", "config", ",", "lineagename", ")", ":", "return", "(", "os", ".", "path", ".", "join", "(", "config", ".", "renewal_configs_dir", ",", "lineagename", ")", "+", "'.conf'", ")" ]
returns the lineagename for a configuration filename .
train
false
24,699
def Parse(query): parser = CreateParser(query) try: return parser.query() except Exception as e: msg = ("%s in query '%s'" % (e.message, query)) raise QueryException(msg)
[ "def", "Parse", "(", "query", ")", ":", "parser", "=", "CreateParser", "(", "query", ")", "try", ":", "return", "parser", ".", "query", "(", ")", "except", "Exception", "as", "e", ":", "msg", "=", "(", "\"%s in query '%s'\"", "%", "(", "e", ".", "message", ",", "query", ")", ")", "raise", "QueryException", "(", "msg", ")" ]
parses an expression and returns the antlr tree .
train
false
24,700
def libvlc_media_player_set_xwindow(p_mi, drawable): f = (_Cfunctions.get('libvlc_media_player_set_xwindow', None) or _Cfunction('libvlc_media_player_set_xwindow', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_uint32)) return f(p_mi, drawable)
[ "def", "libvlc_media_player_set_xwindow", "(", "p_mi", ",", "drawable", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_player_set_xwindow'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_player_set_xwindow'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ")", ",", "None", ",", "None", ",", "MediaPlayer", ",", "ctypes", ".", "c_uint32", ")", ")", "return", "f", "(", "p_mi", ",", "drawable", ")" ]
set an x window system drawable where the media player should render its video output .
train
true
24,701
def deprecated_call(func=None, *args, **kwargs): if (not func): return WarningsChecker(expected_warning=DeprecationWarning) categories = [] def warn_explicit(message, category, *args, **kwargs): categories.append(category) old_warn_explicit(message, category, *args, **kwargs) def warn(message, category=None, *args, **kwargs): if isinstance(message, Warning): categories.append(message.__class__) else: categories.append(category) old_warn(message, category, *args, **kwargs) old_warn = warnings.warn old_warn_explicit = warnings.warn_explicit warnings.warn_explicit = warn_explicit warnings.warn = warn try: ret = func(*args, **kwargs) finally: warnings.warn_explicit = old_warn_explicit warnings.warn = old_warn deprecation_categories = (DeprecationWarning, PendingDeprecationWarning) if (not any((issubclass(c, deprecation_categories) for c in categories))): __tracebackhide__ = True raise AssertionError(('%r did not produce DeprecationWarning' % (func,))) return ret
[ "def", "deprecated_call", "(", "func", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "not", "func", ")", ":", "return", "WarningsChecker", "(", "expected_warning", "=", "DeprecationWarning", ")", "categories", "=", "[", "]", "def", "warn_explicit", "(", "message", ",", "category", ",", "*", "args", ",", "**", "kwargs", ")", ":", "categories", ".", "append", "(", "category", ")", "old_warn_explicit", "(", "message", ",", "category", ",", "*", "args", ",", "**", "kwargs", ")", "def", "warn", "(", "message", ",", "category", "=", "None", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "isinstance", "(", "message", ",", "Warning", ")", ":", "categories", ".", "append", "(", "message", ".", "__class__", ")", "else", ":", "categories", ".", "append", "(", "category", ")", "old_warn", "(", "message", ",", "category", ",", "*", "args", ",", "**", "kwargs", ")", "old_warn", "=", "warnings", ".", "warn", "old_warn_explicit", "=", "warnings", ".", "warn_explicit", "warnings", ".", "warn_explicit", "=", "warn_explicit", "warnings", ".", "warn", "=", "warn", "try", ":", "ret", "=", "func", "(", "*", "args", ",", "**", "kwargs", ")", "finally", ":", "warnings", ".", "warn_explicit", "=", "old_warn_explicit", "warnings", ".", "warn", "=", "old_warn", "deprecation_categories", "=", "(", "DeprecationWarning", ",", "PendingDeprecationWarning", ")", "if", "(", "not", "any", "(", "(", "issubclass", "(", "c", ",", "deprecation_categories", ")", "for", "c", "in", "categories", ")", ")", ")", ":", "__tracebackhide__", "=", "True", "raise", "AssertionError", "(", "(", "'%r did not produce DeprecationWarning'", "%", "(", "func", ",", ")", ")", ")", "return", "ret" ]
assert that calling func triggers a deprecationwarning or pendingdeprecationwarning .
train
false
24,703
def _collect_facts(resource): facts = {'identifier': resource['ClusterIdentifier'], 'create_time': resource['ClusterCreateTime'], 'status': resource['ClusterStatus'], 'username': resource['MasterUsername'], 'db_name': resource['DBName'], 'availability_zone': resource['AvailabilityZone'], 'maintenance_window': resource['PreferredMaintenanceWindow']} for node in resource['ClusterNodes']: if (node['NodeRole'] in ('SHARED', 'LEADER')): facts['private_ip_address'] = node['PrivateIPAddress'] break return facts
[ "def", "_collect_facts", "(", "resource", ")", ":", "facts", "=", "{", "'identifier'", ":", "resource", "[", "'ClusterIdentifier'", "]", ",", "'create_time'", ":", "resource", "[", "'ClusterCreateTime'", "]", ",", "'status'", ":", "resource", "[", "'ClusterStatus'", "]", ",", "'username'", ":", "resource", "[", "'MasterUsername'", "]", ",", "'db_name'", ":", "resource", "[", "'DBName'", "]", ",", "'availability_zone'", ":", "resource", "[", "'AvailabilityZone'", "]", ",", "'maintenance_window'", ":", "resource", "[", "'PreferredMaintenanceWindow'", "]", "}", "for", "node", "in", "resource", "[", "'ClusterNodes'", "]", ":", "if", "(", "node", "[", "'NodeRole'", "]", "in", "(", "'SHARED'", ",", "'LEADER'", ")", ")", ":", "facts", "[", "'private_ip_address'", "]", "=", "node", "[", "'PrivateIPAddress'", "]", "break", "return", "facts" ]
transfrom cluster information to dict .
train
false
24,704
def copy_index_vector(a, b, index, inplace=False, prefix=None): if (prefix is None): prefix = find_best_blas_type((a, b))[0] copy = prefix_copy_index_vector_map[prefix] if (not inplace): b = np.copy(b, order='F') try: if (not a.is_f_contig()): raise ValueError() except: a = np.asfortranarray(a) copy(a, b, np.asfortranarray(index)) return b
[ "def", "copy_index_vector", "(", "a", ",", "b", ",", "index", ",", "inplace", "=", "False", ",", "prefix", "=", "None", ")", ":", "if", "(", "prefix", "is", "None", ")", ":", "prefix", "=", "find_best_blas_type", "(", "(", "a", ",", "b", ")", ")", "[", "0", "]", "copy", "=", "prefix_copy_index_vector_map", "[", "prefix", "]", "if", "(", "not", "inplace", ")", ":", "b", "=", "np", ".", "copy", "(", "b", ",", "order", "=", "'F'", ")", "try", ":", "if", "(", "not", "a", ".", "is_f_contig", "(", ")", ")", ":", "raise", "ValueError", "(", ")", "except", ":", "a", "=", "np", ".", "asfortranarray", "(", "a", ")", "copy", "(", "a", ",", "b", ",", "np", ".", "asfortranarray", "(", "index", ")", ")", "return", "b" ]
reorder the elements of a time-varying vector where all non-index values are in the first elements of the vector .
train
false
24,705
def resize_plot_item_list(lst, size, item_type, parent): n = len(lst) if (n > size): for i in lst[size:]: i.setParentItem(None) if i.scene(): i.scene().removeItem(i) del lst[size:] elif (n < size): lst.extend((item_type(parent) for i in range((size - n))))
[ "def", "resize_plot_item_list", "(", "lst", ",", "size", ",", "item_type", ",", "parent", ")", ":", "n", "=", "len", "(", "lst", ")", "if", "(", "n", ">", "size", ")", ":", "for", "i", "in", "lst", "[", "size", ":", "]", ":", "i", ".", "setParentItem", "(", "None", ")", "if", "i", ".", "scene", "(", ")", ":", "i", ".", "scene", "(", ")", ".", "removeItem", "(", "i", ")", "del", "lst", "[", "size", ":", "]", "elif", "(", "n", "<", "size", ")", ":", "lst", ".", "extend", "(", "(", "item_type", "(", "parent", ")", "for", "i", "in", "range", "(", "(", "size", "-", "n", ")", ")", ")", ")" ]
efficiently resizes a list of qgraphicsitems .
train
false
24,706
def raises_msg(exc, msg, func, *args, **kwds): with pytest.raises(exc) as excinfo: func(*args, **kwds) assert (msg in str(excinfo.value))
[ "def", "raises_msg", "(", "exc", ",", "msg", ",", "func", ",", "*", "args", ",", "**", "kwds", ")", ":", "with", "pytest", ".", "raises", "(", "exc", ")", "as", "excinfo", ":", "func", "(", "*", "args", ",", "**", "kwds", ")", "assert", "(", "msg", "in", "str", "(", "excinfo", ".", "value", ")", ")" ]
raise :exc:assertionerror if func does not raise *exc* .
train
false
24,708
def is_hash_empty(context, builder, h): empty = ir.Constant(h.type, EMPTY) return builder.icmp_unsigned('==', h, empty)
[ "def", "is_hash_empty", "(", "context", ",", "builder", ",", "h", ")", ":", "empty", "=", "ir", ".", "Constant", "(", "h", ".", "type", ",", "EMPTY", ")", "return", "builder", ".", "icmp_unsigned", "(", "'=='", ",", "h", ",", "empty", ")" ]
whether the hash value denotes an empty entry .
train
false
24,710
def nochange(function): function.NO_CHANGE = True return function
[ "def", "nochange", "(", "function", ")", ":", "function", ".", "NO_CHANGE", "=", "True", "return", "function" ]
decorator for benchmarks that do not change the xml tree .
train
false
24,711
def to_list(x, default=None): if (x is None): return default if (not isinstance(x, (list, tuple))): return [x] else: return x
[ "def", "to_list", "(", "x", ",", "default", "=", "None", ")", ":", "if", "(", "x", "is", "None", ")", ":", "return", "default", "if", "(", "not", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ")", ":", "return", "[", "x", "]", "else", ":", "return", "x" ]
converts an arbitrary object c{obj} to a c{list} .
train
true
24,712
def make_lsq_full_matrix(x, y, t, k=3): (x, y, t) = map(np.asarray, (x, y, t)) m = x.size n = ((t.size - k) - 1) A = np.zeros((m, n), dtype=np.float_) for j in range(m): xval = x[j] if (xval == t[k]): left = k else: left = (np.searchsorted(t, xval) - 1) bb = _bspl.evaluate_all_bspl(t, k, xval, left) A[j, (left - k):(left + 1)] = bb B = np.dot(A.T, A) Y = np.dot(A.T, y) c = sl.solve(B, Y) return (c, (A, Y))
[ "def", "make_lsq_full_matrix", "(", "x", ",", "y", ",", "t", ",", "k", "=", "3", ")", ":", "(", "x", ",", "y", ",", "t", ")", "=", "map", "(", "np", ".", "asarray", ",", "(", "x", ",", "y", ",", "t", ")", ")", "m", "=", "x", ".", "size", "n", "=", "(", "(", "t", ".", "size", "-", "k", ")", "-", "1", ")", "A", "=", "np", ".", "zeros", "(", "(", "m", ",", "n", ")", ",", "dtype", "=", "np", ".", "float_", ")", "for", "j", "in", "range", "(", "m", ")", ":", "xval", "=", "x", "[", "j", "]", "if", "(", "xval", "==", "t", "[", "k", "]", ")", ":", "left", "=", "k", "else", ":", "left", "=", "(", "np", ".", "searchsorted", "(", "t", ",", "xval", ")", "-", "1", ")", "bb", "=", "_bspl", ".", "evaluate_all_bspl", "(", "t", ",", "k", ",", "xval", ",", "left", ")", "A", "[", "j", ",", "(", "left", "-", "k", ")", ":", "(", "left", "+", "1", ")", "]", "=", "bb", "B", "=", "np", ".", "dot", "(", "A", ".", "T", ",", "A", ")", "Y", "=", "np", ".", "dot", "(", "A", ".", "T", ",", "y", ")", "c", "=", "sl", ".", "solve", "(", "B", ",", "Y", ")", "return", "(", "c", ",", "(", "A", ",", "Y", ")", ")" ]
make the least-square spline .
train
false
24,713
def iso_to_plotly_time_string(iso_string): if ((iso_string.split('-')[:3] is '00:00') or (iso_string.split('+')[0] is '00:00')): raise Exception("Plotly won't accept timestrings with timezone info.\nAll timestrings are assumed to be in UTC.") iso_string = iso_string.replace('-00:00', '').replace('+00:00', '') if iso_string.endswith('T00:00:00'): return iso_string.replace('T00:00:00', '') else: return iso_string.replace('T', ' ')
[ "def", "iso_to_plotly_time_string", "(", "iso_string", ")", ":", "if", "(", "(", "iso_string", ".", "split", "(", "'-'", ")", "[", ":", "3", "]", "is", "'00:00'", ")", "or", "(", "iso_string", ".", "split", "(", "'+'", ")", "[", "0", "]", "is", "'00:00'", ")", ")", ":", "raise", "Exception", "(", "\"Plotly won't accept timestrings with timezone info.\\nAll timestrings are assumed to be in UTC.\"", ")", "iso_string", "=", "iso_string", ".", "replace", "(", "'-00:00'", ",", "''", ")", ".", "replace", "(", "'+00:00'", ",", "''", ")", "if", "iso_string", ".", "endswith", "(", "'T00:00:00'", ")", ":", "return", "iso_string", ".", "replace", "(", "'T00:00:00'", ",", "''", ")", "else", ":", "return", "iso_string", ".", "replace", "(", "'T'", ",", "' '", ")" ]
remove timezone info and replace t delimeter with .
train
false
24,714
def fixup_for_packaged(): if exists(join(ROOT, 'PKG-INFOvi ')): if (('--build-js' in sys.argv) or ('--install-js' in sys.argv)): print(SDIST_BUILD_WARNING) if ('--build-js' in sys.argv): sys.argv.remove('--build-js') if ('--install-js' in sys.argv): sys.argv.remove('--install-js') if ('--existing-js' not in sys.argv): sys.argv.append('--existing-js')
[ "def", "fixup_for_packaged", "(", ")", ":", "if", "exists", "(", "join", "(", "ROOT", ",", "'PKG-INFOvi '", ")", ")", ":", "if", "(", "(", "'--build-js'", "in", "sys", ".", "argv", ")", "or", "(", "'--install-js'", "in", "sys", ".", "argv", ")", ")", ":", "print", "(", "SDIST_BUILD_WARNING", ")", "if", "(", "'--build-js'", "in", "sys", ".", "argv", ")", ":", "sys", ".", "argv", ".", "remove", "(", "'--build-js'", ")", "if", "(", "'--install-js'", "in", "sys", ".", "argv", ")", ":", "sys", ".", "argv", ".", "remove", "(", "'--install-js'", ")", "if", "(", "'--existing-js'", "not", "in", "sys", ".", "argv", ")", ":", "sys", ".", "argv", ".", "append", "(", "'--existing-js'", ")" ]
if we are installing from an sdist .
train
true
24,717
def clean_savepoints(using=None): get_connection(using).clean_savepoints()
[ "def", "clean_savepoints", "(", "using", "=", "None", ")", ":", "get_connection", "(", "using", ")", ".", "clean_savepoints", "(", ")" ]
resets the counter used to generate unique savepoint ids in this thread .
train
false
24,718
def init(mpstate): return SerialModule(mpstate)
[ "def", "init", "(", "mpstate", ")", ":", "return", "SerialModule", "(", "mpstate", ")" ]
initialise module .
train
false
24,719
def compound_statements(logical_line): line = logical_line last_char = (len(line) - 1) found = line.find(':') while ((-1) < found < last_char): before = line[:found] if ((before.count('{') <= before.count('}')) and (before.count('[') <= before.count(']')) and (before.count('(') <= before.count(')'))): lambda_kw = LAMBDA_REGEX.search(before) if lambda_kw: before = line[:lambda_kw.start()].rstrip() if ((before[(-1):] == '=') and isidentifier(before[:(-1)].strip())): (yield (0, 'E731 do not assign a lambda expression, use a def')) break if before.startswith('def '): (yield (0, 'E704 multiple statements on one line (def)')) else: (yield (found, 'E701 multiple statements on one line (colon)')) found = line.find(':', (found + 1)) found = line.find(';') while ((-1) < found): if (found < last_char): (yield (found, 'E702 multiple statements on one line (semicolon)')) else: (yield (found, 'E703 statement ends with a semicolon')) found = line.find(';', (found + 1))
[ "def", "compound_statements", "(", "logical_line", ")", ":", "line", "=", "logical_line", "last_char", "=", "(", "len", "(", "line", ")", "-", "1", ")", "found", "=", "line", ".", "find", "(", "':'", ")", "while", "(", "(", "-", "1", ")", "<", "found", "<", "last_char", ")", ":", "before", "=", "line", "[", ":", "found", "]", "if", "(", "(", "before", ".", "count", "(", "'{'", ")", "<=", "before", ".", "count", "(", "'}'", ")", ")", "and", "(", "before", ".", "count", "(", "'['", ")", "<=", "before", ".", "count", "(", "']'", ")", ")", "and", "(", "before", ".", "count", "(", "'('", ")", "<=", "before", ".", "count", "(", "')'", ")", ")", ")", ":", "lambda_kw", "=", "LAMBDA_REGEX", ".", "search", "(", "before", ")", "if", "lambda_kw", ":", "before", "=", "line", "[", ":", "lambda_kw", ".", "start", "(", ")", "]", ".", "rstrip", "(", ")", "if", "(", "(", "before", "[", "(", "-", "1", ")", ":", "]", "==", "'='", ")", "and", "isidentifier", "(", "before", "[", ":", "(", "-", "1", ")", "]", ".", "strip", "(", ")", ")", ")", ":", "(", "yield", "(", "0", ",", "'E731 do not assign a lambda expression, use a def'", ")", ")", "break", "if", "before", ".", "startswith", "(", "'def '", ")", ":", "(", "yield", "(", "0", ",", "'E704 multiple statements on one line (def)'", ")", ")", "else", ":", "(", "yield", "(", "found", ",", "'E701 multiple statements on one line (colon)'", ")", ")", "found", "=", "line", ".", "find", "(", "':'", ",", "(", "found", "+", "1", ")", ")", "found", "=", "line", ".", "find", "(", "';'", ")", "while", "(", "(", "-", "1", ")", "<", "found", ")", ":", "if", "(", "found", "<", "last_char", ")", ":", "(", "yield", "(", "found", ",", "'E702 multiple statements on one line (semicolon)'", ")", ")", "else", ":", "(", "yield", "(", "found", ",", "'E703 statement ends with a semicolon'", ")", ")", "found", "=", "line", ".", "find", "(", "';'", ",", "(", "found", "+", "1", ")", ")" ]
compound statements are generally discouraged .
train
false
24,720
def horcmgr_synchronized(func): @functools.wraps(func) def wrap(self, *args, **kwargs): 'Synchronize CCI operations per CCI instance.' @coordination.synchronized(self.lock[args[0]]) def func_locked(*_args, **_kwargs): 'Execute the wrapped function in a synchronized section.' return func(*_args, **_kwargs) return func_locked(self, *args, **kwargs) return wrap
[ "def", "horcmgr_synchronized", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrap", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "@", "coordination", ".", "synchronized", "(", "self", ".", "lock", "[", "args", "[", "0", "]", "]", ")", "def", "func_locked", "(", "*", "_args", ",", "**", "_kwargs", ")", ":", "return", "func", "(", "*", "_args", ",", "**", "_kwargs", ")", "return", "func_locked", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "wrap" ]
synchronize cci operations per cci instance .
train
false
24,721
def next_pow2(n): if (n <= 0): return 1 n2 = (1 << n.bit_length()) if ((n2 >> 1) == n): return n else: return n2
[ "def", "next_pow2", "(", "n", ")", ":", "if", "(", "n", "<=", "0", ")", ":", "return", "1", "n2", "=", "(", "1", "<<", "n", ".", "bit_length", "(", ")", ")", "if", "(", "(", "n2", ">>", "1", ")", "==", "n", ")", ":", "return", "n", "else", ":", "return", "n2" ]
return first power of 2 >= n .
train
false
24,723
def _orbit_transversal(degree, generators, alpha, pairs, af=False): tr = [(alpha, list(range(degree)))] used = ([False] * degree) used[alpha] = True gens = [x._array_form for x in generators] for (x, px) in tr: for gen in gens: temp = gen[x] if (used[temp] == False): tr.append((temp, _af_rmul(gen, px))) used[temp] = True if pairs: if (not af): tr = [(x, _af_new(y)) for (x, y) in tr] return tr if af: return [y for (_, y) in tr] return [_af_new(y) for (_, y) in tr]
[ "def", "_orbit_transversal", "(", "degree", ",", "generators", ",", "alpha", ",", "pairs", ",", "af", "=", "False", ")", ":", "tr", "=", "[", "(", "alpha", ",", "list", "(", "range", "(", "degree", ")", ")", ")", "]", "used", "=", "(", "[", "False", "]", "*", "degree", ")", "used", "[", "alpha", "]", "=", "True", "gens", "=", "[", "x", ".", "_array_form", "for", "x", "in", "generators", "]", "for", "(", "x", ",", "px", ")", "in", "tr", ":", "for", "gen", "in", "gens", ":", "temp", "=", "gen", "[", "x", "]", "if", "(", "used", "[", "temp", "]", "==", "False", ")", ":", "tr", ".", "append", "(", "(", "temp", ",", "_af_rmul", "(", "gen", ",", "px", ")", ")", ")", "used", "[", "temp", "]", "=", "True", "if", "pairs", ":", "if", "(", "not", "af", ")", ":", "tr", "=", "[", "(", "x", ",", "_af_new", "(", "y", ")", ")", "for", "(", "x", ",", "y", ")", "in", "tr", "]", "return", "tr", "if", "af", ":", "return", "[", "y", "for", "(", "_", ",", "y", ")", "in", "tr", "]", "return", "[", "_af_new", "(", "y", ")", "for", "(", "_", ",", "y", ")", "in", "tr", "]" ]
computes a transversal for the orbit of alpha as a set .
train
false
24,724
def TupleRow(cursor): class Row(tuple, ): cursor_description = cursor.description def get(self, field): if (not hasattr(self, 'field_dict')): self.field_dict = {} for (i, item) in enumerate(self): self.field_dict[self.cursor_description[i][0]] = item return self.field_dict.get(field) def __getitem__(self, field): if isinstance(field, (unicode, str)): return self.get(field) else: return tuple.__getitem__(self, field) return Row
[ "def", "TupleRow", "(", "cursor", ")", ":", "class", "Row", "(", "tuple", ",", ")", ":", "cursor_description", "=", "cursor", ".", "description", "def", "get", "(", "self", ",", "field", ")", ":", "if", "(", "not", "hasattr", "(", "self", ",", "'field_dict'", ")", ")", ":", "self", ".", "field_dict", "=", "{", "}", "for", "(", "i", ",", "item", ")", "in", "enumerate", "(", "self", ")", ":", "self", ".", "field_dict", "[", "self", ".", "cursor_description", "[", "i", "]", "[", "0", "]", "]", "=", "item", "return", "self", ".", "field_dict", ".", "get", "(", "field", ")", "def", "__getitem__", "(", "self", ",", "field", ")", ":", "if", "isinstance", "(", "field", ",", "(", "unicode", ",", "str", ")", ")", ":", "return", "self", ".", "get", "(", "field", ")", "else", ":", "return", "tuple", ".", "__getitem__", "(", "self", ",", "field", ")", "return", "Row" ]
normal tuple with added attribute cursor_description .
train
false
24,725
def get_attr(cmd): if (u'.' in cmd): method = frappe.get_attr(cmd) else: method = globals()[cmd] frappe.log((u'method:' + cmd)) return method
[ "def", "get_attr", "(", "cmd", ")", ":", "if", "(", "u'.'", "in", "cmd", ")", ":", "method", "=", "frappe", ".", "get_attr", "(", "cmd", ")", "else", ":", "method", "=", "globals", "(", ")", "[", "cmd", "]", "frappe", ".", "log", "(", "(", "u'method:'", "+", "cmd", ")", ")", "return", "method" ]
get method object from cmd .
train
false
24,727
def has_wildcard(pattern): match = wildcard_check_pattern.search(pattern) return (match is not None)
[ "def", "has_wildcard", "(", "pattern", ")", ":", "match", "=", "wildcard_check_pattern", ".", "search", "(", "pattern", ")", "return", "(", "match", "is", "not", "None", ")" ]
checks whether pattern has any wildcards .
train
false