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
32,436
def export_course_to_xml(modulestore, contentstore, course_key, root_dir, course_dir): CourseExportManager(modulestore, contentstore, course_key, root_dir, course_dir).export()
[ "def", "export_course_to_xml", "(", "modulestore", ",", "contentstore", ",", "course_key", ",", "root_dir", ",", "course_dir", ")", ":", "CourseExportManager", "(", "modulestore", ",", "contentstore", ",", "course_key", ",", "root_dir", ",", "course_dir", ")", "."...
thin wrapper for the course export manager .
train
false
32,437
def timefunc(num_tries=1, verbose=True): def real_decorator(function): @wraps(function) def wrapper(*args, **kwargs): ts = time.time() for i in range(num_tries): result = function(*args, **kwargs) te = time.time() tt = ((te - ts) / num_tries) if verbose: log.info(u'{0} took {1} s on AVERAGE for {2} call(s).'.format(function.__name__, tt, num_tries)) return (tt, result) return wrapper return real_decorator
[ "def", "timefunc", "(", "num_tries", "=", "1", ",", "verbose", "=", "True", ")", ":", "def", "real_decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "ts", "...
decorator that logs how long a particular function took to execute .
train
false
32,438
def remove_old_snapshots(session, instance, vm_ref): LOG.debug('Starting remove_old_snapshots for VM', instance=instance) (vm_vdi_ref, vm_vdi_rec) = get_vdi_for_vm_safely(session, vm_ref) chain = _walk_vdi_chain(session, vm_vdi_rec['uuid']) vdi_uuid_chain = [vdi_rec['uuid'] for vdi_rec in chain] sr_ref = vm_vdi_rec['SR'] _delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref)
[ "def", "remove_old_snapshots", "(", "session", ",", "instance", ",", "vm_ref", ")", ":", "LOG", ".", "debug", "(", "'Starting remove_old_snapshots for VM'", ",", "instance", "=", "instance", ")", "(", "vm_vdi_ref", ",", "vm_vdi_rec", ")", "=", "get_vdi_for_vm_safe...
see if there is an snapshot present that should be removed .
train
false
32,439
def appendAttributes(fromElementNode, toElementNode): for childNode in fromElementNode.childNodes: toElementNode.attributes.update(evaluate.removeIdentifiersFromDictionary(childNode.attributes.copy()))
[ "def", "appendAttributes", "(", "fromElementNode", ",", "toElementNode", ")", ":", "for", "childNode", "in", "fromElementNode", ".", "childNodes", ":", "toElementNode", ".", "attributes", ".", "update", "(", "evaluate", ".", "removeIdentifiersFromDictionary", "(", "...
append the attributes from the child nodes of fromelementnode to the attributes of toelementnode .
train
false
32,440
def replace_node(ptr, value): (parent, attrname, listidx) = ptr if (listidx is None): setattr(parent, attrname, value) else: getattr(parent, attrname)[listidx] = value
[ "def", "replace_node", "(", "ptr", ",", "value", ")", ":", "(", "parent", ",", "attrname", ",", "listidx", ")", "=", "ptr", "if", "(", "listidx", "is", "None", ")", ":", "setattr", "(", "parent", ",", "attrname", ",", "value", ")", "else", ":", "ge...
replaces a node .
train
false
32,441
def mse(x1, x2, axis=0): x1 = np.asanyarray(x1) x2 = np.asanyarray(x2) return np.mean(((x1 - x2) ** 2), axis=axis)
[ "def", "mse", "(", "x1", ",", "x2", ",", "axis", "=", "0", ")", ":", "x1", "=", "np", ".", "asanyarray", "(", "x1", ")", "x2", "=", "np", ".", "asanyarray", "(", "x2", ")", "return", "np", ".", "mean", "(", "(", "(", "x1", "-", "x2", ")", ...
mean squared error parameters x1 .
train
false
32,442
def get_registration_contributors(): registrations = models.Node.find(Q('is_registration', 'eq', True)) contributors = [] def has_received_message(contrib): query = (Q('_id', 'eq', contrib._id) & Q('security_messages.{0}'.format(MESSAGE_NAME), 'exists', False)) return (models.User.find(query).count() == 0) for node in registrations: contributors.extend([contrib for contrib in node.contributors if ((contrib not in contributors) and (not has_received_message(contrib)))]) return contributors
[ "def", "get_registration_contributors", "(", ")", ":", "registrations", "=", "models", ".", "Node", ".", "find", "(", "Q", "(", "'is_registration'", ",", "'eq'", ",", "True", ")", ")", "contributors", "=", "[", "]", "def", "has_received_message", "(", "contr...
returns set of users that contribute to registrations .
train
false
32,443
def _get_int_param(request, param): try: int_param = utils.validate_integer(request.GET[param], param, min_value=0) except exception.InvalidInput as e: raise webob.exc.HTTPBadRequest(explanation=e.format_message()) return int_param
[ "def", "_get_int_param", "(", "request", ",", "param", ")", ":", "try", ":", "int_param", "=", "utils", ".", "validate_integer", "(", "request", ".", "GET", "[", "param", "]", ",", "param", ",", "min_value", "=", "0", ")", "except", "exception", ".", "...
extract integer param from request or fail .
train
false
32,444
@pytest.mark.network def test_git_with_branch_name_as_revision(script): version_pkg_path = _create_test_package(script) script.run('git', 'checkout', '-b', 'test_branch', expect_stderr=True, cwd=version_pkg_path) _change_test_package_version(script, version_pkg_path) script.pip('install', '-e', ('%s@test_branch#egg=version_pkg' % ('git+file://' + version_pkg_path.abspath.replace('\\', '/')))) version = script.run('version_pkg') assert ('some different version' in version.stdout)
[ "@", "pytest", ".", "mark", ".", "network", "def", "test_git_with_branch_name_as_revision", "(", "script", ")", ":", "version_pkg_path", "=", "_create_test_package", "(", "script", ")", "script", ".", "run", "(", "'git'", ",", "'checkout'", ",", "'-b'", ",", "...
git backend should be able to install from branch names .
train
false
32,447
def assertIsNotSubdomainOf(testCase, descendant, ancestor): testCase.assertFalse(dns._isSubdomainOf(descendant, ancestor), ('%r is a subdomain of %r' % (descendant, ancestor)))
[ "def", "assertIsNotSubdomainOf", "(", "testCase", ",", "descendant", ",", "ancestor", ")", ":", "testCase", ".", "assertFalse", "(", "dns", ".", "_isSubdomainOf", "(", "descendant", ",", "ancestor", ")", ",", "(", "'%r is a subdomain of %r'", "%", "(", "descenda...
assert that c{descendant} *is not* a subdomain of c{ancestor} .
train
false
32,448
def _consensus_base_alphabet(alphabets): common = None for alpha in alphabets: a = _get_base_alphabet(alpha) if (common is None): common = a elif (common == a): pass elif isinstance(a, common.__class__): pass elif isinstance(common, a.__class__): common = a elif (isinstance(a, NucleotideAlphabet) and isinstance(common, NucleotideAlphabet)): common = generic_nucleotide elif (isinstance(a, SingleLetterAlphabet) and isinstance(common, SingleLetterAlphabet)): common = single_letter_alphabet else: return generic_alphabet if (common is None): return generic_alphabet return common
[ "def", "_consensus_base_alphabet", "(", "alphabets", ")", ":", "common", "=", "None", "for", "alpha", "in", "alphabets", ":", "a", "=", "_get_base_alphabet", "(", "alpha", ")", "if", "(", "common", "is", "None", ")", ":", "common", "=", "a", "elif", "(",...
returns a common but often generic base alphabet object .
train
false
32,450
def ValidateInteger(value, name='unused', exception=datastore_errors.BadValueError, empty_ok=False, zero_ok=False, negative_ok=False): if ((value is None) and empty_ok): return if (not isinstance(value, (int, long))): raise exception(('%s should be an integer; received %s (a %s).' % (name, value, typename(value)))) if ((not value) and (not zero_ok)): raise exception(('%s must not be 0 (zero)' % name)) if ((value < 0) and (not negative_ok)): raise exception(('%s must not be negative.' % name))
[ "def", "ValidateInteger", "(", "value", ",", "name", "=", "'unused'", ",", "exception", "=", "datastore_errors", ".", "BadValueError", ",", "empty_ok", "=", "False", ",", "zero_ok", "=", "False", ",", "negative_ok", "=", "False", ")", ":", "if", "(", "(", ...
raises an exception if value is not a valid integer .
train
false
32,451
def poweroff(): return shutdown()
[ "def", "poweroff", "(", ")", ":", "return", "shutdown", "(", ")" ]
poweroff a running system cli example: .
train
false
32,452
def _has_detached_class_tag(descriptor): return (ACCESS_GRANTED if ('detached' in descriptor._class_tags) else ACCESS_DENIED)
[ "def", "_has_detached_class_tag", "(", "descriptor", ")", ":", "return", "(", "ACCESS_GRANTED", "if", "(", "'detached'", "in", "descriptor", ".", "_class_tags", ")", "else", "ACCESS_DENIED", ")" ]
returns if the given descriptors type is marked as detached .
train
false
32,453
def _parse_vw_output(text): data = {} for line in text.splitlines(): if line.startswith(u'average loss'): data[u'average_loss'] = float(line.split(u'=')[1]) break return data
[ "def", "_parse_vw_output", "(", "text", ")", ":", "data", "=", "{", "}", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "if", "line", ".", "startswith", "(", "u'average loss'", ")", ":", "data", "[", "u'average_loss'", "]", "=", "float"...
get dict of useful fields from vowpal wabbits output .
train
false
32,454
def intget(integer, default=None): try: return int(integer) except (TypeError, ValueError): return default
[ "def", "intget", "(", "integer", ",", "default", "=", "None", ")", ":", "try", ":", "return", "int", "(", "integer", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "default" ]
returns integer as an int or default if it cant .
train
false
32,455
def imfft(X): return fftshift(fft2(X))
[ "def", "imfft", "(", "X", ")", ":", "return", "fftshift", "(", "fft2", "(", "X", ")", ")" ]
perform 2d fft on an image and center low frequencies .
train
false
32,456
def lookup_ubuntu_ami(table, release, stream, store, arch, region, virt): expected = (release, stream, store, arch, region, virt) for row in table: (actual_release, actual_stream, tag, serial, actual_store, actual_arch, actual_region, ami, aki, ari, actual_virt) = row actual = (actual_release, actual_stream, actual_store, actual_arch, actual_region, actual_virt) if (actual == expected): if (aki == ''): aki = None if (ari == ''): ari = None return (ami, aki, ari, tag, serial) raise KeyError()
[ "def", "lookup_ubuntu_ami", "(", "table", ",", "release", ",", "stream", ",", "store", ",", "arch", ",", "region", ",", "virt", ")", ":", "expected", "=", "(", "release", ",", "stream", ",", "store", ",", "arch", ",", "region", ",", "virt", ")", "for...
look up the ubuntu ami that matches query given a table of amis table: an iterable that returns a row of release: ubuntu release name stream: server or desktop store: ebs .
train
false
32,458
def libvlc_media_new_location(p_instance, psz_mrl): f = (_Cfunctions.get('libvlc_media_new_location', None) or _Cfunction('libvlc_media_new_location', ((1,), (1,)), class_result(Media), ctypes.c_void_p, Instance, ctypes.c_char_p)) return f(p_instance, psz_mrl)
[ "def", "libvlc_media_new_location", "(", "p_instance", ",", "psz_mrl", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_new_location'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_new_location'", ",", "(", "(", "1", ",", ")...
create a media with a certain given media resource location .
train
true
32,459
@require_safe def filtered_chunk(request, task_id, pid, category): if (not request.is_ajax()): raise PermissionDenied record = results_db.analysis.find_one({'info.id': int(task_id), 'behavior.processes.pid': int(pid)}, {'behavior.processes.pid': 1, 'behavior.processes.calls': 1}) if (not record): raise ObjectDoesNotExist process = None for pdict in record['behavior']['processes']: if (pdict['pid'] == int(pid)): process = pdict if (not process): raise ObjectDoesNotExist filtered_process = {'pid': pid, 'calls': []} for call in process['calls']: chunk = results_db.calls.find_one({'_id': call}) for call in chunk['calls']: if (call['category'] == category): filtered_process['calls'].append(call) return render(request, 'analysis/behavior/_chunk.html', {'chunk': filtered_process})
[ "@", "require_safe", "def", "filtered_chunk", "(", "request", ",", "task_id", ",", "pid", ",", "category", ")", ":", "if", "(", "not", "request", ".", "is_ajax", "(", ")", ")", ":", "raise", "PermissionDenied", "record", "=", "results_db", ".", "analysis",...
filters calls for call category .
train
false
32,460
def resolve_fractions(a, b): a_is_fraction = isinstance(a, Fraction) b_is_fraction = isinstance(b, Fraction) if (a_is_fraction and (not b_is_fraction)): b = Fraction(b) elif ((not a_is_fraction) and b_is_fraction): a = Fraction(a) return (a, b)
[ "def", "resolve_fractions", "(", "a", ",", "b", ")", ":", "a_is_fraction", "=", "isinstance", "(", "a", ",", "Fraction", ")", "b_is_fraction", "=", "isinstance", "(", "b", ",", "Fraction", ")", "if", "(", "a_is_fraction", "and", "(", "not", "b_is_fraction"...
if either input is a fraction .
train
false
32,461
def db_version(database='main', context=None): return IMPL.db_version(database=database, context=context)
[ "def", "db_version", "(", "database", "=", "'main'", ",", "context", "=", "None", ")", ":", "return", "IMPL", ".", "db_version", "(", "database", "=", "database", ",", "context", "=", "context", ")" ]
display the current database version .
train
false
32,462
def textile_restricted(text, lite=True, noimage=True, html_type='xhtml'): return Textile(restricted=True, lite=lite, noimage=noimage).textile(text, rel='nofollow', html_type=html_type)
[ "def", "textile_restricted", "(", "text", ",", "lite", "=", "True", ",", "noimage", "=", "True", ",", "html_type", "=", "'xhtml'", ")", ":", "return", "Textile", "(", "restricted", "=", "True", ",", "lite", "=", "lite", ",", "noimage", "=", "noimage", ...
restricted version of textile designed for weblog comments and other untrusted input .
train
false
32,463
def migrate_category(node): if (node.category not in settings.NODE_CATEGORY_MAP.keys()): node.category = MIGRATE_MAP.get(node.category, 'other') return True return False
[ "def", "migrate_category", "(", "node", ")", ":", "if", "(", "node", ".", "category", "not", "in", "settings", ".", "NODE_CATEGORY_MAP", ".", "keys", "(", ")", ")", ":", "node", ".", "category", "=", "MIGRATE_MAP", ".", "get", "(", "node", ".", "catego...
migrate legacy .
train
false
32,464
def _open_state(): try: with open(config['statefile'].as_filename(), 'rb') as f: return pickle.load(f) except Exception as exc: log.debug(u'state file could not be read: {0}', exc) return {}
[ "def", "_open_state", "(", ")", ":", "try", ":", "with", "open", "(", "config", "[", "'statefile'", "]", ".", "as_filename", "(", ")", ",", "'rb'", ")", "as", "f", ":", "return", "pickle", ".", "load", "(", "f", ")", "except", "Exception", "as", "e...
reads the state file .
train
false
32,466
def RunModbusFrontend(server, port=8080): from bottle import TwistedServer, run application = build_application(server) run(app=application, server=TwistedServer, port=port)
[ "def", "RunModbusFrontend", "(", "server", ",", "port", "=", "8080", ")", ":", "from", "bottle", "import", "TwistedServer", ",", "run", "application", "=", "build_application", "(", "server", ")", "run", "(", "app", "=", "application", ",", "server", "=", ...
helper method to host bottle in twisted .
train
false
32,467
def bench_scikit_tree_regressor(X, Y): from sklearn.tree import DecisionTreeRegressor gc.collect() tstart = datetime.now() clf = DecisionTreeRegressor() clf.fit(X, Y).predict(X) delta = (datetime.now() - tstart) scikit_regressor_results.append((delta.seconds + (delta.microseconds / mu_second)))
[ "def", "bench_scikit_tree_regressor", "(", "X", ",", "Y", ")", ":", "from", "sklearn", ".", "tree", "import", "DecisionTreeRegressor", "gc", ".", "collect", "(", ")", "tstart", "=", "datetime", ".", "now", "(", ")", "clf", "=", "DecisionTreeRegressor", "(", ...
benchmark with scikit-learn decision tree regressor .
train
false
32,468
def eq_msg(a, b, msg=None): assert (a == b), ((str(msg) or '') + (' (%r != %r)' % (a, b)))
[ "def", "eq_msg", "(", "a", ",", "b", ",", "msg", "=", "None", ")", ":", "assert", "(", "a", "==", "b", ")", ",", "(", "(", "str", "(", "msg", ")", "or", "''", ")", "+", "(", "' (%r != %r)'", "%", "(", "a", ",", "b", ")", ")", ")" ]
shorthand for assert a == b .
train
false
32,469
def _escape(value): if isinstance(value, (list, tuple)): value = u','.join(value) elif isinstance(value, (date, datetime)): value = value.isoformat() elif isinstance(value, bool): value = str(value).lower() if isinstance(value, string_types): try: return value.encode(u'utf-8') except UnicodeDecodeError: pass return str(value)
[ "def", "_escape", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "value", "=", "u','", ".", "join", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "(", "date", ",", "datetime", ...
basic html escaping .
train
false
32,471
def rstrip_last_char(input_str, char_to_strip): if (not input_str): return input_str if (not char_to_strip): return input_str if input_str.endswith(char_to_strip): return input_str[:(- len(char_to_strip))] return input_str
[ "def", "rstrip_last_char", "(", "input_str", ",", "char_to_strip", ")", ":", "if", "(", "not", "input_str", ")", ":", "return", "input_str", "if", "(", "not", "char_to_strip", ")", ":", "return", "input_str", "if", "input_str", ".", "endswith", "(", "char_to...
strips the last char_to_strip from input_str if input_str ends with char_to_strip .
train
false
32,472
def substitute(request, node, subs): for child in node.childNodes: if (hasattr(child, 'nodeValue') and child.nodeValue): child.replaceData(0, len(child.nodeValue), (child.nodeValue % subs)) substitute(request, child, subs)
[ "def", "substitute", "(", "request", ",", "node", ",", "subs", ")", ":", "for", "child", "in", "node", ".", "childNodes", ":", "if", "(", "hasattr", "(", "child", ",", "'nodeValue'", ")", "and", "child", ".", "nodeValue", ")", ":", "child", ".", "rep...
look through the given nodes children for strings .
train
false
32,473
def attr_lt(accessing_obj, accessed_obj, *args, **kwargs): return attr(accessing_obj, accessed_obj, *args, **{'compare': 'lt'})
[ "def", "attr_lt", "(", "accessing_obj", ",", "accessed_obj", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "attr", "(", "accessing_obj", ",", "accessed_obj", ",", "*", "args", ",", "**", "{", "'compare'", ":", "'lt'", "}", ")" ]
usage: attr_gt only true if access_objs attribute < the value given .
train
false
32,477
def get_index_settings(index): return get_es().indices.get_settings(index=index).get(index, {}).get('settings', {})
[ "def", "get_index_settings", "(", "index", ")", ":", "return", "get_es", "(", ")", ".", "indices", ".", "get_settings", "(", "index", "=", "index", ")", ".", "get", "(", "index", ",", "{", "}", ")", ".", "get", "(", "'settings'", ",", "{", "}", ")"...
returns es settings for this index .
train
false
32,478
def unique_justseen(iterable, key=None): imap = itertools.imap itemgetter = operator.itemgetter groupby = itertools.groupby return imap(next, imap(itemgetter(1), groupby(iterable, key)))
[ "def", "unique_justseen", "(", "iterable", ",", "key", "=", "None", ")", ":", "imap", "=", "itertools", ".", "imap", "itemgetter", "=", "operator", ".", "itemgetter", "groupby", "=", "itertools", ".", "groupby", "return", "imap", "(", "next", ",", "imap", ...
list unique elements .
train
false
32,479
def delete_from_postgis(resource_name): import psycopg2 db = ogc_server_settings.datastore_db conn = None port = str(db['PORT']) try: conn = psycopg2.connect((((((((((("dbname='" + db['NAME']) + "' user='") + db['USER']) + "' password='") + db['PASSWORD']) + "' port=") + port) + " host='") + db['HOST']) + "'")) cur = conn.cursor() cur.execute(("SELECT DropGeometryTable ('%s')" % resource_name)) conn.commit() except Exception as e: logger.error('Error deleting PostGIS table %s:%s', resource_name, str(e)) finally: try: if conn: conn.close() except Exception as e: logger.error('Error closing PostGIS conn %s:%s', resource_name, str(e))
[ "def", "delete_from_postgis", "(", "resource_name", ")", ":", "import", "psycopg2", "db", "=", "ogc_server_settings", ".", "datastore_db", "conn", "=", "None", "port", "=", "str", "(", "db", "[", "'PORT'", "]", ")", "try", ":", "conn", "=", "psycopg2", "."...
delete a table from postgis ; to be used after deleting a layer from the system .
train
false
32,480
def corr_clipped(corr, threshold=1e-15): (x_new, clipped) = clip_evals(corr, value=threshold) if (not clipped): return corr x_std = np.sqrt(np.diag(x_new)) x_new = ((x_new / x_std) / x_std[:, None]) return x_new
[ "def", "corr_clipped", "(", "corr", ",", "threshold", "=", "1e-15", ")", ":", "(", "x_new", ",", "clipped", ")", "=", "clip_evals", "(", "corr", ",", "value", "=", "threshold", ")", "if", "(", "not", "clipped", ")", ":", "return", "corr", "x_std", "=...
find a near correlation matrix that is positive semi-definite this function clips the eigenvalues .
train
false
32,481
def create_classification_imageset(folder, image_size=10, image_count=10, add_unbalanced_category=False): paths = defaultdict(list) config = [('red-to-right', 0, 0, image_count), ('green-to-top', 1, 90, image_count), ('blue-to-left', 2, 180, image_count)] if add_unbalanced_category: config.append(('blue-to-bottom', 2, 270, (image_count / 2))) for (class_name, pixel_index, rotation, image_count) in config: os.makedirs(os.path.join(folder, class_name)) colors = np.linspace(200, 255, image_count) for (i, color) in enumerate(colors): pixel = [0, 0, 0] pixel[pixel_index] = color pil_img = _create_gradient_image(image_size, (0, 0, 0), pixel, rotation) img_path = os.path.join(class_name, (str(i) + '.png')) pil_img.save(os.path.join(folder, img_path)) paths[class_name].append(img_path) return paths
[ "def", "create_classification_imageset", "(", "folder", ",", "image_size", "=", "10", ",", "image_count", "=", "10", ",", "add_unbalanced_category", "=", "False", ")", ":", "paths", "=", "defaultdict", "(", "list", ")", "config", "=", "[", "(", "'red-to-right'...
creates a folder of folders of images for classification if requested to add an unbalanced category then a category is added with half the number of samples of other categories .
train
false
32,484
def parse_article(generator, metadata): if ('event-start' not in metadata): return dtstart = parse_tstamp(metadata, 'event-start') if ('event-end' in metadata): dtend = parse_tstamp(metadata, 'event-end') elif ('event-duration' in metadata): dtdelta = parse_timedelta(metadata) dtend = (dtstart + dtdelta) else: msg = ("Either 'event-end' or 'event-duration' must be" + (" speciefied in the event named '%s'" % metadata['title'])) log.error(msg) raise ValueError(msg) events.append(Event(dtstart, dtend, metadata))
[ "def", "parse_article", "(", "generator", ",", "metadata", ")", ":", "if", "(", "'event-start'", "not", "in", "metadata", ")", ":", "return", "dtstart", "=", "parse_tstamp", "(", "metadata", ",", "'event-start'", ")", "if", "(", "'event-end'", "in", "metadat...
collect articles metadata to be used for building the event calendar :returns: none .
train
true
32,485
def new(rsa_key): return PKCS115_SigScheme(rsa_key)
[ "def", "new", "(", "rsa_key", ")", ":", "return", "PKCS115_SigScheme", "(", "rsa_key", ")" ]
initialize a new hash object .
train
false
32,486
def generate_equivalent_ids(gate_seq, return_as_muls=False): if isinstance(gate_seq, Number): return {Integer(1)} elif isinstance(gate_seq, Mul): gate_seq = gate_seq.args eq_ids = set() gate_rules = generate_gate_rules(gate_seq) for rule in gate_rules: (l, r) = rule if (l == ()): eq_ids.add(r) elif (r == ()): eq_ids.add(l) if return_as_muls: convert_to_mul = (lambda id_seq: Mul(*id_seq)) eq_ids = set(map(convert_to_mul, eq_ids)) return eq_ids
[ "def", "generate_equivalent_ids", "(", "gate_seq", ",", "return_as_muls", "=", "False", ")", ":", "if", "isinstance", "(", "gate_seq", ",", "Number", ")", ":", "return", "{", "Integer", "(", "1", ")", "}", "elif", "isinstance", "(", "gate_seq", ",", "Mul",...
returns a set of equivalent gate identities .
train
false
32,487
def get_unicode_from_response(r): warnings.warn('In requests 3.0, get_unicode_from_response will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)', DeprecationWarning) tried_encodings = [] encoding = get_encoding_from_headers(r.headers) if encoding: try: return str(r.content, encoding) except UnicodeError: tried_encodings.append(encoding) try: return str(r.content, encoding, errors='replace') except TypeError: return r.content
[ "def", "get_unicode_from_response", "(", "r", ")", ":", "warnings", ".", "warn", "(", "'In requests 3.0, get_unicode_from_response will be removed. For more information, please see the discussion on issue #2266. (This warning should only appear once.)'", ",", "DeprecationWarning", ")", "...
returns the requested content back in unicode .
train
true
32,488
def json_encoder(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() else: return obj
[ "def", "json_encoder", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ".", "datetime", ")", ":", "return", "obj", ".", "isoformat", "(", ")", "else", ":", "return", "obj" ]
json encoder that formats datetimes as iso8601 format .
train
false
32,489
def mismatch(mismatched, description, details): return _Mismatch(mismatched=mismatched, _description=description, _details=details)
[ "def", "mismatch", "(", "mismatched", ",", "description", ",", "details", ")", ":", "return", "_Mismatch", "(", "mismatched", "=", "mismatched", ",", "_description", "=", "description", ",", "_details", "=", "details", ")" ]
create an immutable mismatch that also stores the mismatched object .
train
false
32,490
def dmp_terms_gcd(f, u, K): if (dmp_ground_TC(f, u, K) or dmp_zero_p(f, u)): return (((0,) * (u + 1)), f) F = dmp_to_dict(f, u) G = monomial_min(*list(F.keys())) if all(((g == 0) for g in G)): return (G, f) f = {} for (monom, coeff) in F.items(): f[monomial_div(monom, G)] = coeff return (G, dmp_from_dict(f, u, K))
[ "def", "dmp_terms_gcd", "(", "f", ",", "u", ",", "K", ")", ":", "if", "(", "dmp_ground_TC", "(", "f", ",", "u", ",", "K", ")", "or", "dmp_zero_p", "(", "f", ",", "u", ")", ")", ":", "return", "(", "(", "(", "0", ",", ")", "*", "(", "u", "...
remove gcd of terms from f in k[x] .
train
false
32,491
@requires_segment_info def tablister(pl, segment_info, **kwargs): cur_tabpage = current_tabpage() cur_tabnr = cur_tabpage.number def add_multiplier(tabpage, dct): dct[u'priority_multiplier'] = (1 + (0.001 * abs((tabpage.number - cur_tabnr)))) return dct return ((lambda tabpage, prefix: (tabpage_updated_segment_info(segment_info, tabpage), add_multiplier(tabpage, {u'highlight_group_prefix': prefix, u'divider_highlight_group': u'tab:divider'})))(tabpage, (u'tab' if (tabpage == cur_tabpage) else u'tab_nc')) for tabpage in list_tabpages())
[ "@", "requires_segment_info", "def", "tablister", "(", "pl", ",", "segment_info", ",", "**", "kwargs", ")", ":", "cur_tabpage", "=", "current_tabpage", "(", ")", "cur_tabnr", "=", "cur_tabpage", ".", "number", "def", "add_multiplier", "(", "tabpage", ",", "dct...
list all tab pages in segment_info format specifically generates a list of segment info dictionaries with window .
train
false
32,492
def _create_kernel_image(context, session, instance, name_label, image_id, image_type): if CONF.xenserver.independent_compute: raise exception.NotSupportedWithOption(operation='Non-VHD images', option='CONF.xenserver.independent_compute') filename = '' if (CONF.xenserver.cache_images != 'none'): args = {} args['cached-image'] = image_id args['new-image-uuid'] = uuidutils.generate_uuid() filename = session.call_plugin('kernel.py', 'create_kernel_ramdisk', args) if (filename == ''): return _fetch_disk_image(context, session, instance, name_label, image_id, image_type) else: vdi_type = ImageType.to_string(image_type) return {vdi_type: dict(uuid=None, file=filename)}
[ "def", "_create_kernel_image", "(", "context", ",", "session", ",", "instance", ",", "name_label", ",", "image_id", ",", "image_type", ")", ":", "if", "CONF", ".", "xenserver", ".", "independent_compute", ":", "raise", "exception", ".", "NotSupportedWithOption", ...
creates kernel/ramdisk file from the image stored in the cache .
train
false
32,493
def delete_autoscaler(autoscaler): changed = False if autoscaler.destroy(): changed = True return changed
[ "def", "delete_autoscaler", "(", "autoscaler", ")", ":", "changed", "=", "False", "if", "autoscaler", ".", "destroy", "(", ")", ":", "changed", "=", "True", "return", "changed" ]
delete an autoscaler .
train
false
32,494
def remove_null_refct_call(bb): pass
[ "def", "remove_null_refct_call", "(", "bb", ")", ":", "pass" ]
remove refct api calls to null pointer .
train
false
32,495
def strip_shell_chars(input_str): stripped_str = rstrip_last_char(input_str, '\n') stripped_str = rstrip_last_char(stripped_str, '\r') return stripped_str
[ "def", "strip_shell_chars", "(", "input_str", ")", ":", "stripped_str", "=", "rstrip_last_char", "(", "input_str", ",", "'\\n'", ")", "stripped_str", "=", "rstrip_last_char", "(", "stripped_str", ",", "'\\r'", ")", "return", "stripped_str" ]
strips the last or or string at the end of the input string .
train
false
32,496
def _check_ch_names(inv, info): inv_ch_names = inv['eigen_fields']['col_names'] if (inv['noise_cov'].ch_names != inv_ch_names): raise ValueError('Channels in inverse operator eigen fields do not match noise covariance channels.') data_ch_names = info['ch_names'] missing_ch_names = list() for ch_name in inv_ch_names: if (ch_name not in data_ch_names): missing_ch_names.append(ch_name) n_missing = len(missing_ch_names) if (n_missing > 0): raise ValueError((('%d channels in inverse operator ' % n_missing) + ('are not present in the data (%s)' % missing_ch_names)))
[ "def", "_check_ch_names", "(", "inv", ",", "info", ")", ":", "inv_ch_names", "=", "inv", "[", "'eigen_fields'", "]", "[", "'col_names'", "]", "if", "(", "inv", "[", "'noise_cov'", "]", ".", "ch_names", "!=", "inv_ch_names", ")", ":", "raise", "ValueError",...
check that channels in inverse operator are measurements .
train
false
32,498
def test_popup_injection(): base = HttpResponse('<html><head></head><body>Hello</body></html>') resp = django_util.render_injected(base, ' Cookie monster') assert_true(('Hello Cookie monster' in resp.content)) redirect = HttpResponseRedirect('http://www.cnn.com') resp = django_util.render_injected(redirect, 'Cookie monster') assert_true(('Cookie monster' not in resp.content)) json = django_util.render_json('blah') resp = django_util.render_injected(json, 'Cookie monster') assert_true(('Cookie monster' not in resp.content)) assert_raises(AssertionError, django_util.render_injected, 'foo', 'bar')
[ "def", "test_popup_injection", "(", ")", ":", "base", "=", "HttpResponse", "(", "'<html><head></head><body>Hello</body></html>'", ")", "resp", "=", "django_util", ".", "render_injected", "(", "base", ",", "' Cookie monster'", ")", "assert_true", "(", "(", "'Hello Cook...
test that result injection works .
train
false
32,499
@task def test_travis_else(ctx): flake(ctx) jshint(ctx) test_else(ctx)
[ "@", "task", "def", "test_travis_else", "(", "ctx", ")", ":", "flake", "(", "ctx", ")", "jshint", "(", "ctx", ")", "test_else", "(", "ctx", ")" ]
run other half of the tests to help travis go faster .
train
false
32,500
def instance_group_member_delete(context, group_uuid, instance_id): return IMPL.instance_group_member_delete(context, group_uuid, instance_id)
[ "def", "instance_group_member_delete", "(", "context", ",", "group_uuid", ",", "instance_id", ")", ":", "return", "IMPL", ".", "instance_group_member_delete", "(", "context", ",", "group_uuid", ",", "instance_id", ")" ]
delete a specific member from the group .
train
false
32,501
def get_missing_permissions(user, permissions): if callable(getattr(user, 'has_perm', None)): missing_permissions = set((p for p in set(permissions) if (not user.has_perm(p)))) else: missing_permissions = set(permissions) return missing_permissions
[ "def", "get_missing_permissions", "(", "user", ",", "permissions", ")", ":", "if", "callable", "(", "getattr", "(", "user", ",", "'has_perm'", ",", "None", ")", ")", ":", "missing_permissions", "=", "set", "(", "(", "p", "for", "p", "in", "set", "(", "...
return a set of missing permissions for a given iterable of permission strings .
train
false
32,502
def sync_language(d, data): for key in data: if (key not in d): d[key] = data[key] elif (((d[key] != '') or (d[key] != key)) and ((data[key] == '') or (data[key] == key))): d[key] = d[key] else: d[key] = data[key] return d
[ "def", "sync_language", "(", "d", ",", "data", ")", ":", "for", "key", "in", "data", ":", "if", "(", "key", "not", "in", "d", ")", ":", "d", "[", "key", "]", "=", "data", "[", "key", "]", "elif", "(", "(", "(", "d", "[", "key", "]", "!=", ...
this function makes sure a translated string will be prefered over an untranslated string when syncing languages between apps .
train
false
32,503
def _ensure_2d(x, ndarray=False): if (x is None): return x is_pandas = _is_using_pandas(x, None) if (x.ndim == 2): if is_pandas: return (x, x.columns) else: return (x, None) elif (x.ndim > 2): raise ValueError('x mst be 1 or 2-dimensional.') name = (x.name if is_pandas else None) if ndarray: return (np.asarray(x)[:, None], name) else: return (pd.DataFrame(x), name)
[ "def", "_ensure_2d", "(", "x", ",", "ndarray", "=", "False", ")", ":", "if", "(", "x", "is", "None", ")", ":", "return", "x", "is_pandas", "=", "_is_using_pandas", "(", "x", ",", "None", ")", "if", "(", "x", ".", "ndim", "==", "2", ")", ":", "i...
parameters x : array .
train
false
32,504
def _create_ocb_cipher(factory, **kwargs): try: nonce = kwargs.pop('nonce', None) if (nonce is None): nonce = get_random_bytes(15) mac_len = kwargs.pop('mac_len', 16) except KeyError as e: raise TypeError(('Keyword missing: ' + str(e))) return OcbMode(factory, nonce, mac_len, kwargs)
[ "def", "_create_ocb_cipher", "(", "factory", ",", "**", "kwargs", ")", ":", "try", ":", "nonce", "=", "kwargs", ".", "pop", "(", "'nonce'", ",", "None", ")", "if", "(", "nonce", "is", "None", ")", ":", "nonce", "=", "get_random_bytes", "(", "15", ")"...
create a new block cipher .
train
false
32,505
def _encode_asn1_int(backend, x): i = backend._int_to_bn(x) i = backend._ffi.gc(i, backend._lib.BN_free) i = backend._lib.BN_to_ASN1_INTEGER(i, backend._ffi.NULL) backend.openssl_assert((i != backend._ffi.NULL)) return i
[ "def", "_encode_asn1_int", "(", "backend", ",", "x", ")", ":", "i", "=", "backend", ".", "_int_to_bn", "(", "x", ")", "i", "=", "backend", ".", "_ffi", ".", "gc", "(", "i", ",", "backend", ".", "_lib", ".", "BN_free", ")", "i", "=", "backend", "....
converts a python integer to an asn1_integer .
train
false
32,507
def s3_auth_user_represent_name(id, row=None): if (not row): if (not id): return current.messages['NONE'] db = current.db table = db.auth_user row = db((table.id == id)).select(table.first_name, table.last_name, limitby=(0, 1)).first() try: return s3_format_fullname(row.first_name.strip(), None, row.last_name.strip()) except: return current.messages.UNKNOWN_OPT
[ "def", "s3_auth_user_represent_name", "(", "id", ",", "row", "=", "None", ")", ":", "if", "(", "not", "row", ")", ":", "if", "(", "not", "id", ")", ":", "return", "current", ".", "messages", "[", "'NONE'", "]", "db", "=", "current", ".", "db", "tab...
represent users by their names .
train
false
32,508
def remove_old_versions(db): start = ('%s.%s.0' % (major, minor)) migrate_features = 1 if snapshot: add_data(db, 'Upgrade', [(upgrade_code_snapshot, start, current_version, None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT' else: add_data(db, 'Upgrade', [(upgrade_code, start, current_version, None, migrate_features, None, 'REMOVEOLDVERSION'), (upgrade_code_snapshot, start, ('%s.%d.0' % (major, (int(minor) + 1))), None, migrate_features, None, 'REMOVEOLDSNAPSHOT')]) props = 'REMOVEOLDSNAPSHOT;REMOVEOLDVERSION' props += ';TARGETDIR;DLLDIR;LAUNCHERDIR' add_data(db, 'Property', [('SecureCustomProperties', props)])
[ "def", "remove_old_versions", "(", "db", ")", ":", "start", "=", "(", "'%s.%s.0'", "%", "(", "major", ",", "minor", ")", ")", "migrate_features", "=", "1", "if", "snapshot", ":", "add_data", "(", "db", ",", "'Upgrade'", ",", "[", "(", "upgrade_code_snaps...
fill the upgrade table .
train
false
32,509
def test_step_definition(): def dumb(): pass definition = core.StepDefinition('FOO BAR', dumb) assert_equals(definition.function, dumb) assert_equals(definition.file, core.fs.relpath(__file__).rstrip('c')) assert_equals(definition.line, 39)
[ "def", "test_step_definition", "(", ")", ":", "def", "dumb", "(", ")", ":", "pass", "definition", "=", "core", ".", "StepDefinition", "(", "'FOO BAR'", ",", "dumb", ")", "assert_equals", "(", "definition", ".", "function", ",", "dumb", ")", "assert_equals", ...
step definition takes a function and a step .
train
false
32,510
def endsInNewline(s): return (s[(- len('\n')):] == '\n')
[ "def", "endsInNewline", "(", "s", ")", ":", "return", "(", "s", "[", "(", "-", "len", "(", "'\\n'", ")", ")", ":", "]", "==", "'\\n'", ")" ]
returns true if this string ends in a newline .
train
false
32,512
def format_xml_exception_message(location, key, value): exception_message = 'Block-location:{location}, Key:{key}, Value:{value}'.format(location=unicode(location), key=key, value=value) return exception_message
[ "def", "format_xml_exception_message", "(", "location", ",", "key", ",", "value", ")", ":", "exception_message", "=", "'Block-location:{location}, Key:{key}, Value:{value}'", ".", "format", "(", "location", "=", "unicode", "(", "location", ")", ",", "key", "=", "key...
generate exception message for videodescriptor class which will use for valueerror and unicodedecodeerror when setting xml attributes .
train
false
32,514
def _clickthrough_rate(impressions, clicks): if impressions: return ((float(clicks) / impressions) * 100.0) else: return 0
[ "def", "_clickthrough_rate", "(", "impressions", ",", "clicks", ")", ":", "if", "impressions", ":", "return", "(", "(", "float", "(", "clicks", ")", "/", "impressions", ")", "*", "100.0", ")", "else", ":", "return", "0" ]
return the click-through rate percentage .
train
false
32,516
def split_pulls(all_issues, project='ipython/ipython'): pulls = [] issues = [] for i in all_issues: if is_pull_request(i): pull = get_pull_request(project, i['number'], auth=True) pulls.append(pull) else: issues.append(i) return (issues, pulls)
[ "def", "split_pulls", "(", "all_issues", ",", "project", "=", "'ipython/ipython'", ")", ":", "pulls", "=", "[", "]", "issues", "=", "[", "]", "for", "i", "in", "all_issues", ":", "if", "is_pull_request", "(", "i", ")", ":", "pull", "=", "get_pull_request...
split a list of closed issues into non-pr issues and pull requests .
train
true
32,519
def most_popular_groups(): groups = toolkit.get_action('group_list')(data_dict={'sort': 'packages desc', 'all_fields': True}) groups = groups[:10] return groups
[ "def", "most_popular_groups", "(", ")", ":", "groups", "=", "toolkit", ".", "get_action", "(", "'group_list'", ")", "(", "data_dict", "=", "{", "'sort'", ":", "'packages desc'", ",", "'all_fields'", ":", "True", "}", ")", "groups", "=", "groups", "[", ":",...
return a sorted list of the groups with the most datasets .
train
false
32,522
def _api_config(name, output, kwargs): return _api_config_table.get(name, (_api_config_undefined, 2))[0](output, kwargs)
[ "def", "_api_config", "(", "name", ",", "output", ",", "kwargs", ")", ":", "return", "_api_config_table", ".", "get", "(", "name", ",", "(", "_api_config_undefined", ",", "2", ")", ")", "[", "0", "]", "(", "output", ",", "kwargs", ")" ]
api: dispatcher for "config" .
train
false
32,524
def getGeometryOutputByNegativesPositives(elementNode, negatives, positives): positiveOutput = triangle_mesh.getUnifiedOutput(positives) if (len(negatives) < 1): return solid.getGeometryOutputByManipulation(elementNode, positiveOutput) if (len(positives) < 1): negativeOutput = triangle_mesh.getUnifiedOutput(negatives) return solid.getGeometryOutputByManipulation(elementNode, negativeOutput) return solid.getGeometryOutputByManipulation(elementNode, {'difference': {'shapes': ([positiveOutput] + negatives)}})
[ "def", "getGeometryOutputByNegativesPositives", "(", "elementNode", ",", "negatives", ",", "positives", ")", ":", "positiveOutput", "=", "triangle_mesh", ".", "getUnifiedOutput", "(", "positives", ")", "if", "(", "len", "(", "negatives", ")", "<", "1", ")", ":",...
get triangle mesh from elementnode .
train
false
32,525
def _get_cache_version(): from django.core.cache import cache version = cache.get(CMS_PAGE_CACHE_VERSION_KEY) if version: return version else: _set_cache_version(1) return 1
[ "def", "_get_cache_version", "(", ")", ":", "from", "django", ".", "core", ".", "cache", "import", "cache", "version", "=", "cache", ".", "get", "(", "CMS_PAGE_CACHE_VERSION_KEY", ")", "if", "version", ":", "return", "version", "else", ":", "_set_cache_version...
returns the current page cache version .
train
false
32,526
def test_detrend(): (raw, events, picks) = _get_data() epochs_1 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=None, detrend=1) epochs_2 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=None, detrend=None) data_picks = pick_types(epochs_1.info, meg=True, eeg=True, exclude='bads') evoked_1 = epochs_1.average() evoked_2 = epochs_2.average() evoked_2.detrend(1) assert_true(np.allclose(evoked_1.data, evoked_2.data, rtol=1e-08, atol=1e-20)) for preload in [True, False]: epochs_1 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=(None, None), preload=preload) epochs_2 = Epochs(raw, events[:4], event_id, tmin, tmax, picks=picks, baseline=None, preload=preload, detrend=0) a = epochs_1.get_data() b = epochs_2.get_data() assert_true(np.allclose(a[:, data_picks, :], b[:, data_picks, :], rtol=1e-16, atol=1e-20)) assert_true((not np.allclose(a, b))) for value in ['foo', 2, False, True]: assert_raises(ValueError, Epochs, raw, events[:4], event_id, tmin, tmax, detrend=value)
[ "def", "test_detrend", "(", ")", ":", "(", "raw", ",", "events", ",", "picks", ")", "=", "_get_data", "(", ")", "epochs_1", "=", "Epochs", "(", "raw", ",", "events", "[", ":", "4", "]", ",", "event_id", ",", "tmin", ",", "tmax", ",", "picks", "="...
test zeroth and first order detrending .
train
false
32,527
def _endpoint(name, ignore_body=False): def decorator(f): @wraps(f) @structured(inputSchema={}, outputSchema={u'$ref': (u'/endpoints.json#/definitions/' + name)}, schema_store=SCHEMAS, ignore_body=ignore_body) def wrapped(*args, **kwargs): d = maybeDeferred(f, *args, **kwargs) def handle_error(failure): if failure.check(BadRequest): code = failure.value.code body = failure.value.result else: writeFailure(failure) code = OK body = {u'Err': u'{}: {}'.format(failure.type.__name__, failure.value)} return EndpointResponse(code, body) d.addErrback(handle_error) return d return wrapped return decorator
[ "def", "_endpoint", "(", "name", ",", "ignore_body", "=", "False", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "@", "structured", "(", "inputSchema", "=", "{", "}", ",", "outputSchema", "=", "{", "u'$ref'", ":", "...
decorator factory for api endpoints .
train
false
32,528
def getIdentityMatrixTetragrid(tetragrid=None): if (tetragrid == None): return [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] return tetragrid
[ "def", "getIdentityMatrixTetragrid", "(", "tetragrid", "=", "None", ")", ":", "if", "(", "tetragrid", "==", "None", ")", ":", "return", "[", "[", "1.0", ",", "0.0", ",", "0.0", ",", "0.0", "]", ",", "[", "0.0", ",", "1.0", ",", "0.0", ",", "0.0", ...
get four by four matrix with diagonal elements set to one .
train
false
32,529
def repr_active(h): return u', '.join((repr_readers(h) + repr_writers(h)))
[ "def", "repr_active", "(", "h", ")", ":", "return", "u', '", ".", "join", "(", "(", "repr_readers", "(", "h", ")", "+", "repr_writers", "(", "h", ")", ")", ")" ]
return description of active readers and writers .
train
false
32,530
def test_combine(): global log def f(sender, args): global log log += 'f' def g(sender, args): global log log += 'g' fe = System.EventHandler(f) ge = System.EventHandler(g) fege = fe fege += ge log = '' fege(None, None) AreEqual(log, 'fg') log = '' fe(None, None) AreEqual(log, 'f') log = '' ge(None, None) AreEqual(log, 'g') fege -= ge log = '' fege(None, None) AreEqual(log, 'f')
[ "def", "test_combine", "(", ")", ":", "global", "log", "def", "f", "(", "sender", ",", "args", ")", ":", "global", "log", "log", "+=", "'f'", "def", "g", "(", "sender", ",", "args", ")", ":", "global", "log", "log", "+=", "'g'", "fe", "=", "Syste...
in-place addition on delegates maps to delegate .
train
false
32,531
def path_info_pop(environ): path = environ.get('PATH_INFO', '') if (not path): return None while path.startswith('/'): environ['SCRIPT_NAME'] += '/' path = path[1:] if ('/' not in path): environ['SCRIPT_NAME'] += path environ['PATH_INFO'] = '' return path else: (segment, path) = path.split('/', 1) environ['PATH_INFO'] = ('/' + path) environ['SCRIPT_NAME'] += segment return segment
[ "def", "path_info_pop", "(", "environ", ")", ":", "path", "=", "environ", ".", "get", "(", "'PATH_INFO'", ",", "''", ")", "if", "(", "not", "path", ")", ":", "return", "None", "while", "path", ".", "startswith", "(", "'/'", ")", ":", "environ", "[", ...
pops off the next segment of path_info .
train
false
32,533
def _CanViewViewpointContent(viewpoint, follower): if ((viewpoint is None) or (follower is None) or (not follower.CanViewContent())): return False if (viewpoint.IsSystem() or base.ViewfinderContext.current().CanViewViewpoint(viewpoint.viewpoint_id)): return True return False
[ "def", "_CanViewViewpointContent", "(", "viewpoint", ",", "follower", ")", ":", "if", "(", "(", "viewpoint", "is", "None", ")", "or", "(", "follower", "is", "None", ")", "or", "(", "not", "follower", ".", "CanViewContent", "(", ")", ")", ")", ":", "ret...
returns true if the given follower is allowed to view the viewpoints content: 1 .
train
false
32,535
def to_cpu(array, stream=None): if isinstance(array, ndarray): check_cuda_available() with get_device(array): return array.get(stream) elif isinstance(array, numpy.ndarray): return array else: raise TypeError('The array sent to cpu must be numpy.ndarray or cupy.ndarray.\nActual type: {0}.'.format(type(array)))
[ "def", "to_cpu", "(", "array", ",", "stream", "=", "None", ")", ":", "if", "isinstance", "(", "array", ",", "ndarray", ")", ":", "check_cuda_available", "(", ")", "with", "get_device", "(", "array", ")", ":", "return", "array", ".", "get", "(", "stream...
copies the given gpu array to host cpu .
train
false
32,537
@_docstring('area') def get_area_by_id(id, includes=[], release_status=[], release_type=[]): params = _check_filter_and_make_params('area', includes, release_status, release_type) return _do_mb_query('area', id, includes, params)
[ "@", "_docstring", "(", "'area'", ")", "def", "get_area_by_id", "(", "id", ",", "includes", "=", "[", "]", ",", "release_status", "=", "[", "]", ",", "release_type", "=", "[", "]", ")", ":", "params", "=", "_check_filter_and_make_params", "(", "'area'", ...
get the area with the musicbrainz id as a dict with an area key .
train
false
32,538
def repository_exists(client, repository=None): if (not repository): raise MissingArgument('No value for "repository" provided') test_result = get_repository(client, repository) if (repository in test_result): logger.debug('Repository {0} exists.'.format(repository)) return True else: logger.debug('Repository {0} not found...'.format(repository)) return False
[ "def", "repository_exists", "(", "client", ",", "repository", "=", "None", ")", ":", "if", "(", "not", "repository", ")", ":", "raise", "MissingArgument", "(", "'No value for \"repository\" provided'", ")", "test_result", "=", "get_repository", "(", "client", ",",...
verify the existence of a repository :arg client: an :class:elasticsearch .
train
false
32,540
def load_fonts(): all_fonts = (glob.glob('out/RobotoTTF/*.ttf') + glob.glob('out/RobotoCondensedTTF/*.ttf')) all_fonts = [ttLib.TTFont(font) for font in all_fonts] return all_fonts
[ "def", "load_fonts", "(", ")", ":", "all_fonts", "=", "(", "glob", ".", "glob", "(", "'out/RobotoTTF/*.ttf'", ")", "+", "glob", ".", "glob", "(", "'out/RobotoCondensedTTF/*.ttf'", ")", ")", "all_fonts", "=", "[", "ttLib", ".", "TTFont", "(", "font", ")", ...
load all fonts built for android .
train
false
32,541
def test_renn_init(): renn = RepeatedEditedNearestNeighbours(random_state=RND_SEED) assert_equal(renn.n_neighbors, 3) assert_equal(renn.kind_sel, 'all') assert_equal(renn.n_jobs, (-1)) assert_equal(renn.random_state, RND_SEED)
[ "def", "test_renn_init", "(", ")", ":", "renn", "=", "RepeatedEditedNearestNeighbours", "(", "random_state", "=", "RND_SEED", ")", "assert_equal", "(", "renn", ".", "n_neighbors", ",", "3", ")", "assert_equal", "(", "renn", ".", "kind_sel", ",", "'all'", ")", ...
test the initialisation of the object .
train
false
32,542
def for_type_by_name(type_module, type_name, func): key = (type_module, type_name) oldfunc = _deferred_type_pprinters.get(key, None) if (func is not None): _deferred_type_pprinters[key] = func return oldfunc
[ "def", "for_type_by_name", "(", "type_module", ",", "type_name", ",", "func", ")", ":", "key", "=", "(", "type_module", ",", "type_name", ")", "oldfunc", "=", "_deferred_type_pprinters", ".", "get", "(", "key", ",", "None", ")", "if", "(", "func", "is", ...
add a pretty printer for a type specified by the module and name of a type rather than the type object itself .
train
true
32,543
def Join(*parts): return '/'.join(parts)
[ "def", "Join", "(", "*", "parts", ")", ":", "return", "'/'", ".", "join", "(", "parts", ")" ]
join paths without normalizing .
train
false
32,545
def dependency_dict(dsk): dep_dict = {} for key in dsk: deps = tuple(get_dependencies(dsk, key, True)) dep_dict.setdefault(deps, []).append(key) return dep_dict
[ "def", "dependency_dict", "(", "dsk", ")", ":", "dep_dict", "=", "{", "}", "for", "key", "in", "dsk", ":", "deps", "=", "tuple", "(", "get_dependencies", "(", "dsk", ",", "key", ",", "True", ")", ")", "dep_dict", ".", "setdefault", "(", "deps", ",", ...
create a dict matching ordered dependencies to keys .
train
false
32,547
def get_loglevel(level): if isinstance(level, string_t): return LOG_LEVELS[level] return level
[ "def", "get_loglevel", "(", "level", ")", ":", "if", "isinstance", "(", "level", ",", "string_t", ")", ":", "return", "LOG_LEVELS", "[", "level", "]", "return", "level" ]
get loglevel by name .
train
false
32,548
def run_pep8_for_package(package_name, extra_ignore=None): import pep8 class Checker(pep8.Checker, ): u"\n Subclass pep8's Checker to hook into error reporting.\n " def __init__(self, *args, **kwargs): super(Checker, self).__init__(*args, **kwargs) self.report_error = self._report_error def _report_error(self, line_number, offset, text, check): u'\n Store pairs of line numbers and errors.\n ' self.errors.append((line_number, text.split(u' ', 1)[1])) def check_all(self, *args, **kwargs): u'\n Assign the errors attribute and return it after running.\n ' self.errors = [] super(Checker, self).check_all(*args, **kwargs) return self.errors def pep8_checker(path): for (line_number, text) in Checker(path).check_all(): (yield (u'%s:%s: %s' % (path, line_number, text))) args = (pep8_checker, package_name, extra_ignore) return _run_checker_for_package(*args)
[ "def", "run_pep8_for_package", "(", "package_name", ",", "extra_ignore", "=", "None", ")", ":", "import", "pep8", "class", "Checker", "(", "pep8", ".", "Checker", ",", ")", ":", "def", "__init__", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ...
if pep8 is installed .
train
false
32,549
def module_admin_required(module_name=None): if (not module_name): module_name = 'treeio.core' def wrap(f): 'Wrap' def wrapped_f(cls, request, *args, **kwargs): 'Wrapped' if request.user.profile.is_admin(module_name): return f(cls, request, *args, **kwargs) else: return rc.FORBIDDEN wrapped_f.__doc__ = f.__doc__ wrapped_f.__name__ = f.__name__ return wrapped_f return wrap
[ "def", "module_admin_required", "(", "module_name", "=", "None", ")", ":", "if", "(", "not", "module_name", ")", ":", "module_name", "=", "'treeio.core'", "def", "wrap", "(", "f", ")", ":", "def", "wrapped_f", "(", "cls", ",", "request", ",", "*", "args"...
check that the user has write access to the treeio .
train
false
32,552
def named_validator(optdict, name, value): return optik_ext.check_named(None, name, value)
[ "def", "named_validator", "(", "optdict", ",", "name", ",", "value", ")", ":", "return", "optik_ext", ".", "check_named", "(", "None", ",", "name", ",", "value", ")" ]
validate and return a converted value for option of type named .
train
false
32,553
@cache def geosearch(latitude, longitude, title=None, results=10, radius=1000): search_params = {u'list': u'geosearch', u'gsradius': radius, u'gscoord': u'{0}|{1}'.format(latitude, longitude), u'gslimit': results} if title: search_params[u'titles'] = title raw_results = _wiki_request(search_params) if (u'error' in raw_results): if (raw_results[u'error'][u'info'] in (u'HTTP request timed out.', u'Pool queue is full')): raise HTTPTimeoutError(u'{0}|{1}'.format(latitude, longitude)) else: raise WikipediaException(raw_results[u'error'][u'info']) search_pages = raw_results[u'query'].get(u'pages', None) if search_pages: search_results = (v[u'title'] for (k, v) in search_pages.items() if (k != u'-1')) else: search_results = (d[u'title'] for d in raw_results[u'query'][u'geosearch']) return list(search_results)
[ "@", "cache", "def", "geosearch", "(", "latitude", ",", "longitude", ",", "title", "=", "None", ",", "results", "=", "10", ",", "radius", "=", "1000", ")", ":", "search_params", "=", "{", "u'list'", ":", "u'geosearch'", ",", "u'gsradius'", ":", "radius",...
do a wikipedia geo search for latitude and longitude using http api described in URL arguments: * latitude * longitude keyword arguments: * title - the title of an article to search for * results - the maximum number of results returned * radius - search radius in meters .
train
false
32,554
def create_loader(search_path_string=None): if (search_path_string is None): return Loader() paths = [] extra_paths = search_path_string.split(os.pathsep) for path in extra_paths: path = os.path.expanduser(os.path.expandvars(path)) paths.append(path) return Loader(extra_search_paths=paths)
[ "def", "create_loader", "(", "search_path_string", "=", "None", ")", ":", "if", "(", "search_path_string", "is", "None", ")", ":", "return", "Loader", "(", ")", "paths", "=", "[", "]", "extra_paths", "=", "search_path_string", ".", "split", "(", "os", ".",...
create a loader class .
train
false
32,555
def _escape_fstab(v): if isinstance(v, int): return v else: return v.replace('\\', '\\134').replace(' ', '\\040').replace('&', '\\046')
[ "def", "_escape_fstab", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "int", ")", ":", "return", "v", "else", ":", "return", "v", ".", "replace", "(", "'\\\\'", ",", "'\\\\134'", ")", ".", "replace", "(", "' '", ",", "'\\\\040'", ")", ".",...
escape invalid characters in fstab fields .
train
false
32,556
def _read_events(fid, info): events = np.zeros([info['n_events'], (info['n_segments'] * info['n_samples'])]) fid.seek((36 + (info['n_events'] * 4)), 0) for si in range(info['n_samples']): fid.seek((info['n_channels'] * info['dtype'].itemsize), 1) events[:, si] = np.fromfile(fid, info['dtype'], info['n_events']) return events
[ "def", "_read_events", "(", "fid", ",", "info", ")", ":", "events", "=", "np", ".", "zeros", "(", "[", "info", "[", "'n_events'", "]", ",", "(", "info", "[", "'n_segments'", "]", "*", "info", "[", "'n_samples'", "]", ")", "]", ")", "fid", ".", "s...
read events .
train
false
32,557
def get_transfer_command(command, recursive, quiet): cli_command = ('aws s3 ' + command) if recursive: cli_command += ' --recursive' if quiet: cli_command += ' --quiet' else: print cli_command return cli_command
[ "def", "get_transfer_command", "(", "command", ",", "recursive", ",", "quiet", ")", ":", "cli_command", "=", "(", "'aws s3 '", "+", "command", ")", "if", "recursive", ":", "cli_command", "+=", "' --recursive'", "if", "quiet", ":", "cli_command", "+=", "' --qui...
get a full cli transfer command .
train
false
32,558
def get_subjects_dir(subjects_dir=None, raise_error=False): if (subjects_dir is None): subjects_dir = get_config('SUBJECTS_DIR', raise_error=raise_error) return subjects_dir
[ "def", "get_subjects_dir", "(", "subjects_dir", "=", "None", ",", "raise_error", "=", "False", ")", ":", "if", "(", "subjects_dir", "is", "None", ")", ":", "subjects_dir", "=", "get_config", "(", "'SUBJECTS_DIR'", ",", "raise_error", "=", "raise_error", ")", ...
safely use subjects_dir input to return subjects_dir .
train
false
32,559
@library.global_function def user_is_curator(group, userprofile): return group.curators.filter(id=userprofile.id).exists()
[ "@", "library", ".", "global_function", "def", "user_is_curator", "(", "group", ",", "userprofile", ")", ":", "return", "group", ".", "curators", ".", "filter", "(", "id", "=", "userprofile", ".", "id", ")", ".", "exists", "(", ")" ]
check if a user is curator in the specific group .
train
false
32,560
def test_list(test_data): ds = ChartDataSource.from_data(*test_data.list_data) assert (len(ds.columns) == 2) assert (len(ds.index) == 4)
[ "def", "test_list", "(", "test_data", ")", ":", "ds", "=", "ChartDataSource", ".", "from_data", "(", "*", "test_data", ".", "list_data", ")", "assert", "(", "len", "(", "ds", ".", "columns", ")", "==", "2", ")", "assert", "(", "len", "(", "ds", ".", ...
test creating chart data source from array-like list data .
train
false
32,561
def sdm_strip(f): return [(monom, coeff) for (monom, coeff) in f if coeff]
[ "def", "sdm_strip", "(", "f", ")", ":", "return", "[", "(", "monom", ",", "coeff", ")", "for", "(", "monom", ",", "coeff", ")", "in", "f", "if", "coeff", "]" ]
remove terms with zero coefficients from f in k[x] .
train
false
32,563
def _pd_to_hdf(pd_to_hdf, lock, args, kwargs=None): if lock: lock.acquire() try: pd_to_hdf(*args, **kwargs) finally: if lock: lock.release() return None
[ "def", "_pd_to_hdf", "(", "pd_to_hdf", ",", "lock", ",", "args", ",", "kwargs", "=", "None", ")", ":", "if", "lock", ":", "lock", ".", "acquire", "(", ")", "try", ":", "pd_to_hdf", "(", "*", "args", ",", "**", "kwargs", ")", "finally", ":", "if", ...
a wrapper function around pd_to_hdf that enables locking .
train
false
32,564
def path_match_patterns(path, patterns): for pattern in patterns: if fnmatch.fnmatch(path, pattern): return True return False
[ "def", "path_match_patterns", "(", "path", ",", "patterns", ")", ":", "for", "pattern", "in", "patterns", ":", "if", "fnmatch", ".", "fnmatch", "(", "path", ",", "pattern", ")", ":", "return", "True", "return", "False" ]
check if a path matches one or more patterns .
train
false
32,565
def _build_precondition_join_fn(cls, fn): old_precondition = cls.check_precondition def check_precondition(): (result, message) = fn() if (not result): return (result, message) return old_precondition() return staticmethod(check_precondition)
[ "def", "_build_precondition_join_fn", "(", "cls", ",", "fn", ")", ":", "old_precondition", "=", "cls", ".", "check_precondition", "def", "check_precondition", "(", ")", ":", "(", "result", ",", "message", ")", "=", "fn", "(", ")", "if", "(", "not", "result...
build a check_precondition function that uses both the old precondition check as well as the new function fn cls: class whose check_precondition should be used as a base fn: check_precondition function to check returns a function that can replace a handler check_precondition method .
train
false