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 |
|---|---|---|---|---|---|
8,087
|
def addToCraftMenu(menu):
settings.ToolDialog().addPluginToMenu(menu, archive.getUntilDot(os.path.abspath(__file__)))
menu.add_separator()
directoryPath = skeinforge_craft.getPluginsDirectoryPath()
directoryFolders = settings.getFolders(directoryPath)
pluginFileNames = skeinforge_craft.getPluginFileNames()
for pluginFileName in pluginFileNames:
pluginFolderName = (pluginFileName + '_plugins')
pluginPath = os.path.join(directoryPath, pluginFileName)
if (pluginFolderName in directoryFolders):
addSubmenus(menu, pluginFileName, os.path.join(directoryPath, pluginFolderName), pluginPath)
else:
settings.ToolDialog().addPluginToMenu(menu, pluginPath)
|
[
"def",
"addToCraftMenu",
"(",
"menu",
")",
":",
"settings",
".",
"ToolDialog",
"(",
")",
".",
"addPluginToMenu",
"(",
"menu",
",",
"archive",
".",
"getUntilDot",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
")",
"menu",
".",
"add_separator",
"(",
")",
"directoryPath",
"=",
"skeinforge_craft",
".",
"getPluginsDirectoryPath",
"(",
")",
"directoryFolders",
"=",
"settings",
".",
"getFolders",
"(",
"directoryPath",
")",
"pluginFileNames",
"=",
"skeinforge_craft",
".",
"getPluginFileNames",
"(",
")",
"for",
"pluginFileName",
"in",
"pluginFileNames",
":",
"pluginFolderName",
"=",
"(",
"pluginFileName",
"+",
"'_plugins'",
")",
"pluginPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directoryPath",
",",
"pluginFileName",
")",
"if",
"(",
"pluginFolderName",
"in",
"directoryFolders",
")",
":",
"addSubmenus",
"(",
"menu",
",",
"pluginFileName",
",",
"os",
".",
"path",
".",
"join",
"(",
"directoryPath",
",",
"pluginFolderName",
")",
",",
"pluginPath",
")",
"else",
":",
"settings",
".",
"ToolDialog",
"(",
")",
".",
"addPluginToMenu",
"(",
"menu",
",",
"pluginPath",
")"
] |
add a craft plugin menu .
|
train
| false
|
8,088
|
def kill_group(pid, sig):
os.kill((- pid), sig)
|
[
"def",
"kill_group",
"(",
"pid",
",",
"sig",
")",
":",
"os",
".",
"kill",
"(",
"(",
"-",
"pid",
")",
",",
"sig",
")"
] |
send signal to process group : param pid: process id : param sig: signal to send .
|
train
| false
|
8,090
|
def enumerate_projects():
src_path = os.path.join(_DEFAULT_APP_DIR, 'src')
projects = {}
for project in os.listdir(src_path):
projects[project] = []
project_path = os.path.join(src_path, project)
for file in os.listdir(project_path):
if file.endswith('.gwt.xml'):
projects[project].append(file[:(-8)])
return projects
|
[
"def",
"enumerate_projects",
"(",
")",
":",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_DEFAULT_APP_DIR",
",",
"'src'",
")",
"projects",
"=",
"{",
"}",
"for",
"project",
"in",
"os",
".",
"listdir",
"(",
"src_path",
")",
":",
"projects",
"[",
"project",
"]",
"=",
"[",
"]",
"project_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"src_path",
",",
"project",
")",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"project_path",
")",
":",
"if",
"file",
".",
"endswith",
"(",
"'.gwt.xml'",
")",
":",
"projects",
"[",
"project",
"]",
".",
"append",
"(",
"file",
"[",
":",
"(",
"-",
"8",
")",
"]",
")",
"return",
"projects"
] |
list projects in _default_app_dir .
|
train
| false
|
8,091
|
def p_stmt_simple(p):
p[0] = p[1]
|
[
"def",
"p_stmt_simple",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] |
stmt : simple_stmt .
|
train
| false
|
8,092
|
def regex_replace(value='', pattern='', replacement='', ignorecase=False):
value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr')
if ignorecase:
flags = re.I
else:
flags = 0
_re = re.compile(pattern, flags=flags)
return _re.sub(replacement, value)
|
[
"def",
"regex_replace",
"(",
"value",
"=",
"''",
",",
"pattern",
"=",
"''",
",",
"replacement",
"=",
"''",
",",
"ignorecase",
"=",
"False",
")",
":",
"value",
"=",
"to_text",
"(",
"value",
",",
"errors",
"=",
"'surrogate_or_strict'",
",",
"nonstring",
"=",
"'simplerepr'",
")",
"if",
"ignorecase",
":",
"flags",
"=",
"re",
".",
"I",
"else",
":",
"flags",
"=",
"0",
"_re",
"=",
"re",
".",
"compile",
"(",
"pattern",
",",
"flags",
"=",
"flags",
")",
"return",
"_re",
".",
"sub",
"(",
"replacement",
",",
"value",
")"
] |
perform a re .
|
train
| false
|
8,093
|
def catch_error(func):
import amqp
try:
import pika.exceptions
connect_exceptions = (pika.exceptions.ConnectionClosed, pika.exceptions.AMQPConnectionError)
except ImportError:
connect_exceptions = ()
connect_exceptions += (select.error, socket.error, amqp.ConnectionError)
def wrap(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except connect_exceptions as e:
logging.error('RabbitMQ error: %r, reconnect.', e)
self.reconnect()
return func(self, *args, **kwargs)
return wrap
|
[
"def",
"catch_error",
"(",
"func",
")",
":",
"import",
"amqp",
"try",
":",
"import",
"pika",
".",
"exceptions",
"connect_exceptions",
"=",
"(",
"pika",
".",
"exceptions",
".",
"ConnectionClosed",
",",
"pika",
".",
"exceptions",
".",
"AMQPConnectionError",
")",
"except",
"ImportError",
":",
"connect_exceptions",
"=",
"(",
")",
"connect_exceptions",
"+=",
"(",
"select",
".",
"error",
",",
"socket",
".",
"error",
",",
"amqp",
".",
"ConnectionError",
")",
"def",
"wrap",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"connect_exceptions",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"'RabbitMQ error: %r, reconnect.'",
",",
"e",
")",
"self",
".",
"reconnect",
"(",
")",
"return",
"func",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"wrap"
] |
catch errors of rabbitmq then reconnect .
|
train
| true
|
8,094
|
def view_of(cls):
def view_of_decorator(view_cls):
cls._views.append(view_cls)
view_cls._view_of = cls
return view_cls
return view_of_decorator
|
[
"def",
"view_of",
"(",
"cls",
")",
":",
"def",
"view_of_decorator",
"(",
"view_cls",
")",
":",
"cls",
".",
"_views",
".",
"append",
"(",
"view_cls",
")",
"view_cls",
".",
"_view_of",
"=",
"cls",
"return",
"view_cls",
"return",
"view_of_decorator"
] |
register a class as a view of a thing .
|
train
| false
|
8,095
|
def __get_host(node, vm_):
if ((__get_ssh_interface(vm_) == 'private_ips') or (vm_['external_ip'] is None)):
ip_address = node.private_ips[0]
log.info('Salt node data. Private_ip: {0}'.format(ip_address))
else:
ip_address = node.public_ips[0]
log.info('Salt node data. Public_ip: {0}'.format(ip_address))
if (len(ip_address) > 0):
return ip_address
return node.name
|
[
"def",
"__get_host",
"(",
"node",
",",
"vm_",
")",
":",
"if",
"(",
"(",
"__get_ssh_interface",
"(",
"vm_",
")",
"==",
"'private_ips'",
")",
"or",
"(",
"vm_",
"[",
"'external_ip'",
"]",
"is",
"None",
")",
")",
":",
"ip_address",
"=",
"node",
".",
"private_ips",
"[",
"0",
"]",
"log",
".",
"info",
"(",
"'Salt node data. Private_ip: {0}'",
".",
"format",
"(",
"ip_address",
")",
")",
"else",
":",
"ip_address",
"=",
"node",
".",
"public_ips",
"[",
"0",
"]",
"log",
".",
"info",
"(",
"'Salt node data. Public_ip: {0}'",
".",
"format",
"(",
"ip_address",
")",
")",
"if",
"(",
"len",
"(",
"ip_address",
")",
">",
"0",
")",
":",
"return",
"ip_address",
"return",
"node",
".",
"name"
] |
return public ip .
|
train
| true
|
8,096
|
def dt_data_item(row=1, column=1, tableID='datatable'):
config = current.test_config
browser = config.browser
td = (".//*[@id='%s']/tbody/tr[%s]/td[%s]" % (tableID, row, column))
try:
elem = browser.find_element_by_xpath(td)
return elem.text
except:
return False
|
[
"def",
"dt_data_item",
"(",
"row",
"=",
"1",
",",
"column",
"=",
"1",
",",
"tableID",
"=",
"'datatable'",
")",
":",
"config",
"=",
"current",
".",
"test_config",
"browser",
"=",
"config",
".",
"browser",
"td",
"=",
"(",
"\".//*[@id='%s']/tbody/tr[%s]/td[%s]\"",
"%",
"(",
"tableID",
",",
"row",
",",
"column",
")",
")",
"try",
":",
"elem",
"=",
"browser",
".",
"find_element_by_xpath",
"(",
"td",
")",
"return",
"elem",
".",
"text",
"except",
":",
"return",
"False"
] |
returns the data found in the cell of the datatable .
|
train
| false
|
8,097
|
def aes_cbc_decrypt(data, key, iv):
expanded_key = key_expansion(key)
block_count = int(ceil((float(len(data)) / BLOCK_SIZE_BYTES)))
decrypted_data = []
previous_cipher_block = iv
for i in range(block_count):
block = data[(i * BLOCK_SIZE_BYTES):((i + 1) * BLOCK_SIZE_BYTES)]
block += ([0] * (BLOCK_SIZE_BYTES - len(block)))
decrypted_block = aes_decrypt(block, expanded_key)
decrypted_data += xor(decrypted_block, previous_cipher_block)
previous_cipher_block = block
decrypted_data = decrypted_data[:len(data)]
return decrypted_data
|
[
"def",
"aes_cbc_decrypt",
"(",
"data",
",",
"key",
",",
"iv",
")",
":",
"expanded_key",
"=",
"key_expansion",
"(",
"key",
")",
"block_count",
"=",
"int",
"(",
"ceil",
"(",
"(",
"float",
"(",
"len",
"(",
"data",
")",
")",
"/",
"BLOCK_SIZE_BYTES",
")",
")",
")",
"decrypted_data",
"=",
"[",
"]",
"previous_cipher_block",
"=",
"iv",
"for",
"i",
"in",
"range",
"(",
"block_count",
")",
":",
"block",
"=",
"data",
"[",
"(",
"i",
"*",
"BLOCK_SIZE_BYTES",
")",
":",
"(",
"(",
"i",
"+",
"1",
")",
"*",
"BLOCK_SIZE_BYTES",
")",
"]",
"block",
"+=",
"(",
"[",
"0",
"]",
"*",
"(",
"BLOCK_SIZE_BYTES",
"-",
"len",
"(",
"block",
")",
")",
")",
"decrypted_block",
"=",
"aes_decrypt",
"(",
"block",
",",
"expanded_key",
")",
"decrypted_data",
"+=",
"xor",
"(",
"decrypted_block",
",",
"previous_cipher_block",
")",
"previous_cipher_block",
"=",
"block",
"decrypted_data",
"=",
"decrypted_data",
"[",
":",
"len",
"(",
"data",
")",
"]",
"return",
"decrypted_data"
] |
decrypt with aes in cbc mode .
|
train
| false
|
8,101
|
def median_low(name, num, minimum=0, maximum=0, ref=None):
return calc(name, num, 'median_low', ref)
|
[
"def",
"median_low",
"(",
"name",
",",
"num",
",",
"minimum",
"=",
"0",
",",
"maximum",
"=",
"0",
",",
"ref",
"=",
"None",
")",
":",
"return",
"calc",
"(",
"name",
",",
"num",
",",
"'median_low'",
",",
"ref",
")"
] |
return the low median of numeric data .
|
train
| false
|
8,103
|
def mixing_expansion(G, S, T=None, weight=None):
num_cut_edges = cut_size(G, S, T=T, weight=weight)
num_total_edges = G.number_of_edges()
return (num_cut_edges / (2 * num_total_edges))
|
[
"def",
"mixing_expansion",
"(",
"G",
",",
"S",
",",
"T",
"=",
"None",
",",
"weight",
"=",
"None",
")",
":",
"num_cut_edges",
"=",
"cut_size",
"(",
"G",
",",
"S",
",",
"T",
"=",
"T",
",",
"weight",
"=",
"weight",
")",
"num_total_edges",
"=",
"G",
".",
"number_of_edges",
"(",
")",
"return",
"(",
"num_cut_edges",
"/",
"(",
"2",
"*",
"num_total_edges",
")",
")"
] |
returns the mixing expansion between two node sets .
|
train
| false
|
8,105
|
def zipf_rv(alpha, xmin=1, seed=None):
if (xmin < 1):
raise ValueError('xmin < 1')
if (alpha <= 1):
raise ValueError('a <= 1.0')
if (not (seed is None)):
random.seed(seed)
a1 = (alpha - 1.0)
b = (2 ** a1)
while True:
u = (1.0 - random.random())
v = random.random()
x = int((xmin * (u ** (- (1.0 / a1)))))
t = ((1.0 + (1.0 / x)) ** a1)
if ((((v * x) * (t - 1.0)) / (b - 1.0)) <= (t / b)):
break
return x
|
[
"def",
"zipf_rv",
"(",
"alpha",
",",
"xmin",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"if",
"(",
"xmin",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'xmin < 1'",
")",
"if",
"(",
"alpha",
"<=",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'a <= 1.0'",
")",
"if",
"(",
"not",
"(",
"seed",
"is",
"None",
")",
")",
":",
"random",
".",
"seed",
"(",
"seed",
")",
"a1",
"=",
"(",
"alpha",
"-",
"1.0",
")",
"b",
"=",
"(",
"2",
"**",
"a1",
")",
"while",
"True",
":",
"u",
"=",
"(",
"1.0",
"-",
"random",
".",
"random",
"(",
")",
")",
"v",
"=",
"random",
".",
"random",
"(",
")",
"x",
"=",
"int",
"(",
"(",
"xmin",
"*",
"(",
"u",
"**",
"(",
"-",
"(",
"1.0",
"/",
"a1",
")",
")",
")",
")",
")",
"t",
"=",
"(",
"(",
"1.0",
"+",
"(",
"1.0",
"/",
"x",
")",
")",
"**",
"a1",
")",
"if",
"(",
"(",
"(",
"(",
"v",
"*",
"x",
")",
"*",
"(",
"t",
"-",
"1.0",
")",
")",
"/",
"(",
"b",
"-",
"1.0",
")",
")",
"<=",
"(",
"t",
"/",
"b",
")",
")",
":",
"break",
"return",
"x"
] |
return a random value chosen from the zipf distribution .
|
train
| false
|
8,107
|
def _recursive_flatten(cell, dtype):
while (not isinstance(cell[0], dtype)):
cell = [c for d in cell for c in d]
return cell
|
[
"def",
"_recursive_flatten",
"(",
"cell",
",",
"dtype",
")",
":",
"while",
"(",
"not",
"isinstance",
"(",
"cell",
"[",
"0",
"]",
",",
"dtype",
")",
")",
":",
"cell",
"=",
"[",
"c",
"for",
"d",
"in",
"cell",
"for",
"c",
"in",
"d",
"]",
"return",
"cell"
] |
helper to unpack mat files in python .
|
train
| false
|
8,108
|
def group_activity_list_html(context, data_dict):
activity_stream = group_activity_list(context, data_dict)
offset = int(data_dict.get('offset', 0))
extra_vars = {'controller': 'group', 'action': 'activity', 'id': data_dict['id'], 'offset': offset}
return activity_streams.activity_list_to_html(context, activity_stream, extra_vars)
|
[
"def",
"group_activity_list_html",
"(",
"context",
",",
"data_dict",
")",
":",
"activity_stream",
"=",
"group_activity_list",
"(",
"context",
",",
"data_dict",
")",
"offset",
"=",
"int",
"(",
"data_dict",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
")",
"extra_vars",
"=",
"{",
"'controller'",
":",
"'group'",
",",
"'action'",
":",
"'activity'",
",",
"'id'",
":",
"data_dict",
"[",
"'id'",
"]",
",",
"'offset'",
":",
"offset",
"}",
"return",
"activity_streams",
".",
"activity_list_to_html",
"(",
"context",
",",
"activity_stream",
",",
"extra_vars",
")"
] |
return a groups activity stream as html .
|
train
| false
|
8,110
|
def _send_textmetrics(metrics):
data = ([' '.join(map(str, metric)) for metric in metrics] + [''])
return '\n'.join(data)
|
[
"def",
"_send_textmetrics",
"(",
"metrics",
")",
":",
"data",
"=",
"(",
"[",
"' '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"metric",
")",
")",
"for",
"metric",
"in",
"metrics",
"]",
"+",
"[",
"''",
"]",
")",
"return",
"'\\n'",
".",
"join",
"(",
"data",
")"
] |
format metrics for the carbon plaintext protocol .
|
train
| false
|
8,111
|
def process_tests(suite, process):
if ((not hasattr(suite, u'_tests')) or (hasattr(suite, u'hasFixtures') and suite.hasFixtures())):
process(suite)
else:
for t in suite._tests:
process_tests(t, process)
|
[
"def",
"process_tests",
"(",
"suite",
",",
"process",
")",
":",
"if",
"(",
"(",
"not",
"hasattr",
"(",
"suite",
",",
"u'_tests'",
")",
")",
"or",
"(",
"hasattr",
"(",
"suite",
",",
"u'hasFixtures'",
")",
"and",
"suite",
".",
"hasFixtures",
"(",
")",
")",
")",
":",
"process",
"(",
"suite",
")",
"else",
":",
"for",
"t",
"in",
"suite",
".",
"_tests",
":",
"process_tests",
"(",
"t",
",",
"process",
")"
] |
given a nested disaster of [lazy]suites .
|
train
| false
|
8,112
|
def get_or_create_root():
try:
root = URLPath.root()
if (not root.article):
root.delete()
raise NoRootURL
return root
except NoRootURL:
pass
starting_content = '\n'.join((_('Welcome to the {platform_name} Wiki').format(platform_name=configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)), '===', _('Visit a course wiki to add an article.')))
root = URLPath.create_root(title=_('Wiki'), content=starting_content)
article = root.article
article.group = None
article.group_read = True
article.group_write = False
article.other_read = True
article.other_write = False
article.save()
return root
|
[
"def",
"get_or_create_root",
"(",
")",
":",
"try",
":",
"root",
"=",
"URLPath",
".",
"root",
"(",
")",
"if",
"(",
"not",
"root",
".",
"article",
")",
":",
"root",
".",
"delete",
"(",
")",
"raise",
"NoRootURL",
"return",
"root",
"except",
"NoRootURL",
":",
"pass",
"starting_content",
"=",
"'\\n'",
".",
"join",
"(",
"(",
"_",
"(",
"'Welcome to the {platform_name} Wiki'",
")",
".",
"format",
"(",
"platform_name",
"=",
"configuration_helpers",
".",
"get_value",
"(",
"'PLATFORM_NAME'",
",",
"settings",
".",
"PLATFORM_NAME",
")",
")",
",",
"'==='",
",",
"_",
"(",
"'Visit a course wiki to add an article.'",
")",
")",
")",
"root",
"=",
"URLPath",
".",
"create_root",
"(",
"title",
"=",
"_",
"(",
"'Wiki'",
")",
",",
"content",
"=",
"starting_content",
")",
"article",
"=",
"root",
".",
"article",
"article",
".",
"group",
"=",
"None",
"article",
".",
"group_read",
"=",
"True",
"article",
".",
"group_write",
"=",
"False",
"article",
".",
"other_read",
"=",
"True",
"article",
".",
"other_write",
"=",
"False",
"article",
".",
"save",
"(",
")",
"return",
"root"
] |
returns the root article .
|
train
| false
|
8,113
|
def build_quadratic_1d(J, g, s, diag=None, s0=None):
v = J.dot(s)
a = np.dot(v, v)
if (diag is not None):
a += np.dot((s * diag), s)
a *= 0.5
b = np.dot(g, s)
if (s0 is not None):
u = J.dot(s0)
b += np.dot(u, v)
c = ((0.5 * np.dot(u, u)) + np.dot(g, s0))
if (diag is not None):
b += np.dot((s0 * diag), s)
c += (0.5 * np.dot((s0 * diag), s0))
return (a, b, c)
else:
return (a, b)
|
[
"def",
"build_quadratic_1d",
"(",
"J",
",",
"g",
",",
"s",
",",
"diag",
"=",
"None",
",",
"s0",
"=",
"None",
")",
":",
"v",
"=",
"J",
".",
"dot",
"(",
"s",
")",
"a",
"=",
"np",
".",
"dot",
"(",
"v",
",",
"v",
")",
"if",
"(",
"diag",
"is",
"not",
"None",
")",
":",
"a",
"+=",
"np",
".",
"dot",
"(",
"(",
"s",
"*",
"diag",
")",
",",
"s",
")",
"a",
"*=",
"0.5",
"b",
"=",
"np",
".",
"dot",
"(",
"g",
",",
"s",
")",
"if",
"(",
"s0",
"is",
"not",
"None",
")",
":",
"u",
"=",
"J",
".",
"dot",
"(",
"s0",
")",
"b",
"+=",
"np",
".",
"dot",
"(",
"u",
",",
"v",
")",
"c",
"=",
"(",
"(",
"0.5",
"*",
"np",
".",
"dot",
"(",
"u",
",",
"u",
")",
")",
"+",
"np",
".",
"dot",
"(",
"g",
",",
"s0",
")",
")",
"if",
"(",
"diag",
"is",
"not",
"None",
")",
":",
"b",
"+=",
"np",
".",
"dot",
"(",
"(",
"s0",
"*",
"diag",
")",
",",
"s",
")",
"c",
"+=",
"(",
"0.5",
"*",
"np",
".",
"dot",
"(",
"(",
"s0",
"*",
"diag",
")",
",",
"s0",
")",
")",
"return",
"(",
"a",
",",
"b",
",",
"c",
")",
"else",
":",
"return",
"(",
"a",
",",
"b",
")"
] |
parameterize a multivariate quadratic function along a line .
|
train
| false
|
8,114
|
def disable_colors():
for i in CONF['COLORS']:
if isinstance(CONF['COLORS'][i], dict):
for j in CONF['COLORS'][i]:
CONF['COLORS'][i][j] = Color.normal
else:
CONF['COLORS'][i] = Color.normal
|
[
"def",
"disable_colors",
"(",
")",
":",
"for",
"i",
"in",
"CONF",
"[",
"'COLORS'",
"]",
":",
"if",
"isinstance",
"(",
"CONF",
"[",
"'COLORS'",
"]",
"[",
"i",
"]",
",",
"dict",
")",
":",
"for",
"j",
"in",
"CONF",
"[",
"'COLORS'",
"]",
"[",
"i",
"]",
":",
"CONF",
"[",
"'COLORS'",
"]",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"Color",
".",
"normal",
"else",
":",
"CONF",
"[",
"'COLORS'",
"]",
"[",
"i",
"]",
"=",
"Color",
".",
"normal"
] |
disable colors from the output .
|
train
| true
|
8,115
|
@register.function
def license_link(license):
from olympia.versions.models import License
if isinstance(license, (long, int)):
if (license in PERSONA_LICENSES_IDS):
license = PERSONA_LICENSES_IDS[license]
else:
license = License.objects.filter(id=license)
if (not license.exists()):
return ''
license = license[0]
elif (not license):
return ''
if (not getattr(license, 'builtin', True)):
return _('Custom License')
template = get_env().get_template('amo/license_link.html')
return jinja2.Markup(template.render({'license': license}))
|
[
"@",
"register",
".",
"function",
"def",
"license_link",
"(",
"license",
")",
":",
"from",
"olympia",
".",
"versions",
".",
"models",
"import",
"License",
"if",
"isinstance",
"(",
"license",
",",
"(",
"long",
",",
"int",
")",
")",
":",
"if",
"(",
"license",
"in",
"PERSONA_LICENSES_IDS",
")",
":",
"license",
"=",
"PERSONA_LICENSES_IDS",
"[",
"license",
"]",
"else",
":",
"license",
"=",
"License",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"license",
")",
"if",
"(",
"not",
"license",
".",
"exists",
"(",
")",
")",
":",
"return",
"''",
"license",
"=",
"license",
"[",
"0",
"]",
"elif",
"(",
"not",
"license",
")",
":",
"return",
"''",
"if",
"(",
"not",
"getattr",
"(",
"license",
",",
"'builtin'",
",",
"True",
")",
")",
":",
"return",
"_",
"(",
"'Custom License'",
")",
"template",
"=",
"get_env",
"(",
")",
".",
"get_template",
"(",
"'amo/license_link.html'",
")",
"return",
"jinja2",
".",
"Markup",
"(",
"template",
".",
"render",
"(",
"{",
"'license'",
":",
"license",
"}",
")",
")"
] |
link to a code license .
|
train
| false
|
8,116
|
@command(('(%s{0,3})(?:\\*|all)\\s*(%s{0,3})' % (RS, RS)))
def play_all(pre, choice, post=''):
options = ((pre + choice) + post)
play(options, ('1-' + str(len(g.model))))
|
[
"@",
"command",
"(",
"(",
"'(%s{0,3})(?:\\\\*|all)\\\\s*(%s{0,3})'",
"%",
"(",
"RS",
",",
"RS",
")",
")",
")",
"def",
"play_all",
"(",
"pre",
",",
"choice",
",",
"post",
"=",
"''",
")",
":",
"options",
"=",
"(",
"(",
"pre",
"+",
"choice",
")",
"+",
"post",
")",
"play",
"(",
"options",
",",
"(",
"'1-'",
"+",
"str",
"(",
"len",
"(",
"g",
".",
"model",
")",
")",
")",
")"
] |
play all tracks in model .
|
train
| false
|
8,117
|
def make_debug_app(global_conf, **local_conf):
return DebugApp(**local_conf)
|
[
"def",
"make_debug_app",
"(",
"global_conf",
",",
"**",
"local_conf",
")",
":",
"return",
"DebugApp",
"(",
"**",
"local_conf",
")"
] |
an application that displays the request environment .
|
train
| false
|
8,118
|
def delete_alarm(name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_alarms([name])
log.info('Deleted alarm {0}'.format(name))
return True
|
[
"def",
"delete_alarm",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"conn",
".",
"delete_alarms",
"(",
"[",
"name",
"]",
")",
"log",
".",
"info",
"(",
"'Deleted alarm {0}'",
".",
"format",
"(",
"name",
")",
")",
"return",
"True"
] |
delete a cloudwatch alarm cli example to delete a queue:: salt myminion boto_cloudwatch .
|
train
| true
|
8,120
|
def HashGen(APP_PATH):
try:
print '[INFO] Generating Hashes'
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
BLOCKSIZE = 65536
with io.open(APP_PATH, mode='rb') as afile:
buf = afile.read(BLOCKSIZE)
while buf:
sha1.update(buf)
sha256.update(buf)
buf = afile.read(BLOCKSIZE)
sha1val = sha1.hexdigest()
sha256val = sha256.hexdigest()
return (sha1val, sha256val)
except:
PrintException('[ERROR] Generating Hashes')
|
[
"def",
"HashGen",
"(",
"APP_PATH",
")",
":",
"try",
":",
"print",
"'[INFO] Generating Hashes'",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"sha256",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"BLOCKSIZE",
"=",
"65536",
"with",
"io",
".",
"open",
"(",
"APP_PATH",
",",
"mode",
"=",
"'rb'",
")",
"as",
"afile",
":",
"buf",
"=",
"afile",
".",
"read",
"(",
"BLOCKSIZE",
")",
"while",
"buf",
":",
"sha1",
".",
"update",
"(",
"buf",
")",
"sha256",
".",
"update",
"(",
"buf",
")",
"buf",
"=",
"afile",
".",
"read",
"(",
"BLOCKSIZE",
")",
"sha1val",
"=",
"sha1",
".",
"hexdigest",
"(",
")",
"sha256val",
"=",
"sha256",
".",
"hexdigest",
"(",
")",
"return",
"(",
"sha1val",
",",
"sha256val",
")",
"except",
":",
"PrintException",
"(",
"'[ERROR] Generating Hashes'",
")"
] |
generate and return sha1 and sha256 as a tupel .
|
train
| false
|
8,121
|
def getTransactionId(packet):
if isinstance(packet, list):
return unpack('>H', pack('BB', *packet[:2]))[0]
else:
return unpack('>H', packet[:2])[0]
|
[
"def",
"getTransactionId",
"(",
"packet",
")",
":",
"if",
"isinstance",
"(",
"packet",
",",
"list",
")",
":",
"return",
"unpack",
"(",
"'>H'",
",",
"pack",
"(",
"'BB'",
",",
"*",
"packet",
"[",
":",
"2",
"]",
")",
")",
"[",
"0",
"]",
"else",
":",
"return",
"unpack",
"(",
"'>H'",
",",
"packet",
"[",
":",
"2",
"]",
")",
"[",
"0",
"]"
] |
pulls out the transaction id of the packet .
|
train
| false
|
8,122
|
def set_unresponsive(url):
host = urlparse(url).hostname
if (host in unresponsive_hosts):
return
unresponsive_hosts[host] = True
|
[
"def",
"set_unresponsive",
"(",
"url",
")",
":",
"host",
"=",
"urlparse",
"(",
"url",
")",
".",
"hostname",
"if",
"(",
"host",
"in",
"unresponsive_hosts",
")",
":",
"return",
"unresponsive_hosts",
"[",
"host",
"]",
"=",
"True"
] |
marks the host of a given url as unresponsive .
|
train
| false
|
8,123
|
def _get_child_text(parent, tag, construct=unicode):
child = parent.find(_ns(tag))
if ((child is not None) and child.text):
return construct(child.text)
|
[
"def",
"_get_child_text",
"(",
"parent",
",",
"tag",
",",
"construct",
"=",
"unicode",
")",
":",
"child",
"=",
"parent",
".",
"find",
"(",
"_ns",
"(",
"tag",
")",
")",
"if",
"(",
"(",
"child",
"is",
"not",
"None",
")",
"and",
"child",
".",
"text",
")",
":",
"return",
"construct",
"(",
"child",
".",
"text",
")"
] |
find a child node by tag; pass its text through a constructor .
|
train
| false
|
8,124
|
def unregister_mimetype_handler(handler):
if (not issubclass(handler, MimetypeHandler)):
raise TypeError(u'Only MimetypeHandler subclasses can be unregistered')
try:
_registered_mimetype_handlers.remove(handler)
except ValueError:
logging.error((u'Failed to unregister missing mimetype handler %r' % handler))
raise ValueError(u'This mimetype handler was not previously registered')
|
[
"def",
"unregister_mimetype_handler",
"(",
"handler",
")",
":",
"if",
"(",
"not",
"issubclass",
"(",
"handler",
",",
"MimetypeHandler",
")",
")",
":",
"raise",
"TypeError",
"(",
"u'Only MimetypeHandler subclasses can be unregistered'",
")",
"try",
":",
"_registered_mimetype_handlers",
".",
"remove",
"(",
"handler",
")",
"except",
"ValueError",
":",
"logging",
".",
"error",
"(",
"(",
"u'Failed to unregister missing mimetype handler %r'",
"%",
"handler",
")",
")",
"raise",
"ValueError",
"(",
"u'This mimetype handler was not previously registered'",
")"
] |
unregister a mimetypehandler class .
|
train
| false
|
8,126
|
def basePost(base, a, b):
base.calledBasePost = (base.calledBasePost + 1)
|
[
"def",
"basePost",
"(",
"base",
",",
"a",
",",
"b",
")",
":",
"base",
".",
"calledBasePost",
"=",
"(",
"base",
".",
"calledBasePost",
"+",
"1",
")"
] |
a post-hook for the base class .
|
train
| false
|
8,127
|
def get_mem_used_res():
try:
import resource
except ImportError:
raise NotSupportedException
a = os.popen(('cat /proc/%s/statm' % os.getpid())).read().split()
if (not (len(a) > 1)):
raise NotSupportedException
return (int(a[1]) * resource.getpagesize())
|
[
"def",
"get_mem_used_res",
"(",
")",
":",
"try",
":",
"import",
"resource",
"except",
"ImportError",
":",
"raise",
"NotSupportedException",
"a",
"=",
"os",
".",
"popen",
"(",
"(",
"'cat /proc/%s/statm'",
"%",
"os",
".",
"getpid",
"(",
")",
")",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
")",
"if",
"(",
"not",
"(",
"len",
"(",
"a",
")",
">",
"1",
")",
")",
":",
"raise",
"NotSupportedException",
"return",
"(",
"int",
"(",
"a",
"[",
"1",
"]",
")",
"*",
"resource",
".",
"getpagesize",
"(",
")",
")"
] |
this only works on linux .
|
train
| false
|
8,128
|
def _xml_read(root, element, check=None):
val = root.findtext(element)
if ((val is None) and check):
LOG.error(_LE('Mandatory parameter not found: %(p)s'), {'p': element})
raise exception.ParameterNotFound(param=element)
if (val is None):
return None
svc_tag_pattern = re.compile('svc_[0-3]$')
if (not val.strip()):
if svc_tag_pattern.search(element):
return ''
LOG.error(_LE('Parameter not found: %(param)s'), {'param': element})
raise exception.ParameterNotFound(param=element)
LOG.debug('%(element)s: %(val)s', {'element': element, 'val': (val if (element != 'password') else '***')})
return val.strip()
|
[
"def",
"_xml_read",
"(",
"root",
",",
"element",
",",
"check",
"=",
"None",
")",
":",
"val",
"=",
"root",
".",
"findtext",
"(",
"element",
")",
"if",
"(",
"(",
"val",
"is",
"None",
")",
"and",
"check",
")",
":",
"LOG",
".",
"error",
"(",
"_LE",
"(",
"'Mandatory parameter not found: %(p)s'",
")",
",",
"{",
"'p'",
":",
"element",
"}",
")",
"raise",
"exception",
".",
"ParameterNotFound",
"(",
"param",
"=",
"element",
")",
"if",
"(",
"val",
"is",
"None",
")",
":",
"return",
"None",
"svc_tag_pattern",
"=",
"re",
".",
"compile",
"(",
"'svc_[0-3]$'",
")",
"if",
"(",
"not",
"val",
".",
"strip",
"(",
")",
")",
":",
"if",
"svc_tag_pattern",
".",
"search",
"(",
"element",
")",
":",
"return",
"''",
"LOG",
".",
"error",
"(",
"_LE",
"(",
"'Parameter not found: %(param)s'",
")",
",",
"{",
"'param'",
":",
"element",
"}",
")",
"raise",
"exception",
".",
"ParameterNotFound",
"(",
"param",
"=",
"element",
")",
"LOG",
".",
"debug",
"(",
"'%(element)s: %(val)s'",
",",
"{",
"'element'",
":",
"element",
",",
"'val'",
":",
"(",
"val",
"if",
"(",
"element",
"!=",
"'password'",
")",
"else",
"'***'",
")",
"}",
")",
"return",
"val",
".",
"strip",
"(",
")"
] |
read an xml element .
|
train
| false
|
8,130
|
def _get_object_info(app, env, account, container, obj, swift_source=None):
cache_key = get_cache_key(account, container, obj)
info = env.get('swift.infocache', {}).get(cache_key)
if info:
return info
path = ('/v1/%s/%s/%s' % (account, container, obj))
req = _prepare_pre_auth_info_request(env, path, swift_source)
resp = req.get_response(app)
info = set_object_info_cache(app, env, account, container, obj, resp)
return info
|
[
"def",
"_get_object_info",
"(",
"app",
",",
"env",
",",
"account",
",",
"container",
",",
"obj",
",",
"swift_source",
"=",
"None",
")",
":",
"cache_key",
"=",
"get_cache_key",
"(",
"account",
",",
"container",
",",
"obj",
")",
"info",
"=",
"env",
".",
"get",
"(",
"'swift.infocache'",
",",
"{",
"}",
")",
".",
"get",
"(",
"cache_key",
")",
"if",
"info",
":",
"return",
"info",
"path",
"=",
"(",
"'/v1/%s/%s/%s'",
"%",
"(",
"account",
",",
"container",
",",
"obj",
")",
")",
"req",
"=",
"_prepare_pre_auth_info_request",
"(",
"env",
",",
"path",
",",
"swift_source",
")",
"resp",
"=",
"req",
".",
"get_response",
"(",
"app",
")",
"info",
"=",
"set_object_info_cache",
"(",
"app",
",",
"env",
",",
"account",
",",
"container",
",",
"obj",
",",
"resp",
")",
"return",
"info"
] |
get the info about object note: this call bypasses auth .
|
train
| false
|
8,132
|
def p_field(p):
if (len(p) == 7):
try:
val = _cast(p[3])(p[6])
except AssertionError:
raise ThriftParserError(('Type error for field %s at line %d' % (p[4], p.lineno(4))))
else:
val = None
p[0] = [p[1], p[2], p[3], p[4], val]
|
[
"def",
"p_field",
"(",
"p",
")",
":",
"if",
"(",
"len",
"(",
"p",
")",
"==",
"7",
")",
":",
"try",
":",
"val",
"=",
"_cast",
"(",
"p",
"[",
"3",
"]",
")",
"(",
"p",
"[",
"6",
"]",
")",
"except",
"AssertionError",
":",
"raise",
"ThriftParserError",
"(",
"(",
"'Type error for field %s at line %d'",
"%",
"(",
"p",
"[",
"4",
"]",
",",
"p",
".",
"lineno",
"(",
"4",
")",
")",
")",
")",
"else",
":",
"val",
"=",
"None",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"3",
"]",
",",
"p",
"[",
"4",
"]",
",",
"val",
"]"
] |
field : field_id field_req field_type identifier | field_id field_req field_type identifier = const_value .
|
train
| false
|
8,133
|
def build_target(package_name, version=None, build=None, tag=None):
if (tag is not None):
assert (version is None)
assert (build is None)
(version, build) = split_tag(tag)
return Target(package_name, version, build)
|
[
"def",
"build_target",
"(",
"package_name",
",",
"version",
"=",
"None",
",",
"build",
"=",
"None",
",",
"tag",
"=",
"None",
")",
":",
"if",
"(",
"tag",
"is",
"not",
"None",
")",
":",
"assert",
"(",
"version",
"is",
"None",
")",
"assert",
"(",
"build",
"is",
"None",
")",
"(",
"version",
",",
"build",
")",
"=",
"split_tag",
"(",
"tag",
")",
"return",
"Target",
"(",
"package_name",
",",
"version",
",",
"build",
")"
] |
use supplied arguments to build a :class:target object .
|
train
| false
|
8,134
|
def readNonWhitespace(stream):
tok = WHITESPACES[0]
while (tok in WHITESPACES):
tok = stream.read(1)
return tok
|
[
"def",
"readNonWhitespace",
"(",
"stream",
")",
":",
"tok",
"=",
"WHITESPACES",
"[",
"0",
"]",
"while",
"(",
"tok",
"in",
"WHITESPACES",
")",
":",
"tok",
"=",
"stream",
".",
"read",
"(",
"1",
")",
"return",
"tok"
] |
finds and reads the next non-whitespace character .
|
train
| false
|
8,135
|
def test_which_set():
skip_if_no_sklearn()
this_yaml = (test_yaml_which_set % {'which_set': 'train'})
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
this_yaml = (test_yaml_which_set % {'which_set': ['train', 'test']})
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
this_yaml = (test_yaml_which_set % {'which_set': 'valid'})
try:
trainer = yaml_parse.load(this_yaml)
trainer.main_loop()
raise AssertionError
except ValueError:
pass
this_yaml = (test_yaml_which_set % {'which_set': 'bogus'})
try:
yaml_parse.load(this_yaml)
raise AssertionError
except ValueError:
pass
|
[
"def",
"test_which_set",
"(",
")",
":",
"skip_if_no_sklearn",
"(",
")",
"this_yaml",
"=",
"(",
"test_yaml_which_set",
"%",
"{",
"'which_set'",
":",
"'train'",
"}",
")",
"trainer",
"=",
"yaml_parse",
".",
"load",
"(",
"this_yaml",
")",
"trainer",
".",
"main_loop",
"(",
")",
"this_yaml",
"=",
"(",
"test_yaml_which_set",
"%",
"{",
"'which_set'",
":",
"[",
"'train'",
",",
"'test'",
"]",
"}",
")",
"trainer",
"=",
"yaml_parse",
".",
"load",
"(",
"this_yaml",
")",
"trainer",
".",
"main_loop",
"(",
")",
"this_yaml",
"=",
"(",
"test_yaml_which_set",
"%",
"{",
"'which_set'",
":",
"'valid'",
"}",
")",
"try",
":",
"trainer",
"=",
"yaml_parse",
".",
"load",
"(",
"this_yaml",
")",
"trainer",
".",
"main_loop",
"(",
")",
"raise",
"AssertionError",
"except",
"ValueError",
":",
"pass",
"this_yaml",
"=",
"(",
"test_yaml_which_set",
"%",
"{",
"'which_set'",
":",
"'bogus'",
"}",
")",
"try",
":",
"yaml_parse",
".",
"load",
"(",
"this_yaml",
")",
"raise",
"AssertionError",
"except",
"ValueError",
":",
"pass"
] |
test which_set selector .
|
train
| false
|
8,136
|
@sopel.module.event(events.ERR_NOCHANMODES)
@sopel.module.rule(u'.*')
@sopel.module.priority(u'high')
def retry_join(bot, trigger):
channel = trigger.args[1]
if (channel in bot.memory[u'retry_join'].keys()):
bot.memory[u'retry_join'][channel] += 1
if (bot.memory[u'retry_join'][channel] > 10):
LOGGER.warning(u'Failed to join %s after 10 attempts.', channel)
return
else:
bot.memory[u'retry_join'][channel] = 0
bot.join(channel)
return
time.sleep(6)
bot.join(channel)
|
[
"@",
"sopel",
".",
"module",
".",
"event",
"(",
"events",
".",
"ERR_NOCHANMODES",
")",
"@",
"sopel",
".",
"module",
".",
"rule",
"(",
"u'.*'",
")",
"@",
"sopel",
".",
"module",
".",
"priority",
"(",
"u'high'",
")",
"def",
"retry_join",
"(",
"bot",
",",
"trigger",
")",
":",
"channel",
"=",
"trigger",
".",
"args",
"[",
"1",
"]",
"if",
"(",
"channel",
"in",
"bot",
".",
"memory",
"[",
"u'retry_join'",
"]",
".",
"keys",
"(",
")",
")",
":",
"bot",
".",
"memory",
"[",
"u'retry_join'",
"]",
"[",
"channel",
"]",
"+=",
"1",
"if",
"(",
"bot",
".",
"memory",
"[",
"u'retry_join'",
"]",
"[",
"channel",
"]",
">",
"10",
")",
":",
"LOGGER",
".",
"warning",
"(",
"u'Failed to join %s after 10 attempts.'",
",",
"channel",
")",
"return",
"else",
":",
"bot",
".",
"memory",
"[",
"u'retry_join'",
"]",
"[",
"channel",
"]",
"=",
"0",
"bot",
".",
"join",
"(",
"channel",
")",
"return",
"time",
".",
"sleep",
"(",
"6",
")",
"bot",
".",
"join",
"(",
"channel",
")"
] |
give nickserver enough time to identify on a +r channel .
|
train
| false
|
8,137
|
@deco.keyword('Takes ${embedded} ${args}')
def takes_embedded_args(a=1, b=2, c=3):
pass
|
[
"@",
"deco",
".",
"keyword",
"(",
"'Takes ${embedded} ${args}'",
")",
"def",
"takes_embedded_args",
"(",
"a",
"=",
"1",
",",
"b",
"=",
"2",
",",
"c",
"=",
"3",
")",
":",
"pass"
] |
a keyword which uses embedded args .
|
train
| false
|
8,138
|
def sort_choices(choices):
return sort_unicode(choices, (lambda tup: tup[1]))
|
[
"def",
"sort_choices",
"(",
"choices",
")",
":",
"return",
"sort_unicode",
"(",
"choices",
",",
"(",
"lambda",
"tup",
":",
"tup",
"[",
"1",
"]",
")",
")"
] |
sorts choices alphabetically .
|
train
| false
|
8,139
|
def create_player(key, email, password, typeclass=None, is_superuser=False, locks=None, permissions=None, report_to=None):
global _PlayerDB
if (not _PlayerDB):
from evennia.players.models import PlayerDB as _PlayerDB
typeclass = (typeclass if typeclass else settings.BASE_PLAYER_TYPECLASS)
if isinstance(typeclass, basestring):
typeclass = class_from_module(typeclass, settings.TYPECLASS_PATHS)
if (not email):
email = 'dummy@dummy.com'
if _PlayerDB.objects.filter(username__iexact=key):
raise ValueError(("A Player with the name '%s' already exists." % key))
report_to = dbid_to_obj(report_to, _PlayerDB)
now = timezone.now()
email = typeclass.objects.normalize_email(email)
new_player = typeclass(username=key, email=email, is_staff=is_superuser, is_superuser=is_superuser, last_login=now, date_joined=now)
new_player.set_password(password)
new_player._createdict = {'locks': locks, 'permissions': permissions, 'report_to': report_to}
new_player.save()
return new_player
|
[
"def",
"create_player",
"(",
"key",
",",
"email",
",",
"password",
",",
"typeclass",
"=",
"None",
",",
"is_superuser",
"=",
"False",
",",
"locks",
"=",
"None",
",",
"permissions",
"=",
"None",
",",
"report_to",
"=",
"None",
")",
":",
"global",
"_PlayerDB",
"if",
"(",
"not",
"_PlayerDB",
")",
":",
"from",
"evennia",
".",
"players",
".",
"models",
"import",
"PlayerDB",
"as",
"_PlayerDB",
"typeclass",
"=",
"(",
"typeclass",
"if",
"typeclass",
"else",
"settings",
".",
"BASE_PLAYER_TYPECLASS",
")",
"if",
"isinstance",
"(",
"typeclass",
",",
"basestring",
")",
":",
"typeclass",
"=",
"class_from_module",
"(",
"typeclass",
",",
"settings",
".",
"TYPECLASS_PATHS",
")",
"if",
"(",
"not",
"email",
")",
":",
"email",
"=",
"'dummy@dummy.com'",
"if",
"_PlayerDB",
".",
"objects",
".",
"filter",
"(",
"username__iexact",
"=",
"key",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"A Player with the name '%s' already exists.\"",
"%",
"key",
")",
")",
"report_to",
"=",
"dbid_to_obj",
"(",
"report_to",
",",
"_PlayerDB",
")",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"email",
"=",
"typeclass",
".",
"objects",
".",
"normalize_email",
"(",
"email",
")",
"new_player",
"=",
"typeclass",
"(",
"username",
"=",
"key",
",",
"email",
"=",
"email",
",",
"is_staff",
"=",
"is_superuser",
",",
"is_superuser",
"=",
"is_superuser",
",",
"last_login",
"=",
"now",
",",
"date_joined",
"=",
"now",
")",
"new_player",
".",
"set_password",
"(",
"password",
")",
"new_player",
".",
"_createdict",
"=",
"{",
"'locks'",
":",
"locks",
",",
"'permissions'",
":",
"permissions",
",",
"'report_to'",
":",
"report_to",
"}",
"new_player",
".",
"save",
"(",
")",
"return",
"new_player"
] |
this creates a new player .
|
train
| false
|
8,140
|
def rgb_css(color):
return (u'rgb(%d, %d, %d)' % (color.red(), color.green(), color.blue()))
|
[
"def",
"rgb_css",
"(",
"color",
")",
":",
"return",
"(",
"u'rgb(%d, %d, %d)'",
"%",
"(",
"color",
".",
"red",
"(",
")",
",",
"color",
".",
"green",
"(",
")",
",",
"color",
".",
"blue",
"(",
")",
")",
")"
] |
convert a qcolor into an rgb css string .
|
train
| false
|
8,141
|
def test_show_message_twice(view):
view.show_message(usertypes.MessageLevel.info, 'test')
view.show_message(usertypes.MessageLevel.info, 'test')
assert (len(view._messages) == 1)
|
[
"def",
"test_show_message_twice",
"(",
"view",
")",
":",
"view",
".",
"show_message",
"(",
"usertypes",
".",
"MessageLevel",
".",
"info",
",",
"'test'",
")",
"view",
".",
"show_message",
"(",
"usertypes",
".",
"MessageLevel",
".",
"info",
",",
"'test'",
")",
"assert",
"(",
"len",
"(",
"view",
".",
"_messages",
")",
"==",
"1",
")"
] |
show the same message twice -> only one should be shown .
|
train
| false
|
8,142
|
def xl_rowcol_to_cell_fast(row, col):
if (col in COL_NAMES):
col_str = COL_NAMES[col]
else:
col_str = xl_col_to_name(col)
COL_NAMES[col] = col_str
return (col_str + str((row + 1)))
|
[
"def",
"xl_rowcol_to_cell_fast",
"(",
"row",
",",
"col",
")",
":",
"if",
"(",
"col",
"in",
"COL_NAMES",
")",
":",
"col_str",
"=",
"COL_NAMES",
"[",
"col",
"]",
"else",
":",
"col_str",
"=",
"xl_col_to_name",
"(",
"col",
")",
"COL_NAMES",
"[",
"col",
"]",
"=",
"col_str",
"return",
"(",
"col_str",
"+",
"str",
"(",
"(",
"row",
"+",
"1",
")",
")",
")"
] |
optimized version of the xl_rowcol_to_cell function .
|
train
| false
|
8,148
|
def do_scores_for_objects(parser, token):
bits = token.contents.split()
if (len(bits) != 4):
raise template.TemplateSyntaxError(("'%s' tag takes exactly three arguments" % bits[0]))
if (bits[2] != 'as'):
raise template.TemplateSyntaxError(("second argument to '%s' tag must be 'as'" % bits[0]))
return ScoresForObjectsNode(bits[1], bits[3])
|
[
"def",
"do_scores_for_objects",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"!=",
"4",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"(",
"\"'%s' tag takes exactly three arguments\"",
"%",
"bits",
"[",
"0",
"]",
")",
")",
"if",
"(",
"bits",
"[",
"2",
"]",
"!=",
"'as'",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"(",
"\"second argument to '%s' tag must be 'as'\"",
"%",
"bits",
"[",
"0",
"]",
")",
")",
"return",
"ScoresForObjectsNode",
"(",
"bits",
"[",
"1",
"]",
",",
"bits",
"[",
"3",
"]",
")"
] |
retrieves the total scores for a list of objects and the number of votes they have received and stores them in a context variable .
|
train
| false
|
8,149
|
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=1e-05):
if ((mu != 0) or (sigma != 1)):
return (mu + (sigma * inverse_normal_cdf(p, tolerance=tolerance)))
(low_z, low_p) = ((-10.0), 0)
(hi_z, hi_p) = (10.0, 1)
while ((hi_z - low_z) > tolerance):
mid_z = ((low_z + hi_z) / 2)
mid_p = normal_cdf(mid_z)
if (mid_p < p):
(low_z, low_p) = (mid_z, mid_p)
elif (mid_p > p):
(hi_z, hi_p) = (mid_z, mid_p)
else:
break
return mid_z
|
[
"def",
"inverse_normal_cdf",
"(",
"p",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
",",
"tolerance",
"=",
"1e-05",
")",
":",
"if",
"(",
"(",
"mu",
"!=",
"0",
")",
"or",
"(",
"sigma",
"!=",
"1",
")",
")",
":",
"return",
"(",
"mu",
"+",
"(",
"sigma",
"*",
"inverse_normal_cdf",
"(",
"p",
",",
"tolerance",
"=",
"tolerance",
")",
")",
")",
"(",
"low_z",
",",
"low_p",
")",
"=",
"(",
"(",
"-",
"10.0",
")",
",",
"0",
")",
"(",
"hi_z",
",",
"hi_p",
")",
"=",
"(",
"10.0",
",",
"1",
")",
"while",
"(",
"(",
"hi_z",
"-",
"low_z",
")",
">",
"tolerance",
")",
":",
"mid_z",
"=",
"(",
"(",
"low_z",
"+",
"hi_z",
")",
"/",
"2",
")",
"mid_p",
"=",
"normal_cdf",
"(",
"mid_z",
")",
"if",
"(",
"mid_p",
"<",
"p",
")",
":",
"(",
"low_z",
",",
"low_p",
")",
"=",
"(",
"mid_z",
",",
"mid_p",
")",
"elif",
"(",
"mid_p",
">",
"p",
")",
":",
"(",
"hi_z",
",",
"hi_p",
")",
"=",
"(",
"mid_z",
",",
"mid_p",
")",
"else",
":",
"break",
"return",
"mid_z"
] |
find approximate inverse using binary search .
|
train
| false
|
8,151
|
def list_returners(*args):
returners_ = salt.loader.returners(__opts__, [])
returners = set()
if (not args):
for func in six.iterkeys(returners_):
returners.add(func.split('.')[0])
return sorted(returners)
for module in args:
if ('*' in module):
for func in fnmatch.filter(returners_, module):
returners.add(func.split('.')[0])
else:
for func in returners_:
mod_test = func.split('.')[0]
if (mod_test == module):
returners.add(mod_test)
return sorted(returners)
|
[
"def",
"list_returners",
"(",
"*",
"args",
")",
":",
"returners_",
"=",
"salt",
".",
"loader",
".",
"returners",
"(",
"__opts__",
",",
"[",
"]",
")",
"returners",
"=",
"set",
"(",
")",
"if",
"(",
"not",
"args",
")",
":",
"for",
"func",
"in",
"six",
".",
"iterkeys",
"(",
"returners_",
")",
":",
"returners",
".",
"add",
"(",
"func",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"return",
"sorted",
"(",
"returners",
")",
"for",
"module",
"in",
"args",
":",
"if",
"(",
"'*'",
"in",
"module",
")",
":",
"for",
"func",
"in",
"fnmatch",
".",
"filter",
"(",
"returners_",
",",
"module",
")",
":",
"returners",
".",
"add",
"(",
"func",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"else",
":",
"for",
"func",
"in",
"returners_",
":",
"mod_test",
"=",
"func",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"(",
"mod_test",
"==",
"module",
")",
":",
"returners",
".",
"add",
"(",
"mod_test",
")",
"return",
"sorted",
"(",
"returners",
")"
] |
list the returners loaded on the minion .
|
train
| true
|
8,152
|
def _check_destination_header(req):
return _check_path_header(req, 'Destination', 2, 'Destination header must be of the form <container name>/<object name>')
|
[
"def",
"_check_destination_header",
"(",
"req",
")",
":",
"return",
"_check_path_header",
"(",
"req",
",",
"'Destination'",
",",
"2",
",",
"'Destination header must be of the form <container name>/<object name>'",
")"
] |
validate that the value from destination header is well formatted .
|
train
| false
|
8,154
|
def _iter_all_modules(package, prefix=''):
import os
import pkgutil
if (type(package) is not str):
(path, prefix) = (package.__path__[0], (package.__name__ + '.'))
else:
path = package
for (_, name, is_package) in pkgutil.iter_modules([path]):
if is_package:
for m in _iter_all_modules(os.path.join(path, name), prefix=(name + '.')):
(yield (prefix + m))
else:
(yield (prefix + name))
|
[
"def",
"_iter_all_modules",
"(",
"package",
",",
"prefix",
"=",
"''",
")",
":",
"import",
"os",
"import",
"pkgutil",
"if",
"(",
"type",
"(",
"package",
")",
"is",
"not",
"str",
")",
":",
"(",
"path",
",",
"prefix",
")",
"=",
"(",
"package",
".",
"__path__",
"[",
"0",
"]",
",",
"(",
"package",
".",
"__name__",
"+",
"'.'",
")",
")",
"else",
":",
"path",
"=",
"package",
"for",
"(",
"_",
",",
"name",
",",
"is_package",
")",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"[",
"path",
"]",
")",
":",
"if",
"is_package",
":",
"for",
"m",
"in",
"_iter_all_modules",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
",",
"prefix",
"=",
"(",
"name",
"+",
"'.'",
")",
")",
":",
"(",
"yield",
"(",
"prefix",
"+",
"m",
")",
")",
"else",
":",
"(",
"yield",
"(",
"prefix",
"+",
"name",
")",
")"
] |
iterates over the names of all modules that can be found in the given package .
|
train
| false
|
8,156
|
def get_containers(all=True, trunc=False, since=None, before=None, limit=(-1), host=False, inspect=False):
client = _get_client()
status = base_status.copy()
if host:
status['host'] = {}
status['host']['interfaces'] = __salt__['network.interfaces']()
containers = client.containers(all=all, trunc=trunc, since=since, before=before, limit=limit)
if inspect:
for container in containers:
container_id = container.get('Id')
if container_id:
inspect = _get_container_infos(container_id)
container['detail'] = inspect.copy()
_valid(status, comment='All containers in out', out=containers)
return status
|
[
"def",
"get_containers",
"(",
"all",
"=",
"True",
",",
"trunc",
"=",
"False",
",",
"since",
"=",
"None",
",",
"before",
"=",
"None",
",",
"limit",
"=",
"(",
"-",
"1",
")",
",",
"host",
"=",
"False",
",",
"inspect",
"=",
"False",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"status",
"=",
"base_status",
".",
"copy",
"(",
")",
"if",
"host",
":",
"status",
"[",
"'host'",
"]",
"=",
"{",
"}",
"status",
"[",
"'host'",
"]",
"[",
"'interfaces'",
"]",
"=",
"__salt__",
"[",
"'network.interfaces'",
"]",
"(",
")",
"containers",
"=",
"client",
".",
"containers",
"(",
"all",
"=",
"all",
",",
"trunc",
"=",
"trunc",
",",
"since",
"=",
"since",
",",
"before",
"=",
"before",
",",
"limit",
"=",
"limit",
")",
"if",
"inspect",
":",
"for",
"container",
"in",
"containers",
":",
"container_id",
"=",
"container",
".",
"get",
"(",
"'Id'",
")",
"if",
"container_id",
":",
"inspect",
"=",
"_get_container_infos",
"(",
"container_id",
")",
"container",
"[",
"'detail'",
"]",
"=",
"inspect",
".",
"copy",
"(",
")",
"_valid",
"(",
"status",
",",
"comment",
"=",
"'All containers in out'",
",",
"out",
"=",
"containers",
")",
"return",
"status"
] |
get a list of mappings representing all containers all return all containers .
|
train
| false
|
8,157
|
def m2_repository_cleanup(registry, xml_parent, data):
m2repo = XML.SubElement(xml_parent, 'hudson.plugins.m2__repo__reaper.M2RepoReaperWrapper')
m2repo.set('plugin', 'm2-repo-reaper')
patterns = data.get('patterns', [])
XML.SubElement(m2repo, 'artifactPatterns').text = ','.join(patterns)
p = XML.SubElement(m2repo, 'patterns')
for pattern in patterns:
XML.SubElement(p, 'string').text = pattern
|
[
"def",
"m2_repository_cleanup",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"m2repo",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.m2__repo__reaper.M2RepoReaperWrapper'",
")",
"m2repo",
".",
"set",
"(",
"'plugin'",
",",
"'m2-repo-reaper'",
")",
"patterns",
"=",
"data",
".",
"get",
"(",
"'patterns'",
",",
"[",
"]",
")",
"XML",
".",
"SubElement",
"(",
"m2repo",
",",
"'artifactPatterns'",
")",
".",
"text",
"=",
"','",
".",
"join",
"(",
"patterns",
")",
"p",
"=",
"XML",
".",
"SubElement",
"(",
"m2repo",
",",
"'patterns'",
")",
"for",
"pattern",
"in",
"patterns",
":",
"XML",
".",
"SubElement",
"(",
"p",
",",
"'string'",
")",
".",
"text",
"=",
"pattern"
] |
yaml: m2-repository-cleanup configure m2 repository cleanup requires the jenkins :jenkins-wiki:m2 repository cleanup <m2+repository+cleanup+plugin> .
|
train
| false
|
8,158
|
def _limited_traceback(excinfo):
tb = extract_tb(excinfo.tb)
try:
idx = [(__file__ in e) for e in tb].index(True)
return format_list(tb[(idx + 1):])
except ValueError:
return format_list(tb)
|
[
"def",
"_limited_traceback",
"(",
"excinfo",
")",
":",
"tb",
"=",
"extract_tb",
"(",
"excinfo",
".",
"tb",
")",
"try",
":",
"idx",
"=",
"[",
"(",
"__file__",
"in",
"e",
")",
"for",
"e",
"in",
"tb",
"]",
".",
"index",
"(",
"True",
")",
"return",
"format_list",
"(",
"tb",
"[",
"(",
"idx",
"+",
"1",
")",
":",
"]",
")",
"except",
"ValueError",
":",
"return",
"format_list",
"(",
"tb",
")"
] |
return a formatted traceback with all the stack from this frame up removed .
|
train
| false
|
8,160
|
def log_bugdown_error(msg):
logging.getLogger('').error(msg)
|
[
"def",
"log_bugdown_error",
"(",
"msg",
")",
":",
"logging",
".",
"getLogger",
"(",
"''",
")",
".",
"error",
"(",
"msg",
")"
] |
we use this unusual logging approach to log the bugdown error .
|
train
| false
|
8,161
|
def check_order(group):
global skip_order_check
try:
if (skip_order_check or (len(group) < 2)):
skip_order_check = False
return
if any(((group[0][0] != labels[0]) for labels in group)):
warning('Domain group TLD is not consistent')
sorted_group = sorted(group, key=(lambda labels: (len(labels), psl_key(labels[(-1)][0]), labels)))
if (group != sorted_group):
warning('Incorrectly sorted group of domains')
print (' ' + str(group))
print (' ' + str(sorted_group))
print 'Correct sorting would be:'
print_psl(sorted_group)
finally:
del group[:]
|
[
"def",
"check_order",
"(",
"group",
")",
":",
"global",
"skip_order_check",
"try",
":",
"if",
"(",
"skip_order_check",
"or",
"(",
"len",
"(",
"group",
")",
"<",
"2",
")",
")",
":",
"skip_order_check",
"=",
"False",
"return",
"if",
"any",
"(",
"(",
"(",
"group",
"[",
"0",
"]",
"[",
"0",
"]",
"!=",
"labels",
"[",
"0",
"]",
")",
"for",
"labels",
"in",
"group",
")",
")",
":",
"warning",
"(",
"'Domain group TLD is not consistent'",
")",
"sorted_group",
"=",
"sorted",
"(",
"group",
",",
"key",
"=",
"(",
"lambda",
"labels",
":",
"(",
"len",
"(",
"labels",
")",
",",
"psl_key",
"(",
"labels",
"[",
"(",
"-",
"1",
")",
"]",
"[",
"0",
"]",
")",
",",
"labels",
")",
")",
")",
"if",
"(",
"group",
"!=",
"sorted_group",
")",
":",
"warning",
"(",
"'Incorrectly sorted group of domains'",
")",
"print",
"(",
"' '",
"+",
"str",
"(",
"group",
")",
")",
"print",
"(",
"' '",
"+",
"str",
"(",
"sorted_group",
")",
")",
"print",
"'Correct sorting would be:'",
"print_psl",
"(",
"sorted_group",
")",
"finally",
":",
"del",
"group",
"[",
":",
"]"
] |
check the correct order of a domain group .
|
train
| false
|
8,162
|
def app_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
if ('class' in options):
assert ('classes' not in options)
options['classes'] = options['class']
del options['class']
return ([nodes.inline(rawtext, utils.unescape(text), **options)], [])
|
[
"def",
"app_role",
"(",
"role",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"{",
"}",
",",
"content",
"=",
"[",
"]",
")",
":",
"if",
"(",
"'class'",
"in",
"options",
")",
":",
"assert",
"(",
"'classes'",
"not",
"in",
"options",
")",
"options",
"[",
"'classes'",
"]",
"=",
"options",
"[",
"'class'",
"]",
"del",
"options",
"[",
"'class'",
"]",
"return",
"(",
"[",
"nodes",
".",
"inline",
"(",
"rawtext",
",",
"utils",
".",
"unescape",
"(",
"text",
")",
",",
"**",
"options",
")",
"]",
",",
"[",
"]",
")"
] |
custom role for :app: marker .
|
train
| false
|
8,164
|
def testmod_paths_from_testdir(testdir):
for path in glob.glob(join(testdir, 'test_*.py')):
(yield path)
for path in glob.glob(join(testdir, 'test_*')):
if (not isdir(path)):
continue
if (not isfile(join(path, '__init__.py'))):
continue
(yield path)
|
[
"def",
"testmod_paths_from_testdir",
"(",
"testdir",
")",
":",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"join",
"(",
"testdir",
",",
"'test_*.py'",
")",
")",
":",
"(",
"yield",
"path",
")",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"join",
"(",
"testdir",
",",
"'test_*'",
")",
")",
":",
"if",
"(",
"not",
"isdir",
"(",
"path",
")",
")",
":",
"continue",
"if",
"(",
"not",
"isfile",
"(",
"join",
"(",
"path",
",",
"'__init__.py'",
")",
")",
")",
":",
"continue",
"(",
"yield",
"path",
")"
] |
generate test module paths in the given dir .
|
train
| false
|
8,165
|
def add_lang_dict(code):
messages = extract_messages_from_code(code)
messages = [message for (pos, message) in messages]
code += (u'\n\n$.extend(frappe._messages, %s)' % json.dumps(make_dict_from_messages(messages)))
return code
|
[
"def",
"add_lang_dict",
"(",
"code",
")",
":",
"messages",
"=",
"extract_messages_from_code",
"(",
"code",
")",
"messages",
"=",
"[",
"message",
"for",
"(",
"pos",
",",
"message",
")",
"in",
"messages",
"]",
"code",
"+=",
"(",
"u'\\n\\n$.extend(frappe._messages, %s)'",
"%",
"json",
".",
"dumps",
"(",
"make_dict_from_messages",
"(",
"messages",
")",
")",
")",
"return",
"code"
] |
extracts messages and returns javascript code snippet to be appened at the end of the given script .
|
train
| false
|
8,166
|
def ignore_cidr(vm_, ip):
if (HAS_NETADDR is False):
log.error('Error: netaddr is not installed')
return 'Error: netaddr is not installed'
cidr = config.get_cloud_config_value('ignore_cidr', vm_, __opts__, default='', search_global=False)
if ((cidr != '') and all_matching_cidrs(ip, [cidr])):
log.warning('IP "{0}" found within "{1}"; ignoring it.'.format(ip, cidr))
return True
return False
|
[
"def",
"ignore_cidr",
"(",
"vm_",
",",
"ip",
")",
":",
"if",
"(",
"HAS_NETADDR",
"is",
"False",
")",
":",
"log",
".",
"error",
"(",
"'Error: netaddr is not installed'",
")",
"return",
"'Error: netaddr is not installed'",
"cidr",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'ignore_cidr'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"''",
",",
"search_global",
"=",
"False",
")",
"if",
"(",
"(",
"cidr",
"!=",
"''",
")",
"and",
"all_matching_cidrs",
"(",
"ip",
",",
"[",
"cidr",
"]",
")",
")",
":",
"log",
".",
"warning",
"(",
"'IP \"{0}\" found within \"{1}\"; ignoring it.'",
".",
"format",
"(",
"ip",
",",
"cidr",
")",
")",
"return",
"True",
"return",
"False"
] |
return true if we are to ignore the specified ip .
|
train
| true
|
8,168
|
def create_container_for_test(case, client, name=None):
if (name is None):
name = random_name(case=case)
expected_container = Container(node_uuid=uuid4(), name=name, image=DockerImage.from_string(u'nginx'))
d = client.create_container(node_uuid=expected_container.node_uuid, name=expected_container.name, image=expected_container.image)
return (expected_container, d)
|
[
"def",
"create_container_for_test",
"(",
"case",
",",
"client",
",",
"name",
"=",
"None",
")",
":",
"if",
"(",
"name",
"is",
"None",
")",
":",
"name",
"=",
"random_name",
"(",
"case",
"=",
"case",
")",
"expected_container",
"=",
"Container",
"(",
"node_uuid",
"=",
"uuid4",
"(",
")",
",",
"name",
"=",
"name",
",",
"image",
"=",
"DockerImage",
".",
"from_string",
"(",
"u'nginx'",
")",
")",
"d",
"=",
"client",
".",
"create_container",
"(",
"node_uuid",
"=",
"expected_container",
".",
"node_uuid",
",",
"name",
"=",
"expected_container",
".",
"name",
",",
"image",
"=",
"expected_container",
".",
"image",
")",
"return",
"(",
"expected_container",
",",
"d",
")"
] |
use the api client to create a new container for the running test .
|
train
| false
|
8,170
|
def isBytes(b):
return isinstance(b, bytes_type)
|
[
"def",
"isBytes",
"(",
"b",
")",
":",
"return",
"isinstance",
"(",
"b",
",",
"bytes_type",
")"
] |
test if arg is a bytes instance .
|
train
| false
|
8,173
|
def test_parse_nav_steps():
print sys.path
arg_str = 'selector click'
expected_output = {'runhandler': '_command_handler', 'args': {'commands': [{'action': 'click', 'options': [], 'selector': 'selector'}]}}
actual_output = screenshot._parse_nav_steps(arg_str)
assert_equal(expected_output, actual_output)
arg_str = 'selector click | selector2 click'
expected_output = {'runhandler': '_command_handler', 'args': {'commands': [{'action': 'click', 'options': [], 'selector': 'selector'}, {'action': 'click', 'options': [], 'selector': 'selector2'}]}}
actual_output = screenshot._parse_nav_steps(arg_str)
assert_equal(expected_output, actual_output)
arg_str = ''
expected_output = {'runhandler': '_command_handler', 'args': {'commands': []}}
actual_output = screenshot._parse_nav_steps(arg_str)
assert_equal(expected_output, actual_output)
|
[
"def",
"test_parse_nav_steps",
"(",
")",
":",
"print",
"sys",
".",
"path",
"arg_str",
"=",
"'selector click'",
"expected_output",
"=",
"{",
"'runhandler'",
":",
"'_command_handler'",
",",
"'args'",
":",
"{",
"'commands'",
":",
"[",
"{",
"'action'",
":",
"'click'",
",",
"'options'",
":",
"[",
"]",
",",
"'selector'",
":",
"'selector'",
"}",
"]",
"}",
"}",
"actual_output",
"=",
"screenshot",
".",
"_parse_nav_steps",
"(",
"arg_str",
")",
"assert_equal",
"(",
"expected_output",
",",
"actual_output",
")",
"arg_str",
"=",
"'selector click | selector2 click'",
"expected_output",
"=",
"{",
"'runhandler'",
":",
"'_command_handler'",
",",
"'args'",
":",
"{",
"'commands'",
":",
"[",
"{",
"'action'",
":",
"'click'",
",",
"'options'",
":",
"[",
"]",
",",
"'selector'",
":",
"'selector'",
"}",
",",
"{",
"'action'",
":",
"'click'",
",",
"'options'",
":",
"[",
"]",
",",
"'selector'",
":",
"'selector2'",
"}",
"]",
"}",
"}",
"actual_output",
"=",
"screenshot",
".",
"_parse_nav_steps",
"(",
"arg_str",
")",
"assert_equal",
"(",
"expected_output",
",",
"actual_output",
")",
"arg_str",
"=",
"''",
"expected_output",
"=",
"{",
"'runhandler'",
":",
"'_command_handler'",
",",
"'args'",
":",
"{",
"'commands'",
":",
"[",
"]",
"}",
"}",
"actual_output",
"=",
"screenshot",
".",
"_parse_nav_steps",
"(",
"arg_str",
")",
"assert_equal",
"(",
"expected_output",
",",
"actual_output",
")"
] |
test screenshot .
|
train
| false
|
8,174
|
def is_valid_source(src, fulls, prefixes):
return ((src in fulls) or any(((p in src) for p in prefixes)))
|
[
"def",
"is_valid_source",
"(",
"src",
",",
"fulls",
",",
"prefixes",
")",
":",
"return",
"(",
"(",
"src",
"in",
"fulls",
")",
"or",
"any",
"(",
"(",
"(",
"p",
"in",
"src",
")",
"for",
"p",
"in",
"prefixes",
")",
")",
")"
] |
return true if the source is valid .
|
train
| false
|
8,175
|
@task
def addon_total_contributions(*addons, **kw):
log.info(('[%s@%s] Updating total contributions.' % (len(addons), addon_total_contributions.rate_limit)))
stats = Contribution.objects.filter(addon__in=addons, uuid=None).values_list('addon').annotate(Sum('amount'))
for (addon, total) in stats:
Addon.objects.filter(id=addon).update(total_contributions=total)
|
[
"@",
"task",
"def",
"addon_total_contributions",
"(",
"*",
"addons",
",",
"**",
"kw",
")",
":",
"log",
".",
"info",
"(",
"(",
"'[%s@%s] Updating total contributions.'",
"%",
"(",
"len",
"(",
"addons",
")",
",",
"addon_total_contributions",
".",
"rate_limit",
")",
")",
")",
"stats",
"=",
"Contribution",
".",
"objects",
".",
"filter",
"(",
"addon__in",
"=",
"addons",
",",
"uuid",
"=",
"None",
")",
".",
"values_list",
"(",
"'addon'",
")",
".",
"annotate",
"(",
"Sum",
"(",
"'amount'",
")",
")",
"for",
"(",
"addon",
",",
"total",
")",
"in",
"stats",
":",
"Addon",
".",
"objects",
".",
"filter",
"(",
"id",
"=",
"addon",
")",
".",
"update",
"(",
"total_contributions",
"=",
"total",
")"
] |
updates the total contributions for a given addon .
|
train
| false
|
8,176
|
def _image_get(context, image_id, session=None, force_show_deleted=False):
session = (session or get_session())
try:
query = session.query(models.Image).options(sa_orm.joinedload(models.Image.properties)).options(sa_orm.joinedload(models.Image.locations)).filter_by(id=image_id)
if ((not force_show_deleted) and (not _can_show_deleted(context))):
query = query.filter_by(deleted=False)
image = query.one()
except sa_orm.exc.NoResultFound:
raise exception.NotFound(('No image found with ID %s' % image_id))
if (not is_image_visible(context, image)):
raise exception.Forbidden('Image not visible to you')
return image
|
[
"def",
"_image_get",
"(",
"context",
",",
"image_id",
",",
"session",
"=",
"None",
",",
"force_show_deleted",
"=",
"False",
")",
":",
"session",
"=",
"(",
"session",
"or",
"get_session",
"(",
")",
")",
"try",
":",
"query",
"=",
"session",
".",
"query",
"(",
"models",
".",
"Image",
")",
".",
"options",
"(",
"sa_orm",
".",
"joinedload",
"(",
"models",
".",
"Image",
".",
"properties",
")",
")",
".",
"options",
"(",
"sa_orm",
".",
"joinedload",
"(",
"models",
".",
"Image",
".",
"locations",
")",
")",
".",
"filter_by",
"(",
"id",
"=",
"image_id",
")",
"if",
"(",
"(",
"not",
"force_show_deleted",
")",
"and",
"(",
"not",
"_can_show_deleted",
"(",
"context",
")",
")",
")",
":",
"query",
"=",
"query",
".",
"filter_by",
"(",
"deleted",
"=",
"False",
")",
"image",
"=",
"query",
".",
"one",
"(",
")",
"except",
"sa_orm",
".",
"exc",
".",
"NoResultFound",
":",
"raise",
"exception",
".",
"NotFound",
"(",
"(",
"'No image found with ID %s'",
"%",
"image_id",
")",
")",
"if",
"(",
"not",
"is_image_visible",
"(",
"context",
",",
"image",
")",
")",
":",
"raise",
"exception",
".",
"Forbidden",
"(",
"'Image not visible to you'",
")",
"return",
"image"
] |
get an image or raise if it does not exist .
|
train
| false
|
8,177
|
def buildCompletedList(series_id, question_id_list):
db = current.db
qtable = current.s3db.survey_question
headers = []
happend = headers.append
types = []
items = []
qstn_posn = 0
row_len = len(question_id_list)
complete_lookup = {}
for question_id in question_id_list:
answers = survey_getAllAnswersForQuestionInSeries(question_id, series_id)
widget_obj = survey_getWidgetFromQuestion(question_id)
question = db((qtable.id == question_id)).select(qtable.name, limitby=(0, 1)).first()
happend(question.name)
types.append(widget_obj.db_type())
for answer in answers:
complete_id = answer['complete_id']
if (complete_id in complete_lookup):
row = complete_lookup[complete_id]
else:
row = len(complete_lookup)
complete_lookup[complete_id] = row
items.append(([''] * row_len))
items[row][qstn_posn] = widget_obj.repr(answer['value'])
qstn_posn += 1
return (([headers] + [types]) + items)
|
[
"def",
"buildCompletedList",
"(",
"series_id",
",",
"question_id_list",
")",
":",
"db",
"=",
"current",
".",
"db",
"qtable",
"=",
"current",
".",
"s3db",
".",
"survey_question",
"headers",
"=",
"[",
"]",
"happend",
"=",
"headers",
".",
"append",
"types",
"=",
"[",
"]",
"items",
"=",
"[",
"]",
"qstn_posn",
"=",
"0",
"row_len",
"=",
"len",
"(",
"question_id_list",
")",
"complete_lookup",
"=",
"{",
"}",
"for",
"question_id",
"in",
"question_id_list",
":",
"answers",
"=",
"survey_getAllAnswersForQuestionInSeries",
"(",
"question_id",
",",
"series_id",
")",
"widget_obj",
"=",
"survey_getWidgetFromQuestion",
"(",
"question_id",
")",
"question",
"=",
"db",
"(",
"(",
"qtable",
".",
"id",
"==",
"question_id",
")",
")",
".",
"select",
"(",
"qtable",
".",
"name",
",",
"limitby",
"=",
"(",
"0",
",",
"1",
")",
")",
".",
"first",
"(",
")",
"happend",
"(",
"question",
".",
"name",
")",
"types",
".",
"append",
"(",
"widget_obj",
".",
"db_type",
"(",
")",
")",
"for",
"answer",
"in",
"answers",
":",
"complete_id",
"=",
"answer",
"[",
"'complete_id'",
"]",
"if",
"(",
"complete_id",
"in",
"complete_lookup",
")",
":",
"row",
"=",
"complete_lookup",
"[",
"complete_id",
"]",
"else",
":",
"row",
"=",
"len",
"(",
"complete_lookup",
")",
"complete_lookup",
"[",
"complete_id",
"]",
"=",
"row",
"items",
".",
"append",
"(",
"(",
"[",
"''",
"]",
"*",
"row_len",
")",
")",
"items",
"[",
"row",
"]",
"[",
"qstn_posn",
"]",
"=",
"widget_obj",
".",
"repr",
"(",
"answer",
"[",
"'value'",
"]",
")",
"qstn_posn",
"+=",
"1",
"return",
"(",
"(",
"[",
"headers",
"]",
"+",
"[",
"types",
"]",
")",
"+",
"items",
")"
] |
build a list of completed items for the series including just the questions in the list passed in the list will come in three parts .
|
train
| false
|
8,179
|
def db_clean_all(autotest_dir):
for test in models.Test.objects.all():
logging.info('Removing %s', test.path)
_log_or_execute(repr(test), test.delete)
for profiler in models.Profiler.objects.all():
logging.info('Removing %s', profiler.name)
_log_or_execute(repr(profiler), profiler.delete)
|
[
"def",
"db_clean_all",
"(",
"autotest_dir",
")",
":",
"for",
"test",
"in",
"models",
".",
"Test",
".",
"objects",
".",
"all",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'Removing %s'",
",",
"test",
".",
"path",
")",
"_log_or_execute",
"(",
"repr",
"(",
"test",
")",
",",
"test",
".",
"delete",
")",
"for",
"profiler",
"in",
"models",
".",
"Profiler",
".",
"objects",
".",
"all",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'Removing %s'",
",",
"profiler",
".",
"name",
")",
"_log_or_execute",
"(",
"repr",
"(",
"profiler",
")",
",",
"profiler",
".",
"delete",
")"
] |
remove all tests from autotest_web - very destructive this function invoked when -c supplied on the command line .
|
train
| false
|
8,180
|
def get_cell_type():
if (not CONF.cells.enable):
return
return CONF.cells.cell_type
|
[
"def",
"get_cell_type",
"(",
")",
":",
"if",
"(",
"not",
"CONF",
".",
"cells",
".",
"enable",
")",
":",
"return",
"return",
"CONF",
".",
"cells",
".",
"cell_type"
] |
return the cell type .
|
train
| false
|
8,181
|
def magics_class(cls):
cls.registered = True
cls.magics = dict(line=magics['line'], cell=magics['cell'])
magics['line'] = {}
magics['cell'] = {}
return cls
|
[
"def",
"magics_class",
"(",
"cls",
")",
":",
"cls",
".",
"registered",
"=",
"True",
"cls",
".",
"magics",
"=",
"dict",
"(",
"line",
"=",
"magics",
"[",
"'line'",
"]",
",",
"cell",
"=",
"magics",
"[",
"'cell'",
"]",
")",
"magics",
"[",
"'line'",
"]",
"=",
"{",
"}",
"magics",
"[",
"'cell'",
"]",
"=",
"{",
"}",
"return",
"cls"
] |
class decorator for all subclasses of the main magics class .
|
train
| true
|
8,182
|
def LoadChecksFromFiles(file_paths, overwrite_if_exists=True):
loaded = []
for file_path in file_paths:
configs = LoadConfigsFromFile(file_path)
for conf in configs.values():
check = Check(**conf)
check.Validate()
loaded.append(check)
CheckRegistry.RegisterCheck(check, source=('file:%s' % file_path), overwrite_if_exists=overwrite_if_exists)
logging.debug('Loaded check %s from %s', check.check_id, file_path)
return loaded
|
[
"def",
"LoadChecksFromFiles",
"(",
"file_paths",
",",
"overwrite_if_exists",
"=",
"True",
")",
":",
"loaded",
"=",
"[",
"]",
"for",
"file_path",
"in",
"file_paths",
":",
"configs",
"=",
"LoadConfigsFromFile",
"(",
"file_path",
")",
"for",
"conf",
"in",
"configs",
".",
"values",
"(",
")",
":",
"check",
"=",
"Check",
"(",
"**",
"conf",
")",
"check",
".",
"Validate",
"(",
")",
"loaded",
".",
"append",
"(",
"check",
")",
"CheckRegistry",
".",
"RegisterCheck",
"(",
"check",
",",
"source",
"=",
"(",
"'file:%s'",
"%",
"file_path",
")",
",",
"overwrite_if_exists",
"=",
"overwrite_if_exists",
")",
"logging",
".",
"debug",
"(",
"'Loaded check %s from %s'",
",",
"check",
".",
"check_id",
",",
"file_path",
")",
"return",
"loaded"
] |
load the checks defined in the specified files .
|
train
| true
|
8,184
|
def tag_create(repo, tag, author=None, message=None, annotated=False, objectish='HEAD', tag_time=None, tag_timezone=None):
with open_repo_closing(repo) as r:
object = parse_object(r, objectish)
if annotated:
tag_obj = Tag()
if (author is None):
author = r._get_user_identity()
tag_obj.tagger = author
tag_obj.message = message
tag_obj.name = tag
tag_obj.object = (type(object), object.id)
if (tag_time is None):
tag_time = int(time.time())
tag_obj.tag_time = tag_time
if (tag_timezone is None):
tag_timezone = 0
elif isinstance(tag_timezone, str):
tag_timezone = parse_timezone(tag_timezone)
tag_obj.tag_timezone = tag_timezone
r.object_store.add_object(tag_obj)
tag_id = tag_obj.id
else:
tag_id = object.id
r.refs[('refs/tags/' + tag)] = tag_id
|
[
"def",
"tag_create",
"(",
"repo",
",",
"tag",
",",
"author",
"=",
"None",
",",
"message",
"=",
"None",
",",
"annotated",
"=",
"False",
",",
"objectish",
"=",
"'HEAD'",
",",
"tag_time",
"=",
"None",
",",
"tag_timezone",
"=",
"None",
")",
":",
"with",
"open_repo_closing",
"(",
"repo",
")",
"as",
"r",
":",
"object",
"=",
"parse_object",
"(",
"r",
",",
"objectish",
")",
"if",
"annotated",
":",
"tag_obj",
"=",
"Tag",
"(",
")",
"if",
"(",
"author",
"is",
"None",
")",
":",
"author",
"=",
"r",
".",
"_get_user_identity",
"(",
")",
"tag_obj",
".",
"tagger",
"=",
"author",
"tag_obj",
".",
"message",
"=",
"message",
"tag_obj",
".",
"name",
"=",
"tag",
"tag_obj",
".",
"object",
"=",
"(",
"type",
"(",
"object",
")",
",",
"object",
".",
"id",
")",
"if",
"(",
"tag_time",
"is",
"None",
")",
":",
"tag_time",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"tag_obj",
".",
"tag_time",
"=",
"tag_time",
"if",
"(",
"tag_timezone",
"is",
"None",
")",
":",
"tag_timezone",
"=",
"0",
"elif",
"isinstance",
"(",
"tag_timezone",
",",
"str",
")",
":",
"tag_timezone",
"=",
"parse_timezone",
"(",
"tag_timezone",
")",
"tag_obj",
".",
"tag_timezone",
"=",
"tag_timezone",
"r",
".",
"object_store",
".",
"add_object",
"(",
"tag_obj",
")",
"tag_id",
"=",
"tag_obj",
".",
"id",
"else",
":",
"tag_id",
"=",
"object",
".",
"id",
"r",
".",
"refs",
"[",
"(",
"'refs/tags/'",
"+",
"tag",
")",
"]",
"=",
"tag_id"
] |
create a new vocabulary tag .
|
train
| false
|
8,185
|
def full_info():
return {'node_info': node_info(), 'vm_info': vm_info()}
|
[
"def",
"full_info",
"(",
")",
":",
"return",
"{",
"'node_info'",
":",
"node_info",
"(",
")",
",",
"'vm_info'",
":",
"vm_info",
"(",
")",
"}"
] |
return the node_info .
|
train
| false
|
8,188
|
def getBracketEvaluators(bracketBeginIndex, bracketEndIndex, evaluators):
return getEvaluatedExpressionValueEvaluators(evaluators[(bracketBeginIndex + 1):bracketEndIndex])
|
[
"def",
"getBracketEvaluators",
"(",
"bracketBeginIndex",
",",
"bracketEndIndex",
",",
"evaluators",
")",
":",
"return",
"getEvaluatedExpressionValueEvaluators",
"(",
"evaluators",
"[",
"(",
"bracketBeginIndex",
"+",
"1",
")",
":",
"bracketEndIndex",
"]",
")"
] |
get the bracket evaluators .
|
train
| false
|
8,190
|
def is_youtube_available():
return False
|
[
"def",
"is_youtube_available",
"(",
")",
":",
"return",
"False"
] |
check if the required youtube urls are available .
|
train
| false
|
8,191
|
def sieve(param=None, **kwargs):
def _sieve_hook(func):
assert (len(inspect.getargspec(func).args) == 3), 'Sieve plugin has incorrect argument count. Needs params: bot, input, plugin'
hook = _get_hook(func, 'sieve')
if (hook is None):
hook = _Hook(func, 'sieve')
_add_hook(func, hook)
hook._add_hook(kwargs)
return func
if callable(param):
return _sieve_hook(param)
else:
return (lambda func: _sieve_hook(func))
|
[
"def",
"sieve",
"(",
"param",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"def",
"_sieve_hook",
"(",
"func",
")",
":",
"assert",
"(",
"len",
"(",
"inspect",
".",
"getargspec",
"(",
"func",
")",
".",
"args",
")",
"==",
"3",
")",
",",
"'Sieve plugin has incorrect argument count. Needs params: bot, input, plugin'",
"hook",
"=",
"_get_hook",
"(",
"func",
",",
"'sieve'",
")",
"if",
"(",
"hook",
"is",
"None",
")",
":",
"hook",
"=",
"_Hook",
"(",
"func",
",",
"'sieve'",
")",
"_add_hook",
"(",
"func",
",",
"hook",
")",
"hook",
".",
"_add_hook",
"(",
"kwargs",
")",
"return",
"func",
"if",
"callable",
"(",
"param",
")",
":",
"return",
"_sieve_hook",
"(",
"param",
")",
"else",
":",
"return",
"(",
"lambda",
"func",
":",
"_sieve_hook",
"(",
"func",
")",
")"
] |
external sieve decorator .
|
train
| false
|
8,192
|
def format_reflog_line(old_sha, new_sha, committer, timestamp, timezone, message):
if (old_sha is None):
old_sha = ZERO_SHA
return ((((((((((old_sha + ' ') + new_sha) + ' ') + committer) + ' ') + str(timestamp).encode('ascii')) + ' ') + format_timezone(timezone)) + ' DCTB ') + message)
|
[
"def",
"format_reflog_line",
"(",
"old_sha",
",",
"new_sha",
",",
"committer",
",",
"timestamp",
",",
"timezone",
",",
"message",
")",
":",
"if",
"(",
"old_sha",
"is",
"None",
")",
":",
"old_sha",
"=",
"ZERO_SHA",
"return",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"(",
"old_sha",
"+",
"' '",
")",
"+",
"new_sha",
")",
"+",
"' '",
")",
"+",
"committer",
")",
"+",
"' '",
")",
"+",
"str",
"(",
"timestamp",
")",
".",
"encode",
"(",
"'ascii'",
")",
")",
"+",
"' '",
")",
"+",
"format_timezone",
"(",
"timezone",
")",
")",
"+",
"' DCTB '",
")",
"+",
"message",
")"
] |
generate a single reflog line .
|
train
| false
|
8,194
|
def test_isotime():
time = datetime(2009, 12, 25, 10, 11, 12)
eq_(isotime(time), '2009-12-25T18:11:12Z')
assert (isotime(None) is None)
|
[
"def",
"test_isotime",
"(",
")",
":",
"time",
"=",
"datetime",
"(",
"2009",
",",
"12",
",",
"25",
",",
"10",
",",
"11",
",",
"12",
")",
"eq_",
"(",
"isotime",
"(",
"time",
")",
",",
"'2009-12-25T18:11:12Z'",
")",
"assert",
"(",
"isotime",
"(",
"None",
")",
"is",
"None",
")"
] |
test isotime helper .
|
train
| false
|
8,195
|
def _configure_buffer_sizes():
global PIPE_BUF_BYTES
global OS_PIPE_SZ
PIPE_BUF_BYTES = 65536
OS_PIPE_SZ = None
if (not hasattr(fcntl, 'F_SETPIPE_SZ')):
import platform
if (platform.system() == 'Linux'):
fcntl.F_SETPIPE_SZ = 1031
try:
with open('/proc/sys/fs/pipe-max-size', 'r') as f:
OS_PIPE_SZ = min(int(f.read()), (1024 * 1024))
PIPE_BUF_BYTES = max(OS_PIPE_SZ, PIPE_BUF_BYTES)
except:
pass
|
[
"def",
"_configure_buffer_sizes",
"(",
")",
":",
"global",
"PIPE_BUF_BYTES",
"global",
"OS_PIPE_SZ",
"PIPE_BUF_BYTES",
"=",
"65536",
"OS_PIPE_SZ",
"=",
"None",
"if",
"(",
"not",
"hasattr",
"(",
"fcntl",
",",
"'F_SETPIPE_SZ'",
")",
")",
":",
"import",
"platform",
"if",
"(",
"platform",
".",
"system",
"(",
")",
"==",
"'Linux'",
")",
":",
"fcntl",
".",
"F_SETPIPE_SZ",
"=",
"1031",
"try",
":",
"with",
"open",
"(",
"'/proc/sys/fs/pipe-max-size'",
",",
"'r'",
")",
"as",
"f",
":",
"OS_PIPE_SZ",
"=",
"min",
"(",
"int",
"(",
"f",
".",
"read",
"(",
")",
")",
",",
"(",
"1024",
"*",
"1024",
")",
")",
"PIPE_BUF_BYTES",
"=",
"max",
"(",
"OS_PIPE_SZ",
",",
"PIPE_BUF_BYTES",
")",
"except",
":",
"pass"
] |
set up module globals controlling buffer sizes .
|
train
| true
|
8,196
|
def _get_name_and_version(name, version, for_filename=False):
if for_filename:
name = _FILESAFE.sub(u'-', name)
version = _FILESAFE.sub(u'-', version.replace(u' ', u'.'))
return (u'%s-%s' % (name, version))
|
[
"def",
"_get_name_and_version",
"(",
"name",
",",
"version",
",",
"for_filename",
"=",
"False",
")",
":",
"if",
"for_filename",
":",
"name",
"=",
"_FILESAFE",
".",
"sub",
"(",
"u'-'",
",",
"name",
")",
"version",
"=",
"_FILESAFE",
".",
"sub",
"(",
"u'-'",
",",
"version",
".",
"replace",
"(",
"u' '",
",",
"u'.'",
")",
")",
"return",
"(",
"u'%s-%s'",
"%",
"(",
"name",
",",
"version",
")",
")"
] |
return the distribution name with version .
|
train
| false
|
8,198
|
def _libvirt_creds():
g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf'
u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf'
try:
stdout = subprocess.Popen(g_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
group = salt.utils.to_str(stdout).split('"')[1]
except IndexError:
group = 'root'
try:
stdout = subprocess.Popen(u_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
user = salt.utils.to_str(stdout).split('"')[1]
except IndexError:
user = 'root'
return {'user': user, 'group': group}
|
[
"def",
"_libvirt_creds",
"(",
")",
":",
"g_cmd",
"=",
"'grep ^\\\\s*group /etc/libvirt/qemu.conf'",
"u_cmd",
"=",
"'grep ^\\\\s*user /etc/libvirt/qemu.conf'",
"try",
":",
"stdout",
"=",
"subprocess",
".",
"Popen",
"(",
"g_cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"group",
"=",
"salt",
".",
"utils",
".",
"to_str",
"(",
"stdout",
")",
".",
"split",
"(",
"'\"'",
")",
"[",
"1",
"]",
"except",
"IndexError",
":",
"group",
"=",
"'root'",
"try",
":",
"stdout",
"=",
"subprocess",
".",
"Popen",
"(",
"u_cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"user",
"=",
"salt",
".",
"utils",
".",
"to_str",
"(",
"stdout",
")",
".",
"split",
"(",
"'\"'",
")",
"[",
"1",
"]",
"except",
"IndexError",
":",
"user",
"=",
"'root'",
"return",
"{",
"'user'",
":",
"user",
",",
"'group'",
":",
"group",
"}"
] |
returns the user and group that the disk images should be owned by .
|
train
| true
|
8,200
|
def resource_view_show(context, data_dict):
model = context['model']
id = _get_or_bust(data_dict, 'id')
resource_view = model.ResourceView.get(id)
if (not resource_view):
_check_access('resource_view_show', context, data_dict)
raise NotFound
context['resource_view'] = resource_view
context['resource'] = model.Resource.get(resource_view.resource_id)
_check_access('resource_view_show', context, data_dict)
return model_dictize.resource_view_dictize(resource_view, context)
|
[
"def",
"resource_view_show",
"(",
"context",
",",
"data_dict",
")",
":",
"model",
"=",
"context",
"[",
"'model'",
"]",
"id",
"=",
"_get_or_bust",
"(",
"data_dict",
",",
"'id'",
")",
"resource_view",
"=",
"model",
".",
"ResourceView",
".",
"get",
"(",
"id",
")",
"if",
"(",
"not",
"resource_view",
")",
":",
"_check_access",
"(",
"'resource_view_show'",
",",
"context",
",",
"data_dict",
")",
"raise",
"NotFound",
"context",
"[",
"'resource_view'",
"]",
"=",
"resource_view",
"context",
"[",
"'resource'",
"]",
"=",
"model",
".",
"Resource",
".",
"get",
"(",
"resource_view",
".",
"resource_id",
")",
"_check_access",
"(",
"'resource_view_show'",
",",
"context",
",",
"data_dict",
")",
"return",
"model_dictize",
".",
"resource_view_dictize",
"(",
"resource_view",
",",
"context",
")"
] |
return the metadata of a resource_view .
|
train
| false
|
8,201
|
def set_mp_process_title(progname, info=None, hostname=None):
if hostname:
progname = ('%s@%s' % (progname, hostname.split('.')[0]))
try:
from multiprocessing.process import current_process
except ImportError:
return set_process_title(progname, info=info)
else:
return set_process_title(('%s:%s' % (progname, current_process().name)), info=info)
|
[
"def",
"set_mp_process_title",
"(",
"progname",
",",
"info",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"hostname",
":",
"progname",
"=",
"(",
"'%s@%s'",
"%",
"(",
"progname",
",",
"hostname",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
")",
"try",
":",
"from",
"multiprocessing",
".",
"process",
"import",
"current_process",
"except",
"ImportError",
":",
"return",
"set_process_title",
"(",
"progname",
",",
"info",
"=",
"info",
")",
"else",
":",
"return",
"set_process_title",
"(",
"(",
"'%s:%s'",
"%",
"(",
"progname",
",",
"current_process",
"(",
")",
".",
"name",
")",
")",
",",
"info",
"=",
"info",
")"
] |
set the ps name using the multiprocessing process name .
|
train
| false
|
8,202
|
@requires_segment_info
def current_context(pl, segment_info):
name = segment_info[u'curframe'].f_code.co_name
if (name == u'<module>'):
name = os.path.basename(segment_info[u'curframe'].f_code.co_filename)
return name
|
[
"@",
"requires_segment_info",
"def",
"current_context",
"(",
"pl",
",",
"segment_info",
")",
":",
"name",
"=",
"segment_info",
"[",
"u'curframe'",
"]",
".",
"f_code",
".",
"co_name",
"if",
"(",
"name",
"==",
"u'<module>'",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"segment_info",
"[",
"u'curframe'",
"]",
".",
"f_code",
".",
"co_filename",
")",
"return",
"name"
] |
displays currently executed context name this is similar to :py:func:current_code_name .
|
train
| false
|
8,203
|
def _get_mod_deps(mod_name):
deps = {'ssl': ['setenvif', 'mime']}
return deps.get(mod_name, [])
|
[
"def",
"_get_mod_deps",
"(",
"mod_name",
")",
":",
"deps",
"=",
"{",
"'ssl'",
":",
"[",
"'setenvif'",
",",
"'mime'",
"]",
"}",
"return",
"deps",
".",
"get",
"(",
"mod_name",
",",
"[",
"]",
")"
] |
get known module dependencies .
|
train
| false
|
8,204
|
def make_managed_nodes(addresses, distribution):
[address_type] = set((type(address) for address in addresses))
if (address_type is list):
return [ManagedNode(address=address, private_address=private_address, distribution=distribution) for (private_address, address) in addresses]
else:
return [ManagedNode(address=address, distribution=distribution) for address in addresses]
|
[
"def",
"make_managed_nodes",
"(",
"addresses",
",",
"distribution",
")",
":",
"[",
"address_type",
"]",
"=",
"set",
"(",
"(",
"type",
"(",
"address",
")",
"for",
"address",
"in",
"addresses",
")",
")",
"if",
"(",
"address_type",
"is",
"list",
")",
":",
"return",
"[",
"ManagedNode",
"(",
"address",
"=",
"address",
",",
"private_address",
"=",
"private_address",
",",
"distribution",
"=",
"distribution",
")",
"for",
"(",
"private_address",
",",
"address",
")",
"in",
"addresses",
"]",
"else",
":",
"return",
"[",
"ManagedNode",
"(",
"address",
"=",
"address",
",",
"distribution",
"=",
"distribution",
")",
"for",
"address",
"in",
"addresses",
"]"
] |
create a list of managed nodes from a list of node addresses or address pairs .
|
train
| false
|
8,205
|
def check_utf8(string):
if (not string):
return False
try:
if isinstance(string, unicode):
string.encode('utf-8')
else:
string.decode('UTF-8')
return ('\x00' not in string)
except UnicodeError:
return False
|
[
"def",
"check_utf8",
"(",
"string",
")",
":",
"if",
"(",
"not",
"string",
")",
":",
"return",
"False",
"try",
":",
"if",
"isinstance",
"(",
"string",
",",
"unicode",
")",
":",
"string",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"string",
".",
"decode",
"(",
"'UTF-8'",
")",
"return",
"(",
"'\\x00'",
"not",
"in",
"string",
")",
"except",
"UnicodeError",
":",
"return",
"False"
] |
validate if a string is valid utf-8 str or unicode and that it does not contain any null character .
|
train
| false
|
8,207
|
def _parse_step_syslog(lines):
return _parse_step_syslog_from_log4j_records(_parse_hadoop_log4j_records(lines))
|
[
"def",
"_parse_step_syslog",
"(",
"lines",
")",
":",
"return",
"_parse_step_syslog_from_log4j_records",
"(",
"_parse_hadoop_log4j_records",
"(",
"lines",
")",
")"
] |
parse the syslog from the hadoop jar command .
|
train
| false
|
8,208
|
def largest_factor_relatively_prime(a, b):
while 1:
d = gcd(a, b)
if (d <= 1):
break
b = d
while 1:
(q, r) = divmod(a, d)
if (r > 0):
break
a = q
return a
|
[
"def",
"largest_factor_relatively_prime",
"(",
"a",
",",
"b",
")",
":",
"while",
"1",
":",
"d",
"=",
"gcd",
"(",
"a",
",",
"b",
")",
"if",
"(",
"d",
"<=",
"1",
")",
":",
"break",
"b",
"=",
"d",
"while",
"1",
":",
"(",
"q",
",",
"r",
")",
"=",
"divmod",
"(",
"a",
",",
"d",
")",
"if",
"(",
"r",
">",
"0",
")",
":",
"break",
"a",
"=",
"q",
"return",
"a"
] |
return the largest factor of a relatively prime to b .
|
train
| true
|
8,212
|
def status_to_string(dbus_status):
status_tuple = ((dbus_status & 1), (dbus_status & 2), (dbus_status & 4), (dbus_status & 8), (dbus_status & 16), (dbus_status & 32), (dbus_status & 64), (dbus_status & 128), (dbus_status & 256))
return [DBUS_STATUS_MAP[status] for status in status_tuple if status]
|
[
"def",
"status_to_string",
"(",
"dbus_status",
")",
":",
"status_tuple",
"=",
"(",
"(",
"dbus_status",
"&",
"1",
")",
",",
"(",
"dbus_status",
"&",
"2",
")",
",",
"(",
"dbus_status",
"&",
"4",
")",
",",
"(",
"dbus_status",
"&",
"8",
")",
",",
"(",
"dbus_status",
"&",
"16",
")",
",",
"(",
"dbus_status",
"&",
"32",
")",
",",
"(",
"dbus_status",
"&",
"64",
")",
",",
"(",
"dbus_status",
"&",
"128",
")",
",",
"(",
"dbus_status",
"&",
"256",
")",
")",
"return",
"[",
"DBUS_STATUS_MAP",
"[",
"status",
"]",
"for",
"status",
"in",
"status_tuple",
"if",
"status",
"]"
] |
converts a numeric dbus snapper status into a string cli example: .
|
train
| true
|
8,213
|
def compare_chemical_expression(s1, s2, ignore_state=False):
return (divide_chemical_expression(s1, s2, ignore_state) == 1)
|
[
"def",
"compare_chemical_expression",
"(",
"s1",
",",
"s2",
",",
"ignore_state",
"=",
"False",
")",
":",
"return",
"(",
"divide_chemical_expression",
"(",
"s1",
",",
"s2",
",",
"ignore_state",
")",
"==",
"1",
")"
] |
it does comparison between two expressions .
|
train
| false
|
8,214
|
def ip_quad_to_numstr(quad):
bytes = map(int, quad.split('.'))
packed = struct.pack('BBBB', *bytes)
return str(struct.unpack('>L', packed)[0])
|
[
"def",
"ip_quad_to_numstr",
"(",
"quad",
")",
":",
"bytes",
"=",
"map",
"(",
"int",
",",
"quad",
".",
"split",
"(",
"'.'",
")",
")",
"packed",
"=",
"struct",
".",
"pack",
"(",
"'BBBB'",
",",
"*",
"bytes",
")",
"return",
"str",
"(",
"struct",
".",
"unpack",
"(",
"'>L'",
",",
"packed",
")",
"[",
"0",
"]",
")"
] |
convert an ip address string to an ip number as a base-10 integer given in ascii representation .
|
train
| true
|
8,215
|
@register.as_tag
def tweets_for_user(*args):
return tweets_for(QUERY_TYPE_USER, args)
|
[
"@",
"register",
".",
"as_tag",
"def",
"tweets_for_user",
"(",
"*",
"args",
")",
":",
"return",
"tweets_for",
"(",
"QUERY_TYPE_USER",
",",
"args",
")"
] |
tweets for a user .
|
train
| false
|
8,216
|
def call_and_ignore_notfound_exc(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except exceptions.NotFound:
pass
|
[
"def",
"call_and_ignore_notfound_exc",
"(",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"exceptions",
".",
"NotFound",
":",
"pass"
] |
call the given function and pass if a notfound exception is raised .
|
train
| false
|
8,217
|
def _indentLines(str, indentLevels=1, indentFirstLine=True):
indent = (_ONE_INDENT * indentLevels)
lines = str.splitlines(True)
result = ''
if ((len(lines) > 0) and (not indentFirstLine)):
first = 1
result += lines[0]
else:
first = 0
for line in lines[first:]:
result += (indent + line)
return result
|
[
"def",
"_indentLines",
"(",
"str",
",",
"indentLevels",
"=",
"1",
",",
"indentFirstLine",
"=",
"True",
")",
":",
"indent",
"=",
"(",
"_ONE_INDENT",
"*",
"indentLevels",
")",
"lines",
"=",
"str",
".",
"splitlines",
"(",
"True",
")",
"result",
"=",
"''",
"if",
"(",
"(",
"len",
"(",
"lines",
")",
">",
"0",
")",
"and",
"(",
"not",
"indentFirstLine",
")",
")",
":",
"first",
"=",
"1",
"result",
"+=",
"lines",
"[",
"0",
"]",
"else",
":",
"first",
"=",
"0",
"for",
"line",
"in",
"lines",
"[",
"first",
":",
"]",
":",
"result",
"+=",
"(",
"indent",
"+",
"line",
")",
"return",
"result"
] |
indent all lines in the given string str: input string indentlevels: number of levels of indentation to apply indentfirstline: if false .
|
train
| true
|
8,218
|
def _try_convert(value):
def _negative_zero(value):
epsilon = 1e-07
return (0 if (abs(value) < epsilon) else value)
if (len(value) == 0):
return ''
if (value == 'None'):
return None
lowered_value = value.lower()
if (lowered_value == 'true'):
return True
if (lowered_value == 'false'):
return False
for (prefix, base) in [('0x', 16), ('0b', 2), ('0', 8), ('', 10)]:
try:
if lowered_value.startswith((prefix, ('-' + prefix))):
return int(lowered_value, base)
except ValueError:
pass
try:
return _negative_zero(float(value))
except ValueError:
return value
|
[
"def",
"_try_convert",
"(",
"value",
")",
":",
"def",
"_negative_zero",
"(",
"value",
")",
":",
"epsilon",
"=",
"1e-07",
"return",
"(",
"0",
"if",
"(",
"abs",
"(",
"value",
")",
"<",
"epsilon",
")",
"else",
"value",
")",
"if",
"(",
"len",
"(",
"value",
")",
"==",
"0",
")",
":",
"return",
"''",
"if",
"(",
"value",
"==",
"'None'",
")",
":",
"return",
"None",
"lowered_value",
"=",
"value",
".",
"lower",
"(",
")",
"if",
"(",
"lowered_value",
"==",
"'true'",
")",
":",
"return",
"True",
"if",
"(",
"lowered_value",
"==",
"'false'",
")",
":",
"return",
"False",
"for",
"(",
"prefix",
",",
"base",
")",
"in",
"[",
"(",
"'0x'",
",",
"16",
")",
",",
"(",
"'0b'",
",",
"2",
")",
",",
"(",
"'0'",
",",
"8",
")",
",",
"(",
"''",
",",
"10",
")",
"]",
":",
"try",
":",
"if",
"lowered_value",
".",
"startswith",
"(",
"(",
"prefix",
",",
"(",
"'-'",
"+",
"prefix",
")",
")",
")",
":",
"return",
"int",
"(",
"lowered_value",
",",
"base",
")",
"except",
"ValueError",
":",
"pass",
"try",
":",
"return",
"_negative_zero",
"(",
"float",
"(",
"value",
")",
")",
"except",
"ValueError",
":",
"return",
"value"
] |
return a non-string from a string or unicode .
|
train
| false
|
8,219
|
def _decimate_chpi(raw, decim=4):
raw_dec = RawArray(raw._data[:, ::decim], raw.info, first_samp=(raw.first_samp // decim))
raw_dec.info['sfreq'] /= decim
for coil in raw_dec.info['hpi_meas'][0]['hpi_coils']:
if (coil['coil_freq'] > raw_dec.info['sfreq']):
coil['coil_freq'] = np.mod(coil['coil_freq'], raw_dec.info['sfreq'])
if (coil['coil_freq'] > (raw_dec.info['sfreq'] / 2.0)):
coil['coil_freq'] = (raw_dec.info['sfreq'] - coil['coil_freq'])
return raw_dec
|
[
"def",
"_decimate_chpi",
"(",
"raw",
",",
"decim",
"=",
"4",
")",
":",
"raw_dec",
"=",
"RawArray",
"(",
"raw",
".",
"_data",
"[",
":",
",",
":",
":",
"decim",
"]",
",",
"raw",
".",
"info",
",",
"first_samp",
"=",
"(",
"raw",
".",
"first_samp",
"//",
"decim",
")",
")",
"raw_dec",
".",
"info",
"[",
"'sfreq'",
"]",
"/=",
"decim",
"for",
"coil",
"in",
"raw_dec",
".",
"info",
"[",
"'hpi_meas'",
"]",
"[",
"0",
"]",
"[",
"'hpi_coils'",
"]",
":",
"if",
"(",
"coil",
"[",
"'coil_freq'",
"]",
">",
"raw_dec",
".",
"info",
"[",
"'sfreq'",
"]",
")",
":",
"coil",
"[",
"'coil_freq'",
"]",
"=",
"np",
".",
"mod",
"(",
"coil",
"[",
"'coil_freq'",
"]",
",",
"raw_dec",
".",
"info",
"[",
"'sfreq'",
"]",
")",
"if",
"(",
"coil",
"[",
"'coil_freq'",
"]",
">",
"(",
"raw_dec",
".",
"info",
"[",
"'sfreq'",
"]",
"/",
"2.0",
")",
")",
":",
"coil",
"[",
"'coil_freq'",
"]",
"=",
"(",
"raw_dec",
".",
"info",
"[",
"'sfreq'",
"]",
"-",
"coil",
"[",
"'coil_freq'",
"]",
")",
"return",
"raw_dec"
] |
decimate raw data in chpi-fitting compatible way .
|
train
| false
|
8,220
|
def iwait(objects, timeout=None):
waiter = Waiter()
switch = waiter.switch
if (timeout is not None):
timer = get_hub().loop.timer(timeout, priority=(-1))
timer.start(waiter.switch, _NONE)
try:
count = len(objects)
for obj in objects:
obj.rawlink(switch)
for _ in xrange(count):
item = waiter.get()
waiter.clear()
if (item is _NONE):
return
(yield item)
finally:
if (timeout is not None):
timer.stop()
for obj in objects:
unlink = getattr(obj, 'unlink', None)
if unlink:
try:
unlink(switch)
except:
traceback.print_exc()
|
[
"def",
"iwait",
"(",
"objects",
",",
"timeout",
"=",
"None",
")",
":",
"waiter",
"=",
"Waiter",
"(",
")",
"switch",
"=",
"waiter",
".",
"switch",
"if",
"(",
"timeout",
"is",
"not",
"None",
")",
":",
"timer",
"=",
"get_hub",
"(",
")",
".",
"loop",
".",
"timer",
"(",
"timeout",
",",
"priority",
"=",
"(",
"-",
"1",
")",
")",
"timer",
".",
"start",
"(",
"waiter",
".",
"switch",
",",
"_NONE",
")",
"try",
":",
"count",
"=",
"len",
"(",
"objects",
")",
"for",
"obj",
"in",
"objects",
":",
"obj",
".",
"rawlink",
"(",
"switch",
")",
"for",
"_",
"in",
"xrange",
"(",
"count",
")",
":",
"item",
"=",
"waiter",
".",
"get",
"(",
")",
"waiter",
".",
"clear",
"(",
")",
"if",
"(",
"item",
"is",
"_NONE",
")",
":",
"return",
"(",
"yield",
"item",
")",
"finally",
":",
"if",
"(",
"timeout",
"is",
"not",
"None",
")",
":",
"timer",
".",
"stop",
"(",
")",
"for",
"obj",
"in",
"objects",
":",
"unlink",
"=",
"getattr",
"(",
"obj",
",",
"'unlink'",
",",
"None",
")",
"if",
"unlink",
":",
"try",
":",
"unlink",
"(",
"switch",
")",
"except",
":",
"traceback",
".",
"print_exc",
"(",
")"
] |
iteratively yield *objects* as they are ready .
|
train
| false
|
8,222
|
def create_backup(ctxt, volume_id=fake.VOLUME_ID, display_name='test_backup', display_description='This is a test backup', status=fields.BackupStatus.CREATING, parent_id=None, temp_volume_id=None, temp_snapshot_id=None, snapshot_id=None, data_timestamp=None, **kwargs):
values = {'user_id': (ctxt.user_id or fake.USER_ID), 'project_id': (ctxt.project_id or fake.PROJECT_ID), 'volume_id': volume_id, 'status': status, 'display_name': display_name, 'display_description': display_description, 'container': 'fake', 'availability_zone': 'fake', 'service': 'fake', 'size': ((5 * 1024) * 1024), 'object_count': 22, 'host': socket.gethostname(), 'parent_id': parent_id, 'temp_volume_id': temp_volume_id, 'temp_snapshot_id': temp_snapshot_id, 'snapshot_id': snapshot_id, 'data_timestamp': data_timestamp}
values.update(kwargs)
backup = objects.Backup(ctxt, **values)
backup.create()
return backup
|
[
"def",
"create_backup",
"(",
"ctxt",
",",
"volume_id",
"=",
"fake",
".",
"VOLUME_ID",
",",
"display_name",
"=",
"'test_backup'",
",",
"display_description",
"=",
"'This is a test backup'",
",",
"status",
"=",
"fields",
".",
"BackupStatus",
".",
"CREATING",
",",
"parent_id",
"=",
"None",
",",
"temp_volume_id",
"=",
"None",
",",
"temp_snapshot_id",
"=",
"None",
",",
"snapshot_id",
"=",
"None",
",",
"data_timestamp",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"values",
"=",
"{",
"'user_id'",
":",
"(",
"ctxt",
".",
"user_id",
"or",
"fake",
".",
"USER_ID",
")",
",",
"'project_id'",
":",
"(",
"ctxt",
".",
"project_id",
"or",
"fake",
".",
"PROJECT_ID",
")",
",",
"'volume_id'",
":",
"volume_id",
",",
"'status'",
":",
"status",
",",
"'display_name'",
":",
"display_name",
",",
"'display_description'",
":",
"display_description",
",",
"'container'",
":",
"'fake'",
",",
"'availability_zone'",
":",
"'fake'",
",",
"'service'",
":",
"'fake'",
",",
"'size'",
":",
"(",
"(",
"5",
"*",
"1024",
")",
"*",
"1024",
")",
",",
"'object_count'",
":",
"22",
",",
"'host'",
":",
"socket",
".",
"gethostname",
"(",
")",
",",
"'parent_id'",
":",
"parent_id",
",",
"'temp_volume_id'",
":",
"temp_volume_id",
",",
"'temp_snapshot_id'",
":",
"temp_snapshot_id",
",",
"'snapshot_id'",
":",
"snapshot_id",
",",
"'data_timestamp'",
":",
"data_timestamp",
"}",
"values",
".",
"update",
"(",
"kwargs",
")",
"backup",
"=",
"objects",
".",
"Backup",
"(",
"ctxt",
",",
"**",
"values",
")",
"backup",
".",
"create",
"(",
")",
"return",
"backup"
] |
create a backup object .
|
train
| false
|
8,226
|
@retry_on_failure
def test_fileobject_close():
fd = socket._fileobject(None, close=True)
AreEqual(fd.mode, 'rb')
if (sys.platform == 'win32'):
AreEqual(fd.closed, True)
|
[
"@",
"retry_on_failure",
"def",
"test_fileobject_close",
"(",
")",
":",
"fd",
"=",
"socket",
".",
"_fileobject",
"(",
"None",
",",
"close",
"=",
"True",
")",
"AreEqual",
"(",
"fd",
".",
"mode",
",",
"'rb'",
")",
"if",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
":",
"AreEqual",
"(",
"fd",
".",
"closed",
",",
"True",
")"
] |
verify we can construct fileobjects w/ the close kw arg .
|
train
| false
|
8,228
|
def local_over_kwdict(local_var, kwargs, *keys):
out = local_var
for key in keys:
kwarg_val = kwargs.pop(key, None)
if (kwarg_val is not None):
if (out is None):
out = kwarg_val
else:
warnings.warn((u'"%s" keyword argument will be ignored' % key), IgnoredKeywordWarning)
return out
|
[
"def",
"local_over_kwdict",
"(",
"local_var",
",",
"kwargs",
",",
"*",
"keys",
")",
":",
"out",
"=",
"local_var",
"for",
"key",
"in",
"keys",
":",
"kwarg_val",
"=",
"kwargs",
".",
"pop",
"(",
"key",
",",
"None",
")",
"if",
"(",
"kwarg_val",
"is",
"not",
"None",
")",
":",
"if",
"(",
"out",
"is",
"None",
")",
":",
"out",
"=",
"kwarg_val",
"else",
":",
"warnings",
".",
"warn",
"(",
"(",
"u'\"%s\" keyword argument will be ignored'",
"%",
"key",
")",
",",
"IgnoredKeywordWarning",
")",
"return",
"out"
] |
enforces the priority of a local variable over potentially conflicting argument(s) from a kwargs dict .
|
train
| false
|
8,229
|
def create_imap_connection(host, port, ssl_required, use_timeout=True):
use_ssl = (port == 993)
timeout = (120 if use_timeout else None)
context = create_default_context()
conn = IMAPClient(host, port=port, use_uid=True, ssl=use_ssl, ssl_context=context, timeout=timeout)
if (not use_ssl):
if conn.has_capability('STARTTLS'):
try:
conn.starttls(context)
except Exception:
if (not ssl_required):
log.warning('STARTTLS supported but failed for SSL NOT required authentication', exc_info=True)
else:
raise
elif ssl_required:
raise SSLNotSupportedError('Required IMAP STARTTLS not supported.')
return conn
|
[
"def",
"create_imap_connection",
"(",
"host",
",",
"port",
",",
"ssl_required",
",",
"use_timeout",
"=",
"True",
")",
":",
"use_ssl",
"=",
"(",
"port",
"==",
"993",
")",
"timeout",
"=",
"(",
"120",
"if",
"use_timeout",
"else",
"None",
")",
"context",
"=",
"create_default_context",
"(",
")",
"conn",
"=",
"IMAPClient",
"(",
"host",
",",
"port",
"=",
"port",
",",
"use_uid",
"=",
"True",
",",
"ssl",
"=",
"use_ssl",
",",
"ssl_context",
"=",
"context",
",",
"timeout",
"=",
"timeout",
")",
"if",
"(",
"not",
"use_ssl",
")",
":",
"if",
"conn",
".",
"has_capability",
"(",
"'STARTTLS'",
")",
":",
"try",
":",
"conn",
".",
"starttls",
"(",
"context",
")",
"except",
"Exception",
":",
"if",
"(",
"not",
"ssl_required",
")",
":",
"log",
".",
"warning",
"(",
"'STARTTLS supported but failed for SSL NOT required authentication'",
",",
"exc_info",
"=",
"True",
")",
"else",
":",
"raise",
"elif",
"ssl_required",
":",
"raise",
"SSLNotSupportedError",
"(",
"'Required IMAP STARTTLS not supported.'",
")",
"return",
"conn"
] |
return a connection to the imap server .
|
train
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.