def shortest_string(self):
"""
Uses BFS in order to find the shortest string
Args:
None
Returns:
str: The shortest string
"""
initialstates = sorted(
self.states,
key=attrgetter('initial'),
reverse=True)
if len(initialstates) > 0:
return bfs(self, initialstates[0])
else:
return None
python类attrgetter()的实例源码
def shortest_string(self):
"""
Uses BFS in order to find the shortest string
Args:
None
Returns:
str: The shortest string
"""
initialstates = sorted(
self.states,
key=attrgetter('initial'),
reverse=True)
if len(initialstates) > 0:
return bfs(self, initialstates[0])
else:
return None
def shortest_string(self):
"""
Uses BFS in order to find the shortest string
Args:
None
Returns:
str: The shortest string
"""
initialstates = sorted(
self.states,
key=attrgetter('initial'),
reverse=True)
if len(initialstates) > 0:
return bfs(self, initialstates[0])
else:
return None
def init_from_acceptor(self, acceptor):
"""
Adds a sink state
Args:
alphabet (list): The input alphabet
Returns:
None
"""
states = sorted(
acceptor.states,
key=attrgetter('initial'),
reverse=True)
for state in states:
for arc in state.arcs:
itext = acceptor.isyms.find(arc.ilabel)
if itext in self.alphabet:
self.add_arc(state.stateid, arc.nextstate, itext)
if state.final:
self[state.stateid].final = True
if state.initial:
self[state.stateid].initial = True
def consume_input(self, inp):
"""
Return True/False if the machine accepts/reject the input.
Args:
inp (str): input string to be consumed
Returns:
bool: A true or false value depending on if the DFA
accepts the provided input
"""
cur_state = sorted(
self.states,
key=attrgetter('initial'),
reverse=True)[0]
while len(inp) > 0:
found = False
for arc in cur_state.arcs:
if self.isyms.find(arc.ilabel) == inp[0]:
cur_state = self[arc.nextstate]
inp = inp[1:]
found = True
break
if not found:
return False
return cur_state.final != TropicalWeight(float('inf'))
def save(self, txt_fst_filename):
"""
Save the machine in the openFST format in the file denoted by
txt_fst_filename.
Args:
txt_fst_filename (str): The name of the file
Returns:
None
"""
txt_fst = open(txt_fst_filename, 'w+')
states = sorted(self.states, key=attrgetter('initial'), reverse=True)
for state in states:
for arc in state.arcs:
itext = self.isyms.find(arc.ilabel)
otext = self.osyms.find(arc.ilabel)
txt_fst.write(
'{}\t{}\t{}\t{}\n'.format(
state.stateid,
arc.nextstate,
itext.encode('hex'),
otext.encode('hex')))
if state.final:
txt_fst.write('{}\n'.format(state.stateid))
txt_fst.close()
def consume_input(self, inp):
"""
Return True/False if the machine accepts/reject the input.
Args:
inp (str): input string to be consumed
Returns:
bool: A true or false value depending on if the DFA
accepts the provided input
"""
cur_state = sorted(
self.states,
key=attrgetter('initial'),
reverse=True)[0]
while len(inp) > 0:
found = False
for arc in cur_state.arcs:
if self.isyms.find(arc.ilabel) == inp[0]:
cur_state = self[arc.nextstate]
inp = inp[1:]
found = True
break
if not found:
return False
return cur_state.final
def save(self, txt_fst_file_name):
"""
Save the machine in the openFST format in the file denoted by
txt_fst_file_name.
Args:
txt_fst_file_name (str): The output file
Returns:
None
"""
output_filename = open(txt_fst_file_name, 'w+')
states = sorted(self.states, key=attrgetter('initial'), reverse=True)
for state in states:
for arc in state.arcs:
itext = self.isyms.find(arc.ilabel)
otext = self.osyms.find(arc.ilabel)
output_filename.write(
'{}\t{}\t{}\t{}\n'.format(
state.stateid,
arc.nextstate,
itext.encode('hex'),
otext.encode('hex')))
if state.final:
output_filename.write('{}\n'.format(state.stateid))
output_filename.close()
def qtproperty(name, unwrap=lambda x: x, wrap=lambda x: x):
"""
Expose a property of an attribute that respects Qt's get/setter
conventions.
If transform is defined, it is applied to the value passed to the setter
method.
Example::
class MyObj:
title = qtproperty('_widget.title')
"""
prop, action = name.split('.')
set_name = '%s.set%s' % (prop, action.title())
getter = op.attrgetter(name)
setter = op.attrgetter(set_name)
return property(
lambda x: unwrap(getter(x)()),
lambda x, v: setter(x)(wrap(v)),
)
def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
def run(self):
installed_dists = self.install_dists(self.distribution)
cmd = ' '.join(self._argv)
if self.dry_run:
self.announce('skipping "%s" (dry run)' % cmd)
return
self.announce('running "%s"' % cmd)
paths = map(operator.attrgetter('location'), installed_dists)
with self.paths_on_pythonpath(paths):
with self.project_on_sys_path():
self.run_tests()
def execute(self, context):
selection = sorted(bpy.context.selected_sequences, key=attrgetter('frame_final_start'))
time_move = selection[0].frame_final_start - bpy.context.scene.frame_current
selection = reversed(selection)
empty_channel = find_empty_channel()
for s in selection:
if s.type in SequenceTypes.VIDEO or s.type in SequenceTypes.IMAGE or s.type in SequenceTypes.SOUND:
s.frame_start -= time_move
return {'FINISHED'}
def load_feeds(self):
with concurrent.futures.ProcessPoolExecutor() as executor:
feeds = executor.map(scrape_rss, self.feed_manager.get_feeds())
frontpage_entries = []
for feed in feeds:
feed.entries = feed.entries[:10] # Only get 1st 10
GLib.idle_add(self.add_new_feed_tab, feed.feed.title, feed.entries)
# Load into frontpage-o
frontpage_entries.extend(feed.entries)
frontpage_entries = sorted(frontpage_entries, key=operator.attrgetter('updated'))
GLib.idle_add(self.add_new_feed_tab, "Frontpage", frontpage_entries)
def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
def add(self, dist):
"""Add `dist` if we ``can_add()`` it and it has not already been added
"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key, [])
if dist not in dists:
dists.append(dist)
dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
def run(self):
installed_dists = self.install_dists(self.distribution)
cmd = ' '.join(self._argv)
if self.dry_run:
self.announce('skipping "%s" (dry run)' % cmd)
return
self.announce('running "%s"' % cmd)
paths = map(operator.attrgetter('location'), installed_dists)
with self.paths_on_pythonpath(paths):
with self.project_on_sys_path():
self.run_tests()
def extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 0700
self.extract(tarinfo, path)
# Reverse sort directories.
directories.sort(key=operator.attrgetter('name'))
directories.reverse()
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError, e:
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
def getvalue(self, key, default=None):
"""Dictionary style get() method, including 'value' lookup."""
if key in self:
value = self[key]
if type(value) is type([]):
return map(attrgetter('value'), value)
else:
return value.value
else:
return default
def getlist(self, key):
""" Return list of received values."""
if key in self:
value = self[key]
if type(value) is type([]):
return map(attrgetter('value'), value)
else:
return [value.value]
else:
return []