id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
24,307 | def to_lowercase(path):
_RE_LOWERCASE = re.compile('{([^{]*)}')
while True:
m = _RE_LOWERCASE.search(path)
if (not m):
break
path = ((path[:m.start()] + m.group(1).lower()) + path[m.end():])
path = path.replace('{', '')
path = path.replace('}', '')
return path
| [
"def",
"to_lowercase",
"(",
"path",
")",
":",
"_RE_LOWERCASE",
"=",
"re",
".",
"compile",
"(",
"'{([^{]*)}'",
")",
"while",
"True",
":",
"m",
"=",
"_RE_LOWERCASE",
".",
"search",
"(",
"path",
")",
"if",
"(",
"not",
"m",
")",
":",
"break",
"path",
"=",
"(",
"(",
"path",
"[",
":",
"m",
".",
"start",
"(",
")",
"]",
"+",
"m",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
")",
"+",
"path",
"[",
"m",
".",
"end",
"(",
")",
":",
"]",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"'{'",
",",
"''",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"'}'",
",",
"''",
")",
"return",
"path"
] | lowercases any characters enclosed in {} . | train | false |
24,308 | def camelcase(text):
return (text[0] + ''.join(text.title().split('_'))[1:])
| [
"def",
"camelcase",
"(",
"text",
")",
":",
"return",
"(",
"text",
"[",
"0",
"]",
"+",
"''",
".",
"join",
"(",
"text",
".",
"title",
"(",
")",
".",
"split",
"(",
"'_'",
")",
")",
"[",
"1",
":",
"]",
")"
] | converts text that may be underscored into a camelcase format . | train | false |
24,309 | def get_all_from_queue(Q):
try:
while True:
(yield Q.get_nowait())
except Queue.Empty:
raise StopIteration
| [
"def",
"get_all_from_queue",
"(",
"Q",
")",
":",
"try",
":",
"while",
"True",
":",
"(",
"yield",
"Q",
".",
"get_nowait",
"(",
")",
")",
"except",
"Queue",
".",
"Empty",
":",
"raise",
"StopIteration"
] | generator to yield one after the others all items currently in the queue q . | train | false |
24,310 | @task(queue='web')
def remove_path_from_web(path):
assert (' ' not in path), 'No spaces allowed in path'
run_on_app_servers('rm -rf {path}'.format(path=path))
| [
"@",
"task",
"(",
"queue",
"=",
"'web'",
")",
"def",
"remove_path_from_web",
"(",
"path",
")",
":",
"assert",
"(",
"' '",
"not",
"in",
"path",
")",
",",
"'No spaces allowed in path'",
"run_on_app_servers",
"(",
"'rm -rf {path}'",
".",
"format",
"(",
"path",
"=",
"path",
")",
")"
] | remove the given path from the web servers file system . | train | false |
24,311 | def make_seeded_random_loader(seed, dates, sids):
return SeededRandomLoader(seed, TestingDataSet.columns, dates, sids)
| [
"def",
"make_seeded_random_loader",
"(",
"seed",
",",
"dates",
",",
"sids",
")",
":",
"return",
"SeededRandomLoader",
"(",
"seed",
",",
"TestingDataSet",
".",
"columns",
",",
"dates",
",",
"sids",
")"
] | make a pipelineloader that emits random arrays seeded with seed for the columns in testingdataset . | train | false |
24,312 | def export_date_time(format):
def export_date_time_lambda(value):
if (not value):
return ''
return datetime.datetime.strftime(value, format)
return export_date_time_lambda
| [
"def",
"export_date_time",
"(",
"format",
")",
":",
"def",
"export_date_time_lambda",
"(",
"value",
")",
":",
"if",
"(",
"not",
"value",
")",
":",
"return",
"''",
"return",
"datetime",
".",
"datetime",
".",
"strftime",
"(",
"value",
",",
"format",
")",
"return",
"export_date_time_lambda"
] | a wrapper around strftime . | train | false |
24,313 | def write_seqs_to_fastq(fp, seqs, write_mode='w'):
with open(fp, write_mode) as f:
for s in seqs:
f.write(format_fastq_record(s[0], s[1], s[3]))
| [
"def",
"write_seqs_to_fastq",
"(",
"fp",
",",
"seqs",
",",
"write_mode",
"=",
"'w'",
")",
":",
"with",
"open",
"(",
"fp",
",",
"write_mode",
")",
"as",
"f",
":",
"for",
"s",
"in",
"seqs",
":",
"f",
".",
"write",
"(",
"format_fastq_record",
"(",
"s",
"[",
"0",
"]",
",",
"s",
"[",
"1",
"]",
",",
"s",
"[",
"3",
"]",
")",
")"
] | write seqs to fp with specified write mode seqs: list of tuples . | train | false |
24,315 | def add_shortcut_to_tooltip(action, context, name):
action.setToolTip((action.toolTip() + (' (%s)' % get_shortcut(context=context, name=name))))
| [
"def",
"add_shortcut_to_tooltip",
"(",
"action",
",",
"context",
",",
"name",
")",
":",
"action",
".",
"setToolTip",
"(",
"(",
"action",
".",
"toolTip",
"(",
")",
"+",
"(",
"' (%s)'",
"%",
"get_shortcut",
"(",
"context",
"=",
"context",
",",
"name",
"=",
"name",
")",
")",
")",
")"
] | add the shortcut associated with a given action to its tooltip . | train | true |
24,316 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | initialise module . | train | false |
24,317 | def use_read_replica_if_available(queryset):
return (queryset.using('read_replica') if ('read_replica' in settings.DATABASES) else queryset)
| [
"def",
"use_read_replica_if_available",
"(",
"queryset",
")",
":",
"return",
"(",
"queryset",
".",
"using",
"(",
"'read_replica'",
")",
"if",
"(",
"'read_replica'",
"in",
"settings",
".",
"DATABASES",
")",
"else",
"queryset",
")"
] | if there is a database called read_replica . | train | false |
24,318 | def test_brainvision_data_software_filters_latin1_global_units():
with warnings.catch_warnings(record=True) as w:
raw = _test_raw_reader(read_raw_brainvision, vhdr_fname=vhdr_old_path, eog=('VEOGo', 'VEOGu', 'HEOGli', 'HEOGre'), misc=('A2',))
assert_true(all((('software filter detected' in str(ww.message)) for ww in w)))
assert_equal(raw.info['highpass'], (1.0 / 0.9))
assert_equal(raw.info['lowpass'], 50.0)
| [
"def",
"test_brainvision_data_software_filters_latin1_global_units",
"(",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
"as",
"w",
":",
"raw",
"=",
"_test_raw_reader",
"(",
"read_raw_brainvision",
",",
"vhdr_fname",
"=",
"vhdr_old_path",
",",
"eog",
"=",
"(",
"'VEOGo'",
",",
"'VEOGu'",
",",
"'HEOGli'",
",",
"'HEOGre'",
")",
",",
"misc",
"=",
"(",
"'A2'",
",",
")",
")",
"assert_true",
"(",
"all",
"(",
"(",
"(",
"'software filter detected'",
"in",
"str",
"(",
"ww",
".",
"message",
")",
")",
"for",
"ww",
"in",
"w",
")",
")",
")",
"assert_equal",
"(",
"raw",
".",
"info",
"[",
"'highpass'",
"]",
",",
"(",
"1.0",
"/",
"0.9",
")",
")",
"assert_equal",
"(",
"raw",
".",
"info",
"[",
"'lowpass'",
"]",
",",
"50.0",
")"
] | test reading raw brain vision files . | train | false |
24,319 | def get_file_gid(path):
return os.stat(path).st_gid
| [
"def",
"get_file_gid",
"(",
"path",
")",
":",
"return",
"os",
".",
"stat",
"(",
"path",
")",
".",
"st_gid"
] | this primarily exists to make unit testing easier . | train | false |
24,320 | def report_memory(i=0):
from matplotlib.compat.subprocess import Popen, PIPE
pid = os.getpid()
if (sys.platform == u'sunos5'):
try:
a2 = Popen((str(u'ps -p %d -o osz') % pid), shell=True, stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(u"report_memory works on Sun OS only if the 'ps' program is found")
mem = int(a2[(-1)].strip())
elif sys.platform.startswith(u'linux'):
try:
a2 = Popen((str(u'ps -p %d -o rss,sz') % pid), shell=True, stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(u"report_memory works on Linux only if the 'ps' program is found")
mem = int(a2[1].split()[1])
elif sys.platform.startswith(u'darwin'):
try:
a2 = Popen((str(u'ps -p %d -o rss,vsz') % pid), shell=True, stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(u"report_memory works on Mac OS only if the 'ps' program is found")
mem = int(a2[1].split()[0])
elif sys.platform.startswith(u'win'):
try:
a2 = Popen([str(u'tasklist'), u'/nh', u'/fi', (u'pid eq %d' % pid)], stdout=PIPE).stdout.read()
except OSError:
raise NotImplementedError(u"report_memory works on Windows only if the 'tasklist' program is found")
mem = int(a2.strip().split()[(-2)].replace(u',', u''))
else:
raise NotImplementedError((u"We don't have a memory monitor for %s" % sys.platform))
return mem
| [
"def",
"report_memory",
"(",
"i",
"=",
"0",
")",
":",
"from",
"matplotlib",
".",
"compat",
".",
"subprocess",
"import",
"Popen",
",",
"PIPE",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"if",
"(",
"sys",
".",
"platform",
"==",
"u'sunos5'",
")",
":",
"try",
":",
"a2",
"=",
"Popen",
"(",
"(",
"str",
"(",
"u'ps -p %d -o osz'",
")",
"%",
"pid",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
")",
".",
"stdout",
".",
"readlines",
"(",
")",
"except",
"OSError",
":",
"raise",
"NotImplementedError",
"(",
"u\"report_memory works on Sun OS only if the 'ps' program is found\"",
")",
"mem",
"=",
"int",
"(",
"a2",
"[",
"(",
"-",
"1",
")",
"]",
".",
"strip",
"(",
")",
")",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"u'linux'",
")",
":",
"try",
":",
"a2",
"=",
"Popen",
"(",
"(",
"str",
"(",
"u'ps -p %d -o rss,sz'",
")",
"%",
"pid",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
")",
".",
"stdout",
".",
"readlines",
"(",
")",
"except",
"OSError",
":",
"raise",
"NotImplementedError",
"(",
"u\"report_memory works on Linux only if the 'ps' program is found\"",
")",
"mem",
"=",
"int",
"(",
"a2",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"1",
"]",
")",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"u'darwin'",
")",
":",
"try",
":",
"a2",
"=",
"Popen",
"(",
"(",
"str",
"(",
"u'ps -p %d -o rss,vsz'",
")",
"%",
"pid",
")",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"PIPE",
")",
".",
"stdout",
".",
"readlines",
"(",
")",
"except",
"OSError",
":",
"raise",
"NotImplementedError",
"(",
"u\"report_memory works on Mac OS only if the 'ps' program is found\"",
")",
"mem",
"=",
"int",
"(",
"a2",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"0",
"]",
")",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"u'win'",
")",
":",
"try",
":",
"a2",
"=",
"Popen",
"(",
"[",
"str",
"(",
"u'tasklist'",
")",
",",
"u'/nh'",
",",
"u'/fi'",
",",
"(",
"u'pid eq %d'",
"%",
"pid",
")",
"]",
",",
"stdout",
"=",
"PIPE",
")",
".",
"stdout",
".",
"read",
"(",
")",
"except",
"OSError",
":",
"raise",
"NotImplementedError",
"(",
"u\"report_memory works on Windows only if the 'tasklist' program is found\"",
")",
"mem",
"=",
"int",
"(",
"a2",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
"(",
"-",
"2",
")",
"]",
".",
"replace",
"(",
"u','",
",",
"u''",
")",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"(",
"u\"We don't have a memory monitor for %s\"",
"%",
"sys",
".",
"platform",
")",
")",
"return",
"mem"
] | return the memory consumed by process . | train | false |
24,321 | @app.route('/forms/post')
def view_forms_post():
return render_template('forms-post.html')
| [
"@",
"app",
".",
"route",
"(",
"'/forms/post'",
")",
"def",
"view_forms_post",
"(",
")",
":",
"return",
"render_template",
"(",
"'forms-post.html'",
")"
] | simple html form . | train | false |
24,322 | def stripquotes(s):
s = s.replace('"', '')
s = s.replace("'", '')
return s
| [
"def",
"stripquotes",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
"s",
"=",
"s",
".",
"replace",
"(",
"\"'\"",
",",
"''",
")",
"return",
"s"
] | replace explicit quotes in a string . | train | false |
24,323 | def check_size(path, size):
free = get_free_space(path)
if (free < size):
raise CondaIOError('Not enough space in {}'.format(path))
| [
"def",
"check_size",
"(",
"path",
",",
"size",
")",
":",
"free",
"=",
"get_free_space",
"(",
"path",
")",
"if",
"(",
"free",
"<",
"size",
")",
":",
"raise",
"CondaIOError",
"(",
"'Not enough space in {}'",
".",
"format",
"(",
"path",
")",
")"
] | check whether the directory has enough space . | train | false |
24,324 | def challb_to_achall(challb, account_key, domain):
chall = challb.chall
logger.info('%s challenge for %s', chall.typ, domain)
if isinstance(chall, challenges.KeyAuthorizationChallenge):
return achallenges.KeyAuthorizationAnnotatedChallenge(challb=challb, domain=domain, account_key=account_key)
elif isinstance(chall, challenges.DNS):
return achallenges.DNS(challb=challb, domain=domain)
else:
raise errors.Error('Received unsupported challenge of type: %s', chall.typ)
| [
"def",
"challb_to_achall",
"(",
"challb",
",",
"account_key",
",",
"domain",
")",
":",
"chall",
"=",
"challb",
".",
"chall",
"logger",
".",
"info",
"(",
"'%s challenge for %s'",
",",
"chall",
".",
"typ",
",",
"domain",
")",
"if",
"isinstance",
"(",
"chall",
",",
"challenges",
".",
"KeyAuthorizationChallenge",
")",
":",
"return",
"achallenges",
".",
"KeyAuthorizationAnnotatedChallenge",
"(",
"challb",
"=",
"challb",
",",
"domain",
"=",
"domain",
",",
"account_key",
"=",
"account_key",
")",
"elif",
"isinstance",
"(",
"chall",
",",
"challenges",
".",
"DNS",
")",
":",
"return",
"achallenges",
".",
"DNS",
"(",
"challb",
"=",
"challb",
",",
"domain",
"=",
"domain",
")",
"else",
":",
"raise",
"errors",
".",
"Error",
"(",
"'Received unsupported challenge of type: %s'",
",",
"chall",
".",
"typ",
")"
] | converts a challengebody object to an annotatedchallenge . | train | false |
24,325 | def get_list_or_404(klass, *args, **kwargs):
queryset = _get_queryset(klass)
try:
obj_list = list(queryset.filter(*args, **kwargs))
except AttributeError:
klass__name = (klass.__name__ if isinstance(klass, type) else klass.__class__.__name__)
raise ValueError(("First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not '%s'." % klass__name))
if (not obj_list):
raise Http404(('No %s matches the given query.' % queryset.model._meta.object_name))
return obj_list
| [
"def",
"get_list_or_404",
"(",
"klass",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"queryset",
"=",
"_get_queryset",
"(",
"klass",
")",
"try",
":",
"obj_list",
"=",
"list",
"(",
"queryset",
".",
"filter",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
"except",
"AttributeError",
":",
"klass__name",
"=",
"(",
"klass",
".",
"__name__",
"if",
"isinstance",
"(",
"klass",
",",
"type",
")",
"else",
"klass",
".",
"__class__",
".",
"__name__",
")",
"raise",
"ValueError",
"(",
"(",
"\"First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not '%s'.\"",
"%",
"klass__name",
")",
")",
"if",
"(",
"not",
"obj_list",
")",
":",
"raise",
"Http404",
"(",
"(",
"'No %s matches the given query.'",
"%",
"queryset",
".",
"model",
".",
"_meta",
".",
"object_name",
")",
")",
"return",
"obj_list"
] | uses filter() to return a list of objects . | train | false |
24,327 | def regex_select(env=None, app=None, request=None):
if app:
THREAD_LOCAL.routes = params_apps.get(app, params)
elif (env and params.routes_app):
if routers:
map_url_in(request, env, app=True)
else:
app = regex_uri(env, params.routes_app, 'routes_app')
THREAD_LOCAL.routes = params_apps.get(app, params)
else:
THREAD_LOCAL.routes = params
log_rewrite(('select routing parameters: %s' % THREAD_LOCAL.routes.name))
return app
| [
"def",
"regex_select",
"(",
"env",
"=",
"None",
",",
"app",
"=",
"None",
",",
"request",
"=",
"None",
")",
":",
"if",
"app",
":",
"THREAD_LOCAL",
".",
"routes",
"=",
"params_apps",
".",
"get",
"(",
"app",
",",
"params",
")",
"elif",
"(",
"env",
"and",
"params",
".",
"routes_app",
")",
":",
"if",
"routers",
":",
"map_url_in",
"(",
"request",
",",
"env",
",",
"app",
"=",
"True",
")",
"else",
":",
"app",
"=",
"regex_uri",
"(",
"env",
",",
"params",
".",
"routes_app",
",",
"'routes_app'",
")",
"THREAD_LOCAL",
".",
"routes",
"=",
"params_apps",
".",
"get",
"(",
"app",
",",
"params",
")",
"else",
":",
"THREAD_LOCAL",
".",
"routes",
"=",
"params",
"log_rewrite",
"(",
"(",
"'select routing parameters: %s'",
"%",
"THREAD_LOCAL",
".",
"routes",
".",
"name",
")",
")",
"return",
"app"
] | selects a set of regex rewrite params for the current request . | train | false |
24,328 | def mungeQA(html, type, fields, model, data, col):
for match in regexps['standard'].finditer(html):
html = html.replace(match.group(), _imgLink(col, match.group(1), model))
for match in regexps['expression'].finditer(html):
html = html.replace(match.group(), _imgLink(col, (('$' + match.group(1)) + '$'), model))
for match in regexps['math'].finditer(html):
html = html.replace(match.group(), _imgLink(col, (('\\begin{displaymath}' + match.group(1)) + '\\end{displaymath}'), model))
return html
| [
"def",
"mungeQA",
"(",
"html",
",",
"type",
",",
"fields",
",",
"model",
",",
"data",
",",
"col",
")",
":",
"for",
"match",
"in",
"regexps",
"[",
"'standard'",
"]",
".",
"finditer",
"(",
"html",
")",
":",
"html",
"=",
"html",
".",
"replace",
"(",
"match",
".",
"group",
"(",
")",
",",
"_imgLink",
"(",
"col",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"model",
")",
")",
"for",
"match",
"in",
"regexps",
"[",
"'expression'",
"]",
".",
"finditer",
"(",
"html",
")",
":",
"html",
"=",
"html",
".",
"replace",
"(",
"match",
".",
"group",
"(",
")",
",",
"_imgLink",
"(",
"col",
",",
"(",
"(",
"'$'",
"+",
"match",
".",
"group",
"(",
"1",
")",
")",
"+",
"'$'",
")",
",",
"model",
")",
")",
"for",
"match",
"in",
"regexps",
"[",
"'math'",
"]",
".",
"finditer",
"(",
"html",
")",
":",
"html",
"=",
"html",
".",
"replace",
"(",
"match",
".",
"group",
"(",
")",
",",
"_imgLink",
"(",
"col",
",",
"(",
"(",
"'\\\\begin{displaymath}'",
"+",
"match",
".",
"group",
"(",
"1",
")",
")",
"+",
"'\\\\end{displaymath}'",
")",
",",
"model",
")",
")",
"return",
"html"
] | convert text with embedded latex tags to image links . | train | false |
24,329 | def prepare_cell(argname='cut', target='cell', restrict=False):
converters = {'time': CalendarMemberConverter(workspace.calendar)}
cuts = []
for cut_string in request.args.getlist(argname):
cuts += cuts_from_string(g.cube, cut_string, role_member_converters=converters)
if cuts:
cell = Cell(g.cube, cuts)
else:
cell = None
if restrict:
if workspace.authorizer:
cell = workspace.authorizer.restricted_cell(g.auth_identity, cube=g.cube, cell=cell)
setattr(g, target, cell)
| [
"def",
"prepare_cell",
"(",
"argname",
"=",
"'cut'",
",",
"target",
"=",
"'cell'",
",",
"restrict",
"=",
"False",
")",
":",
"converters",
"=",
"{",
"'time'",
":",
"CalendarMemberConverter",
"(",
"workspace",
".",
"calendar",
")",
"}",
"cuts",
"=",
"[",
"]",
"for",
"cut_string",
"in",
"request",
".",
"args",
".",
"getlist",
"(",
"argname",
")",
":",
"cuts",
"+=",
"cuts_from_string",
"(",
"g",
".",
"cube",
",",
"cut_string",
",",
"role_member_converters",
"=",
"converters",
")",
"if",
"cuts",
":",
"cell",
"=",
"Cell",
"(",
"g",
".",
"cube",
",",
"cuts",
")",
"else",
":",
"cell",
"=",
"None",
"if",
"restrict",
":",
"if",
"workspace",
".",
"authorizer",
":",
"cell",
"=",
"workspace",
".",
"authorizer",
".",
"restricted_cell",
"(",
"g",
".",
"auth_identity",
",",
"cube",
"=",
"g",
".",
"cube",
",",
"cell",
"=",
"cell",
")",
"setattr",
"(",
"g",
",",
"target",
",",
"cell",
")"
] | sets g . | train | false |
24,330 | def _color_to_rgb(color, input):
if (input == 'hls'):
color = colorsys.hls_to_rgb(*color)
elif (input == 'husl'):
color = husl.husl_to_rgb(*color)
elif (input == 'xkcd'):
color = xkcd_rgb[color]
return color
| [
"def",
"_color_to_rgb",
"(",
"color",
",",
"input",
")",
":",
"if",
"(",
"input",
"==",
"'hls'",
")",
":",
"color",
"=",
"colorsys",
".",
"hls_to_rgb",
"(",
"*",
"color",
")",
"elif",
"(",
"input",
"==",
"'husl'",
")",
":",
"color",
"=",
"husl",
".",
"husl_to_rgb",
"(",
"*",
"color",
")",
"elif",
"(",
"input",
"==",
"'xkcd'",
")",
":",
"color",
"=",
"xkcd_rgb",
"[",
"color",
"]",
"return",
"color"
] | add some more flexibility to color choices . | train | false |
24,331 | def GetFullURL(server_name, server_port, relative_url):
if (str(server_port) != '80'):
netloc = ('%s:%s' % (server_name, server_port))
else:
netloc = server_name
return ('http://%s%s' % (netloc, relative_url))
| [
"def",
"GetFullURL",
"(",
"server_name",
",",
"server_port",
",",
"relative_url",
")",
":",
"if",
"(",
"str",
"(",
"server_port",
")",
"!=",
"'80'",
")",
":",
"netloc",
"=",
"(",
"'%s:%s'",
"%",
"(",
"server_name",
",",
"server_port",
")",
")",
"else",
":",
"netloc",
"=",
"server_name",
"return",
"(",
"'http://%s%s'",
"%",
"(",
"netloc",
",",
"relative_url",
")",
")"
] | returns the full . | train | false |
24,332 | def test_tl_fit_single_class():
tl = TomekLinks(random_state=RND_SEED)
y_single_class = np.zeros((X.shape[0],))
assert_warns(UserWarning, tl.fit, X, y_single_class)
| [
"def",
"test_tl_fit_single_class",
"(",
")",
":",
"tl",
"=",
"TomekLinks",
"(",
"random_state",
"=",
"RND_SEED",
")",
"y_single_class",
"=",
"np",
".",
"zeros",
"(",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
")",
")",
"assert_warns",
"(",
"UserWarning",
",",
"tl",
".",
"fit",
",",
"X",
",",
"y_single_class",
")"
] | test either if an error when there is a single class . | train | false |
24,334 | def compiles(class_, *specs):
def decorate(fn):
existing = class_.__dict__.get('_compiler_dispatcher', None)
existing_dispatch = class_.__dict__.get('_compiler_dispatch')
if (not existing):
existing = _dispatcher()
if existing_dispatch:
existing.specs['default'] = existing_dispatch
setattr(class_, '_compiler_dispatch', (lambda *arg, **kw: existing(*arg, **kw)))
setattr(class_, '_compiler_dispatcher', existing)
if specs:
for s in specs:
existing.specs[s] = fn
else:
existing.specs['default'] = fn
return fn
return decorate
| [
"def",
"compiles",
"(",
"class_",
",",
"*",
"specs",
")",
":",
"def",
"decorate",
"(",
"fn",
")",
":",
"existing",
"=",
"class_",
".",
"__dict__",
".",
"get",
"(",
"'_compiler_dispatcher'",
",",
"None",
")",
"existing_dispatch",
"=",
"class_",
".",
"__dict__",
".",
"get",
"(",
"'_compiler_dispatch'",
")",
"if",
"(",
"not",
"existing",
")",
":",
"existing",
"=",
"_dispatcher",
"(",
")",
"if",
"existing_dispatch",
":",
"existing",
".",
"specs",
"[",
"'default'",
"]",
"=",
"existing_dispatch",
"setattr",
"(",
"class_",
",",
"'_compiler_dispatch'",
",",
"(",
"lambda",
"*",
"arg",
",",
"**",
"kw",
":",
"existing",
"(",
"*",
"arg",
",",
"**",
"kw",
")",
")",
")",
"setattr",
"(",
"class_",
",",
"'_compiler_dispatcher'",
",",
"existing",
")",
"if",
"specs",
":",
"for",
"s",
"in",
"specs",
":",
"existing",
".",
"specs",
"[",
"s",
"]",
"=",
"fn",
"else",
":",
"existing",
".",
"specs",
"[",
"'default'",
"]",
"=",
"fn",
"return",
"fn",
"return",
"decorate"
] | register a function as a compiler for a given :class: . | train | false |
24,335 | def urlget(url, *args, **kwargs):
data = kwargs.pop('data', None)
exception = kwargs.pop('exception', PluginError)
method = kwargs.pop('method', 'GET')
session = kwargs.pop('session', None)
timeout = kwargs.pop('timeout', 20)
if (data is not None):
method = 'POST'
try:
if session:
res = session.request(method, url, timeout=timeout, data=data, *args, **kwargs)
else:
res = requests.request(method, url, timeout=timeout, data=data, *args, **kwargs)
res.raise_for_status()
except (requests.exceptions.RequestException, IOError) as rerr:
err = exception('Unable to open URL: {url} ({err})'.format(url=url, err=rerr))
err.err = rerr
raise err
return res
| [
"def",
"urlget",
"(",
"url",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
".",
"pop",
"(",
"'data'",
",",
"None",
")",
"exception",
"=",
"kwargs",
".",
"pop",
"(",
"'exception'",
",",
"PluginError",
")",
"method",
"=",
"kwargs",
".",
"pop",
"(",
"'method'",
",",
"'GET'",
")",
"session",
"=",
"kwargs",
".",
"pop",
"(",
"'session'",
",",
"None",
")",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"20",
")",
"if",
"(",
"data",
"is",
"not",
"None",
")",
":",
"method",
"=",
"'POST'",
"try",
":",
"if",
"session",
":",
"res",
"=",
"session",
".",
"request",
"(",
"method",
",",
"url",
",",
"timeout",
"=",
"timeout",
",",
"data",
"=",
"data",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"else",
":",
"res",
"=",
"requests",
".",
"request",
"(",
"method",
",",
"url",
",",
"timeout",
"=",
"timeout",
",",
"data",
"=",
"data",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"res",
".",
"raise_for_status",
"(",
")",
"except",
"(",
"requests",
".",
"exceptions",
".",
"RequestException",
",",
"IOError",
")",
"as",
"rerr",
":",
"err",
"=",
"exception",
"(",
"'Unable to open URL: {url} ({err})'",
".",
"format",
"(",
"url",
"=",
"url",
",",
"err",
"=",
"rerr",
")",
")",
"err",
".",
"err",
"=",
"rerr",
"raise",
"err",
"return",
"res"
] | this function is deprecated . | train | false |
24,336 | @register(u'kill-word')
def kill_word(event):
buff = event.current_buffer
pos = buff.document.find_next_word_ending(count=event.arg)
if pos:
deleted = buff.delete(count=pos)
event.cli.clipboard.set_text(deleted)
| [
"@",
"register",
"(",
"u'kill-word'",
")",
"def",
"kill_word",
"(",
"event",
")",
":",
"buff",
"=",
"event",
".",
"current_buffer",
"pos",
"=",
"buff",
".",
"document",
".",
"find_next_word_ending",
"(",
"count",
"=",
"event",
".",
"arg",
")",
"if",
"pos",
":",
"deleted",
"=",
"buff",
".",
"delete",
"(",
"count",
"=",
"pos",
")",
"event",
".",
"cli",
".",
"clipboard",
".",
"set_text",
"(",
"deleted",
")"
] | kill from point to the end of the current word . | train | true |
24,338 | def ExecuteTest():
app_id = GetApplicationId(_SCHEME['ios'])
test_name = options.testname
if test_name:
Setup(test_name)
test_dir = ('%s/results/current/%s/%s' % (_BASE_PATH, options.conf, test_name))
os.makedirs(test_dir, 493)
instrument_cmd = ('instruments -t templates/VF_AutoUI_Template.tracetemplate /Users/%s/Library/Application\\ Support/iPhone\\ Simulator/%s/Applications/%s/Viewfinder.app -e UIASCRIPT js/control/%s_control.js -e UIARESULTSPATH %s' % (os.environ['USER'], _SCHEME['ios'], app_id, test_name, test_dir))
print instrument_cmd
call(instrument_cmd, shell=True)
Teardown(test_name)
else:
for temp_name in _SUMMARY.keys():
Setup('all')
test_dir = ('%s/results/current/%s/%s' % (_BASE_PATH, options.conf, temp_name))
os.makedirs(test_dir, 493)
instrument_cmd = ('instruments -t templates/VF_AutoUI_Template.tracetemplate /Users/%s/Library/Application\\ Support/iPhone\\ Simulator/%s/Applications/%s/Viewfinder.app -e UIASCRIPT js/control/%s_control.js -e UIARESULTSPATH %s' % (os.environ['USER'], _SCHEME['ios'], app_id, temp_name, test_dir))
print instrument_cmd
call(instrument_cmd, shell=True)
Teardown(temp_name)
| [
"def",
"ExecuteTest",
"(",
")",
":",
"app_id",
"=",
"GetApplicationId",
"(",
"_SCHEME",
"[",
"'ios'",
"]",
")",
"test_name",
"=",
"options",
".",
"testname",
"if",
"test_name",
":",
"Setup",
"(",
"test_name",
")",
"test_dir",
"=",
"(",
"'%s/results/current/%s/%s'",
"%",
"(",
"_BASE_PATH",
",",
"options",
".",
"conf",
",",
"test_name",
")",
")",
"os",
".",
"makedirs",
"(",
"test_dir",
",",
"493",
")",
"instrument_cmd",
"=",
"(",
"'instruments -t templates/VF_AutoUI_Template.tracetemplate /Users/%s/Library/Application\\\\ Support/iPhone\\\\ Simulator/%s/Applications/%s/Viewfinder.app -e UIASCRIPT js/control/%s_control.js -e UIARESULTSPATH %s'",
"%",
"(",
"os",
".",
"environ",
"[",
"'USER'",
"]",
",",
"_SCHEME",
"[",
"'ios'",
"]",
",",
"app_id",
",",
"test_name",
",",
"test_dir",
")",
")",
"print",
"instrument_cmd",
"call",
"(",
"instrument_cmd",
",",
"shell",
"=",
"True",
")",
"Teardown",
"(",
"test_name",
")",
"else",
":",
"for",
"temp_name",
"in",
"_SUMMARY",
".",
"keys",
"(",
")",
":",
"Setup",
"(",
"'all'",
")",
"test_dir",
"=",
"(",
"'%s/results/current/%s/%s'",
"%",
"(",
"_BASE_PATH",
",",
"options",
".",
"conf",
",",
"temp_name",
")",
")",
"os",
".",
"makedirs",
"(",
"test_dir",
",",
"493",
")",
"instrument_cmd",
"=",
"(",
"'instruments -t templates/VF_AutoUI_Template.tracetemplate /Users/%s/Library/Application\\\\ Support/iPhone\\\\ Simulator/%s/Applications/%s/Viewfinder.app -e UIASCRIPT js/control/%s_control.js -e UIARESULTSPATH %s'",
"%",
"(",
"os",
".",
"environ",
"[",
"'USER'",
"]",
",",
"_SCHEME",
"[",
"'ios'",
"]",
",",
"app_id",
",",
"temp_name",
",",
"test_dir",
")",
")",
"print",
"instrument_cmd",
"call",
"(",
"instrument_cmd",
",",
"shell",
"=",
"True",
")",
"Teardown",
"(",
"temp_name",
")"
] | run the tests . | train | false |
24,339 | def gunzip_stream(fileobj, bufsize=1024):
READ_GZIP_DATA = 16
d = zlib.decompressobj((READ_GZIP_DATA | zlib.MAX_WBITS))
while True:
chunk = fileobj.read(bufsize)
if (not chunk):
return
data = d.decompress(chunk)
if data:
(yield data)
| [
"def",
"gunzip_stream",
"(",
"fileobj",
",",
"bufsize",
"=",
"1024",
")",
":",
"READ_GZIP_DATA",
"=",
"16",
"d",
"=",
"zlib",
".",
"decompressobj",
"(",
"(",
"READ_GZIP_DATA",
"|",
"zlib",
".",
"MAX_WBITS",
")",
")",
"while",
"True",
":",
"chunk",
"=",
"fileobj",
".",
"read",
"(",
"bufsize",
")",
"if",
"(",
"not",
"chunk",
")",
":",
"return",
"data",
"=",
"d",
".",
"decompress",
"(",
"chunk",
")",
"if",
"data",
":",
"(",
"yield",
"data",
")"
] | decompress gzipped data on the fly . | train | false |
24,340 | def get_exception_for_type_error(func, exc):
message = str(exc)
func_name = func.__name__
invalid_num_args_pattern = ('%s\\(\\) takes %s \\d+ arguments? \\(\\d+ given\\)' % (func_name, '(exactly|at most|at least)'))
unexpected_keyword_arg_pattern = ("%s\\(\\) got an unexpected keyword argument '(.*?)'" % func_name)
if re.search(invalid_num_args_pattern, message):
result = webob_exc.HTTPNotFound()
elif re.search(unexpected_keyword_arg_pattern, message):
match = re.match(unexpected_keyword_arg_pattern, message)
if match:
groups = match.groups()
query_param_name = groups[0]
msg = ('Unsupported query parameter: %s' % query_param_name)
else:
msg = 'Unknown error, please contact the administrator.'
result = webob_exc.HTTPBadRequest(detail=msg)
else:
result = exc
return result
| [
"def",
"get_exception_for_type_error",
"(",
"func",
",",
"exc",
")",
":",
"message",
"=",
"str",
"(",
"exc",
")",
"func_name",
"=",
"func",
".",
"__name__",
"invalid_num_args_pattern",
"=",
"(",
"'%s\\\\(\\\\) takes %s \\\\d+ arguments? \\\\(\\\\d+ given\\\\)'",
"%",
"(",
"func_name",
",",
"'(exactly|at most|at least)'",
")",
")",
"unexpected_keyword_arg_pattern",
"=",
"(",
"\"%s\\\\(\\\\) got an unexpected keyword argument '(.*?)'\"",
"%",
"func_name",
")",
"if",
"re",
".",
"search",
"(",
"invalid_num_args_pattern",
",",
"message",
")",
":",
"result",
"=",
"webob_exc",
".",
"HTTPNotFound",
"(",
")",
"elif",
"re",
".",
"search",
"(",
"unexpected_keyword_arg_pattern",
",",
"message",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"unexpected_keyword_arg_pattern",
",",
"message",
")",
"if",
"match",
":",
"groups",
"=",
"match",
".",
"groups",
"(",
")",
"query_param_name",
"=",
"groups",
"[",
"0",
"]",
"msg",
"=",
"(",
"'Unsupported query parameter: %s'",
"%",
"query_param_name",
")",
"else",
":",
"msg",
"=",
"'Unknown error, please contact the administrator.'",
"result",
"=",
"webob_exc",
".",
"HTTPBadRequest",
"(",
"detail",
"=",
"msg",
")",
"else",
":",
"result",
"=",
"exc",
"return",
"result"
] | method which translates typeerror thrown by the controller method and intercepted inside jsexpose decorator and returns a better exception for it . | train | false |
24,342 | def randrange(order, entropy=None):
if (entropy is None):
entropy = os.urandom
assert (order > 1)
bytes = orderlen(order)
dont_try_forever = 10000
while (dont_try_forever > 0):
dont_try_forever -= 1
candidate = (string_to_number(entropy(bytes)) + 1)
if (1 <= candidate < order):
return candidate
continue
raise RuntimeError(('randrange() tried hard but gave up, either something is very wrong or you got realllly unlucky. Order was %x' % order))
| [
"def",
"randrange",
"(",
"order",
",",
"entropy",
"=",
"None",
")",
":",
"if",
"(",
"entropy",
"is",
"None",
")",
":",
"entropy",
"=",
"os",
".",
"urandom",
"assert",
"(",
"order",
">",
"1",
")",
"bytes",
"=",
"orderlen",
"(",
"order",
")",
"dont_try_forever",
"=",
"10000",
"while",
"(",
"dont_try_forever",
">",
"0",
")",
":",
"dont_try_forever",
"-=",
"1",
"candidate",
"=",
"(",
"string_to_number",
"(",
"entropy",
"(",
"bytes",
")",
")",
"+",
"1",
")",
"if",
"(",
"1",
"<=",
"candidate",
"<",
"order",
")",
":",
"return",
"candidate",
"continue",
"raise",
"RuntimeError",
"(",
"(",
"'randrange() tried hard but gave up, either something is very wrong or you got realllly unlucky. Order was %x'",
"%",
"order",
")",
")"
] | return a random integer k such that 1 <= k < order . | train | true |
24,343 | def appendInputWithNSimilarValues(inputs, numNear=10):
numInputs = len(inputs)
skipOne = False
for i in xrange(numInputs):
input = inputs[i]
numChanged = 0
newInput = copy.deepcopy(input)
for j in xrange((len(input) - 1)):
if skipOne:
skipOne = False
continue
if ((input[j] == 1) and (input[(j + 1)] == 0)):
newInput[j] = 0
newInput[(j + 1)] = 1
inputs.append(newInput)
newInput = copy.deepcopy(newInput)
numChanged += 1
skipOne = True
if (numChanged == numNear):
break
| [
"def",
"appendInputWithNSimilarValues",
"(",
"inputs",
",",
"numNear",
"=",
"10",
")",
":",
"numInputs",
"=",
"len",
"(",
"inputs",
")",
"skipOne",
"=",
"False",
"for",
"i",
"in",
"xrange",
"(",
"numInputs",
")",
":",
"input",
"=",
"inputs",
"[",
"i",
"]",
"numChanged",
"=",
"0",
"newInput",
"=",
"copy",
".",
"deepcopy",
"(",
"input",
")",
"for",
"j",
"in",
"xrange",
"(",
"(",
"len",
"(",
"input",
")",
"-",
"1",
")",
")",
":",
"if",
"skipOne",
":",
"skipOne",
"=",
"False",
"continue",
"if",
"(",
"(",
"input",
"[",
"j",
"]",
"==",
"1",
")",
"and",
"(",
"input",
"[",
"(",
"j",
"+",
"1",
")",
"]",
"==",
"0",
")",
")",
":",
"newInput",
"[",
"j",
"]",
"=",
"0",
"newInput",
"[",
"(",
"j",
"+",
"1",
")",
"]",
"=",
"1",
"inputs",
".",
"append",
"(",
"newInput",
")",
"newInput",
"=",
"copy",
".",
"deepcopy",
"(",
"newInput",
")",
"numChanged",
"+=",
"1",
"skipOne",
"=",
"True",
"if",
"(",
"numChanged",
"==",
"numNear",
")",
":",
"break"
] | creates a neighboring record for each record in the inputs and adds new records at the end of the inputs list . | train | true |
24,345 | def htmldiff(old_html, new_html):
old_html_tokens = tokenize(old_html)
new_html_tokens = tokenize(new_html)
result = htmldiff_tokens(old_html_tokens, new_html_tokens)
result = ''.join(result).strip()
return fixup_ins_del_tags(result)
| [
"def",
"htmldiff",
"(",
"old_html",
",",
"new_html",
")",
":",
"old_html_tokens",
"=",
"tokenize",
"(",
"old_html",
")",
"new_html_tokens",
"=",
"tokenize",
"(",
"new_html",
")",
"result",
"=",
"htmldiff_tokens",
"(",
"old_html_tokens",
",",
"new_html_tokens",
")",
"result",
"=",
"''",
".",
"join",
"(",
"result",
")",
".",
"strip",
"(",
")",
"return",
"fixup_ins_del_tags",
"(",
"result",
")"
] | do a diff of the old and new document . | train | true |
24,346 | def list_grep(list, pattern):
compiled = re.compile(pattern)
for line in list:
match = compiled.search(line)
if match:
return 1
return 0
| [
"def",
"list_grep",
"(",
"list",
",",
"pattern",
")",
":",
"compiled",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"for",
"line",
"in",
"list",
":",
"match",
"=",
"compiled",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"return",
"1",
"return",
"0"
] | true if any item in list matches the specified pattern . | train | false |
24,347 | def split_env(url):
if (not url.startswith('salt://')):
return (url, None)
(path, senv) = parse(url)
return (create(path), senv)
| [
"def",
"split_env",
"(",
"url",
")",
":",
"if",
"(",
"not",
"url",
".",
"startswith",
"(",
"'salt://'",
")",
")",
":",
"return",
"(",
"url",
",",
"None",
")",
"(",
"path",
",",
"senv",
")",
"=",
"parse",
"(",
"url",
")",
"return",
"(",
"create",
"(",
"path",
")",
",",
"senv",
")"
] | remove the saltenv query parameter from a salt:// url . | train | true |
24,348 | def provision(distribution, package_source, variants):
commands = []
if (Variants.DISTRO_TESTING in variants):
commands.append(task_enable_updates_testing(distribution))
if (Variants.DOCKER_HEAD in variants):
commands.append(task_enable_docker_head_repository(distribution))
commands.append(task_install_docker(distribution))
commands.append(task_install_flocker(package_source=package_source, distribution=distribution))
commands.append(task_install_docker_plugin(package_source=package_source, distribution=distribution))
commands.append(task_enable_docker(distribution))
return sequence(commands)
| [
"def",
"provision",
"(",
"distribution",
",",
"package_source",
",",
"variants",
")",
":",
"commands",
"=",
"[",
"]",
"if",
"(",
"Variants",
".",
"DISTRO_TESTING",
"in",
"variants",
")",
":",
"commands",
".",
"append",
"(",
"task_enable_updates_testing",
"(",
"distribution",
")",
")",
"if",
"(",
"Variants",
".",
"DOCKER_HEAD",
"in",
"variants",
")",
":",
"commands",
".",
"append",
"(",
"task_enable_docker_head_repository",
"(",
"distribution",
")",
")",
"commands",
".",
"append",
"(",
"task_install_docker",
"(",
"distribution",
")",
")",
"commands",
".",
"append",
"(",
"task_install_flocker",
"(",
"package_source",
"=",
"package_source",
",",
"distribution",
"=",
"distribution",
")",
")",
"commands",
".",
"append",
"(",
"task_install_docker_plugin",
"(",
"package_source",
"=",
"package_source",
",",
"distribution",
"=",
"distribution",
")",
")",
"commands",
".",
"append",
"(",
"task_enable_docker",
"(",
"distribution",
")",
")",
"return",
"sequence",
"(",
"commands",
")"
] | provision a clean ubuntu 12 . | train | false |
24,350 | def test_find_module_3():
nt.assert_is_none(mp.find_module(None, None))
| [
"def",
"test_find_module_3",
"(",
")",
":",
"nt",
".",
"assert_is_none",
"(",
"mp",
".",
"find_module",
"(",
"None",
",",
"None",
")",
")"
] | testing sys . | train | false |
24,351 | @register.function
def locale_url(url):
prefixer = urlresolvers.get_url_prefix()
script = prefixer.request.META['SCRIPT_NAME']
parts = [script, prefixer.locale, url.lstrip('/')]
return '/'.join(parts)
| [
"@",
"register",
".",
"function",
"def",
"locale_url",
"(",
"url",
")",
":",
"prefixer",
"=",
"urlresolvers",
".",
"get_url_prefix",
"(",
")",
"script",
"=",
"prefixer",
".",
"request",
".",
"META",
"[",
"'SCRIPT_NAME'",
"]",
"parts",
"=",
"[",
"script",
",",
"prefixer",
".",
"locale",
",",
"url",
".",
"lstrip",
"(",
"'/'",
")",
"]",
"return",
"'/'",
".",
"join",
"(",
"parts",
")"
] | take a url and give it the locale prefix . | train | false |
24,352 | def _getFieldIndexBySpecial(fields, special):
for (i, field) in enumerate(fields):
if (field.special == special):
return i
return None
| [
"def",
"_getFieldIndexBySpecial",
"(",
"fields",
",",
"special",
")",
":",
"for",
"(",
"i",
",",
"field",
")",
"in",
"enumerate",
"(",
"fields",
")",
":",
"if",
"(",
"field",
".",
"special",
"==",
"special",
")",
":",
"return",
"i",
"return",
"None"
] | return index of the field matching the field meta special value . | train | true |
24,354 | def degree_sequence(creation_sequence):
cs = creation_sequence
seq = []
rd = cs.count('d')
for (i, sym) in enumerate(cs):
if (sym == 'd'):
rd -= 1
seq.append((rd + i))
else:
seq.append(rd)
return seq
| [
"def",
"degree_sequence",
"(",
"creation_sequence",
")",
":",
"cs",
"=",
"creation_sequence",
"seq",
"=",
"[",
"]",
"rd",
"=",
"cs",
".",
"count",
"(",
"'d'",
")",
"for",
"(",
"i",
",",
"sym",
")",
"in",
"enumerate",
"(",
"cs",
")",
":",
"if",
"(",
"sym",
"==",
"'d'",
")",
":",
"rd",
"-=",
"1",
"seq",
".",
"append",
"(",
"(",
"rd",
"+",
"i",
")",
")",
"else",
":",
"seq",
".",
"append",
"(",
"rd",
")",
"return",
"seq"
] | return degree sequence for the threshold graph with the given creation sequence . | train | false |
24,355 | def release_in_episode(episode_id, release_id):
with Session() as session:
release = session.query(Release).filter((Release.id == release_id)).one()
return (release.episode_id == episode_id)
| [
"def",
"release_in_episode",
"(",
"episode_id",
",",
"release_id",
")",
":",
"with",
"Session",
"(",
")",
"as",
"session",
":",
"release",
"=",
"session",
".",
"query",
"(",
"Release",
")",
".",
"filter",
"(",
"(",
"Release",
".",
"id",
"==",
"release_id",
")",
")",
".",
"one",
"(",
")",
"return",
"(",
"release",
".",
"episode_id",
"==",
"episode_id",
")"
] | return true if release_id is part of episode with episode_id . | train | false |
24,356 | def __ipv6_netmask(value):
(valid, errmsg) = (False, 'IPv6 netmask (0->128)')
(valid, value, _) = __int(value)
valid = (valid and (0 <= value <= 128))
return (valid, value, errmsg)
| [
"def",
"__ipv6_netmask",
"(",
"value",
")",
":",
"(",
"valid",
",",
"errmsg",
")",
"=",
"(",
"False",
",",
"'IPv6 netmask (0->128)'",
")",
"(",
"valid",
",",
"value",
",",
"_",
")",
"=",
"__int",
"(",
"value",
")",
"valid",
"=",
"(",
"valid",
"and",
"(",
"0",
"<=",
"value",
"<=",
"128",
")",
")",
"return",
"(",
"valid",
",",
"value",
",",
"errmsg",
")"
] | validate an ipv6 integer netmask . | train | true |
24,357 | def show_curr(caller, showall=False):
stackptr = caller.ndb.batch_stackptr
stack = caller.ndb.batch_stack
if (stackptr >= len(stack)):
caller.ndb.batch_stackptr = (len(stack) - 1)
show_curr(caller, showall)
return
entry = stack[stackptr]
string = format_header(caller, entry)
codeall = entry.strip()
string += '{G(hh for help)'
if showall:
for line in codeall.split('\n'):
string += ('\n{G|{n %s' % line)
caller.msg(string)
| [
"def",
"show_curr",
"(",
"caller",
",",
"showall",
"=",
"False",
")",
":",
"stackptr",
"=",
"caller",
".",
"ndb",
".",
"batch_stackptr",
"stack",
"=",
"caller",
".",
"ndb",
".",
"batch_stack",
"if",
"(",
"stackptr",
">=",
"len",
"(",
"stack",
")",
")",
":",
"caller",
".",
"ndb",
".",
"batch_stackptr",
"=",
"(",
"len",
"(",
"stack",
")",
"-",
"1",
")",
"show_curr",
"(",
"caller",
",",
"showall",
")",
"return",
"entry",
"=",
"stack",
"[",
"stackptr",
"]",
"string",
"=",
"format_header",
"(",
"caller",
",",
"entry",
")",
"codeall",
"=",
"entry",
".",
"strip",
"(",
")",
"string",
"+=",
"'{G(hh for help)'",
"if",
"showall",
":",
"for",
"line",
"in",
"codeall",
".",
"split",
"(",
"'\\n'",
")",
":",
"string",
"+=",
"(",
"'\\n{G|{n %s'",
"%",
"line",
")",
"caller",
".",
"msg",
"(",
"string",
")"
] | show the current position in stack . | train | false |
24,358 | def _get_desired_pkg(name, desired):
if ((not desired[name]) or desired[name].startswith(('<', '>', '='))):
oper = ''
else:
oper = '='
return '{0}{1}{2}'.format(name, oper, ('' if (not desired[name]) else desired[name]))
| [
"def",
"_get_desired_pkg",
"(",
"name",
",",
"desired",
")",
":",
"if",
"(",
"(",
"not",
"desired",
"[",
"name",
"]",
")",
"or",
"desired",
"[",
"name",
"]",
".",
"startswith",
"(",
"(",
"'<'",
",",
"'>'",
",",
"'='",
")",
")",
")",
":",
"oper",
"=",
"''",
"else",
":",
"oper",
"=",
"'='",
"return",
"'{0}{1}{2}'",
".",
"format",
"(",
"name",
",",
"oper",
",",
"(",
"''",
"if",
"(",
"not",
"desired",
"[",
"name",
"]",
")",
"else",
"desired",
"[",
"name",
"]",
")",
")"
] | helper function that retrieves and nicely formats the desired pkg so that helpful information can be printed in the comment for the state . | train | true |
24,361 | def dlls_in_dir(directory):
return files_in_dir(directory, ['*.so', '*.dll', '*.dylib'])
| [
"def",
"dlls_in_dir",
"(",
"directory",
")",
":",
"return",
"files_in_dir",
"(",
"directory",
",",
"[",
"'*.so'",
",",
"'*.dll'",
",",
"'*.dylib'",
"]",
")"
] | returns a list of * . | train | false |
24,364 | def scheme_to_ows_stream(scheme, stream, pretty=False, pickle_fallback=False):
tree = scheme_to_etree(scheme, data_format='literal', pickle_fallback=pickle_fallback)
if pretty:
indent(tree.getroot(), 0)
if (sys.version_info < (2, 7)):
tree.write(stream, encoding='utf-8')
else:
tree.write(stream, encoding='utf-8', xml_declaration=True)
| [
"def",
"scheme_to_ows_stream",
"(",
"scheme",
",",
"stream",
",",
"pretty",
"=",
"False",
",",
"pickle_fallback",
"=",
"False",
")",
":",
"tree",
"=",
"scheme_to_etree",
"(",
"scheme",
",",
"data_format",
"=",
"'literal'",
",",
"pickle_fallback",
"=",
"pickle_fallback",
")",
"if",
"pretty",
":",
"indent",
"(",
"tree",
".",
"getroot",
"(",
")",
",",
"0",
")",
"if",
"(",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
"7",
")",
")",
":",
"tree",
".",
"write",
"(",
"stream",
",",
"encoding",
"=",
"'utf-8'",
")",
"else",
":",
"tree",
".",
"write",
"(",
"stream",
",",
"encoding",
"=",
"'utf-8'",
",",
"xml_declaration",
"=",
"True",
")"
] | write scheme to a a stream in orange scheme . | train | false |
24,365 | def _shadowGetByName(username):
if (spwd is not None):
f = spwd.getspnam
else:
return None
return runAsEffectiveUser(0, 0, f, username)
| [
"def",
"_shadowGetByName",
"(",
"username",
")",
":",
"if",
"(",
"spwd",
"is",
"not",
"None",
")",
":",
"f",
"=",
"spwd",
".",
"getspnam",
"else",
":",
"return",
"None",
"return",
"runAsEffectiveUser",
"(",
"0",
",",
"0",
",",
"f",
",",
"username",
")"
] | look up a user in the /etc/shadow database using the spwd module . | train | false |
24,366 | @app.route('/cookies/set')
def set_cookies():
cookies = dict(request.args.items())
r = app.make_response(redirect(url_for('view_cookies')))
for (key, value) in cookies.items():
r.set_cookie(key=key, value=value, secure=secure_cookie())
return r
| [
"@",
"app",
".",
"route",
"(",
"'/cookies/set'",
")",
"def",
"set_cookies",
"(",
")",
":",
"cookies",
"=",
"dict",
"(",
"request",
".",
"args",
".",
"items",
"(",
")",
")",
"r",
"=",
"app",
".",
"make_response",
"(",
"redirect",
"(",
"url_for",
"(",
"'view_cookies'",
")",
")",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"cookies",
".",
"items",
"(",
")",
":",
"r",
".",
"set_cookie",
"(",
"key",
"=",
"key",
",",
"value",
"=",
"value",
",",
"secure",
"=",
"secure_cookie",
"(",
")",
")",
"return",
"r"
] | sets cookie(s) as provided by the query string and redirects to cookie list . | train | true |
24,367 | def pyramid_expand(image, upscale=2, sigma=None, order=1, mode='reflect', cval=0):
_check_factor(upscale)
image = img_as_float(image)
rows = image.shape[0]
cols = image.shape[1]
out_rows = math.ceil((upscale * rows))
out_cols = math.ceil((upscale * cols))
if (sigma is None):
sigma = ((2 * upscale) / 6.0)
resized = resize(image, (out_rows, out_cols), order=order, mode=mode, cval=cval)
out = _smooth(resized, sigma, mode, cval)
return out
| [
"def",
"pyramid_expand",
"(",
"image",
",",
"upscale",
"=",
"2",
",",
"sigma",
"=",
"None",
",",
"order",
"=",
"1",
",",
"mode",
"=",
"'reflect'",
",",
"cval",
"=",
"0",
")",
":",
"_check_factor",
"(",
"upscale",
")",
"image",
"=",
"img_as_float",
"(",
"image",
")",
"rows",
"=",
"image",
".",
"shape",
"[",
"0",
"]",
"cols",
"=",
"image",
".",
"shape",
"[",
"1",
"]",
"out_rows",
"=",
"math",
".",
"ceil",
"(",
"(",
"upscale",
"*",
"rows",
")",
")",
"out_cols",
"=",
"math",
".",
"ceil",
"(",
"(",
"upscale",
"*",
"cols",
")",
")",
"if",
"(",
"sigma",
"is",
"None",
")",
":",
"sigma",
"=",
"(",
"(",
"2",
"*",
"upscale",
")",
"/",
"6.0",
")",
"resized",
"=",
"resize",
"(",
"image",
",",
"(",
"out_rows",
",",
"out_cols",
")",
",",
"order",
"=",
"order",
",",
"mode",
"=",
"mode",
",",
"cval",
"=",
"cval",
")",
"out",
"=",
"_smooth",
"(",
"resized",
",",
"sigma",
",",
"mode",
",",
"cval",
")",
"return",
"out"
] | upsample and then smooth image . | train | false |
24,369 | def makeDirectoryFromAbsolutePath(absDirPath):
assert os.path.isabs(absDirPath)
try:
os.makedirs(absDirPath)
except OSError as e:
if (e.errno != os.errno.EEXIST):
raise
return absDirPath
| [
"def",
"makeDirectoryFromAbsolutePath",
"(",
"absDirPath",
")",
":",
"assert",
"os",
".",
"path",
".",
"isabs",
"(",
"absDirPath",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"absDirPath",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"(",
"e",
".",
"errno",
"!=",
"os",
".",
"errno",
".",
"EEXIST",
")",
":",
"raise",
"return",
"absDirPath"
] | makes directory for the given directory path with default permissions . | train | true |
24,371 | def removeSeqStarts(vectors, resets, numSteps=1):
if (numSteps == 0):
return vectors
resetIndices = resets.nonzero()[0]
removeRows = resetIndices
for i in range((numSteps - 1)):
removeRows = numpy.hstack((removeRows, ((resetIndices + i) + 1)))
return numpy.delete(vectors, removeRows, axis=0)
| [
"def",
"removeSeqStarts",
"(",
"vectors",
",",
"resets",
",",
"numSteps",
"=",
"1",
")",
":",
"if",
"(",
"numSteps",
"==",
"0",
")",
":",
"return",
"vectors",
"resetIndices",
"=",
"resets",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"removeRows",
"=",
"resetIndices",
"for",
"i",
"in",
"range",
"(",
"(",
"numSteps",
"-",
"1",
")",
")",
":",
"removeRows",
"=",
"numpy",
".",
"hstack",
"(",
"(",
"removeRows",
",",
"(",
"(",
"resetIndices",
"+",
"i",
")",
"+",
"1",
")",
")",
")",
"return",
"numpy",
".",
"delete",
"(",
"vectors",
",",
"removeRows",
",",
"axis",
"=",
"0",
")"
] | convert a list of sequences of pattern indices . | train | true |
24,372 | @pytest.mark.cmd
def test_test_checks_alt_checker(capfd, settings):
settings.POOTLE_QUALITY_CHECKER = 'pootle_misc.checks.ENChecker'
call_command('test_checks', '--source="%s files"', '--target="%s leers"')
(out, err) = capfd.readouterr()
assert ('No errors found' in out)
call_command('test_checks', '--source="%s files"', '--target="%d leers"')
(out, err) = capfd.readouterr()
assert ('Failing checks' in out)
| [
"@",
"pytest",
".",
"mark",
".",
"cmd",
"def",
"test_test_checks_alt_checker",
"(",
"capfd",
",",
"settings",
")",
":",
"settings",
".",
"POOTLE_QUALITY_CHECKER",
"=",
"'pootle_misc.checks.ENChecker'",
"call_command",
"(",
"'test_checks'",
",",
"'--source=\"%s files\"'",
",",
"'--target=\"%s leers\"'",
")",
"(",
"out",
",",
"err",
")",
"=",
"capfd",
".",
"readouterr",
"(",
")",
"assert",
"(",
"'No errors found'",
"in",
"out",
")",
"call_command",
"(",
"'test_checks'",
",",
"'--source=\"%s files\"'",
",",
"'--target=\"%d leers\"'",
")",
"(",
"out",
",",
"err",
")",
"=",
"capfd",
".",
"readouterr",
"(",
")",
"assert",
"(",
"'Failing checks'",
"in",
"out",
")"
] | use an alternate checker . | train | false |
24,373 | def testRemoteTopo(link=RemoteGRELink):
topo = LinearTopo(2)
net = Mininet(topo=topo, host=HostPlacer, switch=SwitchPlacer, link=link, controller=ClusterController)
net.start()
net.pingAll()
net.stop()
| [
"def",
"testRemoteTopo",
"(",
"link",
"=",
"RemoteGRELink",
")",
":",
"topo",
"=",
"LinearTopo",
"(",
"2",
")",
"net",
"=",
"Mininet",
"(",
"topo",
"=",
"topo",
",",
"host",
"=",
"HostPlacer",
",",
"switch",
"=",
"SwitchPlacer",
",",
"link",
"=",
"link",
",",
"controller",
"=",
"ClusterController",
")",
"net",
".",
"start",
"(",
")",
"net",
".",
"pingAll",
"(",
")",
"net",
".",
"stop",
"(",
")"
] | test remote node classes using mininet()/topo() api . | train | false |
24,375 | def _func_name(func):
if isinstance(func, (type, ClassType)):
name = func.__name__
if (func.__module__ not in ('__main__', '__builtin__')):
name = ('%s.%s' % (func.__module__, name))
return name
name = getattr(func, 'func_name', None)
if (name is None):
name = repr(func)
else:
name_self = getattr(func, 'im_self', None)
if (name_self is not None):
name = ('%r.%s' % (name_self, name))
else:
name_class = getattr(func, 'im_class', None)
if (name_class is not None):
name = ('%s.%s' % (name_class.__name__, name))
module = getattr(func, 'func_globals', {}).get('__name__')
if (module and (module != '__main__')):
name = ('%s.%s' % (module, name))
return name
| [
"def",
"_func_name",
"(",
"func",
")",
":",
"if",
"isinstance",
"(",
"func",
",",
"(",
"type",
",",
"ClassType",
")",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"if",
"(",
"func",
".",
"__module__",
"not",
"in",
"(",
"'__main__'",
",",
"'__builtin__'",
")",
")",
":",
"name",
"=",
"(",
"'%s.%s'",
"%",
"(",
"func",
".",
"__module__",
",",
"name",
")",
")",
"return",
"name",
"name",
"=",
"getattr",
"(",
"func",
",",
"'func_name'",
",",
"None",
")",
"if",
"(",
"name",
"is",
"None",
")",
":",
"name",
"=",
"repr",
"(",
"func",
")",
"else",
":",
"name_self",
"=",
"getattr",
"(",
"func",
",",
"'im_self'",
",",
"None",
")",
"if",
"(",
"name_self",
"is",
"not",
"None",
")",
":",
"name",
"=",
"(",
"'%r.%s'",
"%",
"(",
"name_self",
",",
"name",
")",
")",
"else",
":",
"name_class",
"=",
"getattr",
"(",
"func",
",",
"'im_class'",
",",
"None",
")",
"if",
"(",
"name_class",
"is",
"not",
"None",
")",
":",
"name",
"=",
"(",
"'%s.%s'",
"%",
"(",
"name_class",
".",
"__name__",
",",
"name",
")",
")",
"module",
"=",
"getattr",
"(",
"func",
",",
"'func_globals'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'__name__'",
")",
"if",
"(",
"module",
"and",
"(",
"module",
"!=",
"'__main__'",
")",
")",
":",
"name",
"=",
"(",
"'%s.%s'",
"%",
"(",
"module",
",",
"name",
")",
")",
"return",
"name"
] | returns the string name of a function . | train | false |
24,376 | def binned_statistic(x, values, statistic='mean', bins=10, range=None):
try:
N = len(bins)
except TypeError:
N = 1
if (N != 1):
bins = [np.asarray(bins, float)]
if (range is not None):
if (len(range) == 2):
range = [range]
(medians, edges, binnumbers) = binned_statistic_dd([x], values, statistic, bins, range)
return BinnedStatisticResult(medians, edges[0], binnumbers)
| [
"def",
"binned_statistic",
"(",
"x",
",",
"values",
",",
"statistic",
"=",
"'mean'",
",",
"bins",
"=",
"10",
",",
"range",
"=",
"None",
")",
":",
"try",
":",
"N",
"=",
"len",
"(",
"bins",
")",
"except",
"TypeError",
":",
"N",
"=",
"1",
"if",
"(",
"N",
"!=",
"1",
")",
":",
"bins",
"=",
"[",
"np",
".",
"asarray",
"(",
"bins",
",",
"float",
")",
"]",
"if",
"(",
"range",
"is",
"not",
"None",
")",
":",
"if",
"(",
"len",
"(",
"range",
")",
"==",
"2",
")",
":",
"range",
"=",
"[",
"range",
"]",
"(",
"medians",
",",
"edges",
",",
"binnumbers",
")",
"=",
"binned_statistic_dd",
"(",
"[",
"x",
"]",
",",
"values",
",",
"statistic",
",",
"bins",
",",
"range",
")",
"return",
"BinnedStatisticResult",
"(",
"medians",
",",
"edges",
"[",
"0",
"]",
",",
"binnumbers",
")"
] | compute a binned statistic for one or more sets of data . | train | false |
24,377 | def get_full_url(info, log_path):
if (info is not None):
(protocol, host, path) = info
prefix = ('%s://%s' % (protocol, host))
else:
prefix = ''
path = log_path
return (prefix + path)
| [
"def",
"get_full_url",
"(",
"info",
",",
"log_path",
")",
":",
"if",
"(",
"info",
"is",
"not",
"None",
")",
":",
"(",
"protocol",
",",
"host",
",",
"path",
")",
"=",
"info",
"prefix",
"=",
"(",
"'%s://%s'",
"%",
"(",
"protocol",
",",
"host",
")",
")",
"else",
":",
"prefix",
"=",
"''",
"path",
"=",
"log_path",
"return",
"(",
"prefix",
"+",
"path",
")"
] | returns the full url of the requested log path . | train | false |
24,378 | def clean_registries(queue):
registry = FinishedJobRegistry(name=queue.name, connection=queue.connection)
registry.cleanup()
registry = StartedJobRegistry(name=queue.name, connection=queue.connection)
registry.cleanup()
| [
"def",
"clean_registries",
"(",
"queue",
")",
":",
"registry",
"=",
"FinishedJobRegistry",
"(",
"name",
"=",
"queue",
".",
"name",
",",
"connection",
"=",
"queue",
".",
"connection",
")",
"registry",
".",
"cleanup",
"(",
")",
"registry",
"=",
"StartedJobRegistry",
"(",
"name",
"=",
"queue",
".",
"name",
",",
"connection",
"=",
"queue",
".",
"connection",
")",
"registry",
".",
"cleanup",
"(",
")"
] | cleans startedjobregistry and finishedjobregistry of a queue . | train | false |
24,379 | def format_colors(text):
def replace_color(m):
'\n Callback function, to replace a colour tag with its content and a\n suitable escape sequence to change colour.\n '
return ('%s%s%s' % (Colors[m.group(1)], m.group(2), Colors['end']))
text = re.sub('\\[color\\s*([a-z]+)\\](.*?)\\[\\/color\\]', replace_color, text)
return text
| [
"def",
"format_colors",
"(",
"text",
")",
":",
"def",
"replace_color",
"(",
"m",
")",
":",
"return",
"(",
"'%s%s%s'",
"%",
"(",
"Colors",
"[",
"m",
".",
"group",
"(",
"1",
")",
"]",
",",
"m",
".",
"group",
"(",
"2",
")",
",",
"Colors",
"[",
"'end'",
"]",
")",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"'\\\\[color\\\\s*([a-z]+)\\\\](.*?)\\\\[\\\\/color\\\\]'",
",",
"replace_color",
",",
"text",
")",
"return",
"text"
] | inserts *nix colour sequences into a string . | train | false |
24,380 | def bind_row_action(action_name):
primary_action_locator = (by.By.CSS_SELECTOR, 'td.actions_column *.btn:nth-child(1)')
secondary_actions_opener_locator = (by.By.CSS_SELECTOR, 'td.actions_column > .btn-group > *.btn:nth-child(2)')
secondary_actions_locator = (by.By.CSS_SELECTOR, 'td.actions_column > .btn-group > ul.row_actions > li > a, button')
def decorator(method):
@functools.wraps(method)
def wrapper(table, row):
def find_action(element):
pattern = ('__action_%s' % action_name)
return element.get_attribute('id').endswith(pattern)
action_element = row._get_element(*primary_action_locator)
if (not find_action(action_element)):
action_element = None
row._get_element(*secondary_actions_opener_locator).click()
for element in row._get_elements(*secondary_actions_locator):
if find_action(element):
action_element = element
break
if (action_element is None):
msg = ("Could not bind method '%s' to action control '%s'" % (method.__name__, action_name))
raise ValueError(msg)
return method(table, action_element, row)
return wrapper
return decorator
| [
"def",
"bind_row_action",
"(",
"action_name",
")",
":",
"primary_action_locator",
"=",
"(",
"by",
".",
"By",
".",
"CSS_SELECTOR",
",",
"'td.actions_column *.btn:nth-child(1)'",
")",
"secondary_actions_opener_locator",
"=",
"(",
"by",
".",
"By",
".",
"CSS_SELECTOR",
",",
"'td.actions_column > .btn-group > *.btn:nth-child(2)'",
")",
"secondary_actions_locator",
"=",
"(",
"by",
".",
"By",
".",
"CSS_SELECTOR",
",",
"'td.actions_column > .btn-group > ul.row_actions > li > a, button'",
")",
"def",
"decorator",
"(",
"method",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"table",
",",
"row",
")",
":",
"def",
"find_action",
"(",
"element",
")",
":",
"pattern",
"=",
"(",
"'__action_%s'",
"%",
"action_name",
")",
"return",
"element",
".",
"get_attribute",
"(",
"'id'",
")",
".",
"endswith",
"(",
"pattern",
")",
"action_element",
"=",
"row",
".",
"_get_element",
"(",
"*",
"primary_action_locator",
")",
"if",
"(",
"not",
"find_action",
"(",
"action_element",
")",
")",
":",
"action_element",
"=",
"None",
"row",
".",
"_get_element",
"(",
"*",
"secondary_actions_opener_locator",
")",
".",
"click",
"(",
")",
"for",
"element",
"in",
"row",
".",
"_get_elements",
"(",
"*",
"secondary_actions_locator",
")",
":",
"if",
"find_action",
"(",
"element",
")",
":",
"action_element",
"=",
"element",
"break",
"if",
"(",
"action_element",
"is",
"None",
")",
":",
"msg",
"=",
"(",
"\"Could not bind method '%s' to action control '%s'\"",
"%",
"(",
"method",
".",
"__name__",
",",
"action_name",
")",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"return",
"method",
"(",
"table",
",",
"action_element",
",",
"row",
")",
"return",
"wrapper",
"return",
"decorator"
] | a decorator to bind table region method to an actual row action button . | train | false |
24,381 | def get_input_encoding():
encoding = getattr(sys.stdin, 'encoding', None)
if (encoding is None):
encoding = 'ascii'
return encoding
| [
"def",
"get_input_encoding",
"(",
")",
":",
"encoding",
"=",
"getattr",
"(",
"sys",
".",
"stdin",
",",
"'encoding'",
",",
"None",
")",
"if",
"(",
"encoding",
"is",
"None",
")",
":",
"encoding",
"=",
"'ascii'",
"return",
"encoding"
] | return the default standard input encoding . | train | false |
24,383 | def Decode_Ip_Packet(s):
d = {}
d['header_len'] = (ord(s[0]) & 15)
d['data'] = s[(4 * d['header_len']):]
return d
| [
"def",
"Decode_Ip_Packet",
"(",
"s",
")",
":",
"d",
"=",
"{",
"}",
"d",
"[",
"'header_len'",
"]",
"=",
"(",
"ord",
"(",
"s",
"[",
"0",
"]",
")",
"&",
"15",
")",
"d",
"[",
"'data'",
"]",
"=",
"s",
"[",
"(",
"4",
"*",
"d",
"[",
"'header_len'",
"]",
")",
":",
"]",
"return",
"d"
] | taken from pcredz . | train | false |
24,384 | def test_adult():
skip_if_no_data()
adult_train = adult(which_set='train')
assert (adult_train.X >= 0.0).all()
assert (adult_train.y.dtype == bool)
assert (adult_train.X.shape == (30162, 104))
assert (adult_train.y.shape == (30162, 1))
adult_test = adult(which_set='test')
assert (adult_test.X >= 0.0).all()
assert (adult_test.y.dtype == bool)
assert (adult_test.X.shape == (15060, 103))
assert (adult_test.y.shape == (15060, 1))
| [
"def",
"test_adult",
"(",
")",
":",
"skip_if_no_data",
"(",
")",
"adult_train",
"=",
"adult",
"(",
"which_set",
"=",
"'train'",
")",
"assert",
"(",
"adult_train",
".",
"X",
">=",
"0.0",
")",
".",
"all",
"(",
")",
"assert",
"(",
"adult_train",
".",
"y",
".",
"dtype",
"==",
"bool",
")",
"assert",
"(",
"adult_train",
".",
"X",
".",
"shape",
"==",
"(",
"30162",
",",
"104",
")",
")",
"assert",
"(",
"adult_train",
".",
"y",
".",
"shape",
"==",
"(",
"30162",
",",
"1",
")",
")",
"adult_test",
"=",
"adult",
"(",
"which_set",
"=",
"'test'",
")",
"assert",
"(",
"adult_test",
".",
"X",
">=",
"0.0",
")",
".",
"all",
"(",
")",
"assert",
"(",
"adult_test",
".",
"y",
".",
"dtype",
"==",
"bool",
")",
"assert",
"(",
"adult_test",
".",
"X",
".",
"shape",
"==",
"(",
"15060",
",",
"103",
")",
")",
"assert",
"(",
"adult_test",
".",
"y",
".",
"shape",
"==",
"(",
"15060",
",",
"1",
")",
")"
] | tests if it will work correctly for train and test set . | train | false |
24,385 | def shaped_random(shape, xp=cupy, dtype=numpy.float32, scale=10, seed=0):
numpy.random.seed(seed)
if (numpy.dtype(dtype).type == numpy.bool_):
return xp.asarray(numpy.random.randint(2, size=shape).astype(dtype))
else:
return xp.asarray((numpy.random.rand(*shape) * scale).astype(dtype))
| [
"def",
"shaped_random",
"(",
"shape",
",",
"xp",
"=",
"cupy",
",",
"dtype",
"=",
"numpy",
".",
"float32",
",",
"scale",
"=",
"10",
",",
"seed",
"=",
"0",
")",
":",
"numpy",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"if",
"(",
"numpy",
".",
"dtype",
"(",
"dtype",
")",
".",
"type",
"==",
"numpy",
".",
"bool_",
")",
":",
"return",
"xp",
".",
"asarray",
"(",
"numpy",
".",
"random",
".",
"randint",
"(",
"2",
",",
"size",
"=",
"shape",
")",
".",
"astype",
"(",
"dtype",
")",
")",
"else",
":",
"return",
"xp",
".",
"asarray",
"(",
"(",
"numpy",
".",
"random",
".",
"rand",
"(",
"*",
"shape",
")",
"*",
"scale",
")",
".",
"astype",
"(",
"dtype",
")",
")"
] | returns an array filled with random values . | train | false |
24,386 | def exec_python_all(*args, **kwargs):
(cmdargs, kwargs) = __wrap_python(args, kwargs)
return exec_command_all(*cmdargs, **kwargs)
| [
"def",
"exec_python_all",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"(",
"cmdargs",
",",
"kwargs",
")",
"=",
"__wrap_python",
"(",
"args",
",",
"kwargs",
")",
"return",
"exec_command_all",
"(",
"*",
"cmdargs",
",",
"**",
"kwargs",
")"
] | wrap running python script in a subprocess . | train | false |
24,387 | def class_abbrev(type):
try:
return long2short[type]
except KeyError:
return type
| [
"def",
"class_abbrev",
"(",
"type",
")",
":",
"try",
":",
"return",
"long2short",
"[",
"type",
"]",
"except",
"KeyError",
":",
"return",
"type"
] | abbreviate an ne class name . | train | false |
24,389 | def detrend_linear(y):
x = np.arange(len(y), dtype=np.float_)
C = np.cov(x, y, bias=1)
b = (C[(0, 1)] / C[(0, 0)])
a = (y.mean() - (b * x.mean()))
return (y - ((b * x) + a))
| [
"def",
"detrend_linear",
"(",
"y",
")",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"y",
")",
",",
"dtype",
"=",
"np",
".",
"float_",
")",
"C",
"=",
"np",
".",
"cov",
"(",
"x",
",",
"y",
",",
"bias",
"=",
"1",
")",
"b",
"=",
"(",
"C",
"[",
"(",
"0",
",",
"1",
")",
"]",
"/",
"C",
"[",
"(",
"0",
",",
"0",
")",
"]",
")",
"a",
"=",
"(",
"y",
".",
"mean",
"(",
")",
"-",
"(",
"b",
"*",
"x",
".",
"mean",
"(",
")",
")",
")",
"return",
"(",
"y",
"-",
"(",
"(",
"b",
"*",
"x",
")",
"+",
"a",
")",
")"
] | return y minus best fit line; linear detrending . | train | false |
24,390 | def getProfileManufacturer(profile):
try:
if (not isinstance(profile, ImageCmsProfile)):
profile = ImageCmsProfile(profile)
return (profile.profile.product_manufacturer + '\n')
except (AttributeError, IOError, TypeError, ValueError) as v:
raise PyCMSError(v)
| [
"def",
"getProfileManufacturer",
"(",
"profile",
")",
":",
"try",
":",
"if",
"(",
"not",
"isinstance",
"(",
"profile",
",",
"ImageCmsProfile",
")",
")",
":",
"profile",
"=",
"ImageCmsProfile",
"(",
"profile",
")",
"return",
"(",
"profile",
".",
"profile",
".",
"product_manufacturer",
"+",
"'\\n'",
")",
"except",
"(",
"AttributeError",
",",
"IOError",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"v",
":",
"raise",
"PyCMSError",
"(",
"v",
")"
] | gets the manufacturer for the given profile . | train | false |
24,392 | def test_memcached(host, port):
try:
s = socket.socket()
s.connect((host, port))
return True
except Exception as exc:
log.critical(('Failed to connect to memcached (%r): %s' % ((host, port), exc)))
return False
finally:
s.close()
| [
"def",
"test_memcached",
"(",
"host",
",",
"port",
")",
":",
"try",
":",
"s",
"=",
"socket",
".",
"socket",
"(",
")",
"s",
".",
"connect",
"(",
"(",
"host",
",",
"port",
")",
")",
"return",
"True",
"except",
"Exception",
"as",
"exc",
":",
"log",
".",
"critical",
"(",
"(",
"'Failed to connect to memcached (%r): %s'",
"%",
"(",
"(",
"host",
",",
"port",
")",
",",
"exc",
")",
")",
")",
"return",
"False",
"finally",
":",
"s",
".",
"close",
"(",
")"
] | connect to memcached . | train | false |
24,395 | def subclass(cls):
for (name, method) in cls.__dict__.iteritems():
if hasattr(method, 'override'):
found = False
for base_class in inspect.getmro(cls)[1:]:
if (name in base_class.__dict__):
if (not method.__doc__):
method.__doc__ = base_class.__dict__[name].__doc__
found = True
break
assert found, ('"%s.%s" not found in any base class' % (cls.__name__, name))
return cls
| [
"def",
"subclass",
"(",
"cls",
")",
":",
"for",
"(",
"name",
",",
"method",
")",
"in",
"cls",
".",
"__dict__",
".",
"iteritems",
"(",
")",
":",
"if",
"hasattr",
"(",
"method",
",",
"'override'",
")",
":",
"found",
"=",
"False",
"for",
"base_class",
"in",
"inspect",
".",
"getmro",
"(",
"cls",
")",
"[",
"1",
":",
"]",
":",
"if",
"(",
"name",
"in",
"base_class",
".",
"__dict__",
")",
":",
"if",
"(",
"not",
"method",
".",
"__doc__",
")",
":",
"method",
".",
"__doc__",
"=",
"base_class",
".",
"__dict__",
"[",
"name",
"]",
".",
"__doc__",
"found",
"=",
"True",
"break",
"assert",
"found",
",",
"(",
"'\"%s.%s\" not found in any base class'",
"%",
"(",
"cls",
".",
"__name__",
",",
"name",
")",
")",
"return",
"cls"
] | verify all @override methods use a class decorator to find the methods class . | train | false |
24,396 | def get_all_config():
try:
path = ((os.path.expanduser('~') + os.sep) + '.rainbow_config.json')
data = load_config(path)
data.pop('ONLY_LIST', None)
data.pop('IGNORE_LIST', None)
data.pop('FORMAT', None)
data.pop('QUOTE_FORMAT', None)
data.pop('NOTIFY_FORMAT', None)
return data
except:
return []
| [
"def",
"get_all_config",
"(",
")",
":",
"try",
":",
"path",
"=",
"(",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"+",
"os",
".",
"sep",
")",
"+",
"'.rainbow_config.json'",
")",
"data",
"=",
"load_config",
"(",
"path",
")",
"data",
".",
"pop",
"(",
"'ONLY_LIST'",
",",
"None",
")",
"data",
".",
"pop",
"(",
"'IGNORE_LIST'",
",",
"None",
")",
"data",
".",
"pop",
"(",
"'FORMAT'",
",",
"None",
")",
"data",
".",
"pop",
"(",
"'QUOTE_FORMAT'",
",",
"None",
")",
"data",
".",
"pop",
"(",
"'NOTIFY_FORMAT'",
",",
"None",
")",
"return",
"data",
"except",
":",
"return",
"[",
"]"
] | get all config . | train | false |
24,398 | def next_char(input_iter):
for ch in input_iter:
if (ch != u'\\'):
(yield (ch, False))
continue
ch = next(input_iter)
representative = ESCAPE_MAPPINGS.get(ch, ch)
if (representative is None):
continue
(yield (representative, True))
| [
"def",
"next_char",
"(",
"input_iter",
")",
":",
"for",
"ch",
"in",
"input_iter",
":",
"if",
"(",
"ch",
"!=",
"u'\\\\'",
")",
":",
"(",
"yield",
"(",
"ch",
",",
"False",
")",
")",
"continue",
"ch",
"=",
"next",
"(",
"input_iter",
")",
"representative",
"=",
"ESCAPE_MAPPINGS",
".",
"get",
"(",
"ch",
",",
"ch",
")",
"if",
"(",
"representative",
"is",
"None",
")",
":",
"continue",
"(",
"yield",
"(",
"representative",
",",
"True",
")",
")"
] | an iterator that yields the next character from "pattern_iter" . | train | false |
24,402 | def connect_toggle(toggle, fn):
toggle.toggled.connect(fn)
| [
"def",
"connect_toggle",
"(",
"toggle",
",",
"fn",
")",
":",
"toggle",
".",
"toggled",
".",
"connect",
"(",
"fn",
")"
] | connect a toggle button to a function . | train | false |
24,404 | def clearScreen():
sys.stdout.write((((SEQ_PREFIX + '[H') + SEQ_PREFIX) + '[2J'))
| [
"def",
"clearScreen",
"(",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"(",
"(",
"SEQ_PREFIX",
"+",
"'[H'",
")",
"+",
"SEQ_PREFIX",
")",
"+",
"'[2J'",
")",
")"
] | clears the screen . | train | false |
24,405 | def get_rdataset(dataname, package='datasets', cache=False):
data_base_url = (('https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/' + package) + '/')
docs_base_url = (('https://raw.github.com/vincentarelbundock/Rdatasets/master/doc/' + package) + '/rst/')
cache = _get_cache(cache)
(data, from_cache) = _get_data(data_base_url, dataname, cache)
data = read_csv(data, index_col=0)
data = _maybe_reset_index(data)
title = _get_dataset_meta(dataname, package, cache)
(doc, _) = _get_data(docs_base_url, dataname, cache, 'rst')
return Dataset(data=data, __doc__=doc.read(), package=package, title=title, from_cache=from_cache)
| [
"def",
"get_rdataset",
"(",
"dataname",
",",
"package",
"=",
"'datasets'",
",",
"cache",
"=",
"False",
")",
":",
"data_base_url",
"=",
"(",
"(",
"'https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/'",
"+",
"package",
")",
"+",
"'/'",
")",
"docs_base_url",
"=",
"(",
"(",
"'https://raw.github.com/vincentarelbundock/Rdatasets/master/doc/'",
"+",
"package",
")",
"+",
"'/rst/'",
")",
"cache",
"=",
"_get_cache",
"(",
"cache",
")",
"(",
"data",
",",
"from_cache",
")",
"=",
"_get_data",
"(",
"data_base_url",
",",
"dataname",
",",
"cache",
")",
"data",
"=",
"read_csv",
"(",
"data",
",",
"index_col",
"=",
"0",
")",
"data",
"=",
"_maybe_reset_index",
"(",
"data",
")",
"title",
"=",
"_get_dataset_meta",
"(",
"dataname",
",",
"package",
",",
"cache",
")",
"(",
"doc",
",",
"_",
")",
"=",
"_get_data",
"(",
"docs_base_url",
",",
"dataname",
",",
"cache",
",",
"'rst'",
")",
"return",
"Dataset",
"(",
"data",
"=",
"data",
",",
"__doc__",
"=",
"doc",
".",
"read",
"(",
")",
",",
"package",
"=",
"package",
",",
"title",
"=",
"title",
",",
"from_cache",
"=",
"from_cache",
")"
] | download and return r dataset parameters dataname : str the name of the dataset you want to download package : str the package in which the dataset is found . | train | false |
24,406 | def _generateFallbackKoLangInfo(langinfo_db, koLangInst):
class FallbackKoLangInfo(LangInfo, ):
conforms_to_bases = ['Text']
default_encoding = 'utf-8'
def __init__(self, db, koLang):
LangInfo.__init__(self, db)
self.name = koLang.name
if koLang.defaultExtension:
self.exts = [koLang.defaultExtension]
return FallbackKoLangInfo(langinfo_db, koLangInst)
| [
"def",
"_generateFallbackKoLangInfo",
"(",
"langinfo_db",
",",
"koLangInst",
")",
":",
"class",
"FallbackKoLangInfo",
"(",
"LangInfo",
",",
")",
":",
"conforms_to_bases",
"=",
"[",
"'Text'",
"]",
"default_encoding",
"=",
"'utf-8'",
"def",
"__init__",
"(",
"self",
",",
"db",
",",
"koLang",
")",
":",
"LangInfo",
".",
"__init__",
"(",
"self",
",",
"db",
")",
"self",
".",
"name",
"=",
"koLang",
".",
"name",
"if",
"koLang",
".",
"defaultExtension",
":",
"self",
".",
"exts",
"=",
"[",
"koLang",
".",
"defaultExtension",
"]",
"return",
"FallbackKoLangInfo",
"(",
"langinfo_db",
",",
"koLangInst",
")"
] | generate a langinfo instance from the koilanguage instance . | train | false |
24,407 | def _create_sequence(cr, seq_name, number_increment, number_next):
if (number_increment == 0):
raise UserError(_('Step must not be zero.'))
sql = ('CREATE SEQUENCE %s INCREMENT BY %%s START WITH %%s' % seq_name)
cr.execute(sql, (number_increment, number_next))
| [
"def",
"_create_sequence",
"(",
"cr",
",",
"seq_name",
",",
"number_increment",
",",
"number_next",
")",
":",
"if",
"(",
"number_increment",
"==",
"0",
")",
":",
"raise",
"UserError",
"(",
"_",
"(",
"'Step must not be zero.'",
")",
")",
"sql",
"=",
"(",
"'CREATE SEQUENCE %s INCREMENT BY %%s START WITH %%s'",
"%",
"seq_name",
")",
"cr",
".",
"execute",
"(",
"sql",
",",
"(",
"number_increment",
",",
"number_next",
")",
")"
] | create a postresql sequence . | train | false |
24,408 | def calculate_base_branch(version, path):
if (not (is_release(version) or is_weekly_release(version) or is_pre_release(version))):
raise NotARelease()
repo = Repo(path=path, search_parent_directories=True)
existing_tags = [tag for tag in repo.tags if (tag.name == version)]
if existing_tags:
raise TagExists()
base_branch_name = 'master'
repo.git.checkout(base_branch_name)
return (branch for branch in repo.branches if (branch.name == base_branch_name)).next()
| [
"def",
"calculate_base_branch",
"(",
"version",
",",
"path",
")",
":",
"if",
"(",
"not",
"(",
"is_release",
"(",
"version",
")",
"or",
"is_weekly_release",
"(",
"version",
")",
"or",
"is_pre_release",
"(",
"version",
")",
")",
")",
":",
"raise",
"NotARelease",
"(",
")",
"repo",
"=",
"Repo",
"(",
"path",
"=",
"path",
",",
"search_parent_directories",
"=",
"True",
")",
"existing_tags",
"=",
"[",
"tag",
"for",
"tag",
"in",
"repo",
".",
"tags",
"if",
"(",
"tag",
".",
"name",
"==",
"version",
")",
"]",
"if",
"existing_tags",
":",
"raise",
"TagExists",
"(",
")",
"base_branch_name",
"=",
"'master'",
"repo",
".",
"git",
".",
"checkout",
"(",
"base_branch_name",
")",
"return",
"(",
"branch",
"for",
"branch",
"in",
"repo",
".",
"branches",
"if",
"(",
"branch",
".",
"name",
"==",
"base_branch_name",
")",
")",
".",
"next",
"(",
")"
] | the branch a release branch is created from depends on the release type and sometimes which pre-releases have preceeded this . | train | false |
24,409 | def _create_array_of_type(t):
if (t in _array_types):
return _array_types[t]()
array_type_name = ('ArrayOf%s' % t)
array_type = type(array_type_name, (DataObject,), {})
def __init__(self):
super(array_type, self).__init__(array_type_name)
setattr(self, t, [])
setattr(array_type, '__init__', __init__)
_array_types[t] = array_type
return array_type()
| [
"def",
"_create_array_of_type",
"(",
"t",
")",
":",
"if",
"(",
"t",
"in",
"_array_types",
")",
":",
"return",
"_array_types",
"[",
"t",
"]",
"(",
")",
"array_type_name",
"=",
"(",
"'ArrayOf%s'",
"%",
"t",
")",
"array_type",
"=",
"type",
"(",
"array_type_name",
",",
"(",
"DataObject",
",",
")",
",",
"{",
"}",
")",
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"array_type",
",",
"self",
")",
".",
"__init__",
"(",
"array_type_name",
")",
"setattr",
"(",
"self",
",",
"t",
",",
"[",
"]",
")",
"setattr",
"(",
"array_type",
",",
"'__init__'",
",",
"__init__",
")",
"_array_types",
"[",
"t",
"]",
"=",
"array_type",
"return",
"array_type",
"(",
")"
] | returns an array to contain objects of type t . | train | false |
24,411 | def _get_service_manager(host_reference):
return host_reference.configManager.serviceSystem
| [
"def",
"_get_service_manager",
"(",
"host_reference",
")",
":",
"return",
"host_reference",
".",
"configManager",
".",
"serviceSystem"
] | helper function that returns a service manager object from a given host object . | train | false |
24,412 | def reset():
_runtime.reset()
| [
"def",
"reset",
"(",
")",
":",
"_runtime",
".",
"reset",
"(",
")"
] | reset current head to the specified state . | train | false |
24,413 | def _translate_ocsp_query(cert_path, ocsp_output, ocsp_errors):
states = ('good', 'revoked', 'unknown')
patterns = ['{0}: (WARNING.*)?{1}'.format(cert_path, s) for s in states]
(good, revoked, unknown) = (re.search(p, ocsp_output, flags=re.DOTALL) for p in patterns)
warning = (good.group(1) if good else None)
if ((not ('Response verify OK' in ocsp_errors)) or (good and warning) or unknown):
logger.info('Revocation status for %s is unknown', cert_path)
logger.debug('Uncertain output:\n%s\nstderr:\n%s', ocsp_output, ocsp_errors)
return False
elif (good and (not warning)):
return False
elif revoked:
warning = revoked.group(1)
if warning:
logger.info('OCSP revocation warning: %s', warning)
return True
else:
logger.warn('Unable to properly parse OCSP output: %s\nstderr:%s', ocsp_output, ocsp_errors)
return False
| [
"def",
"_translate_ocsp_query",
"(",
"cert_path",
",",
"ocsp_output",
",",
"ocsp_errors",
")",
":",
"states",
"=",
"(",
"'good'",
",",
"'revoked'",
",",
"'unknown'",
")",
"patterns",
"=",
"[",
"'{0}: (WARNING.*)?{1}'",
".",
"format",
"(",
"cert_path",
",",
"s",
")",
"for",
"s",
"in",
"states",
"]",
"(",
"good",
",",
"revoked",
",",
"unknown",
")",
"=",
"(",
"re",
".",
"search",
"(",
"p",
",",
"ocsp_output",
",",
"flags",
"=",
"re",
".",
"DOTALL",
")",
"for",
"p",
"in",
"patterns",
")",
"warning",
"=",
"(",
"good",
".",
"group",
"(",
"1",
")",
"if",
"good",
"else",
"None",
")",
"if",
"(",
"(",
"not",
"(",
"'Response verify OK'",
"in",
"ocsp_errors",
")",
")",
"or",
"(",
"good",
"and",
"warning",
")",
"or",
"unknown",
")",
":",
"logger",
".",
"info",
"(",
"'Revocation status for %s is unknown'",
",",
"cert_path",
")",
"logger",
".",
"debug",
"(",
"'Uncertain output:\\n%s\\nstderr:\\n%s'",
",",
"ocsp_output",
",",
"ocsp_errors",
")",
"return",
"False",
"elif",
"(",
"good",
"and",
"(",
"not",
"warning",
")",
")",
":",
"return",
"False",
"elif",
"revoked",
":",
"warning",
"=",
"revoked",
".",
"group",
"(",
"1",
")",
"if",
"warning",
":",
"logger",
".",
"info",
"(",
"'OCSP revocation warning: %s'",
",",
"warning",
")",
"return",
"True",
"else",
":",
"logger",
".",
"warn",
"(",
"'Unable to properly parse OCSP output: %s\\nstderr:%s'",
",",
"ocsp_output",
",",
"ocsp_errors",
")",
"return",
"False"
] | parse openssls weird output to work out what it means . | train | false |
24,414 | def find_method(rpc_call):
method_lists = [rtorrent.methods, rtorrent.file.methods, rtorrent.tracker.methods, rtorrent.peer.methods, rtorrent.torrent.methods]
for l in method_lists:
for m in l:
if (m.rpc_call.lower() == rpc_call.lower()):
return m
return (-1)
| [
"def",
"find_method",
"(",
"rpc_call",
")",
":",
"method_lists",
"=",
"[",
"rtorrent",
".",
"methods",
",",
"rtorrent",
".",
"file",
".",
"methods",
",",
"rtorrent",
".",
"tracker",
".",
"methods",
",",
"rtorrent",
".",
"peer",
".",
"methods",
",",
"rtorrent",
".",
"torrent",
".",
"methods",
"]",
"for",
"l",
"in",
"method_lists",
":",
"for",
"m",
"in",
"l",
":",
"if",
"(",
"m",
".",
"rpc_call",
".",
"lower",
"(",
")",
"==",
"rpc_call",
".",
"lower",
"(",
")",
")",
":",
"return",
"m",
"return",
"(",
"-",
"1",
")"
] | return l{method} instance associated with given rpc call . | train | false |
24,415 | def _to_ANP_poly(f, ring):
domain = ring.domain
f_ = ring.zero
if isinstance(f.ring.domain, PolynomialRing):
for (monom, coeff) in f.iterterms():
for (mon, coef) in coeff.iterterms():
m = ((monom[0],) + mon)
c = domain(([domain.domain(coef)] + ([0] * monom[1])))
if (m not in f_):
f_[m] = c
else:
f_[m] += c
else:
for (monom, coeff) in f.iterterms():
m = (monom[0],)
c = domain(([domain.domain(coeff)] + ([0] * monom[1])))
if (m not in f_):
f_[m] = c
else:
f_[m] += c
return f_
| [
"def",
"_to_ANP_poly",
"(",
"f",
",",
"ring",
")",
":",
"domain",
"=",
"ring",
".",
"domain",
"f_",
"=",
"ring",
".",
"zero",
"if",
"isinstance",
"(",
"f",
".",
"ring",
".",
"domain",
",",
"PolynomialRing",
")",
":",
"for",
"(",
"monom",
",",
"coeff",
")",
"in",
"f",
".",
"iterterms",
"(",
")",
":",
"for",
"(",
"mon",
",",
"coef",
")",
"in",
"coeff",
".",
"iterterms",
"(",
")",
":",
"m",
"=",
"(",
"(",
"monom",
"[",
"0",
"]",
",",
")",
"+",
"mon",
")",
"c",
"=",
"domain",
"(",
"(",
"[",
"domain",
".",
"domain",
"(",
"coef",
")",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"monom",
"[",
"1",
"]",
")",
")",
")",
"if",
"(",
"m",
"not",
"in",
"f_",
")",
":",
"f_",
"[",
"m",
"]",
"=",
"c",
"else",
":",
"f_",
"[",
"m",
"]",
"+=",
"c",
"else",
":",
"for",
"(",
"monom",
",",
"coeff",
")",
"in",
"f",
".",
"iterterms",
"(",
")",
":",
"m",
"=",
"(",
"monom",
"[",
"0",
"]",
",",
")",
"c",
"=",
"domain",
"(",
"(",
"[",
"domain",
".",
"domain",
"(",
"coeff",
")",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"monom",
"[",
"1",
"]",
")",
")",
")",
"if",
"(",
"m",
"not",
"in",
"f_",
")",
":",
"f_",
"[",
"m",
"]",
"=",
"c",
"else",
":",
"f_",
"[",
"m",
"]",
"+=",
"c",
"return",
"f_"
] | convert a polynomial f in mathbb z[x_1 . | train | false |
24,416 | def set_num_instances(instances, server=None, version=None):
if (not isinstance(instances, (long, int))):
raise TypeError("'instances' arg must be of type long or int.")
req = servers_service_pb.SetNumInstancesRequest()
req.set_instances(instances)
if server:
req.set_server(server)
if version:
req.set_version(version)
resp = servers_service_pb.SetNumInstancesResponse()
try:
apiproxy_stub_map.MakeSyncCall('servers', 'SetNumInstances', req, resp)
except apiproxy_errors.ApplicationError as e:
if (e.application_error == servers_service_pb.ServersServiceError.INVALID_VERSION):
raise InvalidVersionError()
elif (e.application_error == servers_service_pb.ServersServiceError.TRANSIENT_ERROR):
raise TransientError()
else:
raise Error()
| [
"def",
"set_num_instances",
"(",
"instances",
",",
"server",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"instances",
",",
"(",
"long",
",",
"int",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"'instances' arg must be of type long or int.\"",
")",
"req",
"=",
"servers_service_pb",
".",
"SetNumInstancesRequest",
"(",
")",
"req",
".",
"set_instances",
"(",
"instances",
")",
"if",
"server",
":",
"req",
".",
"set_server",
"(",
"server",
")",
"if",
"version",
":",
"req",
".",
"set_version",
"(",
"version",
")",
"resp",
"=",
"servers_service_pb",
".",
"SetNumInstancesResponse",
"(",
")",
"try",
":",
"apiproxy_stub_map",
".",
"MakeSyncCall",
"(",
"'servers'",
",",
"'SetNumInstances'",
",",
"req",
",",
"resp",
")",
"except",
"apiproxy_errors",
".",
"ApplicationError",
"as",
"e",
":",
"if",
"(",
"e",
".",
"application_error",
"==",
"servers_service_pb",
".",
"ServersServiceError",
".",
"INVALID_VERSION",
")",
":",
"raise",
"InvalidVersionError",
"(",
")",
"elif",
"(",
"e",
".",
"application_error",
"==",
"servers_service_pb",
".",
"ServersServiceError",
".",
"TRANSIENT_ERROR",
")",
":",
"raise",
"TransientError",
"(",
")",
"else",
":",
"raise",
"Error",
"(",
")"
] | sets the number of instances on the server and version . | train | false |
24,417 | @pytest.fixture(scope=u'function')
def remove_output_folder(request):
def finalizer_remove_output_folder():
if os.path.exists(u'output_folder'):
utils.rmtree(u'output_folder')
request.addfinalizer(finalizer_remove_output_folder)
| [
"@",
"pytest",
".",
"fixture",
"(",
"scope",
"=",
"u'function'",
")",
"def",
"remove_output_folder",
"(",
"request",
")",
":",
"def",
"finalizer_remove_output_folder",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"u'output_folder'",
")",
":",
"utils",
".",
"rmtree",
"(",
"u'output_folder'",
")",
"request",
".",
"addfinalizer",
"(",
"finalizer_remove_output_folder",
")"
] | remove the output folder in case it exists on disk . | train | false |
24,418 | def _dotUnquoter(line):
if line.startswith('..'):
return line[1:]
return line
| [
"def",
"_dotUnquoter",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'..'",
")",
":",
"return",
"line",
"[",
"1",
":",
"]",
"return",
"line"
] | remove a byte-stuffed termination character at the beginning of a line if present . | train | false |
24,419 | @cache(request.env.path_info, time_expire=5, cache_model=cache.ram)
def cache_controller_in_ram():
t = time.ctime()
return dict(time=t, link=A('click to reload', _href=URL(r=request)))
| [
"@",
"cache",
"(",
"request",
".",
"env",
".",
"path_info",
",",
"time_expire",
"=",
"5",
",",
"cache_model",
"=",
"cache",
".",
"ram",
")",
"def",
"cache_controller_in_ram",
"(",
")",
":",
"t",
"=",
"time",
".",
"ctime",
"(",
")",
"return",
"dict",
"(",
"time",
"=",
"t",
",",
"link",
"=",
"A",
"(",
"'click to reload'",
",",
"_href",
"=",
"URL",
"(",
"r",
"=",
"request",
")",
")",
")"
] | cache the output of the controller in ram . | train | false |
24,420 | def extend_super_fences(md, name, language, formatter):
if (not hasattr(md, u'superfences')):
md.superfences = []
md.superfences.append({u'name': name, u'test': (lambda l, language=language: (language == l)), u'formatter': formatter})
| [
"def",
"extend_super_fences",
"(",
"md",
",",
"name",
",",
"language",
",",
"formatter",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"md",
",",
"u'superfences'",
")",
")",
":",
"md",
".",
"superfences",
"=",
"[",
"]",
"md",
".",
"superfences",
".",
"append",
"(",
"{",
"u'name'",
":",
"name",
",",
"u'test'",
":",
"(",
"lambda",
"l",
",",
"language",
"=",
"language",
":",
"(",
"language",
"==",
"l",
")",
")",
",",
"u'formatter'",
":",
"formatter",
"}",
")"
] | extend superfences with the given name . | train | false |
24,423 | def page_index(request):
_shared_login(request)
pagevars = _gamestats()
return render(request, 'index.html', pagevars)
| [
"def",
"page_index",
"(",
"request",
")",
":",
"_shared_login",
"(",
"request",
")",
"pagevars",
"=",
"_gamestats",
"(",
")",
"return",
"render",
"(",
"request",
",",
"'index.html'",
",",
"pagevars",
")"
] | main root page . | train | false |
24,424 | def _getRecentTile(layer, coord, format):
key = (layer, coord, format)
(body, use_by) = _recent_tiles['hash'].get(key, (None, 0))
if (body is None):
return None
if (time() < use_by):
logging.debug('TileStache.Core._addRecentTile() found tile in recent tiles: %s', key)
return body
try:
del _recent_tiles['hash'][key]
except KeyError:
pass
return None
| [
"def",
"_getRecentTile",
"(",
"layer",
",",
"coord",
",",
"format",
")",
":",
"key",
"=",
"(",
"layer",
",",
"coord",
",",
"format",
")",
"(",
"body",
",",
"use_by",
")",
"=",
"_recent_tiles",
"[",
"'hash'",
"]",
".",
"get",
"(",
"key",
",",
"(",
"None",
",",
"0",
")",
")",
"if",
"(",
"body",
"is",
"None",
")",
":",
"return",
"None",
"if",
"(",
"time",
"(",
")",
"<",
"use_by",
")",
":",
"logging",
".",
"debug",
"(",
"'TileStache.Core._addRecentTile() found tile in recent tiles: %s'",
",",
"key",
")",
"return",
"body",
"try",
":",
"del",
"_recent_tiles",
"[",
"'hash'",
"]",
"[",
"key",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"None"
] | return the body of a recent tile . | train | false |
24,425 | def refmat(p, q):
p.normalize()
q.normalize()
if ((p - q).norm() < 1e-05):
return numpy.identity(3)
pq = (p - q)
pq.normalize()
b = pq.get_array()
b.shape = (3, 1)
i = numpy.identity(3)
ref = (i - (2 * numpy.dot(b, numpy.transpose(b))))
return ref
| [
"def",
"refmat",
"(",
"p",
",",
"q",
")",
":",
"p",
".",
"normalize",
"(",
")",
"q",
".",
"normalize",
"(",
")",
"if",
"(",
"(",
"p",
"-",
"q",
")",
".",
"norm",
"(",
")",
"<",
"1e-05",
")",
":",
"return",
"numpy",
".",
"identity",
"(",
"3",
")",
"pq",
"=",
"(",
"p",
"-",
"q",
")",
"pq",
".",
"normalize",
"(",
")",
"b",
"=",
"pq",
".",
"get_array",
"(",
")",
"b",
".",
"shape",
"=",
"(",
"3",
",",
"1",
")",
"i",
"=",
"numpy",
".",
"identity",
"(",
"3",
")",
"ref",
"=",
"(",
"i",
"-",
"(",
"2",
"*",
"numpy",
".",
"dot",
"(",
"b",
",",
"numpy",
".",
"transpose",
"(",
"b",
")",
")",
")",
")",
"return",
"ref"
] | return a matrix that mirrors p onto q . | train | false |
24,426 | def markFailed(epObj):
log_str = u''
try:
with epObj.lock:
quality = Quality.splitCompositeStatus(epObj.status)[1]
epObj.status = Quality.compositeStatus(FAILED, quality)
epObj.saveToDB()
except EpisodeNotFoundException as e:
logger.log((u'Unable to get episode, please set its status manually: ' + ex(e)), logger.WARNING)
return log_str
| [
"def",
"markFailed",
"(",
"epObj",
")",
":",
"log_str",
"=",
"u''",
"try",
":",
"with",
"epObj",
".",
"lock",
":",
"quality",
"=",
"Quality",
".",
"splitCompositeStatus",
"(",
"epObj",
".",
"status",
")",
"[",
"1",
"]",
"epObj",
".",
"status",
"=",
"Quality",
".",
"compositeStatus",
"(",
"FAILED",
",",
"quality",
")",
"epObj",
".",
"saveToDB",
"(",
")",
"except",
"EpisodeNotFoundException",
"as",
"e",
":",
"logger",
".",
"log",
"(",
"(",
"u'Unable to get episode, please set its status manually: '",
"+",
"ex",
"(",
"e",
")",
")",
",",
"logger",
".",
"WARNING",
")",
"return",
"log_str"
] | mark an episode as failed . | train | false |
24,428 | def _is_bad_path(path, base):
return (not resolved(joinpath(base, path)).startswith(base))
| [
"def",
"_is_bad_path",
"(",
"path",
",",
"base",
")",
":",
"return",
"(",
"not",
"resolved",
"(",
"joinpath",
"(",
"base",
",",
"path",
")",
")",
".",
"startswith",
"(",
"base",
")",
")"
] | is path outside base? . | train | false |
24,429 | def _get_subcollections(collection):
for name in collection.database.collection_names():
cleaned = name[:name.rfind('.')]
if ((cleaned != collection.name) and cleaned.startswith(collection.name)):
(yield cleaned)
| [
"def",
"_get_subcollections",
"(",
"collection",
")",
":",
"for",
"name",
"in",
"collection",
".",
"database",
".",
"collection_names",
"(",
")",
":",
"cleaned",
"=",
"name",
"[",
":",
"name",
".",
"rfind",
"(",
"'.'",
")",
"]",
"if",
"(",
"(",
"cleaned",
"!=",
"collection",
".",
"name",
")",
"and",
"cleaned",
".",
"startswith",
"(",
"collection",
".",
"name",
")",
")",
":",
"(",
"yield",
"cleaned",
")"
] | returns all sub-collections of collection . | train | false |
24,431 | def album_distance(items, album_info, mapping):
from beets.autotag.hooks import Distance
dist = Distance()
for plugin in find_plugins():
dist.update(plugin.album_distance(items, album_info, mapping))
return dist
| [
"def",
"album_distance",
"(",
"items",
",",
"album_info",
",",
"mapping",
")",
":",
"from",
"beets",
".",
"autotag",
".",
"hooks",
"import",
"Distance",
"dist",
"=",
"Distance",
"(",
")",
"for",
"plugin",
"in",
"find_plugins",
"(",
")",
":",
"dist",
".",
"update",
"(",
"plugin",
".",
"album_distance",
"(",
"items",
",",
"album_info",
",",
"mapping",
")",
")",
"return",
"dist"
] | returns the album distance calculated by plugins . | train | false |
24,433 | def image_vacuum(name):
name = name.lower()
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
images = []
for state in __salt__['state.show_lowstate']():
if ('state' not in state):
continue
if (state['state'] != __virtualname__):
continue
if (state['fun'] not in ['image_present']):
continue
if ('name' in state):
images.append(state['name'])
for image_uuid in __salt__['vmadm.list'](order='image_uuid'):
if (image_uuid in images):
continue
images.append(image_uuid)
ret['result'] = True
for image_uuid in __salt__['imgadm.list']():
if (image_uuid in images):
continue
if (image_uuid in __salt__['imgadm.delete'](image_uuid)):
ret['changes'][image_uuid] = None
else:
ret['result'] = False
ret['comment'] = 'failed to delete images'
if (ret['result'] and (len(ret['changes']) == 0)):
ret['comment'] = 'no images deleted'
elif (ret['result'] and (len(ret['changes']) > 0)):
ret['comment'] = 'images deleted'
return ret
| [
"def",
"image_vacuum",
"(",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"images",
"=",
"[",
"]",
"for",
"state",
"in",
"__salt__",
"[",
"'state.show_lowstate'",
"]",
"(",
")",
":",
"if",
"(",
"'state'",
"not",
"in",
"state",
")",
":",
"continue",
"if",
"(",
"state",
"[",
"'state'",
"]",
"!=",
"__virtualname__",
")",
":",
"continue",
"if",
"(",
"state",
"[",
"'fun'",
"]",
"not",
"in",
"[",
"'image_present'",
"]",
")",
":",
"continue",
"if",
"(",
"'name'",
"in",
"state",
")",
":",
"images",
".",
"append",
"(",
"state",
"[",
"'name'",
"]",
")",
"for",
"image_uuid",
"in",
"__salt__",
"[",
"'vmadm.list'",
"]",
"(",
"order",
"=",
"'image_uuid'",
")",
":",
"if",
"(",
"image_uuid",
"in",
"images",
")",
":",
"continue",
"images",
".",
"append",
"(",
"image_uuid",
")",
"ret",
"[",
"'result'",
"]",
"=",
"True",
"for",
"image_uuid",
"in",
"__salt__",
"[",
"'imgadm.list'",
"]",
"(",
")",
":",
"if",
"(",
"image_uuid",
"in",
"images",
")",
":",
"continue",
"if",
"(",
"image_uuid",
"in",
"__salt__",
"[",
"'imgadm.delete'",
"]",
"(",
"image_uuid",
")",
")",
":",
"ret",
"[",
"'changes'",
"]",
"[",
"image_uuid",
"]",
"=",
"None",
"else",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
"[",
"'comment'",
"]",
"=",
"'failed to delete images'",
"if",
"(",
"ret",
"[",
"'result'",
"]",
"and",
"(",
"len",
"(",
"ret",
"[",
"'changes'",
"]",
")",
"==",
"0",
")",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'no images deleted'",
"elif",
"(",
"ret",
"[",
"'result'",
"]",
"and",
"(",
"len",
"(",
"ret",
"[",
"'changes'",
"]",
")",
">",
"0",
")",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'images deleted'",
"return",
"ret"
] | delete images not in use or installed via image_present . | train | false |
24,434 | def get_missing_reqs(dist, installed_dists):
installed_names = set((d.project_name.lower() for d in installed_dists))
missing_requirements = set()
for requirement in dist.requires():
if (requirement.project_name.lower() not in installed_names):
missing_requirements.add(requirement)
(yield requirement)
| [
"def",
"get_missing_reqs",
"(",
"dist",
",",
"installed_dists",
")",
":",
"installed_names",
"=",
"set",
"(",
"(",
"d",
".",
"project_name",
".",
"lower",
"(",
")",
"for",
"d",
"in",
"installed_dists",
")",
")",
"missing_requirements",
"=",
"set",
"(",
")",
"for",
"requirement",
"in",
"dist",
".",
"requires",
"(",
")",
":",
"if",
"(",
"requirement",
".",
"project_name",
".",
"lower",
"(",
")",
"not",
"in",
"installed_names",
")",
":",
"missing_requirements",
".",
"add",
"(",
"requirement",
")",
"(",
"yield",
"requirement",
")"
] | return all of the requirements of dist that arent present in installed_dists . | train | false |
24,435 | def normalize_so_name(name):
if ('cpython' in name):
return os.path.splitext(os.path.splitext(name)[0])[0]
return os.path.splitext(name)[0]
| [
"def",
"normalize_so_name",
"(",
"name",
")",
":",
"if",
"(",
"'cpython'",
"in",
"name",
")",
":",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"[",
"0",
"]"
] | handle different types of python installations . | train | true |
24,436 | def setastest(tf=True):
def set_test(t):
t.__test__ = tf
return t
return set_test
| [
"def",
"setastest",
"(",
"tf",
"=",
"True",
")",
":",
"def",
"set_test",
"(",
"t",
")",
":",
"t",
".",
"__test__",
"=",
"tf",
"return",
"t",
"return",
"set_test"
] | signals to nose that this function is or is not a test . | train | true |
24,437 | @deprecated(u'2.1')
def dict_delall(d, keys):
for key in keys:
try:
del d[key]
except KeyError:
pass
| [
"@",
"deprecated",
"(",
"u'2.1'",
")",
"def",
"dict_delall",
"(",
"d",
",",
"keys",
")",
":",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"del",
"d",
"[",
"key",
"]",
"except",
"KeyError",
":",
"pass"
] | delete all of the *keys* from the :class:dict *d* . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.