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
28,779
def autocrop(im, autocrop=False, **kwargs): if autocrop: if (utils.is_transparent(im) and False): no_alpha = Image.new('L', im.size, 255) no_alpha.paste(im, mask=im.split()[(-1)]) else: no_alpha = im.convert('L') bw = no_alpha.convert('L') bg = Image.new('L', im.size, 255) bbox = ImageChops.difference(bw, bg).getbbox() if bbox: im = im.crop(bbox) return im
[ "def", "autocrop", "(", "im", ",", "autocrop", "=", "False", ",", "**", "kwargs", ")", ":", "if", "autocrop", ":", "if", "(", "utils", ".", "is_transparent", "(", "im", ")", "and", "False", ")", ":", "no_alpha", "=", "Image", ".", "new", "(", "'L'"...
remove any unnecessary whitespace from the edges of the source image .
train
true
28,780
@hgcommand def pq(ui, repo, *pats, **opts): opts['quick'] = True return pending(ui, repo, *pats, **opts)
[ "@", "hgcommand", "def", "pq", "(", "ui", ",", "repo", ",", "*", "pats", ",", "**", "opts", ")", ":", "opts", "[", "'quick'", "]", "=", "True", "return", "pending", "(", "ui", ",", "repo", ",", "*", "pats", ",", "**", "opts", ")" ]
alias for hg p --quick .
train
true
28,783
def try_import(module): from importlib import import_module try: return import_module(module) except ImportError: pass
[ "def", "try_import", "(", "module", ")", ":", "from", "importlib", "import", "import_module", "try", ":", "return", "import_module", "(", "module", ")", "except", "ImportError", ":", "pass" ]
try to import and return module .
train
false
28,785
@contextmanager def loop_nest(builder, shape, intp, order='C'): assert (order in 'CF') if (not shape): (yield ()) else: if (order == 'F'): _swap = (lambda x: x[::(-1)]) else: _swap = (lambda x: x) with _loop_nest(builder, _swap(shape), intp) as indices: assert (len(indices) == len(shape)) (yield _swap(indices))
[ "@", "contextmanager", "def", "loop_nest", "(", "builder", ",", "shape", ",", "intp", ",", "order", "=", "'C'", ")", ":", "assert", "(", "order", "in", "'CF'", ")", "if", "(", "not", "shape", ")", ":", "(", "yield", "(", ")", ")", "else", ":", "i...
generate a loop nest walking a n-dimensional array .
train
false
28,786
def start_block(fid, kind): write_int(fid, FIFF.FIFF_BLOCK_START, kind)
[ "def", "start_block", "(", "fid", ",", "kind", ")", ":", "write_int", "(", "fid", ",", "FIFF", ".", "FIFF_BLOCK_START", ",", "kind", ")" ]
write a fiff_block_start tag .
train
false
28,787
def p_equality_expression_1(t): pass
[ "def", "p_equality_expression_1", "(", "t", ")", ":", "pass" ]
equality_expression : relational_expression .
train
false
28,788
def _expand_disk(disk): ret = {} ret.update(disk.__dict__) zone = ret['extra']['zone'] ret['extra']['zone'] = {} ret['extra']['zone'].update(zone.__dict__) return ret
[ "def", "_expand_disk", "(", "disk", ")", ":", "ret", "=", "{", "}", "ret", ".", "update", "(", "disk", ".", "__dict__", ")", "zone", "=", "ret", "[", "'extra'", "]", "[", "'zone'", "]", "ret", "[", "'extra'", "]", "[", "'zone'", "]", "=", "{", ...
convert the libcloud volume object into something more serializable .
train
true
28,790
def process_sequences(sequences, end_id=0, pad_val=0, is_shorten=True, remain_end_id=False): max_length = 0 for (i_s, seq) in enumerate(sequences): is_end = False for (i_w, n) in enumerate(seq): if ((n == end_id) and (is_end == False)): is_end = True if (max_length < i_w): max_length = i_w if (remain_end_id is False): seq[i_w] = pad_val elif (is_end == True): seq[i_w] = pad_val if (remain_end_id is True): max_length += 1 if is_shorten: for (i, seq) in enumerate(sequences): sequences[i] = seq[:max_length] return sequences
[ "def", "process_sequences", "(", "sequences", ",", "end_id", "=", "0", ",", "pad_val", "=", "0", ",", "is_shorten", "=", "True", ",", "remain_end_id", "=", "False", ")", ":", "max_length", "=", "0", "for", "(", "i_s", ",", "seq", ")", "in", "enumerate"...
set all tokens after end token to the padding value .
train
true
28,792
def get_wu_settings(): ret = {} day = ['Every Day', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] pythoncom.CoInitialize() obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate') obj_au_settings = obj_au.Settings ret['Featured Updates'] = obj_au_settings.FeaturedUpdatesEnabled ret['Group Policy Required'] = obj_au_settings.Required ret['Microsoft Update'] = _get_msupdate_status() ret['Needs Reboot'] = get_needs_reboot() ret['Non Admins Elevated'] = obj_au_settings.NonAdministratorsElevated ret['Notification Level'] = obj_au_settings.NotificationLevel ret['Read Only'] = obj_au_settings.ReadOnly ret['Recommended Updates'] = obj_au_settings.IncludeRecommendedUpdates ret['Scheduled Day'] = day[obj_au_settings.ScheduledInstallationDay] if (obj_au_settings.ScheduledInstallationTime < 10): ret['Scheduled Time'] = '0{0}:00'.format(obj_au_settings.ScheduledInstallationTime) else: ret['Scheduled Time'] = '{0}:00'.format(obj_au_settings.ScheduledInstallationTime) return ret
[ "def", "get_wu_settings", "(", ")", ":", "ret", "=", "{", "}", "day", "=", "[", "'Every Day'", ",", "'Sunday'", ",", "'Monday'", ",", "'Tuesday'", ",", "'Wednesday'", ",", "'Thursday'", ",", "'Friday'", ",", "'Saturday'", "]", "pythoncom", ".", "CoInitiali...
get current windows update settings .
train
false
28,793
def spilu(A, drop_tol=None, fill_factor=None, drop_rule=None, permc_spec=None, diag_pivot_thresh=None, relax=None, panel_size=None, options=None): if (not isspmatrix_csc(A)): A = csc_matrix(A) warn('splu requires CSC matrix format', SparseEfficiencyWarning) A.sort_indices() A = A.asfptype() (M, N) = A.shape if (M != N): raise ValueError('can only factor square matrices') _options = dict(ILU_DropRule=drop_rule, ILU_DropTol=drop_tol, ILU_FillFactor=fill_factor, DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec, PanelSize=panel_size, Relax=relax) if (options is not None): _options.update(options) return _superlu.gstrf(N, A.nnz, A.data, A.indices, A.indptr, ilu=True, options=_options)
[ "def", "spilu", "(", "A", ",", "drop_tol", "=", "None", ",", "fill_factor", "=", "None", ",", "drop_rule", "=", "None", ",", "permc_spec", "=", "None", ",", "diag_pivot_thresh", "=", "None", ",", "relax", "=", "None", ",", "panel_size", "=", "None", ",...
compute an incomplete lu decomposition for a sparse .
train
false
28,794
def fragments_fromstring(html, no_leading_text=False, base_url=None, parser=None, **kw): if (parser is None): parser = html_parser if isinstance(html, bytes): if (not _looks_like_full_html_bytes(html)): html = (('<html><body>'.encode('ascii') + html) + '</body></html>'.encode('ascii')) elif (not _looks_like_full_html_unicode(html)): html = ('<html><body>%s</body></html>' % html) doc = document_fromstring(html, parser=parser, base_url=base_url, **kw) assert (_nons(doc.tag) == 'html') bodies = [e for e in doc if (_nons(e.tag) == 'body')] assert (len(bodies) == 1), ('too many bodies: %r in %r' % (bodies, html)) body = bodies[0] elements = [] if (no_leading_text and body.text and body.text.strip()): raise etree.ParserError(('There is leading text: %r' % body.text)) if (body.text and body.text.strip()): elements.append(body.text) elements.extend(body) return elements
[ "def", "fragments_fromstring", "(", "html", ",", "no_leading_text", "=", "False", ",", "base_url", "=", "None", ",", "parser", "=", "None", ",", "**", "kw", ")", ":", "if", "(", "parser", "is", "None", ")", ":", "parser", "=", "html_parser", "if", "isi...
parses several html elements .
train
true
28,796
def ignore_exception(exception_class): def _decorator(func): def newfunc(*args, **kwds): try: return func(*args, **kwds) except exception_class: pass return newfunc return _decorator
[ "def", "ignore_exception", "(", "exception_class", ")", ":", "def", "_decorator", "(", "func", ")", ":", "def", "newfunc", "(", "*", "args", ",", "**", "kwds", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "**", "kwds", ")", "except"...
a decorator that ignores exception_class exceptions .
train
true
28,799
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
28,804
def make_flow_txt(sff_fp, output_fp, use_sfftools=False): if use_sfftools: _fail_on_gzipped_sff(sff_fp) check_sffinfo() _check_call(['sffinfo', sff_fp], stdout=open(output_fp, 'w')) else: try: format_binary_sff(qiime_open(sff_fp, 'rb'), open(output_fp, 'w')) except: raise IOError(('Could not parse SFF %s' % sff_fp))
[ "def", "make_flow_txt", "(", "sff_fp", ",", "output_fp", ",", "use_sfftools", "=", "False", ")", ":", "if", "use_sfftools", ":", "_fail_on_gzipped_sff", "(", "sff_fp", ")", "check_sffinfo", "(", ")", "_check_call", "(", "[", "'sffinfo'", ",", "sff_fp", "]", ...
makes flowgram file from sff file .
train
false
28,805
def tooltip(): if ('formfield' in request.vars): response.view = ('pr/ajaxtips/%s.html' % request.vars.formfield) return dict()
[ "def", "tooltip", "(", ")", ":", "if", "(", "'formfield'", "in", "request", ".", "vars", ")", ":", "response", ".", "view", "=", "(", "'pr/ajaxtips/%s.html'", "%", "request", ".", "vars", ".", "formfield", ")", "return", "dict", "(", ")" ]
ajax tooltips .
train
false
28,806
def memodict(f): class memodict(defaultdict, ): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__
[ "def", "memodict", "(", "f", ")", ":", "class", "memodict", "(", "defaultdict", ",", ")", ":", "def", "__missing__", "(", "self", ",", "key", ")", ":", "ret", "=", "self", "[", "key", "]", "=", "f", "(", "key", ")", "return", "ret", "return", "me...
memoization decorator for a function taking a single argument .
train
false
28,807
def _log_failure(parameter, exc): log.debug(('proc call failed (%s): %s' % (parameter, exc)))
[ "def", "_log_failure", "(", "parameter", ",", "exc", ")", ":", "log", ".", "debug", "(", "(", "'proc call failed (%s): %s'", "%", "(", "parameter", ",", "exc", ")", ")", ")" ]
logs a message indicating that the proc query failed .
train
false
28,808
def clear_data_home(data_home=None): data_home = get_data_home(data_home) shutil.rmtree(data_home)
[ "def", "clear_data_home", "(", "data_home", "=", "None", ")", ":", "data_home", "=", "get_data_home", "(", "data_home", ")", "shutil", ".", "rmtree", "(", "data_home", ")" ]
delete all the content of the data home cache .
train
false
28,811
def libvlc_module_description_list_release(p_list): f = (_Cfunctions.get('libvlc_module_description_list_release', None) or _Cfunction('libvlc_module_description_list_release', ((1,),), None, None, ctypes.POINTER(ModuleDescription))) return f(p_list)
[ "def", "libvlc_module_description_list_release", "(", "p_list", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_module_description_list_release'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_module_description_list_release'", ",", "(", "(", "...
release a list of module descriptions .
train
true
28,812
def vulnerability_type(): return s3_rest_controller()
[ "def", "vulnerability_type", "(", ")", ":", "return", "s3_rest_controller", "(", ")" ]
vulnerability types: restful crud controller .
train
false
28,813
def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime): return pd.DataFrame({'symbol': [chr((ord('A') + i)) for i in range(num_assets)], 'start_date': pd.date_range(first_start, freq=(periods_between_starts * frequency), periods=num_assets), 'end_date': pd.date_range((first_start + (asset_lifetime * frequency)), freq=(periods_between_starts * frequency), periods=num_assets), 'exchange': 'TEST', 'exchange_full': 'TEST FULL'}, index=range(num_assets))
[ "def", "make_rotating_equity_info", "(", "num_assets", ",", "first_start", ",", "frequency", ",", "periods_between_starts", ",", "asset_lifetime", ")", ":", "return", "pd", ".", "DataFrame", "(", "{", "'symbol'", ":", "[", "chr", "(", "(", "ord", "(", "'A'", ...
create a dataframe representing lifetimes of assets that are constantly rotating in and out of existence .
train
true
28,814
def test_prepare_exec_for_file(test_apps): realpath = os.path.realpath('/tmp/share/test.py') dirname = os.path.dirname(realpath) assert (prepare_exec_for_file('/tmp/share/test.py') == 'test') assert (dirname in sys.path) realpath = os.path.realpath('/tmp/share/__init__.py') dirname = os.path.dirname(os.path.dirname(realpath)) assert (prepare_exec_for_file('/tmp/share/__init__.py') == 'share') assert (dirname in sys.path) with pytest.raises(NoAppException): prepare_exec_for_file('/tmp/share/test.txt')
[ "def", "test_prepare_exec_for_file", "(", "test_apps", ")", ":", "realpath", "=", "os", ".", "path", ".", "realpath", "(", "'/tmp/share/test.py'", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "realpath", ")", "assert", "(", "prepare_exec_for_fi...
expect the correct path to be set and the correct module name to be returned .
train
false
28,816
@login_required @require_http_methods(['POST']) def make_contributor(request): group = Group.objects.get(name=CONTRIBUTOR_GROUP) request.user.groups.add(group) @email_utils.safe_translation def _make_mail(locale): mail = email_utils.make_mail(subject=_('Welcome to SUMO!'), text_template='users/email/contributor.ltxt', html_template='users/email/contributor.html', context_vars={'contributor': request.user}, from_email=settings.DEFAULT_FROM_EMAIL, to_email=request.user.email) return mail email_utils.send_messages([_make_mail(request.LANGUAGE_CODE)]) if ('return_to' in request.POST): return HttpResponseRedirect(request.POST['return_to']) else: return HttpResponseRedirect(reverse('landings.get_involved'))
[ "@", "login_required", "@", "require_http_methods", "(", "[", "'POST'", "]", ")", "def", "make_contributor", "(", "request", ")", ":", "group", "=", "Group", ".", "objects", ".", "get", "(", "name", "=", "CONTRIBUTOR_GROUP", ")", "request", ".", "user", "....
adds the logged in user to the contributor group .
train
false
28,817
def clear_coefficients(expr, rhs=S.Zero): was = None free = expr.free_symbols if expr.is_Rational: return (S.Zero, (rhs - expr)) while (expr and (was != expr)): was = expr (m, expr) = (expr.as_content_primitive() if free else factor_terms(expr).as_coeff_Mul(rational=True)) rhs /= m (c, expr) = expr.as_coeff_Add(rational=True) rhs -= c expr = signsimp(expr, evaluate=False) if _coeff_isneg(expr): expr = (- expr) rhs = (- rhs) return (expr, rhs)
[ "def", "clear_coefficients", "(", "expr", ",", "rhs", "=", "S", ".", "Zero", ")", ":", "was", "=", "None", "free", "=", "expr", ".", "free_symbols", "if", "expr", ".", "is_Rational", ":", "return", "(", "S", ".", "Zero", ",", "(", "rhs", "-", "expr...
return p .
train
false
28,818
def impl_ret_borrowed(ctx, builder, retty, ret): if ctx.enable_nrt: ctx.nrt.incref(builder, retty, ret) return ret
[ "def", "impl_ret_borrowed", "(", "ctx", ",", "builder", ",", "retty", ",", "ret", ")", ":", "if", "ctx", ".", "enable_nrt", ":", "ctx", ".", "nrt", ".", "incref", "(", "builder", ",", "retty", ",", "ret", ")", "return", "ret" ]
the implementation returns a borrowed reference .
train
false
28,819
def addForeignKeys(cls, mapTables, ifNotExists=True): if (not filter(None, [col.foreignKey for col in cls._imdbpySchema.cols])): return fakeTableName = ('myfaketable%s' % cls.sqlmeta.table) if (fakeTableName in FAKE_TABLES_REPOSITORY): newcls = FAKE_TABLES_REPOSITORY[fakeTableName] else: newcls = _buildFakeFKTable(cls, fakeTableName) FAKE_TABLES_REPOSITORY[fakeTableName] = newcls newcls.setConnection(cls._connection) for col in cls._imdbpySchema.cols: if (col.name == 'id'): continue if (not col.foreignKey): continue fkQuery = newcls._connection.createReferenceConstraint(newcls, newcls.sqlmeta.columns[col.name]) if (not fkQuery): continue fkQuery = fkQuery.replace('myfaketable', '') newcls._connection.query(fkQuery) newcls._connection.close()
[ "def", "addForeignKeys", "(", "cls", ",", "mapTables", ",", "ifNotExists", "=", "True", ")", ":", "if", "(", "not", "filter", "(", "None", ",", "[", "col", ".", "foreignKey", "for", "col", "in", "cls", ".", "_imdbpySchema", ".", "cols", "]", ")", ")"...
create all required foreign keys .
train
false
28,820
def get_connected_xrandr_outputs(pl): return (match.groupdict() for match in XRANDR_OUTPUT_RE.finditer(run_cmd(pl, [u'xrandr', u'-q'])))
[ "def", "get_connected_xrandr_outputs", "(", "pl", ")", ":", "return", "(", "match", ".", "groupdict", "(", ")", "for", "match", "in", "XRANDR_OUTPUT_RE", ".", "finditer", "(", "run_cmd", "(", "pl", ",", "[", "u'xrandr'", ",", "u'-q'", "]", ")", ")", ")" ...
iterate over xrandr outputs outputs are represented by a dictionary with name .
train
false
28,821
@require_POST @ensure_csrf_cookie @cache_control(no_cache=True, no_store=True, must_revalidate=True) @require_level('staff') def list_background_email_tasks(request, course_id): course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) task_type = 'bulk_course_email' tasks = lms.djangoapps.instructor_task.api.get_instructor_task_history(course_id, task_type=task_type) response_payload = {'tasks': map(extract_task_features, tasks)} return JsonResponse(response_payload)
[ "@", "require_POST", "@", "ensure_csrf_cookie", "@", "cache_control", "(", "no_cache", "=", "True", ",", "no_store", "=", "True", ",", "must_revalidate", "=", "True", ")", "@", "require_level", "(", "'staff'", ")", "def", "list_background_email_tasks", "(", "req...
list background email tasks .
train
false
28,822
def register_actions(actions, parent_id=None): _populate_defaults() if (parent_id is None): parent = None else: try: parent = _all_actions[parent_id] except KeyError: raise KeyError((u'%s does not correspond to a registered review request action' % parent_id)) for action in reversed(actions): action.register(parent) if parent: parent.reset_max_depth()
[ "def", "register_actions", "(", "actions", ",", "parent_id", "=", "None", ")", ":", "_populate_defaults", "(", ")", "if", "(", "parent_id", "is", "None", ")", ":", "parent", "=", "None", "else", ":", "try", ":", "parent", "=", "_all_actions", "[", "paren...
register the given actions as children of the corresponding parent .
train
false
28,823
def get_indexable(percent=100, mapping_types=None): from kitsune.search.models import get_mapping_types mapping_types = get_mapping_types(mapping_types) to_index = [] percent = (float(percent) / 100) for cls in mapping_types: indexable = cls.get_indexable() if (percent < 1): indexable = indexable[:int((indexable.count() * percent))] to_index.append((cls, indexable)) return to_index
[ "def", "get_indexable", "(", "percent", "=", "100", ",", "mapping_types", "=", "None", ")", ":", "from", "kitsune", ".", "search", ".", "models", "import", "get_mapping_types", "mapping_types", "=", "get_mapping_types", "(", "mapping_types", ")", "to_index", "="...
returns a list of for all the things to index :arg percent: defaults to 100 .
train
false
28,824
def arma_periodogram(ar, ma, worN=None, whole=0): (w, h) = signal.freqd(ma, ar, worN=worN, whole=whole) sd = ((np.abs(h) ** 2) / np.sqrt((2 * np.pi))) if (np.sum(np.isnan(h)) > 0): print('Warning: nan in frequency response h, maybe a unit root') return (w, sd)
[ "def", "arma_periodogram", "(", "ar", ",", "ma", ",", "worN", "=", "None", ",", "whole", "=", "0", ")", ":", "(", "w", ",", "h", ")", "=", "signal", ".", "freqd", "(", "ma", ",", "ar", ",", "worN", "=", "worN", ",", "whole", "=", "whole", ")"...
periodogram for arma process given by lag-polynomials ar and ma parameters ar : array_like autoregressive lag-polynomial with leading 1 and lhs sign ma : array_like moving average lag-polynomial with leading 1 worn : {none .
train
false
28,825
def get_failed_queue(connection=None): return FailedQueue(connection=connection)
[ "def", "get_failed_queue", "(", "connection", "=", "None", ")", ":", "return", "FailedQueue", "(", "connection", "=", "connection", ")" ]
returns a handle to the special failed queue .
train
false
28,826
def getNewRepository(): return ExportRepository()
[ "def", "getNewRepository", "(", ")", ":", "return", "ExportRepository", "(", ")" ]
get the repository constructor .
train
false
28,827
def _unevaluated_Add(*args): args = list(args) newargs = [] co = S.Zero while args: a = args.pop() if a.is_Add: args.extend(a.args) elif a.is_Number: co += a else: newargs.append(a) _addsort(newargs) if co: newargs.insert(0, co) return Add._from_args(newargs)
[ "def", "_unevaluated_Add", "(", "*", "args", ")", ":", "args", "=", "list", "(", "args", ")", "newargs", "=", "[", "]", "co", "=", "S", ".", "Zero", "while", "args", ":", "a", "=", "args", ".", "pop", "(", ")", "if", "a", ".", "is_Add", ":", ...
return a well-formed unevaluated add: numbers are collected and put in slot 0 and args are sorted .
train
false
28,828
def ssh_usernames(vm_, opts, default_users=None): if (default_users is None): default_users = ['root'] usernames = salt.config.get_cloud_config_value('ssh_username', vm_, opts) if (not isinstance(usernames, list)): usernames = [usernames] usernames = [x for x in usernames if x] initial = usernames[:] for name in default_users: if (name not in usernames): usernames.append(name) usernames.extend(initial) return usernames
[ "def", "ssh_usernames", "(", "vm_", ",", "opts", ",", "default_users", "=", "None", ")", ":", "if", "(", "default_users", "is", "None", ")", ":", "default_users", "=", "[", "'root'", "]", "usernames", "=", "salt", ".", "config", ".", "get_cloud_config_valu...
return the ssh_usernames .
train
true
28,830
def partition_nodes(nodes): return [partition_node(node) for node in nodes]
[ "def", "partition_nodes", "(", "nodes", ")", ":", "return", "[", "partition_node", "(", "node", ")", "for", "node", "in", "nodes", "]" ]
translate from [host:port .
train
false
28,831
def linkify_escape(text): def linkify(match): return u'<a href="{0}">{0}</a>'.format(match.group(0)) return URL_RE.sub(linkify, unicode(jinja2.escape(text)))
[ "def", "linkify_escape", "(", "text", ")", ":", "def", "linkify", "(", "match", ")", ":", "return", "u'<a href=\"{0}\">{0}</a>'", ".", "format", "(", "match", ".", "group", "(", "0", ")", ")", "return", "URL_RE", ".", "sub", "(", "linkify", ",", "unicode...
linkifies plain text .
train
false
28,834
def test_pydotprint_profile(): if (not theano.printing.pydot_imported): raise SkipTest('pydot not available') A = tensor.matrix() prof = theano.compile.ProfileStats(atexit_print=False) f = theano.function([A], (A + 1), profile=prof) theano.printing.pydotprint(f, print_output_file=False) f([[1]]) theano.printing.pydotprint(f, print_output_file=False)
[ "def", "test_pydotprint_profile", "(", ")", ":", "if", "(", "not", "theano", ".", "printing", ".", "pydot_imported", ")", ":", "raise", "SkipTest", "(", "'pydot not available'", ")", "A", "=", "tensor", ".", "matrix", "(", ")", "prof", "=", "theano", ".", ...
just check that pydotprint does not crash with profile .
train
false
28,835
def test_merge_with_weird_eq(): x = T.constant(numpy.asarray(1), name='x') y = T.constant(numpy.asarray(1), name='y') g = Env([x, y], [(x + y)]) MergeOptimizer().optimize(g) assert (len(g.apply_nodes) == 1) node = list(g.apply_nodes)[0] assert (len(node.inputs) == 2) assert (node.inputs[0] is node.inputs[1]) x = T.constant(numpy.ones(5), name='x') y = T.constant(numpy.ones(5), name='y') g = Env([x, y], [(x + y)]) MergeOptimizer().optimize(g) assert (len(g.apply_nodes) == 1) node = list(g.apply_nodes)[0] assert (len(node.inputs) == 2) assert (node.inputs[0] is node.inputs[1])
[ "def", "test_merge_with_weird_eq", "(", ")", ":", "x", "=", "T", ".", "constant", "(", "numpy", ".", "asarray", "(", "1", ")", ",", "name", "=", "'x'", ")", "y", "=", "T", ".", "constant", "(", "numpy", ".", "asarray", "(", "1", ")", ",", "name",...
numpy arrays dont compare equal like other python objects .
train
false
28,837
def returns_typeclass(method): def func(self, *args, **kwargs): self.__doc__ = method.__doc__ query = method(self, *args, **kwargs) if hasattr(query, '__iter__'): result = list(query) return (result[0] if result else None) else: return query return update_wrapper(func, method)
[ "def", "returns_typeclass", "(", "method", ")", ":", "def", "func", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "self", ".", "__doc__", "=", "method", ".", "__doc__", "query", "=", "method", "(", "self", ",", "*", "args", ",", "**...
decorator: returns a single typeclass match or none .
train
false
28,839
def test_value_error_if_key_missing_in_context(replay_test_dir, template_name): with pytest.raises(ValueError): replay.dump(replay_test_dir, template_name, {'foo': 'bar'})
[ "def", "test_value_error_if_key_missing_in_context", "(", "replay_test_dir", ",", "template_name", ")", ":", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "replay", ".", "dump", "(", "replay_test_dir", ",", "template_name", ",", "{", "'foo'", ":", ...
test that replay .
train
false
28,840
def aggregate_metadata_get_by_host(context, host, key=None): return IMPL.aggregate_metadata_get_by_host(context, host, key)
[ "def", "aggregate_metadata_get_by_host", "(", "context", ",", "host", ",", "key", "=", "None", ")", ":", "return", "IMPL", ".", "aggregate_metadata_get_by_host", "(", "context", ",", "host", ",", "key", ")" ]
returns a dict of all metadata based on a metadata key for a specific host .
train
false
28,841
def build_sequential(): data = {'di': seqblock(0, [bool(x) for x in range(1, 100)]), 'ci': seqblock(0, [bool((not x)) for x in range(1, 100)]), 'hr': seqblock(0, [int(x) for x in range(1, 100)]), 'ir': seqblock(0, [int((2 * x)) for x in range(1, 100)])} return data
[ "def", "build_sequential", "(", ")", ":", "data", "=", "{", "'di'", ":", "seqblock", "(", "0", ",", "[", "bool", "(", "x", ")", "for", "x", "in", "range", "(", "1", ",", "100", ")", "]", ")", ",", "'ci'", ":", "seqblock", "(", "0", ",", "[", ...
this builds a quick mock sequential datastore with 100 values for each discrete .
train
false
28,842
def in6_issladdr(str): return in6_isincluded(str, 'fec0::', 10)
[ "def", "in6_issladdr", "(", "str", ")", ":", "return", "in6_isincluded", "(", "str", ",", "'fec0::'", ",", "10", ")" ]
returns true if provided address in printable format belongs to _allocated_ site-local address space .
train
false
28,844
def iter_platform_files(dst): for (root, dirs, files) in os.walk(dst): for fn in files: fn = os.path.join(root, fn) if is_platform_file(fn): (yield fn)
[ "def", "iter_platform_files", "(", "dst", ")", ":", "for", "(", "root", ",", "dirs", ",", "files", ")", "in", "os", ".", "walk", "(", "dst", ")", ":", "for", "fn", "in", "files", ":", "fn", "=", "os", ".", "path", ".", "join", "(", "root", ",",...
walk a directory and yield each full path that is a mach-o file .
train
true
28,845
def _clear_datastore_storage(datastore_path): if os.path.lexists(datastore_path): try: os.remove(datastore_path) except OSError as e: logging.warning('Failed to remove datastore file %r: %s', datastore_path, e)
[ "def", "_clear_datastore_storage", "(", "datastore_path", ")", ":", "if", "os", ".", "path", ".", "lexists", "(", "datastore_path", ")", ":", "try", ":", "os", ".", "remove", "(", "datastore_path", ")", "except", "OSError", "as", "e", ":", "logging", ".", ...
delete the datastore storage file at the given path .
train
false
28,847
def getHachoirOptions(parser): def setLogFilename(*args): log.setFilename(args[2]) common = OptionGroup(parser, _('Hachoir library'), 'Configure Hachoir library') common.add_option('--verbose', help=_('Verbose mode'), default=False, action='store_true') common.add_option('--log', help=_('Write log in a file'), type='string', action='callback', callback=setLogFilename) common.add_option('--quiet', help=_("Quiet mode (don't display warning)"), default=False, action='store_true') common.add_option('--debug', help=_('Debug mode'), default=False, action='store_true') return common
[ "def", "getHachoirOptions", "(", "parser", ")", ":", "def", "setLogFilename", "(", "*", "args", ")", ":", "log", ".", "setFilename", "(", "args", "[", "2", "]", ")", "common", "=", "OptionGroup", "(", "parser", ",", "_", "(", "'Hachoir library'", ")", ...
create an option group of hachoir library options .
train
false
28,848
def parse_remainder(arguments): return ' '.join(arguments)
[ "def", "parse_remainder", "(", "arguments", ")", ":", "return", "' '", ".", "join", "(", "arguments", ")" ]
merge list of "remainder arguments" into a single command string .
train
false
28,849
def local_nvra(module, path): ts = rpm.TransactionSet() ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) fd = os.open(path, os.O_RDONLY) try: header = ts.hdrFromFdno(fd) finally: os.close(fd) return ('%s-%s-%s.%s' % (header[rpm.RPMTAG_NAME], header[rpm.RPMTAG_VERSION], header[rpm.RPMTAG_RELEASE], header[rpm.RPMTAG_ARCH]))
[ "def", "local_nvra", "(", "module", ",", "path", ")", ":", "ts", "=", "rpm", ".", "TransactionSet", "(", ")", "ts", ".", "setVSFlags", "(", "rpm", ".", "_RPMVSF_NOSIGNATURES", ")", "fd", "=", "os", ".", "open", "(", "path", ",", "os", ".", "O_RDONLY"...
return nvra of a local rpm passed in .
train
false
28,850
def raiser(*args, **kwargs): raise RaisedArguments(args, kwargs)
[ "def", "raiser", "(", "*", "args", ",", "**", "kwargs", ")", ":", "raise", "RaisedArguments", "(", "args", ",", "kwargs", ")" ]
raise a l{raisedarguments} exception containing the supplied arguments .
train
false
28,852
def semantic(request): create_fake_data() table = SemanticTable(Person.objects.all(), order_by='-name') RequestConfig(request, paginate={'per_page': 10}).configure(table) return render(request, 'semantic_template.html', {'table': table})
[ "def", "semantic", "(", "request", ")", ":", "create_fake_data", "(", ")", "table", "=", "SemanticTable", "(", "Person", ".", "objects", ".", "all", "(", ")", ",", "order_by", "=", "'-name'", ")", "RequestConfig", "(", "request", ",", "paginate", "=", "{...
demonstrate the use of the semantic ui template .
train
false
28,853
def floating_ip_count_by_project(context, project_id, session=None): return IMPL.floating_ip_count_by_project(context, project_id, session=session)
[ "def", "floating_ip_count_by_project", "(", "context", ",", "project_id", ",", "session", "=", "None", ")", ":", "return", "IMPL", ".", "floating_ip_count_by_project", "(", "context", ",", "project_id", ",", "session", "=", "session", ")" ]
count floating ips used by project .
train
false
28,854
def _resolve_link(path): paths_seen = set() while islink(path): if (path in paths_seen): return None paths_seen.add(path) resolved = os.readlink(path) if (not isabs(resolved)): dir = dirname(path) path = normpath(join(dir, resolved)) else: path = normpath(resolved) return path
[ "def", "_resolve_link", "(", "path", ")", ":", "paths_seen", "=", "set", "(", ")", "while", "islink", "(", "path", ")", ":", "if", "(", "path", "in", "paths_seen", ")", ":", "return", "None", "paths_seen", ".", "add", "(", "path", ")", "resolved", "=...
internal helper function .
train
false
28,855
def get_free_namespace_port(protocol, namespace=None, start=1024, end=None): if (protocol == n_const.PROTO_NAME_TCP): param = '-tna' elif (protocol == n_const.PROTO_NAME_UDP): param = '-una' else: raise ValueError(('Unsupported protocol %s' % protocol)) ip_wrapper = ip_lib.IPWrapper(namespace=namespace) output = ip_wrapper.netns.execute(['ss', param]) used_ports = _get_source_ports_from_ss_output(output) return get_unused_port(used_ports, start, end)
[ "def", "get_free_namespace_port", "(", "protocol", ",", "namespace", "=", "None", ",", "start", "=", "1024", ",", "end", "=", "None", ")", ":", "if", "(", "protocol", "==", "n_const", ".", "PROTO_NAME_TCP", ")", ":", "param", "=", "'-tna'", "elif", "(", ...
return an unused port from given namespace warning: this function returns a port that is free at the execution time of this function .
train
false
28,856
def bridge_has_instance_port(bridge): is_instance_port = (lambda p: (not is_trunk_service_port(p))) return bridge_has_port(bridge, is_instance_port)
[ "def", "bridge_has_instance_port", "(", "bridge", ")", ":", "is_instance_port", "=", "(", "lambda", "p", ":", "(", "not", "is_trunk_service_port", "(", "p", ")", ")", ")", "return", "bridge_has_port", "(", "bridge", ",", "is_instance_port", ")" ]
true if there is an ovs port that doesnt have bridge or patch ports prefix .
train
false
28,857
def conv2d_bn(x, nb_filter, nb_row, nb_col, border_mode='same', subsample=(1, 1), name=None): if (name is not None): bn_name = (name + '_bn') conv_name = (name + '_conv') else: bn_name = None conv_name = None if (K.image_dim_ordering() == 'th'): bn_axis = 1 else: bn_axis = 3 x = Convolution2D(nb_filter, nb_row, nb_col, subsample=subsample, activation='relu', border_mode=border_mode, name=conv_name)(x) x = BatchNormalization(axis=bn_axis, name=bn_name)(x) return x
[ "def", "conv2d_bn", "(", "x", ",", "nb_filter", ",", "nb_row", ",", "nb_col", ",", "border_mode", "=", "'same'", ",", "subsample", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ")", ":", "if", "(", "name", "is", "not", "None", ")", ":",...
utility function to apply conv + bn .
train
false
28,860
def _api_addurl(names, output, kwargs): pp = kwargs.get('pp') script = kwargs.get('script') cat = kwargs.get('cat') priority = kwargs.get('priority') nzbnames = kwargs.get('nzbname') if (not isinstance(names, list)): names = [names] if (not isinstance(nzbnames, list)): nzbnames = [nzbnames] nzo_ids = [] for n in xrange(len(names)): name = names[n] if (n < len(nzbnames)): nzbname = nzbnames[n] else: nzbname = '' if name: name = name.strip() if name: nzo_ids.append(sabnzbd.add_url(name, pp, script, cat, priority, nzbname)) if (len(names) > 0): return report(output, keyword='', data={'status': True, 'nzo_ids': nzo_ids}, compat=True) else: logging.info('API-call addurl: no files retrieved from %s', names) return report(output, _MSG_NO_VALUE)
[ "def", "_api_addurl", "(", "names", ",", "output", ",", "kwargs", ")", ":", "pp", "=", "kwargs", ".", "get", "(", "'pp'", ")", "script", "=", "kwargs", ".", "get", "(", "'script'", ")", "cat", "=", "kwargs", ".", "get", "(", "'cat'", ")", "priority...
api: accepts name .
train
false
28,861
def get_thumbnail(file_, geometry_string, **options): return default.backend.get_thumbnail(file_, geometry_string, **options)
[ "def", "get_thumbnail", "(", "file_", ",", "geometry_string", ",", "**", "options", ")", ":", "return", "default", ".", "backend", ".", "get_thumbnail", "(", "file_", ",", "geometry_string", ",", "**", "options", ")" ]
a shortcut for the backend get_thumbnail method .
train
true
28,862
def has_target(alias, target): if (target == ''): raise SaltInvocationError('target can not be an empty string') aliases = list_aliases() if (alias not in aliases): return False if isinstance(target, list): target = ', '.join(target) return (target == aliases[alias])
[ "def", "has_target", "(", "alias", ",", "target", ")", ":", "if", "(", "target", "==", "''", ")", ":", "raise", "SaltInvocationError", "(", "'target can not be an empty string'", ")", "aliases", "=", "list_aliases", "(", ")", "if", "(", "alias", "not", "in",...
return true if the alias/target is set cli example: .
train
true
28,863
def build_or_install_bokehjs(): if ('--existing-js' in sys.argv): sys.argv.remove('--existing-js') return 'packaged' if (('--build-js' not in sys.argv) and ('--install-js' not in sys.argv)): jsbuild = jsbuild_prompt() elif ('--build-js' in sys.argv): jsbuild = True sys.argv.remove('--build-js') else: jsbuild = False sys.argv.remove('--install-js') jsbuild_ok = ('install', 'develop', 'sdist', 'egg_info', 'build') if (jsbuild and (not any(((arg in sys.argv) for arg in jsbuild_ok)))): print("Error: Option '--build-js' only valid with 'install', 'develop', 'sdist', or 'build', exiting.") sys.exit(1) if jsbuild: build_js() install_js() return 'built' else: install_js() return 'installed'
[ "def", "build_or_install_bokehjs", "(", ")", ":", "if", "(", "'--existing-js'", "in", "sys", ".", "argv", ")", ":", "sys", ".", "argv", ".", "remove", "(", "'--existing-js'", ")", "return", "'packaged'", "if", "(", "(", "'--build-js'", "not", "in", "sys", ...
build a new bokehjs or install a previously build bokehjs .
train
true
28,864
def _normalizeHostname(domain): def convertLabel(label): if _isASCII(label): return label.lower() return encodings.idna.ToASCII(label) return '.'.join(map(convertLabel, domain.split('.')))
[ "def", "_normalizeHostname", "(", "domain", ")", ":", "def", "convertLabel", "(", "label", ")", ":", "if", "_isASCII", "(", "label", ")", ":", "return", "label", ".", "lower", "(", ")", "return", "encodings", ".", "idna", ".", "ToASCII", "(", "label", ...
normalizes the given domain .
train
false
28,865
def infer_getattr(self, context=None): for owner in self.expr.infer(context): if (owner is YES): (yield owner) continue try: context.boundnode = owner for obj in owner.igetattr(self.attrname, context): (yield obj) context.boundnode = None except (NotFoundError, InferenceError): context.boundnode = None except AttributeError: context.boundnode = None
[ "def", "infer_getattr", "(", "self", ",", "context", "=", "None", ")", ":", "for", "owner", "in", "self", ".", "expr", ".", "infer", "(", "context", ")", ":", "if", "(", "owner", "is", "YES", ")", ":", "(", "yield", "owner", ")", "continue", "try",...
infer a getattr node by using getattr on the associated object .
train
false
28,866
def getNumsFromBytes(bytes, bitsPerComponent=8): if (not isinstance(bytes, str)): return ((-1), 'bytes must be a string') if (not isinstance(bitsPerComponent, int)): return ((-1), 'bitsPerComponent must be an integer') outputComponents = [] bitsStream = '' for byte in bytes: try: bitsRepresentation = bin(ord(byte)) bitsRepresentation = bitsRepresentation.replace('0b', '') bitsRepresentation = (('0' * (8 - len(bitsRepresentation))) + bitsRepresentation) bitsStream += bitsRepresentation except: return ((-1), 'Error in conversion from bytes to bits') try: for i in range(0, len(bitsStream), bitsPerComponent): bytes = '' bits = bitsStream[i:(i + bitsPerComponent)] num = int(bits, 2) outputComponents.append(num) except: return ((-1), 'Error in conversion from bits to bytes') return (0, outputComponents)
[ "def", "getNumsFromBytes", "(", "bytes", ",", "bitsPerComponent", "=", "8", ")", ":", "if", "(", "not", "isinstance", "(", "bytes", ",", "str", ")", ")", ":", "return", "(", "(", "-", "1", ")", ",", "'bytes must be a string'", ")", "if", "(", "not", ...
makes the conversion between bytes and numbers .
train
false
28,867
def has_data_for_dates(series_or_df, first_date, last_date): dts = series_or_df.index if (not isinstance(dts, pd.DatetimeIndex)): raise TypeError(('Expected a DatetimeIndex, but got %s.' % type(dts))) (first, last) = dts[[0, (-1)]] return ((first <= first_date) and (last >= last_date))
[ "def", "has_data_for_dates", "(", "series_or_df", ",", "first_date", ",", "last_date", ")", ":", "dts", "=", "series_or_df", ".", "index", "if", "(", "not", "isinstance", "(", "dts", ",", "pd", ".", "DatetimeIndex", ")", ")", ":", "raise", "TypeError", "("...
does series_or_df have data on or before first_date and on or after last_date? .
train
true
28,868
def convert_basic(txt, title='', epub_split_size_kb=0): txt = clean_txt(txt) txt = split_txt(txt, epub_split_size_kb) lines = [] blank_count = 0 for line in txt.split('\n'): if line.strip(): blank_count = 0 lines.append((u'<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' ')))) else: blank_count += 1 if (blank_count == 2): lines.append(u'<p>&nbsp;</p>') return (HTML_TEMPLATE % (title, u'\n'.join(lines)))
[ "def", "convert_basic", "(", "txt", ",", "title", "=", "''", ",", "epub_split_size_kb", "=", "0", ")", ":", "txt", "=", "clean_txt", "(", "txt", ")", "txt", "=", "split_txt", "(", "txt", ",", "epub_split_size_kb", ")", "lines", "=", "[", "]", "blank_co...
converts plain text to html by putting all paragraphs in <p> tags .
train
false
28,869
def hvals(key, host=None, port=None, db=None, password=None): server = _connect(host, port, db, password) return server.hvals(key)
[ "def", "hvals", "(", "key", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ")", "return", "serve...
return all the values in a hash .
train
true
28,870
def show_by_id(show_id, session=None): return session.query(Series).filter((Series.id == show_id)).one()
[ "def", "show_by_id", "(", "show_id", ",", "session", "=", "None", ")", ":", "return", "session", ".", "query", "(", "Series", ")", ".", "filter", "(", "(", "Series", ".", "id", "==", "show_id", ")", ")", ".", "one", "(", ")" ]
return an instance of a show by querying its id .
train
false
28,871
def normalize_percent_characters(s): matches = set(PERCENT_MATCHER.findall(s)) for m in matches: if (not m.isupper()): s = s.replace(m, m.upper()) return s
[ "def", "normalize_percent_characters", "(", "s", ")", ":", "matches", "=", "set", "(", "PERCENT_MATCHER", ".", "findall", "(", "s", ")", ")", "for", "m", "in", "matches", ":", "if", "(", "not", "m", ".", "isupper", "(", ")", ")", ":", "s", "=", "s"...
all percent characters should be upper-cased .
train
false
28,873
def unbound_cache(func): cache = {} @wraps(func) def caching_wrapper(*args): try: return cache[args] except KeyError: result = func(*args) cache[args] = result return result return caching_wrapper
[ "def", "unbound_cache", "(", "func", ")", ":", "cache", "=", "{", "}", "@", "wraps", "(", "func", ")", "def", "caching_wrapper", "(", "*", "args", ")", ":", "try", ":", "return", "cache", "[", "args", "]", "except", "KeyError", ":", "result", "=", ...
caching decorator with an unbounded cache size .
train
false
28,874
@requires_mayavi def test_check_mayavi(): assert_raises(RuntimeError, _check_mayavi_version, '100.0.0')
[ "@", "requires_mayavi", "def", "test_check_mayavi", "(", ")", ":", "assert_raises", "(", "RuntimeError", ",", "_check_mayavi_version", ",", "'100.0.0'", ")" ]
test mayavi version check .
train
false
28,875
def authn_statement(authn_class=None, authn_auth=None, authn_decl=None, authn_decl_ref=None, authn_instant='', subject_locality=''): if authn_instant: _instant = instant(time_stamp=authn_instant) else: _instant = instant() if authn_class: res = factory(saml.AuthnStatement, authn_instant=_instant, session_index=sid(), authn_context=_authn_context_class_ref(authn_class, authn_auth)) elif authn_decl: res = factory(saml.AuthnStatement, authn_instant=_instant, session_index=sid(), authn_context=_authn_context_decl(authn_decl, authn_auth)) elif authn_decl_ref: res = factory(saml.AuthnStatement, authn_instant=_instant, session_index=sid(), authn_context=_authn_context_decl_ref(authn_decl_ref, authn_auth)) else: res = factory(saml.AuthnStatement, authn_instant=_instant, session_index=sid()) if subject_locality: res.subject_locality = saml.SubjectLocality(text=subject_locality) return res
[ "def", "authn_statement", "(", "authn_class", "=", "None", ",", "authn_auth", "=", "None", ",", "authn_decl", "=", "None", ",", "authn_decl_ref", "=", "None", ",", "authn_instant", "=", "''", ",", "subject_locality", "=", "''", ")", ":", "if", "authn_instant...
construct the authnstatement .
train
true
28,876
def mw_snippet(server, query): snippet_url = ((u'https://' + server) + u'/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&exchars=300&redirects&titles=') snippet_url += query snippet = json.loads(web.get(snippet_url)) snippet = snippet[u'query'][u'pages'] snippet = snippet[list(snippet.keys())[0]] return snippet[u'extract']
[ "def", "mw_snippet", "(", "server", ",", "query", ")", ":", "snippet_url", "=", "(", "(", "u'https://'", "+", "server", ")", "+", "u'/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&exchars=300&redirects&titles='", ")", "snippet_url", "+=", "query", "...
retrives a snippet of the specified length from the given page on the given server .
train
false
28,877
def getGitVersion(tagPrefix): path = os.getcwd() if (not os.path.isdir(os.path.join(path, '.git'))): return None v = check_output(['git', 'describe', '--tags', '--dirty', ('--match=%s*' % tagPrefix)]).strip().decode('utf-8') assert v.startswith(tagPrefix) v = v[len(tagPrefix):] parts = v.split('-') modified = False if (parts[(-1)] == 'dirty'): modified = True parts = parts[:(-1)] local = None if ((len(parts) > 2) and re.match('\\d+', parts[(-2)]) and re.match('g[0-9a-f]{7}', parts[(-1)])): local = parts[(-1)] parts = parts[:(-2)] gitVersion = '-'.join(parts) if (local is not None): gitVersion += ('+' + local) if modified: gitVersion += 'm' return gitVersion
[ "def", "getGitVersion", "(", "tagPrefix", ")", ":", "path", "=", "os", ".", "getcwd", "(", ")", "if", "(", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'.git'", ")", ")", ")", ":", "return", "N...
return a version string with information about this git checkout .
train
false
28,878
def call_unrar(params, custom_path=None): global rar_executable_cached if (rar_executable_cached is None): for command in (custom_path, 'unrar', 'rar', osx_unrar): if (not command): continue try: subprocess.Popen([command], stdout=subprocess.PIPE) rar_executable_cached = command break except OSError: pass if (rar_executable_cached is None): raise UnpackerNotInstalled('No suitable RAR unpacker installed') assert (type(params) == list), 'params must be list' args = ([rar_executable_cached] + params) try: gc.disable() return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) finally: gc.enable()
[ "def", "call_unrar", "(", "params", ",", "custom_path", "=", "None", ")", ":", "global", "rar_executable_cached", "if", "(", "rar_executable_cached", "is", "None", ")", ":", "for", "command", "in", "(", "custom_path", ",", "'unrar'", ",", "'rar'", ",", "osx_...
calls rar/unrar command line executable .
train
true
28,879
@decorators.memoize def _cmd(): rcctl = salt.utils.which('rcctl') if (not rcctl): raise CommandNotFoundError return rcctl
[ "@", "decorators", ".", "memoize", "def", "_cmd", "(", ")", ":", "rcctl", "=", "salt", ".", "utils", ".", "which", "(", "'rcctl'", ")", "if", "(", "not", "rcctl", ")", ":", "raise", "CommandNotFoundError", "return", "rcctl" ]
return the full path to the rcctl(8) command .
train
false
28,880
def after_scenario(context, _): if (hasattr(context, u'cli') and (not context.exit_sent)): context.cli.terminate()
[ "def", "after_scenario", "(", "context", ",", "_", ")", ":", "if", "(", "hasattr", "(", "context", ",", "u'cli'", ")", "and", "(", "not", "context", ".", "exit_sent", ")", ")", ":", "context", ".", "cli", ".", "terminate", "(", ")" ]
cleans up after each test complete .
train
false
28,882
def read_chunk(fp): chunk = [] lines = [] while 1: line = fp.readline() if (not line): break if (line == sep1): if lines: chunk.append(lines) break if (line == sep2): if lines: chunk.append(lines) lines = [] else: lines.append(line) return chunk
[ "def", "read_chunk", "(", "fp", ")", ":", "chunk", "=", "[", "]", "lines", "=", "[", "]", "while", "1", ":", "line", "=", "fp", ".", "readline", "(", ")", "if", "(", "not", "line", ")", ":", "break", "if", "(", "line", "==", "sep1", ")", ":",...
read a chunk -- data for one file .
train
false
28,884
def _super_pprint(obj, p, cycle): p.begin_group(8, '<super: ') p.pretty(obj.__thisclass__) p.text(',') p.breakable() if PYPY: dself = obj.__repr__.__self__ p.pretty((None if (dself is obj) else dself)) else: p.pretty(obj.__self__) p.end_group(8, '>')
[ "def", "_super_pprint", "(", "obj", ",", "p", ",", "cycle", ")", ":", "p", ".", "begin_group", "(", "8", ",", "'<super: '", ")", "p", ".", "pretty", "(", "obj", ".", "__thisclass__", ")", "p", ".", "text", "(", "','", ")", "p", ".", "breakable", ...
the pprint for the super type .
train
false
28,885
def add_node(workflow, name, node_type, parents, attrs={}): NodeClass = NODE_TYPES[node_type] node = NodeClass(workflow=workflow, node_type=node_type, name=name) for attr in attrs: setattr(node, attr, attrs[attr]) node.save() if parents: for parent in parents: name = 'ok' if ((parent.node_type == 'start') or (parent.node_type == 'join')): name = 'to' elif ((parent.node_type == 'fork') or (parent.node_type == 'decision')): name = 'start' link = Link(parent=parent, child=node, name=name) link.save() if ((node_type != 'fork') and (node_type != 'decision') and (node_type != 'join')): link = Link(parent=node, child=Kill.objects.get(name='kill', workflow=workflow), name='error') link.save() return node
[ "def", "add_node", "(", "workflow", ",", "name", ",", "node_type", ",", "parents", ",", "attrs", "=", "{", "}", ")", ":", "NodeClass", "=", "NODE_TYPES", "[", "node_type", "]", "node", "=", "NodeClass", "(", "workflow", "=", "workflow", ",", "node_type",...
create a node of type node_type and associate the listed parents .
train
false
28,886
def list_themes(v=False): for (t, l) in themes(): if (not v): t = os.path.basename(t) if l: if v: print((t + ((u' (symbolic link to `' + l) + u"')"))) else: print((t + u'@')) else: print(t)
[ "def", "list_themes", "(", "v", "=", "False", ")", ":", "for", "(", "t", ",", "l", ")", "in", "themes", "(", ")", ":", "if", "(", "not", "v", ")", ":", "t", "=", "os", ".", "path", ".", "basename", "(", "t", ")", "if", "l", ":", "if", "v"...
lists all installed themes .
train
false
28,887
def dmp_factor_list_include(f, u, K): if (not u): return dup_factor_list_include(f, K) (coeff, factors) = dmp_factor_list(f, u, K) if (not factors): return [(dmp_ground(coeff, u), 1)] else: g = dmp_mul_ground(factors[0][0], coeff, u, K) return ([(g, factors[0][1])] + factors[1:])
[ "def", "dmp_factor_list_include", "(", "f", ",", "u", ",", "K", ")", ":", "if", "(", "not", "u", ")", ":", "return", "dup_factor_list_include", "(", "f", ",", "K", ")", "(", "coeff", ",", "factors", ")", "=", "dmp_factor_list", "(", "f", ",", "u", ...
factor polynomials into irreducibles in k[x] .
train
false
28,888
def test_function_series3(): class mytanh(Function, ): def fdiff(self, argindex=1): return (1 - (mytanh(self.args[0]) ** 2)) @classmethod def eval(cls, arg): arg = sympify(arg) if (arg == 0): return sympify(0) e = tanh(x) f = mytanh(x) assert (tanh(x).series(x, 0, 6) == mytanh(x).series(x, 0, 6))
[ "def", "test_function_series3", "(", ")", ":", "class", "mytanh", "(", "Function", ",", ")", ":", "def", "fdiff", "(", "self", ",", "argindex", "=", "1", ")", ":", "return", "(", "1", "-", "(", "mytanh", "(", "self", ".", "args", "[", "0", "]", "...
test our easy "tanh" function .
train
false
28,891
def _fix2comp(num): assert (0 <= num < (2 ** 32)) if (num & (2 ** 31)): return (num - (2 ** 32)) else: return num
[ "def", "_fix2comp", "(", "num", ")", ":", "assert", "(", "0", "<=", "num", "<", "(", "2", "**", "32", ")", ")", "if", "(", "num", "&", "(", "2", "**", "31", ")", ")", ":", "return", "(", "num", "-", "(", "2", "**", "32", ")", ")", "else",...
convert from twos complement to negative .
train
false
28,892
def check_and_join(phrase, symbols=None, filter=None): rv = ''.join(''.join(phrase)) if (symbols is not None): symbols = check_and_join(symbols) missing = ''.join(list(sorted((set(rv) - set(symbols))))) if missing: if (not filter): raise ValueError(('characters in phrase but not symbols: "%s"' % missing)) rv = translate(rv, None, missing) return rv
[ "def", "check_and_join", "(", "phrase", ",", "symbols", "=", "None", ",", "filter", "=", "None", ")", ":", "rv", "=", "''", ".", "join", "(", "''", ".", "join", "(", "phrase", ")", ")", "if", "(", "symbols", "is", "not", "None", ")", ":", "symbol...
joins characters of phrase and if symbols is given .
train
false
28,893
def dblog(msg, module): return insert('INSERT INTO log VALUES (?,?,?)', (module, _timestamp(), msg.rstrip()))
[ "def", "dblog", "(", "msg", ",", "module", ")", ":", "return", "insert", "(", "'INSERT INTO log VALUES (?,?,?)'", ",", "(", "module", ",", "_timestamp", "(", ")", ",", "msg", ".", "rstrip", "(", ")", ")", ")" ]
insert a log event .
train
false
28,895
def simple_import(s): parts = s.split('.') module = import_module(parts[0]) name = parts[0] parts = parts[1:] last_import_error = None while parts: name += ('.' + parts[0]) try: module = import_module(name) parts = parts[1:] except ImportError as e: last_import_error = e break obj = module while parts: try: obj = getattr(module, parts[0]) except AttributeError: raise ImportError(('Cannot find %s in module %r (stopped importing modules with error %s)' % (parts[0], module, last_import_error))) parts = parts[1:] return obj
[ "def", "simple_import", "(", "s", ")", ":", "parts", "=", "s", ".", "split", "(", "'.'", ")", "module", "=", "import_module", "(", "parts", "[", "0", "]", ")", "name", "=", "parts", "[", "0", "]", "parts", "=", "parts", "[", "1", ":", "]", "las...
import a module .
train
false
28,897
def format_by_pattern(numobj, number_format, user_defined_formats): country_code = numobj.country_code nsn = national_significant_number(numobj) if (not _has_valid_country_calling_code(country_code)): return nsn region_code = region_code_for_country_code(country_code) metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) formatted_number = U_EMPTY_STRING formatting_pattern = _choose_formatting_pattern_for_number(user_defined_formats, nsn) if (formatting_pattern is None): formatted_number = nsn else: num_format_copy = _copy_number_format(formatting_pattern) np_formatting_rule = formatting_pattern.national_prefix_formatting_rule if np_formatting_rule: national_prefix = metadata.national_prefix if national_prefix: np_formatting_rule = re.sub(_NP_PATTERN, national_prefix, np_formatting_rule, count=1) np_formatting_rule = re.sub(_FG_PATTERN, unicod('\\\\1'), np_formatting_rule, count=1) num_format_copy.national_prefix_formatting_rule = np_formatting_rule else: num_format_copy.national_prefix_formatting_rule = None formatted_number = _format_nsn_using_pattern(nsn, num_format_copy, number_format) formatted_number = _maybe_append_formatted_extension(numobj, metadata, number_format, formatted_number) formatted_number = _prefix_number_with_country_calling_code(country_code, number_format, formatted_number) return formatted_number
[ "def", "format_by_pattern", "(", "numobj", ",", "number_format", ",", "user_defined_formats", ")", ":", "country_code", "=", "numobj", ".", "country_code", "nsn", "=", "national_significant_number", "(", "numobj", ")", "if", "(", "not", "_has_valid_country_calling_cod...
formats a phone number using client-defined formatting rules .
train
false
28,898
def sanitize_text(text, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X'): if isinstance(text, list): return [sanitize_text(x, valid_characters=valid_characters, character_map=character_map, invalid_character=invalid_character) for x in text] if (not isinstance(text, string_types)): text = smart_str(text) return _sanitize_text_helper(text, valid_characters=valid_characters, character_map=character_map)
[ "def", "sanitize_text", "(", "text", ",", "valid_characters", "=", "valid_chars", ",", "character_map", "=", "mapped_chars", ",", "invalid_character", "=", "'X'", ")", ":", "if", "isinstance", "(", "text", ",", "list", ")", ":", "return", "[", "sanitize_text",...
restricts the characters that are allowed in text; accepts both strings and lists of strings; non-string entities will be cast to strings .
train
false
28,900
def _translate_detail_keys(cons): pool = cons['pool'] info = {'id': cons['id'], 'console_type': pool['console_type'], 'password': cons['password'], 'instance_name': cons['instance_name'], 'port': cons['port'], 'host': pool['public_hostname']} return dict(console=info)
[ "def", "_translate_detail_keys", "(", "cons", ")", ":", "pool", "=", "cons", "[", "'pool'", "]", "info", "=", "{", "'id'", ":", "cons", "[", "'id'", "]", ",", "'console_type'", ":", "pool", "[", "'console_type'", "]", ",", "'password'", ":", "cons", "[...
coerces a console instance into proper dictionary format with detail .
train
false
28,901
def _register_review_uis(**kwargs): from reviewboard.reviews.ui.base import register_ui from reviewboard.reviews.ui.image import ImageReviewUI from reviewboard.reviews.ui.markdownui import MarkdownReviewUI from reviewboard.reviews.ui.text import TextBasedReviewUI register_ui(ImageReviewUI) register_ui(MarkdownReviewUI) register_ui(TextBasedReviewUI)
[ "def", "_register_review_uis", "(", "**", "kwargs", ")", ":", "from", "reviewboard", ".", "reviews", ".", "ui", ".", "base", "import", "register_ui", "from", "reviewboard", ".", "reviews", ".", "ui", ".", "image", "import", "ImageReviewUI", "from", "reviewboar...
registers all bundled review uis .
train
false
28,902
def gist(id_num): return gh.gist(id_num)
[ "def", "gist", "(", "id_num", ")", ":", "return", "gh", ".", "gist", "(", "id_num", ")" ]
render gist script .
train
false
28,904
def _align_method_SERIES(left, right, align_asobject=False): if isinstance(right, ABCSeries): if (not left.index.equals(right.index)): if align_asobject: left = left.astype(object) right = right.astype(object) (left, right) = left.align(right, copy=False) return (left, right)
[ "def", "_align_method_SERIES", "(", "left", ",", "right", ",", "align_asobject", "=", "False", ")", ":", "if", "isinstance", "(", "right", ",", "ABCSeries", ")", ":", "if", "(", "not", "left", ".", "index", ".", "equals", "(", "right", ".", "index", ")...
align lhs and rhs series .
train
true
28,905
def libvlc_media_player_get_length(p_mi): f = (_Cfunctions.get('libvlc_media_player_get_length', None) or _Cfunction('libvlc_media_player_get_length', ((1,),), None, ctypes.c_longlong, MediaPlayer)) return f(p_mi)
[ "def", "libvlc_media_player_get_length", "(", "p_mi", ")", ":", "f", "=", "(", "_Cfunctions", ".", "get", "(", "'libvlc_media_player_get_length'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_player_get_length'", ",", "(", "(", "1", ",", ")", ",", ...
get the current movie length .
train
true
28,908
def _read_sites(handle): alphabet = dna instances = [] for line in handle: if (not line.startswith('>')): break line = next(handle) instance = '' for c in line.strip(): if (c == c.upper()): instance += c instance = Seq(instance, alphabet) instances.append(instance) instances = motifs.Instances(instances, alphabet) motif = Motif(matrix_id=None, name=None, alphabet=alphabet, instances=instances) motif.mask = ('*' * motif.length) record = Record() record.append(motif) return record
[ "def", "_read_sites", "(", "handle", ")", ":", "alphabet", "=", "dna", "instances", "=", "[", "]", "for", "line", "in", "handle", ":", "if", "(", "not", "line", ".", "startswith", "(", "'>'", ")", ")", ":", "break", "line", "=", "next", "(", "handl...
read the motif from jaspar .
train
false
28,909
def flatten_errors(cfg, res, levels=None, results=None): if (levels is None): levels = [] results = [] if (res == True): return results if ((res == False) or isinstance(res, Exception)): results.append((levels[:], None, res)) if levels: levels.pop() return results for (key, val) in res.items(): if (val == True): continue if isinstance(cfg.get(key), dict): levels.append(key) flatten_errors(cfg[key], val, levels, results) continue results.append((levels[:], key, val)) if levels: levels.pop() return results
[ "def", "flatten_errors", "(", "cfg", ",", "res", ",", "levels", "=", "None", ",", "results", "=", "None", ")", ":", "if", "(", "levels", "is", "None", ")", ":", "levels", "=", "[", "]", "results", "=", "[", "]", "if", "(", "res", "==", "True", ...
an example function that will turn a nested dictionary of results into a flat list .
train
true
28,910
def compare_versions(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False): cmp_map = {'<': ((-1),), '<=': ((-1), 0), '==': (0,), '>=': (0, 1), '>': (1,)} if ((oper not in ('!=',)) and (oper not in cmp_map)): log.error("Invalid operator '%s' for version comparison", oper) return False if (cmp_func is None): cmp_func = version_cmp cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch) if (cmp_result is None): return False if (not isinstance(cmp_result, numbers.Integral)): log.error('The version comparison function did not return an integer/long.') return False if (oper == '!='): return (cmp_result not in cmp_map['==']) else: if (cmp_result < (-1)): cmp_result = (-1) elif (cmp_result > 1): cmp_result = 1 return (cmp_result in cmp_map[oper])
[ "def", "compare_versions", "(", "ver1", "=", "''", ",", "oper", "=", "'=='", ",", "ver2", "=", "''", ",", "cmp_func", "=", "None", ",", "ignore_epoch", "=", "False", ")", ":", "cmp_map", "=", "{", "'<'", ":", "(", "(", "-", "1", ")", ",", ")", ...
return true if a is greater than or equal to b .
train
true
28,911
def ci_to_errsize(cis, heights): cis = np.atleast_2d(cis).reshape(2, (-1)) heights = np.atleast_1d(heights) errsize = [] for (i, (low, high)) in enumerate(np.transpose(cis)): h = heights[i] elow = (h - low) ehigh = (high - h) errsize.append([elow, ehigh]) errsize = np.asarray(errsize).T return errsize
[ "def", "ci_to_errsize", "(", "cis", ",", "heights", ")", ":", "cis", "=", "np", ".", "atleast_2d", "(", "cis", ")", ".", "reshape", "(", "2", ",", "(", "-", "1", ")", ")", "heights", "=", "np", ".", "atleast_1d", "(", "heights", ")", "errsize", "...
convert intervals to error arguments relative to plot heights .
train
false
28,912
def pix2deg(pixels, monitor, correctFlat=False): scrWidthCm = monitor.getWidth() scrSizePix = monitor.getSizePix() if (scrSizePix is None): msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)' raise ValueError((msg % monitor.name)) if (scrWidthCm is None): msg = 'Monitor %s has no known width in cm (SEE MONITOR CENTER)' raise ValueError((msg % monitor.name)) cmSize = ((pixels * float(scrWidthCm)) / scrSizePix[0]) return cm2deg(cmSize, monitor, correctFlat)
[ "def", "pix2deg", "(", "pixels", ",", "monitor", ",", "correctFlat", "=", "False", ")", ":", "scrWidthCm", "=", "monitor", ".", "getWidth", "(", ")", "scrSizePix", "=", "monitor", ".", "getSizePix", "(", ")", "if", "(", "scrSizePix", "is", "None", ")", ...
convert size in pixels to size in degrees for a given monitor object .
train
false
28,913
def evalNQueens(individual): size = len(individual) left_diagonal = ([0] * ((2 * size) - 1)) right_diagonal = ([0] * ((2 * size) - 1)) for i in range(size): left_diagonal[(i + individual[i])] += 1 right_diagonal[(((size - 1) - i) + individual[i])] += 1 sum_ = 0 for i in range(((2 * size) - 1)): if (left_diagonal[i] > 1): sum_ += (left_diagonal[i] - 1) if (right_diagonal[i] > 1): sum_ += (right_diagonal[i] - 1) return (sum_,)
[ "def", "evalNQueens", "(", "individual", ")", ":", "size", "=", "len", "(", "individual", ")", "left_diagonal", "=", "(", "[", "0", "]", "*", "(", "(", "2", "*", "size", ")", "-", "1", ")", ")", "right_diagonal", "=", "(", "[", "0", "]", "*", "...
evaluation function for the n-queens problem .
train
false
28,914
def _cloned_intersection(a, b): all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b)) return set((elem for elem in a if all_overlap.intersection(elem._cloned_set)))
[ "def", "_cloned_intersection", "(", "a", ",", "b", ")", ":", "all_overlap", "=", "set", "(", "_expand_cloned", "(", "a", ")", ")", ".", "intersection", "(", "_expand_cloned", "(", "b", ")", ")", "return", "set", "(", "(", "elem", "for", "elem", "in", ...
return the intersection of sets a and b .
train
false