本文整理匯總了Python中__builtin__.len方法的典型用法代碼示例。如果您正苦於以下問題:Python __builtin__.len方法的具體用法?Python __builtin__.len怎麽用?Python __builtin__.len使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類__builtin__
的用法示例。
在下文中一共展示了__builtin__.len方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _get_conditional_content
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _get_conditional_content(self, fname, spans, conditions, contents):
out = []
ieval = []
peval = []
multiline = (spans[0][0] != spans[-1][1])
for condition, content, span in zip(conditions, contents, spans):
try:
cond = bool(self._evaluate(condition, fname, span[0]))
except Exception as exc:
msg = "exception occurred when evaluating '{0}'"\
.format(condition)
raise FyppFatalError(msg, fname, span, exc)
if cond:
if self._linenums and not self._diverted and multiline:
out.append(linenumdir(span[1], fname))
outcont, ievalcont, pevalcont = self._render(content)
ieval += _shiftinds(ievalcont, len(out))
peval += pevalcont
out += outcont
break
if self._linenums and not self._diverted and multiline:
out.append(linenumdir(spans[-1][1], fname))
return out, ieval, peval
示例2: __init__
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def __init__(self, maxlen=132, indent=4, method='smart', prefix='&',
suffix='&'):
# Line length should be long enough that contintuation lines can host at
# east one character apart of indentation and two continuation signs
minmaxlen = indent + len(prefix) + len(suffix) + 1
if maxlen < minmaxlen:
msg = 'Maximal line length less than {0} when using an indentation'\
' of {1}'.format(minmaxlen, indent)
raise FyppFatalError(msg)
self._maxlen = maxlen
self._indent = indent
self._prefix = ' ' * self._indent + prefix
self._suffix = suffix
if method not in ['brute', 'smart', 'simple']:
raise FyppFatalError('invalid folding type')
if method == 'brute':
self._inherit_indent = False
self._fold_position_finder = self._get_maximal_fold_pos
elif method == 'simple':
self._inherit_indent = True
self._fold_position_finder = self._get_maximal_fold_pos
elif method == 'smart':
self._inherit_indent = True
self._fold_position_finder = self._get_smart_fold_pos
示例3: run_fypp
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def run_fypp():
'''Run the Fypp command line tool.'''
options = FyppOptions()
optparser = get_option_parser()
opts, leftover = optparser.parse_args(values=options)
infile = leftover[0] if len(leftover) > 0 else '-'
outfile = leftover[1] if len(leftover) > 1 else '-'
try:
tool = Fypp(opts)
tool.process_file(infile, outfile)
except FyppStopRequest as exc:
sys.stderr.write(_formatted_exception(exc))
sys.exit(USER_ERROR_EXIT_CODE)
except FyppFatalError as exc:
sys.stderr.write(_formatted_exception(exc))
sys.exit(ERROR_EXIT_CODE)
示例4: _get_callable_argspec_py2
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _get_callable_argspec_py2(func):
argspec = inspect.getargspec(func)
varpos = argspec.varargs
varkw = argspec.keywords
args = argspec.args
tuplearg = False
for elem in args:
tuplearg = tuplearg or isinstance(elem, list)
if tuplearg:
msg = 'tuple argument(s) found'
raise FyppFatalError(msg)
defaults = {}
if argspec.defaults is not None:
for ind, default in enumerate(argspec.defaults):
iarg = len(args) - len(argspec.defaults) + ind
defaults[args[iarg]] = default
return args, defaults, varpos, varkw
示例5: len
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def len(obj):
try:
return _len(obj)
except TypeError:
try:
# note: this is an internal undocumented API,
# don't rely on it in your own programs
return obj.__length_hint__()
except AttributeError:
raise TypeError
示例6: __UpdateAllVariables
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def __UpdateAllVariables(self, NId, Objective):
if NId in self.node_objectives:
# First, remove the Variables from the old Objective.
old_obj = self.node_objectives[NId]
self.all_variables = self.all_variables - set(old_obj.variables())
# Check that the Variables of the new Objective are not currently
# in other Objectives.
new_variables = set(Objective.variables())
if __builtin__.len(self.all_variables.intersection(new_variables)) != 0:
raise Exception('Objective at NId %d shares a variable.' % NId)
self.all_variables = self.all_variables | new_variables
# Helper method to get CVXPY Variables out of a CVXPY Objective
示例7: ADMM_x
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def ADMM_x(entry):
global rho
variables = entry[X_VARS]
#-----------------------Proximal operator ---------------------------
x_update = [] # proximal update for the variable x
if(__builtin__.len(entry[1].args) > 1 ):
# print 'we are in logdet + trace node'
cvxpyMat = entry[1].args[1].args[0].args[0]
numpymat = cvxpyMat.value
mat_shape = ( int( numpymat.shape[1] * ( numpymat.shape[1]+1 )/2.0 ) ,)
a = numpy.zeros(mat_shape)
for i in xrange(entry[X_DEG]):
z_index = X_NEIGHBORS + (2 * i)
u_index = z_index + 1
zi = entry[z_index]
ui = entry[u_index]
for (varID, varName, var, offset) in variables:
z = getValue(edge_z_vals, zi + offset, var.size[0])
u = getValue(edge_u_vals, ui + offset, var.size[0])
a += (z-u)
A = upper2Full(a)
A = A/entry[X_DEG]
eta = 1/float(rho)
x_update = Prox_logdet(numpymat, A, eta)
solution = numpy.array(x_update).T.reshape(-1)
writeValue(node_vals, entry[X_IND] + variables[0][3], solution, variables[0][2].size[0])
else:
x_update = [] # no variable to update for dummy node
return None
# z-update for ADMM for one edge
示例8: handle_include
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def handle_include(self, span, fname):
'''Should be called to signalize change to new file.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file to be included.
'''
self._path.append(self._curnode)
self._curnode = []
self._open_blocks.append(
('include', self._curfile, [span], fname, None))
self._curfile = fname
self._nr_prev_blocks.append(len(self._open_blocks))
示例9: handle_endinclude
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def handle_endinclude(self, span, fname):
'''Should be called when processing of a file finished.
Args:
span (tuple of int): Start and end line of the include directive
or None if called the first time for the main input.
fname (str): Name of the file which has been included.
'''
nprev_blocks = self._nr_prev_blocks.pop(-1)
if len(self._open_blocks) > nprev_blocks:
directive, fname, spans = self._open_blocks[-1][0:3]
msg = '{0} directive still unclosed when reaching end of file'\
.format(directive)
raise FyppFatalError(msg, self._curfile, spans[0])
block = self._open_blocks.pop(-1)
directive, blockfname, spans = block[0:3]
if directive != 'include':
msg = 'internal error: last open block is not \'include\' when '\
'closing file \'{0}\''.format(fname)
raise FyppFatalError(msg)
if span != spans[0]:
msg = 'internal error: span for include and endinclude differ ('\
'{0} vs {1}'.format(span, spans[0])
raise FyppFatalError(msg)
oldfname, _ = block[3:5]
if fname != oldfname:
msg = 'internal error: mismatching file name in close_file event'\
" (expected: '{0}', got: '{1}')".format(oldfname, fname)
raise FyppFatalError(msg, fname)
block = directive, blockfname, spans, fname, self._curnode
self._curnode = self._path.pop(-1)
self._curnode.append(block)
self._curfile = blockfname
示例10: handle_endcall
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def handle_endcall(self, span, name, blockcall):
'''Should be called to signalize an endcall directive.
Args:
span (tuple of int): Start and end line of the directive.
name (str): Name of the endcall statement. Could be None, if endcall
was specified without name.
blockcall (bool): Whether the alternative "block / contains /
endblock" calling directive has been used.
'''
self._check_for_open_block(span, 'endcall')
block = self._open_blocks.pop(-1)
directive, fname, spans = block[0:3]
callname, callargexpr, args, argnames = block[3:7]
if blockcall:
opened, current = 'block', 'endblock'
else:
opened, current = 'call', 'endcall'
self._check_if_matches_last(directive, opened, spans[0], span, current)
if name is not None and name != callname:
msg = "wrong name in {0} directive "\
"(expected '{1}', got '{2}')".format(current, callname, name)
raise FyppFatalError(msg, fname, span)
args.append(self._curnode)
# If nextarg or endcall immediately followed call, then first argument
# is empty and should be removed (to allow for calls without arguments
# and named first argument in calls)
if args and not args[0]:
if len(argnames) == len(args):
del argnames[0]
del args[0]
del spans[1]
spans.append(span)
block = (directive, fname, spans, callname, callargexpr, args, argnames)
self._curnode = self._path.pop(-1)
self._curnode.append(block)
示例11: _check_for_open_block
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _check_for_open_block(self, span, directive):
if len(self._open_blocks) <= self._nr_prev_blocks[-1]:
msg = 'unexpected {0} directive'.format(directive)
raise FyppFatalError(msg, self._curfile, span)
示例12: _get_iterated_content
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _get_iterated_content(self, fname, spans, loopvars, loopiter, content):
out = []
ieval = []
peval = []
try:
iterobj = iter(self._evaluate(loopiter, fname, spans[0][0]))
except Exception as exc:
msg = "exception occurred when evaluating '{0}'"\
.format(loopiter)
raise FyppFatalError(msg, fname, spans[0], exc)
multiline = (spans[0][0] != spans[-1][1])
for var in iterobj:
if len(loopvars) == 1:
self._define(loopvars[0], var)
else:
for varname, value in zip(loopvars, var):
self._define(varname, value)
if self._linenums and not self._diverted and multiline:
out.append(linenumdir(spans[0][1], fname))
outcont, ievalcont, pevalcont = self._render(content)
ieval += _shiftinds(ievalcont, len(out))
peval += pevalcont
out += outcont
if self._linenums and not self._diverted and multiline:
out.append(linenumdir(spans[1][1], fname))
return out, ieval, peval
示例13: _get_call_arguments
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _get_call_arguments(self, fname, spans, argexpr, contents, argnames):
if argexpr is None:
posargs = []
kwargs = {}
else:
# Parse and evaluate arguments passed in call header
self._evaluator.openscope()
try:
posargs, kwargs = self._evaluate(
'__getargvalues(' + argexpr + ')', fname, spans[0][0])
except Exception as exc:
msg = "unable to parse argument expression '{0}'"\
.format(argexpr)
raise FyppFatalError(msg, fname, spans[0], exc)
self._evaluator.closescope()
# Render arguments passed in call body
args = []
for content in contents:
self._evaluator.openscope()
rendered = self.render(content, divert=True)
self._evaluator.closescope()
if rendered.endswith('\n'):
rendered = rendered[:-1]
args.append(rendered)
# Separate arguments in call body into positional and keyword ones:
if argnames:
posargs += args[:len(args) - len(argnames)]
offset = len(args) - len(argnames)
for iargname, argname in enumerate(argnames):
ind = offset + iargname
if argname in kwargs:
msg = "keyword argument '{0}' already defined"\
.format(argname)
raise FyppFatalError(msg, fname, spans[ind + 1])
kwargs[argname] = args[ind]
else:
posargs += args
return posargs, kwargs
示例14: _get_included_content
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _get_included_content(self, fname, spans, includefname, content):
includefile = spans[0] is not None
out = []
if self._linenums and not self._diverted:
if includefile or self._linenum_gfortran5:
out += linenumdir(0, includefname, _LINENUM_NEW_FILE)
else:
out += linenumdir(0, includefname)
outcont, ieval, peval = self._render(content)
ieval = _shiftinds(ieval, len(out))
out += outcont
if self._linenums and not self._diverted and includefile:
out += linenumdir(spans[0][1], fname, _LINENUM_RETURN_TO_FILE)
return out, ieval, peval
示例15: _find_next_eol
# 需要導入模塊: import __builtin__ [as 別名]
# 或者: from __builtin__ import len [as 別名]
def _find_next_eol(output, ind):
'Find last newline before current position.'
# find first eol after expr. evaluation
inext = ind + 1
while inext < len(output):
eolnext = output[inext].find('\n')
if eolnext != -1:
break
inext += 1
else:
inext = len(output) - 1
eolnext = len(output[-1]) - 1
return inext, eolnext