本文整理汇总了Python中collections.ChainMap.get方法的典型用法代码示例。如果您正苦于以下问题:Python ChainMap.get方法的具体用法?Python ChainMap.get怎么用?Python ChainMap.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类collections.ChainMap
的用法示例。
在下文中一共展示了ChainMap.get方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: store_selections
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
def store_selections(view, selections, replace=False, **settings):
"""
Save selections to storage.
"""
id = get_id(settings)
if not replace:
# Add old selections to selections, so as not to remove them
selections = list(chain(selections, view.get_regions(id)))
# Filter "settings" to only have "flags", "scope" and "icon"
filtered = {"flags": parse_flags(**settings)}
# Chain settings with preset to provide fallback
settings = ChainMap(settings, presets[settings.get("preset", "")])
if "scope" in settings:
filtered["scope"] = settings["scope"]
if "icon" in settings:
filtered["icon"] = settings["icon"]
# Done! Finish up!
#
# Wrap the call in a timeout to appease adzenith who was kind enough
# to open my first bug report at github.com/Veedrac/Sublime-Extras/issues/1.
# This should make sure that you can switch panes with the mouse.
sublime.set_timeout(lambda: view.add_regions(id, selections, **filtered), 0)
示例2: fromDocAndFlags
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
def fromDocAndFlags(document, flags):
"""
@param document: input document
@param flags: additional API parameters
@return: S2ApiInput corresponding to given document and flags
"""
docDict = {k: v for k, v in document._asdict().items() if v}
data = ChainMap(docDict, flags)
inputDict = {fldName : data.get(fldName, None) for fldName in S2ApiInput._fields}
return S2ApiInput(**inputDict)
示例3: Module
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class Module(object):
def __init__(self, name, fullname, parent=None, reader=None):
self.name = name
self.fullname = fullname
self.parent = parent
self.reader = reader
self.files = OrderedDict()
self.reset()
@property
def package_name(self):
return self.name
def fulladdress(self, name):
return "{}.{}".format(self.fullname, name)
def read_file(self, name, file):
self.files[name] = self.reader.read_file(file, parent=self)
def normalize(self):
self.reset()
for file in self.files.values():
file.normalize()
self.new_child(file.members)
def reset(self):
self.members = ChainMap()
def new_child(self, item):
self.members = self.members.new_child(item)
def __getitem__(self, name):
return self.members[name]
def get(self, name, default=None):
return self.members.get(name, default)
def __contains__(self, name):
return name in self.members
@property
def world(self):
return self.parent
示例4: SymbolTable
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class SymbolTable(object):
'''
Class representing a symbol table. It should provide functionality
for adding and looking up nodes associated with identifiers.
'''
def __init__(self):
self.table = ChainMap()
self.current_scope = self.table
self.root_scope = self.table
self.type_objects = {
int: gonetype.int_type,
float: gonetype.float_type,
str: gonetype.string_type,
bool: gonetype.bool_type,
'int': gonetype.int_type,
'float': gonetype.float_type,
'string': gonetype.string_type,
'bool': gonetype.bool_type
}
def add(self, symbol, data):
self.current_scope[symbol] = data
def get(self, symbol):
if symbol in self.current_scope:
return self.current_scope[symbol]
return None
def push_scope(self):
self.current_scope = self.table.new_child()
return self.current_scope
def pop_scope(self):
self.current_scope = self.current_scope.parents
return self.current_scope
def pprint(self):
print("{}top".format("-" * 10))
for symbol in self.table:
print("{}: {}".format(symbol, self.table.get(symbol)))
print("-" * 10)
示例5: _ClientProtocol
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class _ClientProtocol(_BaseProtocol):
"""Client protocol implementation."""
REQ_PREFIX = struct.Struct('=HH')
REQ_SUFFIX = struct.Struct('=Ld')
RESP = struct.Struct('=HHLd?')
def __init__(self, loop, *, error_table=None, translation_table=None):
super().__init__(loop, translation_table=translation_table)
self.calls = {}
self.prefix = self.REQ_PREFIX.pack(os.getpid() % 0x10000,
random.randrange(0x10000))
self.counter = 0
if error_table is None:
self.error_table = _default_error_table
else:
self.error_table = ChainMap(error_table, _default_error_table)
def msg_received(self, data):
try:
header, banswer = data
pid, rnd, req_id, timestamp, is_error = self.RESP.unpack(header)
answer = self.packer.unpackb(banswer)
except Exception:
logger.critical("Cannot unpack %r", data, exc_info=sys.exc_info())
return
call = self.calls.pop(req_id, None)
if call is None:
logger.critical("Unknown answer id: %d (%d %d %f %d) -> %s",
req_id, pid, rnd, timestamp, is_error, answer)
elif call.cancelled():
logger.debug("The future for request #%08x has been cancelled, "
"skip the received result.", req_id)
else:
if is_error:
call.set_exception(self._translate_error(*answer))
else:
call.set_result(answer)
def connection_lost(self, exc):
super().connection_lost(exc)
for call in self.calls.values():
if not call.cancelled():
call.cancel()
def _translate_error(self, exc_type, exc_args, exc_repr):
found = self.error_table.get(exc_type)
if found is None:
return GenericError(exc_type, exc_args, exc_repr)
else:
return found(*exc_args)
def _new_id(self):
self.counter += 1
if self.counter > 0xffffffff:
self.counter = 0
return (self.prefix + self.REQ_SUFFIX.pack(self.counter, time.time()),
self.counter)
def call(self, name, args, kwargs):
if self.transport is None:
raise ServiceClosedError()
bname = name.encode('utf-8')
bargs = self.packer.packb(args)
bkwargs = self.packer.packb(kwargs)
header, req_id = self._new_id()
assert req_id not in self.calls, (req_id, self.calls)
fut = asyncio.Future(loop=self.loop)
self.calls[req_id] = fut
self.transport.write([header, bname, bargs, bkwargs])
return fut
示例6: CheckProgramVisitor
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class CheckProgramVisitor(NodeVisitor):
def __init__(self):
self.symtab = ChainMap({
'int': types.IntType,
'float': types.FloatType,
'string': types.StringType,
'bool': types.BoolType,
})
def visit_Program(self, node):
self.visit(node.statements)
# Make sure we have a main func
main = self.symtab.get('main')
if not isinstance(main, FunctionPrototype):
error(0, 'No main() defined')
def visit_Statements(self, node):
for s in node.statement_list:
self.visit(s)
def visit_PrintStatement(self, node):
self.visit(node.expression)
node.type = node.expression.type
def visit_UnaryOp(self, node):
self.visit(node.operand)
ret_type = node.operand.type.check_unaop(node.op)
if ret_type is types.ErrorType:
error(node.lineno, 'Unsupported operation: {} {}'.format(
node.op, node.operand.type))
node.type = ret_type
def visit_BinaryOp(self, node):
self.visit(node.left)
self.visit(node.right)
ret_type = node.left.type.check_binop(node.op, node.left, node.right)
if ret_type is types.ErrorType:
error(node.lineno, 'Unsupported operation: {} {} {}'.format(
node.left.type, node.op, node.right.type))
node.type = ret_type
def visit_ExternDeclaration(self, node):
self.visit(node.func_prototype)
node.type = node.func_prototype.type
def visit_FunctionDeclaration(self, node):
self.visit(node.prototype)
# Create a local scope with declared vars and check statements
self.symtab = self.symtab.new_child() # push local scope on
for p in node.prototype.parameters:
self.symtab[p.name] = Literal(None)
self.symtab[p.name].type = p.typename.type
self.visit(node.statements)
self.symtab = self.symtab.parents # pop local scope off
# Make sure we return from this function someday
return_type = node.prototype.output_typename.type
if not node.statements.is_terminal(return_type):
error(node.lineno, 'Function {} may not return'.format(node.prototype.name))
def visit_ReturnStatement(self, node):
self.visit(node.expression)
node.type = node.expression.type
def visit_FunctionPrototype(self, node):
sym = self.symtab.get(node.name)
if sym is not None:
error(node.lineno, "{} is already defined".format(node.name))
else:
for p in node.parameters:
self.visit(p)
self.visit(node.output_typename)
node.type = node.output_typename.type
self.symtab[node.name] = node
def visit_Parameter(self, node):
self.visit(node.typename)
node.type = node.typename.type
def visit_FunctionCall(self, node):
for p in node.parameters:
self.visit(p)
sym = self.symtab.get(node.name)
if sym is None:
error(node.lineno, '{} is not defined'.format(node.name))
node.type = types.ErrorType
elif not isinstance(sym, FunctionPrototype):
error(node.lineno, '{} is not a function'.format(node.name))
node.type = types.ErrorType
elif len(node.parameters) != len(sym.parameters):
error(node.lineno, '{} expected {} parameters, but got {}'.format(
node.name, len(sym.parameters), len(node.parameters)))
node.type = types.ErrorType
else:
func_types = [p.type for p in sym.parameters]
node_types = [p.type for p in node.parameters]
for i, (func_t,node_t) in enumerate(zip(func_types,node_types)):
#.........这里部分代码省略.........
示例7: KeyboardChorder
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class KeyboardChorder(object):
def __init__(self, im):
self.im = im
self.conf_file = path.expanduser('~/.config/chords')
self.remap = ChainMap()
self.logger = DummyLogger()
self.real_logger = None
self.configure()
self.on_reset()
self.quiet = False
ctx = zmq.Context.instance()
rtd = os.environ["XDG_RUNTIME_DIR"]
self.sock = ctx.socket(zmq.PULL)
self.sock.bind("ipc://{}/chords".format(rtd))
fd = self.sock.getsockopt(zmq.FD)
self.im.poll_read(fd, self.on_sock_poll)
def lookup_keysym(self, s):
if s == 'HOLD': return HOLD
syms = self.im.lookup_keysym(s)
return syms[0][0] if syms else s
def translate_keymap(self, keymap):
km = {}
for desc, val in keymap.items():
if isinstance(desc, str):
chord = []
for ch in desc:
if ch == 'F':
chord.append(lookup(self.modmap, LEVEL3))
chord.append((HOLD,))
else:
chord.append(lookup(self.unshifted, ch))
elif isinstance(desc, Press):
chord = [(desc.keycode,)]
for ch in product(*chord):
ch = tuple(sorted(ch))
if isinstance(val, Shift):
if val.base is not None:
km[ch] = val.base
km[(HOLD,)+ch] = val.hold
else:
km[ch] = val
return km
def configure(self):
#FIXME: place these in a class w defaults
def Sym(*a):
mod = reduce(or_,a[:-1],0)
keysym = desc_to_keysym(a[-1])
keycode, state = self.im.lookup_keysym(keysym)[0]
return Press(keysym, keycode, mod+state, 0)
# Do you even curry?
curry = partial(partial, partial)
conf = SimpleNamespace(
pause=self.pause,
quiet=self.set_quiet,
conf=self.configure,
set_keymap=curry(self.set_keymap),
lock=curry(self.toggle_lock),
unlock=partial(self.set_lock, None),
keymap={},
parents={},
Shift=Shift,
Sym=Sym,
SHIFT=0x01,
CTRL=0x04,
ALT=ALT,
LEVEL3=0x80,
on_reset=lambda: None,
logs=False,
)
runfile(self.conf_file,conf.__dict__)
self.holdThreshold = conf.holdThreshold
self.holdThreshold2 = conf.holdThreshold2
self.chordTreshold = conf.chordTreshold
self.chordThreshold2 = conf.holdThreshold2
self.modThreshold = conf.modThreshold
self.seqThreshold = conf.seqThreshold
self.unshifted = {}
for k in range(8,255):
sym = self.im.get_keyval(k,0)
istext, string = keysym_desc(sym)
if istext:
self.unshifted[k] = string
code_s = self.lookup_keysym
self.modmap = { code_s(s) or s: mod for s, mod in conf.modmap.items()}
for k,v in self.modmap.items():
#this is a bit brittle, but works under circumstances.
if v == LEVEL3:
self.unshifted[k] = 'T'
# NB: depends on modmap:
self.keymap = { k:self.translate_keymap(v) for k,v in conf.keymap.items() }
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class FileConfig:
def __init__(self, path, data=None):
self.path = path
self._data = ChainMap({}, data)
self._validators = {}
def validator(self, key):
"""Register a configuration key validator function."""
def _inner(func):
self._validators[key] = func
return _inner
def _validate_value(self, key, value):
if key in self._validators:
self._validators[key](value)
def get(self, key, default=None):
value = self._data.get(key, default)
self._validate_value(key, value)
return value
def __getitem__(self, key):
value = self._data[key]
self._validate_value(key, value)
return value
def __setitem__(self, key, value):
self._validate_value(key, value)
self._data[key] = value
def __delitem__(self, key):
del self._data[key]
def __len__(self):
return len(self._data)
def __iter__(self):
return iter(self._data)
def dump(self):
"""Dump the configuration to disk."""
with open(self.path, "w") as config_file:
json.dump(dict(self._data), config_file, indent=4, sort_keys=True)
@classmethod
def load(cls, path, data=None):
"""Load configuration from a file.
Reads configuration from `file` and returns a :class:`Config` instance
with the configuration. The `defaults` will be merged into the
configuration.
:param path str: Path to the configuration file.
:param defaults dict: A set of defaults to merge into the configuration.
"""
try:
with open(path) as config_file:
file_config = json.load(config_file)
except FileNotFoundError:
file_config = {}
if data is None:
data = {}
else:
data = dict(data)
data.update(file_config)
return cls(path=path, data=data)
示例9: __init__
# 需要导入模块: from collections import ChainMap [as 别名]
# 或者: from collections.ChainMap import get [as 别名]
class TextPainter:
'''
Paints text on a QPaintDevice.
'''
def __init__(self, *, settings=None, device=None):
self.settings = settings or TextViewSettings()
self._metrics = Qt.QFontMetricsF(self.settings.q_font)
self.device = device
self.reset()
self._base_attrs = {}
self._cur_lc_attrs = {}
self._cur_attrs = {}
self._attrs = ChainMap(self._cur_attrs, self._cur_lc_attrs, self._base_attrs)
def reset(self):
self.q_bgcolor = self.settings.q_bgcolor
self.q_fgcolor = self.settings.q_fgcolor
def __enter__(self):
'''
Create the QPainter on the device.
'''
self._painter = Qt.QPainter(self.device)
self._painter.setFont(self.settings.q_font)
self._painter.setPen(self.q_fgcolor)
self._painter.setBrush(self.q_bgcolor)
return self
def __exit__(self, *args, **kw):
'''
End the painter.
'''
self._painter.end()
self._painter = None
def _make_font(self):
'''
Return the current font.
'''
font = Qt.QFont(self.settings.q_font)
font.setBold(self._attrs.get('bold') or False)
font.setItalic(self._attrs.get('italic') or False)
font.setUnderline(self._attrs.get('underline') or False)
return font
def _make_pen(self):
'''
Return the current pen.
'''
sel_color = self._attrs.get('sel_color')
if sel_color == 'auto':
sel_color = self.settings.scheme.selection_fg
return Qt.QPen(to_q_color(sel_color
or self._attrs.get('color',
self.settings.q_fgcolor)))
def _make_brush(self):
'''
Return the current brush.
'''
sel_bgcolor = self._attrs.get('sel_bgcolor')
if sel_bgcolor == 'auto':
sel_bgcolor = self.settings.scheme.selection_bg
return Qt.QBrush(to_q_color(sel_bgcolor
or self._attrs.get('bgcolor',
self.settings.q_bgcolor)))
def update_attrs(self, attrs):
'''
Update internal state to reflect the string attributes given.
'''
sentinel = object()
for k, v in attrs.items():
if v is None:
try:
del self._cur_attrs[k]
except KeyError:
pass
else:
self._cur_attrs[k] = v
lc = attrs.get('lexcat', sentinel)
if lc is not sentinel:
self._cur_lc_attrs.clear()
if lc is not None:
lcattrs = self.settings.scheme.lexcat_attrs(lc)
self._cur_lc_attrs.update(lcattrs)
self._painter.setPen(self._make_pen())
self._painter.setBrush(self._make_brush())
self._painter.setFont(self._make_font())
#.........这里部分代码省略.........