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 |
|---|---|---|---|---|---|
39,025 | def add_documenter(cls):
if (not issubclass(cls, Documenter)):
raise ExtensionError(('autodoc documenter %r must be a subclass of Documenter' % cls))
AutoDirective._registry[cls.objtype] = cls
| [
"def",
"add_documenter",
"(",
"cls",
")",
":",
"if",
"(",
"not",
"issubclass",
"(",
"cls",
",",
"Documenter",
")",
")",
":",
"raise",
"ExtensionError",
"(",
"(",
"'autodoc documenter %r must be a subclass of Documenter'",
"%",
"cls",
")",
")",
"AutoDirective",
".",
"_registry",
"[",
"cls",
".",
"objtype",
"]",
"=",
"cls"
] | register a new documenter . | train | false |
39,028 | @webob.dec.wsgify
@util.check_accept('application/json')
def get_inventory(req):
context = req.environ['placement.context']
uuid = util.wsgi_path_item(req.environ, 'uuid')
resource_class = util.wsgi_path_item(req.environ, 'resource_class')
resource_provider = objects.ResourceProvider.get_by_uuid(context, uuid)
inventory = objects.InventoryList.get_all_by_resource_provider_uuid(context, resource_provider.uuid).find(resource_class)
if (not inventory):
raise webob.exc.HTTPNotFound((_('No inventory of class %(class)s for %(rp_uuid)s') % {'class': resource_class, 'rp_uuid': resource_provider.uuid}), json_formatter=util.json_error_formatter)
return _send_inventory(req.response, resource_provider, inventory)
| [
"@",
"webob",
".",
"dec",
".",
"wsgify",
"@",
"util",
".",
"check_accept",
"(",
"'application/json'",
")",
"def",
"get_inventory",
"(",
"req",
")",
":",
"context",
"=",
"req",
".",
"environ",
"[",
"'placement.context'",
"]",
"uuid",
"=",
"util",
".",
"wsgi_path_item",
"(",
"req",
".",
"environ",
",",
"'uuid'",
")",
"resource_class",
"=",
"util",
".",
"wsgi_path_item",
"(",
"req",
".",
"environ",
",",
"'resource_class'",
")",
"resource_provider",
"=",
"objects",
".",
"ResourceProvider",
".",
"get_by_uuid",
"(",
"context",
",",
"uuid",
")",
"inventory",
"=",
"objects",
".",
"InventoryList",
".",
"get_all_by_resource_provider_uuid",
"(",
"context",
",",
"resource_provider",
".",
"uuid",
")",
".",
"find",
"(",
"resource_class",
")",
"if",
"(",
"not",
"inventory",
")",
":",
"raise",
"webob",
".",
"exc",
".",
"HTTPNotFound",
"(",
"(",
"_",
"(",
"'No inventory of class %(class)s for %(rp_uuid)s'",
")",
"%",
"{",
"'class'",
":",
"resource_class",
",",
"'rp_uuid'",
":",
"resource_provider",
".",
"uuid",
"}",
")",
",",
"json_formatter",
"=",
"util",
".",
"json_error_formatter",
")",
"return",
"_send_inventory",
"(",
"req",
".",
"response",
",",
"resource_provider",
",",
"inventory",
")"
] | get one inventory . | train | false |
39,029 | def RemoveMultiLineComments(filename, lines, error):
lineix = 0
while (lineix < len(lines)):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if (lineix_begin >= len(lines)):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if (lineix_end >= len(lines)):
error(filename, (lineix_begin + 1), 'readability/multiline_comment', 5, 'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, (lineix_end + 1))
lineix = (lineix_end + 1)
| [
"def",
"RemoveMultiLineComments",
"(",
"filename",
",",
"lines",
",",
"error",
")",
":",
"lineix",
"=",
"0",
"while",
"(",
"lineix",
"<",
"len",
"(",
"lines",
")",
")",
":",
"lineix_begin",
"=",
"FindNextMultiLineCommentStart",
"(",
"lines",
",",
"lineix",
")",
"if",
"(",
"lineix_begin",
">=",
"len",
"(",
"lines",
")",
")",
":",
"return",
"lineix_end",
"=",
"FindNextMultiLineCommentEnd",
"(",
"lines",
",",
"lineix_begin",
")",
"if",
"(",
"lineix_end",
">=",
"len",
"(",
"lines",
")",
")",
":",
"error",
"(",
"filename",
",",
"(",
"lineix_begin",
"+",
"1",
")",
",",
"'readability/multiline_comment'",
",",
"5",
",",
"'Could not find end of multi-line comment'",
")",
"return",
"RemoveMultiLineCommentsFromRange",
"(",
"lines",
",",
"lineix_begin",
",",
"(",
"lineix_end",
"+",
"1",
")",
")",
"lineix",
"=",
"(",
"lineix_end",
"+",
"1",
")"
] | removes multiline comments from lines . | train | true |
39,030 | def exponential_retrier(func_to_retry, exception_filter=(lambda *args, **kw: True), retry_min_wait_ms=500, max_retries=5):
sleep_time = retry_min_wait_ms
num_retried = 0
while True:
try:
return func_to_retry()
except StopIteration:
raise
except Exception as e:
g.log.exception(('%d number retried' % num_retried))
num_retried += 1
if ((num_retried > max_retries) or (not exception_filter(e))):
raise
time.sleep((sleep_time / 1000.0))
sleep_time *= 2
| [
"def",
"exponential_retrier",
"(",
"func_to_retry",
",",
"exception_filter",
"=",
"(",
"lambda",
"*",
"args",
",",
"**",
"kw",
":",
"True",
")",
",",
"retry_min_wait_ms",
"=",
"500",
",",
"max_retries",
"=",
"5",
")",
":",
"sleep_time",
"=",
"retry_min_wait_ms",
"num_retried",
"=",
"0",
"while",
"True",
":",
"try",
":",
"return",
"func_to_retry",
"(",
")",
"except",
"StopIteration",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"g",
".",
"log",
".",
"exception",
"(",
"(",
"'%d number retried'",
"%",
"num_retried",
")",
")",
"num_retried",
"+=",
"1",
"if",
"(",
"(",
"num_retried",
">",
"max_retries",
")",
"or",
"(",
"not",
"exception_filter",
"(",
"e",
")",
")",
")",
":",
"raise",
"time",
".",
"sleep",
"(",
"(",
"sleep_time",
"/",
"1000.0",
")",
")",
"sleep_time",
"*=",
"2"
] | call func_to_retry and return its results . | train | false |
39,031 | def test_world_should_be_able_to_absorb_lambdas():
assert (not hasattr(world, 'named_func'))
world.absorb((lambda : 'absorbed'), 'named_func')
assert hasattr(world, 'named_func')
assert callable(world.named_func)
assert_equals(world.named_func(), 'absorbed')
world.spew('named_func')
assert (not hasattr(world, 'named_func'))
| [
"def",
"test_world_should_be_able_to_absorb_lambdas",
"(",
")",
":",
"assert",
"(",
"not",
"hasattr",
"(",
"world",
",",
"'named_func'",
")",
")",
"world",
".",
"absorb",
"(",
"(",
"lambda",
":",
"'absorbed'",
")",
",",
"'named_func'",
")",
"assert",
"hasattr",
"(",
"world",
",",
"'named_func'",
")",
"assert",
"callable",
"(",
"world",
".",
"named_func",
")",
"assert_equals",
"(",
"world",
".",
"named_func",
"(",
")",
",",
"'absorbed'",
")",
"world",
".",
"spew",
"(",
"'named_func'",
")",
"assert",
"(",
"not",
"hasattr",
"(",
"world",
",",
"'named_func'",
")",
")"
] | world should be able to absorb lambdas . | train | false |
39,032 | def get_secret_parameters(parameters):
secret_parameters = [parameter for (parameter, options) in six.iteritems(parameters) if options.get('secret', False)]
return secret_parameters
| [
"def",
"get_secret_parameters",
"(",
"parameters",
")",
":",
"secret_parameters",
"=",
"[",
"parameter",
"for",
"(",
"parameter",
",",
"options",
")",
"in",
"six",
".",
"iteritems",
"(",
"parameters",
")",
"if",
"options",
".",
"get",
"(",
"'secret'",
",",
"False",
")",
"]",
"return",
"secret_parameters"
] | filter the provided parameters dict and return a list of parameter names which are marked as secret . | train | false |
39,034 | def snap_to_roads(client, path, interpolate=False):
params = {'path': convert.location_list(path)}
if interpolate:
params['interpolate'] = 'true'
return client._get('/v1/snapToRoads', params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get('snappedPoints', [])
| [
"def",
"snap_to_roads",
"(",
"client",
",",
"path",
",",
"interpolate",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'path'",
":",
"convert",
".",
"location_list",
"(",
"path",
")",
"}",
"if",
"interpolate",
":",
"params",
"[",
"'interpolate'",
"]",
"=",
"'true'",
"return",
"client",
".",
"_get",
"(",
"'/v1/snapToRoads'",
",",
"params",
",",
"base_url",
"=",
"_ROADS_BASE_URL",
",",
"accepts_clientid",
"=",
"False",
",",
"extract_body",
"=",
"_roads_extract",
")",
".",
"get",
"(",
"'snappedPoints'",
",",
"[",
"]",
")"
] | snaps a path to the most likely roads travelled . | train | true |
39,035 | def new_wrapper(wrapper, model):
if isinstance(model, dict):
infodict = model
else:
infodict = getinfo(model)
assert (not ('_wrapper_' in infodict['argnames'])), '"_wrapper_" is a reserved argument name!'
src = ('lambda %(signature)s: _wrapper_(%(signature)s)' % infodict)
funcopy = eval(src, dict(_wrapper_=wrapper))
return update_wrapper(funcopy, model, infodict)
| [
"def",
"new_wrapper",
"(",
"wrapper",
",",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"dict",
")",
":",
"infodict",
"=",
"model",
"else",
":",
"infodict",
"=",
"getinfo",
"(",
"model",
")",
"assert",
"(",
"not",
"(",
"'_wrapper_'",
"in",
"infodict",
"[",
"'argnames'",
"]",
")",
")",
",",
"'\"_wrapper_\" is a reserved argument name!'",
"src",
"=",
"(",
"'lambda %(signature)s: _wrapper_(%(signature)s)'",
"%",
"infodict",
")",
"funcopy",
"=",
"eval",
"(",
"src",
",",
"dict",
"(",
"_wrapper_",
"=",
"wrapper",
")",
")",
"return",
"update_wrapper",
"(",
"funcopy",
",",
"model",
",",
"infodict",
")"
] | an improvement over functools . | train | false |
39,037 | def pipeline_property(name, **kwargs):
cache_attr_name = ('_%s' % name)
def getter(self):
cached_value = getattr(self, cache_attr_name, None)
if cached_value:
return cached_value
app = self
while True:
app = getattr(app, 'app', None)
if (not app):
break
try:
value = getattr(app, name)
except AttributeError:
continue
setattr(self, cache_attr_name, value)
return value
if ('default' in kwargs):
return kwargs['default']
raise AttributeError(('No apps in pipeline have a %s attribute' % name))
return property(getter)
| [
"def",
"pipeline_property",
"(",
"name",
",",
"**",
"kwargs",
")",
":",
"cache_attr_name",
"=",
"(",
"'_%s'",
"%",
"name",
")",
"def",
"getter",
"(",
"self",
")",
":",
"cached_value",
"=",
"getattr",
"(",
"self",
",",
"cache_attr_name",
",",
"None",
")",
"if",
"cached_value",
":",
"return",
"cached_value",
"app",
"=",
"self",
"while",
"True",
":",
"app",
"=",
"getattr",
"(",
"app",
",",
"'app'",
",",
"None",
")",
"if",
"(",
"not",
"app",
")",
":",
"break",
"try",
":",
"value",
"=",
"getattr",
"(",
"app",
",",
"name",
")",
"except",
"AttributeError",
":",
"continue",
"setattr",
"(",
"self",
",",
"cache_attr_name",
",",
"value",
")",
"return",
"value",
"if",
"(",
"'default'",
"in",
"kwargs",
")",
":",
"return",
"kwargs",
"[",
"'default'",
"]",
"raise",
"AttributeError",
"(",
"(",
"'No apps in pipeline have a %s attribute'",
"%",
"name",
")",
")",
"return",
"property",
"(",
"getter",
")"
] | create a property accessor for the given name . | train | false |
39,038 | def get_latest_downloadable_repository_metadata_if_it_includes_tools(trans, repository):
repository_metadata = get_latest_downloadable_repository_metadata(trans, repository)
if ((repository_metadata is not None) and repository_metadata.includes_tools):
return repository_metadata
return None
| [
"def",
"get_latest_downloadable_repository_metadata_if_it_includes_tools",
"(",
"trans",
",",
"repository",
")",
":",
"repository_metadata",
"=",
"get_latest_downloadable_repository_metadata",
"(",
"trans",
",",
"repository",
")",
"if",
"(",
"(",
"repository_metadata",
"is",
"not",
"None",
")",
"and",
"repository_metadata",
".",
"includes_tools",
")",
":",
"return",
"repository_metadata",
"return",
"None"
] | return the latest downloadable repository_metadata record for the received repository if its includes_tools attribute is true . | train | false |
39,039 | def _list_all_steps(emr_conn, cluster_id, *args, **kwargs):
return list(reversed(list(_yield_all_steps(emr_conn, cluster_id, *args, **kwargs))))
| [
"def",
"_list_all_steps",
"(",
"emr_conn",
",",
"cluster_id",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"list",
"(",
"reversed",
"(",
"list",
"(",
"_yield_all_steps",
"(",
"emr_conn",
",",
"cluster_id",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
")",
")"
] | return all steps for the cluster as a list . | train | false |
39,040 | def _encode_bool(name, value, dummy0, dummy1):
return (('\x08' + name) + ((value and '\x01') or '\x00'))
| [
"def",
"_encode_bool",
"(",
"name",
",",
"value",
",",
"dummy0",
",",
"dummy1",
")",
":",
"return",
"(",
"(",
"'\\x08'",
"+",
"name",
")",
"+",
"(",
"(",
"value",
"and",
"'\\x01'",
")",
"or",
"'\\x00'",
")",
")"
] | encode a python boolean . | train | false |
39,041 | def getProcedures(procedure, text):
craftSequence = getReadCraftSequence()
sequenceIndexFromProcedure = 0
if (procedure in craftSequence):
sequenceIndexFromProcedure = craftSequence.index(procedure)
craftSequence = craftSequence[:(sequenceIndexFromProcedure + 1)]
for craftSequenceIndex in xrange((len(craftSequence) - 1), (-1), (-1)):
procedure = craftSequence[craftSequenceIndex]
if gcodec.isProcedureDone(text, procedure):
return craftSequence[(craftSequenceIndex + 1):]
return craftSequence
| [
"def",
"getProcedures",
"(",
"procedure",
",",
"text",
")",
":",
"craftSequence",
"=",
"getReadCraftSequence",
"(",
")",
"sequenceIndexFromProcedure",
"=",
"0",
"if",
"(",
"procedure",
"in",
"craftSequence",
")",
":",
"sequenceIndexFromProcedure",
"=",
"craftSequence",
".",
"index",
"(",
"procedure",
")",
"craftSequence",
"=",
"craftSequence",
"[",
":",
"(",
"sequenceIndexFromProcedure",
"+",
"1",
")",
"]",
"for",
"craftSequenceIndex",
"in",
"xrange",
"(",
"(",
"len",
"(",
"craftSequence",
")",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
":",
"procedure",
"=",
"craftSequence",
"[",
"craftSequenceIndex",
"]",
"if",
"gcodec",
".",
"isProcedureDone",
"(",
"text",
",",
"procedure",
")",
":",
"return",
"craftSequence",
"[",
"(",
"craftSequenceIndex",
"+",
"1",
")",
":",
"]",
"return",
"craftSequence"
] | get the procedures up to and including the given procedure . | train | false |
39,042 | def _handle_blacklist(blacklist, dirnames, filenames):
for norecurs in blacklist:
if (norecurs in dirnames):
dirnames.remove(norecurs)
elif (norecurs in filenames):
filenames.remove(norecurs)
| [
"def",
"_handle_blacklist",
"(",
"blacklist",
",",
"dirnames",
",",
"filenames",
")",
":",
"for",
"norecurs",
"in",
"blacklist",
":",
"if",
"(",
"norecurs",
"in",
"dirnames",
")",
":",
"dirnames",
".",
"remove",
"(",
"norecurs",
")",
"elif",
"(",
"norecurs",
"in",
"filenames",
")",
":",
"filenames",
".",
"remove",
"(",
"norecurs",
")"
] | remove files/directories in the black list dirnames/filenames are usually from os . | train | true |
39,043 | def tslash(apath):
if (apath and (apath != '.') and (not apath.endswith('/')) and (not apath.endswith('\\'))):
return (apath + '/')
else:
return apath
| [
"def",
"tslash",
"(",
"apath",
")",
":",
"if",
"(",
"apath",
"and",
"(",
"apath",
"!=",
"'.'",
")",
"and",
"(",
"not",
"apath",
".",
"endswith",
"(",
"'/'",
")",
")",
"and",
"(",
"not",
"apath",
".",
"endswith",
"(",
"'\\\\'",
")",
")",
")",
":",
"return",
"(",
"apath",
"+",
"'/'",
")",
"else",
":",
"return",
"apath"
] | add a trailing slash to a path if it needs one . | train | false |
39,044 | def p_relational_expression_4(t):
pass
| [
"def",
"p_relational_expression_4",
"(",
"t",
")",
":",
"pass"
] | relational_expression : relational_expression le shift_expression . | train | false |
39,045 | def update_local_plugin_descriptor(plugins):
structure = []
if os.path.isfile(resources.PLUGINS_DESCRIPTOR):
structure = json_manager.read_json(resources.PLUGINS_DESCRIPTOR)
for plug_list in plugins:
plug = {}
plug[u'name'] = plug_list[0]
plug[u'version'] = plug_list[1]
plug[u'description'] = plug_list[2]
plug[u'authors'] = plug_list[3]
plug[u'home'] = plug_list[4]
plug[u'download'] = plug_list[5]
plug[u'plugin-descriptor'] = plug_list[6]
structure.append(plug)
json_manager.write_json(structure, resources.PLUGINS_DESCRIPTOR)
| [
"def",
"update_local_plugin_descriptor",
"(",
"plugins",
")",
":",
"structure",
"=",
"[",
"]",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"resources",
".",
"PLUGINS_DESCRIPTOR",
")",
":",
"structure",
"=",
"json_manager",
".",
"read_json",
"(",
"resources",
".",
"PLUGINS_DESCRIPTOR",
")",
"for",
"plug_list",
"in",
"plugins",
":",
"plug",
"=",
"{",
"}",
"plug",
"[",
"u'name'",
"]",
"=",
"plug_list",
"[",
"0",
"]",
"plug",
"[",
"u'version'",
"]",
"=",
"plug_list",
"[",
"1",
"]",
"plug",
"[",
"u'description'",
"]",
"=",
"plug_list",
"[",
"2",
"]",
"plug",
"[",
"u'authors'",
"]",
"=",
"plug_list",
"[",
"3",
"]",
"plug",
"[",
"u'home'",
"]",
"=",
"plug_list",
"[",
"4",
"]",
"plug",
"[",
"u'download'",
"]",
"=",
"plug_list",
"[",
"5",
"]",
"plug",
"[",
"u'plugin-descriptor'",
"]",
"=",
"plug_list",
"[",
"6",
"]",
"structure",
".",
"append",
"(",
"plug",
")",
"json_manager",
".",
"write_json",
"(",
"structure",
",",
"resources",
".",
"PLUGINS_DESCRIPTOR",
")"
] | updates the local plugin description the description . | train | false |
39,046 | def _onenormest_m1_power(A, p, t=2, itmax=5, compute_v=False, compute_w=False):
return onenormest(_MatrixM1PowerOperator(A, p), t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w)
| [
"def",
"_onenormest_m1_power",
"(",
"A",
",",
"p",
",",
"t",
"=",
"2",
",",
"itmax",
"=",
"5",
",",
"compute_v",
"=",
"False",
",",
"compute_w",
"=",
"False",
")",
":",
"return",
"onenormest",
"(",
"_MatrixM1PowerOperator",
"(",
"A",
",",
"p",
")",
",",
"t",
"=",
"t",
",",
"itmax",
"=",
"itmax",
",",
"compute_v",
"=",
"compute_v",
",",
"compute_w",
"=",
"compute_w",
")"
] | efficiently estimate the 1-norm of ^p . | train | false |
39,048 | def _GetUnifiedDiff(before, after, filename='code'):
before = before.splitlines()
after = after.splitlines()
return ('\n'.join(difflib.unified_diff(before, after, filename, filename, '(original)', '(reformatted)', lineterm='')) + '\n')
| [
"def",
"_GetUnifiedDiff",
"(",
"before",
",",
"after",
",",
"filename",
"=",
"'code'",
")",
":",
"before",
"=",
"before",
".",
"splitlines",
"(",
")",
"after",
"=",
"after",
".",
"splitlines",
"(",
")",
"return",
"(",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"unified_diff",
"(",
"before",
",",
"after",
",",
"filename",
",",
"filename",
",",
"'(original)'",
",",
"'(reformatted)'",
",",
"lineterm",
"=",
"''",
")",
")",
"+",
"'\\n'",
")"
] | get a unified diff of the changes . | train | false |
39,053 | def test_scharr_v_horizontal():
(i, j) = np.mgrid[(-5):6, (-5):6]
image = (i >= 0).astype(float)
result = filters.scharr_v(image)
assert_allclose(result, 0)
| [
"def",
"test_scharr_v_horizontal",
"(",
")",
":",
"(",
"i",
",",
"j",
")",
"=",
"np",
".",
"mgrid",
"[",
"(",
"-",
"5",
")",
":",
"6",
",",
"(",
"-",
"5",
")",
":",
"6",
"]",
"image",
"=",
"(",
"i",
">=",
"0",
")",
".",
"astype",
"(",
"float",
")",
"result",
"=",
"filters",
".",
"scharr_v",
"(",
"image",
")",
"assert_allclose",
"(",
"result",
",",
"0",
")"
] | vertical scharr on a horizontal edge should be zero . | train | false |
39,054 | @contextfunction
def events_event_list(context, events):
request = context['request']
response_format = 'html'
if ('response_format' in context):
response_format = context['response_format']
return Markup(render_to_string('events/tags/event_list', {'events': events}, context_instance=RequestContext(request), response_format=response_format))
| [
"@",
"contextfunction",
"def",
"events_event_list",
"(",
"context",
",",
"events",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"response_format",
"=",
"'html'",
"if",
"(",
"'response_format'",
"in",
"context",
")",
":",
"response_format",
"=",
"context",
"[",
"'response_format'",
"]",
"return",
"Markup",
"(",
"render_to_string",
"(",
"'events/tags/event_list'",
",",
"{",
"'events'",
":",
"events",
"}",
",",
"context_instance",
"=",
"RequestContext",
"(",
"request",
")",
",",
"response_format",
"=",
"response_format",
")",
")"
] | print a list of events . | train | false |
39,055 | def rapply(data, func, *args, **kwargs):
if isinstance(data, collections.Mapping):
return {key: rapply(value, func, *args, **kwargs) for (key, value) in data.iteritems()}
elif (isinstance(data, collections.Iterable) and (not isinstance(data, basestring))):
desired_type = type(data)
return desired_type((rapply(item, func, *args, **kwargs) for item in data))
else:
return func(data, *args, **kwargs)
| [
"def",
"rapply",
"(",
"data",
",",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"collections",
".",
"Mapping",
")",
":",
"return",
"{",
"key",
":",
"rapply",
"(",
"value",
",",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"data",
".",
"iteritems",
"(",
")",
"}",
"elif",
"(",
"isinstance",
"(",
"data",
",",
"collections",
".",
"Iterable",
")",
"and",
"(",
"not",
"isinstance",
"(",
"data",
",",
"basestring",
")",
")",
")",
":",
"desired_type",
"=",
"type",
"(",
"data",
")",
"return",
"desired_type",
"(",
"(",
"rapply",
"(",
"item",
",",
"func",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"for",
"item",
"in",
"data",
")",
")",
"else",
":",
"return",
"func",
"(",
"data",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | recursively apply a function to all values in an iterable . | train | false |
39,056 | def requires_mac_ver(*min_version):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
if (sys.platform == 'darwin'):
version_txt = platform.mac_ver()[0]
try:
version = tuple(map(int, version_txt.split('.')))
except ValueError:
pass
else:
if (version < min_version):
min_version_txt = '.'.join(map(str, min_version))
raise unittest.SkipTest(('Mac OS X %s or higher required, not %s' % (min_version_txt, version_txt)))
return func(*args, **kw)
wrapper.min_version = min_version
return wrapper
return decorator
| [
"def",
"requires_mac_ver",
"(",
"*",
"min_version",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kw",
")",
":",
"if",
"(",
"sys",
".",
"platform",
"==",
"'darwin'",
")",
":",
"version_txt",
"=",
"platform",
".",
"mac_ver",
"(",
")",
"[",
"0",
"]",
"try",
":",
"version",
"=",
"tuple",
"(",
"map",
"(",
"int",
",",
"version_txt",
".",
"split",
"(",
"'.'",
")",
")",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"if",
"(",
"version",
"<",
"min_version",
")",
":",
"min_version_txt",
"=",
"'.'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"min_version",
")",
")",
"raise",
"unittest",
".",
"SkipTest",
"(",
"(",
"'Mac OS X %s or higher required, not %s'",
"%",
"(",
"min_version_txt",
",",
"version_txt",
")",
")",
")",
"return",
"func",
"(",
"*",
"args",
",",
"**",
"kw",
")",
"wrapper",
".",
"min_version",
"=",
"min_version",
"return",
"wrapper",
"return",
"decorator"
] | decorator raising skiptest if the os is mac os x and the os x version if less than min_version . | train | false |
39,057 | def _character_name(code):
return unicode_data.name(unichr(code), '<Unassigned>')
| [
"def",
"_character_name",
"(",
"code",
")",
":",
"return",
"unicode_data",
".",
"name",
"(",
"unichr",
"(",
"code",
")",
",",
"'<Unassigned>'",
")"
] | returns the printable name of a character . | train | false |
39,059 | @receiver(pre_delete, sender=Repository, dispatch_uid=u'repository_delete_reset_review_counts')
def repository_delete_reset_review_counts(sender, instance, using, **kwargs):
fix_review_counts()
| [
"@",
"receiver",
"(",
"pre_delete",
",",
"sender",
"=",
"Repository",
",",
"dispatch_uid",
"=",
"u'repository_delete_reset_review_counts'",
")",
"def",
"repository_delete_reset_review_counts",
"(",
"sender",
",",
"instance",
",",
"using",
",",
"**",
"kwargs",
")",
":",
"fix_review_counts",
"(",
")"
] | reset review counts in the dashboard when deleting repository objects . | train | false |
39,062 | def _get_buildout_scripts(module_path):
project_root = _get_parent_dir_with_file(module_path, 'buildout.cfg')
if (not project_root):
return []
bin_path = os.path.join(project_root, 'bin')
if (not os.path.exists(bin_path)):
return []
extra_module_paths = []
for filename in os.listdir(bin_path):
try:
filepath = os.path.join(bin_path, filename)
with open(filepath, 'r') as f:
firstline = f.readline()
if (firstline.startswith('#!') and ('python' in firstline)):
extra_module_paths.append(filepath)
except (UnicodeDecodeError, IOError) as e:
debug.warning(unicode(e))
continue
return extra_module_paths
| [
"def",
"_get_buildout_scripts",
"(",
"module_path",
")",
":",
"project_root",
"=",
"_get_parent_dir_with_file",
"(",
"module_path",
",",
"'buildout.cfg'",
")",
"if",
"(",
"not",
"project_root",
")",
":",
"return",
"[",
"]",
"bin_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"project_root",
",",
"'bin'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"bin_path",
")",
")",
":",
"return",
"[",
"]",
"extra_module_paths",
"=",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"bin_path",
")",
":",
"try",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"bin_path",
",",
"filename",
")",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"firstline",
"=",
"f",
".",
"readline",
"(",
")",
"if",
"(",
"firstline",
".",
"startswith",
"(",
"'#!'",
")",
"and",
"(",
"'python'",
"in",
"firstline",
")",
")",
":",
"extra_module_paths",
".",
"append",
"(",
"filepath",
")",
"except",
"(",
"UnicodeDecodeError",
",",
"IOError",
")",
"as",
"e",
":",
"debug",
".",
"warning",
"(",
"unicode",
"(",
"e",
")",
")",
"continue",
"return",
"extra_module_paths"
] | if there is a buildout . | train | false |
39,063 | def test_numberpattern_repr():
format = u'\xa4#,##0.00;(\xa4#,##0.00)'
np = numbers.parse_pattern(format)
assert (repr(format) in repr(np))
| [
"def",
"test_numberpattern_repr",
"(",
")",
":",
"format",
"=",
"u'\\xa4#,##0.00;(\\xa4#,##0.00)'",
"np",
"=",
"numbers",
".",
"parse_pattern",
"(",
"format",
")",
"assert",
"(",
"repr",
"(",
"format",
")",
"in",
"repr",
"(",
"np",
")",
")"
] | repr() outputs the pattern string . | train | false |
39,064 | def find_library(name, cached=True, internal=True):
if (not cached):
return cdll.LoadLibrary(_so_mapping[name])
if internal:
if (name not in _internal):
_internal[name] = cdll.LoadLibrary(_so_mapping[name])
return _internal[name]
return getattr(cdll, _so_mapping[name])
| [
"def",
"find_library",
"(",
"name",
",",
"cached",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"if",
"(",
"not",
"cached",
")",
":",
"return",
"cdll",
".",
"LoadLibrary",
"(",
"_so_mapping",
"[",
"name",
"]",
")",
"if",
"internal",
":",
"if",
"(",
"name",
"not",
"in",
"_internal",
")",
":",
"_internal",
"[",
"name",
"]",
"=",
"cdll",
".",
"LoadLibrary",
"(",
"_so_mapping",
"[",
"name",
"]",
")",
"return",
"_internal",
"[",
"name",
"]",
"return",
"getattr",
"(",
"cdll",
",",
"_so_mapping",
"[",
"name",
"]",
")"
] | cached: return a new instance internal: return a shared instance thats not the ctypes cached one . | train | true |
39,066 | def make_back_table(table, default_stop_codon):
back_table = {}
for key in sorted(table):
back_table[table[key]] = key
back_table[None] = default_stop_codon
return back_table
| [
"def",
"make_back_table",
"(",
"table",
",",
"default_stop_codon",
")",
":",
"back_table",
"=",
"{",
"}",
"for",
"key",
"in",
"sorted",
"(",
"table",
")",
":",
"back_table",
"[",
"table",
"[",
"key",
"]",
"]",
"=",
"key",
"back_table",
"[",
"None",
"]",
"=",
"default_stop_codon",
"return",
"back_table"
] | back a back-table . | train | false |
39,067 | def survey_buildQuestionnaireFromSeries(series_id, complete_id=None):
questions = survey_getAllQuestionsForSeries(series_id)
return buildQuestionsForm(questions, complete_id)
| [
"def",
"survey_buildQuestionnaireFromSeries",
"(",
"series_id",
",",
"complete_id",
"=",
"None",
")",
":",
"questions",
"=",
"survey_getAllQuestionsForSeries",
"(",
"series_id",
")",
"return",
"buildQuestionsForm",
"(",
"questions",
",",
"complete_id",
")"
] | build a form displaying all the questions for a given series_id if the complete_id is also provided then the responses to each completed question will also be displayed @todo: remove wrapper . | train | false |
39,069 | @keras_test
def test_temporal_regression():
((X_train, y_train), (X_test, y_test)) = get_test_data(nb_train=500, nb_test=400, input_shape=(3, 5), output_shape=(2,), classification=False)
model = Sequential()
model.add(GRU(y_train.shape[(-1)], input_shape=(X_train.shape[1], X_train.shape[2])))
model.compile(loss='hinge', optimizer='adam')
history = model.fit(X_train, y_train, nb_epoch=5, batch_size=16, validation_data=(X_test, y_test), verbose=0)
assert (history.history['val_loss'][(-1)] < 1.0)
| [
"@",
"keras_test",
"def",
"test_temporal_regression",
"(",
")",
":",
"(",
"(",
"X_train",
",",
"y_train",
")",
",",
"(",
"X_test",
",",
"y_test",
")",
")",
"=",
"get_test_data",
"(",
"nb_train",
"=",
"500",
",",
"nb_test",
"=",
"400",
",",
"input_shape",
"=",
"(",
"3",
",",
"5",
")",
",",
"output_shape",
"=",
"(",
"2",
",",
")",
",",
"classification",
"=",
"False",
")",
"model",
"=",
"Sequential",
"(",
")",
"model",
".",
"add",
"(",
"GRU",
"(",
"y_train",
".",
"shape",
"[",
"(",
"-",
"1",
")",
"]",
",",
"input_shape",
"=",
"(",
"X_train",
".",
"shape",
"[",
"1",
"]",
",",
"X_train",
".",
"shape",
"[",
"2",
"]",
")",
")",
")",
"model",
".",
"compile",
"(",
"loss",
"=",
"'hinge'",
",",
"optimizer",
"=",
"'adam'",
")",
"history",
"=",
"model",
".",
"fit",
"(",
"X_train",
",",
"y_train",
",",
"nb_epoch",
"=",
"5",
",",
"batch_size",
"=",
"16",
",",
"validation_data",
"=",
"(",
"X_test",
",",
"y_test",
")",
",",
"verbose",
"=",
"0",
")",
"assert",
"(",
"history",
".",
"history",
"[",
"'val_loss'",
"]",
"[",
"(",
"-",
"1",
")",
"]",
"<",
"1.0",
")"
] | predict float numbers based on sequences of float numbers of length 3 using a single layer of gru units . | train | false |
39,070 | def rowmul(matlist, index, k, K):
for i in range(len(matlist[index])):
matlist[index][i] = (k * matlist[index][i])
return matlist
| [
"def",
"rowmul",
"(",
"matlist",
",",
"index",
",",
"k",
",",
"K",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"matlist",
"[",
"index",
"]",
")",
")",
":",
"matlist",
"[",
"index",
"]",
"[",
"i",
"]",
"=",
"(",
"k",
"*",
"matlist",
"[",
"index",
"]",
"[",
"i",
"]",
")",
"return",
"matlist"
] | multiplies index row with k . | train | false |
39,072 | def getComplexByMultiplierPrefixes(multiplier, prefixes, valueComplex, xmlElement):
for prefix in prefixes:
valueComplex = getComplexByMultiplierPrefix(multiplier, prefix, valueComplex, xmlElement)
return valueComplex
| [
"def",
"getComplexByMultiplierPrefixes",
"(",
"multiplier",
",",
"prefixes",
",",
"valueComplex",
",",
"xmlElement",
")",
":",
"for",
"prefix",
"in",
"prefixes",
":",
"valueComplex",
"=",
"getComplexByMultiplierPrefix",
"(",
"multiplier",
",",
"prefix",
",",
"valueComplex",
",",
"xmlElement",
")",
"return",
"valueComplex"
] | get complex from multiplier . | train | false |
39,073 | def _stroke_and_fill_colors(color, border):
if (not isinstance(color, colors.Color)):
raise ValueError(('Invalid color %r' % color))
if ((color == colors.white) and (border is None)):
strokecolor = colors.black
elif (border is None):
strokecolor = color
elif border:
if (not isinstance(border, colors.Color)):
raise ValueError(('Invalid border color %r' % border))
strokecolor = border
else:
strokecolor = None
return (strokecolor, color)
| [
"def",
"_stroke_and_fill_colors",
"(",
"color",
",",
"border",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"color",
",",
"colors",
".",
"Color",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid color %r'",
"%",
"color",
")",
")",
"if",
"(",
"(",
"color",
"==",
"colors",
".",
"white",
")",
"and",
"(",
"border",
"is",
"None",
")",
")",
":",
"strokecolor",
"=",
"colors",
".",
"black",
"elif",
"(",
"border",
"is",
"None",
")",
":",
"strokecolor",
"=",
"color",
"elif",
"border",
":",
"if",
"(",
"not",
"isinstance",
"(",
"border",
",",
"colors",
".",
"Color",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"'Invalid border color %r'",
"%",
"border",
")",
")",
"strokecolor",
"=",
"border",
"else",
":",
"strokecolor",
"=",
"None",
"return",
"(",
"strokecolor",
",",
"color",
")"
] | helper function handle border and fill colors . | train | false |
39,075 | def get_numeric_types(with_int=True, with_float=True, with_complex=False, only_theano_types=True):
if only_theano_types:
theano_types = [d.dtype for d in theano.scalar.all_types]
rval = []
def is_within(cls1, cls2):
return ((cls1 is cls2) or issubclass(cls1, cls2) or isinstance(numpy.array([0], dtype=cls1)[0], cls2))
for cls in get_numeric_subclasses():
dtype = numpy.dtype(cls)
if (((not with_complex) and is_within(cls, numpy.complexfloating)) or ((not with_int) and is_within(cls, numpy.integer)) or ((not with_float) and is_within(cls, numpy.floating)) or (only_theano_types and (dtype not in theano_types))):
continue
rval.append([str(dtype), dtype, dtype.num])
return [x[1] for x in sorted(rval, key=str)]
| [
"def",
"get_numeric_types",
"(",
"with_int",
"=",
"True",
",",
"with_float",
"=",
"True",
",",
"with_complex",
"=",
"False",
",",
"only_theano_types",
"=",
"True",
")",
":",
"if",
"only_theano_types",
":",
"theano_types",
"=",
"[",
"d",
".",
"dtype",
"for",
"d",
"in",
"theano",
".",
"scalar",
".",
"all_types",
"]",
"rval",
"=",
"[",
"]",
"def",
"is_within",
"(",
"cls1",
",",
"cls2",
")",
":",
"return",
"(",
"(",
"cls1",
"is",
"cls2",
")",
"or",
"issubclass",
"(",
"cls1",
",",
"cls2",
")",
"or",
"isinstance",
"(",
"numpy",
".",
"array",
"(",
"[",
"0",
"]",
",",
"dtype",
"=",
"cls1",
")",
"[",
"0",
"]",
",",
"cls2",
")",
")",
"for",
"cls",
"in",
"get_numeric_subclasses",
"(",
")",
":",
"dtype",
"=",
"numpy",
".",
"dtype",
"(",
"cls",
")",
"if",
"(",
"(",
"(",
"not",
"with_complex",
")",
"and",
"is_within",
"(",
"cls",
",",
"numpy",
".",
"complexfloating",
")",
")",
"or",
"(",
"(",
"not",
"with_int",
")",
"and",
"is_within",
"(",
"cls",
",",
"numpy",
".",
"integer",
")",
")",
"or",
"(",
"(",
"not",
"with_float",
")",
"and",
"is_within",
"(",
"cls",
",",
"numpy",
".",
"floating",
")",
")",
"or",
"(",
"only_theano_types",
"and",
"(",
"dtype",
"not",
"in",
"theano_types",
")",
")",
")",
":",
"continue",
"rval",
".",
"append",
"(",
"[",
"str",
"(",
"dtype",
")",
",",
"dtype",
",",
"dtype",
".",
"num",
"]",
")",
"return",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"sorted",
"(",
"rval",
",",
"key",
"=",
"str",
")",
"]"
] | return numpy numeric data types . | train | false |
39,076 | def consume_task(task, services=None):
if (services is None):
services = {}
logger.info((u'Consuming %r' % task))
result = None
if isinstance(task, ListTask):
service = get_service(services, task.service, config=task.config)
result = service.list(task.video, task.languages)
elif isinstance(task, DownloadTask):
for subtitle in task.subtitles:
service = get_service(services, subtitle.service)
try:
service.download(subtitle)
result = [subtitle]
break
except DownloadFailedError:
logger.warning((u'Could not download subtitle %r, trying next' % subtitle))
continue
if (result is None):
logger.error((u'No subtitles could be downloaded for video %r' % task.video))
return result
| [
"def",
"consume_task",
"(",
"task",
",",
"services",
"=",
"None",
")",
":",
"if",
"(",
"services",
"is",
"None",
")",
":",
"services",
"=",
"{",
"}",
"logger",
".",
"info",
"(",
"(",
"u'Consuming %r'",
"%",
"task",
")",
")",
"result",
"=",
"None",
"if",
"isinstance",
"(",
"task",
",",
"ListTask",
")",
":",
"service",
"=",
"get_service",
"(",
"services",
",",
"task",
".",
"service",
",",
"config",
"=",
"task",
".",
"config",
")",
"result",
"=",
"service",
".",
"list",
"(",
"task",
".",
"video",
",",
"task",
".",
"languages",
")",
"elif",
"isinstance",
"(",
"task",
",",
"DownloadTask",
")",
":",
"for",
"subtitle",
"in",
"task",
".",
"subtitles",
":",
"service",
"=",
"get_service",
"(",
"services",
",",
"subtitle",
".",
"service",
")",
"try",
":",
"service",
".",
"download",
"(",
"subtitle",
")",
"result",
"=",
"[",
"subtitle",
"]",
"break",
"except",
"DownloadFailedError",
":",
"logger",
".",
"warning",
"(",
"(",
"u'Could not download subtitle %r, trying next'",
"%",
"subtitle",
")",
")",
"continue",
"if",
"(",
"result",
"is",
"None",
")",
":",
"logger",
".",
"error",
"(",
"(",
"u'No subtitles could be downloaded for video %r'",
"%",
"task",
".",
"video",
")",
")",
"return",
"result"
] | consume a task . | train | false |
39,078 | @celery.task(base=RequestContextTask, name='import.event', bind=True, throws=(BaseError,))
def import_event_task(self, file, source_type, creator_id):
task_id = self.request.id.__str__()
try:
result = import_event_task_base(self, file, source_type, creator_id)
update_import_job(task_id, result['id'], 'SUCCESS')
except BaseError as e:
print(traceback.format_exc())
update_import_job(task_id, e.message, (e.status if hasattr(e, 'status') else 'failure'))
result = {'__error': True, 'result': e.to_dict()}
except Exception as e:
print(traceback.format_exc())
update_import_job(task_id, e.message, (e.status if hasattr(e, 'status') else 'failure'))
result = {'__error': True, 'result': ServerError().to_dict()}
send_import_mail(task_id, result)
return result
| [
"@",
"celery",
".",
"task",
"(",
"base",
"=",
"RequestContextTask",
",",
"name",
"=",
"'import.event'",
",",
"bind",
"=",
"True",
",",
"throws",
"=",
"(",
"BaseError",
",",
")",
")",
"def",
"import_event_task",
"(",
"self",
",",
"file",
",",
"source_type",
",",
"creator_id",
")",
":",
"task_id",
"=",
"self",
".",
"request",
".",
"id",
".",
"__str__",
"(",
")",
"try",
":",
"result",
"=",
"import_event_task_base",
"(",
"self",
",",
"file",
",",
"source_type",
",",
"creator_id",
")",
"update_import_job",
"(",
"task_id",
",",
"result",
"[",
"'id'",
"]",
",",
"'SUCCESS'",
")",
"except",
"BaseError",
"as",
"e",
":",
"print",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"update_import_job",
"(",
"task_id",
",",
"e",
".",
"message",
",",
"(",
"e",
".",
"status",
"if",
"hasattr",
"(",
"e",
",",
"'status'",
")",
"else",
"'failure'",
")",
")",
"result",
"=",
"{",
"'__error'",
":",
"True",
",",
"'result'",
":",
"e",
".",
"to_dict",
"(",
")",
"}",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"update_import_job",
"(",
"task_id",
",",
"e",
".",
"message",
",",
"(",
"e",
".",
"status",
"if",
"hasattr",
"(",
"e",
",",
"'status'",
")",
"else",
"'failure'",
")",
")",
"result",
"=",
"{",
"'__error'",
":",
"True",
",",
"'result'",
":",
"ServerError",
"(",
")",
".",
"to_dict",
"(",
")",
"}",
"send_import_mail",
"(",
"task_id",
",",
"result",
")",
"return",
"result"
] | import event task . | train | false |
39,081 | def test_roc_auc_one_vs_rest():
skip_if_no_sklearn()
trainer = yaml_parse.load(test_yaml_ovr)
trainer.main_loop()
| [
"def",
"test_roc_auc_one_vs_rest",
"(",
")",
":",
"skip_if_no_sklearn",
"(",
")",
"trainer",
"=",
"yaml_parse",
".",
"load",
"(",
"test_yaml_ovr",
")",
"trainer",
".",
"main_loop",
"(",
")"
] | test one vs . | train | false |
39,082 | def format_fastq_record(label, seq, qual):
return ('@%s\n%s\n+\n%s\n' % (label, seq, qual))
| [
"def",
"format_fastq_record",
"(",
"label",
",",
"seq",
",",
"qual",
")",
":",
"return",
"(",
"'@%s\\n%s\\n+\\n%s\\n'",
"%",
"(",
"label",
",",
"seq",
",",
"qual",
")",
")"
] | formats a line of fastq data to be written label: fastq label seq: nucleotide sequence qual: quality scores . | train | false |
39,083 | def _get_own_device():
from ..devices.models import Device
return Device.get_own_device()
| [
"def",
"_get_own_device",
"(",
")",
":",
"from",
".",
".",
"devices",
".",
"models",
"import",
"Device",
"return",
"Device",
".",
"get_own_device",
"(",
")"
] | to allow imports to resolve . | train | false |
39,084 | def _verify_options(options):
bitwise_args = [('level', options['level']), ('facility', options['facility'])]
bitwise_args.extend([('option', x) for x in options['options']])
for (opt_name, opt) in bitwise_args:
if (not hasattr(syslog, opt)):
log.error('syslog has no attribute {0}'.format(opt))
return False
if (not isinstance(getattr(syslog, opt), int)):
log.error('{0} is not a valid syslog {1}'.format(opt, opt_name))
return False
if ('tag' in options):
if (not isinstance(options['tag'], six.string_types)):
log.error('tag must be a string')
return False
if (len(options['tag']) > 32):
log.error('tag size is limited to 32 characters')
return False
return True
| [
"def",
"_verify_options",
"(",
"options",
")",
":",
"bitwise_args",
"=",
"[",
"(",
"'level'",
",",
"options",
"[",
"'level'",
"]",
")",
",",
"(",
"'facility'",
",",
"options",
"[",
"'facility'",
"]",
")",
"]",
"bitwise_args",
".",
"extend",
"(",
"[",
"(",
"'option'",
",",
"x",
")",
"for",
"x",
"in",
"options",
"[",
"'options'",
"]",
"]",
")",
"for",
"(",
"opt_name",
",",
"opt",
")",
"in",
"bitwise_args",
":",
"if",
"(",
"not",
"hasattr",
"(",
"syslog",
",",
"opt",
")",
")",
":",
"log",
".",
"error",
"(",
"'syslog has no attribute {0}'",
".",
"format",
"(",
"opt",
")",
")",
"return",
"False",
"if",
"(",
"not",
"isinstance",
"(",
"getattr",
"(",
"syslog",
",",
"opt",
")",
",",
"int",
")",
")",
":",
"log",
".",
"error",
"(",
"'{0} is not a valid syslog {1}'",
".",
"format",
"(",
"opt",
",",
"opt_name",
")",
")",
"return",
"False",
"if",
"(",
"'tag'",
"in",
"options",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"options",
"[",
"'tag'",
"]",
",",
"six",
".",
"string_types",
")",
")",
":",
"log",
".",
"error",
"(",
"'tag must be a string'",
")",
"return",
"False",
"if",
"(",
"len",
"(",
"options",
"[",
"'tag'",
"]",
")",
">",
"32",
")",
":",
"log",
".",
"error",
"(",
"'tag size is limited to 32 characters'",
")",
"return",
"False",
"return",
"True"
] | verify options and log warnings returns true if all options can be verified . | train | true |
39,085 | def get_score_funcs():
from scipy import stats
from scipy.spatial import distance
score_funcs = Bunch()
xy_arg_dist_funcs = [(n, f) for (n, f) in vars(distance).items() if (isfunction(f) and (not n.startswith('_')))]
xy_arg_stats_funcs = [(n, f) for (n, f) in vars(stats).items() if (isfunction(f) and (not n.startswith('_')))]
score_funcs.update(dict(((n, _make_xy_sfunc(f)) for (n, f) in xy_arg_dist_funcs if (_get_args(f) == ['u', 'v']))))
score_funcs.update(dict(((n, _make_xy_sfunc(f, ndim_output=True)) for (n, f) in xy_arg_stats_funcs if (_get_args(f) == ['x', 'y']))))
return score_funcs
| [
"def",
"get_score_funcs",
"(",
")",
":",
"from",
"scipy",
"import",
"stats",
"from",
"scipy",
".",
"spatial",
"import",
"distance",
"score_funcs",
"=",
"Bunch",
"(",
")",
"xy_arg_dist_funcs",
"=",
"[",
"(",
"n",
",",
"f",
")",
"for",
"(",
"n",
",",
"f",
")",
"in",
"vars",
"(",
"distance",
")",
".",
"items",
"(",
")",
"if",
"(",
"isfunction",
"(",
"f",
")",
"and",
"(",
"not",
"n",
".",
"startswith",
"(",
"'_'",
")",
")",
")",
"]",
"xy_arg_stats_funcs",
"=",
"[",
"(",
"n",
",",
"f",
")",
"for",
"(",
"n",
",",
"f",
")",
"in",
"vars",
"(",
"stats",
")",
".",
"items",
"(",
")",
"if",
"(",
"isfunction",
"(",
"f",
")",
"and",
"(",
"not",
"n",
".",
"startswith",
"(",
"'_'",
")",
")",
")",
"]",
"score_funcs",
".",
"update",
"(",
"dict",
"(",
"(",
"(",
"n",
",",
"_make_xy_sfunc",
"(",
"f",
")",
")",
"for",
"(",
"n",
",",
"f",
")",
"in",
"xy_arg_dist_funcs",
"if",
"(",
"_get_args",
"(",
"f",
")",
"==",
"[",
"'u'",
",",
"'v'",
"]",
")",
")",
")",
")",
"score_funcs",
".",
"update",
"(",
"dict",
"(",
"(",
"(",
"n",
",",
"_make_xy_sfunc",
"(",
"f",
",",
"ndim_output",
"=",
"True",
")",
")",
"for",
"(",
"n",
",",
"f",
")",
"in",
"xy_arg_stats_funcs",
"if",
"(",
"_get_args",
"(",
"f",
")",
"==",
"[",
"'x'",
",",
"'y'",
"]",
")",
")",
")",
")",
"return",
"score_funcs"
] | get the score functions . | train | false |
39,086 | def make_gzip_middleware(app, global_conf, compress_level=6):
compress_level = int(compress_level)
return middleware(app, compress_level=compress_level)
| [
"def",
"make_gzip_middleware",
"(",
"app",
",",
"global_conf",
",",
"compress_level",
"=",
"6",
")",
":",
"compress_level",
"=",
"int",
"(",
"compress_level",
")",
"return",
"middleware",
"(",
"app",
",",
"compress_level",
"=",
"compress_level",
")"
] | return a gzip-compressing middleware . | train | false |
39,087 | def add_wsgi_intercept(host, port, app_create_fn, script_name=''):
_wsgi_intercept[(host, port)] = (app_create_fn, script_name)
| [
"def",
"add_wsgi_intercept",
"(",
"host",
",",
"port",
",",
"app_create_fn",
",",
"script_name",
"=",
"''",
")",
":",
"_wsgi_intercept",
"[",
"(",
"host",
",",
"port",
")",
"]",
"=",
"(",
"app_create_fn",
",",
"script_name",
")"
] | add a wsgi intercept call for host:port . | train | false |
39,088 | def chroomnumber(name, roomnumber):
return _update_gecos(name, 'roomnumber', roomnumber)
| [
"def",
"chroomnumber",
"(",
"name",
",",
"roomnumber",
")",
":",
"return",
"_update_gecos",
"(",
"name",
",",
"'roomnumber'",
",",
"roomnumber",
")"
] | change the users room number cli example: . | train | false |
39,089 | @contextmanager
def assert_produces_warning(expected_warning=Warning, filter_level=u'always', clear=None):
with warnings.catch_warnings(record=True) as w:
if (clear is not None):
if (not _is_list_like(clear)):
clear = [clear]
for m in clear:
getattr(m, u'__warningregistry__', {}).clear()
saw_warning = False
warnings.simplefilter(filter_level)
(yield w)
extra_warnings = []
for actual_warning in w:
if (expected_warning and issubclass(actual_warning.category, expected_warning)):
saw_warning = True
else:
extra_warnings.append(actual_warning.category.__name__)
if expected_warning:
assert saw_warning, (u'Did not see expected warning of class %r.' % expected_warning.__name__)
assert (not extra_warnings), (u'Caused unexpected warning(s): %r.' % extra_warnings)
| [
"@",
"contextmanager",
"def",
"assert_produces_warning",
"(",
"expected_warning",
"=",
"Warning",
",",
"filter_level",
"=",
"u'always'",
",",
"clear",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
"as",
"w",
":",
"if",
"(",
"clear",
"is",
"not",
"None",
")",
":",
"if",
"(",
"not",
"_is_list_like",
"(",
"clear",
")",
")",
":",
"clear",
"=",
"[",
"clear",
"]",
"for",
"m",
"in",
"clear",
":",
"getattr",
"(",
"m",
",",
"u'__warningregistry__'",
",",
"{",
"}",
")",
".",
"clear",
"(",
")",
"saw_warning",
"=",
"False",
"warnings",
".",
"simplefilter",
"(",
"filter_level",
")",
"(",
"yield",
"w",
")",
"extra_warnings",
"=",
"[",
"]",
"for",
"actual_warning",
"in",
"w",
":",
"if",
"(",
"expected_warning",
"and",
"issubclass",
"(",
"actual_warning",
".",
"category",
",",
"expected_warning",
")",
")",
":",
"saw_warning",
"=",
"True",
"else",
":",
"extra_warnings",
".",
"append",
"(",
"actual_warning",
".",
"category",
".",
"__name__",
")",
"if",
"expected_warning",
":",
"assert",
"saw_warning",
",",
"(",
"u'Did not see expected warning of class %r.'",
"%",
"expected_warning",
".",
"__name__",
")",
"assert",
"(",
"not",
"extra_warnings",
")",
",",
"(",
"u'Caused unexpected warning(s): %r.'",
"%",
"extra_warnings",
")"
] | context manager for running code that expects to raise warnings . | train | false |
39,092 | def update_thread(request, thread_id, update_data):
(cc_thread, context) = _get_thread_and_context(request, thread_id, retrieve_kwargs={'with_responses': True})
_check_editable_fields(cc_thread, update_data, context)
serializer = ThreadSerializer(cc_thread, data=update_data, partial=True, context=context)
actions_form = ThreadActionsForm(update_data)
if (not (serializer.is_valid() and actions_form.is_valid())):
raise ValidationError(dict((serializer.errors.items() + actions_form.errors.items())))
if (set(update_data) - set(actions_form.fields)):
serializer.save()
thread_edited.send(sender=None, user=request.user, post=cc_thread)
api_thread = serializer.data
_do_extra_actions(api_thread, cc_thread, update_data.keys(), actions_form, context, request)
api_thread['read'] = True
api_thread['unread_comment_count'] = 0
return api_thread
| [
"def",
"update_thread",
"(",
"request",
",",
"thread_id",
",",
"update_data",
")",
":",
"(",
"cc_thread",
",",
"context",
")",
"=",
"_get_thread_and_context",
"(",
"request",
",",
"thread_id",
",",
"retrieve_kwargs",
"=",
"{",
"'with_responses'",
":",
"True",
"}",
")",
"_check_editable_fields",
"(",
"cc_thread",
",",
"update_data",
",",
"context",
")",
"serializer",
"=",
"ThreadSerializer",
"(",
"cc_thread",
",",
"data",
"=",
"update_data",
",",
"partial",
"=",
"True",
",",
"context",
"=",
"context",
")",
"actions_form",
"=",
"ThreadActionsForm",
"(",
"update_data",
")",
"if",
"(",
"not",
"(",
"serializer",
".",
"is_valid",
"(",
")",
"and",
"actions_form",
".",
"is_valid",
"(",
")",
")",
")",
":",
"raise",
"ValidationError",
"(",
"dict",
"(",
"(",
"serializer",
".",
"errors",
".",
"items",
"(",
")",
"+",
"actions_form",
".",
"errors",
".",
"items",
"(",
")",
")",
")",
")",
"if",
"(",
"set",
"(",
"update_data",
")",
"-",
"set",
"(",
"actions_form",
".",
"fields",
")",
")",
":",
"serializer",
".",
"save",
"(",
")",
"thread_edited",
".",
"send",
"(",
"sender",
"=",
"None",
",",
"user",
"=",
"request",
".",
"user",
",",
"post",
"=",
"cc_thread",
")",
"api_thread",
"=",
"serializer",
".",
"data",
"_do_extra_actions",
"(",
"api_thread",
",",
"cc_thread",
",",
"update_data",
".",
"keys",
"(",
")",
",",
"actions_form",
",",
"context",
",",
"request",
")",
"api_thread",
"[",
"'read'",
"]",
"=",
"True",
"api_thread",
"[",
"'unread_comment_count'",
"]",
"=",
"0",
"return",
"api_thread"
] | update a thread . | train | false |
39,093 | @importorskip('PIL')
@importorskip(modname_tkinter)
@xfail(is_darwin, reason='Issue #1895. Known to fail with macpython - python.org binary.')
def test_pil_tkinter(pyi_builder):
pyi_builder.test_source('\n import PIL.Image\n\n # Statically importing the Tkinter package should succeed, implying this\n # importation successfully overrode the exclusion of this package\n # requested by "PIL" package hooks. To ensure PyInstaller parses this\n # import and freezes this package with this test, this import is static.\n try:\n import {modname_tkinter}\n except ImportError:\n raise SystemExit(\'ERROR: Module {modname_tkinter} is NOT bundled.\')\n '.format(modname_tkinter=modname_tkinter))
| [
"@",
"importorskip",
"(",
"'PIL'",
")",
"@",
"importorskip",
"(",
"modname_tkinter",
")",
"@",
"xfail",
"(",
"is_darwin",
",",
"reason",
"=",
"'Issue #1895. Known to fail with macpython - python.org binary.'",
")",
"def",
"test_pil_tkinter",
"(",
"pyi_builder",
")",
":",
"pyi_builder",
".",
"test_source",
"(",
"'\\n import PIL.Image\\n\\n # Statically importing the Tkinter package should succeed, implying this\\n # importation successfully overrode the exclusion of this package\\n # requested by \"PIL\" package hooks. To ensure PyInstaller parses this\\n # import and freezes this package with this test, this import is static.\\n try:\\n import {modname_tkinter}\\n except ImportError:\\n raise SystemExit(\\'ERROR: Module {modname_tkinter} is NOT bundled.\\')\\n '",
".",
"format",
"(",
"modname_tkinter",
"=",
"modname_tkinter",
")",
")"
] | ensure that the tkinter package excluded by pil package hooks is importable by frozen applications explicitly importing both . | train | false |
39,094 | def regions():
from boto.cloudtrail.layer1 import CloudTrailConnection
return get_regions('cloudtrail', connection_cls=CloudTrailConnection)
| [
"def",
"regions",
"(",
")",
":",
"from",
"boto",
".",
"cloudtrail",
".",
"layer1",
"import",
"CloudTrailConnection",
"return",
"get_regions",
"(",
"'cloudtrail'",
",",
"connection_cls",
"=",
"CloudTrailConnection",
")"
] | get all available regions for the amazon machine learning . | train | false |
39,096 | def _market_hmm_example():
states = [u'bull', u'bear', u'static']
symbols = [u'up', u'down', u'unchanged']
A = np.array([[0.6, 0.2, 0.2], [0.5, 0.3, 0.2], [0.4, 0.1, 0.5]], np.float64)
B = np.array([[0.7, 0.1, 0.2], [0.1, 0.6, 0.3], [0.3, 0.3, 0.4]], np.float64)
pi = np.array([0.5, 0.2, 0.3], np.float64)
model = _create_hmm_tagger(states, symbols, A, B, pi)
return (model, states, symbols)
| [
"def",
"_market_hmm_example",
"(",
")",
":",
"states",
"=",
"[",
"u'bull'",
",",
"u'bear'",
",",
"u'static'",
"]",
"symbols",
"=",
"[",
"u'up'",
",",
"u'down'",
",",
"u'unchanged'",
"]",
"A",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.6",
",",
"0.2",
",",
"0.2",
"]",
",",
"[",
"0.5",
",",
"0.3",
",",
"0.2",
"]",
",",
"[",
"0.4",
",",
"0.1",
",",
"0.5",
"]",
"]",
",",
"np",
".",
"float64",
")",
"B",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.7",
",",
"0.1",
",",
"0.2",
"]",
",",
"[",
"0.1",
",",
"0.6",
",",
"0.3",
"]",
",",
"[",
"0.3",
",",
"0.3",
",",
"0.4",
"]",
"]",
",",
"np",
".",
"float64",
")",
"pi",
"=",
"np",
".",
"array",
"(",
"[",
"0.5",
",",
"0.2",
",",
"0.3",
"]",
",",
"np",
".",
"float64",
")",
"model",
"=",
"_create_hmm_tagger",
"(",
"states",
",",
"symbols",
",",
"A",
",",
"B",
",",
"pi",
")",
"return",
"(",
"model",
",",
"states",
",",
"symbols",
")"
] | return an example hmm . | train | false |
39,099 | def _validate_node(node):
try:
if (node is not None):
node = nodeprep(node)
if (not node):
raise InvalidJID(u'Localpart must not be 0 bytes')
if (len(node) > 1023):
raise InvalidJID(u'Localpart must be less than 1024 bytes')
return node
except stringprep_profiles.StringPrepError:
raise InvalidJID(u'Invalid local part')
| [
"def",
"_validate_node",
"(",
"node",
")",
":",
"try",
":",
"if",
"(",
"node",
"is",
"not",
"None",
")",
":",
"node",
"=",
"nodeprep",
"(",
"node",
")",
"if",
"(",
"not",
"node",
")",
":",
"raise",
"InvalidJID",
"(",
"u'Localpart must not be 0 bytes'",
")",
"if",
"(",
"len",
"(",
"node",
")",
">",
"1023",
")",
":",
"raise",
"InvalidJID",
"(",
"u'Localpart must be less than 1024 bytes'",
")",
"return",
"node",
"except",
"stringprep_profiles",
".",
"StringPrepError",
":",
"raise",
"InvalidJID",
"(",
"u'Invalid local part'",
")"
] | validate the local . | train | false |
39,100 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | initialise module . | train | false |
39,101 | def calculate_multipart_etag(source_path, chunk_size=DEFAULT_CHUNK_SIZE):
md5s = []
with open(source_path, 'rb') as fp:
while True:
data = fp.read(chunk_size)
if (not data):
break
md5s.append(hashlib.md5(data))
if (len(md5s) == 1):
new_etag = '"{}"'.format(md5s[0].hexdigest())
else:
digests = ''.join((m.digest() for m in md5s))
new_md5 = hashlib.md5(digests)
new_etag = '"{}-{}"'.format(new_md5.hexdigest(), len(md5s))
return new_etag
| [
"def",
"calculate_multipart_etag",
"(",
"source_path",
",",
"chunk_size",
"=",
"DEFAULT_CHUNK_SIZE",
")",
":",
"md5s",
"=",
"[",
"]",
"with",
"open",
"(",
"source_path",
",",
"'rb'",
")",
"as",
"fp",
":",
"while",
"True",
":",
"data",
"=",
"fp",
".",
"read",
"(",
"chunk_size",
")",
"if",
"(",
"not",
"data",
")",
":",
"break",
"md5s",
".",
"append",
"(",
"hashlib",
".",
"md5",
"(",
"data",
")",
")",
"if",
"(",
"len",
"(",
"md5s",
")",
"==",
"1",
")",
":",
"new_etag",
"=",
"'\"{}\"'",
".",
"format",
"(",
"md5s",
"[",
"0",
"]",
".",
"hexdigest",
"(",
")",
")",
"else",
":",
"digests",
"=",
"''",
".",
"join",
"(",
"(",
"m",
".",
"digest",
"(",
")",
"for",
"m",
"in",
"md5s",
")",
")",
"new_md5",
"=",
"hashlib",
".",
"md5",
"(",
"digests",
")",
"new_etag",
"=",
"'\"{}-{}\"'",
".",
"format",
"(",
"new_md5",
".",
"hexdigest",
"(",
")",
",",
"len",
"(",
"md5s",
")",
")",
"return",
"new_etag"
] | calculates a multipart upload etag for amazon s3 arguments: source_path -- the file to calculate the etag for chunk_size -- the chunk size to calculate for . | train | true |
39,104 | def removePrefix(s, prefix='!'):
if s.startswith(prefix):
return s[len(prefix):]
else:
return s
| [
"def",
"removePrefix",
"(",
"s",
",",
"prefix",
"=",
"'!'",
")",
":",
"if",
"s",
".",
"startswith",
"(",
"prefix",
")",
":",
"return",
"s",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"else",
":",
"return",
"s"
] | if the string starts from the prefix . | train | false |
39,105 | def distros_for_url(url, metadata=None):
(base, fragment) = egg_info_for_url(url)
for dist in distros_for_location(url, base, metadata):
(yield dist)
if fragment:
match = EGG_FRAGMENT.match(fragment)
if match:
for dist in interpret_distro_name(url, match.group(1), metadata, precedence=CHECKOUT_DIST):
(yield dist)
| [
"def",
"distros_for_url",
"(",
"url",
",",
"metadata",
"=",
"None",
")",
":",
"(",
"base",
",",
"fragment",
")",
"=",
"egg_info_for_url",
"(",
"url",
")",
"for",
"dist",
"in",
"distros_for_location",
"(",
"url",
",",
"base",
",",
"metadata",
")",
":",
"(",
"yield",
"dist",
")",
"if",
"fragment",
":",
"match",
"=",
"EGG_FRAGMENT",
".",
"match",
"(",
"fragment",
")",
"if",
"match",
":",
"for",
"dist",
"in",
"interpret_distro_name",
"(",
"url",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"metadata",
",",
"precedence",
"=",
"CHECKOUT_DIST",
")",
":",
"(",
"yield",
"dist",
")"
] | yield egg or source distribution objects that might be found at a url . | train | true |
39,106 | def side_effect_free(action):
@functools.wraps(action)
def wrapper(context, data_dict):
return action(context, data_dict)
wrapper.side_effect_free = True
return wrapper
| [
"def",
"side_effect_free",
"(",
"action",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"action",
")",
"def",
"wrapper",
"(",
"context",
",",
"data_dict",
")",
":",
"return",
"action",
"(",
"context",
",",
"data_dict",
")",
"wrapper",
".",
"side_effect_free",
"=",
"True",
"return",
"wrapper"
] | a decorator that marks the given action function as side-effect-free . | train | false |
39,107 | def orm_item_locator(orm_obj):
the_class = orm_obj._meta.object_name
original_class = the_class
pk_name = orm_obj._meta.pk.name
original_pk_name = pk_name
pk_value = getattr(orm_obj, pk_name)
while (hasattr(pk_value, '_meta') and hasattr(pk_value._meta, 'pk') and hasattr(pk_value._meta.pk, 'name')):
the_class = pk_value._meta.object_name
pk_name = pk_value._meta.pk.name
pk_value = getattr(pk_value, pk_name)
clean_dict = make_clean_dict(orm_obj.__dict__)
for key in clean_dict:
v = clean_dict[key]
if ((v is not None) and (not isinstance(v, (six.string_types, six.integer_types, float, datetime.datetime)))):
clean_dict[key] = six.u(('%s' % v))
output = (' importer.locate_object(%s, "%s", %s, "%s", %s, %s ) ' % (original_class, original_pk_name, the_class, pk_name, pk_value, clean_dict))
return output
| [
"def",
"orm_item_locator",
"(",
"orm_obj",
")",
":",
"the_class",
"=",
"orm_obj",
".",
"_meta",
".",
"object_name",
"original_class",
"=",
"the_class",
"pk_name",
"=",
"orm_obj",
".",
"_meta",
".",
"pk",
".",
"name",
"original_pk_name",
"=",
"pk_name",
"pk_value",
"=",
"getattr",
"(",
"orm_obj",
",",
"pk_name",
")",
"while",
"(",
"hasattr",
"(",
"pk_value",
",",
"'_meta'",
")",
"and",
"hasattr",
"(",
"pk_value",
".",
"_meta",
",",
"'pk'",
")",
"and",
"hasattr",
"(",
"pk_value",
".",
"_meta",
".",
"pk",
",",
"'name'",
")",
")",
":",
"the_class",
"=",
"pk_value",
".",
"_meta",
".",
"object_name",
"pk_name",
"=",
"pk_value",
".",
"_meta",
".",
"pk",
".",
"name",
"pk_value",
"=",
"getattr",
"(",
"pk_value",
",",
"pk_name",
")",
"clean_dict",
"=",
"make_clean_dict",
"(",
"orm_obj",
".",
"__dict__",
")",
"for",
"key",
"in",
"clean_dict",
":",
"v",
"=",
"clean_dict",
"[",
"key",
"]",
"if",
"(",
"(",
"v",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"v",
",",
"(",
"six",
".",
"string_types",
",",
"six",
".",
"integer_types",
",",
"float",
",",
"datetime",
".",
"datetime",
")",
")",
")",
")",
":",
"clean_dict",
"[",
"key",
"]",
"=",
"six",
".",
"u",
"(",
"(",
"'%s'",
"%",
"v",
")",
")",
"output",
"=",
"(",
"' importer.locate_object(%s, \"%s\", %s, \"%s\", %s, %s ) '",
"%",
"(",
"original_class",
",",
"original_pk_name",
",",
"the_class",
",",
"pk_name",
",",
"pk_value",
",",
"clean_dict",
")",
")",
"return",
"output"
] | this function is called every time an object that will not be exported is required . | train | true |
39,108 | def post_install(flag):
def decorator(obj):
obj.post_install = flag
return obj
return decorator
| [
"def",
"post_install",
"(",
"flag",
")",
":",
"def",
"decorator",
"(",
"obj",
")",
":",
"obj",
".",
"post_install",
"=",
"flag",
"return",
"obj",
"return",
"decorator"
] | sets the post-install state of a test . | train | false |
39,109 | def square_factor(a):
f = (a if isinstance(a, dict) else factorint(a))
return Mul(*[(p ** (e // 2)) for (p, e) in f.items()])
| [
"def",
"square_factor",
"(",
"a",
")",
":",
"f",
"=",
"(",
"a",
"if",
"isinstance",
"(",
"a",
",",
"dict",
")",
"else",
"factorint",
"(",
"a",
")",
")",
"return",
"Mul",
"(",
"*",
"[",
"(",
"p",
"**",
"(",
"e",
"//",
"2",
")",
")",
"for",
"(",
"p",
",",
"e",
")",
"in",
"f",
".",
"items",
"(",
")",
"]",
")"
] | returns an integer c s . | train | false |
39,111 | def __firewall_cmd(cmd):
firewall_cmd = '{0} {1}'.format(salt.utils.which('firewall-cmd'), cmd)
out = __salt__['cmd.run_all'](firewall_cmd)
if (out['retcode'] != 0):
if (not out['stderr']):
msg = out['stdout']
else:
msg = out['stderr']
raise CommandExecutionError('firewall-cmd failed: {0}'.format(msg))
return out['stdout']
| [
"def",
"__firewall_cmd",
"(",
"cmd",
")",
":",
"firewall_cmd",
"=",
"'{0} {1}'",
".",
"format",
"(",
"salt",
".",
"utils",
".",
"which",
"(",
"'firewall-cmd'",
")",
",",
"cmd",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"firewall_cmd",
")",
"if",
"(",
"out",
"[",
"'retcode'",
"]",
"!=",
"0",
")",
":",
"if",
"(",
"not",
"out",
"[",
"'stderr'",
"]",
")",
":",
"msg",
"=",
"out",
"[",
"'stdout'",
"]",
"else",
":",
"msg",
"=",
"out",
"[",
"'stderr'",
"]",
"raise",
"CommandExecutionError",
"(",
"'firewall-cmd failed: {0}'",
".",
"format",
"(",
"msg",
")",
")",
"return",
"out",
"[",
"'stdout'",
"]"
] | return the firewall-cmd location . | train | true |
39,113 | def list_trash(cookie, tokens, path='/', page=1, num=100):
url = ''.join([const.PAN_API_URL, 'recycle/list?channel=chunlei&clienttype=0&web=1', '&num=', str(num), '&t=', util.timestamp(), '&dir=', encoder.encode_uri_component(path), '&t=', util.latency(), '&order=time&desc=1', '&_=', util.timestamp(), '&bdstoken=', tokens['bdstoken']])
req = net.urlopen(url, headers={'Cookie': cookie.header_output()})
if req:
content = req.data
return json.loads(content.decode())
else:
return None
| [
"def",
"list_trash",
"(",
"cookie",
",",
"tokens",
",",
"path",
"=",
"'/'",
",",
"page",
"=",
"1",
",",
"num",
"=",
"100",
")",
":",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_API_URL",
",",
"'recycle/list?channel=chunlei&clienttype=0&web=1'",
",",
"'&num='",
",",
"str",
"(",
"num",
")",
",",
"'&t='",
",",
"util",
".",
"timestamp",
"(",
")",
",",
"'&dir='",
",",
"encoder",
".",
"encode_uri_component",
"(",
"path",
")",
",",
"'&t='",
",",
"util",
".",
"latency",
"(",
")",
",",
"'&order=time&desc=1'",
",",
"'&_='",
",",
"util",
".",
"timestamp",
"(",
")",
",",
"'&bdstoken='",
",",
"tokens",
"[",
"'bdstoken'",
"]",
"]",
")",
"req",
"=",
"net",
".",
"urlopen",
"(",
"url",
",",
"headers",
"=",
"{",
"'Cookie'",
":",
"cookie",
".",
"header_output",
"(",
")",
"}",
")",
"if",
"req",
":",
"content",
"=",
"req",
".",
"data",
"return",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
")",
")",
"else",
":",
"return",
"None"
] | path - 目录的绝对路径 . | train | true |
39,116 | def authenticate_user_if_possible(request, user):
if request.line.uri.startswith('/assets/'):
pass
elif ('Authorization' in request.headers):
header = request.headers['authorization']
if header.startswith('Basic '):
user = _get_user_via_basic_auth(header)
if (not user.ANON):
_turn_off_csrf(request)
elif (SESSION in request.headers.cookie):
token = request.headers.cookie[SESSION].value
user = User.from_session_token(token)
return {'user': user}
| [
"def",
"authenticate_user_if_possible",
"(",
"request",
",",
"user",
")",
":",
"if",
"request",
".",
"line",
".",
"uri",
".",
"startswith",
"(",
"'/assets/'",
")",
":",
"pass",
"elif",
"(",
"'Authorization'",
"in",
"request",
".",
"headers",
")",
":",
"header",
"=",
"request",
".",
"headers",
"[",
"'authorization'",
"]",
"if",
"header",
".",
"startswith",
"(",
"'Basic '",
")",
":",
"user",
"=",
"_get_user_via_basic_auth",
"(",
"header",
")",
"if",
"(",
"not",
"user",
".",
"ANON",
")",
":",
"_turn_off_csrf",
"(",
"request",
")",
"elif",
"(",
"SESSION",
"in",
"request",
".",
"headers",
".",
"cookie",
")",
":",
"token",
"=",
"request",
".",
"headers",
".",
"cookie",
"[",
"SESSION",
"]",
".",
"value",
"user",
"=",
"User",
".",
"from_session_token",
"(",
"token",
")",
"return",
"{",
"'user'",
":",
"user",
"}"
] | this signs the user in . | train | false |
39,117 | def getPathInFabmetheusFromFileNameHelp(fileNameHelp):
fabmetheusPath = archive.getFabmetheusPath()
splitFileNameHelps = fileNameHelp.split('.')
splitFileNameDirectoryNames = splitFileNameHelps[:(-1)]
for splitFileNameDirectoryName in splitFileNameDirectoryNames:
fabmetheusPath = os.path.join(fabmetheusPath, splitFileNameDirectoryName)
return fabmetheusPath
| [
"def",
"getPathInFabmetheusFromFileNameHelp",
"(",
"fileNameHelp",
")",
":",
"fabmetheusPath",
"=",
"archive",
".",
"getFabmetheusPath",
"(",
")",
"splitFileNameHelps",
"=",
"fileNameHelp",
".",
"split",
"(",
"'.'",
")",
"splitFileNameDirectoryNames",
"=",
"splitFileNameHelps",
"[",
":",
"(",
"-",
"1",
")",
"]",
"for",
"splitFileNameDirectoryName",
"in",
"splitFileNameDirectoryNames",
":",
"fabmetheusPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"fabmetheusPath",
",",
"splitFileNameDirectoryName",
")",
"return",
"fabmetheusPath"
] | get the directory path from file name help . | train | false |
39,119 | def engine_to_rdbms_type(django_engine):
rdbms_type = django_engine.split('.')[(-1)]
if (rdbms_type == 'afe'):
rdbms_type = 'mysql'
elif rdbms_type.startswith('afe_'):
rdbms_type = rdbms_type[4:]
return rdbms_type
| [
"def",
"engine_to_rdbms_type",
"(",
"django_engine",
")",
":",
"rdbms_type",
"=",
"django_engine",
".",
"split",
"(",
"'.'",
")",
"[",
"(",
"-",
"1",
")",
"]",
"if",
"(",
"rdbms_type",
"==",
"'afe'",
")",
":",
"rdbms_type",
"=",
"'mysql'",
"elif",
"rdbms_type",
".",
"startswith",
"(",
"'afe_'",
")",
":",
"rdbms_type",
"=",
"rdbms_type",
"[",
"4",
":",
"]",
"return",
"rdbms_type"
] | returns a rdbms type for a given django engine name . | train | false |
39,120 | def memoized_property(func=None, key_factory=per_instance, **kwargs):
getter = memoized_method(func=func, key_factory=key_factory, **kwargs)
return property(fget=getter, fdel=(lambda self: getter.forget(self)))
| [
"def",
"memoized_property",
"(",
"func",
"=",
"None",
",",
"key_factory",
"=",
"per_instance",
",",
"**",
"kwargs",
")",
":",
"getter",
"=",
"memoized_method",
"(",
"func",
"=",
"func",
",",
"key_factory",
"=",
"key_factory",
",",
"**",
"kwargs",
")",
"return",
"property",
"(",
"fget",
"=",
"getter",
",",
"fdel",
"=",
"(",
"lambda",
"self",
":",
"getter",
".",
"forget",
"(",
"self",
")",
")",
")"
] | a convenience wrapper for memoizing properties . | train | true |
39,121 | def UploadSignedConfigBlob(content, aff4_path, client_context=None, limit=None, token=None):
if (limit is None):
limit = config_lib.CONFIG['Datastore.maximum_blob_size']
if (client_context is None):
client_context = ['Platform:Windows', 'Client Context']
config_lib.CONFIG.Validate(parameters='PrivateKeys.executable_signing_private_key')
sig_key = config_lib.CONFIG.Get('PrivateKeys.executable_signing_private_key', context=client_context)
ver_key = config_lib.CONFIG.Get('Client.executable_signing_public_key', context=client_context)
urn = collects.GRRSignedBlob.NewFromContent(content, aff4_path, chunk_size=limit, token=token, private_key=sig_key, public_key=ver_key)
logging.info('Uploaded to %s', urn)
| [
"def",
"UploadSignedConfigBlob",
"(",
"content",
",",
"aff4_path",
",",
"client_context",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"if",
"(",
"limit",
"is",
"None",
")",
":",
"limit",
"=",
"config_lib",
".",
"CONFIG",
"[",
"'Datastore.maximum_blob_size'",
"]",
"if",
"(",
"client_context",
"is",
"None",
")",
":",
"client_context",
"=",
"[",
"'Platform:Windows'",
",",
"'Client Context'",
"]",
"config_lib",
".",
"CONFIG",
".",
"Validate",
"(",
"parameters",
"=",
"'PrivateKeys.executable_signing_private_key'",
")",
"sig_key",
"=",
"config_lib",
".",
"CONFIG",
".",
"Get",
"(",
"'PrivateKeys.executable_signing_private_key'",
",",
"context",
"=",
"client_context",
")",
"ver_key",
"=",
"config_lib",
".",
"CONFIG",
".",
"Get",
"(",
"'Client.executable_signing_public_key'",
",",
"context",
"=",
"client_context",
")",
"urn",
"=",
"collects",
".",
"GRRSignedBlob",
".",
"NewFromContent",
"(",
"content",
",",
"aff4_path",
",",
"chunk_size",
"=",
"limit",
",",
"token",
"=",
"token",
",",
"private_key",
"=",
"sig_key",
",",
"public_key",
"=",
"ver_key",
")",
"logging",
".",
"info",
"(",
"'Uploaded to %s'",
",",
"urn",
")"
] | upload a signed blob into the datastore . | train | false |
39,122 | def MakeGoogleUniqueID(cloud_instance):
if (not (cloud_instance.zone and cloud_instance.project_id and cloud_instance.instance_id)):
raise ValueError(("Bad zone/project_id/id: '%s/%s/%s'" % (cloud_instance.zone, cloud_instance.project_id, cloud_instance.instance_id)))
return '/'.join([cloud_instance.zone.split('/')[(-1)], cloud_instance.project_id, cloud_instance.instance_id])
| [
"def",
"MakeGoogleUniqueID",
"(",
"cloud_instance",
")",
":",
"if",
"(",
"not",
"(",
"cloud_instance",
".",
"zone",
"and",
"cloud_instance",
".",
"project_id",
"and",
"cloud_instance",
".",
"instance_id",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"Bad zone/project_id/id: '%s/%s/%s'\"",
"%",
"(",
"cloud_instance",
".",
"zone",
",",
"cloud_instance",
".",
"project_id",
",",
"cloud_instance",
".",
"instance_id",
")",
")",
")",
"return",
"'/'",
".",
"join",
"(",
"[",
"cloud_instance",
".",
"zone",
".",
"split",
"(",
"'/'",
")",
"[",
"(",
"-",
"1",
")",
"]",
",",
"cloud_instance",
".",
"project_id",
",",
"cloud_instance",
".",
"instance_id",
"]",
")"
] | make the google unique id of zone/project/id . | train | true |
39,124 | def _VerifySourcesExist(sources, root_dir):
missing_sources = []
for source in sources:
if isinstance(source, MSVSProject.Filter):
missing_sources.extend(_VerifySourcesExist(source.contents, root_dir))
elif ('$' not in source):
full_path = os.path.join(root_dir, source)
if (not os.path.exists(full_path)):
missing_sources.append(full_path)
return missing_sources
| [
"def",
"_VerifySourcesExist",
"(",
"sources",
",",
"root_dir",
")",
":",
"missing_sources",
"=",
"[",
"]",
"for",
"source",
"in",
"sources",
":",
"if",
"isinstance",
"(",
"source",
",",
"MSVSProject",
".",
"Filter",
")",
":",
"missing_sources",
".",
"extend",
"(",
"_VerifySourcesExist",
"(",
"source",
".",
"contents",
",",
"root_dir",
")",
")",
"elif",
"(",
"'$'",
"not",
"in",
"source",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"source",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
")",
":",
"missing_sources",
".",
"append",
"(",
"full_path",
")",
"return",
"missing_sources"
] | verifies that all source files exist on disk . | train | false |
39,126 | def MigrateClientsAndUsersLabels(token=None):
print 'Migrating clients.'
MigrateObjectsLabels(aff4.ROOT_URN, aff4_grr.VFSGRRClient, token=token)
print '\nMigrating users.'
MigrateObjectsLabels(aff4.ROOT_URN.Add('users'), users.GRRUser, label_suffix='labels', token=token)
| [
"def",
"MigrateClientsAndUsersLabels",
"(",
"token",
"=",
"None",
")",
":",
"print",
"'Migrating clients.'",
"MigrateObjectsLabels",
"(",
"aff4",
".",
"ROOT_URN",
",",
"aff4_grr",
".",
"VFSGRRClient",
",",
"token",
"=",
"token",
")",
"print",
"'\\nMigrating users.'",
"MigrateObjectsLabels",
"(",
"aff4",
".",
"ROOT_URN",
".",
"Add",
"(",
"'users'",
")",
",",
"users",
".",
"GRRUser",
",",
"label_suffix",
"=",
"'labels'",
",",
"token",
"=",
"token",
")"
] | migrates clients and users labels . | train | false |
39,127 | @register.inclusion_tag(u'includes/search_form.html', takes_context=True)
def search_form(context, search_model_names=None):
template_vars = {u'request': context[u'request']}
if ((not search_model_names) or (not settings.SEARCH_MODEL_CHOICES)):
search_model_names = []
elif (search_model_names == u'all'):
search_model_names = list(settings.SEARCH_MODEL_CHOICES)
else:
search_model_names = search_model_names.split(u' ')
search_model_choices = []
for model_name in search_model_names:
try:
model = apps.get_model(*model_name.split(u'.', 1))
except LookupError:
pass
else:
verbose_name = model._meta.verbose_name_plural.capitalize()
search_model_choices.append((verbose_name, model_name))
template_vars[u'search_model_choices'] = sorted(search_model_choices)
return template_vars
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"u'includes/search_form.html'",
",",
"takes_context",
"=",
"True",
")",
"def",
"search_form",
"(",
"context",
",",
"search_model_names",
"=",
"None",
")",
":",
"template_vars",
"=",
"{",
"u'request'",
":",
"context",
"[",
"u'request'",
"]",
"}",
"if",
"(",
"(",
"not",
"search_model_names",
")",
"or",
"(",
"not",
"settings",
".",
"SEARCH_MODEL_CHOICES",
")",
")",
":",
"search_model_names",
"=",
"[",
"]",
"elif",
"(",
"search_model_names",
"==",
"u'all'",
")",
":",
"search_model_names",
"=",
"list",
"(",
"settings",
".",
"SEARCH_MODEL_CHOICES",
")",
"else",
":",
"search_model_names",
"=",
"search_model_names",
".",
"split",
"(",
"u' '",
")",
"search_model_choices",
"=",
"[",
"]",
"for",
"model_name",
"in",
"search_model_names",
":",
"try",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"*",
"model_name",
".",
"split",
"(",
"u'.'",
",",
"1",
")",
")",
"except",
"LookupError",
":",
"pass",
"else",
":",
"verbose_name",
"=",
"model",
".",
"_meta",
".",
"verbose_name_plural",
".",
"capitalize",
"(",
")",
"search_model_choices",
".",
"append",
"(",
"(",
"verbose_name",
",",
"model_name",
")",
")",
"template_vars",
"[",
"u'search_model_choices'",
"]",
"=",
"sorted",
"(",
"search_model_choices",
")",
"return",
"template_vars"
] | displays a search form for searching the list . | train | false |
39,128 | def hello_world_window():
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_border_width(50)
button = gtk.Button(u'Hello World')
window.add(button)
def clicked(data):
print u'Button clicked!'
button.connect(u'clicked', clicked)
button.show()
window.show()
| [
"def",
"hello_world_window",
"(",
")",
":",
"window",
"=",
"gtk",
".",
"Window",
"(",
"gtk",
".",
"WINDOW_TOPLEVEL",
")",
"window",
".",
"set_border_width",
"(",
"50",
")",
"button",
"=",
"gtk",
".",
"Button",
"(",
"u'Hello World'",
")",
"window",
".",
"add",
"(",
"button",
")",
"def",
"clicked",
"(",
"data",
")",
":",
"print",
"u'Button clicked!'",
"button",
".",
"connect",
"(",
"u'clicked'",
",",
"clicked",
")",
"button",
".",
"show",
"(",
")",
"window",
".",
"show",
"(",
")"
] | create a gtk window with one hello world button . | train | false |
39,129 | @synchronized(IO_LOCK)
def get_new_id(prefix, folder, check_list=None):
for n in xrange(10000):
try:
if (not os.path.exists(folder)):
os.makedirs(folder)
(fd, path) = tempfile.mkstemp('', ('SABnzbd_%s_' % prefix), folder)
os.close(fd)
(head, tail) = os.path.split(path)
if ((not check_list) or (tail not in check_list)):
return tail
except:
logging.error(T('Failure in tempfile.mkstemp'))
logging.info('Traceback: ', exc_info=True)
raise IOError
| [
"@",
"synchronized",
"(",
"IO_LOCK",
")",
"def",
"get_new_id",
"(",
"prefix",
",",
"folder",
",",
"check_list",
"=",
"None",
")",
":",
"for",
"n",
"in",
"xrange",
"(",
"10000",
")",
":",
"try",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"folder",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"folder",
")",
"(",
"fd",
",",
"path",
")",
"=",
"tempfile",
".",
"mkstemp",
"(",
"''",
",",
"(",
"'SABnzbd_%s_'",
"%",
"prefix",
")",
",",
"folder",
")",
"os",
".",
"close",
"(",
"fd",
")",
"(",
"head",
",",
"tail",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"(",
"(",
"not",
"check_list",
")",
"or",
"(",
"tail",
"not",
"in",
"check_list",
")",
")",
":",
"return",
"tail",
"except",
":",
"logging",
".",
"error",
"(",
"T",
"(",
"'Failure in tempfile.mkstemp'",
")",
")",
"logging",
".",
"info",
"(",
"'Traceback: '",
",",
"exc_info",
"=",
"True",
")",
"raise",
"IOError"
] | return unique prefixed admin identifier within folder optionally making sure that id is not in the check_list . | train | false |
39,131 | def _load_dist_subclass(cls, *args, **kwargs):
subclass = None
distro = kwargs['module'].params['distro']
if (distro is not None):
for sc in cls.__subclasses__():
if ((sc.distro is not None) and (sc.distro == distro)):
subclass = sc
if (subclass is None):
subclass = cls
return super(cls, subclass).__new__(subclass)
| [
"def",
"_load_dist_subclass",
"(",
"cls",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"subclass",
"=",
"None",
"distro",
"=",
"kwargs",
"[",
"'module'",
"]",
".",
"params",
"[",
"'distro'",
"]",
"if",
"(",
"distro",
"is",
"not",
"None",
")",
":",
"for",
"sc",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"if",
"(",
"(",
"sc",
".",
"distro",
"is",
"not",
"None",
")",
"and",
"(",
"sc",
".",
"distro",
"==",
"distro",
")",
")",
":",
"subclass",
"=",
"sc",
"if",
"(",
"subclass",
"is",
"None",
")",
":",
"subclass",
"=",
"cls",
"return",
"super",
"(",
"cls",
",",
"subclass",
")",
".",
"__new__",
"(",
"subclass",
")"
] | used for derivative implementations . | train | false |
39,134 | @mine.command('set')
@click.argument('x', type=float)
@click.argument('y', type=float)
@click.option('ty', '--moored', flag_value='moored', default=True, help='Moored (anchored) mine. Default.')
@click.option('ty', '--drifting', flag_value='drifting', help='Drifting mine.')
def mine_set(x, y, ty):
click.echo(('Set %s mine at %s,%s' % (ty, x, y)))
| [
"@",
"mine",
".",
"command",
"(",
"'set'",
")",
"@",
"click",
".",
"argument",
"(",
"'x'",
",",
"type",
"=",
"float",
")",
"@",
"click",
".",
"argument",
"(",
"'y'",
",",
"type",
"=",
"float",
")",
"@",
"click",
".",
"option",
"(",
"'ty'",
",",
"'--moored'",
",",
"flag_value",
"=",
"'moored'",
",",
"default",
"=",
"True",
",",
"help",
"=",
"'Moored (anchored) mine. Default.'",
")",
"@",
"click",
".",
"option",
"(",
"'ty'",
",",
"'--drifting'",
",",
"flag_value",
"=",
"'drifting'",
",",
"help",
"=",
"'Drifting mine.'",
")",
"def",
"mine_set",
"(",
"x",
",",
"y",
",",
"ty",
")",
":",
"click",
".",
"echo",
"(",
"(",
"'Set %s mine at %s,%s'",
"%",
"(",
"ty",
",",
"x",
",",
"y",
")",
")",
")"
] | sets a mine at a specific coordinate . | train | false |
39,135 | def Application_End():
pass
| [
"def",
"Application_End",
"(",
")",
":",
"pass"
] | code that runs on application shutdown . | train | false |
39,136 | def psversion():
salt.utils.warn_until(u'Oxygen', u"The 'psversion' has been deprecated and has been replaced by 'cmd.shell_info'.")
powershell_info = __salt__[u'cmd.shell_info'](u'powershell')
if powershell_info[u'installed']:
try:
return int(powershell_info[u'version'].split(u'.')[0])
except ValueError:
pass
return 0
| [
"def",
"psversion",
"(",
")",
":",
"salt",
".",
"utils",
".",
"warn_until",
"(",
"u'Oxygen'",
",",
"u\"The 'psversion' has been deprecated and has been replaced by 'cmd.shell_info'.\"",
")",
"powershell_info",
"=",
"__salt__",
"[",
"u'cmd.shell_info'",
"]",
"(",
"u'powershell'",
")",
"if",
"powershell_info",
"[",
"u'installed'",
"]",
":",
"try",
":",
"return",
"int",
"(",
"powershell_info",
"[",
"u'version'",
"]",
".",
"split",
"(",
"u'.'",
")",
"[",
"0",
"]",
")",
"except",
"ValueError",
":",
"pass",
"return",
"0"
] | returns the powershell version this has been deprecated and has been replaced by cmd . | train | false |
39,138 | def norm_lls(y, params):
(mu, sigma2) = params.T
lls = ((-0.5) * ((np.log((2 * np.pi)) + np.log(sigma2)) + (((y - mu) ** 2) / sigma2)))
return lls
| [
"def",
"norm_lls",
"(",
"y",
",",
"params",
")",
":",
"(",
"mu",
",",
"sigma2",
")",
"=",
"params",
".",
"T",
"lls",
"=",
"(",
"(",
"-",
"0.5",
")",
"*",
"(",
"(",
"np",
".",
"log",
"(",
"(",
"2",
"*",
"np",
".",
"pi",
")",
")",
"+",
"np",
".",
"log",
"(",
"sigma2",
")",
")",
"+",
"(",
"(",
"(",
"y",
"-",
"mu",
")",
"**",
"2",
")",
"/",
"sigma2",
")",
")",
")",
"return",
"lls"
] | normal loglikelihood given observations and mean mu and variance sigma2 parameters y : array . | train | false |
39,139 | def check_io_schema_list(io_configs):
if ((not isinstance(io_configs, collections.Sequence)) or isinstance(io_configs, collections.Mapping) or isinstance(io_configs, six.string_types)):
raise TypeError('Software Config I/O Schema must be in a list')
if (not all((isinstance(conf, collections.Mapping) for conf in io_configs))):
raise TypeError('Software Config I/O Schema must be a dict')
| [
"def",
"check_io_schema_list",
"(",
"io_configs",
")",
":",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"io_configs",
",",
"collections",
".",
"Sequence",
")",
")",
"or",
"isinstance",
"(",
"io_configs",
",",
"collections",
".",
"Mapping",
")",
"or",
"isinstance",
"(",
"io_configs",
",",
"six",
".",
"string_types",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Software Config I/O Schema must be in a list'",
")",
"if",
"(",
"not",
"all",
"(",
"(",
"isinstance",
"(",
"conf",
",",
"collections",
".",
"Mapping",
")",
"for",
"conf",
"in",
"io_configs",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Software Config I/O Schema must be a dict'",
")"
] | check that an input or output schema list is of the correct type . | train | false |
39,140 | def process_events():
use_app(call_reuse=False)
return default_app.process_events()
| [
"def",
"process_events",
"(",
")",
":",
"use_app",
"(",
"call_reuse",
"=",
"False",
")",
"return",
"default_app",
".",
"process_events",
"(",
")"
] | process all pending gui events if the mainloop is not running . | train | false |
39,141 | def history_remove_failed():
logging.info('Scheduled removal of all failed jobs')
history_db = HistoryDB()
del_job_files(history_db.get_failed_paths())
history_db.remove_failed()
history_db.close()
del history_db
| [
"def",
"history_remove_failed",
"(",
")",
":",
"logging",
".",
"info",
"(",
"'Scheduled removal of all failed jobs'",
")",
"history_db",
"=",
"HistoryDB",
"(",
")",
"del_job_files",
"(",
"history_db",
".",
"get_failed_paths",
"(",
")",
")",
"history_db",
".",
"remove_failed",
"(",
")",
"history_db",
".",
"close",
"(",
")",
"del",
"history_db"
] | remove all failed jobs from history . | train | false |
39,142 | def xml_add_links(data):
xml = ''
chunk = '<link rel="%s" href="%s" title="%s" />'
links = data.pop(config.LINKS, {})
ordered_links = OrderedDict(sorted(links.items()))
for (rel, link) in ordered_links.items():
if isinstance(link, list):
xml += ''.join([(chunk % (rel, utils.escape(d['href']), utils.escape(d['title']))) for d in link])
else:
xml += ''.join((chunk % (rel, utils.escape(link['href']), link['title'])))
return xml
| [
"def",
"xml_add_links",
"(",
"data",
")",
":",
"xml",
"=",
"''",
"chunk",
"=",
"'<link rel=\"%s\" href=\"%s\" title=\"%s\" />'",
"links",
"=",
"data",
".",
"pop",
"(",
"config",
".",
"LINKS",
",",
"{",
"}",
")",
"ordered_links",
"=",
"OrderedDict",
"(",
"sorted",
"(",
"links",
".",
"items",
"(",
")",
")",
")",
"for",
"(",
"rel",
",",
"link",
")",
"in",
"ordered_links",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"link",
",",
"list",
")",
":",
"xml",
"+=",
"''",
".",
"join",
"(",
"[",
"(",
"chunk",
"%",
"(",
"rel",
",",
"utils",
".",
"escape",
"(",
"d",
"[",
"'href'",
"]",
")",
",",
"utils",
".",
"escape",
"(",
"d",
"[",
"'title'",
"]",
")",
")",
")",
"for",
"d",
"in",
"link",
"]",
")",
"else",
":",
"xml",
"+=",
"''",
".",
"join",
"(",
"(",
"chunk",
"%",
"(",
"rel",
",",
"utils",
".",
"escape",
"(",
"link",
"[",
"'href'",
"]",
")",
",",
"link",
"[",
"'title'",
"]",
")",
")",
")",
"return",
"xml"
] | returns as many <link> nodes as there are in the datastream . | train | false |
39,146 | def aes_decrypt_text(data, password, key_size_bytes):
NONCE_LENGTH_BYTES = 8
data = bytes_to_intlist(base64.b64decode(data))
password = bytes_to_intlist(password.encode(u'utf-8'))
key = (password[:key_size_bytes] + ([0] * (key_size_bytes - len(password))))
key = (aes_encrypt(key[:BLOCK_SIZE_BYTES], key_expansion(key)) * (key_size_bytes // BLOCK_SIZE_BYTES))
nonce = data[:NONCE_LENGTH_BYTES]
cipher = data[NONCE_LENGTH_BYTES:]
class Counter:
__value = (nonce + ([0] * (BLOCK_SIZE_BYTES - NONCE_LENGTH_BYTES)))
def next_value(self):
temp = self.__value
self.__value = inc(self.__value)
return temp
decrypted_data = aes_ctr_decrypt(cipher, key, Counter())
plaintext = intlist_to_bytes(decrypted_data)
return plaintext
| [
"def",
"aes_decrypt_text",
"(",
"data",
",",
"password",
",",
"key_size_bytes",
")",
":",
"NONCE_LENGTH_BYTES",
"=",
"8",
"data",
"=",
"bytes_to_intlist",
"(",
"base64",
".",
"b64decode",
"(",
"data",
")",
")",
"password",
"=",
"bytes_to_intlist",
"(",
"password",
".",
"encode",
"(",
"u'utf-8'",
")",
")",
"key",
"=",
"(",
"password",
"[",
":",
"key_size_bytes",
"]",
"+",
"(",
"[",
"0",
"]",
"*",
"(",
"key_size_bytes",
"-",
"len",
"(",
"password",
")",
")",
")",
")",
"key",
"=",
"(",
"aes_encrypt",
"(",
"key",
"[",
":",
"BLOCK_SIZE_BYTES",
"]",
",",
"key_expansion",
"(",
"key",
")",
")",
"*",
"(",
"key_size_bytes",
"//",
"BLOCK_SIZE_BYTES",
")",
")",
"nonce",
"=",
"data",
"[",
":",
"NONCE_LENGTH_BYTES",
"]",
"cipher",
"=",
"data",
"[",
"NONCE_LENGTH_BYTES",
":",
"]",
"class",
"Counter",
":",
"__value",
"=",
"(",
"nonce",
"+",
"(",
"[",
"0",
"]",
"*",
"(",
"BLOCK_SIZE_BYTES",
"-",
"NONCE_LENGTH_BYTES",
")",
")",
")",
"def",
"next_value",
"(",
"self",
")",
":",
"temp",
"=",
"self",
".",
"__value",
"self",
".",
"__value",
"=",
"inc",
"(",
"self",
".",
"__value",
")",
"return",
"temp",
"decrypted_data",
"=",
"aes_ctr_decrypt",
"(",
"cipher",
",",
"key",
",",
"Counter",
"(",
")",
")",
"plaintext",
"=",
"intlist_to_bytes",
"(",
"decrypted_data",
")",
"return",
"plaintext"
] | decrypt text - the first 8 bytes of decoded data are the 8 high bytes of the counter - the cipher key is retrieved by encrypting the first 16 byte of password with the first key_size_bytes bytes from password - mode of operation is counter . | train | false |
39,147 | @nox.parametrize('sample', SAMPLES_WITH_GENERATED_READMES)
def session_readmegen(session, sample):
session.install('jinja2', 'pyyaml')
if os.path.exists(os.path.join(sample, 'requirements.txt')):
session.install('-r', os.path.join(sample, 'requirements.txt'))
in_file = os.path.join(sample, 'README.rst.in')
session.run('python', 'scripts/readme-gen/readme_gen.py', in_file)
| [
"@",
"nox",
".",
"parametrize",
"(",
"'sample'",
",",
"SAMPLES_WITH_GENERATED_READMES",
")",
"def",
"session_readmegen",
"(",
"session",
",",
"sample",
")",
":",
"session",
".",
"install",
"(",
"'jinja2'",
",",
"'pyyaml'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"sample",
",",
"'requirements.txt'",
")",
")",
":",
"session",
".",
"install",
"(",
"'-r'",
",",
"os",
".",
"path",
".",
"join",
"(",
"sample",
",",
"'requirements.txt'",
")",
")",
"in_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sample",
",",
"'README.rst.in'",
")",
"session",
".",
"run",
"(",
"'python'",
",",
"'scripts/readme-gen/readme_gen.py'",
",",
"in_file",
")"
] | generates the readme for a sample . | train | false |
39,148 | def verified_email_required(function=None, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
def decorator(view_func):
@login_required(redirect_field_name=redirect_field_name, login_url=login_url)
def _wrapped_view(request, *args, **kwargs):
if (not EmailAddress.objects.filter(user=request.user, verified=True).exists()):
send_email_confirmation(request, request.user)
return render(request, 'account/verified_email_required.html')
return view_func(request, *args, **kwargs)
return _wrapped_view
if function:
return decorator(function)
return decorator
| [
"def",
"verified_email_required",
"(",
"function",
"=",
"None",
",",
"login_url",
"=",
"None",
",",
"redirect_field_name",
"=",
"REDIRECT_FIELD_NAME",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"login_required",
"(",
"redirect_field_name",
"=",
"redirect_field_name",
",",
"login_url",
"=",
"login_url",
")",
"def",
"_wrapped_view",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"EmailAddress",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"request",
".",
"user",
",",
"verified",
"=",
"True",
")",
".",
"exists",
"(",
")",
")",
":",
"send_email_confirmation",
"(",
"request",
",",
"request",
".",
"user",
")",
"return",
"render",
"(",
"request",
",",
"'account/verified_email_required.html'",
")",
"return",
"view_func",
"(",
"request",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"_wrapped_view",
"if",
"function",
":",
"return",
"decorator",
"(",
"function",
")",
"return",
"decorator"
] | even when email verification is not mandatory during signup . | train | true |
39,149 | @doctest_depends_on(modules=('numpy',))
def symarray(prefix, shape, **kwargs):
from numpy import empty, ndindex
arr = empty(shape, dtype=object)
for index in ndindex(shape):
arr[index] = Symbol(('%s_%s' % (prefix, '_'.join(map(str, index)))), **kwargs)
return arr
| [
"@",
"doctest_depends_on",
"(",
"modules",
"=",
"(",
"'numpy'",
",",
")",
")",
"def",
"symarray",
"(",
"prefix",
",",
"shape",
",",
"**",
"kwargs",
")",
":",
"from",
"numpy",
"import",
"empty",
",",
"ndindex",
"arr",
"=",
"empty",
"(",
"shape",
",",
"dtype",
"=",
"object",
")",
"for",
"index",
"in",
"ndindex",
"(",
"shape",
")",
":",
"arr",
"[",
"index",
"]",
"=",
"Symbol",
"(",
"(",
"'%s_%s'",
"%",
"(",
"prefix",
",",
"'_'",
".",
"join",
"(",
"map",
"(",
"str",
",",
"index",
")",
")",
")",
")",
",",
"**",
"kwargs",
")",
"return",
"arr"
] | create a numpy ndarray of symbols . | train | false |
39,152 | def get_dynamodb_type(val, use_boolean=True):
dynamodb_type = None
if (val is None):
dynamodb_type = 'NULL'
elif is_num(val):
if (isinstance(val, bool) and use_boolean):
dynamodb_type = 'BOOL'
else:
dynamodb_type = 'N'
elif is_str(val):
dynamodb_type = 'S'
elif isinstance(val, (set, frozenset)):
if (False not in map(is_num, val)):
dynamodb_type = 'NS'
elif (False not in map(is_str, val)):
dynamodb_type = 'SS'
elif (False not in map(is_binary, val)):
dynamodb_type = 'BS'
elif is_binary(val):
dynamodb_type = 'B'
elif isinstance(val, Mapping):
dynamodb_type = 'M'
elif isinstance(val, list):
dynamodb_type = 'L'
if (dynamodb_type is None):
msg = ('Unsupported type "%s" for value "%s"' % (type(val), val))
raise TypeError(msg)
return dynamodb_type
| [
"def",
"get_dynamodb_type",
"(",
"val",
",",
"use_boolean",
"=",
"True",
")",
":",
"dynamodb_type",
"=",
"None",
"if",
"(",
"val",
"is",
"None",
")",
":",
"dynamodb_type",
"=",
"'NULL'",
"elif",
"is_num",
"(",
"val",
")",
":",
"if",
"(",
"isinstance",
"(",
"val",
",",
"bool",
")",
"and",
"use_boolean",
")",
":",
"dynamodb_type",
"=",
"'BOOL'",
"else",
":",
"dynamodb_type",
"=",
"'N'",
"elif",
"is_str",
"(",
"val",
")",
":",
"dynamodb_type",
"=",
"'S'",
"elif",
"isinstance",
"(",
"val",
",",
"(",
"set",
",",
"frozenset",
")",
")",
":",
"if",
"(",
"False",
"not",
"in",
"map",
"(",
"is_num",
",",
"val",
")",
")",
":",
"dynamodb_type",
"=",
"'NS'",
"elif",
"(",
"False",
"not",
"in",
"map",
"(",
"is_str",
",",
"val",
")",
")",
":",
"dynamodb_type",
"=",
"'SS'",
"elif",
"(",
"False",
"not",
"in",
"map",
"(",
"is_binary",
",",
"val",
")",
")",
":",
"dynamodb_type",
"=",
"'BS'",
"elif",
"is_binary",
"(",
"val",
")",
":",
"dynamodb_type",
"=",
"'B'",
"elif",
"isinstance",
"(",
"val",
",",
"Mapping",
")",
":",
"dynamodb_type",
"=",
"'M'",
"elif",
"isinstance",
"(",
"val",
",",
"list",
")",
":",
"dynamodb_type",
"=",
"'L'",
"if",
"(",
"dynamodb_type",
"is",
"None",
")",
":",
"msg",
"=",
"(",
"'Unsupported type \"%s\" for value \"%s\"'",
"%",
"(",
"type",
"(",
"val",
")",
",",
"val",
")",
")",
"raise",
"TypeError",
"(",
"msg",
")",
"return",
"dynamodb_type"
] | take a scalar python value and return a string representing the corresponding amazon dynamodb type . | train | false |
39,153 | @real_memoize
def is_sunos():
return sys.platform.startswith('sunos')
| [
"@",
"real_memoize",
"def",
"is_sunos",
"(",
")",
":",
"return",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'sunos'",
")"
] | simple function to return if host is sunos or not . | train | false |
39,154 | def octocat(say=None):
return gh.octocat(say)
| [
"def",
"octocat",
"(",
"say",
"=",
"None",
")",
":",
"return",
"gh",
".",
"octocat",
"(",
"say",
")"
] | return an easter egg from the api . | train | false |
39,155 | def allowed_flags(args, flags):
flags = set(flags)
for arg in args.keys():
try:
if (Options.__options__[arg].is_Flag and (not (arg in flags))):
raise FlagError(("'%s' flag is not allowed in this context" % arg))
except KeyError:
raise OptionError(("'%s' is not a valid option" % arg))
| [
"def",
"allowed_flags",
"(",
"args",
",",
"flags",
")",
":",
"flags",
"=",
"set",
"(",
"flags",
")",
"for",
"arg",
"in",
"args",
".",
"keys",
"(",
")",
":",
"try",
":",
"if",
"(",
"Options",
".",
"__options__",
"[",
"arg",
"]",
".",
"is_Flag",
"and",
"(",
"not",
"(",
"arg",
"in",
"flags",
")",
")",
")",
":",
"raise",
"FlagError",
"(",
"(",
"\"'%s' flag is not allowed in this context\"",
"%",
"arg",
")",
")",
"except",
"KeyError",
":",
"raise",
"OptionError",
"(",
"(",
"\"'%s' is not a valid option\"",
"%",
"arg",
")",
")"
] | allow specified flags to be used in the given context . | train | false |
39,156 | def render_message_to_string(subject_template, message_template, param_dict, language=None):
language = (language or settings.LANGUAGE_CODE)
with override_language(language):
return get_subject_and_message(subject_template, message_template, param_dict)
| [
"def",
"render_message_to_string",
"(",
"subject_template",
",",
"message_template",
",",
"param_dict",
",",
"language",
"=",
"None",
")",
":",
"language",
"=",
"(",
"language",
"or",
"settings",
".",
"LANGUAGE_CODE",
")",
"with",
"override_language",
"(",
"language",
")",
":",
"return",
"get_subject_and_message",
"(",
"subject_template",
",",
"message_template",
",",
"param_dict",
")"
] | render a mail subject and message templates using the parameters from param_dict and the given language . | train | false |
39,157 | def _encoding():
encoding = config['terminal_encoding'].get()
if encoding:
return encoding
try:
return (locale.getdefaultlocale()[1] or 'utf8')
except ValueError:
return 'utf8'
| [
"def",
"_encoding",
"(",
")",
":",
"encoding",
"=",
"config",
"[",
"'terminal_encoding'",
"]",
".",
"get",
"(",
")",
"if",
"encoding",
":",
"return",
"encoding",
"try",
":",
"return",
"(",
"locale",
".",
"getdefaultlocale",
"(",
")",
"[",
"1",
"]",
"or",
"'utf8'",
")",
"except",
"ValueError",
":",
"return",
"'utf8'"
] | tries to guess the encoding used by the terminal . | train | false |
39,158 | def _vis_minibatch(im_blob, rois_blob, labels_blob, overlaps):
import matplotlib.pyplot as plt
for i in xrange(rois_blob.shape[0]):
rois = rois_blob[i, :]
im_ind = rois[0]
roi = rois[1:]
im = im_blob[im_ind, :, :, :].transpose((1, 2, 0)).copy()
im += cfg.PIXEL_MEANS
im = im[:, :, (2, 1, 0)]
im = im.astype(np.uint8)
cls = labels_blob[i]
plt.imshow(im)
print 'class: ', cls, ' overlap: ', overlaps[i]
plt.gca().add_patch(plt.Rectangle((roi[0], roi[1]), (roi[2] - roi[0]), (roi[3] - roi[1]), fill=False, edgecolor='r', linewidth=3))
plt.show()
| [
"def",
"_vis_minibatch",
"(",
"im_blob",
",",
"rois_blob",
",",
"labels_blob",
",",
"overlaps",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"for",
"i",
"in",
"xrange",
"(",
"rois_blob",
".",
"shape",
"[",
"0",
"]",
")",
":",
"rois",
"=",
"rois_blob",
"[",
"i",
",",
":",
"]",
"im_ind",
"=",
"rois",
"[",
"0",
"]",
"roi",
"=",
"rois",
"[",
"1",
":",
"]",
"im",
"=",
"im_blob",
"[",
"im_ind",
",",
":",
",",
":",
",",
":",
"]",
".",
"transpose",
"(",
"(",
"1",
",",
"2",
",",
"0",
")",
")",
".",
"copy",
"(",
")",
"im",
"+=",
"cfg",
".",
"PIXEL_MEANS",
"im",
"=",
"im",
"[",
":",
",",
":",
",",
"(",
"2",
",",
"1",
",",
"0",
")",
"]",
"im",
"=",
"im",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
"cls",
"=",
"labels_blob",
"[",
"i",
"]",
"plt",
".",
"imshow",
"(",
"im",
")",
"print",
"'class: '",
",",
"cls",
",",
"' overlap: '",
",",
"overlaps",
"[",
"i",
"]",
"plt",
".",
"gca",
"(",
")",
".",
"add_patch",
"(",
"plt",
".",
"Rectangle",
"(",
"(",
"roi",
"[",
"0",
"]",
",",
"roi",
"[",
"1",
"]",
")",
",",
"(",
"roi",
"[",
"2",
"]",
"-",
"roi",
"[",
"0",
"]",
")",
",",
"(",
"roi",
"[",
"3",
"]",
"-",
"roi",
"[",
"1",
"]",
")",
",",
"fill",
"=",
"False",
",",
"edgecolor",
"=",
"'r'",
",",
"linewidth",
"=",
"3",
")",
")",
"plt",
".",
"show",
"(",
")"
] | visualize a mini-batch for debugging . | train | false |
39,159 | def floating_ip_get_by_address(context, address):
return IMPL.floating_ip_get_by_address(context, address)
| [
"def",
"floating_ip_get_by_address",
"(",
"context",
",",
"address",
")",
":",
"return",
"IMPL",
".",
"floating_ip_get_by_address",
"(",
"context",
",",
"address",
")"
] | get a floating ip by address or raise if it doesnt exist . | train | false |
39,160 | def random_state_data_python(n, random_state=None):
if (not isinstance(random_state, Random)):
random_state = Random(random_state)
maxuint32 = (1 << 32)
return [tuple((random_state.randint(0, maxuint32) for i in range(624))) for i in range(n)]
| [
"def",
"random_state_data_python",
"(",
"n",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"random_state",
",",
"Random",
")",
")",
":",
"random_state",
"=",
"Random",
"(",
"random_state",
")",
"maxuint32",
"=",
"(",
"1",
"<<",
"32",
")",
"return",
"[",
"tuple",
"(",
"(",
"random_state",
".",
"randint",
"(",
"0",
",",
"maxuint32",
")",
"for",
"i",
"in",
"range",
"(",
"624",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]"
] | return a list of tuples that can initialize random . | train | false |
39,164 | def _cached_dfs_serialize(input_object):
if (input_object is None):
return None
input_type = type(input_object)
if (input_type in _BASIC_JSON_TYPES):
return input_object
is_pyrsistent = False
if (input_type in _BASIC_JSON_COLLECTIONS):
obj = input_object
else:
if _is_pyrsistent(input_object):
is_pyrsistent = True
cached_value = _cached_dfs_serialize_cache.get(input_object, _UNCACHED_SENTINEL)
if (cached_value is not _UNCACHED_SENTINEL):
return cached_value
obj = _to_serializables(input_object)
result = obj
obj_type = type(obj)
if (obj_type == dict):
result = dict(((_cached_dfs_serialize(key), _cached_dfs_serialize(value)) for (key, value) in obj.iteritems()))
elif ((obj_type == list) or (obj_type == tuple)):
result = list((_cached_dfs_serialize(x) for x in obj))
if is_pyrsistent:
_cached_dfs_serialize_cache[input_object] = result
return result
| [
"def",
"_cached_dfs_serialize",
"(",
"input_object",
")",
":",
"if",
"(",
"input_object",
"is",
"None",
")",
":",
"return",
"None",
"input_type",
"=",
"type",
"(",
"input_object",
")",
"if",
"(",
"input_type",
"in",
"_BASIC_JSON_TYPES",
")",
":",
"return",
"input_object",
"is_pyrsistent",
"=",
"False",
"if",
"(",
"input_type",
"in",
"_BASIC_JSON_COLLECTIONS",
")",
":",
"obj",
"=",
"input_object",
"else",
":",
"if",
"_is_pyrsistent",
"(",
"input_object",
")",
":",
"is_pyrsistent",
"=",
"True",
"cached_value",
"=",
"_cached_dfs_serialize_cache",
".",
"get",
"(",
"input_object",
",",
"_UNCACHED_SENTINEL",
")",
"if",
"(",
"cached_value",
"is",
"not",
"_UNCACHED_SENTINEL",
")",
":",
"return",
"cached_value",
"obj",
"=",
"_to_serializables",
"(",
"input_object",
")",
"result",
"=",
"obj",
"obj_type",
"=",
"type",
"(",
"obj",
")",
"if",
"(",
"obj_type",
"==",
"dict",
")",
":",
"result",
"=",
"dict",
"(",
"(",
"(",
"_cached_dfs_serialize",
"(",
"key",
")",
",",
"_cached_dfs_serialize",
"(",
"value",
")",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"obj",
".",
"iteritems",
"(",
")",
")",
")",
"elif",
"(",
"(",
"obj_type",
"==",
"list",
")",
"or",
"(",
"obj_type",
"==",
"tuple",
")",
")",
":",
"result",
"=",
"list",
"(",
"(",
"_cached_dfs_serialize",
"(",
"x",
")",
"for",
"x",
"in",
"obj",
")",
")",
"if",
"is_pyrsistent",
":",
"_cached_dfs_serialize_cache",
"[",
"input_object",
"]",
"=",
"result",
"return",
"result"
] | this serializes an input object into something that can be serialized by the python json encoder . | train | false |
39,165 | @with_setup(prepare_stdout)
def test_output_background_with_success_colorless():
from lettuce import step
line = currentframe().f_lineno
@step(u'the variable "(\\w+)" holds (\\d+)')
@step(u'the variable "(\\w+)" is equal to (\\d+)')
def just_pass(step, *args):
pass
filename = bg_feature_name('simple')
runner = Runner(filename, verbosity=3, no_color=True)
runner.run()
assert_stdout_lines('\nFeature: Simple and successful # tests/functional/bg_features/simple/simple.feature:1\n As the Lettuce maintainer # tests/functional/bg_features/simple/simple.feature:2\n In order to make sure the output is pretty # tests/functional/bg_features/simple/simple.feature:3\n I want to automate its test # tests/functional/bg_features/simple/simple.feature:4\n\n Background:\n Given the variable "X" holds 2 # tests/functional/test_runner.py:{line}\n\n Scenario: multiplication changing the value # tests/functional/bg_features/simple/simple.feature:9\n Given the variable "X" is equal to 2 # tests/functional/test_runner.py:{line}\n\n1 feature (1 passed)\n1 scenario (1 passed)\n1 step (1 passed)\n'.format(line=(line + 2)))
| [
"@",
"with_setup",
"(",
"prepare_stdout",
")",
"def",
"test_output_background_with_success_colorless",
"(",
")",
":",
"from",
"lettuce",
"import",
"step",
"line",
"=",
"currentframe",
"(",
")",
".",
"f_lineno",
"@",
"step",
"(",
"u'the variable \"(\\\\w+)\" holds (\\\\d+)'",
")",
"@",
"step",
"(",
"u'the variable \"(\\\\w+)\" is equal to (\\\\d+)'",
")",
"def",
"just_pass",
"(",
"step",
",",
"*",
"args",
")",
":",
"pass",
"filename",
"=",
"bg_feature_name",
"(",
"'simple'",
")",
"runner",
"=",
"Runner",
"(",
"filename",
",",
"verbosity",
"=",
"3",
",",
"no_color",
"=",
"True",
")",
"runner",
".",
"run",
"(",
")",
"assert_stdout_lines",
"(",
"'\\nFeature: Simple and successful # tests/functional/bg_features/simple/simple.feature:1\\n As the Lettuce maintainer # tests/functional/bg_features/simple/simple.feature:2\\n In order to make sure the output is pretty # tests/functional/bg_features/simple/simple.feature:3\\n I want to automate its test # tests/functional/bg_features/simple/simple.feature:4\\n\\n Background:\\n Given the variable \"X\" holds 2 # tests/functional/test_runner.py:{line}\\n\\n Scenario: multiplication changing the value # tests/functional/bg_features/simple/simple.feature:9\\n Given the variable \"X\" is equal to 2 # tests/functional/test_runner.py:{line}\\n\\n1 feature (1 passed)\\n1 scenario (1 passed)\\n1 step (1 passed)\\n'",
".",
"format",
"(",
"line",
"=",
"(",
"line",
"+",
"2",
")",
")",
")"
] | a feature with background should print it accordingly under verbosity 3 . | train | false |
39,166 | def print_matrix(matrix):
matrixT = [[] for x in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrixT[j].append(len(str(matrix[i][j])))
ndigits = [max(x) for x in matrixT]
for i in range(len(matrix)):
print(' '.join((('%*s ' % (ndigits[j], matrix[i][j])) for j in range(len(matrix[i])))))
| [
"def",
"print_matrix",
"(",
"matrix",
")",
":",
"matrixT",
"=",
"[",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"matrix",
"[",
"0",
"]",
")",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"matrix",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"matrix",
"[",
"i",
"]",
")",
")",
":",
"matrixT",
"[",
"j",
"]",
".",
"append",
"(",
"len",
"(",
"str",
"(",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
")",
"ndigits",
"=",
"[",
"max",
"(",
"x",
")",
"for",
"x",
"in",
"matrixT",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"matrix",
")",
")",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"(",
"(",
"'%*s '",
"%",
"(",
"ndigits",
"[",
"j",
"]",
",",
"matrix",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"matrix",
"[",
"i",
"]",
")",
")",
")",
")",
")"
] | print_matrix print out a matrix . | train | false |
39,167 | def select_child(cache, left, right):
right = (always_in if (right is None) else frozenset(right))
for parent in left:
for child in cache.iterchildren(parent):
if (child in right):
(yield child)
| [
"def",
"select_child",
"(",
"cache",
",",
"left",
",",
"right",
")",
":",
"right",
"=",
"(",
"always_in",
"if",
"(",
"right",
"is",
"None",
")",
"else",
"frozenset",
"(",
"right",
")",
")",
"for",
"parent",
"in",
"left",
":",
"for",
"child",
"in",
"cache",
".",
"iterchildren",
"(",
"parent",
")",
":",
"if",
"(",
"child",
"in",
"right",
")",
":",
"(",
"yield",
"child",
")"
] | right is an immediate child of left . | train | false |
39,169 | def print_job(jid, ext_source=None):
ret = {}
returner = _get_returner((__opts__['ext_job_cache'], ext_source, __opts__['master_job_cache']))
mminion = salt.minion.MasterMinion(__opts__)
try:
job = mminion.returners['{0}.get_load'.format(returner)](jid)
ret[jid] = _format_jid_instance(jid, job)
except TypeError:
ret[jid]['Result'] = 'Requested returner {0} is not available. Jobs cannot be retrieved. Check master log for details.'.format(returner)
return ret
ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)
fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
if (__opts__.get('job_cache_store_endtime') and (fstr in mminion.returners)):
endtime = mminion.returners[fstr](jid)
if endtime:
ret[jid]['EndTime'] = endtime
return ret
| [
"def",
"print_job",
"(",
"jid",
",",
"ext_source",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"returner",
"=",
"_get_returner",
"(",
"(",
"__opts__",
"[",
"'ext_job_cache'",
"]",
",",
"ext_source",
",",
"__opts__",
"[",
"'master_job_cache'",
"]",
")",
")",
"mminion",
"=",
"salt",
".",
"minion",
".",
"MasterMinion",
"(",
"__opts__",
")",
"try",
":",
"job",
"=",
"mminion",
".",
"returners",
"[",
"'{0}.get_load'",
".",
"format",
"(",
"returner",
")",
"]",
"(",
"jid",
")",
"ret",
"[",
"jid",
"]",
"=",
"_format_jid_instance",
"(",
"jid",
",",
"job",
")",
"except",
"TypeError",
":",
"ret",
"[",
"jid",
"]",
"[",
"'Result'",
"]",
"=",
"'Requested returner {0} is not available. Jobs cannot be retrieved. Check master log for details.'",
".",
"format",
"(",
"returner",
")",
"return",
"ret",
"ret",
"[",
"jid",
"]",
"[",
"'Result'",
"]",
"=",
"mminion",
".",
"returners",
"[",
"'{0}.get_jid'",
".",
"format",
"(",
"returner",
")",
"]",
"(",
"jid",
")",
"fstr",
"=",
"'{0}.get_endtime'",
".",
"format",
"(",
"__opts__",
"[",
"'master_job_cache'",
"]",
")",
"if",
"(",
"__opts__",
".",
"get",
"(",
"'job_cache_store_endtime'",
")",
"and",
"(",
"fstr",
"in",
"mminion",
".",
"returners",
")",
")",
":",
"endtime",
"=",
"mminion",
".",
"returners",
"[",
"fstr",
"]",
"(",
"jid",
")",
"if",
"endtime",
":",
"ret",
"[",
"jid",
"]",
"[",
"'EndTime'",
"]",
"=",
"endtime",
"return",
"ret"
] | print a specific jobs detail given by its jid . | train | true |
39,170 | def libvlc_set_user_agent(p_instance, name, http):
f = (_Cfunctions.get('libvlc_set_user_agent', None) or _Cfunction('libvlc_set_user_agent', ((1,), (1,), (1,)), None, None, Instance, ctypes.c_char_p, ctypes.c_char_p))
return f(p_instance, name, http)
| [
"def",
"libvlc_set_user_agent",
"(",
"p_instance",
",",
"name",
",",
"http",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_set_user_agent'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_set_user_agent'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
")",
",",
"None",
",",
"None",
",",
"Instance",
",",
"ctypes",
".",
"c_char_p",
",",
"ctypes",
".",
"c_char_p",
")",
")",
"return",
"f",
"(",
"p_instance",
",",
"name",
",",
"http",
")"
] | sets the application name . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.