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 pl... | [
"def",
"addToCraftMenu",
"(",
"menu",
")",
":",
"settings",
".",
"ToolDialog",
"(",
")",
".",
"addPluginToMenu",
"(",
"menu",
",",
"archive",
".",
"getUntilDot",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
")",
"menu",
".",
"add_... | 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)])
r... | [
"def",
"enumerate_projects",
"(",
")",
":",
"src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_DEFAULT_APP_DIR",
",",
"'src'",
")",
"projects",
"=",
"{",
"}",
"for",
"project",
"in",
"os",
".",
"listdir",
"(",
"src_path",
")",
":",
"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",
"=... | 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):
t... | [
"def",
"catch_error",
"(",
"func",
")",
":",
"import",
"amqp",
"try",
":",
"import",
"pika",
".",
"exceptions",
"connect_exceptions",
"=",
"(",
"pika",
".",
"exceptions",
".",
"ConnectionClosed",
",",
"pika",
".",
"exceptions",
".",
"AMQPConnectionError",
")",... | 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 (... | [
"def",
"__get_host",
"(",
"node",
",",
"vm_",
")",
":",
"if",
"(",
"(",
"__get_ssh_interface",
"(",
"vm_",
")",
"==",
"'private_ips'",
")",
"or",
"(",
"vm_",
"[",
"'external_ip'",
"]",
"is",
"None",
")",
")",
":",
"ip_address",
"=",
"node",
".",
"pri... | 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]\... | 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 - ... | [
"def",
"aes_cbc_decrypt",
"(",
"data",
",",
"key",
",",
"iv",
")",
":",
"expanded_key",
"=",
"key_expansion",
"(",
"key",
")",
"block_count",
"=",
"int",
"(",
"ceil",
"(",
"(",
"float",
"(",
"len",
"(",
"data",
")",
")",
"/",
"BLOCK_SIZE_BYTES",
")",
... | 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",
... | 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)))... | [
"def",
"zipf_rv",
"(",
"alpha",
",",
"xmin",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"if",
"(",
"xmin",
"<",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'xmin < 1'",
")",
"if",
"(",
"alpha",
"<=",
"1",
")",
":",
"raise",
"ValueError",
"(",
... | 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",
... | 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_str... | [
"def",
"group_activity_list_html",
"(",
"context",
",",
"data_dict",
")",
":",
"activity_stream",
"=",
"group_activity_list",
"(",
"context",
",",
"data_dict",
")",
"offset",
"=",
"int",
"(",
"data_dict",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
")",
"ext... | 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",
"("... | 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",
"(",
")",
... | 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_NAM... | [
"def",
"get_or_create_root",
"(",
")",
":",
"try",
":",
"root",
"=",
"URLPath",
".",
"root",
"(",
")",
"if",
"(",
"not",
"root",
".",
"article",
")",
":",
"root",
".",
"delete",
"(",
")",
"raise",
"NoRootURL",
"return",
"root",
"except",
"NoRootURL",
... | 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)... | [
"def",
"build_quadratic_1d",
"(",
"J",
",",
"g",
",",
"s",
",",
"diag",
"=",
"None",
",",
"s0",
"=",
"None",
")",
":",
"v",
"=",
"J",
".",
"dot",
"(",
"s",
")",
"a",
"=",
"np",
".",
"dot",
"(",
"v",
",",
"v",
")",
"if",
"(",
"diag",
"is",... | 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",
... | 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 ''
licen... | [
"@",
"register",
".",
"function",
"def",
"license_link",
"(",
"license",
")",
":",
"from",
"olympia",
".",
"versions",
".",
"models",
"import",
"License",
"if",
"isinstance",
"(",
"license",
",",
"(",
"long",
",",
"int",
")",
")",
":",
"if",
"(",
"lice... | 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",
")",
"+",
... | 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",... | 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.... | [
"def",
"HashGen",
"(",
"APP_PATH",
")",
":",
"try",
":",
"print",
"'[INFO] Generating Hashes'",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"sha256",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"BLOCKSIZE",
"=",
"65536",
"with",
"io",
".",
"open",
"(",
... | 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",
":",... | 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",
... | 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))
... | [
"def",
"unregister_mimetype_handler",
"(",
"handler",
")",
":",
"if",
"(",
"not",
"issubclass",
"(",
"handler",
",",
"MimetypeHandler",
")",
")",
":",
"raise",
"TypeError",
"(",
"u'Only MimetypeHandler subclasses can be unregistered'",
")",
"try",
":",
"_registered_mi... | 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",
"(",
")",
")",
")",
".",
... | 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.str... | [
"def",
"_xml_read",
"(",
"root",
",",
"element",
",",
"check",
"=",
"None",
")",
":",
"val",
"=",
"root",
".",
"findtext",
"(",
"element",
")",
"if",
"(",
"(",
"val",
"is",
"None",
")",
"and",
"check",
")",
":",
"LOG",
".",
"error",
"(",
"_LE",
... | 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... | [
"def",
"_get_object_info",
"(",
"app",
",",
"env",
",",
"account",
",",
"container",
",",
"obj",
",",
"swift_source",
"=",
"None",
")",
":",
"cache_key",
"=",
"get_cache_key",
"(",
"account",
",",
"container",
",",
"obj",
")",
"info",
"=",
"env",
".",
... | 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",
"ThriftParserEr... | 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",
"(",
"bui... | 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_whic... | [
"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_l... | 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'... | [
"@",
"sopel",
".",
"module",
".",
"event",
"(",
"events",
".",
"ERR_NOCHANMODES",
")",
"@",
"sopel",
".",
"module",
".",
"rule",
"(",
"u'.*'",
")",
"@",
"sopel",
".",
"module",
".",
"priority",
"(",
"u'high'",
")",
"def",
"retry_join",
"(",
"bot",
",... | 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,... | [
"def",
"create_player",
"(",
"key",
",",
"email",
",",
"password",
",",
"typeclass",
"=",
"None",
",",
"is_superuser",
"=",
"False",
",",
"locks",
"=",
"None",
",",
"permissions",
"=",
"None",
",",
"report_to",
"=",
"None",
")",
":",
"global",
"_PlayerDB... | 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'",
")",... | 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",
"]"... | 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 ScoresForO... | [
"def",
"do_scores_for_objects",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"(",
"len",
"(",
"bits",
")",
"!=",
"4",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"(",
... | 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 (... | [
"def",
"inverse_normal_cdf",
"(",
"p",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
",",
"tolerance",
"=",
"1e-05",
")",
":",
"if",
"(",
"(",
"mu",
"!=",
"0",
")",
"or",
"(",
"sigma",
"!=",
"1",
")",
")",
":",
"return",
"(",
"mu",
"+",
"(",
... | 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):
return... | [
"def",
"list_returners",
"(",
"*",
"args",
")",
":",
"returners_",
"=",
"salt",
".",
"loader",
".",
"returners",
"(",
"__opts__",
",",
"[",
"]",
")",
"returners",
"=",
"set",
"(",
")",
"if",
"(",
"not",
"args",
")",
":",
"for",
"func",
"in",
"six",... | 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, n... | [
"def",
"_iter_all_modules",
"(",
"package",
",",
"prefix",
"=",
"''",
")",
":",
"import",
"os",
"import",
"pkgutil",
"if",
"(",
"type",
"(",
"package",
")",
"is",
"not",
"str",
")",
":",
"(",
"path",
",",
"prefix",
")",
"=",
"(",
"package",
".",
"_... | 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=si... | [
"def",
"get_containers",
"(",
"all",
"=",
"True",
",",
"trunc",
"=",
"False",
",",
"since",
"=",
"None",
",",
"before",
"=",
"None",
",",
"limit",
"=",
"(",
"-",
"1",
")",
",",
"host",
"=",
"False",
",",
"inspect",
"=",
"False",
")",
":",
"client... | 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... | [
"def",
"m2_repository_cleanup",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"m2repo",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.m2__repo__reaper.M2RepoReaperWrapper'",
")",
"m2repo",
".",
"set",
"(",
"'plugin'",
",",
"'... | 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",
"... | 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(... | [
"def",
"check_order",
"(",
"group",
")",
":",
"global",
"skip_order_check",
"try",
":",
"if",
"(",
"skip_order_check",
"or",
"(",
"len",
"(",
"group",
")",
"<",
"2",
")",
")",
":",
"skip_order_check",
"=",
"False",
"return",
"if",
"any",
"(",
"(",
"(",... | 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",
... | 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",
... | 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._message... | 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 "{... | [
"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_co... | 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=expe... | [
"def",
"create_container_for_test",
"(",
"case",
",",
"client",
",",
"name",
"=",
"None",
")",
":",
"if",
"(",
"name",
"is",
"None",
")",
":",
"name",
"=",
"random_name",
"(",
"case",
"=",
"case",
")",
"expected_container",
"=",
"Container",
"(",
"node_u... | 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 =... | [
"def",
"test_parse_nav_steps",
"(",
")",
":",
"print",
"sys",
".",
"path",
"arg_str",
"=",
"'selector click'",
"expected_output",
"=",
"{",
"'runhandler'",
":",
"'_command_handler'",
",",
"'args'",
":",
"{",
"'commands'",
":",
"[",
"{",
"'action'",
":",
"'clic... | 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.filt... | [
"@",
"task",
"def",
"addon_total_contributions",
"(",
"*",
"addons",
",",
"**",
"kw",
")",
":",
"log",
".",
"info",
"(",
"(",
"'[%s@%s] Updating total contributions.'",
"%",
"(",
"len",
"(",
"addons",
")",
",",
"addon_total_contributions",
".",
"rate_limit",
"... | 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 (n... | [
"def",
"_image_get",
"(",
"context",
",",
"image_id",
",",
"session",
"=",
"None",
",",
"force_show_deleted",
"=",
"False",
")",
":",
"session",
"=",
"(",
"session",
"or",
"get_session",
"(",
")",
")",
"try",
":",
"query",
"=",
"session",
".",
"query",
... | 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_getAllAnswersForQues... | [
"def",
"buildCompletedList",
"(",
"series_id",
",",
"question_id_list",
")",
":",
"db",
"=",
"current",
".",
"db",
"qtable",
"=",
"current",
".",
"s3db",
".",
"survey_question",
"headers",
"=",
"[",
"]",
"happend",
"=",
"headers",
".",
"append",
"types",
"... | 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",
"(... | 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'",
"]"... | 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), ... | [
"def",
"LoadChecksFromFiles",
"(",
"file_paths",
",",
"overwrite_if_exists",
"=",
"True",
")",
":",
"loaded",
"=",
"[",
"]",
"for",
"file_path",
"in",
"file_paths",
":",
"configs",
"=",
"LoadConfigsFromFile",
"(",
"file_path",
")",
"for",
"conf",
"in",
"config... | 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
... | [
"def",
"tag_create",
"(",
"repo",
",",
"tag",
",",
"author",
"=",
"None",
",",
"message",
"=",
"None",
",",
"annotated",
"=",
"False",
",",
"objectish",
"=",
"'HEAD'",
",",
"tag_time",
"=",
"None",
",",
"tag_timezone",
"=",
"None",
")",
":",
"with",
... | 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(kwarg... | [
"def",
"sieve",
"(",
"param",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"def",
"_sieve_hook",
"(",
"func",
")",
":",
"assert",
"(",
"len",
"(",
"inspect",
".",
"getargspec",
"(",
"func",
")",
".",
"args",
")",
"==",
"3",
")",
",",
"'Sieve plugin ... | 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",
"(",
"(",
"(",
"(",
"(",
"("... | 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",
"(",
"Non... | 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... | [
"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",... | 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'-'"... | 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 = s... | [
"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",
",",
"stdou... | 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... | [
"def",
"resource_view_show",
"(",
"context",
",",
"data_dict",
")",
":",
"model",
"=",
"context",
"[",
"'model'",
"]",
"id",
"=",
"_get_or_bust",
"(",
"data_dict",
",",
"'id'",
")",
"resource_view",
"=",
"model",
".",
"ResourceView",
".",
"get",
"(",
"id",... | 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,... | [
"def",
"set_mp_process_title",
"(",
"progname",
",",
"info",
"=",
"None",
",",
"hostname",
"=",
"None",
")",
":",
"if",
"hostname",
":",
"progname",
"=",
"(",
"'%s@%s'",
"%",
"(",
"progname",
",",
"hostname",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
... | 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",
".",... | 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(addres... | [
"def",
"make_managed_nodes",
"(",
"addresses",
",",
"distribution",
")",
":",
"[",
"address_type",
"]",
"=",
"set",
"(",
"(",
"type",
"(",
"address",
")",
"for",
"address",
"in",
"addresses",
")",
")",
"if",
"(",
"address_type",
"is",
"list",
")",
":",
... | 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",
".",
... | 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",
")",
"=... | 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",
")",
",",
"(",
... | 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",
".",
... | 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",
"=",
"''",
... | 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... | [
"def",
"_try_convert",
"(",
"value",
")",
":",
"def",
"_negative_zero",
"(",
"value",
")",
":",
"epsilon",
"=",
"1e-07",
"return",
"(",
"0",
"if",
"(",
"abs",
"(",
"value",
")",
"<",
"epsilon",
")",
"else",
"value",
")",
"if",
"(",
"len",
"(",
"val... | 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.i... | [
"def",
"_decimate_chpi",
"(",
"raw",
",",
"decim",
"=",
"4",
")",
":",
"raw_dec",
"=",
"RawArray",
"(",
"raw",
".",
"_data",
"[",
":",
",",
":",
":",
"decim",
"]",
",",
"raw",
".",
"info",
",",
"first_samp",
"=",
"(",
"raw",
".",
"first_samp",
"/... | 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()
... | [
"def",
"iwait",
"(",
"objects",
",",
"timeout",
"=",
"None",
")",
":",
"waiter",
"=",
"Waiter",
"(",
")",
"switch",
"=",
"waiter",
".",
"switch",
"if",
"(",
"timeout",
"is",
"not",
"None",
")",
":",
"timer",
"=",
"get_hub",
"(",
")",
".",
"loop",
... | 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_I... | [
"def",
"create_backup",
"(",
"ctxt",
",",
"volume_id",
"=",
"fake",
".",
"VOLUME_ID",
",",
"display_name",
"=",
"'test_backup'",
",",
"display_description",
"=",
"'This is a test backup'",
",",
"status",
"=",
"fields",
".",
"BackupStatus",
".",
"CREATING",
",",
... | 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",
"==",... | 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",
"no... | 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(... | [
"def",
"create_imap_connection",
"(",
"host",
",",
"port",
",",
"ssl_required",
",",
"use_timeout",
"=",
"True",
")",
":",
"use_ssl",
"=",
"(",
"port",
"==",
"993",
")",
"timeout",
"=",
"(",
"120",
"if",
"use_timeout",
"else",
"None",
")",
"context",
"="... | 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.