def test_subsequent_indent(self):
# Test subsequent_indent parameter
expect = '''\
* This paragraph will be filled, first
without any indentation, and then
with some (including a hanging
indent).'''
result = fill(self.text, 40,
initial_indent=" * ", subsequent_indent=" ")
self.check(result, expect)
# Despite the similar names, DedentTestCase is *not* the inverse
# of IndentTestCase!
python类fill()的实例源码
def wrap_function_name(self, name):
"""Split the function name on multiple lines."""
if len(name) > 32:
ratio = 2.0/3.0
height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
width = max(len(name)/height, 32)
# TODO: break lines in symbols
name = textwrap.fill(name, width, break_long_words=False)
# Take away spaces
name = name.replace(", ", ",")
name = name.replace("> >", ">>")
name = name.replace("> >", ">>") # catch consecutive
return name
def store_dict_as_FASTA_file(d, output_file_path, report_unique_sequences=False, wrap_from=200):
filesnpaths.is_output_file_writable(output_file_path)
output = open(output_file_path, 'w')
props_h = sorted(list(list(d.values())[0]['props'].keys()))
if report_unique_sequences:
seqs_sorted_by_frequency = [x[1] for x in sorted([(len(d[seq]['ids']), seq) for seq in d], reverse=True)]
for seq in seqs_sorted_by_frequency:
frequency = len(d[seq]['ids'])
seq_id = d[seq]['ids'].pop()
output.write('>%s %s|frequency:%d\n' % (seq_id, '|'.join(['%s:%s' % (t[0], t[1]) for t in d[seq]['props'].items()]), frequency))
output.write('%s\n' % textwrap.fill(seq, wrap_from, break_on_hyphens=False))
else:
for seq in d:
props = '|'.join(['%s:%s' % (t[0], t[1]) for t in d[seq]['props'].items()])
for seq_id in d[seq]['ids']:
output.write('>%s %s\n' % (seq_id, props))
output.write('%s\n' % textwrap.fill(seq, wrap_from, break_on_hyphens=False))
output.close()
return True
def __str__(self):
"""Returns a user-readable docstring for this function."""
DOCSTRING_WIDTH = 75
signature = self.getSignature()
parts = []
if 'description' in signature:
parts.append(
textwrap.fill(signature['description'], width=DOCSTRING_WIDTH))
args = signature['args']
if args:
parts.append('')
parts.append('Args:')
for arg in args:
name_part = ' ' + arg['name']
if 'description' in arg:
name_part += ': '
arg_header = name_part + arg['description']
else:
arg_header = name_part
arg_doc = textwrap.fill(arg_header,
width=DOCSTRING_WIDTH - len(name_part),
subsequent_indent=' ' * 6)
parts.append(arg_doc)
return u'\n'.join(parts).encode('utf8')
def test_subsequent_indent(self):
# Test subsequent_indent parameter
expect = '''\
* This paragraph will be filled, first
without any indentation, and then
with some (including a hanging
indent).'''
result = fill(self.text, 40,
initial_indent=" * ", subsequent_indent=" ")
self.check(result, expect)
# Despite the similar names, DedentTestCase is *not* the inverse
# of IndentTestCase!
def executable_path():
"""Determines the value to use for SSH_ASKPASS.
The value is cached since this may be called many times.
"""
global _executable_path
if _executable_path is None:
for path in ASKPASS_PATHS:
if os.access(path, os.X_OK):
_executable_path = path
break
else:
_executable_path = ''
sys.stderr.write(textwrap.fill("Warning: could not find an"
" executable path for askpass because PSSH was not"
" installed correctly. Password prompts will not work."))
sys.stderr.write('\n')
return _executable_path
def start(self, iomap, backlog):
"""Prompts for the password, creates a socket, and starts listening.
The specified backlog should be the max number of clients connecting
at once.
"""
message = ('Warning: do not enter your password if anyone else has'
' superuser privileges or access to your account.')
print(textwrap.fill(message))
self.password = getpass.getpass()
# Note that according to the docs for mkdtemp, "The directory is
# readable, writable, and searchable only by the creating user."
self.tempdir = tempfile.mkdtemp(prefix='pssh.')
self.address = os.path.join(self.tempdir, 'pssh_askpass_socket')
self.sock = socket.socket(socket.AF_UNIX)
psshutil.set_cloexec(self.sock)
self.sock.bind(self.address)
self.sock.listen(backlog)
iomap.register_read(self.sock.fileno(), self.handle_listen)
def wrap_function_name(self, name):
"""Split the function name on multiple lines."""
if len(name) > 32:
ratio = 2.0/3.0
height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
width = max(len(name)/height, 32)
# TODO: break lines in symbols
name = textwrap.fill(name, width, break_long_words=False)
# Take away spaces
name = name.replace(", ", ",")
name = name.replace("> >", ">>")
name = name.replace("> >", ">>") # catch consecutive
return name
def print_help(self):
""" Print make help """
import textwrap as _textwrap
targets = self.targetinfo()
keys = []
for key, info in targets.items():
if not info['hide']:
keys.append(key)
keys.sort()
length = max(map(len, keys))
info = []
for key in keys:
info.append("%s%s" % (
(key + " " * length)[:length + 2],
_textwrap.fill(
targets[key]['desc'].strip(),
subsequent_indent=" " * (length + 2)
),
))
print "Available targets:\n\n" + "\n".join(info)
def print_help(self):
""" Print make help """
import textwrap as _textwrap
targets = self.targetinfo()
keys = []
for key, info in list(targets.items()):
if not info['hide']:
keys.append(key)
keys.sort()
length = max(list(map(len, keys)))
info = []
for key in keys:
info.append("%s%s" % (
(key + " " * length)[:length + 2],
_textwrap.fill(
targets[key]['desc'].strip(),
subsequent_indent=" " * (length + 2)
),
))
print("Available targets:\n\n" + "\n".join(info))
verbnet.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def pprint_subclasses(self, vnclass, indent=''):
"""
Return a string containing a pretty-printed representation of
the given verbnet class's subclasses.
:param vnclass: A verbnet class identifier; or an ElementTree
containing the xml contents of a verbnet class.
"""
if isinstance(vnclass, compat.string_types):
vnclass = self.vnclass(vnclass)
subclasses = [subclass.get('ID') for subclass in
vnclass.findall('SUBCLASSES/VNSUBCLASS')]
if not subclasses: subclasses = ['(none)']
s = 'Subclasses: ' + ' '.join(subclasses)
return textwrap.fill(s, 70, initial_indent=indent,
subsequent_indent=indent+' ')
verbnet.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def pprint_members(self, vnclass, indent=''):
"""
Return a string containing a pretty-printed representation of
the given verbnet class's member verbs.
:param vnclass: A verbnet class identifier; or an ElementTree
containing the xml contents of a verbnet class.
"""
if isinstance(vnclass, compat.string_types):
vnclass = self.vnclass(vnclass)
members = [member.get('name') for member in
vnclass.findall('MEMBERS/MEMBER')]
if not members: members = ['(none)']
s = 'Members: ' + ' '.join(members)
return textwrap.fill(s, 70, initial_indent=indent,
subsequent_indent=indent+' ')
internals.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def _add_epytext_field(obj, field, message):
"""Add an epytext @field to a given object's docstring."""
indent = ''
# If we already have a docstring, then add a blank line to separate
# it from the new field, and check its indentation.
if obj.__doc__:
obj.__doc__ = obj.__doc__.rstrip()+'\n\n'
indents = re.findall(r'(?<=\n)[ ]+(?!\s)', obj.__doc__.expandtabs())
if indents: indent = min(indents)
# If we don't have a docstring, add an empty one.
else:
obj.__doc__ = ''
obj.__doc__ += textwrap.fill('@%s: %s' % (field, message),
initial_indent=indent,
subsequent_indent=indent+' ')
brill_trainer.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def _trace_rule(self, rule):
assert self._rule_scores[rule] == sum(self._positions_by_rule[rule].values())
changes = self._positions_by_rule[rule].values()
num_fixed = len([c for c in changes if c == 1])
num_broken = len([c for c in changes if c == -1])
num_other = len([c for c in changes if c == 0])
score = self._rule_scores[rule]
rulestr = rule.format(self._ruleformat)
if self._trace > 2:
print('%4d%4d%4d%4d |' % (score, num_fixed, num_broken, num_other), end=' ')
print(textwrap.fill(rulestr, initial_indent=' '*20, width=79,
subsequent_indent=' '*18+'| ').strip())
else:
print(rulestr)
def display_iam_user_permissions_table(self,
user_name,
profile_perms):
'''
Display tabular format
'''
table = prettytable.PrettyTable()
table.add_column("User Name", [user_name])
for profile in profile_perms.keys():
if profile_perms[profile] is None:
continue
statementstr = ""
for statement in profile_perms[profile]:
resources = statement['Resource']
actions = statement.get('Action', None)
if not actions:
actions = statement.get('NotAction', None)
effect = statement['Effect']
#statementstr = statementstr + "-" * 29 + "\n"
tempstr = "Resources: " + str(resources)
statementstr = statementstr + self.fillstr(tempstr, 30)
tempstr = "Actions: " + \
str(actions)
statementstr = statementstr + self.fillstr(tempstr, 30)
tempstr = "Effect: " + \
str(effect)
statementstr = statementstr + self.fillstr(tempstr, 30)
statementstr = statementstr + "-" * 29 + "\n"
statementstr = textwrap.fill(statementstr, 34)
table.add_column(profile, [statementstr], align="l")
print table
def display_iam_user_policies_table(self,
user_name,
policyinfo):
'''
Display user policy info in tabular format
'''
table = prettytable.PrettyTable()
table.add_column("User Name", [user_name])
for profile in policyinfo.keys():
if policyinfo[profile] is None:
continue
policystr = ""
for policy in policyinfo[profile]:
policyname = policy['PolicyName']
policy_type = policy['type']
tempstr = "Name: " + policyname
policystr = policystr + self.fillstr(tempstr, 30)
tempstr = "Type: " + policy_type
policystr = policystr + self.fillstr(tempstr, 30)
policystr = textwrap.fill(policystr, 34)
table.add_column(profile, [policystr], align="l")
print table
def _format_text(self, text):
"""
Format a paragraph of free-form text for inclusion in the
help output at the current indentation level.
"""
text_width = self.width - self.current_indent
indent = " "*self.current_indent
return textwrap.fill(text,
text_width,
initial_indent=indent,
subsequent_indent=indent)