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 |
|---|---|---|---|---|---|
31,489 | def _calc_errors(actual, expected):
base = max(abs(actual), abs(expected))
abs_err = abs((actual - expected))
rel_err = ((abs_err / base) if base else float('inf'))
return (abs_err, rel_err)
| [
"def",
"_calc_errors",
"(",
"actual",
",",
"expected",
")",
":",
"base",
"=",
"max",
"(",
"abs",
"(",
"actual",
")",
",",
"abs",
"(",
"expected",
")",
")",
"abs_err",
"=",
"abs",
"(",
"(",
"actual",
"-",
"expected",
")",
")",
"rel_err",
"=",
"(",
... | return the absolute and relative errors between two numbers . | train | false |
31,490 | def output():
return s3_rest_controller()
| [
"def",
"output",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | format the data for printing stage information from the overstate system . | train | false |
31,493 | def test_contravariance():
print 'TODO'
| [
"def",
"test_contravariance",
"(",
")",
":",
"print",
"'TODO'"
] | URL - generic interface - generic delegate only reference types should work . | train | false |
31,494 | def user_followee_count(context, data_dict):
return _followee_count(context, data_dict, context['model'].UserFollowingUser)
| [
"def",
"user_followee_count",
"(",
"context",
",",
"data_dict",
")",
":",
"return",
"_followee_count",
"(",
"context",
",",
"data_dict",
",",
"context",
"[",
"'model'",
"]",
".",
"UserFollowingUser",
")"
] | return the number of users that are followed by the given user . | train | false |
31,495 | @flake8ext
def check_no_contextlib_nested(logical_line, filename):
msg = 'N324: contextlib.nested is deprecated. With Python 2.7 and later the with-statement supports multiple nested objects. See https://docs.python.org/2/library/contextlib.html#contextlib.nested for more information.'
if checks.contextlib_nested.match(logical_line):
(yield (0, msg))
| [
"@",
"flake8ext",
"def",
"check_no_contextlib_nested",
"(",
"logical_line",
",",
"filename",
")",
":",
"msg",
"=",
"'N324: contextlib.nested is deprecated. With Python 2.7 and later the with-statement supports multiple nested objects. See https://docs.python.org/2/library/contextlib.html#con... | n324 - dont use contextlib . | train | false |
31,497 | def volume_admin_metadata_get(context, volume_id):
return IMPL.volume_admin_metadata_get(context, volume_id)
| [
"def",
"volume_admin_metadata_get",
"(",
"context",
",",
"volume_id",
")",
":",
"return",
"IMPL",
".",
"volume_admin_metadata_get",
"(",
"context",
",",
"volume_id",
")"
] | get all administration metadata for a volume . | train | false |
31,498 | def enable_mpl_offline(resize=False, strip_style=False, verbose=False, show_link=True, link_text='Export to plot.ly', validate=True):
init_notebook_mode()
ip = ipython.core.getipython.get_ipython()
formatter = ip.display_formatter.formatters['text/html']
formatter.for_type(matplotlib.figure.Figure, (lambda fig: iplot_mpl(fig, resize, strip_style, verbose, show_link, link_text, validate)))
| [
"def",
"enable_mpl_offline",
"(",
"resize",
"=",
"False",
",",
"strip_style",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"show_link",
"=",
"True",
",",
"link_text",
"=",
"'Export to plot.ly'",
",",
"validate",
"=",
"True",
")",
":",
"init_notebook_mode",... | convert mpl plots to locally hosted html documents . | train | false |
31,500 | def server_poweroff(host=None, admin_username=None, admin_password=None, module=None):
return __execute_cmd('serveraction powerdown', host=host, admin_username=admin_username, admin_password=admin_password, module=module)
| [
"def",
"server_poweroff",
"(",
"host",
"=",
"None",
",",
"admin_username",
"=",
"None",
",",
"admin_password",
"=",
"None",
",",
"module",
"=",
"None",
")",
":",
"return",
"__execute_cmd",
"(",
"'serveraction powerdown'",
",",
"host",
"=",
"host",
",",
"admi... | powers down the managed server . | train | true |
31,501 | @download_tool('urllib2')
def urllib2_download(client, download_url, filename, resuming=False):
assert (not resuming)
print 'Downloading', download_url, 'to', filename, '...'
request = urllib2.Request(download_url, headers={'Cookie': ('gdriveid=' + client.get_gdriveid())})
response = urllib2.urlopen(request)
import shutil
with open(filename, 'wb') as output:
shutil.copyfileobj(response, output)
| [
"@",
"download_tool",
"(",
"'urllib2'",
")",
"def",
"urllib2_download",
"(",
"client",
",",
"download_url",
",",
"filename",
",",
"resuming",
"=",
"False",
")",
":",
"assert",
"(",
"not",
"resuming",
")",
"print",
"'Downloading'",
",",
"download_url",
",",
"... | in the case you dont even have wget . | train | false |
31,504 | def PRE(text):
return (('<pre>' + escape(text)) + '</pre>')
| [
"def",
"PRE",
"(",
"text",
")",
":",
"return",
"(",
"(",
"'<pre>'",
"+",
"escape",
"(",
"text",
")",
")",
"+",
"'</pre>'",
")"
] | munging to turn a method name into a pre-hook-method-name . | train | false |
31,505 | def test_ordered_dict_order():
schema = vol.Schema(cv.ordered_dict(int, cv.string))
val = OrderedDict()
val['first'] = 1
val['second'] = 2
validated = schema(val)
assert isinstance(validated, OrderedDict)
assert (['first', 'second'] == list(validated.keys()))
| [
"def",
"test_ordered_dict_order",
"(",
")",
":",
"schema",
"=",
"vol",
".",
"Schema",
"(",
"cv",
".",
"ordered_dict",
"(",
"int",
",",
"cv",
".",
"string",
")",
")",
"val",
"=",
"OrderedDict",
"(",
")",
"val",
"[",
"'first'",
"]",
"=",
"1",
"val",
... | test ordered_dict validator . | train | false |
31,506 | def print_to_stdout(color, str_out):
col = getattr(Fore, color)
_lazy_colorama_init()
if (not is_py3):
str_out = str_out.encode(encoding, 'replace')
print ((col + str_out) + Fore.RESET)
| [
"def",
"print_to_stdout",
"(",
"color",
",",
"str_out",
")",
":",
"col",
"=",
"getattr",
"(",
"Fore",
",",
"color",
")",
"_lazy_colorama_init",
"(",
")",
"if",
"(",
"not",
"is_py3",
")",
":",
"str_out",
"=",
"str_out",
".",
"encode",
"(",
"encoding",
"... | the default debug function that prints to standard out . | train | false |
31,507 | def make_templates():
if (not os.path.exists('email')):
os.makedirs('email')
for path in glob.glob(os.path.join(MO_DIR, '*')):
lng = os.path.split(path)[1]
if (lng != 'en'):
print ('Create email template for %s' % lng)
trans = gettext.translation(DOMAIN_E, MO_DIR, [lng], fallback=False, codeset='latin-1')
trans.install(unicode=True, names=['lgettext'])
translate_tmpl('email', lng)
translate_tmpl('rss', lng)
translate_tmpl('badfetch', lng)
mo_path = os.path.normpath(('%s/%s%s/%s.mo' % (MO_DIR, path, MO_LOCALE, DOMAIN_E)))
if os.path.exists(mo_path):
os.remove(mo_path)
| [
"def",
"make_templates",
"(",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'email'",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"'email'",
")",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
... | create email templates . | train | false |
31,508 | @not_implemented_for('directed')
@not_implemented_for('multigraph')
def min_edge_cover(G, matching_algorithm=None):
if (nx.number_of_isolates(G) > 0):
raise nx.NetworkXException('Graph has a node with no edge incident on it, so no edge cover exists.')
if (matching_algorithm is None):
matching_algorithm = partial(nx.max_weight_matching, maxcardinality=True)
maximum_matching = matching_algorithm(G)
min_cover = set(maximum_matching.items())
uncovered_nodes = (set(G) - {v for (u, v) in min_cover})
for v in uncovered_nodes:
u = arbitrary_element(G[v])
min_cover.add((u, v))
min_cover.add((v, u))
return min_cover
| [
"@",
"not_implemented_for",
"(",
"'directed'",
")",
"@",
"not_implemented_for",
"(",
"'multigraph'",
")",
"def",
"min_edge_cover",
"(",
"G",
",",
"matching_algorithm",
"=",
"None",
")",
":",
"if",
"(",
"nx",
".",
"number_of_isolates",
"(",
"G",
")",
">",
"0"... | returns a set of edges which constitutes the minimum edge cover of the graph . | train | false |
31,509 | @hook.command
def imdb(text, bot):
headers = {'User-Agent': bot.user_agent}
strip = text.strip()
if id_re.match(strip):
params = {'i': strip}
else:
params = {'t': strip}
request = requests.get('http://www.omdbapi.com/', params=params, headers=headers)
content = request.json()
if (content.get('Error', None) == 'Movie not found!'):
return 'Movie not found!'
elif (content['Response'] == 'True'):
content['URL'] = 'http://www.imdb.com/title/{}'.format(content['imdbID'])
out = '\x02%(Title)s\x02 (%(Year)s) (%(Genre)s): %(Plot)s'
if (content['Runtime'] != 'N/A'):
out += ' \x02%(Runtime)s\x02.'
if ((content['imdbRating'] != 'N/A') and (content['imdbVotes'] != 'N/A')):
out += ' \x02%(imdbRating)s/10\x02 with \x02%(imdbVotes)s\x02 votes.'
out += ' %(URL)s'
return (out % content)
else:
return 'Unknown error.'
| [
"@",
"hook",
".",
"command",
"def",
"imdb",
"(",
"text",
",",
"bot",
")",
":",
"headers",
"=",
"{",
"'User-Agent'",
":",
"bot",
".",
"user_agent",
"}",
"strip",
"=",
"text",
".",
"strip",
"(",
")",
"if",
"id_re",
".",
"match",
"(",
"strip",
")",
... | imdb <movie> - gets information about <movie> from imdb . | train | false |
31,510 | def should_ignore_paypal():
return (settings.DEBUG and ('sandbox' not in settings.PAYPAL_PERMISSIONS_URL))
| [
"def",
"should_ignore_paypal",
"(",
")",
":",
"return",
"(",
"settings",
".",
"DEBUG",
"and",
"(",
"'sandbox'",
"not",
"in",
"settings",
".",
"PAYPAL_PERMISSIONS_URL",
")",
")"
] | returns whether to skip paypal communications for development purposes or not . | train | false |
31,511 | def emf_unwrap(raw, verbose=0):
w = EMF(raw, verbose=verbose)
if (not w.has_raster_image):
raise ValueError(u'No raster image found in the EMF')
return w.to_png()
| [
"def",
"emf_unwrap",
"(",
"raw",
",",
"verbose",
"=",
"0",
")",
":",
"w",
"=",
"EMF",
"(",
"raw",
",",
"verbose",
"=",
"verbose",
")",
"if",
"(",
"not",
"w",
".",
"has_raster_image",
")",
":",
"raise",
"ValueError",
"(",
"u'No raster image found in the E... | return the largest embedded raster image in the emf . | train | false |
31,513 | def libvlc_vlm_set_mux(p_instance, psz_name, psz_mux):
f = (_Cfunctions.get('libvlc_vlm_set_mux', None) or _Cfunction('libvlc_vlm_set_mux', ((1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_char_p))
return f(p_instance, psz_name, psz_mux)
| [
"def",
"libvlc_vlm_set_mux",
"(",
"p_instance",
",",
"psz_name",
",",
"psz_mux",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_vlm_set_mux'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_vlm_set_mux'",
",",
"(",
"(",
"1",
",",
")... | set a medias vod muxer . | train | true |
31,514 | def rmtree(dirname):
excs = []
try:
os.chmod(dirname, ((stat.S_IWRITE | stat.S_IEXEC) | stat.S_IREAD))
for f in os.listdir(dirname):
fullname = os.path.join(dirname, f)
if os.path.isdir(fullname):
rm_dir(fullname)
else:
remove(fullname)
os.rmdir(dirname)
except EnvironmentError as le:
if (((le.args[0] != 2) and (le.args[0] != 3)) or (le.args[0] != errno.ENOENT)):
excs.append(le)
except Exception as le:
excs.append(le)
if os.path.exists(dirname):
if (len(excs) == 1):
raise excs[0]
if (len(excs) == 0):
raise OSError, 'Failed to remove dir for unknown reason.'
raise OSError, excs
| [
"def",
"rmtree",
"(",
"dirname",
")",
":",
"excs",
"=",
"[",
"]",
"try",
":",
"os",
".",
"chmod",
"(",
"dirname",
",",
"(",
"(",
"stat",
".",
"S_IWRITE",
"|",
"stat",
".",
"S_IEXEC",
")",
"|",
"stat",
".",
"S_IREAD",
")",
")",
"for",
"f",
"in",... | recursively delete a directory tree . | train | false |
31,516 | def pslist(addr_space):
for p in get_kdbg(addr_space).processes():
(yield p)
| [
"def",
"pslist",
"(",
"addr_space",
")",
":",
"for",
"p",
"in",
"get_kdbg",
"(",
"addr_space",
")",
".",
"processes",
"(",
")",
":",
"(",
"yield",
"p",
")"
] | a generator for _eprocess objects . | train | false |
31,517 | def Pdfs(pdfs, **options):
for pdf in pdfs:
Pdf(pdf, **options)
| [
"def",
"Pdfs",
"(",
"pdfs",
",",
"**",
"options",
")",
":",
"for",
"pdf",
"in",
"pdfs",
":",
"Pdf",
"(",
"pdf",
",",
"**",
"options",
")"
] | plots a sequence of pdfs . | train | false |
31,519 | def post_process_filtered_equals(opcodes):
cur_chunk = None
for (tag, i1, i2, j1, j2, meta) in opcodes:
if (((tag == u'equal') and (not meta.get(u'indentation_changes'))) or (tag == u'filtered-equal')):
if cur_chunk:
i1 = cur_chunk[1]
j1 = cur_chunk[3]
meta = cur_chunk[5]
cur_chunk = (u'equal', i1, i2, j1, j2, meta)
else:
if cur_chunk:
(yield cur_chunk)
cur_chunk = None
(yield (tag, i1, i2, j1, j2, meta))
if cur_chunk:
(yield cur_chunk)
| [
"def",
"post_process_filtered_equals",
"(",
"opcodes",
")",
":",
"cur_chunk",
"=",
"None",
"for",
"(",
"tag",
",",
"i1",
",",
"i2",
",",
"j1",
",",
"j2",
",",
"meta",
")",
"in",
"opcodes",
":",
"if",
"(",
"(",
"(",
"tag",
"==",
"u'equal'",
")",
"an... | post-processes filtered-equal and equal chunks from interdiffs . | train | false |
31,521 | def _MakeDosListIntoYaml(dos_list):
statements = ['blacklist:']
for entry in dos_list:
statements += entry.ToYaml()
return ('\n'.join(statements) + '\n')
| [
"def",
"_MakeDosListIntoYaml",
"(",
"dos_list",
")",
":",
"statements",
"=",
"[",
"'blacklist:'",
"]",
"for",
"entry",
"in",
"dos_list",
":",
"statements",
"+=",
"entry",
".",
"ToYaml",
"(",
")",
"return",
"(",
"'\\n'",
".",
"join",
"(",
"statements",
")",... | converts yaml statement list of blacklisted ips into a string . | train | false |
31,523 | def tree2conllstr(t):
lines = [u' '.join(token) for token in tree2conlltags(t)]
return u'\n'.join(lines)
| [
"def",
"tree2conllstr",
"(",
"t",
")",
":",
"lines",
"=",
"[",
"u' '",
".",
"join",
"(",
"token",
")",
"for",
"token",
"in",
"tree2conlltags",
"(",
"t",
")",
"]",
"return",
"u'\\n'",
".",
"join",
"(",
"lines",
")"
] | return a multiline string where each line contains a word . | train | false |
31,524 | def getSegmentsFromLoopListsPoints(loopLists, pointBegin, pointEnd):
normalizedSegment = (pointEnd - pointBegin)
normalizedSegmentLength = abs(normalizedSegment)
if (normalizedSegmentLength == 0.0):
return []
normalizedSegment /= normalizedSegmentLength
segmentYMirror = complex(normalizedSegment.real, (- normalizedSegment.imag))
pointBeginRotated = (segmentYMirror * pointBegin)
pointEndRotated = (segmentYMirror * pointEnd)
rotatedLoopLists = []
for loopList in loopLists:
rotatedLoopList = []
rotatedLoopLists.append(rotatedLoopList)
for loop in loopList:
rotatedLoop = euclidean.getPointsRoundZAxis(segmentYMirror, loop)
rotatedLoopList.append(rotatedLoop)
xIntersectionIndexList = []
xIntersectionIndexList.append(euclidean.XIntersectionIndex((-1), pointBeginRotated.real))
xIntersectionIndexList.append(euclidean.XIntersectionIndex((-1), pointEndRotated.real))
euclidean.addXIntersectionIndexesFromLoopListsY(rotatedLoopLists, xIntersectionIndexList, pointBeginRotated.imag)
segments = euclidean.getSegmentsFromXIntersectionIndexes(xIntersectionIndexList, pointBeginRotated.imag)
for segment in segments:
for endpoint in segment:
endpoint.point *= normalizedSegment
return segments
| [
"def",
"getSegmentsFromLoopListsPoints",
"(",
"loopLists",
",",
"pointBegin",
",",
"pointEnd",
")",
":",
"normalizedSegment",
"=",
"(",
"pointEnd",
"-",
"pointBegin",
")",
"normalizedSegmentLength",
"=",
"abs",
"(",
"normalizedSegment",
")",
"if",
"(",
"normalizedSe... | get endpoint segments from the beginning and end of a line segment . | train | false |
31,526 | def test_strange_inheritance():
class m(StrangeOverrides, ):
def SomeMethodWithContext(self, arg):
AreEqual(arg, 'abc')
def ParamsMethodWithContext(self, *arg):
AreEqual(arg, ('abc', 'def'))
def ParamsIntMethodWithContext(self, *arg):
AreEqual(arg, (2, 3))
a = m()
a.CallWithContext('abc')
a.CallParamsWithContext('abc', 'def')
a.CallIntParamsWithContext(2, 3)
| [
"def",
"test_strange_inheritance",
"(",
")",
":",
"class",
"m",
"(",
"StrangeOverrides",
",",
")",
":",
"def",
"SomeMethodWithContext",
"(",
"self",
",",
"arg",
")",
":",
"AreEqual",
"(",
"arg",
",",
"'abc'",
")",
"def",
"ParamsMethodWithContext",
"(",
"self... | verify that overriding strange methods doesnt flow caller context through . | train | false |
31,527 | def bincount(x, weights=None, minlength=None, assert_nonneg=False):
if (x.ndim != 1):
raise TypeError('Inputs must be of dimension 1.')
if assert_nonneg:
from theano.tensor.opt import Assert
assert_op = Assert('Input to bincount has negative values!')
x = assert_op(x, theano.tensor.all((x >= 0)))
max_value = theano.tensor.cast((x.max() + 1), 'int64')
if (minlength is not None):
max_value = theano.tensor.maximum(max_value, minlength)
if (weights is None):
out = theano.tensor.zeros([max_value], dtype=x.dtype)
out = theano.tensor.advanced_inc_subtensor1(out, 1, x)
else:
out = theano.tensor.zeros([max_value], dtype=weights.dtype)
out = theano.tensor.advanced_inc_subtensor1(out, weights, x)
return out
| [
"def",
"bincount",
"(",
"x",
",",
"weights",
"=",
"None",
",",
"minlength",
"=",
"None",
",",
"assert_nonneg",
"=",
"False",
")",
":",
"if",
"(",
"x",
".",
"ndim",
"!=",
"1",
")",
":",
"raise",
"TypeError",
"(",
"'Inputs must be of dimension 1.'",
")",
... | count number of occurrences of each value in array of ints . | train | false |
31,529 | def randu(nchars):
return ''.join(np.random.choice(RANDU_CHARS, nchars))
| [
"def",
"randu",
"(",
"nchars",
")",
":",
"return",
"''",
".",
"join",
"(",
"np",
".",
"random",
".",
"choice",
"(",
"RANDU_CHARS",
",",
"nchars",
")",
")"
] | generate one random unicode string . | train | false |
31,530 | def swig_library(name, srcs=[], deps=[], warning='', java_package='', java_lib_packed=False, optimize=[], extra_swigflags=[], **kwargs):
target = SwigLibrary(name, srcs, deps, warning, java_package, java_lib_packed, optimize, extra_swigflags, blade.blade, kwargs)
blade.blade.register_target(target)
| [
"def",
"swig_library",
"(",
"name",
",",
"srcs",
"=",
"[",
"]",
",",
"deps",
"=",
"[",
"]",
",",
"warning",
"=",
"''",
",",
"java_package",
"=",
"''",
",",
"java_lib_packed",
"=",
"False",
",",
"optimize",
"=",
"[",
"]",
",",
"extra_swigflags",
"=",
... | swig_library target . | train | false |
31,531 | def build_summary(layout, level=1):
assert (level > 0)
level -= 1
summary = List(klass=u'summary')
for child in layout.children:
if (not isinstance(child, Section)):
continue
label = layout_title(child)
if ((not label) and (not child.id)):
continue
if (not child.id):
child.id = label.replace(' ', '-')
node = Link((u'#' + child.id), label=(label or child.id))
if (level and [n for n in child.children if isinstance(n, Section)]):
node = Paragraph([node, build_summary(child, level)])
summary.append(node)
return summary
| [
"def",
"build_summary",
"(",
"layout",
",",
"level",
"=",
"1",
")",
":",
"assert",
"(",
"level",
">",
"0",
")",
"level",
"-=",
"1",
"summary",
"=",
"List",
"(",
"klass",
"=",
"u'summary'",
")",
"for",
"child",
"in",
"layout",
".",
"children",
":",
... | make a summary for the report . | train | false |
31,532 | def string_to_rank(text, maxint=sys.maxint):
rs = CleanText(text, banned=CleanText.NONALNUM).clean.lower()
rank = 0.0
frac = 1.0
for pos in range(0, min(15, len(rs))):
rank += (frac * (int(rs[pos], 36) / (36.0 + (0.09 * pos))))
frac *= (1.0 / (36 - pos))
return (long((rank * (maxint - 100))) + min(100, len(text)))
| [
"def",
"string_to_rank",
"(",
"text",
",",
"maxint",
"=",
"sys",
".",
"maxint",
")",
":",
"rs",
"=",
"CleanText",
"(",
"text",
",",
"banned",
"=",
"CleanText",
".",
"NONALNUM",
")",
".",
"clean",
".",
"lower",
"(",
")",
"rank",
"=",
"0.0",
"frac",
... | approximate lexographical order with an int . | train | false |
31,533 | def get_int_property(device_type, property, cf_number_type):
key = cf.CFStringCreateWithCString(kCFAllocatorDefault, property.encode('mac_roman'), kCFStringEncodingMacRoman)
CFContainer = iokit.IORegistryEntryCreateCFProperty(device_type, key, kCFAllocatorDefault, 0)
if CFContainer:
if (cf_number_type == kCFNumberSInt32Type):
number = ctypes.c_uint32()
elif (cf_number_type == kCFNumberSInt16Type):
number = ctypes.c_uint16()
cf.CFNumberGetValue(CFContainer, cf_number_type, ctypes.byref(number))
cf.CFRelease(CFContainer)
return number.value
return None
| [
"def",
"get_int_property",
"(",
"device_type",
",",
"property",
",",
"cf_number_type",
")",
":",
"key",
"=",
"cf",
".",
"CFStringCreateWithCString",
"(",
"kCFAllocatorDefault",
",",
"property",
".",
"encode",
"(",
"'mac_roman'",
")",
",",
"kCFStringEncodingMacRoman"... | search the given device for the specified string property . | train | false |
31,534 | def write_string_table(string_table):
temp_buffer = StringIO()
doc = XMLGenerator(temp_buffer, 'utf-8')
start_tag(doc, 'sst', {'xmlns': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'uniqueCount': ('%d' % len(string_table))})
strings_to_write = sorted(iter(string_table.items()), key=(lambda pair: pair[1]))
for key in [pair[0] for pair in strings_to_write]:
start_tag(doc, 'si')
if (key.strip() != key):
attr = {'xml:space': 'preserve'}
else:
attr = {}
tag(doc, 't', attr, key)
end_tag(doc, 'si')
end_tag(doc, 'sst')
string_table_xml = temp_buffer.getvalue()
temp_buffer.close()
return string_table_xml
| [
"def",
"write_string_table",
"(",
"string_table",
")",
":",
"temp_buffer",
"=",
"StringIO",
"(",
")",
"doc",
"=",
"XMLGenerator",
"(",
"temp_buffer",
",",
"'utf-8'",
")",
"start_tag",
"(",
"doc",
",",
"'sst'",
",",
"{",
"'xmlns'",
":",
"'http://schemas.openxml... | write the string table xml . | train | false |
31,535 | def _tgrep_node_literal_value(node):
return (node.label() if _istree(node) else text_type(node))
| [
"def",
"_tgrep_node_literal_value",
"(",
"node",
")",
":",
"return",
"(",
"node",
".",
"label",
"(",
")",
"if",
"_istree",
"(",
"node",
")",
"else",
"text_type",
"(",
"node",
")",
")"
] | gets the string value of a given parse tree node . | train | false |
31,537 | def share_transfer(cookie, tokens, shareid, uk, filelist, dest, upload_mode):
ondup = const.UPLOAD_ONDUP[upload_mode]
url = ''.join([const.PAN_URL, 'share/transfer?app_id=250528&channel=chunlei&clienttype=0&web=1', '&bdstoken=', tokens['bdstoken'], '&from=', uk, '&shareid=', shareid, '&ondup=', ondup, '&async=1'])
data = ''.join(['path=', encoder.encode_uri_component(dest), '&filelist=', encoder.encode_uri_component(json.dumps(filelist))])
req = net.urlopen(url, headers={'Cookie': cookie.header_output(), 'Content-Type': const.CONTENT_FORM_UTF8}, data=data.encode())
if req:
content = req.data.decode()
return json.loads(content)
else:
return None
| [
"def",
"share_transfer",
"(",
"cookie",
",",
"tokens",
",",
"shareid",
",",
"uk",
",",
"filelist",
",",
"dest",
",",
"upload_mode",
")",
":",
"ondup",
"=",
"const",
".",
"UPLOAD_ONDUP",
"[",
"upload_mode",
"]",
"url",
"=",
"''",
".",
"join",
"(",
"[",
... | uk - 其他用户的uk filelist - 要转移文件的列表 . | train | true |
31,539 | def strip_sys_meta_prefix(server_type, key):
return key[len(get_sys_meta_prefix(server_type)):]
| [
"def",
"strip_sys_meta_prefix",
"(",
"server_type",
",",
"key",
")",
":",
"return",
"key",
"[",
"len",
"(",
"get_sys_meta_prefix",
"(",
"server_type",
")",
")",
":",
"]"
] | removes the system metadata prefix for a given server type from the start of a header key . | train | false |
31,541 | @user_registered.connect
def replace_unclaimed_user_with_registered(user):
unreg_user_info = session.data.get('unreg_user')
if unreg_user_info:
unreg_user = User.load(unreg_user_info['uid'])
pid = unreg_user_info['pid']
node = Node.load(pid)
node.replace_contributor(old=unreg_user, new=user)
node.save()
status.push_status_message('Successfully claimed contributor.', kind='success', trust=False)
| [
"@",
"user_registered",
".",
"connect",
"def",
"replace_unclaimed_user_with_registered",
"(",
"user",
")",
":",
"unreg_user_info",
"=",
"session",
".",
"data",
".",
"get",
"(",
"'unreg_user'",
")",
"if",
"unreg_user_info",
":",
"unreg_user",
"=",
"User",
".",
"l... | listens for the user_registered signal . | train | false |
31,544 | def _calculate_meta(meta, bases):
winner = meta
for base in bases:
base_meta = type(base)
if issubclass(winner, base_meta):
continue
if issubclass(base_meta, winner):
winner = base_meta
continue
raise TypeError('metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases')
return winner
| [
"def",
"_calculate_meta",
"(",
"meta",
",",
"bases",
")",
":",
"winner",
"=",
"meta",
"for",
"base",
"in",
"bases",
":",
"base_meta",
"=",
"type",
"(",
"base",
")",
"if",
"issubclass",
"(",
"winner",
",",
"base_meta",
")",
":",
"continue",
"if",
"issub... | calculate the most derived metaclass . | train | false |
31,545 | def dist_sum(D1, D2):
(X1, W1) = D1
(X2, W2) = D2
X = numpy.r_[(X1, X2)]
W = numpy.r_[(W1, W2)]
sort_ind = numpy.argsort(X)
(X, W) = (X[sort_ind], W[sort_ind])
(unique, uniq_index) = numpy.unique(X, return_index=True)
spans = numpy.diff(numpy.r_[(uniq_index, len(X))])
W = [numpy.sum(W[start:(start + span)]) for (start, span) in zip(uniq_index, spans)]
W = numpy.array(W)
assert (W.shape[0] == unique.shape[0])
return (unique, W)
| [
"def",
"dist_sum",
"(",
"D1",
",",
"D2",
")",
":",
"(",
"X1",
",",
"W1",
")",
"=",
"D1",
"(",
"X2",
",",
"W2",
")",
"=",
"D2",
"X",
"=",
"numpy",
".",
"r_",
"[",
"(",
"X1",
",",
"X2",
")",
"]",
"W",
"=",
"numpy",
".",
"r_",
"[",
"(",
... | a sum of two continuous distributions . | train | false |
31,547 | def egd(path, bytes=_unspecified):
if (not isinstance(path, _builtin_bytes)):
raise TypeError('path must be a byte string')
if (bytes is _unspecified):
bytes = 255
elif (not isinstance(bytes, int)):
raise TypeError('bytes must be an integer')
return _lib.RAND_egd_bytes(path, bytes)
| [
"def",
"egd",
"(",
"path",
",",
"bytes",
"=",
"_unspecified",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"path",
",",
"_builtin_bytes",
")",
")",
":",
"raise",
"TypeError",
"(",
"'path must be a byte string'",
")",
"if",
"(",
"bytes",
"is",
"_unspecifi... | query an entropy gathering daemon for random data and add it to the prng . | train | false |
31,548 | def _ToDbApiException(sql_exception):
exception = _ERROR_CODE_TO_EXCEPTION.get(sql_exception.code)
if (not exception):
if (sql_exception.code < 1000):
exception = InternalError
else:
exception = OperationalError
return exception(sql_exception.code, sql_exception.message)
| [
"def",
"_ToDbApiException",
"(",
"sql_exception",
")",
":",
"exception",
"=",
"_ERROR_CODE_TO_EXCEPTION",
".",
"get",
"(",
"sql_exception",
".",
"code",
")",
"if",
"(",
"not",
"exception",
")",
":",
"if",
"(",
"sql_exception",
".",
"code",
"<",
"1000",
")",
... | returns a db-api exception type appropriate for the given sql_exception . | train | false |
31,549 | def _asarray_square(A):
A = np.asarray(A)
if ((len(A.shape) != 2) or (A.shape[0] != A.shape[1])):
raise ValueError('expected square array_like input')
return A
| [
"def",
"_asarray_square",
"(",
"A",
")",
":",
"A",
"=",
"np",
".",
"asarray",
"(",
"A",
")",
"if",
"(",
"(",
"len",
"(",
"A",
".",
"shape",
")",
"!=",
"2",
")",
"or",
"(",
"A",
".",
"shape",
"[",
"0",
"]",
"!=",
"A",
".",
"shape",
"[",
"1... | wraps asarray with the extra requirement that the input be a square matrix . | train | false |
31,550 | def register_shape_i_c_code(typ, code, check_input, version=()):
Shape_i.c_code_and_version[typ] = (code, check_input, version)
| [
"def",
"register_shape_i_c_code",
"(",
"typ",
",",
"code",
",",
"check_input",
",",
"version",
"=",
"(",
")",
")",
":",
"Shape_i",
".",
"c_code_and_version",
"[",
"typ",
"]",
"=",
"(",
"code",
",",
"check_input",
",",
"version",
")"
] | tell shape_i how to generate c code for a theano type . | train | false |
31,552 | def test_unsafe_url():
eq_('All your{"<a href="http://xx.yy.com/grover.png" rel="nofollow">xx.yy.com/grover.png</a>"}base are', linkify('All your{"xx.yy.com/grover.png"}base are'))
| [
"def",
"test_unsafe_url",
"(",
")",
":",
"eq_",
"(",
"'All your{\"<a href=\"http://xx.yy.com/grover.png\" rel=\"nofollow\">xx.yy.com/grover.png</a>\"}base are'",
",",
"linkify",
"(",
"'All your{\"xx.yy.com/grover.png\"}base are'",
")",
")"
] | any unsafe char in the path should end url scanning . | train | false |
31,553 | def right_multiply(J, d, copy=True):
if (copy and (not isinstance(J, LinearOperator))):
J = J.copy()
if issparse(J):
J.data *= d.take(J.indices, mode='clip')
elif isinstance(J, LinearOperator):
J = right_multiplied_operator(J, d)
else:
J *= d
return J
| [
"def",
"right_multiply",
"(",
"J",
",",
"d",
",",
"copy",
"=",
"True",
")",
":",
"if",
"(",
"copy",
"and",
"(",
"not",
"isinstance",
"(",
"J",
",",
"LinearOperator",
")",
")",
")",
":",
"J",
"=",
"J",
".",
"copy",
"(",
")",
"if",
"issparse",
"(... | compute j diag(d) . | train | false |
31,554 | def get_access_token_from_code(code, redirect_uri, app_id, app_secret):
args = {'code': code, 'redirect_uri': redirect_uri, 'client_id': app_id, 'client_secret': app_secret}
response = urllib.urlopen((('https://graph.facebook.com/oauth/access_token' + '?') + urllib.urlencode(args))).read()
query_str = parse_qs(response)
if ('access_token' in query_str):
result = {'access_token': query_str['access_token'][0]}
if ('expires' in query_str):
result['expires'] = query_str['expires'][0]
return result
else:
response = json.loads(response)
raise GraphAPIError(response)
| [
"def",
"get_access_token_from_code",
"(",
"code",
",",
"redirect_uri",
",",
"app_id",
",",
"app_secret",
")",
":",
"args",
"=",
"{",
"'code'",
":",
"code",
",",
"'redirect_uri'",
":",
"redirect_uri",
",",
"'client_id'",
":",
"app_id",
",",
"'client_secret'",
"... | get an access token from the "code" returned from an oauth dialog . | train | false |
31,555 | def get_thumbnailer(obj, relative_name=None):
if hasattr(obj, 'easy_thumbnails_thumbnailer'):
return obj.easy_thumbnails_thumbnailer
if isinstance(obj, Thumbnailer):
return obj
elif isinstance(obj, FieldFile):
if (not relative_name):
relative_name = obj.name
return ThumbnailerFieldFile(obj.instance, obj.field, relative_name)
source_storage = None
if isinstance(obj, six.string_types):
relative_name = obj
obj = None
if (not relative_name):
raise ValueError('If object is not a FieldFile or Thumbnailer instance, the relative name must be provided')
if isinstance(obj, File):
obj = obj.file
if (isinstance(obj, Storage) or (obj == default_storage)):
source_storage = obj
obj = None
return Thumbnailer(file=obj, name=relative_name, source_storage=source_storage, remote_source=(obj is not None))
| [
"def",
"get_thumbnailer",
"(",
"obj",
",",
"relative_name",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'easy_thumbnails_thumbnailer'",
")",
":",
"return",
"obj",
".",
"easy_thumbnails_thumbnailer",
"if",
"isinstance",
"(",
"obj",
",",
"Thumbnailer... | get a :class:thumbnailer for a source file . | train | true |
31,556 | def programme():
mode = session.s3.hrm.mode
if (not auth.s3_has_role(ADMIN)):
s3.filter = auth.filter_by_root_org(s3db.hrm_programme)
def prep(r):
if (mode is not None):
auth.permission.fail()
if (r.component_name == 'person'):
s3db.configure('hrm_programme_hours', list_fields=['person_id', 'training', 'programme_id', 'date', 'hours'])
return True
s3.prep = prep
return s3_rest_controller('hrm', resourcename, csv_stylesheet=('hrm', 'programme.xsl'), csv_template=('hrm', 'programme'), rheader=s3db.hrm_rheader)
| [
"def",
"programme",
"(",
")",
":",
"mode",
"=",
"session",
".",
"s3",
".",
"hrm",
".",
"mode",
"if",
"(",
"not",
"auth",
".",
"s3_has_role",
"(",
"ADMIN",
")",
")",
":",
"s3",
".",
"filter",
"=",
"auth",
".",
"filter_by_root_org",
"(",
"s3db",
".",... | volunteer programmes controller . | train | false |
31,559 | def addAlongWay(begin, distance, end, loop):
endMinusBegin = (end - begin)
endMinusBeginLength = abs(endMinusBegin)
if (endMinusBeginLength <= 0.0):
return
alongWayMultiplier = (distance / endMinusBeginLength)
loop.append((begin + (alongWayMultiplier * endMinusBegin)))
| [
"def",
"addAlongWay",
"(",
"begin",
",",
"distance",
",",
"end",
",",
"loop",
")",
":",
"endMinusBegin",
"=",
"(",
"end",
"-",
"begin",
")",
"endMinusBeginLength",
"=",
"abs",
"(",
"endMinusBegin",
")",
"if",
"(",
"endMinusBeginLength",
"<=",
"0.0",
")",
... | get the beveled rectangle . | train | false |
31,560 | def maximum_independent_set(G):
(iset, _) = clique_removal(G)
return iset
| [
"def",
"maximum_independent_set",
"(",
"G",
")",
":",
"(",
"iset",
",",
"_",
")",
"=",
"clique_removal",
"(",
"G",
")",
"return",
"iset"
] | return an approximate maximum independent set . | train | false |
31,562 | @parametrize('table', tables.mapped_classes)
def test_identifiers_with_names(table):
for translation_class in table.translation_classes:
if hasattr(translation_class, 'name'):
assert hasattr(table, 'identifier'), table
| [
"@",
"parametrize",
"(",
"'table'",
",",
"tables",
".",
"mapped_classes",
")",
"def",
"test_identifiers_with_names",
"(",
"table",
")",
":",
"for",
"translation_class",
"in",
"table",
".",
"translation_classes",
":",
"if",
"hasattr",
"(",
"translation_class",
",",... | test that named tables have identifiers . | train | false |
31,563 | def resolve_variable(path, context):
return Variable(path).resolve(context)
| [
"def",
"resolve_variable",
"(",
"path",
",",
"context",
")",
":",
"return",
"Variable",
"(",
"path",
")",
".",
"resolve",
"(",
"context",
")"
] | returns the resolved variable . | train | false |
31,565 | def _update_image(facebook_id, image_url):
image_name = ('fb_image_%s.jpg' % facebook_id)
image_temp = NamedTemporaryFile()
try:
image_response = urllib2.urlopen(image_url)
except AttributeError:
image_response = urllib.request.urlopen(image_url)
image_content = image_response.read()
image_temp.write(image_content)
http_message = image_response.info()
image_size = len(image_content)
try:
content_type = http_message.type
except AttributeError:
content_type = http_message.get_content_type()
image_file = InMemoryUploadedFile(file=image_temp, name=image_name, field_name='image', content_type=content_type, size=image_size, charset=None)
image_file.seek(0)
image_temp.flush()
return (image_name, image_file)
| [
"def",
"_update_image",
"(",
"facebook_id",
",",
"image_url",
")",
":",
"image_name",
"=",
"(",
"'fb_image_%s.jpg'",
"%",
"facebook_id",
")",
"image_temp",
"=",
"NamedTemporaryFile",
"(",
")",
"try",
":",
"image_response",
"=",
"urllib2",
".",
"urlopen",
"(",
... | updates the user profiles image to the given image url unfortunately this is quite a pain to get right with django suggestions to improve this are welcome . | train | false |
31,566 | def _parse_dist_kw(dist, enforce_subclass=True):
if isinstance(dist, rv_generic):
pass
elif isinstance(dist, string_types):
try:
dist = getattr(distributions, dist)
except AttributeError:
raise ValueError(('%s is not a valid distribution name' % dist))
elif enforce_subclass:
msg = '`dist` should be a stats.distributions instance or a string with the name of such a distribution.'
raise ValueError(msg)
return dist
| [
"def",
"_parse_dist_kw",
"(",
"dist",
",",
"enforce_subclass",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"dist",
",",
"rv_generic",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"dist",
",",
"string_types",
")",
":",
"try",
":",
"dist",
"=",
"getatt... | parse dist keyword . | train | false |
31,567 | def _find_impl(cls, registry):
mro = _compose_mro(cls, registry.keys())
match = None
for t in mro:
if (match is not None):
if ((t in registry) and (t not in cls.__mro__) and (match not in cls.__mro__) and (not issubclass(match, t))):
raise RuntimeError(u'Ambiguous dispatch: {0} or {1}'.format(match, t))
break
if (t in registry):
match = t
return registry.get(match)
| [
"def",
"_find_impl",
"(",
"cls",
",",
"registry",
")",
":",
"mro",
"=",
"_compose_mro",
"(",
"cls",
",",
"registry",
".",
"keys",
"(",
")",
")",
"match",
"=",
"None",
"for",
"t",
"in",
"mro",
":",
"if",
"(",
"match",
"is",
"not",
"None",
")",
":"... | returns the best matching implementation from *registry* for type *cls* . | train | true |
31,568 | def do_crypt_parameters_and_properties():
ctxt = context.get_admin_context()
prev_encryption_key = CONF.command.previous_encryption_key
if (CONF.command.crypt_operation == 'encrypt'):
db_api.encrypt_parameters_and_properties(ctxt, prev_encryption_key, CONF.command.verbose_update_params)
elif (CONF.command.crypt_operation == 'decrypt'):
db_api.decrypt_parameters_and_properties(ctxt, prev_encryption_key, CONF.command.verbose_update_params)
| [
"def",
"do_crypt_parameters_and_properties",
"(",
")",
":",
"ctxt",
"=",
"context",
".",
"get_admin_context",
"(",
")",
"prev_encryption_key",
"=",
"CONF",
".",
"command",
".",
"previous_encryption_key",
"if",
"(",
"CONF",
".",
"command",
".",
"crypt_operation",
"... | encrypt/decrypt hidden parameters and resource properties data . | train | false |
31,569 | def add_bought_with_relations_for_product(product_id, max_quantity=10):
order_ids_to_check = OrderLine.objects.filter(product_id=product_id).values_list('order_id', flat=True)
related_product_ids_and_quantities = OrderLine.objects.exclude(product_id=product_id).filter(type=OrderLineType.PRODUCT, order_id__in=set(order_ids_to_check)).values('product_id').annotate(total_quantity=Sum('quantity')).order_by('-total_quantity')[:max_quantity]
for product_data in related_product_ids_and_quantities:
ProductCrossSell.objects.create(product1_id=product_id, product2_id=product_data['product_id'], weight=product_data['total_quantity'], type=ProductCrossSellType.BOUGHT_WITH)
| [
"def",
"add_bought_with_relations_for_product",
"(",
"product_id",
",",
"max_quantity",
"=",
"10",
")",
":",
"order_ids_to_check",
"=",
"OrderLine",
".",
"objects",
".",
"filter",
"(",
"product_id",
"=",
"product_id",
")",
".",
"values_list",
"(",
"'order_id'",
",... | add productcrosssell objects with type productcrossselltype . | train | false |
31,570 | def print_line(line, highlight=False):
global lineno
try:
if highlight:
line += (' ' * (win.getmaxyx()[1] - len(line)))
win.addstr(lineno, 0, line, curses.A_REVERSE)
else:
win.addstr(lineno, 0, line, 0)
except curses.error:
lineno = 0
win.refresh()
raise
else:
lineno += 1
| [
"def",
"print_line",
"(",
"line",
",",
"highlight",
"=",
"False",
")",
":",
"global",
"lineno",
"try",
":",
"if",
"highlight",
":",
"line",
"+=",
"(",
"' '",
"*",
"(",
"win",
".",
"getmaxyx",
"(",
")",
"[",
"1",
"]",
"-",
"len",
"(",
"line",
")",... | a thin wrapper around cursess addstr() . | train | false |
31,571 | def _csc_gen_triples(A):
ncols = A.shape[1]
(data, indices, indptr) = (A.data, A.indices, A.indptr)
for i in range(ncols):
for j in range(indptr[i], indptr[(i + 1)]):
(yield (indices[j], i, data[j]))
| [
"def",
"_csc_gen_triples",
"(",
"A",
")",
":",
"ncols",
"=",
"A",
".",
"shape",
"[",
"1",
"]",
"(",
"data",
",",
"indices",
",",
"indptr",
")",
"=",
"(",
"A",
".",
"data",
",",
"A",
".",
"indices",
",",
"A",
".",
"indptr",
")",
"for",
"i",
"i... | converts a scipy sparse matrix in **compressed sparse column** format to an iterable of weighted edge triples . | train | false |
31,573 | def class_mock(request, q_class_name, autospec=True, **kwargs):
_patch = patch(q_class_name, autospec=autospec, **kwargs)
request.addfinalizer(_patch.stop)
return _patch.start()
| [
"def",
"class_mock",
"(",
"request",
",",
"q_class_name",
",",
"autospec",
"=",
"True",
",",
"**",
"kwargs",
")",
":",
"_patch",
"=",
"patch",
"(",
"q_class_name",
",",
"autospec",
"=",
"autospec",
",",
"**",
"kwargs",
")",
"request",
".",
"addfinalizer",
... | return a mock patching the class with qualified name *q_class_name* . | train | false |
31,574 | def _add_flags(flags, new_flags):
flags = _get_flags(flags)
new_flags = _get_flags(new_flags)
return (flags | new_flags)
| [
"def",
"_add_flags",
"(",
"flags",
",",
"new_flags",
")",
":",
"flags",
"=",
"_get_flags",
"(",
"flags",
")",
"new_flags",
"=",
"_get_flags",
"(",
"new_flags",
")",
"return",
"(",
"flags",
"|",
"new_flags",
")"
] | combine flags and new_flags . | train | true |
31,575 | def get_tag_from_other_config(bridge, port_name):
other_config = None
try:
other_config = bridge.db_get_val('Port', port_name, 'other_config')
return int(other_config['tag'])
except (KeyError, TypeError, ValueError):
raise exceptions.OVSFWTagNotFound(port_name=port_name, other_config=other_config)
| [
"def",
"get_tag_from_other_config",
"(",
"bridge",
",",
"port_name",
")",
":",
"other_config",
"=",
"None",
"try",
":",
"other_config",
"=",
"bridge",
".",
"db_get_val",
"(",
"'Port'",
",",
"port_name",
",",
"'other_config'",
")",
"return",
"int",
"(",
"other_... | return tag stored in ovsdb other_config metadata . | train | false |
31,577 | def increment_odd(x):
raise NotImplementedError('TODO: implement the function.')
| [
"def",
"increment_odd",
"(",
"x",
")",
":",
"raise",
"NotImplementedError",
"(",
"'TODO: implement the function.'",
")"
] | x: a theano vector returns: y: a theano vector equal to x . | train | false |
31,578 | def convertContainerElementNode(elementNode, geometryOutput, xmlObject):
elementNode.linkObject(xmlObject)
matrix.getBranchMatrixSetElementNode(elementNode)
elementNode.getXMLProcessor().createChildNodes(geometryOutput['shapes'], elementNode)
| [
"def",
"convertContainerElementNode",
"(",
"elementNode",
",",
"geometryOutput",
",",
"xmlObject",
")",
":",
"elementNode",
".",
"linkObject",
"(",
"xmlObject",
")",
"matrix",
".",
"getBranchMatrixSetElementNode",
"(",
"elementNode",
")",
"elementNode",
".",
"getXMLPr... | convert the xml element to a group xml element . | train | false |
31,579 | def _ra_pid_for(dev):
pid_file = _ra_file(dev, 'pid')
if os.path.exists(pid_file):
with open(pid_file, 'r') as f:
return int(f.read())
| [
"def",
"_ra_pid_for",
"(",
"dev",
")",
":",
"pid_file",
"=",
"_ra_file",
"(",
"dev",
",",
"'pid'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pid_file",
")",
":",
"with",
"open",
"(",
"pid_file",
",",
"'r'",
")",
"as",
"f",
":",
"return",
... | returns the pid for prior radvd instance for a bridge/device . | train | false |
31,580 | def sm_backend_conf_get_all(context):
return IMPL.sm_backend_conf_get_all(context)
| [
"def",
"sm_backend_conf_get_all",
"(",
"context",
")",
":",
"return",
"IMPL",
".",
"sm_backend_conf_get_all",
"(",
"context",
")"
] | get all sm backend configs . | train | false |
31,581 | def global_avg_pool(incoming, name='GlobalAvgPool'):
input_shape = utils.get_incoming_shape(incoming)
assert (len(input_shape) == 4), 'Incoming Tensor shape must be 4-D'
with tf.name_scope(name):
inference = tf.reduce_mean(incoming, [1, 2])
tf.add_to_collection(((tf.GraphKeys.LAYER_TENSOR + '/') + name), inference)
return inference
| [
"def",
"global_avg_pool",
"(",
"incoming",
",",
"name",
"=",
"'GlobalAvgPool'",
")",
":",
"input_shape",
"=",
"utils",
".",
"get_incoming_shape",
"(",
"incoming",
")",
"assert",
"(",
"len",
"(",
"input_shape",
")",
"==",
"4",
")",
",",
"'Incoming Tensor shape ... | global average pooling . | train | false |
31,582 | def BatchedSparseToDense(sparse_indices, output_size):
eye = tf.diag(tf.fill([output_size], tf.constant(1, tf.float32)))
return tf.nn.embedding_lookup(eye, sparse_indices)
| [
"def",
"BatchedSparseToDense",
"(",
"sparse_indices",
",",
"output_size",
")",
":",
"eye",
"=",
"tf",
".",
"diag",
"(",
"tf",
".",
"fill",
"(",
"[",
"output_size",
"]",
",",
"tf",
".",
"constant",
"(",
"1",
",",
"tf",
".",
"float32",
")",
")",
")",
... | batch compatible sparse to dense conversion . | train | false |
31,583 | def _get_builtin_permissions(opts):
perms = []
for action in (u'add', u'change', u'delete'):
perms.append((get_permission_codename(action, opts), (u'Can %s %s' % (action, opts.verbose_name_raw))))
return perms
| [
"def",
"_get_builtin_permissions",
"(",
"opts",
")",
":",
"perms",
"=",
"[",
"]",
"for",
"action",
"in",
"(",
"u'add'",
",",
"u'change'",
",",
"u'delete'",
")",
":",
"perms",
".",
"append",
"(",
"(",
"get_permission_codename",
"(",
"action",
",",
"opts",
... | returns for all autogenerated permissions . | train | false |
31,585 | def save_products(shop, products_pk):
configuration.set(shop, SAMPLE_PRODUCTS_KEY, products_pk)
| [
"def",
"save_products",
"(",
"shop",
",",
"products_pk",
")",
":",
"configuration",
".",
"set",
"(",
"shop",
",",
"SAMPLE_PRODUCTS_KEY",
",",
"products_pk",
")"
] | save a list of pk as a list of sample products for a shop . | train | false |
31,586 | @register_specialize
@gof.local_optimizer([T.Elemwise])
def local_elemwise_sub_zeros(node):
if (isinstance(node.op, T.Elemwise) and (node.op.scalar_op.nin == 2) and (node.op.scalar_op == scalar.sub) and (node.inputs[0] == node.inputs[1])):
res = T.zeros_like(node.inputs[0])
copy_stack_trace(node.outputs, res)
return [res]
| [
"@",
"register_specialize",
"@",
"gof",
".",
"local_optimizer",
"(",
"[",
"T",
".",
"Elemwise",
"]",
")",
"def",
"local_elemwise_sub_zeros",
"(",
"node",
")",
":",
"if",
"(",
"isinstance",
"(",
"node",
".",
"op",
",",
"T",
".",
"Elemwise",
")",
"and",
... | elemwise{sub} -> zeros_like(x) . | train | false |
31,588 | def _basic_auth_str(username, password):
return ('Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1'))
| [
"def",
"_basic_auth_str",
"(",
"username",
",",
"password",
")",
":",
"return",
"(",
"'Basic '",
"+",
"b64encode",
"(",
"(",
"'%s:%s'",
"%",
"(",
"username",
",",
"password",
")",
")",
".",
"encode",
"(",
"'latin1'",
")",
")",
".",
"strip",
"(",
")",
... | returns a basic auth string . | train | false |
31,589 | def format_explanation(explanation):
explanation = ecu(explanation)
lines = _split_explanation(explanation)
result = _format_lines(lines)
return u('\n').join(result)
| [
"def",
"format_explanation",
"(",
"explanation",
")",
":",
"explanation",
"=",
"ecu",
"(",
"explanation",
")",
"lines",
"=",
"_split_explanation",
"(",
"explanation",
")",
"result",
"=",
"_format_lines",
"(",
"lines",
")",
"return",
"u",
"(",
"'\\n'",
")",
"... | this formats an explanation normally all embedded newlines are escaped . | train | false |
31,591 | def ellipse(x, y, a, b, resolution, fillDensity=False):
poly = toolpath.Polygon()
if (not resolution):
resolution = self.circleResolution
if fillDensity:
if (a > b):
largerDimension = a
else:
largerDimension = b
numFills = int((float(fillDensity) * float(largerDimension)))
else:
numFills = 1
(startAngle, endAngle) = (0, 360)
circumference = ((float(2) * math.pi) * float((float((a + b)) / 2)))
angleDiv = (float(360) / float((circumference * resolution)))
(lastX, lastY) = _calcEllipse(startAngle, a, b)
if (startAngle > endAngle):
endAngle += 360
for d in range(1, (numFills + 1)):
ra = ((float(d) / float(numFills)) * float(a))
rb = ((float(d) / float(numFills)) * float(b))
for theta in _frange(startAngle, (endAngle + angleDiv), angleDiv):
(newX, newY) = _calcEllipse(theta, ra, rb)
aLine = poly.addPoint(toolpath.Point((newX + x), (newY + y)))
if debug:
print 'aLine', aLine
return poly
| [
"def",
"ellipse",
"(",
"x",
",",
"y",
",",
"a",
",",
"b",
",",
"resolution",
",",
"fillDensity",
"=",
"False",
")",
":",
"poly",
"=",
"toolpath",
".",
"Polygon",
"(",
")",
"if",
"(",
"not",
"resolution",
")",
":",
"resolution",
"=",
"self",
".",
... | generates a flat . | train | false |
31,592 | def ward(y):
return linkage(y, method='ward', metric='euclidean')
| [
"def",
"ward",
"(",
"y",
")",
":",
"return",
"linkage",
"(",
"y",
",",
"method",
"=",
"'ward'",
",",
"metric",
"=",
"'euclidean'",
")"
] | performs wards linkage on a condensed distance matrix . | train | false |
31,593 | def get_doc_version(version):
parsed_version = parse_version(version)
if (is_release(version) and (parsed_version.documentation_revision is not None)):
return parsed_version.release
else:
return version
| [
"def",
"get_doc_version",
"(",
"version",
")",
":",
"parsed_version",
"=",
"parse_version",
"(",
"version",
")",
"if",
"(",
"is_release",
"(",
"version",
")",
"and",
"(",
"parsed_version",
".",
"documentation_revision",
"is",
"not",
"None",
")",
")",
":",
"r... | get the version string of flocker to display in documentation . | train | false |
31,594 | def get_row_nnz(mat, row):
return (mat.indptr[(row + 1)] - mat.indptr[row])
| [
"def",
"get_row_nnz",
"(",
"mat",
",",
"row",
")",
":",
"return",
"(",
"mat",
".",
"indptr",
"[",
"(",
"row",
"+",
"1",
")",
"]",
"-",
"mat",
".",
"indptr",
"[",
"row",
"]",
")"
] | return the number of nonzeros in row . | train | false |
31,596 | def int2bytes(number):
if (not ((type(number) is types.LongType) or (type(number) is types.IntType))):
raise TypeError('You must pass a long or an int')
string = ''
while (number > 0):
string = ('%s%s' % (byte((number & 255)), string))
number /= 256
return string
| [
"def",
"int2bytes",
"(",
"number",
")",
":",
"if",
"(",
"not",
"(",
"(",
"type",
"(",
"number",
")",
"is",
"types",
".",
"LongType",
")",
"or",
"(",
"type",
"(",
"number",
")",
"is",
"types",
".",
"IntType",
")",
")",
")",
":",
"raise",
"TypeErro... | converts a number to a string of bytes . | train | false |
31,597 | def disable_plugin(name, runas=None):
if ((runas is None) and (not salt.utils.is_windows())):
runas = salt.utils.get_user()
cmd = [_get_rabbitmq_plugin(), 'disable', name]
ret = __salt__['cmd.run_all'](cmd, runas=runas, python_shell=False)
return _format_response(ret, 'Disabled')
| [
"def",
"disable_plugin",
"(",
"name",
",",
"runas",
"=",
"None",
")",
":",
"if",
"(",
"(",
"runas",
"is",
"None",
")",
"and",
"(",
"not",
"salt",
".",
"utils",
".",
"is_windows",
"(",
")",
")",
")",
":",
"runas",
"=",
"salt",
".",
"utils",
".",
... | disable a rabbitmq plugin via the rabbitmq-plugins command . | train | true |
31,598 | def p_pointer_2(t):
pass
| [
"def",
"p_pointer_2",
"(",
"t",
")",
":",
"pass"
] | pointer : times . | train | false |
31,599 | def check_fiff_length(fid, close=True):
if (fid.tell() > 2147483648):
if close:
fid.close()
raise IOError('FIFF file exceeded 2GB limit, please split file or save to a different format')
| [
"def",
"check_fiff_length",
"(",
"fid",
",",
"close",
"=",
"True",
")",
":",
"if",
"(",
"fid",
".",
"tell",
"(",
")",
">",
"2147483648",
")",
":",
"if",
"close",
":",
"fid",
".",
"close",
"(",
")",
"raise",
"IOError",
"(",
"'FIFF file exceeded 2GB limi... | ensure our file hasnt grown too large to work properly . | train | false |
31,600 | def dup_convert(f, K0, K1):
if ((K0 is not None) and (K0 == K1)):
return f
else:
return dup_strip([K1.convert(c, K0) for c in f])
| [
"def",
"dup_convert",
"(",
"f",
",",
"K0",
",",
"K1",
")",
":",
"if",
"(",
"(",
"K0",
"is",
"not",
"None",
")",
"and",
"(",
"K0",
"==",
"K1",
")",
")",
":",
"return",
"f",
"else",
":",
"return",
"dup_strip",
"(",
"[",
"K1",
".",
"convert",
"(... | convert the ground domain of f from k0 to k1 . | train | false |
31,604 | def get_cfg_args():
if (not os.path.exists('setup.cfg')):
return {}
cfg = ConfigParser()
cfg.read('setup.cfg')
cfg = cfg2dict(cfg)
g = cfg.setdefault('global', {})
for key in ['libzmq_extension', 'bundle_libzmq_dylib', 'no_libzmq_extension', 'have_sys_un_h', 'skip_check_zmq', 'bundle_msvcp']:
if (key in g):
g[key] = eval(g[key])
cfg.update(cfg.pop('global'))
return cfg
| [
"def",
"get_cfg_args",
"(",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'setup.cfg'",
")",
")",
":",
"return",
"{",
"}",
"cfg",
"=",
"ConfigParser",
"(",
")",
"cfg",
".",
"read",
"(",
"'setup.cfg'",
")",
"cfg",
"=",
"cfg2dic... | look for options in setup . | train | true |
31,605 | def crossentropy_softmax_max_and_argmax_1hot_with_bias(x, b, y_idx, **kwargs):
(xent, softmax) = crossentropy_softmax_1hot_with_bias(x, b, y_idx, **kwargs)
(max_pr, argmax) = tensor.max_and_argmax(softmax, axis=(-1))
return (xent, softmax, max_pr, argmax)
| [
"def",
"crossentropy_softmax_max_and_argmax_1hot_with_bias",
"(",
"x",
",",
"b",
",",
"y_idx",
",",
"**",
"kwargs",
")",
":",
"(",
"xent",
",",
"softmax",
")",
"=",
"crossentropy_softmax_1hot_with_bias",
"(",
"x",
",",
"b",
",",
"y_idx",
",",
"**",
"kwargs",
... | returns object the cross-entropy . | train | false |
31,607 | def enqueue(method, queue=u'default', timeout=300, event=None, async=True, job_name=None, **kwargs):
q = get_queue(queue, async=async)
if (not timeout):
timeout = (queue_timeout.get(queue) or 300)
return q.enqueue_call(execute_job, timeout=timeout, kwargs={u'site': frappe.local.site, u'user': frappe.session.user, u'method': method, u'event': event, u'job_name': (job_name or cstr(method)), u'async': async, u'kwargs': kwargs})
| [
"def",
"enqueue",
"(",
"method",
",",
"queue",
"=",
"u'default'",
",",
"timeout",
"=",
"300",
",",
"event",
"=",
"None",
",",
"async",
"=",
"True",
",",
"job_name",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"q",
"=",
"get_queue",
"(",
"queue",
",... | enqueue method to be executed using a background worker . | train | false |
31,608 | def humanbytes(s):
return next((u'{0}{1}'.format(hfloat(((s / div) if div else s)), unit) for (div, unit) in UNITS if (s >= div)))
| [
"def",
"humanbytes",
"(",
"s",
")",
":",
"return",
"next",
"(",
"(",
"u'{0}{1}'",
".",
"format",
"(",
"hfloat",
"(",
"(",
"(",
"s",
"/",
"div",
")",
"if",
"div",
"else",
"s",
")",
")",
",",
"unit",
")",
"for",
"(",
"div",
",",
"unit",
")",
"i... | convert bytes to human-readable form . | train | false |
31,609 | def get_phylogenetic_metric(name):
try:
return getattr(qiime.beta_metrics, ('dist_' + name.lower()))
except AttributeError:
try:
return getattr(qiime.beta_metrics, name.replace('binary', 'binary_dist').lower())
except AttributeError:
return getattr(qiime.beta_metrics, name.lower())
| [
"def",
"get_phylogenetic_metric",
"(",
"name",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"qiime",
".",
"beta_metrics",
",",
"(",
"'dist_'",
"+",
"name",
".",
"lower",
"(",
")",
")",
")",
"except",
"AttributeError",
":",
"try",
":",
"return",
"getat... | gets metric by name from list in this module . | train | false |
31,611 | def get_system_packs_base_path():
return cfg.CONF.content.system_packs_base_path
| [
"def",
"get_system_packs_base_path",
"(",
")",
":",
"return",
"cfg",
".",
"CONF",
".",
"content",
".",
"system_packs_base_path"
] | return a path to the directory where system packs are stored . | train | false |
31,612 | def has_value(key):
return (True if salt.utils.traverse_dict_and_list(__grains__, key, False) else False)
| [
"def",
"has_value",
"(",
"key",
")",
":",
"return",
"(",
"True",
"if",
"salt",
".",
"utils",
".",
"traverse_dict_and_list",
"(",
"__grains__",
",",
"key",
",",
"False",
")",
"else",
"False",
")"
] | determine whether a named value exists in the grains dictionary . | train | true |
31,614 | @removals.remove(message='Use is_asn1_token() instead.', version='1.7.0', removal_version='2.0.0')
def is_ans1_token(token):
return is_asn1_token(token)
| [
"@",
"removals",
".",
"remove",
"(",
"message",
"=",
"'Use is_asn1_token() instead.'",
",",
"version",
"=",
"'1.7.0'",
",",
"removal_version",
"=",
"'2.0.0'",
")",
"def",
"is_ans1_token",
"(",
"token",
")",
":",
"return",
"is_asn1_token",
"(",
"token",
")"
] | thx to ayoung for sorting this out . | train | false |
31,615 | def _get_mac_address(ip_address):
from subprocess import Popen, PIPE
pid = Popen(['arp', '-n', ip_address], stdout=PIPE)
pid_component = pid.communicate()[0]
match = re.search('(([a-f\\d]{1,2}\\:){5}[a-f\\d]{1,2})'.encode('UTF-8'), pid_component)
if (match is not None):
return match.groups()[0]
else:
return None
| [
"def",
"_get_mac_address",
"(",
"ip_address",
")",
":",
"from",
"subprocess",
"import",
"Popen",
",",
"PIPE",
"pid",
"=",
"Popen",
"(",
"[",
"'arp'",
",",
"'-n'",
",",
"ip_address",
"]",
",",
"stdout",
"=",
"PIPE",
")",
"pid_component",
"=",
"pid",
".",
... | get the mac address of the device . | train | false |
31,617 | def xlabel(s, *args, **kwargs):
l = gca().set_xlabel(s, *args, **kwargs)
draw_if_interactive()
return l
| [
"def",
"xlabel",
"(",
"s",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"l",
"=",
"gca",
"(",
")",
".",
"set_xlabel",
"(",
"s",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"draw_if_interactive",
"(",
")",
"return",
"l"
] | set the *x* axis label of the current axis . | train | false |
31,619 | def get_moon(time, location=None, ephemeris=None):
return get_body(u'moon', time, location=location, ephemeris=ephemeris)
| [
"def",
"get_moon",
"(",
"time",
",",
"location",
"=",
"None",
",",
"ephemeris",
"=",
"None",
")",
":",
"return",
"get_body",
"(",
"u'moon'",
",",
"time",
",",
"location",
"=",
"location",
",",
"ephemeris",
"=",
"ephemeris",
")"
] | get a ~astropy . | train | false |
31,620 | def p_direct_declarator_5(t):
pass
| [
"def",
"p_direct_declarator_5",
"(",
"t",
")",
":",
"pass"
] | direct_declarator : direct_declarator lparen identifier_list rparen . | train | false |
31,621 | def newid(length=16):
l = int(math.ceil(((float(length) * 6.0) / 8.0)))
return base64.b64encode(os.urandom(l))[:length].decode('ascii')
| [
"def",
"newid",
"(",
"length",
"=",
"16",
")",
":",
"l",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"(",
"(",
"float",
"(",
"length",
")",
"*",
"6.0",
")",
"/",
"8.0",
")",
")",
")",
"return",
"base64",
".",
"b64encode",
"(",
"os",
".",
"uran... | generate a new random string id . | train | false |
31,622 | def quaternion_inverse(quaternion):
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
numpy.negative(q[1:], q[1:])
return (q / numpy.dot(q, q))
| [
"def",
"quaternion_inverse",
"(",
"quaternion",
")",
":",
"q",
"=",
"numpy",
".",
"array",
"(",
"quaternion",
",",
"dtype",
"=",
"numpy",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"numpy",
".",
"negative",
"(",
"q",
"[",
"1",
":",
"]",
",",
"q... | return inverse of quaternion . | train | true |
31,624 | def expire(key, seconds, host=None, port=None, db=None, password=None):
server = _connect(host, port, db, password)
return server.expire(key, seconds)
| [
"def",
"expire",
"(",
"key",
",",
"seconds",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",... | expire the current session cookie . | train | true |
31,625 | def read_cz_lsm_positions(fh):
size = struct.unpack('<I', fh.read(4))[0]
return fh.read_array('<2f8', count=size)
| [
"def",
"read_cz_lsm_positions",
"(",
"fh",
")",
":",
"size",
"=",
"struct",
".",
"unpack",
"(",
"'<I'",
",",
"fh",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"return",
"fh",
".",
"read_array",
"(",
"'<2f8'",
",",
"count",
"=",
"size",
")"
] | read lsm positions from file and return as list . | train | false |
31,628 | def getCraftModule(fileName):
return archive.getModuleWithDirectoryPath(getPluginsDirectoryPath(), fileName)
| [
"def",
"getCraftModule",
"(",
"fileName",
")",
":",
"return",
"archive",
".",
"getModuleWithDirectoryPath",
"(",
"getPluginsDirectoryPath",
"(",
")",
",",
"fileName",
")"
] | get craft module . | train | false |
31,630 | def get_venv_path(venv):
sys_path = _get_venv_path_dirs(venv)
with common.ignored(ValueError):
sys_path.remove('')
sys_path = _get_sys_path_with_egglinks(sys_path)
return (sys_path + sys.path)
| [
"def",
"get_venv_path",
"(",
"venv",
")",
":",
"sys_path",
"=",
"_get_venv_path_dirs",
"(",
"venv",
")",
"with",
"common",
".",
"ignored",
"(",
"ValueError",
")",
":",
"sys_path",
".",
"remove",
"(",
"''",
")",
"sys_path",
"=",
"_get_sys_path_with_egglinks",
... | get sys . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.