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
47,906
def serial_listen_ports(migrate_data): ports = [] if migrate_data.obj_attr_is_set('serial_listen_ports'): ports = migrate_data.serial_listen_ports return ports
[ "def", "serial_listen_ports", "(", "migrate_data", ")", ":", "ports", "=", "[", "]", "if", "migrate_data", ".", "obj_attr_is_set", "(", "'serial_listen_ports'", ")", ":", "ports", "=", "migrate_data", ".", "serial_listen_ports", "return", "ports" ]
returns ports serial from a libvirtlivemigratedata .
train
false
47,907
def tileswrap(ihtORsize, numtilings, floats, wrapwidths, ints=[], readonly=False): qfloats = [floor((f * numtilings)) for f in floats] Tiles = [] for tiling in range(numtilings): tilingX2 = (tiling * 2) coords = [tiling] b = tiling for (q, width) in zip_longest(qfloats, wrapwidths): c = ((q + (b % numtilings)) // numtilings) coords.append(((c % width) if width else c)) b += tilingX2 coords.extend(ints) Tiles.append(hashcoords(coords, ihtORsize, readonly)) return Tiles
[ "def", "tileswrap", "(", "ihtORsize", ",", "numtilings", ",", "floats", ",", "wrapwidths", ",", "ints", "=", "[", "]", ",", "readonly", "=", "False", ")", ":", "qfloats", "=", "[", "floor", "(", "(", "f", "*", "numtilings", ")", ")", "for", "f", "in", "floats", "]", "Tiles", "=", "[", "]", "for", "tiling", "in", "range", "(", "numtilings", ")", ":", "tilingX2", "=", "(", "tiling", "*", "2", ")", "coords", "=", "[", "tiling", "]", "b", "=", "tiling", "for", "(", "q", ",", "width", ")", "in", "zip_longest", "(", "qfloats", ",", "wrapwidths", ")", ":", "c", "=", "(", "(", "q", "+", "(", "b", "%", "numtilings", ")", ")", "//", "numtilings", ")", "coords", ".", "append", "(", "(", "(", "c", "%", "width", ")", "if", "width", "else", "c", ")", ")", "b", "+=", "tilingX2", "coords", ".", "extend", "(", "ints", ")", "Tiles", ".", "append", "(", "hashcoords", "(", "coords", ",", "ihtORsize", ",", "readonly", ")", ")", "return", "Tiles" ]
returns num-tilings tile indices corresponding to the floats and ints .
train
false
47,908
def to_pandas_dataframe(G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight='weight', nonedge=0.0): import pandas as pd M = to_numpy_matrix(G, nodelist=nodelist, dtype=dtype, order=order, multigraph_weight=multigraph_weight, weight=weight, nonedge=nonedge) if (nodelist is None): nodelist = list(G) return pd.DataFrame(data=M, index=nodelist, columns=nodelist)
[ "def", "to_pandas_dataframe", "(", "G", ",", "nodelist", "=", "None", ",", "dtype", "=", "None", ",", "order", "=", "None", ",", "multigraph_weight", "=", "sum", ",", "weight", "=", "'weight'", ",", "nonedge", "=", "0.0", ")", ":", "import", "pandas", "as", "pd", "M", "=", "to_numpy_matrix", "(", "G", ",", "nodelist", "=", "nodelist", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", "multigraph_weight", "=", "multigraph_weight", ",", "weight", "=", "weight", ",", "nonedge", "=", "nonedge", ")", "if", "(", "nodelist", "is", "None", ")", ":", "nodelist", "=", "list", "(", "G", ")", "return", "pd", ".", "DataFrame", "(", "data", "=", "M", ",", "index", "=", "nodelist", ",", "columns", "=", "nodelist", ")" ]
return the graph adjacency matrix as a pandas dataframe .
train
false
47,909
def define_rss(): global CFG try: for r in CFG['rss']: ConfigRSS(r, CFG['rss'][r]) except KeyError: pass
[ "def", "define_rss", "(", ")", ":", "global", "CFG", "try", ":", "for", "r", "in", "CFG", "[", "'rss'", "]", ":", "ConfigRSS", "(", "r", ",", "CFG", "[", "'rss'", "]", "[", "r", "]", ")", "except", "KeyError", ":", "pass" ]
define rss-feeds listed in the setup file return a list of configrss instances .
train
false
47,911
@bdd.then(bdd.parsers.parse('The requests should be:\n{pages}')) def list_of_requests(httpbin, pages): expected_requests = [httpbin.ExpectedRequest('GET', ('/' + path.strip())) for path in pages.split('\n')] actual_requests = httpbin.get_requests() assert (actual_requests == expected_requests)
[ "@", "bdd", ".", "then", "(", "bdd", ".", "parsers", ".", "parse", "(", "'The requests should be:\\n{pages}'", ")", ")", "def", "list_of_requests", "(", "httpbin", ",", "pages", ")", ":", "expected_requests", "=", "[", "httpbin", ".", "ExpectedRequest", "(", "'GET'", ",", "(", "'/'", "+", "path", ".", "strip", "(", ")", ")", ")", "for", "path", "in", "pages", ".", "split", "(", "'\\n'", ")", "]", "actual_requests", "=", "httpbin", ".", "get_requests", "(", ")", "assert", "(", "actual_requests", "==", "expected_requests", ")" ]
make sure the given requests were done from the webserver .
train
false
47,914
def apply_func_to_match_groups(match, func=icu_upper, handle_entities=handle_entities): found_groups = False i = 0 (parts, pos) = ([], match.start()) f = (lambda text: handle_entities(text, func)) while True: i += 1 try: (start, end) = match.span(i) except IndexError: break found_groups = True if (start > (-1)): parts.append(match.string[pos:start]) parts.append(f(match.string[start:end])) pos = end if (not found_groups): return f(match.group()) parts.append(match.string[pos:match.end()]) return u''.join(parts)
[ "def", "apply_func_to_match_groups", "(", "match", ",", "func", "=", "icu_upper", ",", "handle_entities", "=", "handle_entities", ")", ":", "found_groups", "=", "False", "i", "=", "0", "(", "parts", ",", "pos", ")", "=", "(", "[", "]", ",", "match", ".", "start", "(", ")", ")", "f", "=", "(", "lambda", "text", ":", "handle_entities", "(", "text", ",", "func", ")", ")", "while", "True", ":", "i", "+=", "1", "try", ":", "(", "start", ",", "end", ")", "=", "match", ".", "span", "(", "i", ")", "except", "IndexError", ":", "break", "found_groups", "=", "True", "if", "(", "start", ">", "(", "-", "1", ")", ")", ":", "parts", ".", "append", "(", "match", ".", "string", "[", "pos", ":", "start", "]", ")", "parts", ".", "append", "(", "f", "(", "match", ".", "string", "[", "start", ":", "end", "]", ")", ")", "pos", "=", "end", "if", "(", "not", "found_groups", ")", ":", "return", "f", "(", "match", ".", "group", "(", ")", ")", "parts", ".", "append", "(", "match", ".", "string", "[", "pos", ":", "match", ".", "end", "(", ")", "]", ")", "return", "u''", ".", "join", "(", "parts", ")" ]
apply the specified function to individual groups in the match object (the result of re .
train
false
47,915
def shannonentropy(px, logbase=2): px = np.asarray(px) if ((not np.all((px <= 1))) or (not np.all((px >= 0)))): raise ValueError('px does not define proper distribution') entropy = (- np.sum(np.nan_to_num((px * np.log2(px))))) if (logbase != 2): return (logbasechange(2, logbase) * entropy) else: return entropy
[ "def", "shannonentropy", "(", "px", ",", "logbase", "=", "2", ")", ":", "px", "=", "np", ".", "asarray", "(", "px", ")", "if", "(", "(", "not", "np", ".", "all", "(", "(", "px", "<=", "1", ")", ")", ")", "or", "(", "not", "np", ".", "all", "(", "(", "px", ">=", "0", ")", ")", ")", ")", ":", "raise", "ValueError", "(", "'px does not define proper distribution'", ")", "entropy", "=", "(", "-", "np", ".", "sum", "(", "np", ".", "nan_to_num", "(", "(", "px", "*", "np", ".", "log2", "(", "px", ")", ")", ")", ")", ")", "if", "(", "logbase", "!=", "2", ")", ":", "return", "(", "logbasechange", "(", "2", ",", "logbase", ")", "*", "entropy", ")", "else", ":", "return", "entropy" ]
this is shannons entropy parameters logbase .
train
false
47,916
def generic_find_constraint_name(table, columns, referenced, db): t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for fk in t.foreign_key_constraints: if ((fk.referred_table.name == referenced) and (set(fk.column_keys) == columns)): return fk.name
[ "def", "generic_find_constraint_name", "(", "table", ",", "columns", ",", "referenced", ",", "db", ")", ":", "t", "=", "sa", ".", "Table", "(", "table", ",", "db", ".", "metadata", ",", "autoload", "=", "True", ",", "autoload_with", "=", "db", ".", "engine", ")", "for", "fk", "in", "t", ".", "foreign_key_constraints", ":", "if", "(", "(", "fk", ".", "referred_table", ".", "name", "==", "referenced", ")", "and", "(", "set", "(", "fk", ".", "column_keys", ")", "==", "columns", ")", ")", ":", "return", "fk", ".", "name" ]
utility to find a constraint name in alembic migrations .
train
true
47,917
def classify_cert(cert_meta, now, time_remaining, expire_window, cert_list): expiry_str = str(cert_meta['expiry']) if (cert_meta['expiry'] < now): cert_meta['health'] = 'expired' elif (time_remaining < expire_window): cert_meta['health'] = 'warning' else: cert_meta['health'] = 'ok' cert_meta['expiry'] = expiry_str cert_meta['serial_hex'] = hex(int(cert_meta['serial'])) cert_list.append(cert_meta) return cert_list
[ "def", "classify_cert", "(", "cert_meta", ",", "now", ",", "time_remaining", ",", "expire_window", ",", "cert_list", ")", ":", "expiry_str", "=", "str", "(", "cert_meta", "[", "'expiry'", "]", ")", "if", "(", "cert_meta", "[", "'expiry'", "]", "<", "now", ")", ":", "cert_meta", "[", "'health'", "]", "=", "'expired'", "elif", "(", "time_remaining", "<", "expire_window", ")", ":", "cert_meta", "[", "'health'", "]", "=", "'warning'", "else", ":", "cert_meta", "[", "'health'", "]", "=", "'ok'", "cert_meta", "[", "'expiry'", "]", "=", "expiry_str", "cert_meta", "[", "'serial_hex'", "]", "=", "hex", "(", "int", "(", "cert_meta", "[", "'serial'", "]", ")", ")", "cert_list", ".", "append", "(", "cert_meta", ")", "return", "cert_list" ]
given metadata about a certificate under examination .
train
false
47,918
def isShellBuiltin(cmd): if (isShellBuiltin.builtIns is None): isShellBuiltin.builtIns = quietRun('bash -c enable') space = cmd.find(' ') if (space > 0): cmd = cmd[:space] return (cmd in isShellBuiltin.builtIns)
[ "def", "isShellBuiltin", "(", "cmd", ")", ":", "if", "(", "isShellBuiltin", ".", "builtIns", "is", "None", ")", ":", "isShellBuiltin", ".", "builtIns", "=", "quietRun", "(", "'bash -c enable'", ")", "space", "=", "cmd", ".", "find", "(", "' '", ")", "if", "(", "space", ">", "0", ")", ":", "cmd", "=", "cmd", "[", ":", "space", "]", "return", "(", "cmd", "in", "isShellBuiltin", ".", "builtIns", ")" ]
return true if cmd is a bash builtin .
train
false
47,920
def aggregate_get_by_host(context, host, key=None): return IMPL.aggregate_get_by_host(context, host, key)
[ "def", "aggregate_get_by_host", "(", "context", ",", "host", ",", "key", "=", "None", ")", ":", "return", "IMPL", ".", "aggregate_get_by_host", "(", "context", ",", "host", ",", "key", ")" ]
get a list of aggregates that host belongs to .
train
false
47,921
def _has_rational_power(expr, symbol): (a, p, q) = (Wild('a'), Wild('p'), Wild('q')) pattern_match = (expr.match((a * (p ** q))) or {}) if (pattern_match.get(a, S.Zero) is S.Zero): return (False, S.One) elif (p not in pattern_match.keys()): return (False, S.One) elif (isinstance(pattern_match[q], Rational) and pattern_match[p].has(symbol)): if (not (pattern_match[q].q == S.One)): return (True, pattern_match[q].q) if ((not isinstance(pattern_match[a], Pow)) or isinstance(pattern_match[a], Mul)): return (False, S.One) else: return _has_rational_power(pattern_match[a], symbol)
[ "def", "_has_rational_power", "(", "expr", ",", "symbol", ")", ":", "(", "a", ",", "p", ",", "q", ")", "=", "(", "Wild", "(", "'a'", ")", ",", "Wild", "(", "'p'", ")", ",", "Wild", "(", "'q'", ")", ")", "pattern_match", "=", "(", "expr", ".", "match", "(", "(", "a", "*", "(", "p", "**", "q", ")", ")", ")", "or", "{", "}", ")", "if", "(", "pattern_match", ".", "get", "(", "a", ",", "S", ".", "Zero", ")", "is", "S", ".", "Zero", ")", ":", "return", "(", "False", ",", "S", ".", "One", ")", "elif", "(", "p", "not", "in", "pattern_match", ".", "keys", "(", ")", ")", ":", "return", "(", "False", ",", "S", ".", "One", ")", "elif", "(", "isinstance", "(", "pattern_match", "[", "q", "]", ",", "Rational", ")", "and", "pattern_match", "[", "p", "]", ".", "has", "(", "symbol", ")", ")", ":", "if", "(", "not", "(", "pattern_match", "[", "q", "]", ".", "q", "==", "S", ".", "One", ")", ")", ":", "return", "(", "True", ",", "pattern_match", "[", "q", "]", ".", "q", ")", "if", "(", "(", "not", "isinstance", "(", "pattern_match", "[", "a", "]", ",", "Pow", ")", ")", "or", "isinstance", "(", "pattern_match", "[", "a", "]", ",", "Mul", ")", ")", ":", "return", "(", "False", ",", "S", ".", "One", ")", "else", ":", "return", "_has_rational_power", "(", "pattern_match", "[", "a", "]", ",", "symbol", ")" ]
returns where bool is true if the term has a non-integer rational power and den is the denominator of the expressions exponent .
train
false
47,922
def trailing_blank_lines(physical_line, lines, line_number): if ((not physical_line.rstrip()) and (line_number == len(lines))): return (0, 'W391 blank line at end of file')
[ "def", "trailing_blank_lines", "(", "physical_line", ",", "lines", ",", "line_number", ")", ":", "if", "(", "(", "not", "physical_line", ".", "rstrip", "(", ")", ")", "and", "(", "line_number", "==", "len", "(", "lines", ")", ")", ")", ":", "return", "(", "0", ",", "'W391 blank line at end of file'", ")" ]
trailing blank lines are superfluous .
train
false
47,923
def sorensen_coefficient(X, Y): if (X is Y): X = Y = np.asanyarray(X) else: X = np.asanyarray(X) Y = np.asanyarray(Y) XY = [] i = 0 for arrayX in X: XY.append([]) for arrayY in Y: XY[i].append(((2 * np.intersect1d(arrayX, arrayY).size) / float((len(arrayX) + len(arrayY))))) XY[i] = np.array(XY[i]) i += 1 XY = np.array(XY) return XY
[ "def", "sorensen_coefficient", "(", "X", ",", "Y", ")", ":", "if", "(", "X", "is", "Y", ")", ":", "X", "=", "Y", "=", "np", ".", "asanyarray", "(", "X", ")", "else", ":", "X", "=", "np", ".", "asanyarray", "(", "X", ")", "Y", "=", "np", ".", "asanyarray", "(", "Y", ")", "XY", "=", "[", "]", "i", "=", "0", "for", "arrayX", "in", "X", ":", "XY", ".", "append", "(", "[", "]", ")", "for", "arrayY", "in", "Y", ":", "XY", "[", "i", "]", ".", "append", "(", "(", "(", "2", "*", "np", ".", "intersect1d", "(", "arrayX", ",", "arrayY", ")", ".", "size", ")", "/", "float", "(", "(", "len", "(", "arrayX", ")", "+", "len", "(", "arrayY", ")", ")", ")", ")", ")", "XY", "[", "i", "]", "=", "np", ".", "array", "(", "XY", "[", "i", "]", ")", "i", "+=", "1", "XY", "=", "np", ".", "array", "(", "XY", ")", "return", "XY" ]
considering the rows of x as vectors .
train
false
47,924
def get_effective_form_data(form): old = [(key, getattr(form, key)) for key in ('_errors', '_changed_data')] form.full_clean() data = merged_initial_and_data(form) for (key, value) in old: setattr(form, key, value) return data
[ "def", "get_effective_form_data", "(", "form", ")", ":", "old", "=", "[", "(", "key", ",", "getattr", "(", "form", ",", "key", ")", ")", "for", "key", "in", "(", "'_errors'", ",", "'_changed_data'", ")", "]", "form", ".", "full_clean", "(", ")", "data", "=", "merged_initial_and_data", "(", "form", ")", "for", "(", "key", ",", "value", ")", "in", "old", ":", "setattr", "(", "form", ",", "key", ",", "value", ")", "return", "data" ]
return effective data for the form .
train
false
47,925
def from_response(response, body): cls = _code_map.get(response.status_code, ClientException) if response.headers: request_id = response.headers.get('x-compute-request-id') else: request_id = None if body: message = 'n/a' details = 'n/a' if hasattr(body, 'keys'): error = body[body.keys()[0]] message = error.get('message', None) details = error.get('details', None) return cls(code=response.status_code, message=message, details=details, request_id=request_id) else: return cls(code=response.status_code, request_id=request_id)
[ "def", "from_response", "(", "response", ",", "body", ")", ":", "cls", "=", "_code_map", ".", "get", "(", "response", ".", "status_code", ",", "ClientException", ")", "if", "response", ".", "headers", ":", "request_id", "=", "response", ".", "headers", ".", "get", "(", "'x-compute-request-id'", ")", "else", ":", "request_id", "=", "None", "if", "body", ":", "message", "=", "'n/a'", "details", "=", "'n/a'", "if", "hasattr", "(", "body", ",", "'keys'", ")", ":", "error", "=", "body", "[", "body", ".", "keys", "(", ")", "[", "0", "]", "]", "message", "=", "error", ".", "get", "(", "'message'", ",", "None", ")", "details", "=", "error", ".", "get", "(", "'details'", ",", "None", ")", "return", "cls", "(", "code", "=", "response", ".", "status_code", ",", "message", "=", "message", ",", "details", "=", "details", ",", "request_id", "=", "request_id", ")", "else", ":", "return", "cls", "(", "code", "=", "response", ".", "status_code", ",", "request_id", "=", "request_id", ")" ]
return an instance of an clientexception or subclass based on an requests response .
train
false
47,927
def setprofile(func): global _profile_hook _profile_hook = func
[ "def", "setprofile", "(", "func", ")", ":", "global", "_profile_hook", "_profile_hook", "=", "func" ]
set a profile function for all threads started from the threading module .
train
false
47,929
@require_authorized_access_to_student_data def student_view_context(request): user = get_user_from_request(request=request) if (not user): raise Http404('User not found.') context = {'facility_id': user.facility.id, 'student': user} return context
[ "@", "require_authorized_access_to_student_data", "def", "student_view_context", "(", "request", ")", ":", "user", "=", "get_user_from_request", "(", "request", "=", "request", ")", "if", "(", "not", "user", ")", ":", "raise", "Http404", "(", "'User not found.'", ")", "context", "=", "{", "'facility_id'", ":", "user", ".", "facility", ".", "id", ",", "'student'", ":", "user", "}", "return", "context" ]
context done separately .
train
false
47,930
def polygon_load(filename): ret = [] f = open(filename) for line in f: if line.startswith('#'): continue line = line.strip() if (not line): continue a = line.split() if (len(a) != 2): raise RuntimeError(('invalid polygon line: %s' % line)) ret.append((float(a[0]), float(a[1]))) f.close() return ret
[ "def", "polygon_load", "(", "filename", ")", ":", "ret", "=", "[", "]", "f", "=", "open", "(", "filename", ")", "for", "line", "in", "f", ":", "if", "line", ".", "startswith", "(", "'#'", ")", ":", "continue", "line", "=", "line", ".", "strip", "(", ")", "if", "(", "not", "line", ")", ":", "continue", "a", "=", "line", ".", "split", "(", ")", "if", "(", "len", "(", "a", ")", "!=", "2", ")", ":", "raise", "RuntimeError", "(", "(", "'invalid polygon line: %s'", "%", "line", ")", ")", "ret", ".", "append", "(", "(", "float", "(", "a", "[", "0", "]", ")", ",", "float", "(", "a", "[", "1", "]", ")", ")", ")", "f", ".", "close", "(", ")", "return", "ret" ]
load a polygon from a file .
train
true
47,932
def _cleanName(n): if (not n): return u'' n = n.replace('Filmography by type for', '') return n
[ "def", "_cleanName", "(", "n", ")", ":", "if", "(", "not", "n", ")", ":", "return", "u''", "n", "=", "n", ".", "replace", "(", "'Filmography by type for'", ",", "''", ")", "return", "n" ]
clean the name in a title tag .
train
false
47,933
def get_and_group_by_field(cr, uid, obj, ids, field, context=None): res = {} for record in obj.read(cr, uid, ids, [field], context=context): key = record[field] res.setdefault((key[0] if isinstance(key, tuple) else key), []).append(record['id']) return res
[ "def", "get_and_group_by_field", "(", "cr", ",", "uid", ",", "obj", ",", "ids", ",", "field", ",", "context", "=", "None", ")", ":", "res", "=", "{", "}", "for", "record", "in", "obj", ".", "read", "(", "cr", ",", "uid", ",", "ids", ",", "[", "field", "]", ",", "context", "=", "context", ")", ":", "key", "=", "record", "[", "field", "]", "res", ".", "setdefault", "(", "(", "key", "[", "0", "]", "if", "isinstance", "(", "key", ",", "tuple", ")", "else", "key", ")", ",", "[", "]", ")", ".", "append", "(", "record", "[", "'id'", "]", ")", "return", "res" ]
read the values of field´´ for the given ids´´ and group ids by value .
train
false
47,934
def document_tabs(r): tab_opts = [{'tablename': 'assess_rat', 'resource': 'rat', 'one_title': '1 Assessment', 'num_title': ' Assessments'}, {'tablename': 'irs_ireport', 'resource': 'ireport', 'one_title': '1 Incident Report', 'num_title': ' Incident Reports'}, {'tablename': 'cr_shelter', 'resource': 'shelter', 'one_title': '1 Shelter', 'num_title': ' Shelters'}, {'tablename': 'req_req', 'resource': 'req', 'one_title': '1 Request', 'num_title': ' Requests'}] tabs = [(T('Details'), None)] crud_string = s3base.S3CRUD.crud_string for tab_opt in tab_opts: tablename = tab_opt['tablename'] if ((tablename in db) and (document_id in db[tablename])): table = db[tablename] query = ((table.deleted == False) & (table.document_id == r.id)) tab_count = db(query).count() if (tab_count == 0): label = crud_string(tablename, 'label_create') elif (tab_count == 1): label = tab_opt['one_title'] else: label = T((str(tab_count) + tab_opt['num_title'])) tabs.append((label, tab_opt['resource'])) return tabs
[ "def", "document_tabs", "(", "r", ")", ":", "tab_opts", "=", "[", "{", "'tablename'", ":", "'assess_rat'", ",", "'resource'", ":", "'rat'", ",", "'one_title'", ":", "'1 Assessment'", ",", "'num_title'", ":", "' Assessments'", "}", ",", "{", "'tablename'", ":", "'irs_ireport'", ",", "'resource'", ":", "'ireport'", ",", "'one_title'", ":", "'1 Incident Report'", ",", "'num_title'", ":", "' Incident Reports'", "}", ",", "{", "'tablename'", ":", "'cr_shelter'", ",", "'resource'", ":", "'shelter'", ",", "'one_title'", ":", "'1 Shelter'", ",", "'num_title'", ":", "' Shelters'", "}", ",", "{", "'tablename'", ":", "'req_req'", ",", "'resource'", ":", "'req'", ",", "'one_title'", ":", "'1 Request'", ",", "'num_title'", ":", "' Requests'", "}", "]", "tabs", "=", "[", "(", "T", "(", "'Details'", ")", ",", "None", ")", "]", "crud_string", "=", "s3base", ".", "S3CRUD", ".", "crud_string", "for", "tab_opt", "in", "tab_opts", ":", "tablename", "=", "tab_opt", "[", "'tablename'", "]", "if", "(", "(", "tablename", "in", "db", ")", "and", "(", "document_id", "in", "db", "[", "tablename", "]", ")", ")", ":", "table", "=", "db", "[", "tablename", "]", "query", "=", "(", "(", "table", ".", "deleted", "==", "False", ")", "&", "(", "table", ".", "document_id", "==", "r", ".", "id", ")", ")", "tab_count", "=", "db", "(", "query", ")", ".", "count", "(", ")", "if", "(", "tab_count", "==", "0", ")", ":", "label", "=", "crud_string", "(", "tablename", ",", "'label_create'", ")", "elif", "(", "tab_count", "==", "1", ")", ":", "label", "=", "tab_opt", "[", "'one_title'", "]", "else", ":", "label", "=", "T", "(", "(", "str", "(", "tab_count", ")", "+", "tab_opt", "[", "'num_title'", "]", ")", ")", "tabs", ".", "append", "(", "(", "label", ",", "tab_opt", "[", "'resource'", "]", ")", ")", "return", "tabs" ]
display the number of components in the tabs - currently unused as we dont have these tabs off documents .
train
false
47,935
def _is_running_from_main_thread(): return tornado.ioloop.IOLoop.current(instance=False)
[ "def", "_is_running_from_main_thread", "(", ")", ":", "return", "tornado", ".", "ioloop", ".", "IOLoop", ".", "current", "(", "instance", "=", "False", ")" ]
return true if were the same thread as the one that created the tornado ioloop .
train
false
47,936
def encode_params_utf8(params): encoded = [] for (k, v) in params: encoded.append(((k.encode('utf-8') if isinstance(k, unicode) else k), (v.encode('utf-8') if isinstance(v, unicode) else v))) return encoded
[ "def", "encode_params_utf8", "(", "params", ")", ":", "encoded", "=", "[", "]", "for", "(", "k", ",", "v", ")", "in", "params", ":", "encoded", ".", "append", "(", "(", "(", "k", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "unicode", ")", "else", "k", ")", ",", "(", "v", ".", "encode", "(", "'utf-8'", ")", "if", "isinstance", "(", "v", ",", "unicode", ")", "else", "v", ")", ")", ")", "return", "encoded" ]
ensures that all parameters in a list of 2-element tuples are encoded to bytestrings using utf-8 .
train
true
47,937
def extract_filename_from_headers(headers): cont_disp_regex = 'attachment; ?filename="?([^"]+)' res = None if ('content-disposition' in headers): cont_disp = headers['content-disposition'] match = re.match(cont_disp_regex, cont_disp) if match: res = match.group(1) res = os.path.basename(res) return res
[ "def", "extract_filename_from_headers", "(", "headers", ")", ":", "cont_disp_regex", "=", "'attachment; ?filename=\"?([^\"]+)'", "res", "=", "None", "if", "(", "'content-disposition'", "in", "headers", ")", ":", "cont_disp", "=", "headers", "[", "'content-disposition'", "]", "match", "=", "re", ".", "match", "(", "cont_disp_regex", ",", "cont_disp", ")", "if", "match", ":", "res", "=", "match", ".", "group", "(", "1", ")", "res", "=", "os", ".", "path", ".", "basename", "(", "res", ")", "return", "res" ]
extracts a filename from the given dict of http headers .
train
false
47,938
def time_calls(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): _timer = timer(('%s_calls' % get_qualname(fn))) with _timer.time(fn=get_qualname(fn)): return fn(*args, **kwargs) return wrapper
[ "def", "time_calls", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "_timer", "=", "timer", "(", "(", "'%s_calls'", "%", "get_qualname", "(", "fn", ")", ")", ")", "with", "_timer", ".", "time", "(", "fn", "=", "get_qualname", "(", "fn", ")", ")", ":", "return", "fn", "(", "*", "args", ",", "**", "kwargs", ")", "return", "wrapper" ]
decorator to time the execution of the function .
train
false
47,939
def test_goto_assignments_keyword(): Script('in').goto_assignments()
[ "def", "test_goto_assignments_keyword", "(", ")", ":", "Script", "(", "'in'", ")", ".", "goto_assignments", "(", ")" ]
bug: goto assignments on in used to raise attributeerror:: unicode object has no attribute generate_call_path .
train
false
47,940
def combine(games, plays=False): if plays: return combine_play_stats(games) else: return combine_game_stats(games)
[ "def", "combine", "(", "games", ",", "plays", "=", "False", ")", ":", "if", "plays", ":", "return", "combine_play_stats", "(", "games", ")", "else", ":", "return", "combine_game_stats", "(", "games", ")" ]
combine multiple tuples into a combined tuple the current state is passed in via prev .
train
false
47,941
def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]): env = inliner.document.settings.env r = env.get_domain('py').role('obj')('obj', rawtext, etext, lineno, inliner, options, content) pnode = r[0][0] prefixes = get_import_prefixes_from_env(env) try: (name, obj, parent) = import_by_name(pnode['reftarget'], prefixes) except ImportError: content = pnode[0] r[0][0] = nodes.emphasis(rawtext, content[0].astext(), classes=content['classes']) return r
[ "def", "autolink_role", "(", "typ", ",", "rawtext", ",", "etext", ",", "lineno", ",", "inliner", ",", "options", "=", "{", "}", ",", "content", "=", "[", "]", ")", ":", "env", "=", "inliner", ".", "document", ".", "settings", ".", "env", "r", "=", "env", ".", "get_domain", "(", "'py'", ")", ".", "role", "(", "'obj'", ")", "(", "'obj'", ",", "rawtext", ",", "etext", ",", "lineno", ",", "inliner", ",", "options", ",", "content", ")", "pnode", "=", "r", "[", "0", "]", "[", "0", "]", "prefixes", "=", "get_import_prefixes_from_env", "(", "env", ")", "try", ":", "(", "name", ",", "obj", ",", "parent", ")", "=", "import_by_name", "(", "pnode", "[", "'reftarget'", "]", ",", "prefixes", ")", "except", "ImportError", ":", "content", "=", "pnode", "[", "0", "]", "r", "[", "0", "]", "[", "0", "]", "=", "nodes", ".", "emphasis", "(", "rawtext", ",", "content", "[", "0", "]", ".", "astext", "(", ")", ",", "classes", "=", "content", "[", "'classes'", "]", ")", "return", "r" ]
smart linking role .
train
true
47,945
def run_program(program, args=None, **subprocess_kwargs): if (('shell' in subprocess_kwargs) and subprocess_kwargs['shell']): raise ProgramError('This function is only for non-shell programs, use run_shell_command() instead.') fullcmd = find_program(program) if (not fullcmd): raise ProgramError(('Program %s was not found' % program)) fullcmd = ([fullcmd] + (args or [])) for stream in ['stdin', 'stdout', 'stderr']: subprocess_kwargs.setdefault(stream, subprocess.PIPE) subprocess_kwargs = alter_subprocess_kwargs_by_platform(**subprocess_kwargs) return subprocess.Popen(fullcmd, **subprocess_kwargs)
[ "def", "run_program", "(", "program", ",", "args", "=", "None", ",", "**", "subprocess_kwargs", ")", ":", "if", "(", "(", "'shell'", "in", "subprocess_kwargs", ")", "and", "subprocess_kwargs", "[", "'shell'", "]", ")", ":", "raise", "ProgramError", "(", "'This function is only for non-shell programs, use run_shell_command() instead.'", ")", "fullcmd", "=", "find_program", "(", "program", ")", "if", "(", "not", "fullcmd", ")", ":", "raise", "ProgramError", "(", "(", "'Program %s was not found'", "%", "program", ")", ")", "fullcmd", "=", "(", "[", "fullcmd", "]", "+", "(", "args", "or", "[", "]", ")", ")", "for", "stream", "in", "[", "'stdin'", ",", "'stdout'", ",", "'stderr'", "]", ":", "subprocess_kwargs", ".", "setdefault", "(", "stream", ",", "subprocess", ".", "PIPE", ")", "subprocess_kwargs", "=", "alter_subprocess_kwargs_by_platform", "(", "**", "subprocess_kwargs", ")", "return", "subprocess", ".", "Popen", "(", "fullcmd", ",", "**", "subprocess_kwargs", ")" ]
run program in a separate process .
train
true
47,946
def default_release_date(): today = date.today() TUESDAY = 2 days_until_tuesday = ((TUESDAY - today.isoweekday()) % 7) return (today + timedelta(days=days_until_tuesday))
[ "def", "default_release_date", "(", ")", ":", "today", "=", "date", ".", "today", "(", ")", "TUESDAY", "=", "2", "days_until_tuesday", "=", "(", "(", "TUESDAY", "-", "today", ".", "isoweekday", "(", ")", ")", "%", "7", ")", "return", "(", "today", "+", "timedelta", "(", "days", "=", "days_until_tuesday", ")", ")" ]
returns a date object corresponding to the expected date of the next release: normally .
train
false
47,948
def get_default_language(): return (Settings.get('default_language') or settings.LANGUAGE_CODE or 'en')
[ "def", "get_default_language", "(", ")", ":", "return", "(", "Settings", ".", "get", "(", "'default_language'", ")", "or", "settings", ".", "LANGUAGE_CODE", "or", "'en'", ")" ]
returns: the default language .
train
false
47,949
def __execute_cmd(command, host=None, admin_username=None, admin_password=None, module=None): if module: if module.startswith('ALL_'): modswitch = ('-a ' + module[(module.index('_') + 1):len(module)].lower()) else: modswitch = '-m {0}'.format(module) else: modswitch = '' if (not host): cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command, modswitch)) else: cmd = __salt__['cmd.run_all']('racadm -r {0} -u {1} -p {2} {3} {4}'.format(host, admin_username, admin_password, command, modswitch), output_loglevel='quiet') if (cmd['retcode'] != 0): log.warning("racadm return an exit code '{0}'.".format(cmd['retcode'])) return False return True
[ "def", "__execute_cmd", "(", "command", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ",", "module", "=", "None", ")", ":", "if", "module", ":", "if", "module", ".", "startswith", "(", "'ALL_'", ")", ":", "modswitch", "=", "(", "'-a '", "+", "module", "[", "(", "module", ".", "index", "(", "'_'", ")", "+", "1", ")", ":", "len", "(", "module", ")", "]", ".", "lower", "(", ")", ")", "else", ":", "modswitch", "=", "'-m {0}'", ".", "format", "(", "module", ")", "else", ":", "modswitch", "=", "''", "if", "(", "not", "host", ")", ":", "cmd", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'racadm {0} {1}'", ".", "format", "(", "command", ",", "modswitch", ")", ")", "else", ":", "cmd", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'racadm -r {0} -u {1} -p {2} {3} {4}'", ".", "format", "(", "host", ",", "admin_username", ",", "admin_password", ",", "command", ",", "modswitch", ")", ",", "output_loglevel", "=", "'quiet'", ")", "if", "(", "cmd", "[", "'retcode'", "]", "!=", "0", ")", ":", "log", ".", "warning", "(", "\"racadm return an exit code '{0}'.\"", ".", "format", "(", "cmd", "[", "'retcode'", "]", ")", ")", "return", "False", "return", "True" ]
execute rac commands .
train
true
47,950
def logit(x): x = tf.convert_to_tensor(x) dependencies = [tf.assert_positive(x), tf.assert_less(x, 1.0)] x = control_flow_ops.with_dependencies(dependencies, x) return (tf.log(x) - tf.log((1.0 - x)))
[ "def", "logit", "(", "x", ")", ":", "x", "=", "tf", ".", "convert_to_tensor", "(", "x", ")", "dependencies", "=", "[", "tf", ".", "assert_positive", "(", "x", ")", ",", "tf", ".", "assert_less", "(", "x", ",", "1.0", ")", "]", "x", "=", "control_flow_ops", ".", "with_dependencies", "(", "dependencies", ",", "x", ")", "return", "(", "tf", ".", "log", "(", "x", ")", "-", "tf", ".", "log", "(", "(", "1.0", "-", "x", ")", ")", ")" ]
evaluate :math:log(x / ) elementwise .
train
false
47,951
@aggregate(_(u'Avg. of')) def aggregate_avg(items, col): try: return (aggregate_sum(items, col) / aggregate_count(items, col)) except: log.warning(c.LOGMSG_WAR_DBI_AVG_ZERODIV) return 0.0
[ "@", "aggregate", "(", "_", "(", "u'Avg. of'", ")", ")", "def", "aggregate_avg", "(", "items", ",", "col", ")", ":", "try", ":", "return", "(", "aggregate_sum", "(", "items", ",", "col", ")", "/", "aggregate_count", "(", "items", ",", "col", ")", ")", "except", ":", "log", ".", "warning", "(", "c", ".", "LOGMSG_WAR_DBI_AVG_ZERODIV", ")", "return", "0.0" ]
function to use on group by charts .
train
false
47,952
def read_proj(fname): check_fname(fname, 'projection', ('-proj.fif', '-proj.fif.gz')) (ff, tree, _) = io.fiff_open(fname) with ff as fid: projs = io.proj._read_proj(fid, tree) return projs
[ "def", "read_proj", "(", "fname", ")", ":", "check_fname", "(", "fname", ",", "'projection'", ",", "(", "'-proj.fif'", ",", "'-proj.fif.gz'", ")", ")", "(", "ff", ",", "tree", ",", "_", ")", "=", "io", ".", "fiff_open", "(", "fname", ")", "with", "ff", "as", "fid", ":", "projs", "=", "io", ".", "proj", ".", "_read_proj", "(", "fid", ",", "tree", ")", "return", "projs" ]
read projections from a fif file .
train
false
47,953
@box(IndexType) def box_index(typ, val, c): index = make_index(c.context, c.builder, typ, value=val) classobj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.pyclass)) arrayobj = c.box(typ.as_array, index.data) indexobj = c.pyapi.call_function_objargs(classobj, (arrayobj,)) return indexobj
[ "@", "box", "(", "IndexType", ")", "def", "box_index", "(", "typ", ",", "val", ",", "c", ")", ":", "index", "=", "make_index", "(", "c", ".", "context", ",", "c", ".", "builder", ",", "typ", ",", "value", "=", "val", ")", "classobj", "=", "c", ".", "pyapi", ".", "unserialize", "(", "c", ".", "pyapi", ".", "serialize_object", "(", "typ", ".", "pyclass", ")", ")", "arrayobj", "=", "c", ".", "box", "(", "typ", ".", "as_array", ",", "index", ".", "data", ")", "indexobj", "=", "c", ".", "pyapi", ".", "call_function_objargs", "(", "classobj", ",", "(", "arrayobj", ",", ")", ")", "return", "indexobj" ]
convert a native index structure to a index object .
train
false
47,954
@gof.local_optimizer([usmm]) def local_usmm_csx(node): if (node.op == usmm): (alpha, x, y, z) = node.inputs x_is_sparse_variable = _is_sparse_variable(x) y_is_sparse_variable = _is_sparse_variable(y) if (x_is_sparse_variable and (not y_is_sparse_variable)): if (x.type.format == 'csc'): (x_val, x_ind, x_ptr, x_shape) = csm_properties(x) x_nsparse = x_shape[0] dtype_out = scalar.upcast(alpha.type.dtype, x.type.dtype, y.type.dtype, z.type.dtype) if (dtype_out not in ('float32', 'float64')): return False if (y.type.dtype != dtype_out): return False return [usmm_csc_dense(alpha, x_val, x_ind, x_ptr, x_nsparse, y, z)] return False
[ "@", "gof", ".", "local_optimizer", "(", "[", "usmm", "]", ")", "def", "local_usmm_csx", "(", "node", ")", ":", "if", "(", "node", ".", "op", "==", "usmm", ")", ":", "(", "alpha", ",", "x", ",", "y", ",", "z", ")", "=", "node", ".", "inputs", "x_is_sparse_variable", "=", "_is_sparse_variable", "(", "x", ")", "y_is_sparse_variable", "=", "_is_sparse_variable", "(", "y", ")", "if", "(", "x_is_sparse_variable", "and", "(", "not", "y_is_sparse_variable", ")", ")", ":", "if", "(", "x", ".", "type", ".", "format", "==", "'csc'", ")", ":", "(", "x_val", ",", "x_ind", ",", "x_ptr", ",", "x_shape", ")", "=", "csm_properties", "(", "x", ")", "x_nsparse", "=", "x_shape", "[", "0", "]", "dtype_out", "=", "scalar", ".", "upcast", "(", "alpha", ".", "type", ".", "dtype", ",", "x", ".", "type", ".", "dtype", ",", "y", ".", "type", ".", "dtype", ",", "z", ".", "type", ".", "dtype", ")", "if", "(", "dtype_out", "not", "in", "(", "'float32'", ",", "'float64'", ")", ")", ":", "return", "False", "if", "(", "y", ".", "type", ".", "dtype", "!=", "dtype_out", ")", ":", "return", "False", "return", "[", "usmm_csc_dense", "(", "alpha", ",", "x_val", ",", "x_ind", ",", "x_ptr", ",", "x_nsparse", ",", "y", ",", "z", ")", "]", "return", "False" ]
usmm -> usmm_csc_dense .
train
false
47,956
@world.absorb def wait_for_ajax_complete(): javascript = '\n var callback = arguments[arguments.length - 1];\n if(!window.jQuery) {callback(false);}\n var intervalID = setInterval(function() {\n if(jQuery.active == 0) {\n clearInterval(intervalID);\n callback(true);\n }\n }, 100);\n ' for _ in range(5): try: result = world.browser.driver.execute_async_script(dedent(javascript)) except WebDriverException as wde: if ('document unloaded while waiting for result' in wde.msg): world.wait(1) continue else: raise return result
[ "@", "world", ".", "absorb", "def", "wait_for_ajax_complete", "(", ")", ":", "javascript", "=", "'\\n var callback = arguments[arguments.length - 1];\\n if(!window.jQuery) {callback(false);}\\n var intervalID = setInterval(function() {\\n if(jQuery.active == 0) {\\n clearInterval(intervalID);\\n callback(true);\\n }\\n }, 100);\\n '", "for", "_", "in", "range", "(", "5", ")", ":", "try", ":", "result", "=", "world", ".", "browser", ".", "driver", ".", "execute_async_script", "(", "dedent", "(", "javascript", ")", ")", "except", "WebDriverException", "as", "wde", ":", "if", "(", "'document unloaded while waiting for result'", "in", "wde", ".", "msg", ")", ":", "world", ".", "wait", "(", "1", ")", "continue", "else", ":", "raise", "return", "result" ]
wait until all jquery ajax calls have completed .
train
false
47,957
def rowadd(matlist, index1, index2, k, K): result = [] for i in range(len(matlist[index1])): matlist[index1][i] = (matlist[index1][i] + (k * matlist[index2][i])) return matlist
[ "def", "rowadd", "(", "matlist", ",", "index1", ",", "index2", ",", "k", ",", "K", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "matlist", "[", "index1", "]", ")", ")", ":", "matlist", "[", "index1", "]", "[", "i", "]", "=", "(", "matlist", "[", "index1", "]", "[", "i", "]", "+", "(", "k", "*", "matlist", "[", "index2", "]", "[", "i", "]", ")", ")", "return", "matlist" ]
adds the index1 row with index2 row which in turn is multiplied by k .
train
false
47,958
def set_default_language(lang_code): Settings.set('default_language', lcode_to_ietf(lang_code))
[ "def", "set_default_language", "(", "lang_code", ")", ":", "Settings", ".", "set", "(", "'default_language'", ",", "lcode_to_ietf", "(", "lang_code", ")", ")" ]
sets the default language .
train
false
47,959
@register.simple_tag(takes_context=True) def review_request_actions(context): content = [] for top_level_action in get_top_level_actions(): try: content.append(top_level_action.render(context)) except Exception: logging.exception(u'Error rendering top-level action %s', top_level_action.action_id) return u''.join(content)
[ "@", "register", ".", "simple_tag", "(", "takes_context", "=", "True", ")", "def", "review_request_actions", "(", "context", ")", ":", "content", "=", "[", "]", "for", "top_level_action", "in", "get_top_level_actions", "(", ")", ":", "try", ":", "content", ".", "append", "(", "top_level_action", ".", "render", "(", "context", ")", ")", "except", "Exception", ":", "logging", ".", "exception", "(", "u'Error rendering top-level action %s'", ",", "top_level_action", ".", "action_id", ")", "return", "u''", ".", "join", "(", "content", ")" ]
render all registered review request actions .
train
false
47,961
def get_variables_in_scope(scope, collection=tf.GraphKeys.TRAINABLE_VARIABLES): scope_name = (re.escape(scope.name) + '/') return tuple(tf.get_collection(collection, scope_name))
[ "def", "get_variables_in_scope", "(", "scope", ",", "collection", "=", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ")", ":", "scope_name", "=", "(", "re", ".", "escape", "(", "scope", ".", "name", ")", "+", "'/'", ")", "return", "tuple", "(", "tf", ".", "get_collection", "(", "collection", ",", "scope_name", ")", ")" ]
returns a tuple tf .
train
true
47,962
def clean_socket_close(sock): _LOGGER.info('UPNP responder shutting down.') sock.close()
[ "def", "clean_socket_close", "(", "sock", ")", ":", "_LOGGER", ".", "info", "(", "'UPNP responder shutting down.'", ")", "sock", ".", "close", "(", ")" ]
close a socket connection and logs its closure .
train
false
47,963
@require_authorized_admin def add_facility_teacher(request): title = _('Add a new coach') return _facility_user(request, new_user=True, is_teacher=True, title=title)
[ "@", "require_authorized_admin", "def", "add_facility_teacher", "(", "request", ")", ":", "title", "=", "_", "(", "'Add a new coach'", ")", "return", "_facility_user", "(", "request", ",", "new_user", "=", "True", ",", "is_teacher", "=", "True", ",", "title", "=", "title", ")" ]
admins and coaches can add teachers if central .
train
false
47,964
def parse_linters(linters): result = list() for name in split_csp_str(linters): linter = LINTERS.get(name) if linter: result.append((name, linter)) else: logging.warn('Linter `%s` not found.', name) return result
[ "def", "parse_linters", "(", "linters", ")", ":", "result", "=", "list", "(", ")", "for", "name", "in", "split_csp_str", "(", "linters", ")", ":", "linter", "=", "LINTERS", ".", "get", "(", "name", ")", "if", "linter", ":", "result", ".", "append", "(", "(", "name", ",", "linter", ")", ")", "else", ":", "logging", ".", "warn", "(", "'Linter `%s` not found.'", ",", "name", ")", "return", "result" ]
initialize choosen linters .
train
true
47,965
def accumulateMethods(obj, dict, prefix='', curClass=None): if (not curClass): curClass = obj.__class__ for base in curClass.__bases__: accumulateMethods(obj, dict, prefix, base) for (name, method) in curClass.__dict__.items(): optName = name[len(prefix):] if ((type(method) is types.FunctionType) and (name[:len(prefix)] == prefix) and len(optName)): dict[optName] = getattr(obj, name)
[ "def", "accumulateMethods", "(", "obj", ",", "dict", ",", "prefix", "=", "''", ",", "curClass", "=", "None", ")", ":", "if", "(", "not", "curClass", ")", ":", "curClass", "=", "obj", ".", "__class__", "for", "base", "in", "curClass", ".", "__bases__", ":", "accumulateMethods", "(", "obj", ",", "dict", ",", "prefix", ",", "base", ")", "for", "(", "name", ",", "method", ")", "in", "curClass", ".", "__dict__", ".", "items", "(", ")", ":", "optName", "=", "name", "[", "len", "(", "prefix", ")", ":", "]", "if", "(", "(", "type", "(", "method", ")", "is", "types", ".", "FunctionType", ")", "and", "(", "name", "[", ":", "len", "(", "prefix", ")", "]", "==", "prefix", ")", "and", "len", "(", "optName", ")", ")", ":", "dict", "[", "optName", "]", "=", "getattr", "(", "obj", ",", "name", ")" ]
given an object c{obj} .
train
false
47,967
def _close_sd_ref(): global SD_REF if SD_REF: SD_REF.close() SD_REF = None
[ "def", "_close_sd_ref", "(", ")", ":", "global", "SD_REF", "if", "SD_REF", ":", "SD_REF", ".", "close", "(", ")", "SD_REF", "=", "None" ]
close the sd_ref object if it isnt null for use with atexit .
train
false
47,971
def Kumaraswamy(name, a, b): return rv(name, KumaraswamyDistribution, (a, b))
[ "def", "Kumaraswamy", "(", "name", ",", "a", ",", "b", ")", ":", "return", "rv", "(", "name", ",", "KumaraswamyDistribution", ",", "(", "a", ",", "b", ")", ")" ]
create a continuous random variable with a kumaraswamy distribution .
train
false
47,972
def parse_html_dict(dictionary, prefix=''): ret = MultiValueDict() regex = re.compile(('^%s\\.(.+)$' % re.escape(prefix))) for field in dictionary: match = regex.match(field) if (not match): continue key = match.groups()[0] value = dictionary.getlist(field) ret.setlist(key, value) return ret
[ "def", "parse_html_dict", "(", "dictionary", ",", "prefix", "=", "''", ")", ":", "ret", "=", "MultiValueDict", "(", ")", "regex", "=", "re", ".", "compile", "(", "(", "'^%s\\\\.(.+)$'", "%", "re", ".", "escape", "(", "prefix", ")", ")", ")", "for", "field", "in", "dictionary", ":", "match", "=", "regex", ".", "match", "(", "field", ")", "if", "(", "not", "match", ")", ":", "continue", "key", "=", "match", ".", "groups", "(", ")", "[", "0", "]", "value", "=", "dictionary", ".", "getlist", "(", "field", ")", "ret", ".", "setlist", "(", "key", ",", "value", ")", "return", "ret" ]
used to support dictionary values in html forms .
train
false
47,973
def Post(env, resp): input = env['wsgi.input'] length = int(env.get('CONTENT_LENGTH', 0)) if (length > 0): postdata = input.read(length) fields = cgi.parse_qs(postdata) content = fields['content'][0] content = content.strip() if content: forumdb.AddPost(content) headers = [('Location', '/'), ('Content-type', 'text/plain')] resp('302 REDIRECT', headers) return ['Redirecting']
[ "def", "Post", "(", "env", ",", "resp", ")", ":", "input", "=", "env", "[", "'wsgi.input'", "]", "length", "=", "int", "(", "env", ".", "get", "(", "'CONTENT_LENGTH'", ",", "0", ")", ")", "if", "(", "length", ">", "0", ")", ":", "postdata", "=", "input", ".", "read", "(", "length", ")", "fields", "=", "cgi", ".", "parse_qs", "(", "postdata", ")", "content", "=", "fields", "[", "'content'", "]", "[", "0", "]", "content", "=", "content", ".", "strip", "(", ")", "if", "content", ":", "forumdb", ".", "AddPost", "(", "content", ")", "headers", "=", "[", "(", "'Location'", ",", "'/'", ")", ",", "(", "'Content-type'", ",", "'text/plain'", ")", "]", "resp", "(", "'302 REDIRECT'", ",", "headers", ")", "return", "[", "'Redirecting'", "]" ]
post handles a submission of the forums form .
train
false
47,974
def unload_all(): unload(*reversed(_PLUGINS))
[ "def", "unload_all", "(", ")", ":", "unload", "(", "*", "reversed", "(", "_PLUGINS", ")", ")" ]
unload all loaded plugins in the reverse order that they were loaded .
train
false
47,976
@pytest.fixture def fake_save_manager(): fake_save_manager = unittest.mock.Mock(spec=savemanager.SaveManager) objreg.register('save-manager', fake_save_manager) (yield fake_save_manager) objreg.delete('save-manager')
[ "@", "pytest", ".", "fixture", "def", "fake_save_manager", "(", ")", ":", "fake_save_manager", "=", "unittest", ".", "mock", ".", "Mock", "(", "spec", "=", "savemanager", ".", "SaveManager", ")", "objreg", ".", "register", "(", "'save-manager'", ",", "fake_save_manager", ")", "(", "yield", "fake_save_manager", ")", "objreg", ".", "delete", "(", "'save-manager'", ")" ]
create a mock of save-manager and register it into objreg .
train
false
47,977
def get_liveaction_by_id(liveaction_id): liveaction = None try: liveaction = LiveAction.get_by_id(liveaction_id) except (ValidationError, ValueError) as e: LOG.error('Database lookup for LiveAction with id="%s" resulted in exception: %s', liveaction_id, e) raise StackStormDBObjectNotFoundError(('Unable to find LiveAction with id="%s"' % liveaction_id)) return liveaction
[ "def", "get_liveaction_by_id", "(", "liveaction_id", ")", ":", "liveaction", "=", "None", "try", ":", "liveaction", "=", "LiveAction", ".", "get_by_id", "(", "liveaction_id", ")", "except", "(", "ValidationError", ",", "ValueError", ")", "as", "e", ":", "LOG", ".", "error", "(", "'Database lookup for LiveAction with id=\"%s\" resulted in exception: %s'", ",", "liveaction_id", ",", "e", ")", "raise", "StackStormDBObjectNotFoundError", "(", "(", "'Unable to find LiveAction with id=\"%s\"'", "%", "liveaction_id", ")", ")", "return", "liveaction" ]
get liveaction by id .
train
false
47,979
def fixed_shortcut(keystr, parent, action): sc = QShortcut(QKeySequence(keystr), parent, action) sc.setContext(Qt.WidgetWithChildrenShortcut) return sc
[ "def", "fixed_shortcut", "(", "keystr", ",", "parent", ",", "action", ")", ":", "sc", "=", "QShortcut", "(", "QKeySequence", "(", "keystr", ")", ",", "parent", ",", "action", ")", "sc", ".", "setContext", "(", "Qt", ".", "WidgetWithChildrenShortcut", ")", "return", "sc" ]
deprecated: this function will be removed in spyder 4 .
train
true
47,981
def bzr_wc_sudo(): test = 'bzr_wc_sudo' wt = ('%s-test-%s' % (DIR, test)) puts(magenta(('Executing test: %s' % test))) from fabric.api import sudo from fabtools.files import group, is_dir, owner from fabtools import require assert (not is_dir(wt)) require.bazaar.working_copy(REMOTE_URL, wt, use_sudo=True) assert_wc_exists(wt) assert (owner(wt) == 'root') assert (group(wt) == 'root')
[ "def", "bzr_wc_sudo", "(", ")", ":", "test", "=", "'bzr_wc_sudo'", "wt", "=", "(", "'%s-test-%s'", "%", "(", "DIR", ",", "test", ")", ")", "puts", "(", "magenta", "(", "(", "'Executing test: %s'", "%", "test", ")", ")", ")", "from", "fabric", ".", "api", "import", "sudo", "from", "fabtools", ".", "files", "import", "group", ",", "is_dir", ",", "owner", "from", "fabtools", "import", "require", "assert", "(", "not", "is_dir", "(", "wt", ")", ")", "require", ".", "bazaar", ".", "working_copy", "(", "REMOTE_URL", ",", "wt", ",", "use_sudo", "=", "True", ")", "assert_wc_exists", "(", "wt", ")", "assert", "(", "owner", "(", "wt", ")", "==", "'root'", ")", "assert", "(", "group", "(", "wt", ")", "==", "'root'", ")" ]
test working copy with sudo .
train
false
47,982
def _load_all_data(): from .megsim import data_path for url in urls: data_path((url_root + url))
[ "def", "_load_all_data", "(", ")", ":", "from", ".", "megsim", "import", "data_path", "for", "url", "in", "urls", ":", "data_path", "(", "(", "url_root", "+", "url", ")", ")" ]
helper for downloading all megsim datasets .
train
false
47,983
def p_labeled_statement_1(t): pass
[ "def", "p_labeled_statement_1", "(", "t", ")", ":", "pass" ]
labeled_statement : id colon statement .
train
false
47,984
def rgb_to_256(rgb): rgb = rgb.lstrip('#') if (len(rgb) == 0): return ('0', '000000') incs = (0, 95, 135, 175, 215, 255) parts = rgb_to_ints(rgb) res = [] for part in parts: i = 0 while (i < (len(incs) - 1)): (s, b) = (incs[i], incs[(i + 1)]) if (s <= part <= b): s1 = abs((s - part)) b1 = abs((b - part)) if (s1 < b1): closest = s else: closest = b res.append(closest) break i += 1 res = ''.join([('%02.x' % i) for i in res]) equiv = RGB_256[res] return (equiv, res)
[ "def", "rgb_to_256", "(", "rgb", ")", ":", "rgb", "=", "rgb", ".", "lstrip", "(", "'#'", ")", "if", "(", "len", "(", "rgb", ")", "==", "0", ")", ":", "return", "(", "'0'", ",", "'000000'", ")", "incs", "=", "(", "0", ",", "95", ",", "135", ",", "175", ",", "215", ",", "255", ")", "parts", "=", "rgb_to_ints", "(", "rgb", ")", "res", "=", "[", "]", "for", "part", "in", "parts", ":", "i", "=", "0", "while", "(", "i", "<", "(", "len", "(", "incs", ")", "-", "1", ")", ")", ":", "(", "s", ",", "b", ")", "=", "(", "incs", "[", "i", "]", ",", "incs", "[", "(", "i", "+", "1", ")", "]", ")", "if", "(", "s", "<=", "part", "<=", "b", ")", ":", "s1", "=", "abs", "(", "(", "s", "-", "part", ")", ")", "b1", "=", "abs", "(", "(", "b", "-", "part", ")", ")", "if", "(", "s1", "<", "b1", ")", ":", "closest", "=", "s", "else", ":", "closest", "=", "b", "res", ".", "append", "(", "closest", ")", "break", "i", "+=", "1", "res", "=", "''", ".", "join", "(", "[", "(", "'%02.x'", "%", "i", ")", "for", "i", "in", "res", "]", ")", "equiv", "=", "RGB_256", "[", "res", "]", "return", "(", "equiv", ",", "res", ")" ]
find the closest ansi 256 approximation to the given rgb value .
train
false
47,985
def _prettyformat_lines(lines): for line in lines: data = json.loads(line) (yield (pretty_format(data) + '\n'))
[ "def", "_prettyformat_lines", "(", "lines", ")", ":", "for", "line", "in", "lines", ":", "data", "=", "json", ".", "loads", "(", "line", ")", "(", "yield", "(", "pretty_format", "(", "data", ")", "+", "'\\n'", ")", ")" ]
pretty format lines of eliot logs .
train
false
47,987
def contains_feat(title): return bool(re.search(plugins.feat_tokens(), title, flags=re.IGNORECASE))
[ "def", "contains_feat", "(", "title", ")", ":", "return", "bool", "(", "re", ".", "search", "(", "plugins", ".", "feat_tokens", "(", ")", ",", "title", ",", "flags", "=", "re", ".", "IGNORECASE", ")", ")" ]
determine whether the title contains a "featured" marker .
train
false
47,988
def GoOne(Handle): if (os.name == 'nt'): staticLib = ctypes.windll.LoadLibrary('labjackud') ec = staticLib.GoOne(Handle) if (ec != 0): raise LabJackException(ec) else: raise LabJackException(0, 'Function only supported for Windows')
[ "def", "GoOne", "(", "Handle", ")", ":", "if", "(", "os", ".", "name", "==", "'nt'", ")", ":", "staticLib", "=", "ctypes", ".", "windll", ".", "LoadLibrary", "(", "'labjackud'", ")", "ec", "=", "staticLib", ".", "GoOne", "(", "Handle", ")", "if", "(", "ec", "!=", "0", ")", ":", "raise", "LabJackException", "(", "ec", ")", "else", ":", "raise", "LabJackException", "(", "0", ",", "'Function only supported for Windows'", ")" ]
performs the next request on the labjackud request stack for windows only sample usage: .
train
false
47,989
@command(usage='export task download urls') @command_line_parser() @with_parser(parse_login) @command_line_option('all') @command_line_value('category') def export_download_urls(args): assert (len(args) or args.all or args.category), 'Not enough arguments' client = create_client(args) import lixian_query tasks = lixian_query.search_tasks(client, args) urls = [] for task in tasks: if (task['type'] == 'bt'): (subs, skipped, single_file) = lixian_query.expand_bt_sub_tasks(task) if (not subs): continue if single_file: urls.append((subs[0]['xunlei_url'], subs[0]['name'], None)) else: for f in subs: urls.append((f['xunlei_url'], f['name'], task['name'])) else: urls.append((task['xunlei_url'], task['name'], None)) for (url, _, _) in urls: print url
[ "@", "command", "(", "usage", "=", "'export task download urls'", ")", "@", "command_line_parser", "(", ")", "@", "with_parser", "(", "parse_login", ")", "@", "command_line_option", "(", "'all'", ")", "@", "command_line_value", "(", "'category'", ")", "def", "export_download_urls", "(", "args", ")", ":", "assert", "(", "len", "(", "args", ")", "or", "args", ".", "all", "or", "args", ".", "category", ")", ",", "'Not enough arguments'", "client", "=", "create_client", "(", "args", ")", "import", "lixian_query", "tasks", "=", "lixian_query", ".", "search_tasks", "(", "client", ",", "args", ")", "urls", "=", "[", "]", "for", "task", "in", "tasks", ":", "if", "(", "task", "[", "'type'", "]", "==", "'bt'", ")", ":", "(", "subs", ",", "skipped", ",", "single_file", ")", "=", "lixian_query", ".", "expand_bt_sub_tasks", "(", "task", ")", "if", "(", "not", "subs", ")", ":", "continue", "if", "single_file", ":", "urls", ".", "append", "(", "(", "subs", "[", "0", "]", "[", "'xunlei_url'", "]", ",", "subs", "[", "0", "]", "[", "'name'", "]", ",", "None", ")", ")", "else", ":", "for", "f", "in", "subs", ":", "urls", ".", "append", "(", "(", "f", "[", "'xunlei_url'", "]", ",", "f", "[", "'name'", "]", ",", "task", "[", "'name'", "]", ")", ")", "else", ":", "urls", ".", "append", "(", "(", "task", "[", "'xunlei_url'", "]", ",", "task", "[", "'name'", "]", ",", "None", ")", ")", "for", "(", "url", ",", "_", ",", "_", ")", "in", "urls", ":", "print", "url" ]
usage: lx export-download-urls [id|name] .
train
false
47,990
def _ordered_dict_to_dict(config): return loads(dumps(config))
[ "def", "_ordered_dict_to_dict", "(", "config", ")", ":", "return", "loads", "(", "dumps", "(", "config", ")", ")" ]
forced the datatype to dict .
train
false
47,991
def lifted_f(a, indices): object() for idx in indices: sleep((10 * sleep_factor)) a[idx] = PyThread_get_thread_ident()
[ "def", "lifted_f", "(", "a", ",", "indices", ")", ":", "object", "(", ")", "for", "idx", "in", "indices", ":", "sleep", "(", "(", "10", "*", "sleep_factor", ")", ")", "a", "[", "idx", "]", "=", "PyThread_get_thread_ident", "(", ")" ]
same as f() .
train
false
47,995
def more_like(pk, source, top=5): index = get_source_index() with index.searcher() as searcher: docnum = searcher.document_number(pk=pk) if (docnum is None): return set() results = searcher.more_like(docnum, 'source', source, top) return set([result['pk'] for result in results])
[ "def", "more_like", "(", "pk", ",", "source", ",", "top", "=", "5", ")", ":", "index", "=", "get_source_index", "(", ")", "with", "index", ".", "searcher", "(", ")", "as", "searcher", ":", "docnum", "=", "searcher", ".", "document_number", "(", "pk", "=", "pk", ")", "if", "(", "docnum", "is", "None", ")", ":", "return", "set", "(", ")", "results", "=", "searcher", ".", "more_like", "(", "docnum", ",", "'source'", ",", "source", ",", "top", ")", "return", "set", "(", "[", "result", "[", "'pk'", "]", "for", "result", "in", "results", "]", ")" ]
finds similar units .
train
false
47,996
def test_recursive_fallback(): world.step_list = list() runner = Runner(join(abspath(dirname(__file__)), 'simple_features', '3rd_feature_dir'), verbosity=0) runner.run() assert_equals(world.step_list, ['Given I define step at look/here/step_one.py', 'And at look/and_here/step_two.py', 'Also at look/here/for_steps/step_three.py', 'And finally at look/and_here/and_any_python_file/step_four.py']) del world.step_list
[ "def", "test_recursive_fallback", "(", ")", ":", "world", ".", "step_list", "=", "list", "(", ")", "runner", "=", "Runner", "(", "join", "(", "abspath", "(", "dirname", "(", "__file__", ")", ")", ",", "'simple_features'", ",", "'3rd_feature_dir'", ")", ",", "verbosity", "=", "0", ")", "runner", ".", "run", "(", ")", "assert_equals", "(", "world", ".", "step_list", ",", "[", "'Given I define step at look/here/step_one.py'", ",", "'And at look/and_here/step_two.py'", ",", "'Also at look/here/for_steps/step_three.py'", ",", "'And finally at look/and_here/and_any_python_file/step_four.py'", "]", ")", "del", "world", ".", "step_list" ]
if dont find a step_definitions folder .
train
false
47,997
def _group_id_from_name(path, project=None): return _name_from_project_path(path, project, _GROUP_TEMPLATE)
[ "def", "_group_id_from_name", "(", "path", ",", "project", "=", "None", ")", ":", "return", "_name_from_project_path", "(", "path", ",", "project", ",", "_GROUP_TEMPLATE", ")" ]
validate a group uri path and get the group id .
train
false
47,998
def sum_simplify(s): from sympy.concrete.summations import Sum from sympy.core.function import expand terms = Add.make_args(expand(s)) s_t = [] o_t = [] for term in terms: if isinstance(term, Mul): other = 1 sum_terms = [] if (not term.has(Sum)): o_t.append(term) continue mul_terms = Mul.make_args(term) for mul_term in mul_terms: if isinstance(mul_term, Sum): r = mul_term._eval_simplify() sum_terms.extend(Add.make_args(r)) else: other = (other * mul_term) if len(sum_terms): s_t.append((Mul(*sum_terms) * other)) else: o_t.append(other) elif isinstance(term, Sum): r = term._eval_simplify() s_t.extend(Add.make_args(r)) else: o_t.append(term) result = Add(sum_combine(s_t), *o_t) return result
[ "def", "sum_simplify", "(", "s", ")", ":", "from", "sympy", ".", "concrete", ".", "summations", "import", "Sum", "from", "sympy", ".", "core", ".", "function", "import", "expand", "terms", "=", "Add", ".", "make_args", "(", "expand", "(", "s", ")", ")", "s_t", "=", "[", "]", "o_t", "=", "[", "]", "for", "term", "in", "terms", ":", "if", "isinstance", "(", "term", ",", "Mul", ")", ":", "other", "=", "1", "sum_terms", "=", "[", "]", "if", "(", "not", "term", ".", "has", "(", "Sum", ")", ")", ":", "o_t", ".", "append", "(", "term", ")", "continue", "mul_terms", "=", "Mul", ".", "make_args", "(", "term", ")", "for", "mul_term", "in", "mul_terms", ":", "if", "isinstance", "(", "mul_term", ",", "Sum", ")", ":", "r", "=", "mul_term", ".", "_eval_simplify", "(", ")", "sum_terms", ".", "extend", "(", "Add", ".", "make_args", "(", "r", ")", ")", "else", ":", "other", "=", "(", "other", "*", "mul_term", ")", "if", "len", "(", "sum_terms", ")", ":", "s_t", ".", "append", "(", "(", "Mul", "(", "*", "sum_terms", ")", "*", "other", ")", ")", "else", ":", "o_t", ".", "append", "(", "other", ")", "elif", "isinstance", "(", "term", ",", "Sum", ")", ":", "r", "=", "term", ".", "_eval_simplify", "(", ")", "s_t", ".", "extend", "(", "Add", ".", "make_args", "(", "r", ")", ")", "else", ":", "o_t", ".", "append", "(", "term", ")", "result", "=", "Add", "(", "sum_combine", "(", "s_t", ")", ",", "*", "o_t", ")", "return", "result" ]
main function for sum simplification .
train
false
47,999
def parse_hsl(args, alpha): types = [arg.type for arg in args] if (types == [u'INTEGER', u'PERCENTAGE', u'PERCENTAGE']): hsl = [arg.value for arg in args[:3]] (r, g, b) = hsl_to_rgb(*hsl) return RGBA(r, g, b, alpha)
[ "def", "parse_hsl", "(", "args", ",", "alpha", ")", ":", "types", "=", "[", "arg", ".", "type", "for", "arg", "in", "args", "]", "if", "(", "types", "==", "[", "u'INTEGER'", ",", "u'PERCENTAGE'", ",", "u'PERCENTAGE'", "]", ")", ":", "hsl", "=", "[", "arg", ".", "value", "for", "arg", "in", "args", "[", ":", "3", "]", "]", "(", "r", ",", "g", ",", "b", ")", "=", "hsl_to_rgb", "(", "*", "hsl", ")", "return", "RGBA", "(", "r", ",", "g", ",", "b", ",", "alpha", ")" ]
if args is a list of 1 integer token and 2 percentage tokens .
train
false
48,001
def plug_router_port_attachment(cluster, router_id, port_id, attachment_uuid, nvp_attachment_type, attachment_vlan=None): uri = _build_uri_path(LROUTERPORT_RESOURCE, port_id, router_id, is_attachment=True) attach_obj = {} attach_obj['type'] = nvp_attachment_type if (nvp_attachment_type == 'PatchAttachment'): attach_obj['peer_port_uuid'] = attachment_uuid elif (nvp_attachment_type == 'L3GatewayAttachment'): attach_obj['l3_gateway_service_uuid'] = attachment_uuid if attachment_vlan: attach_obj['vlan_id'] = attachment_vlan else: raise Exception(_("Invalid NVP attachment type '%s'"), nvp_attachment_type) try: resp_obj = do_single_request(HTTP_PUT, uri, json.dumps(attach_obj), cluster=cluster) except NvpApiClient.ResourceNotFound as e: LOG.exception(_('Router Port not found, Error: %s'), str(e)) raise except NvpApiClient.Conflict as e: LOG.exception(_('Conflict while setting router port attachment')) raise except NvpApiClient.NvpApiException as e: LOG.exception(_('Unable to plug attachment into logical router port')) raise result = json.loads(resp_obj) return result
[ "def", "plug_router_port_attachment", "(", "cluster", ",", "router_id", ",", "port_id", ",", "attachment_uuid", ",", "nvp_attachment_type", ",", "attachment_vlan", "=", "None", ")", ":", "uri", "=", "_build_uri_path", "(", "LROUTERPORT_RESOURCE", ",", "port_id", ",", "router_id", ",", "is_attachment", "=", "True", ")", "attach_obj", "=", "{", "}", "attach_obj", "[", "'type'", "]", "=", "nvp_attachment_type", "if", "(", "nvp_attachment_type", "==", "'PatchAttachment'", ")", ":", "attach_obj", "[", "'peer_port_uuid'", "]", "=", "attachment_uuid", "elif", "(", "nvp_attachment_type", "==", "'L3GatewayAttachment'", ")", ":", "attach_obj", "[", "'l3_gateway_service_uuid'", "]", "=", "attachment_uuid", "if", "attachment_vlan", ":", "attach_obj", "[", "'vlan_id'", "]", "=", "attachment_vlan", "else", ":", "raise", "Exception", "(", "_", "(", "\"Invalid NVP attachment type '%s'\"", ")", ",", "nvp_attachment_type", ")", "try", ":", "resp_obj", "=", "do_single_request", "(", "HTTP_PUT", ",", "uri", ",", "json", ".", "dumps", "(", "attach_obj", ")", ",", "cluster", "=", "cluster", ")", "except", "NvpApiClient", ".", "ResourceNotFound", "as", "e", ":", "LOG", ".", "exception", "(", "_", "(", "'Router Port not found, Error: %s'", ")", ",", "str", "(", "e", ")", ")", "raise", "except", "NvpApiClient", ".", "Conflict", "as", "e", ":", "LOG", ".", "exception", "(", "_", "(", "'Conflict while setting router port attachment'", ")", ")", "raise", "except", "NvpApiClient", ".", "NvpApiException", "as", "e", ":", "LOG", ".", "exception", "(", "_", "(", "'Unable to plug attachment into logical router port'", ")", ")", "raise", "result", "=", "json", ".", "loads", "(", "resp_obj", ")", "return", "result" ]
attach a router port to the given attachment .
train
false
48,002
def argspec_args(argspec, constructor, *args, **kwargs): if argspec.keywords: call_kwarg = kwargs else: call_kwarg = dict(((k, kwargs[k]) for k in kwargs if (k in argspec.args))) if argspec.varargs: call_args = args else: call_args = args[:(len(argspec.args) - (1 if constructor else 0))] return (call_args, call_kwarg)
[ "def", "argspec_args", "(", "argspec", ",", "constructor", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "argspec", ".", "keywords", ":", "call_kwarg", "=", "kwargs", "else", ":", "call_kwarg", "=", "dict", "(", "(", "(", "k", ",", "kwargs", "[", "k", "]", ")", "for", "k", "in", "kwargs", "if", "(", "k", "in", "argspec", ".", "args", ")", ")", ")", "if", "argspec", ".", "varargs", ":", "call_args", "=", "args", "else", ":", "call_args", "=", "args", "[", ":", "(", "len", "(", "argspec", ".", "args", ")", "-", "(", "1", "if", "constructor", "else", "0", ")", ")", "]", "return", "(", "call_args", ",", "call_kwarg", ")" ]
return matching the argspec object .
train
true
48,003
def log_floor(n, b): p = 1 k = 0 while (p <= n): p *= b k += 1 return (k - 1)
[ "def", "log_floor", "(", "n", ",", "b", ")", ":", "p", "=", "1", "k", "=", "0", "while", "(", "p", "<=", "n", ")", ":", "p", "*=", "b", "k", "+=", "1", "return", "(", "k", "-", "1", ")" ]
the largest integer k such that b^k <= n .
train
false
48,004
@deprecated(u'1.4.0', _deprecation_msg) def create_subsystem(subsystem_type, scope=u'test-scope', **options): if (not issubclass(subsystem_type, Subsystem)): raise TypeError(u'The given `subsystem_type` was not a subclass of `Subsystem`: {}'.format(subsystem_type)) option_values = create_option_values_for_optionable(subsystem_type, **options) return subsystem_type(scope, option_values)
[ "@", "deprecated", "(", "u'1.4.0'", ",", "_deprecation_msg", ")", "def", "create_subsystem", "(", "subsystem_type", ",", "scope", "=", "u'test-scope'", ",", "**", "options", ")", ":", "if", "(", "not", "issubclass", "(", "subsystem_type", ",", "Subsystem", ")", ")", ":", "raise", "TypeError", "(", "u'The given `subsystem_type` was not a subclass of `Subsystem`: {}'", ".", "format", "(", "subsystem_type", ")", ")", "option_values", "=", "create_option_values_for_optionable", "(", "subsystem_type", ",", "**", "options", ")", "return", "subsystem_type", "(", "scope", ",", "option_values", ")" ]
creates a subsystem for test .
train
false
48,005
def printf_format_for_struct(t, types): fields = [] for (name, argtype) in type_description(t, types)['struct'].items(): printf_specifier = type_description(argtype, types).get('printf_specifier', None) if (printf_specifier != None): fields.append((((('"' + name) + '"') + ' : ') + printf_specifier)) else: struct_format = printf_format_for_struct(argtype, types) fields.append((((('"' + name) + '"') + ' : ') + struct_format)) return ('{%s}' % ', '.join(fields))
[ "def", "printf_format_for_struct", "(", "t", ",", "types", ")", ":", "fields", "=", "[", "]", "for", "(", "name", ",", "argtype", ")", "in", "type_description", "(", "t", ",", "types", ")", "[", "'struct'", "]", ".", "items", "(", ")", ":", "printf_specifier", "=", "type_description", "(", "argtype", ",", "types", ")", ".", "get", "(", "'printf_specifier'", ",", "None", ")", "if", "(", "printf_specifier", "!=", "None", ")", ":", "fields", ".", "append", "(", "(", "(", "(", "(", "'\"'", "+", "name", ")", "+", "'\"'", ")", "+", "' : '", ")", "+", "printf_specifier", ")", ")", "else", ":", "struct_format", "=", "printf_format_for_struct", "(", "argtype", ",", "types", ")", "fields", ".", "append", "(", "(", "(", "(", "(", "'\"'", "+", "name", ")", "+", "'\"'", ")", "+", "' : '", ")", "+", "struct_format", ")", ")", "return", "(", "'{%s}'", "%", "', '", ".", "join", "(", "fields", ")", ")" ]
returns a format string for printing the given struct type .
train
false
48,006
def _get_nose_vars(): from nose import tools new_names = {} for t in dir(tools): if (t.startswith(u'assert_') or (t in (u'ok_', u'eq_'))): new_names[t] = getattr(tools, t) return new_names
[ "def", "_get_nose_vars", "(", ")", ":", "from", "nose", "import", "tools", "new_names", "=", "{", "}", "for", "t", "in", "dir", "(", "tools", ")", ":", "if", "(", "t", ".", "startswith", "(", "u'assert_'", ")", "or", "(", "t", "in", "(", "u'ok_'", ",", "u'eq_'", ")", ")", ")", ":", "new_names", "[", "t", "]", "=", "getattr", "(", "tools", ",", "t", ")", "return", "new_names" ]
collect assert_* .
train
false
48,007
def expand_line(line, sites): try: l = line.strip() (msg_format, links) = find_links(l) args = tuple((follow_redirects(l, sites) for l in links)) line = (msg_format % args) except Exception as e: try: err(('expanding line %s failed due to %s' % (line, unicode(e)))) except: pass return line
[ "def", "expand_line", "(", "line", ",", "sites", ")", ":", "try", ":", "l", "=", "line", ".", "strip", "(", ")", "(", "msg_format", ",", "links", ")", "=", "find_links", "(", "l", ")", "args", "=", "tuple", "(", "(", "follow_redirects", "(", "l", ",", "sites", ")", "for", "l", "in", "links", ")", ")", "line", "=", "(", "msg_format", "%", "args", ")", "except", "Exception", "as", "e", ":", "try", ":", "err", "(", "(", "'expanding line %s failed due to %s'", "%", "(", "line", ",", "unicode", "(", "e", ")", ")", ")", ")", "except", ":", "pass", "return", "line" ]
expand the links in the line for the given sites .
train
false
48,008
def _nan_rows(*arrs): if (len(arrs) == 1): arrs += ([[False]],) def _nan_row_maybe_two_inputs(x, y): x_is_boolean_array = (hasattr(x, 'dtype') and (x.dtype == bool) and x) return np.logical_or(_asarray_2d_null_rows(x), (x_is_boolean_array | _asarray_2d_null_rows(y))) return reduce(_nan_row_maybe_two_inputs, arrs).squeeze()
[ "def", "_nan_rows", "(", "*", "arrs", ")", ":", "if", "(", "len", "(", "arrs", ")", "==", "1", ")", ":", "arrs", "+=", "(", "[", "[", "False", "]", "]", ",", ")", "def", "_nan_row_maybe_two_inputs", "(", "x", ",", "y", ")", ":", "x_is_boolean_array", "=", "(", "hasattr", "(", "x", ",", "'dtype'", ")", "and", "(", "x", ".", "dtype", "==", "bool", ")", "and", "x", ")", "return", "np", ".", "logical_or", "(", "_asarray_2d_null_rows", "(", "x", ")", ",", "(", "x_is_boolean_array", "|", "_asarray_2d_null_rows", "(", "y", ")", ")", ")", "return", "reduce", "(", "_nan_row_maybe_two_inputs", ",", "arrs", ")", ".", "squeeze", "(", ")" ]
returns a boolean array which is true where any of the rows in any of the _2d_ arrays in arrs are nans .
train
false
48,009
def get_tax_module(): return load_module('SHUUP_TAX_MODULE', 'tax_module')()
[ "def", "get_tax_module", "(", ")", ":", "return", "load_module", "(", "'SHUUP_TAX_MODULE'", ",", "'tax_module'", ")", "(", ")" ]
get the taxmodule specified in settings .
train
false
48,010
def generate_minion_id(): return (_generate_minion_id().first() or 'localhost')
[ "def", "generate_minion_id", "(", ")", ":", "return", "(", "_generate_minion_id", "(", ")", ".", "first", "(", ")", "or", "'localhost'", ")" ]
return only first element of the hostname from all possible list .
train
false
48,011
def LINEARREG_SLOPE(ds, count, timeperiod=(- (2 ** 31))): return call_talib_with_ds(ds, count, talib.LINEARREG_SLOPE, timeperiod)
[ "def", "LINEARREG_SLOPE", "(", "ds", ",", "count", ",", "timeperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ")", ":", "return", "call_talib_with_ds", "(", "ds", ",", "count", ",", "talib", ".", "LINEARREG_SLOPE", ",", "timeperiod", ")" ]
linear regression slope .
train
false
48,012
def setupmethod(f): def wrapper_func(self, *args, **kwargs): if (self.debug and self._got_first_request): raise AssertionError('A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.') return f(self, *args, **kwargs) return update_wrapper(wrapper_func, f)
[ "def", "setupmethod", "(", "f", ")", ":", "def", "wrapper_func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "self", ".", "debug", "and", "self", ".", "_got_first_request", ")", ":", "raise", "AssertionError", "(", "'A setup function was called after the first request was handled. This usually indicates a bug in the application where a module was not imported and decorators or other functionality was called too late.\\nTo fix this make sure to import all your view modules, database models and everything related at a central place before the application starts serving requests.'", ")", "return", "f", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", "return", "update_wrapper", "(", "wrapper_func", ",", "f", ")" ]
wraps a method so that it performs a check in debug mode if the first request was already handled .
train
true
48,013
def fullversion(): ret = {} cmd = 'lvm version' out = __salt__['cmd.run'](cmd).splitlines() for line in out: comps = line.split(':') ret[comps[0].strip()] = comps[1].strip() return ret
[ "def", "fullversion", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'lvm version'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "for", "line", "in", "out", ":", "comps", "=", "line", ".", "split", "(", "':'", ")", "ret", "[", "comps", "[", "0", "]", ".", "strip", "(", ")", "]", "=", "comps", "[", "1", "]", ".", "strip", "(", ")", "return", "ret" ]
return all version info from lvm version cli example: .
train
true
48,014
def parse_single_table(source, **kwargs): if (kwargs.get(u'table_number') is None): kwargs[u'table_number'] = 0 votable = parse(source, **kwargs) return votable.get_first_table()
[ "def", "parse_single_table", "(", "source", ",", "**", "kwargs", ")", ":", "if", "(", "kwargs", ".", "get", "(", "u'table_number'", ")", "is", "None", ")", ":", "kwargs", "[", "u'table_number'", "]", "=", "0", "votable", "=", "parse", "(", "source", ",", "**", "kwargs", ")", "return", "votable", ".", "get_first_table", "(", ")" ]
parses a votable_ xml file .
train
false
48,015
def _pol_to_cart(pol): out = np.empty_like(pol) out[:, 0] = (pol[:, 0] * np.cos(pol[:, 1])) out[:, 1] = (pol[:, 0] * np.sin(pol[:, 1])) return out
[ "def", "_pol_to_cart", "(", "pol", ")", ":", "out", "=", "np", ".", "empty_like", "(", "pol", ")", "out", "[", ":", ",", "0", "]", "=", "(", "pol", "[", ":", ",", "0", "]", "*", "np", ".", "cos", "(", "pol", "[", ":", ",", "1", "]", ")", ")", "out", "[", ":", ",", "1", "]", "=", "(", "pol", "[", ":", ",", "0", "]", "*", "np", ".", "sin", "(", "pol", "[", ":", ",", "1", "]", ")", ")", "return", "out" ]
transform polar coordinates to cartesian .
train
false
48,017
def normalize_language_tag(tag): tag = ascii_lower(tag).replace(u'_', u'-') tag = re.sub(u'-([a-zA-Z0-9])-', u'-\\1_', tag) subtags = [subtag.replace(u'_', u'-') for subtag in tag.split(u'-')] base_tag = (subtags.pop(0),) taglist = {base_tag[0]} for n in range(len(subtags), 0, (-1)): for tags in itertools.combinations(subtags, n): taglist.add(u'-'.join((base_tag + tags))) return taglist
[ "def", "normalize_language_tag", "(", "tag", ")", ":", "tag", "=", "ascii_lower", "(", "tag", ")", ".", "replace", "(", "u'_'", ",", "u'-'", ")", "tag", "=", "re", ".", "sub", "(", "u'-([a-zA-Z0-9])-'", ",", "u'-\\\\1_'", ",", "tag", ")", "subtags", "=", "[", "subtag", ".", "replace", "(", "u'_'", ",", "u'-'", ")", "for", "subtag", "in", "tag", ".", "split", "(", "u'-'", ")", "]", "base_tag", "=", "(", "subtags", ".", "pop", "(", "0", ")", ",", ")", "taglist", "=", "{", "base_tag", "[", "0", "]", "}", "for", "n", "in", "range", "(", "len", "(", "subtags", ")", ",", "0", ",", "(", "-", "1", ")", ")", ":", "for", "tags", "in", "itertools", ".", "combinations", "(", "subtags", ",", "n", ")", ":", "taglist", ".", "add", "(", "u'-'", ".", "join", "(", "(", "base_tag", "+", "tags", ")", ")", ")", "return", "taglist" ]
return a list of normalized combinations for a bcp 47 language tag .
train
false
48,019
def RandomSeed(x): random.seed(x) np.random.seed(x)
[ "def", "RandomSeed", "(", "x", ")", ":", "random", ".", "seed", "(", "x", ")", "np", ".", "random", ".", "seed", "(", "x", ")" ]
initialize the random and np .
train
false
48,020
def to_db(value): if (value is None): return None return unparse_multistring(value)
[ "def", "to_db", "(", "value", ")", ":", "if", "(", "value", "is", "None", ")", ":", "return", "None", "return", "unparse_multistring", "(", "value", ")" ]
flatten the given value into the database string representation .
train
false
48,021
def applications_page_check(request, current_page=None, path=None): if current_page: return current_page if (path is None): path = request.path_info.replace(reverse('pages-root'), '', 1) for lang in get_language_list(): if path.startswith((lang + '/')): path = path[len((lang + '/')):] for resolver in APP_RESOLVERS: try: page_id = resolver.resolve_page_id(path) page = Page.objects.public().get(id=page_id) return page except Resolver404: pass except Page.DoesNotExist: pass return None
[ "def", "applications_page_check", "(", "request", ",", "current_page", "=", "None", ",", "path", "=", "None", ")", ":", "if", "current_page", ":", "return", "current_page", "if", "(", "path", "is", "None", ")", ":", "path", "=", "request", ".", "path_info", ".", "replace", "(", "reverse", "(", "'pages-root'", ")", ",", "''", ",", "1", ")", "for", "lang", "in", "get_language_list", "(", ")", ":", "if", "path", ".", "startswith", "(", "(", "lang", "+", "'/'", ")", ")", ":", "path", "=", "path", "[", "len", "(", "(", "lang", "+", "'/'", ")", ")", ":", "]", "for", "resolver", "in", "APP_RESOLVERS", ":", "try", ":", "page_id", "=", "resolver", ".", "resolve_page_id", "(", "path", ")", "page", "=", "Page", ".", "objects", ".", "public", "(", ")", ".", "get", "(", "id", "=", "page_id", ")", "return", "page", "except", "Resolver404", ":", "pass", "except", "Page", ".", "DoesNotExist", ":", "pass", "return", "None" ]
tries to find if given path was resolved over application .
train
false
48,022
def _info(*pkgs): cmd = 'brew info --json=v1 {0}'.format(' '.join(pkgs)) brew_result = _call_brew(cmd) if brew_result['retcode']: log.error('Failed to get info about packages: {0}'.format(' '.join(pkgs))) return {} output = json.loads(brew_result['stdout']) return dict(zip(pkgs, output))
[ "def", "_info", "(", "*", "pkgs", ")", ":", "cmd", "=", "'brew info --json=v1 {0}'", ".", "format", "(", "' '", ".", "join", "(", "pkgs", ")", ")", "brew_result", "=", "_call_brew", "(", "cmd", ")", "if", "brew_result", "[", "'retcode'", "]", ":", "log", ".", "error", "(", "'Failed to get info about packages: {0}'", ".", "format", "(", "' '", ".", "join", "(", "pkgs", ")", ")", ")", "return", "{", "}", "output", "=", "json", ".", "loads", "(", "brew_result", "[", "'stdout'", "]", ")", "return", "dict", "(", "zip", "(", "pkgs", ",", "output", ")", ")" ]
get all info brew can provide about a list of packages .
train
true
48,023
def keyring_auth_add(**kwargs): return ceph_cfg.keyring_auth_add(**kwargs)
[ "def", "keyring_auth_add", "(", "**", "kwargs", ")", ":", "return", "ceph_cfg", ".", "keyring_auth_add", "(", "**", "kwargs", ")" ]
add keyring to authorised list cli example: .
train
false
48,027
def apply_tag_sets(tag_sets, selection): for tag_set in tag_sets: with_tag_set = apply_single_tag_set(tag_set, selection) if with_tag_set: return with_tag_set return selection.with_server_descriptions([])
[ "def", "apply_tag_sets", "(", "tag_sets", ",", "selection", ")", ":", "for", "tag_set", "in", "tag_sets", ":", "with_tag_set", "=", "apply_single_tag_set", "(", "tag_set", ",", "selection", ")", "if", "with_tag_set", ":", "return", "with_tag_set", "return", "selection", ".", "with_server_descriptions", "(", "[", "]", ")" ]
all servers match a list of tag sets .
train
true
48,028
def is_literal(expr): if isinstance(expr, Not): return (not isinstance(expr.args[0], BooleanFunction)) else: return (not isinstance(expr, BooleanFunction))
[ "def", "is_literal", "(", "expr", ")", ":", "if", "isinstance", "(", "expr", ",", "Not", ")", ":", "return", "(", "not", "isinstance", "(", "expr", ".", "args", "[", "0", "]", ",", "BooleanFunction", ")", ")", "else", ":", "return", "(", "not", "isinstance", "(", "expr", ",", "BooleanFunction", ")", ")" ]
returns true if expr is a literal .
train
false
48,033
def maximum_spanning_tree(G, weight='weight', algorithm='kruskal'): return _optimum_spanning_tree(G, algorithm=algorithm, minimum=False, weight=weight)
[ "def", "maximum_spanning_tree", "(", "G", ",", "weight", "=", "'weight'", ",", "algorithm", "=", "'kruskal'", ")", ":", "return", "_optimum_spanning_tree", "(", "G", ",", "algorithm", "=", "algorithm", ",", "minimum", "=", "False", ",", "weight", "=", "weight", ")" ]
returns a maximum spanning tree or forest on an undirected graph g .
train
false
48,035
def riccati_jn(n, x): if (not (isscalar(n) and isscalar(x))): raise ValueError('arguments must be scalars.') if ((n != floor(n)) or (n < 0)): raise ValueError('n must be a non-negative integer.') if (n == 0): n1 = 1 else: n1 = n (nm, jn, jnp) = specfun.rctj(n1, x) return (jn[:(n + 1)], jnp[:(n + 1)])
[ "def", "riccati_jn", "(", "n", ",", "x", ")", ":", "if", "(", "not", "(", "isscalar", "(", "n", ")", "and", "isscalar", "(", "x", ")", ")", ")", ":", "raise", "ValueError", "(", "'arguments must be scalars.'", ")", "if", "(", "(", "n", "!=", "floor", "(", "n", ")", ")", "or", "(", "n", "<", "0", ")", ")", ":", "raise", "ValueError", "(", "'n must be a non-negative integer.'", ")", "if", "(", "n", "==", "0", ")", ":", "n1", "=", "1", "else", ":", "n1", "=", "n", "(", "nm", ",", "jn", ",", "jnp", ")", "=", "specfun", ".", "rctj", "(", "n1", ",", "x", ")", "return", "(", "jn", "[", ":", "(", "n", "+", "1", ")", "]", ",", "jnp", "[", ":", "(", "n", "+", "1", ")", "]", ")" ]
compute ricatti-bessel function of the first kind and its derivative .
train
false
48,036
def custom_box_style(x0, y0, width, height, mutation_size, mutation_aspect=1): mypad = 0.3 pad = (mutation_size * mypad) (width, height) = ((width + (2.0 * pad)), (height + (2.0 * pad))) (x0, y0) = ((x0 - pad), (y0 - pad)) (x1, y1) = ((x0 + width), (y0 + height)) cp = [(x0, y0), (x1, y0), (x1, y1), (x0, y1), ((x0 - pad), ((y0 + y1) / 2.0)), (x0, y0), (x0, y0)] com = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] path = Path(cp, com) return path
[ "def", "custom_box_style", "(", "x0", ",", "y0", ",", "width", ",", "height", ",", "mutation_size", ",", "mutation_aspect", "=", "1", ")", ":", "mypad", "=", "0.3", "pad", "=", "(", "mutation_size", "*", "mypad", ")", "(", "width", ",", "height", ")", "=", "(", "(", "width", "+", "(", "2.0", "*", "pad", ")", ")", ",", "(", "height", "+", "(", "2.0", "*", "pad", ")", ")", ")", "(", "x0", ",", "y0", ")", "=", "(", "(", "x0", "-", "pad", ")", ",", "(", "y0", "-", "pad", ")", ")", "(", "x1", ",", "y1", ")", "=", "(", "(", "x0", "+", "width", ")", ",", "(", "y0", "+", "height", ")", ")", "cp", "=", "[", "(", "x0", ",", "y0", ")", ",", "(", "x1", ",", "y0", ")", ",", "(", "x1", ",", "y1", ")", ",", "(", "x0", ",", "y1", ")", ",", "(", "(", "x0", "-", "pad", ")", ",", "(", "(", "y0", "+", "y1", ")", "/", "2.0", ")", ")", ",", "(", "x0", ",", "y0", ")", ",", "(", "x0", ",", "y0", ")", "]", "com", "=", "[", "Path", ".", "MOVETO", ",", "Path", ".", "LINETO", ",", "Path", ".", "LINETO", ",", "Path", ".", "LINETO", ",", "Path", ".", "LINETO", ",", "Path", ".", "LINETO", ",", "Path", ".", "CLOSEPOLY", "]", "path", "=", "Path", "(", "cp", ",", "com", ")", "return", "path" ]
given the location and size of the box .
train
false
48,037
def sub_expr(lh_op, rh_op): return sum_expr([lh_op, neg_expr(rh_op)])
[ "def", "sub_expr", "(", "lh_op", ",", "rh_op", ")", ":", "return", "sum_expr", "(", "[", "lh_op", ",", "neg_expr", "(", "rh_op", ")", "]", ")" ]
difference of linear operators .
train
false
48,038
def update_local_friends(core, l): fullList = (core.memberList + core.mpList) for friend in l: if ('NickName' in friend): utils.emoji_formatter(friend, 'NickName') if ('DisplayName' in friend): utils.emoji_formatter(friend, 'DisplayName') oldInfoDict = utils.search_dict_list(fullList, 'UserName', friend['UserName']) if (oldInfoDict is None): oldInfoDict = copy.deepcopy(friend) if ((oldInfoDict['VerifyFlag'] & 8) == 0): core.memberList.append(oldInfoDict) else: core.mpList.append(oldInfoDict) else: update_info_dict(oldInfoDict, friend)
[ "def", "update_local_friends", "(", "core", ",", "l", ")", ":", "fullList", "=", "(", "core", ".", "memberList", "+", "core", ".", "mpList", ")", "for", "friend", "in", "l", ":", "if", "(", "'NickName'", "in", "friend", ")", ":", "utils", ".", "emoji_formatter", "(", "friend", ",", "'NickName'", ")", "if", "(", "'DisplayName'", "in", "friend", ")", ":", "utils", ".", "emoji_formatter", "(", "friend", ",", "'DisplayName'", ")", "oldInfoDict", "=", "utils", ".", "search_dict_list", "(", "fullList", ",", "'UserName'", ",", "friend", "[", "'UserName'", "]", ")", "if", "(", "oldInfoDict", "is", "None", ")", ":", "oldInfoDict", "=", "copy", ".", "deepcopy", "(", "friend", ")", "if", "(", "(", "oldInfoDict", "[", "'VerifyFlag'", "]", "&", "8", ")", "==", "0", ")", ":", "core", ".", "memberList", ".", "append", "(", "oldInfoDict", ")", "else", ":", "core", ".", "mpList", ".", "append", "(", "oldInfoDict", ")", "else", ":", "update_info_dict", "(", "oldInfoDict", ",", "friend", ")" ]
get a list of friends or mps for updating local contact .
train
false
48,039
def _prep_create_using(create_using): if (create_using is None): return nx.Graph() try: create_using.clear() except: raise TypeError('Input graph is not a networkx graph type') return create_using
[ "def", "_prep_create_using", "(", "create_using", ")", ":", "if", "(", "create_using", "is", "None", ")", ":", "return", "nx", ".", "Graph", "(", ")", "try", ":", "create_using", ".", "clear", "(", ")", "except", ":", "raise", "TypeError", "(", "'Input graph is not a networkx graph type'", ")", "return", "create_using" ]
return a graph object ready to be populated .
train
false
48,040
def make_boolean(value): value = str(value) value = value.lower().strip() if (value in ('true', 'false')): if (value == 'true'): return True return False try: ival = int(value) return bool(ival) except ValueError: pass if (value in ('+', '-')): if (value == '+'): return True return False if (value in ('on', 'off')): if (value == 'on'): return True return False raise TwillException(("unable to convert '%s' into true/false" % (value,)))
[ "def", "make_boolean", "(", "value", ")", ":", "value", "=", "str", "(", "value", ")", "value", "=", "value", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "(", "value", "in", "(", "'true'", ",", "'false'", ")", ")", ":", "if", "(", "value", "==", "'true'", ")", ":", "return", "True", "return", "False", "try", ":", "ival", "=", "int", "(", "value", ")", "return", "bool", "(", "ival", ")", "except", "ValueError", ":", "pass", "if", "(", "value", "in", "(", "'+'", ",", "'-'", ")", ")", ":", "if", "(", "value", "==", "'+'", ")", ":", "return", "True", "return", "False", "if", "(", "value", "in", "(", "'on'", ",", "'off'", ")", ")", ":", "if", "(", "value", "==", "'on'", ")", ":", "return", "True", "return", "False", "raise", "TwillException", "(", "(", "\"unable to convert '%s' into true/false\"", "%", "(", "value", ",", ")", ")", ")" ]
convert the input value into a boolean like so: >> make_boolean true >> make_boolean false >> make_boolean(1) true >> make_boolean(0) false >> make_boolean(+) true >> make_boolean(-) false .
train
false