partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
reverse_bintree
construct {parent:[children]} dict from {child:parent} keys are the nodes in the tree, and values are the lists of children of that node in the tree. reverse_tree[None] is the root node >>> tree = bintree(range(7)) >>> reverse_bintree(tree) {None: 0, 0: [1, 4], 4: [5, 6], 1: [2, 3]}
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def reverse_bintree(parents): """construct {parent:[children]} dict from {child:parent} keys are the nodes in the tree, and values are the lists of children of that node in the tree. reverse_tree[None] is the root node >>> tree = bintree(range(7)) >>> reverse_bintree(tree) {None: 0, 0: [1, 4], 4: [5, 6], 1: [2, 3]} """ children = {} for child,parent in parents.iteritems(): if parent is None: children[None] = child continue elif parent not in children: children[parent] = [] children[parent].append(child) return children
def reverse_bintree(parents): """construct {parent:[children]} dict from {child:parent} keys are the nodes in the tree, and values are the lists of children of that node in the tree. reverse_tree[None] is the root node >>> tree = bintree(range(7)) >>> reverse_bintree(tree) {None: 0, 0: [1, 4], 4: [5, 6], 1: [2, 3]} """ children = {} for child,parent in parents.iteritems(): if parent is None: children[None] = child continue elif parent not in children: children[parent] = [] children[parent].append(child) return children
[ "construct", "{", "parent", ":", "[", "children", "]", "}", "dict", "from", "{", "child", ":", "parent", "}", "keys", "are", "the", "nodes", "in", "the", "tree", "and", "values", "are", "the", "lists", "of", "children", "of", "that", "node", "in", "the", "tree", ".", "reverse_tree", "[", "None", "]", "is", "the", "root", "node", ">>>", "tree", "=", "bintree", "(", "range", "(", "7", "))", ">>>", "reverse_bintree", "(", "tree", ")", "{", "None", ":", "0", "0", ":", "[", "1", "4", "]", "4", ":", "[", "5", "6", "]", "1", ":", "[", "2", "3", "]", "}" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L60-L81
[ "def", "reverse_bintree", "(", "parents", ")", ":", "children", "=", "{", "}", "for", "child", ",", "parent", "in", "parents", ".", "iteritems", "(", ")", ":", "if", "parent", "is", "None", ":", "children", "[", "None", "]", "=", "child", "continue", "elif", "parent", "not", "in", "children", ":", "children", "[", "parent", "]", "=", "[", "]", "children", "[", "parent", "]", ".", "append", "(", "child", ")", "return", "children" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
depth
get depth of an element in the tree
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def depth(n, tree): """get depth of an element in the tree""" d = 0 parent = tree[n] while parent is not None: d += 1 parent = tree[parent] return d
def depth(n, tree): """get depth of an element in the tree""" d = 0 parent = tree[n] while parent is not None: d += 1 parent = tree[parent] return d
[ "get", "depth", "of", "an", "element", "in", "the", "tree" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L83-L90
[ "def", "depth", "(", "n", ",", "tree", ")", ":", "d", "=", "0", "parent", "=", "tree", "[", "n", "]", "while", "parent", "is", "not", "None", ":", "d", "+=", "1", "parent", "=", "tree", "[", "parent", "]", "return", "d" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
print_bintree
print a binary tree
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def print_bintree(tree, indent=' '): """print a binary tree""" for n in sorted(tree.keys()): print "%s%s" % (indent * depth(n,tree), n)
def print_bintree(tree, indent=' '): """print a binary tree""" for n in sorted(tree.keys()): print "%s%s" % (indent * depth(n,tree), n)
[ "print", "a", "binary", "tree" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L92-L95
[ "def", "print_bintree", "(", "tree", ",", "indent", "=", "' '", ")", ":", "for", "n", "in", "sorted", "(", "tree", ".", "keys", "(", ")", ")", ":", "print", "\"%s%s\"", "%", "(", "indent", "*", "depth", "(", "n", ",", "tree", ")", ",", "n", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
disambiguate_dns_url
accept either IP address or dns name, and return IP
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def disambiguate_dns_url(url, location): """accept either IP address or dns name, and return IP""" if not ip_pat.match(location): location = socket.gethostbyname(location) return disambiguate_url(url, location)
def disambiguate_dns_url(url, location): """accept either IP address or dns name, and return IP""" if not ip_pat.match(location): location = socket.gethostbyname(location) return disambiguate_url(url, location)
[ "accept", "either", "IP", "address", "or", "dns", "name", "and", "return", "IP" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L103-L107
[ "def", "disambiguate_dns_url", "(", "url", ",", "location", ")", ":", "if", "not", "ip_pat", ".", "match", "(", "location", ")", ":", "location", "=", "socket", ".", "gethostbyname", "(", "location", ")", "return", "disambiguate_url", "(", "url", ",", "location", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BinaryTreeCommunicator.connect
connect to peers. `peers` will be a dict of 4-tuples, keyed by name. {peer : (ident, addr, pub_addr, location)} where peer is the name, ident is the XREP identity, addr,pub_addr are the
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def connect(self, peers, btree, pub_url, root_id=0): """connect to peers. `peers` will be a dict of 4-tuples, keyed by name. {peer : (ident, addr, pub_addr, location)} where peer is the name, ident is the XREP identity, addr,pub_addr are the """ # count the number of children we have self.nchildren = btree.values().count(self.id) if self.root: return # root only binds root_location = peers[root_id][-1] self.sub.connect(disambiguate_dns_url(pub_url, root_location)) parent = btree[self.id] tree_url, location = peers[parent] self.upstream.connect(disambiguate_dns_url(tree_url, location))
def connect(self, peers, btree, pub_url, root_id=0): """connect to peers. `peers` will be a dict of 4-tuples, keyed by name. {peer : (ident, addr, pub_addr, location)} where peer is the name, ident is the XREP identity, addr,pub_addr are the """ # count the number of children we have self.nchildren = btree.values().count(self.id) if self.root: return # root only binds root_location = peers[root_id][-1] self.sub.connect(disambiguate_dns_url(pub_url, root_location)) parent = btree[self.id] tree_url, location = peers[parent] self.upstream.connect(disambiguate_dns_url(tree_url, location))
[ "connect", "to", "peers", ".", "peers", "will", "be", "a", "dict", "of", "4", "-", "tuples", "keyed", "by", "name", ".", "{", "peer", ":", "(", "ident", "addr", "pub_addr", "location", ")", "}", "where", "peer", "is", "the", "name", "ident", "is", "the", "XREP", "identity", "addr", "pub_addr", "are", "the" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L161-L179
[ "def", "connect", "(", "self", ",", "peers", ",", "btree", ",", "pub_url", ",", "root_id", "=", "0", ")", ":", "# count the number of children we have", "self", ".", "nchildren", "=", "btree", ".", "values", "(", ")", ".", "count", "(", "self", ".", "id", ")", "if", "self", ".", "root", ":", "return", "# root only binds", "root_location", "=", "peers", "[", "root_id", "]", "[", "-", "1", "]", "self", ".", "sub", ".", "connect", "(", "disambiguate_dns_url", "(", "pub_url", ",", "root_location", ")", ")", "parent", "=", "btree", "[", "self", ".", "id", "]", "tree_url", ",", "location", "=", "peers", "[", "parent", "]", "self", ".", "upstream", ".", "connect", "(", "disambiguate_dns_url", "(", "tree_url", ",", "location", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BinaryTreeCommunicator.reduce
parallel reduce on binary tree if flat: value is an entry in the sequence else: value is a list of entries in the sequence if all: broadcast final result to all nodes else: only root gets final result
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def reduce(self, f, value, flat=True, all=False): """parallel reduce on binary tree if flat: value is an entry in the sequence else: value is a list of entries in the sequence if all: broadcast final result to all nodes else: only root gets final result """ if not flat: value = reduce(f, value) for i in range(self.nchildren): value = f(value, self.recv_downstream()) if not self.root: self.send_upstream(value) if all: if self.root: self.publish(value) else: value = self.consume() return value
def reduce(self, f, value, flat=True, all=False): """parallel reduce on binary tree if flat: value is an entry in the sequence else: value is a list of entries in the sequence if all: broadcast final result to all nodes else: only root gets final result """ if not flat: value = reduce(f, value) for i in range(self.nchildren): value = f(value, self.recv_downstream()) if not self.root: self.send_upstream(value) if all: if self.root: self.publish(value) else: value = self.consume() return value
[ "parallel", "reduce", "on", "binary", "tree", "if", "flat", ":", "value", "is", "an", "entry", "in", "the", "sequence", "else", ":", "value", "is", "a", "list", "of", "entries", "in", "the", "sequence", "if", "all", ":", "broadcast", "final", "result", "to", "all", "nodes", "else", ":", "only", "root", "gets", "final", "result" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L213-L240
[ "def", "reduce", "(", "self", ",", "f", ",", "value", ",", "flat", "=", "True", ",", "all", "=", "False", ")", ":", "if", "not", "flat", ":", "value", "=", "reduce", "(", "f", ",", "value", ")", "for", "i", "in", "range", "(", "self", ".", "nchildren", ")", ":", "value", "=", "f", "(", "value", ",", "self", ".", "recv_downstream", "(", ")", ")", "if", "not", "self", ".", "root", ":", "self", ".", "send_upstream", "(", "value", ")", "if", "all", ":", "if", "self", ".", "root", ":", "self", ".", "publish", "(", "value", ")", "else", ":", "value", "=", "self", ".", "consume", "(", ")", "return", "value" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BinaryTreeCommunicator.allreduce
parallel reduce followed by broadcast of the result
environment/share/doc/ipython/examples/parallel/interengine/bintree.py
def allreduce(self, f, value, flat=True): """parallel reduce followed by broadcast of the result""" return self.reduce(f, value, flat=flat, all=True)
def allreduce(self, f, value, flat=True): """parallel reduce followed by broadcast of the result""" return self.reduce(f, value, flat=flat, all=True)
[ "parallel", "reduce", "followed", "by", "broadcast", "of", "the", "result" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/bintree.py#L242-L244
[ "def", "allreduce", "(", "self", ",", "f", ",", "value", ",", "flat", "=", "True", ")", ":", "return", "self", ".", "reduce", "(", "f", ",", "value", ",", "flat", "=", "flat", ",", "all", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
HubFactory.init_hub
construct
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def init_hub(self): """construct""" client_iface = "%s://%s:" % (self.client_transport, self.client_ip) + "%i" engine_iface = "%s://%s:" % (self.engine_transport, self.engine_ip) + "%i" ctx = self.context loop = self.loop # Registrar socket q = ZMQStream(ctx.socket(zmq.ROUTER), loop) q.bind(client_iface % self.regport) self.log.info("Hub listening on %s for registration.", client_iface % self.regport) if self.client_ip != self.engine_ip: q.bind(engine_iface % self.regport) self.log.info("Hub listening on %s for registration.", engine_iface % self.regport) ### Engine connections ### # heartbeat hpub = ctx.socket(zmq.PUB) hpub.bind(engine_iface % self.hb[0]) hrep = ctx.socket(zmq.ROUTER) hrep.bind(engine_iface % self.hb[1]) self.heartmonitor = HeartMonitor(loop=loop, config=self.config, log=self.log, pingstream=ZMQStream(hpub,loop), pongstream=ZMQStream(hrep,loop) ) ### Client connections ### # Notifier socket n = ZMQStream(ctx.socket(zmq.PUB), loop) n.bind(client_iface%self.notifier_port) ### build and launch the queues ### # monitor socket sub = ctx.socket(zmq.SUB) sub.setsockopt(zmq.SUBSCRIBE, b"") sub.bind(self.monitor_url) sub.bind('inproc://monitor') sub = ZMQStream(sub, loop) # connect the db db_class = _db_shortcuts.get(self.db_class.lower(), self.db_class) self.log.info('Hub using DB backend: %r', (db_class.split('.')[-1])) self.db = import_item(str(db_class))(session=self.session.session, config=self.config, log=self.log) time.sleep(.25) try: scheme = self.config.TaskScheduler.scheme_name except AttributeError: from .scheduler import TaskScheduler scheme = TaskScheduler.scheme_name.get_default_value() # build connection dicts self.engine_info = { 'control' : engine_iface%self.control[1], 'mux': engine_iface%self.mux[1], 'heartbeat': (engine_iface%self.hb[0], engine_iface%self.hb[1]), 'task' : engine_iface%self.task[1], 'iopub' : engine_iface%self.iopub[1], # 'monitor' : engine_iface%self.mon_port, } self.client_info = { 'control' : client_iface%self.control[0], 'mux': client_iface%self.mux[0], 'task' : (scheme, client_iface%self.task[0]), 'iopub' : client_iface%self.iopub[0], 'notification': client_iface%self.notifier_port } self.log.debug("Hub engine addrs: %s", self.engine_info) self.log.debug("Hub client addrs: %s", self.client_info) # resubmit stream r = ZMQStream(ctx.socket(zmq.DEALER), loop) url = util.disambiguate_url(self.client_info['task'][-1]) r.setsockopt(zmq.IDENTITY, self.session.bsession) r.connect(url) self.hub = Hub(loop=loop, session=self.session, monitor=sub, heartmonitor=self.heartmonitor, query=q, notifier=n, resubmit=r, db=self.db, engine_info=self.engine_info, client_info=self.client_info, log=self.log)
def init_hub(self): """construct""" client_iface = "%s://%s:" % (self.client_transport, self.client_ip) + "%i" engine_iface = "%s://%s:" % (self.engine_transport, self.engine_ip) + "%i" ctx = self.context loop = self.loop # Registrar socket q = ZMQStream(ctx.socket(zmq.ROUTER), loop) q.bind(client_iface % self.regport) self.log.info("Hub listening on %s for registration.", client_iface % self.regport) if self.client_ip != self.engine_ip: q.bind(engine_iface % self.regport) self.log.info("Hub listening on %s for registration.", engine_iface % self.regport) ### Engine connections ### # heartbeat hpub = ctx.socket(zmq.PUB) hpub.bind(engine_iface % self.hb[0]) hrep = ctx.socket(zmq.ROUTER) hrep.bind(engine_iface % self.hb[1]) self.heartmonitor = HeartMonitor(loop=loop, config=self.config, log=self.log, pingstream=ZMQStream(hpub,loop), pongstream=ZMQStream(hrep,loop) ) ### Client connections ### # Notifier socket n = ZMQStream(ctx.socket(zmq.PUB), loop) n.bind(client_iface%self.notifier_port) ### build and launch the queues ### # monitor socket sub = ctx.socket(zmq.SUB) sub.setsockopt(zmq.SUBSCRIBE, b"") sub.bind(self.monitor_url) sub.bind('inproc://monitor') sub = ZMQStream(sub, loop) # connect the db db_class = _db_shortcuts.get(self.db_class.lower(), self.db_class) self.log.info('Hub using DB backend: %r', (db_class.split('.')[-1])) self.db = import_item(str(db_class))(session=self.session.session, config=self.config, log=self.log) time.sleep(.25) try: scheme = self.config.TaskScheduler.scheme_name except AttributeError: from .scheduler import TaskScheduler scheme = TaskScheduler.scheme_name.get_default_value() # build connection dicts self.engine_info = { 'control' : engine_iface%self.control[1], 'mux': engine_iface%self.mux[1], 'heartbeat': (engine_iface%self.hb[0], engine_iface%self.hb[1]), 'task' : engine_iface%self.task[1], 'iopub' : engine_iface%self.iopub[1], # 'monitor' : engine_iface%self.mon_port, } self.client_info = { 'control' : client_iface%self.control[0], 'mux': client_iface%self.mux[0], 'task' : (scheme, client_iface%self.task[0]), 'iopub' : client_iface%self.iopub[0], 'notification': client_iface%self.notifier_port } self.log.debug("Hub engine addrs: %s", self.engine_info) self.log.debug("Hub client addrs: %s", self.client_info) # resubmit stream r = ZMQStream(ctx.socket(zmq.DEALER), loop) url = util.disambiguate_url(self.client_info['task'][-1]) r.setsockopt(zmq.IDENTITY, self.session.bsession) r.connect(url) self.hub = Hub(loop=loop, session=self.session, monitor=sub, heartmonitor=self.heartmonitor, query=q, notifier=n, resubmit=r, db=self.db, engine_info=self.engine_info, client_info=self.client_info, log=self.log)
[ "construct" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L234-L316
[ "def", "init_hub", "(", "self", ")", ":", "client_iface", "=", "\"%s://%s:\"", "%", "(", "self", ".", "client_transport", ",", "self", ".", "client_ip", ")", "+", "\"%i\"", "engine_iface", "=", "\"%s://%s:\"", "%", "(", "self", ".", "engine_transport", ",", "self", ".", "engine_ip", ")", "+", "\"%i\"", "ctx", "=", "self", ".", "context", "loop", "=", "self", ".", "loop", "# Registrar socket", "q", "=", "ZMQStream", "(", "ctx", ".", "socket", "(", "zmq", ".", "ROUTER", ")", ",", "loop", ")", "q", ".", "bind", "(", "client_iface", "%", "self", ".", "regport", ")", "self", ".", "log", ".", "info", "(", "\"Hub listening on %s for registration.\"", ",", "client_iface", "%", "self", ".", "regport", ")", "if", "self", ".", "client_ip", "!=", "self", ".", "engine_ip", ":", "q", ".", "bind", "(", "engine_iface", "%", "self", ".", "regport", ")", "self", ".", "log", ".", "info", "(", "\"Hub listening on %s for registration.\"", ",", "engine_iface", "%", "self", ".", "regport", ")", "### Engine connections ###", "# heartbeat", "hpub", "=", "ctx", ".", "socket", "(", "zmq", ".", "PUB", ")", "hpub", ".", "bind", "(", "engine_iface", "%", "self", ".", "hb", "[", "0", "]", ")", "hrep", "=", "ctx", ".", "socket", "(", "zmq", ".", "ROUTER", ")", "hrep", ".", "bind", "(", "engine_iface", "%", "self", ".", "hb", "[", "1", "]", ")", "self", ".", "heartmonitor", "=", "HeartMonitor", "(", "loop", "=", "loop", ",", "config", "=", "self", ".", "config", ",", "log", "=", "self", ".", "log", ",", "pingstream", "=", "ZMQStream", "(", "hpub", ",", "loop", ")", ",", "pongstream", "=", "ZMQStream", "(", "hrep", ",", "loop", ")", ")", "### Client connections ###", "# Notifier socket", "n", "=", "ZMQStream", "(", "ctx", ".", "socket", "(", "zmq", ".", "PUB", ")", ",", "loop", ")", "n", ".", "bind", "(", "client_iface", "%", "self", ".", "notifier_port", ")", "### build and launch the queues ###", "# monitor socket", "sub", "=", "ctx", ".", "socket", "(", "zmq", ".", "SUB", ")", "sub", ".", "setsockopt", "(", "zmq", ".", "SUBSCRIBE", ",", "b\"\"", ")", "sub", ".", "bind", "(", "self", ".", "monitor_url", ")", "sub", ".", "bind", "(", "'inproc://monitor'", ")", "sub", "=", "ZMQStream", "(", "sub", ",", "loop", ")", "# connect the db", "db_class", "=", "_db_shortcuts", ".", "get", "(", "self", ".", "db_class", ".", "lower", "(", ")", ",", "self", ".", "db_class", ")", "self", ".", "log", ".", "info", "(", "'Hub using DB backend: %r'", ",", "(", "db_class", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", ")", "self", ".", "db", "=", "import_item", "(", "str", "(", "db_class", ")", ")", "(", "session", "=", "self", ".", "session", ".", "session", ",", "config", "=", "self", ".", "config", ",", "log", "=", "self", ".", "log", ")", "time", ".", "sleep", "(", ".25", ")", "try", ":", "scheme", "=", "self", ".", "config", ".", "TaskScheduler", ".", "scheme_name", "except", "AttributeError", ":", "from", ".", "scheduler", "import", "TaskScheduler", "scheme", "=", "TaskScheduler", ".", "scheme_name", ".", "get_default_value", "(", ")", "# build connection dicts", "self", ".", "engine_info", "=", "{", "'control'", ":", "engine_iface", "%", "self", ".", "control", "[", "1", "]", ",", "'mux'", ":", "engine_iface", "%", "self", ".", "mux", "[", "1", "]", ",", "'heartbeat'", ":", "(", "engine_iface", "%", "self", ".", "hb", "[", "0", "]", ",", "engine_iface", "%", "self", ".", "hb", "[", "1", "]", ")", ",", "'task'", ":", "engine_iface", "%", "self", ".", "task", "[", "1", "]", ",", "'iopub'", ":", "engine_iface", "%", "self", ".", "iopub", "[", "1", "]", ",", "# 'monitor' : engine_iface%self.mon_port,", "}", "self", ".", "client_info", "=", "{", "'control'", ":", "client_iface", "%", "self", ".", "control", "[", "0", "]", ",", "'mux'", ":", "client_iface", "%", "self", ".", "mux", "[", "0", "]", ",", "'task'", ":", "(", "scheme", ",", "client_iface", "%", "self", ".", "task", "[", "0", "]", ")", ",", "'iopub'", ":", "client_iface", "%", "self", ".", "iopub", "[", "0", "]", ",", "'notification'", ":", "client_iface", "%", "self", ".", "notifier_port", "}", "self", ".", "log", ".", "debug", "(", "\"Hub engine addrs: %s\"", ",", "self", ".", "engine_info", ")", "self", ".", "log", ".", "debug", "(", "\"Hub client addrs: %s\"", ",", "self", ".", "client_info", ")", "# resubmit stream", "r", "=", "ZMQStream", "(", "ctx", ".", "socket", "(", "zmq", ".", "DEALER", ")", ",", "loop", ")", "url", "=", "util", ".", "disambiguate_url", "(", "self", ".", "client_info", "[", "'task'", "]", "[", "-", "1", "]", ")", "r", ".", "setsockopt", "(", "zmq", ".", "IDENTITY", ",", "self", ".", "session", ".", "bsession", ")", "r", ".", "connect", "(", "url", ")", "self", ".", "hub", "=", "Hub", "(", "loop", "=", "loop", ",", "session", "=", "self", ".", "session", ",", "monitor", "=", "sub", ",", "heartmonitor", "=", "self", ".", "heartmonitor", ",", "query", "=", "q", ",", "notifier", "=", "n", ",", "resubmit", "=", "r", ",", "db", "=", "self", ".", "db", ",", "engine_info", "=", "self", ".", "engine_info", ",", "client_info", "=", "self", ".", "client_info", ",", "log", "=", "self", ".", "log", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub._validate_targets
turn any valid targets argument into a list of integer ids
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def _validate_targets(self, targets): """turn any valid targets argument into a list of integer ids""" if targets is None: # default to all return self.ids if isinstance(targets, (int,str,unicode)): # only one target specified targets = [targets] _targets = [] for t in targets: # map raw identities to ids if isinstance(t, (str,unicode)): t = self.by_ident.get(cast_bytes(t), t) _targets.append(t) targets = _targets bad_targets = [ t for t in targets if t not in self.ids ] if bad_targets: raise IndexError("No Such Engine: %r" % bad_targets) if not targets: raise IndexError("No Engines Registered") return targets
def _validate_targets(self, targets): """turn any valid targets argument into a list of integer ids""" if targets is None: # default to all return self.ids if isinstance(targets, (int,str,unicode)): # only one target specified targets = [targets] _targets = [] for t in targets: # map raw identities to ids if isinstance(t, (str,unicode)): t = self.by_ident.get(cast_bytes(t), t) _targets.append(t) targets = _targets bad_targets = [ t for t in targets if t not in self.ids ] if bad_targets: raise IndexError("No Such Engine: %r" % bad_targets) if not targets: raise IndexError("No Engines Registered") return targets
[ "turn", "any", "valid", "targets", "argument", "into", "a", "list", "of", "integer", "ids" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L448-L469
[ "def", "_validate_targets", "(", "self", ",", "targets", ")", ":", "if", "targets", "is", "None", ":", "# default to all", "return", "self", ".", "ids", "if", "isinstance", "(", "targets", ",", "(", "int", ",", "str", ",", "unicode", ")", ")", ":", "# only one target specified", "targets", "=", "[", "targets", "]", "_targets", "=", "[", "]", "for", "t", "in", "targets", ":", "# map raw identities to ids", "if", "isinstance", "(", "t", ",", "(", "str", ",", "unicode", ")", ")", ":", "t", "=", "self", ".", "by_ident", ".", "get", "(", "cast_bytes", "(", "t", ")", ",", "t", ")", "_targets", ".", "append", "(", "t", ")", "targets", "=", "_targets", "bad_targets", "=", "[", "t", "for", "t", "in", "targets", "if", "t", "not", "in", "self", ".", "ids", "]", "if", "bad_targets", ":", "raise", "IndexError", "(", "\"No Such Engine: %r\"", "%", "bad_targets", ")", "if", "not", "targets", ":", "raise", "IndexError", "(", "\"No Engines Registered\"", ")", "return", "targets" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.dispatch_monitor_traffic
all ME and Task queue messages come through here, as well as IOPub traffic.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def dispatch_monitor_traffic(self, msg): """all ME and Task queue messages come through here, as well as IOPub traffic.""" self.log.debug("monitor traffic: %r", msg[0]) switch = msg[0] try: idents, msg = self.session.feed_identities(msg[1:]) except ValueError: idents=[] if not idents: self.log.error("Monitor message without topic: %r", msg) return handler = self.monitor_handlers.get(switch, None) if handler is not None: handler(idents, msg) else: self.log.error("Unrecognized monitor topic: %r", switch)
def dispatch_monitor_traffic(self, msg): """all ME and Task queue messages come through here, as well as IOPub traffic.""" self.log.debug("monitor traffic: %r", msg[0]) switch = msg[0] try: idents, msg = self.session.feed_identities(msg[1:]) except ValueError: idents=[] if not idents: self.log.error("Monitor message without topic: %r", msg) return handler = self.monitor_handlers.get(switch, None) if handler is not None: handler(idents, msg) else: self.log.error("Unrecognized monitor topic: %r", switch)
[ "all", "ME", "and", "Task", "queue", "messages", "come", "through", "here", "as", "well", "as", "IOPub", "traffic", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L477-L493
[ "def", "dispatch_monitor_traffic", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"monitor traffic: %r\"", ",", "msg", "[", "0", "]", ")", "switch", "=", "msg", "[", "0", "]", "try", ":", "idents", ",", "msg", "=", "self", ".", "session", ".", "feed_identities", "(", "msg", "[", "1", ":", "]", ")", "except", "ValueError", ":", "idents", "=", "[", "]", "if", "not", "idents", ":", "self", ".", "log", ".", "error", "(", "\"Monitor message without topic: %r\"", ",", "msg", ")", "return", "handler", "=", "self", ".", "monitor_handlers", ".", "get", "(", "switch", ",", "None", ")", "if", "handler", "is", "not", "None", ":", "handler", "(", "idents", ",", "msg", ")", "else", ":", "self", ".", "log", ".", "error", "(", "\"Unrecognized monitor topic: %r\"", ",", "switch", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.dispatch_query
Route registration requests and queries from clients.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def dispatch_query(self, msg): """Route registration requests and queries from clients.""" try: idents, msg = self.session.feed_identities(msg) except ValueError: idents = [] if not idents: self.log.error("Bad Query Message: %r", msg) return client_id = idents[0] try: msg = self.session.unserialize(msg, content=True) except Exception: content = error.wrap_exception() self.log.error("Bad Query Message: %r", msg, exc_info=True) self.session.send(self.query, "hub_error", ident=client_id, content=content) return # print client_id, header, parent, content #switch on message type: msg_type = msg['header']['msg_type'] self.log.info("client::client %r requested %r", client_id, msg_type) handler = self.query_handlers.get(msg_type, None) try: assert handler is not None, "Bad Message Type: %r" % msg_type except: content = error.wrap_exception() self.log.error("Bad Message Type: %r", msg_type, exc_info=True) self.session.send(self.query, "hub_error", ident=client_id, content=content) return else: handler(idents, msg)
def dispatch_query(self, msg): """Route registration requests and queries from clients.""" try: idents, msg = self.session.feed_identities(msg) except ValueError: idents = [] if not idents: self.log.error("Bad Query Message: %r", msg) return client_id = idents[0] try: msg = self.session.unserialize(msg, content=True) except Exception: content = error.wrap_exception() self.log.error("Bad Query Message: %r", msg, exc_info=True) self.session.send(self.query, "hub_error", ident=client_id, content=content) return # print client_id, header, parent, content #switch on message type: msg_type = msg['header']['msg_type'] self.log.info("client::client %r requested %r", client_id, msg_type) handler = self.query_handlers.get(msg_type, None) try: assert handler is not None, "Bad Message Type: %r" % msg_type except: content = error.wrap_exception() self.log.error("Bad Message Type: %r", msg_type, exc_info=True) self.session.send(self.query, "hub_error", ident=client_id, content=content) return else: handler(idents, msg)
[ "Route", "registration", "requests", "and", "queries", "from", "clients", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L497-L530
[ "def", "dispatch_query", "(", "self", ",", "msg", ")", ":", "try", ":", "idents", ",", "msg", "=", "self", ".", "session", ".", "feed_identities", "(", "msg", ")", "except", "ValueError", ":", "idents", "=", "[", "]", "if", "not", "idents", ":", "self", ".", "log", ".", "error", "(", "\"Bad Query Message: %r\"", ",", "msg", ")", "return", "client_id", "=", "idents", "[", "0", "]", "try", ":", "msg", "=", "self", ".", "session", ".", "unserialize", "(", "msg", ",", "content", "=", "True", ")", "except", "Exception", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "self", ".", "log", ".", "error", "(", "\"Bad Query Message: %r\"", ",", "msg", ",", "exc_info", "=", "True", ")", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"hub_error\"", ",", "ident", "=", "client_id", ",", "content", "=", "content", ")", "return", "# print client_id, header, parent, content", "#switch on message type:", "msg_type", "=", "msg", "[", "'header'", "]", "[", "'msg_type'", "]", "self", ".", "log", ".", "info", "(", "\"client::client %r requested %r\"", ",", "client_id", ",", "msg_type", ")", "handler", "=", "self", ".", "query_handlers", ".", "get", "(", "msg_type", ",", "None", ")", "try", ":", "assert", "handler", "is", "not", "None", ",", "\"Bad Message Type: %r\"", "%", "msg_type", "except", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "self", ".", "log", ".", "error", "(", "\"Bad Message Type: %r\"", ",", "msg_type", ",", "exc_info", "=", "True", ")", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"hub_error\"", ",", "ident", "=", "client_id", ",", "content", "=", "content", ")", "return", "else", ":", "handler", "(", "idents", ",", "msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.handle_new_heart
handler to attach to heartbeater. Called when a new heart starts to beat. Triggers completion of registration.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def handle_new_heart(self, heart): """handler to attach to heartbeater. Called when a new heart starts to beat. Triggers completion of registration.""" self.log.debug("heartbeat::handle_new_heart(%r)", heart) if heart not in self.incoming_registrations: self.log.info("heartbeat::ignoring new heart: %r", heart) else: self.finish_registration(heart)
def handle_new_heart(self, heart): """handler to attach to heartbeater. Called when a new heart starts to beat. Triggers completion of registration.""" self.log.debug("heartbeat::handle_new_heart(%r)", heart) if heart not in self.incoming_registrations: self.log.info("heartbeat::ignoring new heart: %r", heart) else: self.finish_registration(heart)
[ "handler", "to", "attach", "to", "heartbeater", ".", "Called", "when", "a", "new", "heart", "starts", "to", "beat", ".", "Triggers", "completion", "of", "registration", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L542-L550
[ "def", "handle_new_heart", "(", "self", ",", "heart", ")", ":", "self", ".", "log", ".", "debug", "(", "\"heartbeat::handle_new_heart(%r)\"", ",", "heart", ")", "if", "heart", "not", "in", "self", ".", "incoming_registrations", ":", "self", ".", "log", ".", "info", "(", "\"heartbeat::ignoring new heart: %r\"", ",", "heart", ")", "else", ":", "self", ".", "finish_registration", "(", "heart", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.handle_heart_failure
handler to attach to heartbeater. called when a previously registered heart fails to respond to beat request. triggers unregistration
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def handle_heart_failure(self, heart): """handler to attach to heartbeater. called when a previously registered heart fails to respond to beat request. triggers unregistration""" self.log.debug("heartbeat::handle_heart_failure(%r)", heart) eid = self.hearts.get(heart, None) queue = self.engines[eid].queue if eid is None or self.keytable[eid] in self.dead_engines: self.log.info("heartbeat::ignoring heart failure %r (not an engine or already dead)", heart) else: self.unregister_engine(heart, dict(content=dict(id=eid, queue=queue)))
def handle_heart_failure(self, heart): """handler to attach to heartbeater. called when a previously registered heart fails to respond to beat request. triggers unregistration""" self.log.debug("heartbeat::handle_heart_failure(%r)", heart) eid = self.hearts.get(heart, None) queue = self.engines[eid].queue if eid is None or self.keytable[eid] in self.dead_engines: self.log.info("heartbeat::ignoring heart failure %r (not an engine or already dead)", heart) else: self.unregister_engine(heart, dict(content=dict(id=eid, queue=queue)))
[ "handler", "to", "attach", "to", "heartbeater", ".", "called", "when", "a", "previously", "registered", "heart", "fails", "to", "respond", "to", "beat", "request", ".", "triggers", "unregistration" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L553-L563
[ "def", "handle_heart_failure", "(", "self", ",", "heart", ")", ":", "self", ".", "log", ".", "debug", "(", "\"heartbeat::handle_heart_failure(%r)\"", ",", "heart", ")", "eid", "=", "self", ".", "hearts", ".", "get", "(", "heart", ",", "None", ")", "queue", "=", "self", ".", "engines", "[", "eid", "]", ".", "queue", "if", "eid", "is", "None", "or", "self", ".", "keytable", "[", "eid", "]", "in", "self", ".", "dead_engines", ":", "self", ".", "log", ".", "info", "(", "\"heartbeat::ignoring heart failure %r (not an engine or already dead)\"", ",", "heart", ")", "else", ":", "self", ".", "unregister_engine", "(", "heart", ",", "dict", "(", "content", "=", "dict", "(", "id", "=", "eid", ",", "queue", "=", "queue", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.save_task_request
Save the submission of a task.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def save_task_request(self, idents, msg): """Save the submission of a task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::client %r sent invalid task message: %r", client_id, msg, exc_info=True) return record = init_record(msg) record['client_uuid'] = client_id.decode('ascii') record['queue'] = 'task' header = msg['header'] msg_id = header['msg_id'] self.pending.add(msg_id) self.unassigned.add(msg_id) try: # it's posible iopub arrived first: existing = self.db.get_record(msg_id) if existing['resubmitted']: for key in ('submitted', 'client_uuid', 'buffers'): # don't clobber these keys on resubmit # submitted and client_uuid should be different # and buffers might be big, and shouldn't have changed record.pop(key) # still check content,header which should not change # but are not expensive to compare as buffers for key,evalue in existing.iteritems(): if key.endswith('buffers'): # don't compare buffers continue rvalue = record.get(key, None) if evalue and rvalue and evalue != rvalue: self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue) elif evalue and not rvalue: record[key] = evalue try: self.db.update_record(msg_id, record) except Exception: self.log.error("DB Error updating record %r", msg_id, exc_info=True) except KeyError: try: self.db.add_record(msg_id, record) except Exception: self.log.error("DB Error adding record %r", msg_id, exc_info=True) except Exception: self.log.error("DB Error saving task request %r", msg_id, exc_info=True)
def save_task_request(self, idents, msg): """Save the submission of a task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::client %r sent invalid task message: %r", client_id, msg, exc_info=True) return record = init_record(msg) record['client_uuid'] = client_id.decode('ascii') record['queue'] = 'task' header = msg['header'] msg_id = header['msg_id'] self.pending.add(msg_id) self.unassigned.add(msg_id) try: # it's posible iopub arrived first: existing = self.db.get_record(msg_id) if existing['resubmitted']: for key in ('submitted', 'client_uuid', 'buffers'): # don't clobber these keys on resubmit # submitted and client_uuid should be different # and buffers might be big, and shouldn't have changed record.pop(key) # still check content,header which should not change # but are not expensive to compare as buffers for key,evalue in existing.iteritems(): if key.endswith('buffers'): # don't compare buffers continue rvalue = record.get(key, None) if evalue and rvalue and evalue != rvalue: self.log.warn("conflicting initial state for record: %r:%r <%r> %r", msg_id, rvalue, key, evalue) elif evalue and not rvalue: record[key] = evalue try: self.db.update_record(msg_id, record) except Exception: self.log.error("DB Error updating record %r", msg_id, exc_info=True) except KeyError: try: self.db.add_record(msg_id, record) except Exception: self.log.error("DB Error adding record %r", msg_id, exc_info=True) except Exception: self.log.error("DB Error saving task request %r", msg_id, exc_info=True)
[ "Save", "the", "submission", "of", "a", "task", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L668-L717
[ "def", "save_task_request", "(", "self", ",", "idents", ",", "msg", ")", ":", "client_id", "=", "idents", "[", "0", "]", "try", ":", "msg", "=", "self", ".", "session", ".", "unserialize", "(", "msg", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"task::client %r sent invalid task message: %r\"", ",", "client_id", ",", "msg", ",", "exc_info", "=", "True", ")", "return", "record", "=", "init_record", "(", "msg", ")", "record", "[", "'client_uuid'", "]", "=", "client_id", ".", "decode", "(", "'ascii'", ")", "record", "[", "'queue'", "]", "=", "'task'", "header", "=", "msg", "[", "'header'", "]", "msg_id", "=", "header", "[", "'msg_id'", "]", "self", ".", "pending", ".", "add", "(", "msg_id", ")", "self", ".", "unassigned", ".", "add", "(", "msg_id", ")", "try", ":", "# it's posible iopub arrived first:", "existing", "=", "self", ".", "db", ".", "get_record", "(", "msg_id", ")", "if", "existing", "[", "'resubmitted'", "]", ":", "for", "key", "in", "(", "'submitted'", ",", "'client_uuid'", ",", "'buffers'", ")", ":", "# don't clobber these keys on resubmit", "# submitted and client_uuid should be different", "# and buffers might be big, and shouldn't have changed", "record", ".", "pop", "(", "key", ")", "# still check content,header which should not change", "# but are not expensive to compare as buffers", "for", "key", ",", "evalue", "in", "existing", ".", "iteritems", "(", ")", ":", "if", "key", ".", "endswith", "(", "'buffers'", ")", ":", "# don't compare buffers", "continue", "rvalue", "=", "record", ".", "get", "(", "key", ",", "None", ")", "if", "evalue", "and", "rvalue", "and", "evalue", "!=", "rvalue", ":", "self", ".", "log", ".", "warn", "(", "\"conflicting initial state for record: %r:%r <%r> %r\"", ",", "msg_id", ",", "rvalue", ",", "key", ",", "evalue", ")", "elif", "evalue", "and", "not", "rvalue", ":", "record", "[", "key", "]", "=", "evalue", "try", ":", "self", ".", "db", ".", "update_record", "(", "msg_id", ",", "record", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"DB Error updating record %r\"", ",", "msg_id", ",", "exc_info", "=", "True", ")", "except", "KeyError", ":", "try", ":", "self", ".", "db", ".", "add_record", "(", "msg_id", ",", "record", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"DB Error adding record %r\"", ",", "msg_id", ",", "exc_info", "=", "True", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"DB Error saving task request %r\"", ",", "msg_id", ",", "exc_info", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.save_task_result
save the result of a completed task.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def save_task_result(self, idents, msg): """save the result of a completed task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::invalid task result message send to %r: %r", client_id, msg, exc_info=True) return parent = msg['parent_header'] if not parent: # print msg self.log.warn("Task %r had no parent!", msg) return msg_id = parent['msg_id'] if msg_id in self.unassigned: self.unassigned.remove(msg_id) header = msg['header'] engine_uuid = header.get('engine', u'') eid = self.by_ident.get(cast_bytes(engine_uuid), None) status = header.get('status', None) if msg_id in self.pending: self.log.info("task::task %r finished on %s", msg_id, eid) self.pending.remove(msg_id) self.all_completed.add(msg_id) if eid is not None: if status != 'aborted': self.completed[eid].append(msg_id) if msg_id in self.tasks[eid]: self.tasks[eid].remove(msg_id) completed = header['date'] started = header.get('started', None) result = { 'result_header' : header, 'result_content': msg['content'], 'started' : started, 'completed' : completed, 'received' : datetime.now(), 'engine_uuid': engine_uuid, } result['result_buffers'] = msg['buffers'] try: self.db.update_record(msg_id, result) except Exception: self.log.error("DB Error saving task request %r", msg_id, exc_info=True) else: self.log.debug("task::unknown task %r finished", msg_id)
def save_task_result(self, idents, msg): """save the result of a completed task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::invalid task result message send to %r: %r", client_id, msg, exc_info=True) return parent = msg['parent_header'] if not parent: # print msg self.log.warn("Task %r had no parent!", msg) return msg_id = parent['msg_id'] if msg_id in self.unassigned: self.unassigned.remove(msg_id) header = msg['header'] engine_uuid = header.get('engine', u'') eid = self.by_ident.get(cast_bytes(engine_uuid), None) status = header.get('status', None) if msg_id in self.pending: self.log.info("task::task %r finished on %s", msg_id, eid) self.pending.remove(msg_id) self.all_completed.add(msg_id) if eid is not None: if status != 'aborted': self.completed[eid].append(msg_id) if msg_id in self.tasks[eid]: self.tasks[eid].remove(msg_id) completed = header['date'] started = header.get('started', None) result = { 'result_header' : header, 'result_content': msg['content'], 'started' : started, 'completed' : completed, 'received' : datetime.now(), 'engine_uuid': engine_uuid, } result['result_buffers'] = msg['buffers'] try: self.db.update_record(msg_id, result) except Exception: self.log.error("DB Error saving task request %r", msg_id, exc_info=True) else: self.log.debug("task::unknown task %r finished", msg_id)
[ "save", "the", "result", "of", "a", "completed", "task", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L719-L771
[ "def", "save_task_result", "(", "self", ",", "idents", ",", "msg", ")", ":", "client_id", "=", "idents", "[", "0", "]", "try", ":", "msg", "=", "self", ".", "session", ".", "unserialize", "(", "msg", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"task::invalid task result message send to %r: %r\"", ",", "client_id", ",", "msg", ",", "exc_info", "=", "True", ")", "return", "parent", "=", "msg", "[", "'parent_header'", "]", "if", "not", "parent", ":", "# print msg", "self", ".", "log", ".", "warn", "(", "\"Task %r had no parent!\"", ",", "msg", ")", "return", "msg_id", "=", "parent", "[", "'msg_id'", "]", "if", "msg_id", "in", "self", ".", "unassigned", ":", "self", ".", "unassigned", ".", "remove", "(", "msg_id", ")", "header", "=", "msg", "[", "'header'", "]", "engine_uuid", "=", "header", ".", "get", "(", "'engine'", ",", "u''", ")", "eid", "=", "self", ".", "by_ident", ".", "get", "(", "cast_bytes", "(", "engine_uuid", ")", ",", "None", ")", "status", "=", "header", ".", "get", "(", "'status'", ",", "None", ")", "if", "msg_id", "in", "self", ".", "pending", ":", "self", ".", "log", ".", "info", "(", "\"task::task %r finished on %s\"", ",", "msg_id", ",", "eid", ")", "self", ".", "pending", ".", "remove", "(", "msg_id", ")", "self", ".", "all_completed", ".", "add", "(", "msg_id", ")", "if", "eid", "is", "not", "None", ":", "if", "status", "!=", "'aborted'", ":", "self", ".", "completed", "[", "eid", "]", ".", "append", "(", "msg_id", ")", "if", "msg_id", "in", "self", ".", "tasks", "[", "eid", "]", ":", "self", ".", "tasks", "[", "eid", "]", ".", "remove", "(", "msg_id", ")", "completed", "=", "header", "[", "'date'", "]", "started", "=", "header", ".", "get", "(", "'started'", ",", "None", ")", "result", "=", "{", "'result_header'", ":", "header", ",", "'result_content'", ":", "msg", "[", "'content'", "]", ",", "'started'", ":", "started", ",", "'completed'", ":", "completed", ",", "'received'", ":", "datetime", ".", "now", "(", ")", ",", "'engine_uuid'", ":", "engine_uuid", ",", "}", "result", "[", "'result_buffers'", "]", "=", "msg", "[", "'buffers'", "]", "try", ":", "self", ".", "db", ".", "update_record", "(", "msg_id", ",", "result", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"DB Error saving task request %r\"", ",", "msg_id", ",", "exc_info", "=", "True", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "\"task::unknown task %r finished\"", ",", "msg_id", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.save_iopub_message
save an iopub message into the db
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def save_iopub_message(self, topics, msg): """save an iopub message into the db""" # print (topics) try: msg = self.session.unserialize(msg, content=True) except Exception: self.log.error("iopub::invalid IOPub message", exc_info=True) return parent = msg['parent_header'] if not parent: self.log.warn("iopub::IOPub message lacks parent: %r", msg) return msg_id = parent['msg_id'] msg_type = msg['header']['msg_type'] content = msg['content'] # ensure msg_id is in db try: rec = self.db.get_record(msg_id) except KeyError: rec = empty_record() rec['msg_id'] = msg_id self.db.add_record(msg_id, rec) # stream d = {} if msg_type == 'stream': name = content['name'] s = rec[name] or '' d[name] = s + content['data'] elif msg_type == 'pyerr': d['pyerr'] = content elif msg_type == 'pyin': d['pyin'] = content['code'] elif msg_type in ('display_data', 'pyout'): d[msg_type] = content elif msg_type == 'status': pass else: self.log.warn("unhandled iopub msg_type: %r", msg_type) if not d: return try: self.db.update_record(msg_id, d) except Exception: self.log.error("DB Error saving iopub message %r", msg_id, exc_info=True)
def save_iopub_message(self, topics, msg): """save an iopub message into the db""" # print (topics) try: msg = self.session.unserialize(msg, content=True) except Exception: self.log.error("iopub::invalid IOPub message", exc_info=True) return parent = msg['parent_header'] if not parent: self.log.warn("iopub::IOPub message lacks parent: %r", msg) return msg_id = parent['msg_id'] msg_type = msg['header']['msg_type'] content = msg['content'] # ensure msg_id is in db try: rec = self.db.get_record(msg_id) except KeyError: rec = empty_record() rec['msg_id'] = msg_id self.db.add_record(msg_id, rec) # stream d = {} if msg_type == 'stream': name = content['name'] s = rec[name] or '' d[name] = s + content['data'] elif msg_type == 'pyerr': d['pyerr'] = content elif msg_type == 'pyin': d['pyin'] = content['code'] elif msg_type in ('display_data', 'pyout'): d[msg_type] = content elif msg_type == 'status': pass else: self.log.warn("unhandled iopub msg_type: %r", msg_type) if not d: return try: self.db.update_record(msg_id, d) except Exception: self.log.error("DB Error saving iopub message %r", msg_id, exc_info=True)
[ "save", "an", "iopub", "message", "into", "the", "db" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L808-L856
[ "def", "save_iopub_message", "(", "self", ",", "topics", ",", "msg", ")", ":", "# print (topics)", "try", ":", "msg", "=", "self", ".", "session", ".", "unserialize", "(", "msg", ",", "content", "=", "True", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"iopub::invalid IOPub message\"", ",", "exc_info", "=", "True", ")", "return", "parent", "=", "msg", "[", "'parent_header'", "]", "if", "not", "parent", ":", "self", ".", "log", ".", "warn", "(", "\"iopub::IOPub message lacks parent: %r\"", ",", "msg", ")", "return", "msg_id", "=", "parent", "[", "'msg_id'", "]", "msg_type", "=", "msg", "[", "'header'", "]", "[", "'msg_type'", "]", "content", "=", "msg", "[", "'content'", "]", "# ensure msg_id is in db", "try", ":", "rec", "=", "self", ".", "db", ".", "get_record", "(", "msg_id", ")", "except", "KeyError", ":", "rec", "=", "empty_record", "(", ")", "rec", "[", "'msg_id'", "]", "=", "msg_id", "self", ".", "db", ".", "add_record", "(", "msg_id", ",", "rec", ")", "# stream", "d", "=", "{", "}", "if", "msg_type", "==", "'stream'", ":", "name", "=", "content", "[", "'name'", "]", "s", "=", "rec", "[", "name", "]", "or", "''", "d", "[", "name", "]", "=", "s", "+", "content", "[", "'data'", "]", "elif", "msg_type", "==", "'pyerr'", ":", "d", "[", "'pyerr'", "]", "=", "content", "elif", "msg_type", "==", "'pyin'", ":", "d", "[", "'pyin'", "]", "=", "content", "[", "'code'", "]", "elif", "msg_type", "in", "(", "'display_data'", ",", "'pyout'", ")", ":", "d", "[", "msg_type", "]", "=", "content", "elif", "msg_type", "==", "'status'", ":", "pass", "else", ":", "self", ".", "log", ".", "warn", "(", "\"unhandled iopub msg_type: %r\"", ",", "msg_type", ")", "if", "not", "d", ":", "return", "try", ":", "self", ".", "db", ".", "update_record", "(", "msg_id", ",", "d", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"DB Error saving iopub message %r\"", ",", "msg_id", ",", "exc_info", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.connection_request
Reply with connection addresses for clients.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def connection_request(self, client_id, msg): """Reply with connection addresses for clients.""" self.log.info("client::client %r connected", client_id) content = dict(status='ok') content.update(self.client_info) jsonable = {} for k,v in self.keytable.iteritems(): if v not in self.dead_engines: jsonable[str(k)] = v.decode('ascii') content['engines'] = jsonable self.session.send(self.query, 'connection_reply', content, parent=msg, ident=client_id)
def connection_request(self, client_id, msg): """Reply with connection addresses for clients.""" self.log.info("client::client %r connected", client_id) content = dict(status='ok') content.update(self.client_info) jsonable = {} for k,v in self.keytable.iteritems(): if v not in self.dead_engines: jsonable[str(k)] = v.decode('ascii') content['engines'] = jsonable self.session.send(self.query, 'connection_reply', content, parent=msg, ident=client_id)
[ "Reply", "with", "connection", "addresses", "for", "clients", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L864-L874
[ "def", "connection_request", "(", "self", ",", "client_id", ",", "msg", ")", ":", "self", ".", "log", ".", "info", "(", "\"client::client %r connected\"", ",", "client_id", ")", "content", "=", "dict", "(", "status", "=", "'ok'", ")", "content", ".", "update", "(", "self", ".", "client_info", ")", "jsonable", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "keytable", ".", "iteritems", "(", ")", ":", "if", "v", "not", "in", "self", ".", "dead_engines", ":", "jsonable", "[", "str", "(", "k", ")", "]", "=", "v", ".", "decode", "(", "'ascii'", ")", "content", "[", "'engines'", "]", "=", "jsonable", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "'connection_reply'", ",", "content", ",", "parent", "=", "msg", ",", "ident", "=", "client_id", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.register_engine
Register a new engine.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def register_engine(self, reg, msg): """Register a new engine.""" content = msg['content'] try: queue = cast_bytes(content['queue']) except KeyError: self.log.error("registration::queue not specified", exc_info=True) return heart = content.get('heartbeat', None) if heart: heart = cast_bytes(heart) """register a new engine, and create the socket(s) necessary""" eid = self._next_id # print (eid, queue, reg, heart) self.log.debug("registration::register_engine(%i, %r, %r, %r)", eid, queue, reg, heart) content = dict(id=eid,status='ok') content.update(self.engine_info) # check if requesting available IDs: if queue in self.by_ident: try: raise KeyError("queue_id %r in use" % queue) except: content = error.wrap_exception() self.log.error("queue_id %r in use", queue, exc_info=True) elif heart in self.hearts: # need to check unique hearts? try: raise KeyError("heart_id %r in use" % heart) except: self.log.error("heart_id %r in use", heart, exc_info=True) content = error.wrap_exception() else: for h, pack in self.incoming_registrations.iteritems(): if heart == h: try: raise KeyError("heart_id %r in use" % heart) except: self.log.error("heart_id %r in use", heart, exc_info=True) content = error.wrap_exception() break elif queue == pack[1]: try: raise KeyError("queue_id %r in use" % queue) except: self.log.error("queue_id %r in use", queue, exc_info=True) content = error.wrap_exception() break msg = self.session.send(self.query, "registration_reply", content=content, ident=reg) if content['status'] == 'ok': if heart in self.heartmonitor.hearts: # already beating self.incoming_registrations[heart] = (eid,queue,reg[0],None) self.finish_registration(heart) else: purge = lambda : self._purge_stalled_registration(heart) dc = ioloop.DelayedCallback(purge, self.registration_timeout, self.loop) dc.start() self.incoming_registrations[heart] = (eid,queue,reg[0],dc) else: self.log.error("registration::registration %i failed: %r", eid, content['evalue']) return eid
def register_engine(self, reg, msg): """Register a new engine.""" content = msg['content'] try: queue = cast_bytes(content['queue']) except KeyError: self.log.error("registration::queue not specified", exc_info=True) return heart = content.get('heartbeat', None) if heart: heart = cast_bytes(heart) """register a new engine, and create the socket(s) necessary""" eid = self._next_id # print (eid, queue, reg, heart) self.log.debug("registration::register_engine(%i, %r, %r, %r)", eid, queue, reg, heart) content = dict(id=eid,status='ok') content.update(self.engine_info) # check if requesting available IDs: if queue in self.by_ident: try: raise KeyError("queue_id %r in use" % queue) except: content = error.wrap_exception() self.log.error("queue_id %r in use", queue, exc_info=True) elif heart in self.hearts: # need to check unique hearts? try: raise KeyError("heart_id %r in use" % heart) except: self.log.error("heart_id %r in use", heart, exc_info=True) content = error.wrap_exception() else: for h, pack in self.incoming_registrations.iteritems(): if heart == h: try: raise KeyError("heart_id %r in use" % heart) except: self.log.error("heart_id %r in use", heart, exc_info=True) content = error.wrap_exception() break elif queue == pack[1]: try: raise KeyError("queue_id %r in use" % queue) except: self.log.error("queue_id %r in use", queue, exc_info=True) content = error.wrap_exception() break msg = self.session.send(self.query, "registration_reply", content=content, ident=reg) if content['status'] == 'ok': if heart in self.heartmonitor.hearts: # already beating self.incoming_registrations[heart] = (eid,queue,reg[0],None) self.finish_registration(heart) else: purge = lambda : self._purge_stalled_registration(heart) dc = ioloop.DelayedCallback(purge, self.registration_timeout, self.loop) dc.start() self.incoming_registrations[heart] = (eid,queue,reg[0],dc) else: self.log.error("registration::registration %i failed: %r", eid, content['evalue']) return eid
[ "Register", "a", "new", "engine", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L876-L941
[ "def", "register_engine", "(", "self", ",", "reg", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "try", ":", "queue", "=", "cast_bytes", "(", "content", "[", "'queue'", "]", ")", "except", "KeyError", ":", "self", ".", "log", ".", "error", "(", "\"registration::queue not specified\"", ",", "exc_info", "=", "True", ")", "return", "heart", "=", "content", ".", "get", "(", "'heartbeat'", ",", "None", ")", "if", "heart", ":", "heart", "=", "cast_bytes", "(", "heart", ")", "\"\"\"register a new engine, and create the socket(s) necessary\"\"\"", "eid", "=", "self", ".", "_next_id", "# print (eid, queue, reg, heart)", "self", ".", "log", ".", "debug", "(", "\"registration::register_engine(%i, %r, %r, %r)\"", ",", "eid", ",", "queue", ",", "reg", ",", "heart", ")", "content", "=", "dict", "(", "id", "=", "eid", ",", "status", "=", "'ok'", ")", "content", ".", "update", "(", "self", ".", "engine_info", ")", "# check if requesting available IDs:", "if", "queue", "in", "self", ".", "by_ident", ":", "try", ":", "raise", "KeyError", "(", "\"queue_id %r in use\"", "%", "queue", ")", "except", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "self", ".", "log", ".", "error", "(", "\"queue_id %r in use\"", ",", "queue", ",", "exc_info", "=", "True", ")", "elif", "heart", "in", "self", ".", "hearts", ":", "# need to check unique hearts?", "try", ":", "raise", "KeyError", "(", "\"heart_id %r in use\"", "%", "heart", ")", "except", ":", "self", ".", "log", ".", "error", "(", "\"heart_id %r in use\"", ",", "heart", ",", "exc_info", "=", "True", ")", "content", "=", "error", ".", "wrap_exception", "(", ")", "else", ":", "for", "h", ",", "pack", "in", "self", ".", "incoming_registrations", ".", "iteritems", "(", ")", ":", "if", "heart", "==", "h", ":", "try", ":", "raise", "KeyError", "(", "\"heart_id %r in use\"", "%", "heart", ")", "except", ":", "self", ".", "log", ".", "error", "(", "\"heart_id %r in use\"", ",", "heart", ",", "exc_info", "=", "True", ")", "content", "=", "error", ".", "wrap_exception", "(", ")", "break", "elif", "queue", "==", "pack", "[", "1", "]", ":", "try", ":", "raise", "KeyError", "(", "\"queue_id %r in use\"", "%", "queue", ")", "except", ":", "self", ".", "log", ".", "error", "(", "\"queue_id %r in use\"", ",", "queue", ",", "exc_info", "=", "True", ")", "content", "=", "error", ".", "wrap_exception", "(", ")", "break", "msg", "=", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"registration_reply\"", ",", "content", "=", "content", ",", "ident", "=", "reg", ")", "if", "content", "[", "'status'", "]", "==", "'ok'", ":", "if", "heart", "in", "self", ".", "heartmonitor", ".", "hearts", ":", "# already beating", "self", ".", "incoming_registrations", "[", "heart", "]", "=", "(", "eid", ",", "queue", ",", "reg", "[", "0", "]", ",", "None", ")", "self", ".", "finish_registration", "(", "heart", ")", "else", ":", "purge", "=", "lambda", ":", "self", ".", "_purge_stalled_registration", "(", "heart", ")", "dc", "=", "ioloop", ".", "DelayedCallback", "(", "purge", ",", "self", ".", "registration_timeout", ",", "self", ".", "loop", ")", "dc", ".", "start", "(", ")", "self", ".", "incoming_registrations", "[", "heart", "]", "=", "(", "eid", ",", "queue", ",", "reg", "[", "0", "]", ",", "dc", ")", "else", ":", "self", ".", "log", ".", "error", "(", "\"registration::registration %i failed: %r\"", ",", "eid", ",", "content", "[", "'evalue'", "]", ")", "return", "eid" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.unregister_engine
Unregister an engine that explicitly requested to leave.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def unregister_engine(self, ident, msg): """Unregister an engine that explicitly requested to leave.""" try: eid = msg['content']['id'] except: self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True) return self.log.info("registration::unregister_engine(%r)", eid) # print (eid) uuid = self.keytable[eid] content=dict(id=eid, queue=uuid.decode('ascii')) self.dead_engines.add(uuid) # self.ids.remove(eid) # uuid = self.keytable.pop(eid) # # ec = self.engines.pop(eid) # self.hearts.pop(ec.heartbeat) # self.by_ident.pop(ec.queue) # self.completed.pop(eid) handleit = lambda : self._handle_stranded_msgs(eid, uuid) dc = ioloop.DelayedCallback(handleit, self.registration_timeout, self.loop) dc.start() ############## TODO: HANDLE IT ################ if self.notifier: self.session.send(self.notifier, "unregistration_notification", content=content)
def unregister_engine(self, ident, msg): """Unregister an engine that explicitly requested to leave.""" try: eid = msg['content']['id'] except: self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True) return self.log.info("registration::unregister_engine(%r)", eid) # print (eid) uuid = self.keytable[eid] content=dict(id=eid, queue=uuid.decode('ascii')) self.dead_engines.add(uuid) # self.ids.remove(eid) # uuid = self.keytable.pop(eid) # # ec = self.engines.pop(eid) # self.hearts.pop(ec.heartbeat) # self.by_ident.pop(ec.queue) # self.completed.pop(eid) handleit = lambda : self._handle_stranded_msgs(eid, uuid) dc = ioloop.DelayedCallback(handleit, self.registration_timeout, self.loop) dc.start() ############## TODO: HANDLE IT ################ if self.notifier: self.session.send(self.notifier, "unregistration_notification", content=content)
[ "Unregister", "an", "engine", "that", "explicitly", "requested", "to", "leave", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L943-L968
[ "def", "unregister_engine", "(", "self", ",", "ident", ",", "msg", ")", ":", "try", ":", "eid", "=", "msg", "[", "'content'", "]", "[", "'id'", "]", "except", ":", "self", ".", "log", ".", "error", "(", "\"registration::bad engine id for unregistration: %r\"", ",", "ident", ",", "exc_info", "=", "True", ")", "return", "self", ".", "log", ".", "info", "(", "\"registration::unregister_engine(%r)\"", ",", "eid", ")", "# print (eid)", "uuid", "=", "self", ".", "keytable", "[", "eid", "]", "content", "=", "dict", "(", "id", "=", "eid", ",", "queue", "=", "uuid", ".", "decode", "(", "'ascii'", ")", ")", "self", ".", "dead_engines", ".", "add", "(", "uuid", ")", "# self.ids.remove(eid)", "# uuid = self.keytable.pop(eid)", "#", "# ec = self.engines.pop(eid)", "# self.hearts.pop(ec.heartbeat)", "# self.by_ident.pop(ec.queue)", "# self.completed.pop(eid)", "handleit", "=", "lambda", ":", "self", ".", "_handle_stranded_msgs", "(", "eid", ",", "uuid", ")", "dc", "=", "ioloop", ".", "DelayedCallback", "(", "handleit", ",", "self", ".", "registration_timeout", ",", "self", ".", "loop", ")", "dc", ".", "start", "(", ")", "############## TODO: HANDLE IT ################", "if", "self", ".", "notifier", ":", "self", ".", "session", ".", "send", "(", "self", ".", "notifier", ",", "\"unregistration_notification\"", ",", "content", "=", "content", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub._handle_stranded_msgs
Handle messages known to be on an engine when the engine unregisters. It is possible that this will fire prematurely - that is, an engine will go down after completing a result, and the client will be notified that the result failed and later receive the actual result.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def _handle_stranded_msgs(self, eid, uuid): """Handle messages known to be on an engine when the engine unregisters. It is possible that this will fire prematurely - that is, an engine will go down after completing a result, and the client will be notified that the result failed and later receive the actual result. """ outstanding = self.queues[eid] for msg_id in outstanding: self.pending.remove(msg_id) self.all_completed.add(msg_id) try: raise error.EngineError("Engine %r died while running task %r" % (eid, msg_id)) except: content = error.wrap_exception() # build a fake header: header = {} header['engine'] = uuid header['date'] = datetime.now() rec = dict(result_content=content, result_header=header, result_buffers=[]) rec['completed'] = header['date'] rec['engine_uuid'] = uuid try: self.db.update_record(msg_id, rec) except Exception: self.log.error("DB Error handling stranded msg %r", msg_id, exc_info=True)
def _handle_stranded_msgs(self, eid, uuid): """Handle messages known to be on an engine when the engine unregisters. It is possible that this will fire prematurely - that is, an engine will go down after completing a result, and the client will be notified that the result failed and later receive the actual result. """ outstanding = self.queues[eid] for msg_id in outstanding: self.pending.remove(msg_id) self.all_completed.add(msg_id) try: raise error.EngineError("Engine %r died while running task %r" % (eid, msg_id)) except: content = error.wrap_exception() # build a fake header: header = {} header['engine'] = uuid header['date'] = datetime.now() rec = dict(result_content=content, result_header=header, result_buffers=[]) rec['completed'] = header['date'] rec['engine_uuid'] = uuid try: self.db.update_record(msg_id, rec) except Exception: self.log.error("DB Error handling stranded msg %r", msg_id, exc_info=True)
[ "Handle", "messages", "known", "to", "be", "on", "an", "engine", "when", "the", "engine", "unregisters", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L970-L997
[ "def", "_handle_stranded_msgs", "(", "self", ",", "eid", ",", "uuid", ")", ":", "outstanding", "=", "self", ".", "queues", "[", "eid", "]", "for", "msg_id", "in", "outstanding", ":", "self", ".", "pending", ".", "remove", "(", "msg_id", ")", "self", ".", "all_completed", ".", "add", "(", "msg_id", ")", "try", ":", "raise", "error", ".", "EngineError", "(", "\"Engine %r died while running task %r\"", "%", "(", "eid", ",", "msg_id", ")", ")", "except", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "# build a fake header:", "header", "=", "{", "}", "header", "[", "'engine'", "]", "=", "uuid", "header", "[", "'date'", "]", "=", "datetime", ".", "now", "(", ")", "rec", "=", "dict", "(", "result_content", "=", "content", ",", "result_header", "=", "header", ",", "result_buffers", "=", "[", "]", ")", "rec", "[", "'completed'", "]", "=", "header", "[", "'date'", "]", "rec", "[", "'engine_uuid'", "]", "=", "uuid", "try", ":", "self", ".", "db", ".", "update_record", "(", "msg_id", ",", "rec", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"DB Error handling stranded msg %r\"", ",", "msg_id", ",", "exc_info", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.finish_registration
Second half of engine registration, called after our HeartMonitor has received a beat from the Engine's Heart.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def finish_registration(self, heart): """Second half of engine registration, called after our HeartMonitor has received a beat from the Engine's Heart.""" try: (eid,queue,reg,purge) = self.incoming_registrations.pop(heart) except KeyError: self.log.error("registration::tried to finish nonexistant registration", exc_info=True) return self.log.info("registration::finished registering engine %i:%r", eid, queue) if purge is not None: purge.stop() control = queue self.ids.add(eid) self.keytable[eid] = queue self.engines[eid] = EngineConnector(id=eid, queue=queue, registration=reg, control=control, heartbeat=heart) self.by_ident[queue] = eid self.queues[eid] = list() self.tasks[eid] = list() self.completed[eid] = list() self.hearts[heart] = eid content = dict(id=eid, queue=self.engines[eid].queue.decode('ascii')) if self.notifier: self.session.send(self.notifier, "registration_notification", content=content) self.log.info("engine::Engine Connected: %i", eid)
def finish_registration(self, heart): """Second half of engine registration, called after our HeartMonitor has received a beat from the Engine's Heart.""" try: (eid,queue,reg,purge) = self.incoming_registrations.pop(heart) except KeyError: self.log.error("registration::tried to finish nonexistant registration", exc_info=True) return self.log.info("registration::finished registering engine %i:%r", eid, queue) if purge is not None: purge.stop() control = queue self.ids.add(eid) self.keytable[eid] = queue self.engines[eid] = EngineConnector(id=eid, queue=queue, registration=reg, control=control, heartbeat=heart) self.by_ident[queue] = eid self.queues[eid] = list() self.tasks[eid] = list() self.completed[eid] = list() self.hearts[heart] = eid content = dict(id=eid, queue=self.engines[eid].queue.decode('ascii')) if self.notifier: self.session.send(self.notifier, "registration_notification", content=content) self.log.info("engine::Engine Connected: %i", eid)
[ "Second", "half", "of", "engine", "registration", "called", "after", "our", "HeartMonitor", "has", "received", "a", "beat", "from", "the", "Engine", "s", "Heart", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1000-L1024
[ "def", "finish_registration", "(", "self", ",", "heart", ")", ":", "try", ":", "(", "eid", ",", "queue", ",", "reg", ",", "purge", ")", "=", "self", ".", "incoming_registrations", ".", "pop", "(", "heart", ")", "except", "KeyError", ":", "self", ".", "log", ".", "error", "(", "\"registration::tried to finish nonexistant registration\"", ",", "exc_info", "=", "True", ")", "return", "self", ".", "log", ".", "info", "(", "\"registration::finished registering engine %i:%r\"", ",", "eid", ",", "queue", ")", "if", "purge", "is", "not", "None", ":", "purge", ".", "stop", "(", ")", "control", "=", "queue", "self", ".", "ids", ".", "add", "(", "eid", ")", "self", ".", "keytable", "[", "eid", "]", "=", "queue", "self", ".", "engines", "[", "eid", "]", "=", "EngineConnector", "(", "id", "=", "eid", ",", "queue", "=", "queue", ",", "registration", "=", "reg", ",", "control", "=", "control", ",", "heartbeat", "=", "heart", ")", "self", ".", "by_ident", "[", "queue", "]", "=", "eid", "self", ".", "queues", "[", "eid", "]", "=", "list", "(", ")", "self", ".", "tasks", "[", "eid", "]", "=", "list", "(", ")", "self", ".", "completed", "[", "eid", "]", "=", "list", "(", ")", "self", ".", "hearts", "[", "heart", "]", "=", "eid", "content", "=", "dict", "(", "id", "=", "eid", ",", "queue", "=", "self", ".", "engines", "[", "eid", "]", ".", "queue", ".", "decode", "(", "'ascii'", ")", ")", "if", "self", ".", "notifier", ":", "self", ".", "session", ".", "send", "(", "self", ".", "notifier", ",", "\"registration_notification\"", ",", "content", "=", "content", ")", "self", ".", "log", ".", "info", "(", "\"engine::Engine Connected: %i\"", ",", "eid", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.shutdown_request
handle shutdown request.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def shutdown_request(self, client_id, msg): """handle shutdown request.""" self.session.send(self.query, 'shutdown_reply', content={'status': 'ok'}, ident=client_id) # also notify other clients of shutdown self.session.send(self.notifier, 'shutdown_notice', content={'status': 'ok'}) dc = ioloop.DelayedCallback(lambda : self._shutdown(), 1000, self.loop) dc.start()
def shutdown_request(self, client_id, msg): """handle shutdown request.""" self.session.send(self.query, 'shutdown_reply', content={'status': 'ok'}, ident=client_id) # also notify other clients of shutdown self.session.send(self.notifier, 'shutdown_notice', content={'status': 'ok'}) dc = ioloop.DelayedCallback(lambda : self._shutdown(), 1000, self.loop) dc.start()
[ "handle", "shutdown", "request", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1037-L1043
[ "def", "shutdown_request", "(", "self", ",", "client_id", ",", "msg", ")", ":", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "'shutdown_reply'", ",", "content", "=", "{", "'status'", ":", "'ok'", "}", ",", "ident", "=", "client_id", ")", "# also notify other clients of shutdown", "self", ".", "session", ".", "send", "(", "self", ".", "notifier", ",", "'shutdown_notice'", ",", "content", "=", "{", "'status'", ":", "'ok'", "}", ")", "dc", "=", "ioloop", ".", "DelayedCallback", "(", "lambda", ":", "self", ".", "_shutdown", "(", ")", ",", "1000", ",", "self", ".", "loop", ")", "dc", ".", "start", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.queue_status
Return the Queue status of one or more targets. if verbose: return the msg_ids else: return len of each type. keys: queue (pending MUX jobs) tasks (pending Task jobs) completed (finished jobs from both queues)
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def queue_status(self, client_id, msg): """Return the Queue status of one or more targets. if verbose: return the msg_ids else: return len of each type. keys: queue (pending MUX jobs) tasks (pending Task jobs) completed (finished jobs from both queues)""" content = msg['content'] targets = content['targets'] try: targets = self._validate_targets(targets) except: content = error.wrap_exception() self.session.send(self.query, "hub_error", content=content, ident=client_id) return verbose = content.get('verbose', False) content = dict(status='ok') for t in targets: queue = self.queues[t] completed = self.completed[t] tasks = self.tasks[t] if not verbose: queue = len(queue) completed = len(completed) tasks = len(tasks) content[str(t)] = {'queue': queue, 'completed': completed , 'tasks': tasks} content['unassigned'] = list(self.unassigned) if verbose else len(self.unassigned) # print (content) self.session.send(self.query, "queue_reply", content=content, ident=client_id)
def queue_status(self, client_id, msg): """Return the Queue status of one or more targets. if verbose: return the msg_ids else: return len of each type. keys: queue (pending MUX jobs) tasks (pending Task jobs) completed (finished jobs from both queues)""" content = msg['content'] targets = content['targets'] try: targets = self._validate_targets(targets) except: content = error.wrap_exception() self.session.send(self.query, "hub_error", content=content, ident=client_id) return verbose = content.get('verbose', False) content = dict(status='ok') for t in targets: queue = self.queues[t] completed = self.completed[t] tasks = self.tasks[t] if not verbose: queue = len(queue) completed = len(completed) tasks = len(tasks) content[str(t)] = {'queue': queue, 'completed': completed , 'tasks': tasks} content['unassigned'] = list(self.unassigned) if verbose else len(self.unassigned) # print (content) self.session.send(self.query, "queue_reply", content=content, ident=client_id)
[ "Return", "the", "Queue", "status", "of", "one", "or", "more", "targets", ".", "if", "verbose", ":", "return", "the", "msg_ids", "else", ":", "return", "len", "of", "each", "type", ".", "keys", ":", "queue", "(", "pending", "MUX", "jobs", ")", "tasks", "(", "pending", "Task", "jobs", ")", "completed", "(", "finished", "jobs", "from", "both", "queues", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1069-L1098
[ "def", "queue_status", "(", "self", ",", "client_id", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "targets", "=", "content", "[", "'targets'", "]", "try", ":", "targets", "=", "self", ".", "_validate_targets", "(", "targets", ")", "except", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"hub_error\"", ",", "content", "=", "content", ",", "ident", "=", "client_id", ")", "return", "verbose", "=", "content", ".", "get", "(", "'verbose'", ",", "False", ")", "content", "=", "dict", "(", "status", "=", "'ok'", ")", "for", "t", "in", "targets", ":", "queue", "=", "self", ".", "queues", "[", "t", "]", "completed", "=", "self", ".", "completed", "[", "t", "]", "tasks", "=", "self", ".", "tasks", "[", "t", "]", "if", "not", "verbose", ":", "queue", "=", "len", "(", "queue", ")", "completed", "=", "len", "(", "completed", ")", "tasks", "=", "len", "(", "tasks", ")", "content", "[", "str", "(", "t", ")", "]", "=", "{", "'queue'", ":", "queue", ",", "'completed'", ":", "completed", ",", "'tasks'", ":", "tasks", "}", "content", "[", "'unassigned'", "]", "=", "list", "(", "self", ".", "unassigned", ")", "if", "verbose", "else", "len", "(", "self", ".", "unassigned", ")", "# print (content)", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"queue_reply\"", ",", "content", "=", "content", ",", "ident", "=", "client_id", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.purge_results
Purge results from memory. This method is more valuable before we move to a DB based message storage mechanism.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def purge_results(self, client_id, msg): """Purge results from memory. This method is more valuable before we move to a DB based message storage mechanism.""" content = msg['content'] self.log.info("Dropping records with %s", content) msg_ids = content.get('msg_ids', []) reply = dict(status='ok') if msg_ids == 'all': try: self.db.drop_matching_records(dict(completed={'$ne':None})) except Exception: reply = error.wrap_exception() else: pending = filter(lambda m: m in self.pending, msg_ids) if pending: try: raise IndexError("msg pending: %r" % pending[0]) except: reply = error.wrap_exception() else: try: self.db.drop_matching_records(dict(msg_id={'$in':msg_ids})) except Exception: reply = error.wrap_exception() if reply['status'] == 'ok': eids = content.get('engine_ids', []) for eid in eids: if eid not in self.engines: try: raise IndexError("No such engine: %i" % eid) except: reply = error.wrap_exception() break uid = self.engines[eid].queue try: self.db.drop_matching_records(dict(engine_uuid=uid, completed={'$ne':None})) except Exception: reply = error.wrap_exception() break self.session.send(self.query, 'purge_reply', content=reply, ident=client_id)
def purge_results(self, client_id, msg): """Purge results from memory. This method is more valuable before we move to a DB based message storage mechanism.""" content = msg['content'] self.log.info("Dropping records with %s", content) msg_ids = content.get('msg_ids', []) reply = dict(status='ok') if msg_ids == 'all': try: self.db.drop_matching_records(dict(completed={'$ne':None})) except Exception: reply = error.wrap_exception() else: pending = filter(lambda m: m in self.pending, msg_ids) if pending: try: raise IndexError("msg pending: %r" % pending[0]) except: reply = error.wrap_exception() else: try: self.db.drop_matching_records(dict(msg_id={'$in':msg_ids})) except Exception: reply = error.wrap_exception() if reply['status'] == 'ok': eids = content.get('engine_ids', []) for eid in eids: if eid not in self.engines: try: raise IndexError("No such engine: %i" % eid) except: reply = error.wrap_exception() break uid = self.engines[eid].queue try: self.db.drop_matching_records(dict(engine_uuid=uid, completed={'$ne':None})) except Exception: reply = error.wrap_exception() break self.session.send(self.query, 'purge_reply', content=reply, ident=client_id)
[ "Purge", "results", "from", "memory", ".", "This", "method", "is", "more", "valuable", "before", "we", "move", "to", "a", "DB", "based", "message", "storage", "mechanism", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1100-L1141
[ "def", "purge_results", "(", "self", ",", "client_id", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "self", ".", "log", ".", "info", "(", "\"Dropping records with %s\"", ",", "content", ")", "msg_ids", "=", "content", ".", "get", "(", "'msg_ids'", ",", "[", "]", ")", "reply", "=", "dict", "(", "status", "=", "'ok'", ")", "if", "msg_ids", "==", "'all'", ":", "try", ":", "self", ".", "db", ".", "drop_matching_records", "(", "dict", "(", "completed", "=", "{", "'$ne'", ":", "None", "}", ")", ")", "except", "Exception", ":", "reply", "=", "error", ".", "wrap_exception", "(", ")", "else", ":", "pending", "=", "filter", "(", "lambda", "m", ":", "m", "in", "self", ".", "pending", ",", "msg_ids", ")", "if", "pending", ":", "try", ":", "raise", "IndexError", "(", "\"msg pending: %r\"", "%", "pending", "[", "0", "]", ")", "except", ":", "reply", "=", "error", ".", "wrap_exception", "(", ")", "else", ":", "try", ":", "self", ".", "db", ".", "drop_matching_records", "(", "dict", "(", "msg_id", "=", "{", "'$in'", ":", "msg_ids", "}", ")", ")", "except", "Exception", ":", "reply", "=", "error", ".", "wrap_exception", "(", ")", "if", "reply", "[", "'status'", "]", "==", "'ok'", ":", "eids", "=", "content", ".", "get", "(", "'engine_ids'", ",", "[", "]", ")", "for", "eid", "in", "eids", ":", "if", "eid", "not", "in", "self", ".", "engines", ":", "try", ":", "raise", "IndexError", "(", "\"No such engine: %i\"", "%", "eid", ")", "except", ":", "reply", "=", "error", ".", "wrap_exception", "(", ")", "break", "uid", "=", "self", ".", "engines", "[", "eid", "]", ".", "queue", "try", ":", "self", ".", "db", ".", "drop_matching_records", "(", "dict", "(", "engine_uuid", "=", "uid", ",", "completed", "=", "{", "'$ne'", ":", "None", "}", ")", ")", "except", "Exception", ":", "reply", "=", "error", ".", "wrap_exception", "(", ")", "break", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "'purge_reply'", ",", "content", "=", "reply", ",", "ident", "=", "client_id", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.resubmit_task
Resubmit one or more tasks.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def resubmit_task(self, client_id, msg): """Resubmit one or more tasks.""" def finish(reply): self.session.send(self.query, 'resubmit_reply', content=reply, ident=client_id) content = msg['content'] msg_ids = content['msg_ids'] reply = dict(status='ok') try: records = self.db.find_records({'msg_id' : {'$in' : msg_ids}}, keys=[ 'header', 'content', 'buffers']) except Exception: self.log.error('db::db error finding tasks to resubmit', exc_info=True) return finish(error.wrap_exception()) # validate msg_ids found_ids = [ rec['msg_id'] for rec in records ] pending_ids = [ msg_id for msg_id in found_ids if msg_id in self.pending ] if len(records) > len(msg_ids): try: raise RuntimeError("DB appears to be in an inconsistent state." "More matching records were found than should exist") except Exception: return finish(error.wrap_exception()) elif len(records) < len(msg_ids): missing = [ m for m in msg_ids if m not in found_ids ] try: raise KeyError("No such msg(s): %r" % missing) except KeyError: return finish(error.wrap_exception()) elif pending_ids: pass # no need to raise on resubmit of pending task, now that we # resubmit under new ID, but do we want to raise anyway? # msg_id = invalid_ids[0] # try: # raise ValueError("Task(s) %r appears to be inflight" % ) # except Exception: # return finish(error.wrap_exception()) # mapping of original IDs to resubmitted IDs resubmitted = {} # send the messages for rec in records: header = rec['header'] msg = self.session.msg(header['msg_type'], parent=header) msg_id = msg['msg_id'] msg['content'] = rec['content'] # use the old header, but update msg_id and timestamp fresh = msg['header'] header['msg_id'] = fresh['msg_id'] header['date'] = fresh['date'] msg['header'] = header self.session.send(self.resubmit, msg, buffers=rec['buffers']) resubmitted[rec['msg_id']] = msg_id self.pending.add(msg_id) msg['buffers'] = rec['buffers'] try: self.db.add_record(msg_id, init_record(msg)) except Exception: self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True) finish(dict(status='ok', resubmitted=resubmitted)) # store the new IDs in the Task DB for msg_id, resubmit_id in resubmitted.iteritems(): try: self.db.update_record(msg_id, {'resubmitted' : resubmit_id}) except Exception: self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True)
def resubmit_task(self, client_id, msg): """Resubmit one or more tasks.""" def finish(reply): self.session.send(self.query, 'resubmit_reply', content=reply, ident=client_id) content = msg['content'] msg_ids = content['msg_ids'] reply = dict(status='ok') try: records = self.db.find_records({'msg_id' : {'$in' : msg_ids}}, keys=[ 'header', 'content', 'buffers']) except Exception: self.log.error('db::db error finding tasks to resubmit', exc_info=True) return finish(error.wrap_exception()) # validate msg_ids found_ids = [ rec['msg_id'] for rec in records ] pending_ids = [ msg_id for msg_id in found_ids if msg_id in self.pending ] if len(records) > len(msg_ids): try: raise RuntimeError("DB appears to be in an inconsistent state." "More matching records were found than should exist") except Exception: return finish(error.wrap_exception()) elif len(records) < len(msg_ids): missing = [ m for m in msg_ids if m not in found_ids ] try: raise KeyError("No such msg(s): %r" % missing) except KeyError: return finish(error.wrap_exception()) elif pending_ids: pass # no need to raise on resubmit of pending task, now that we # resubmit under new ID, but do we want to raise anyway? # msg_id = invalid_ids[0] # try: # raise ValueError("Task(s) %r appears to be inflight" % ) # except Exception: # return finish(error.wrap_exception()) # mapping of original IDs to resubmitted IDs resubmitted = {} # send the messages for rec in records: header = rec['header'] msg = self.session.msg(header['msg_type'], parent=header) msg_id = msg['msg_id'] msg['content'] = rec['content'] # use the old header, but update msg_id and timestamp fresh = msg['header'] header['msg_id'] = fresh['msg_id'] header['date'] = fresh['date'] msg['header'] = header self.session.send(self.resubmit, msg, buffers=rec['buffers']) resubmitted[rec['msg_id']] = msg_id self.pending.add(msg_id) msg['buffers'] = rec['buffers'] try: self.db.add_record(msg_id, init_record(msg)) except Exception: self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True) finish(dict(status='ok', resubmitted=resubmitted)) # store the new IDs in the Task DB for msg_id, resubmit_id in resubmitted.iteritems(): try: self.db.update_record(msg_id, {'resubmitted' : resubmit_id}) except Exception: self.log.error("db::DB Error updating record: %s", msg_id, exc_info=True)
[ "Resubmit", "one", "or", "more", "tasks", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1143-L1216
[ "def", "resubmit_task", "(", "self", ",", "client_id", ",", "msg", ")", ":", "def", "finish", "(", "reply", ")", ":", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "'resubmit_reply'", ",", "content", "=", "reply", ",", "ident", "=", "client_id", ")", "content", "=", "msg", "[", "'content'", "]", "msg_ids", "=", "content", "[", "'msg_ids'", "]", "reply", "=", "dict", "(", "status", "=", "'ok'", ")", "try", ":", "records", "=", "self", ".", "db", ".", "find_records", "(", "{", "'msg_id'", ":", "{", "'$in'", ":", "msg_ids", "}", "}", ",", "keys", "=", "[", "'header'", ",", "'content'", ",", "'buffers'", "]", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "'db::db error finding tasks to resubmit'", ",", "exc_info", "=", "True", ")", "return", "finish", "(", "error", ".", "wrap_exception", "(", ")", ")", "# validate msg_ids", "found_ids", "=", "[", "rec", "[", "'msg_id'", "]", "for", "rec", "in", "records", "]", "pending_ids", "=", "[", "msg_id", "for", "msg_id", "in", "found_ids", "if", "msg_id", "in", "self", ".", "pending", "]", "if", "len", "(", "records", ")", ">", "len", "(", "msg_ids", ")", ":", "try", ":", "raise", "RuntimeError", "(", "\"DB appears to be in an inconsistent state.\"", "\"More matching records were found than should exist\"", ")", "except", "Exception", ":", "return", "finish", "(", "error", ".", "wrap_exception", "(", ")", ")", "elif", "len", "(", "records", ")", "<", "len", "(", "msg_ids", ")", ":", "missing", "=", "[", "m", "for", "m", "in", "msg_ids", "if", "m", "not", "in", "found_ids", "]", "try", ":", "raise", "KeyError", "(", "\"No such msg(s): %r\"", "%", "missing", ")", "except", "KeyError", ":", "return", "finish", "(", "error", ".", "wrap_exception", "(", ")", ")", "elif", "pending_ids", ":", "pass", "# no need to raise on resubmit of pending task, now that we", "# resubmit under new ID, but do we want to raise anyway?", "# msg_id = invalid_ids[0]", "# try:", "# raise ValueError(\"Task(s) %r appears to be inflight\" % )", "# except Exception:", "# return finish(error.wrap_exception())", "# mapping of original IDs to resubmitted IDs", "resubmitted", "=", "{", "}", "# send the messages", "for", "rec", "in", "records", ":", "header", "=", "rec", "[", "'header'", "]", "msg", "=", "self", ".", "session", ".", "msg", "(", "header", "[", "'msg_type'", "]", ",", "parent", "=", "header", ")", "msg_id", "=", "msg", "[", "'msg_id'", "]", "msg", "[", "'content'", "]", "=", "rec", "[", "'content'", "]", "# use the old header, but update msg_id and timestamp", "fresh", "=", "msg", "[", "'header'", "]", "header", "[", "'msg_id'", "]", "=", "fresh", "[", "'msg_id'", "]", "header", "[", "'date'", "]", "=", "fresh", "[", "'date'", "]", "msg", "[", "'header'", "]", "=", "header", "self", ".", "session", ".", "send", "(", "self", ".", "resubmit", ",", "msg", ",", "buffers", "=", "rec", "[", "'buffers'", "]", ")", "resubmitted", "[", "rec", "[", "'msg_id'", "]", "]", "=", "msg_id", "self", ".", "pending", ".", "add", "(", "msg_id", ")", "msg", "[", "'buffers'", "]", "=", "rec", "[", "'buffers'", "]", "try", ":", "self", ".", "db", ".", "add_record", "(", "msg_id", ",", "init_record", "(", "msg", ")", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"db::DB Error updating record: %s\"", ",", "msg_id", ",", "exc_info", "=", "True", ")", "finish", "(", "dict", "(", "status", "=", "'ok'", ",", "resubmitted", "=", "resubmitted", ")", ")", "# store the new IDs in the Task DB", "for", "msg_id", ",", "resubmit_id", "in", "resubmitted", ".", "iteritems", "(", ")", ":", "try", ":", "self", ".", "db", ".", "update_record", "(", "msg_id", ",", "{", "'resubmitted'", ":", "resubmit_id", "}", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"db::DB Error updating record: %s\"", ",", "msg_id", ",", "exc_info", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub._extract_record
decompose a TaskRecord dict into subsection of reply for get_result
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def _extract_record(self, rec): """decompose a TaskRecord dict into subsection of reply for get_result""" io_dict = {} for key in ('pyin', 'pyout', 'pyerr', 'stdout', 'stderr'): io_dict[key] = rec[key] content = { 'result_content': rec['result_content'], 'header': rec['header'], 'result_header' : rec['result_header'], 'received' : rec['received'], 'io' : io_dict, } if rec['result_buffers']: buffers = map(bytes, rec['result_buffers']) else: buffers = [] return content, buffers
def _extract_record(self, rec): """decompose a TaskRecord dict into subsection of reply for get_result""" io_dict = {} for key in ('pyin', 'pyout', 'pyerr', 'stdout', 'stderr'): io_dict[key] = rec[key] content = { 'result_content': rec['result_content'], 'header': rec['header'], 'result_header' : rec['result_header'], 'received' : rec['received'], 'io' : io_dict, } if rec['result_buffers']: buffers = map(bytes, rec['result_buffers']) else: buffers = [] return content, buffers
[ "decompose", "a", "TaskRecord", "dict", "into", "subsection", "of", "reply", "for", "get_result" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1219-L1235
[ "def", "_extract_record", "(", "self", ",", "rec", ")", ":", "io_dict", "=", "{", "}", "for", "key", "in", "(", "'pyin'", ",", "'pyout'", ",", "'pyerr'", ",", "'stdout'", ",", "'stderr'", ")", ":", "io_dict", "[", "key", "]", "=", "rec", "[", "key", "]", "content", "=", "{", "'result_content'", ":", "rec", "[", "'result_content'", "]", ",", "'header'", ":", "rec", "[", "'header'", "]", ",", "'result_header'", ":", "rec", "[", "'result_header'", "]", ",", "'received'", ":", "rec", "[", "'received'", "]", ",", "'io'", ":", "io_dict", ",", "}", "if", "rec", "[", "'result_buffers'", "]", ":", "buffers", "=", "map", "(", "bytes", ",", "rec", "[", "'result_buffers'", "]", ")", "else", ":", "buffers", "=", "[", "]", "return", "content", ",", "buffers" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.get_results
Get the result of 1 or more messages.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def get_results(self, client_id, msg): """Get the result of 1 or more messages.""" content = msg['content'] msg_ids = sorted(set(content['msg_ids'])) statusonly = content.get('status_only', False) pending = [] completed = [] content = dict(status='ok') content['pending'] = pending content['completed'] = completed buffers = [] if not statusonly: try: matches = self.db.find_records(dict(msg_id={'$in':msg_ids})) # turn match list into dict, for faster lookup records = {} for rec in matches: records[rec['msg_id']] = rec except Exception: content = error.wrap_exception() self.session.send(self.query, "result_reply", content=content, parent=msg, ident=client_id) return else: records = {} for msg_id in msg_ids: if msg_id in self.pending: pending.append(msg_id) elif msg_id in self.all_completed: completed.append(msg_id) if not statusonly: c,bufs = self._extract_record(records[msg_id]) content[msg_id] = c buffers.extend(bufs) elif msg_id in records: if rec['completed']: completed.append(msg_id) c,bufs = self._extract_record(records[msg_id]) content[msg_id] = c buffers.extend(bufs) else: pending.append(msg_id) else: try: raise KeyError('No such message: '+msg_id) except: content = error.wrap_exception() break self.session.send(self.query, "result_reply", content=content, parent=msg, ident=client_id, buffers=buffers)
def get_results(self, client_id, msg): """Get the result of 1 or more messages.""" content = msg['content'] msg_ids = sorted(set(content['msg_ids'])) statusonly = content.get('status_only', False) pending = [] completed = [] content = dict(status='ok') content['pending'] = pending content['completed'] = completed buffers = [] if not statusonly: try: matches = self.db.find_records(dict(msg_id={'$in':msg_ids})) # turn match list into dict, for faster lookup records = {} for rec in matches: records[rec['msg_id']] = rec except Exception: content = error.wrap_exception() self.session.send(self.query, "result_reply", content=content, parent=msg, ident=client_id) return else: records = {} for msg_id in msg_ids: if msg_id in self.pending: pending.append(msg_id) elif msg_id in self.all_completed: completed.append(msg_id) if not statusonly: c,bufs = self._extract_record(records[msg_id]) content[msg_id] = c buffers.extend(bufs) elif msg_id in records: if rec['completed']: completed.append(msg_id) c,bufs = self._extract_record(records[msg_id]) content[msg_id] = c buffers.extend(bufs) else: pending.append(msg_id) else: try: raise KeyError('No such message: '+msg_id) except: content = error.wrap_exception() break self.session.send(self.query, "result_reply", content=content, parent=msg, ident=client_id, buffers=buffers)
[ "Get", "the", "result", "of", "1", "or", "more", "messages", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1237-L1287
[ "def", "get_results", "(", "self", ",", "client_id", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "msg_ids", "=", "sorted", "(", "set", "(", "content", "[", "'msg_ids'", "]", ")", ")", "statusonly", "=", "content", ".", "get", "(", "'status_only'", ",", "False", ")", "pending", "=", "[", "]", "completed", "=", "[", "]", "content", "=", "dict", "(", "status", "=", "'ok'", ")", "content", "[", "'pending'", "]", "=", "pending", "content", "[", "'completed'", "]", "=", "completed", "buffers", "=", "[", "]", "if", "not", "statusonly", ":", "try", ":", "matches", "=", "self", ".", "db", ".", "find_records", "(", "dict", "(", "msg_id", "=", "{", "'$in'", ":", "msg_ids", "}", ")", ")", "# turn match list into dict, for faster lookup", "records", "=", "{", "}", "for", "rec", "in", "matches", ":", "records", "[", "rec", "[", "'msg_id'", "]", "]", "=", "rec", "except", "Exception", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"result_reply\"", ",", "content", "=", "content", ",", "parent", "=", "msg", ",", "ident", "=", "client_id", ")", "return", "else", ":", "records", "=", "{", "}", "for", "msg_id", "in", "msg_ids", ":", "if", "msg_id", "in", "self", ".", "pending", ":", "pending", ".", "append", "(", "msg_id", ")", "elif", "msg_id", "in", "self", ".", "all_completed", ":", "completed", ".", "append", "(", "msg_id", ")", "if", "not", "statusonly", ":", "c", ",", "bufs", "=", "self", ".", "_extract_record", "(", "records", "[", "msg_id", "]", ")", "content", "[", "msg_id", "]", "=", "c", "buffers", ".", "extend", "(", "bufs", ")", "elif", "msg_id", "in", "records", ":", "if", "rec", "[", "'completed'", "]", ":", "completed", ".", "append", "(", "msg_id", ")", "c", ",", "bufs", "=", "self", ".", "_extract_record", "(", "records", "[", "msg_id", "]", ")", "content", "[", "msg_id", "]", "=", "c", "buffers", ".", "extend", "(", "bufs", ")", "else", ":", "pending", ".", "append", "(", "msg_id", ")", "else", ":", "try", ":", "raise", "KeyError", "(", "'No such message: '", "+", "msg_id", ")", "except", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "break", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"result_reply\"", ",", "content", "=", "content", ",", "parent", "=", "msg", ",", "ident", "=", "client_id", ",", "buffers", "=", "buffers", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.get_history
Get a list of all msg_ids in our DB records
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def get_history(self, client_id, msg): """Get a list of all msg_ids in our DB records""" try: msg_ids = self.db.get_history() except Exception as e: content = error.wrap_exception() else: content = dict(status='ok', history=msg_ids) self.session.send(self.query, "history_reply", content=content, parent=msg, ident=client_id)
def get_history(self, client_id, msg): """Get a list of all msg_ids in our DB records""" try: msg_ids = self.db.get_history() except Exception as e: content = error.wrap_exception() else: content = dict(status='ok', history=msg_ids) self.session.send(self.query, "history_reply", content=content, parent=msg, ident=client_id)
[ "Get", "a", "list", "of", "all", "msg_ids", "in", "our", "DB", "records" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1289-L1299
[ "def", "get_history", "(", "self", ",", "client_id", ",", "msg", ")", ":", "try", ":", "msg_ids", "=", "self", ".", "db", ".", "get_history", "(", ")", "except", "Exception", "as", "e", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "else", ":", "content", "=", "dict", "(", "status", "=", "'ok'", ",", "history", "=", "msg_ids", ")", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"history_reply\"", ",", "content", "=", "content", ",", "parent", "=", "msg", ",", "ident", "=", "client_id", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Hub.db_query
Perform a raw query on the task record database.
environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py
def db_query(self, client_id, msg): """Perform a raw query on the task record database.""" content = msg['content'] query = content.get('query', {}) keys = content.get('keys', None) buffers = [] empty = list() try: records = self.db.find_records(query, keys) except Exception as e: content = error.wrap_exception() else: # extract buffers from reply content: if keys is not None: buffer_lens = [] if 'buffers' in keys else None result_buffer_lens = [] if 'result_buffers' in keys else None else: buffer_lens = None result_buffer_lens = None for rec in records: # buffers may be None, so double check b = rec.pop('buffers', empty) or empty if buffer_lens is not None: buffer_lens.append(len(b)) buffers.extend(b) rb = rec.pop('result_buffers', empty) or empty if result_buffer_lens is not None: result_buffer_lens.append(len(rb)) buffers.extend(rb) content = dict(status='ok', records=records, buffer_lens=buffer_lens, result_buffer_lens=result_buffer_lens) # self.log.debug (content) self.session.send(self.query, "db_reply", content=content, parent=msg, ident=client_id, buffers=buffers)
def db_query(self, client_id, msg): """Perform a raw query on the task record database.""" content = msg['content'] query = content.get('query', {}) keys = content.get('keys', None) buffers = [] empty = list() try: records = self.db.find_records(query, keys) except Exception as e: content = error.wrap_exception() else: # extract buffers from reply content: if keys is not None: buffer_lens = [] if 'buffers' in keys else None result_buffer_lens = [] if 'result_buffers' in keys else None else: buffer_lens = None result_buffer_lens = None for rec in records: # buffers may be None, so double check b = rec.pop('buffers', empty) or empty if buffer_lens is not None: buffer_lens.append(len(b)) buffers.extend(b) rb = rec.pop('result_buffers', empty) or empty if result_buffer_lens is not None: result_buffer_lens.append(len(rb)) buffers.extend(rb) content = dict(status='ok', records=records, buffer_lens=buffer_lens, result_buffer_lens=result_buffer_lens) # self.log.debug (content) self.session.send(self.query, "db_reply", content=content, parent=msg, ident=client_id, buffers=buffers)
[ "Perform", "a", "raw", "query", "on", "the", "task", "record", "database", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/hub.py#L1301-L1336
[ "def", "db_query", "(", "self", ",", "client_id", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "query", "=", "content", ".", "get", "(", "'query'", ",", "{", "}", ")", "keys", "=", "content", ".", "get", "(", "'keys'", ",", "None", ")", "buffers", "=", "[", "]", "empty", "=", "list", "(", ")", "try", ":", "records", "=", "self", ".", "db", ".", "find_records", "(", "query", ",", "keys", ")", "except", "Exception", "as", "e", ":", "content", "=", "error", ".", "wrap_exception", "(", ")", "else", ":", "# extract buffers from reply content:", "if", "keys", "is", "not", "None", ":", "buffer_lens", "=", "[", "]", "if", "'buffers'", "in", "keys", "else", "None", "result_buffer_lens", "=", "[", "]", "if", "'result_buffers'", "in", "keys", "else", "None", "else", ":", "buffer_lens", "=", "None", "result_buffer_lens", "=", "None", "for", "rec", "in", "records", ":", "# buffers may be None, so double check", "b", "=", "rec", ".", "pop", "(", "'buffers'", ",", "empty", ")", "or", "empty", "if", "buffer_lens", "is", "not", "None", ":", "buffer_lens", ".", "append", "(", "len", "(", "b", ")", ")", "buffers", ".", "extend", "(", "b", ")", "rb", "=", "rec", ".", "pop", "(", "'result_buffers'", ",", "empty", ")", "or", "empty", "if", "result_buffer_lens", "is", "not", "None", ":", "result_buffer_lens", ".", "append", "(", "len", "(", "rb", ")", ")", "buffers", ".", "extend", "(", "rb", ")", "content", "=", "dict", "(", "status", "=", "'ok'", ",", "records", "=", "records", ",", "buffer_lens", "=", "buffer_lens", ",", "result_buffer_lens", "=", "result_buffer_lens", ")", "# self.log.debug (content)", "self", ".", "session", ".", "send", "(", "self", ".", "query", ",", "\"db_reply\"", ",", "content", "=", "content", ",", "parent", "=", "msg", ",", "ident", "=", "client_id", ",", "buffers", "=", "buffers", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Rscript.cd
go to the path
pyRscript/pyRscript.py
def cd(self, newdir): """ go to the path """ prevdir = os.getcwd() os.chdir(newdir) try: yield finally: os.chdir(prevdir)
def cd(self, newdir): """ go to the path """ prevdir = os.getcwd() os.chdir(newdir) try: yield finally: os.chdir(prevdir)
[ "go", "to", "the", "path" ]
chairco/pyRscript
python
https://github.com/chairco/pyRscript/blob/e952f450a873de52baa4fe80ed901f0cf990c0b7/pyRscript/pyRscript.py#L52-L61
[ "def", "cd", "(", "self", ",", "newdir", ")", ":", "prevdir", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir", "(", "newdir", ")", "try", ":", "yield", "finally", ":", "os", ".", "chdir", "(", "prevdir", ")" ]
e952f450a873de52baa4fe80ed901f0cf990c0b7
test
Rscript.decode_cmd_out
return a standard message
pyRscript/pyRscript.py
def decode_cmd_out(self, completed_cmd): """ return a standard message """ try: stdout = completed_cmd.stdout.encode('utf-8').decode() except AttributeError: try: stdout = str(bytes(completed_cmd.stdout), 'big5').strip() except AttributeError: stdout = str(bytes(completed_cmd.stdout).decode('utf-8')).strip() try: stderr = completed_cmd.stderr.encode('utf-8').decode() except AttributeError: try: stderr = str(bytes(completed_cmd.stderr), 'big5').strip() except AttributeError: stderr = str(bytes(completed_cmd.stderr).decode('utf-8')).strip() return ParsedCompletedCommand( completed_cmd.returncode, completed_cmd.args, stdout, stderr )
def decode_cmd_out(self, completed_cmd): """ return a standard message """ try: stdout = completed_cmd.stdout.encode('utf-8').decode() except AttributeError: try: stdout = str(bytes(completed_cmd.stdout), 'big5').strip() except AttributeError: stdout = str(bytes(completed_cmd.stdout).decode('utf-8')).strip() try: stderr = completed_cmd.stderr.encode('utf-8').decode() except AttributeError: try: stderr = str(bytes(completed_cmd.stderr), 'big5').strip() except AttributeError: stderr = str(bytes(completed_cmd.stderr).decode('utf-8')).strip() return ParsedCompletedCommand( completed_cmd.returncode, completed_cmd.args, stdout, stderr )
[ "return", "a", "standard", "message" ]
chairco/pyRscript
python
https://github.com/chairco/pyRscript/blob/e952f450a873de52baa4fe80ed901f0cf990c0b7/pyRscript/pyRscript.py#L63-L86
[ "def", "decode_cmd_out", "(", "self", ",", "completed_cmd", ")", ":", "try", ":", "stdout", "=", "completed_cmd", ".", "stdout", ".", "encode", "(", "'utf-8'", ")", ".", "decode", "(", ")", "except", "AttributeError", ":", "try", ":", "stdout", "=", "str", "(", "bytes", "(", "completed_cmd", ".", "stdout", ")", ",", "'big5'", ")", ".", "strip", "(", ")", "except", "AttributeError", ":", "stdout", "=", "str", "(", "bytes", "(", "completed_cmd", ".", "stdout", ")", ".", "decode", "(", "'utf-8'", ")", ")", ".", "strip", "(", ")", "try", ":", "stderr", "=", "completed_cmd", ".", "stderr", ".", "encode", "(", "'utf-8'", ")", ".", "decode", "(", ")", "except", "AttributeError", ":", "try", ":", "stderr", "=", "str", "(", "bytes", "(", "completed_cmd", ".", "stderr", ")", ",", "'big5'", ")", ".", "strip", "(", ")", "except", "AttributeError", ":", "stderr", "=", "str", "(", "bytes", "(", "completed_cmd", ".", "stderr", ")", ".", "decode", "(", "'utf-8'", ")", ")", ".", "strip", "(", ")", "return", "ParsedCompletedCommand", "(", "completed_cmd", ".", "returncode", ",", "completed_cmd", ".", "args", ",", "stdout", ",", "stderr", ")" ]
e952f450a873de52baa4fe80ed901f0cf990c0b7
test
Rscript.run_command_under_r_root
subprocess run on here
pyRscript/pyRscript.py
def run_command_under_r_root(self, cmd, catched=True): """ subprocess run on here """ RPATH = self.path with self.cd(newdir=RPATH): if catched: process = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE) else: process = sp.run(cmd) return process
def run_command_under_r_root(self, cmd, catched=True): """ subprocess run on here """ RPATH = self.path with self.cd(newdir=RPATH): if catched: process = sp.run(cmd, stdout=sp.PIPE, stderr=sp.PIPE) else: process = sp.run(cmd) return process
[ "subprocess", "run", "on", "here" ]
chairco/pyRscript
python
https://github.com/chairco/pyRscript/blob/e952f450a873de52baa4fe80ed901f0cf990c0b7/pyRscript/pyRscript.py#L88-L98
[ "def", "run_command_under_r_root", "(", "self", ",", "cmd", ",", "catched", "=", "True", ")", ":", "RPATH", "=", "self", ".", "path", "with", "self", ".", "cd", "(", "newdir", "=", "RPATH", ")", ":", "if", "catched", ":", "process", "=", "sp", ".", "run", "(", "cmd", ",", "stdout", "=", "sp", ".", "PIPE", ",", "stderr", "=", "sp", ".", "PIPE", ")", "else", ":", "process", "=", "sp", ".", "run", "(", "cmd", ")", "return", "process" ]
e952f450a873de52baa4fe80ed901f0cf990c0b7
test
Rscript.execute
Execute R script
pyRscript/pyRscript.py
def execute(self): """ Execute R script """ rprocess = OrderedDict() commands = OrderedDict([ (self.file, ['Rscript', self.file] + self.cmd), ]) for cmd_name, cmd in commands.items(): rprocess[cmd_name] = self.run_command_under_r_root(cmd) return self.decode_cmd_out(completed_cmd=rprocess[self.file])
def execute(self): """ Execute R script """ rprocess = OrderedDict() commands = OrderedDict([ (self.file, ['Rscript', self.file] + self.cmd), ]) for cmd_name, cmd in commands.items(): rprocess[cmd_name] = self.run_command_under_r_root(cmd) return self.decode_cmd_out(completed_cmd=rprocess[self.file])
[ "Execute", "R", "script" ]
chairco/pyRscript
python
https://github.com/chairco/pyRscript/blob/e952f450a873de52baa4fe80ed901f0cf990c0b7/pyRscript/pyRscript.py#L100-L111
[ "def", "execute", "(", "self", ")", ":", "rprocess", "=", "OrderedDict", "(", ")", "commands", "=", "OrderedDict", "(", "[", "(", "self", ".", "file", ",", "[", "'Rscript'", ",", "self", ".", "file", "]", "+", "self", ".", "cmd", ")", ",", "]", ")", "for", "cmd_name", ",", "cmd", "in", "commands", ".", "items", "(", ")", ":", "rprocess", "[", "cmd_name", "]", "=", "self", ".", "run_command_under_r_root", "(", "cmd", ")", "return", "self", ".", "decode_cmd_out", "(", "completed_cmd", "=", "rprocess", "[", "self", ".", "file", "]", ")" ]
e952f450a873de52baa4fe80ed901f0cf990c0b7
test
BaseFrontendMixin._set_kernel_manager
Disconnect from the current kernel manager (if any) and set a new kernel manager.
environment/lib/python2.7/site-packages/IPython/frontend/qt/base_frontend_mixin.py
def _set_kernel_manager(self, kernel_manager): """ Disconnect from the current kernel manager (if any) and set a new kernel manager. """ # Disconnect the old kernel manager, if necessary. old_manager = self._kernel_manager if old_manager is not None: old_manager.started_kernel.disconnect(self._started_kernel) old_manager.started_channels.disconnect(self._started_channels) old_manager.stopped_channels.disconnect(self._stopped_channels) # Disconnect the old kernel manager's channels. old_manager.sub_channel.message_received.disconnect(self._dispatch) old_manager.shell_channel.message_received.disconnect(self._dispatch) old_manager.stdin_channel.message_received.disconnect(self._dispatch) old_manager.hb_channel.kernel_died.disconnect( self._handle_kernel_died) # Handle the case where the old kernel manager is still listening. if old_manager.channels_running: self._stopped_channels() # Set the new kernel manager. self._kernel_manager = kernel_manager if kernel_manager is None: return # Connect the new kernel manager. kernel_manager.started_kernel.connect(self._started_kernel) kernel_manager.started_channels.connect(self._started_channels) kernel_manager.stopped_channels.connect(self._stopped_channels) # Connect the new kernel manager's channels. kernel_manager.sub_channel.message_received.connect(self._dispatch) kernel_manager.shell_channel.message_received.connect(self._dispatch) kernel_manager.stdin_channel.message_received.connect(self._dispatch) kernel_manager.hb_channel.kernel_died.connect(self._handle_kernel_died) # Handle the case where the kernel manager started channels before # we connected. if kernel_manager.channels_running: self._started_channels()
def _set_kernel_manager(self, kernel_manager): """ Disconnect from the current kernel manager (if any) and set a new kernel manager. """ # Disconnect the old kernel manager, if necessary. old_manager = self._kernel_manager if old_manager is not None: old_manager.started_kernel.disconnect(self._started_kernel) old_manager.started_channels.disconnect(self._started_channels) old_manager.stopped_channels.disconnect(self._stopped_channels) # Disconnect the old kernel manager's channels. old_manager.sub_channel.message_received.disconnect(self._dispatch) old_manager.shell_channel.message_received.disconnect(self._dispatch) old_manager.stdin_channel.message_received.disconnect(self._dispatch) old_manager.hb_channel.kernel_died.disconnect( self._handle_kernel_died) # Handle the case where the old kernel manager is still listening. if old_manager.channels_running: self._stopped_channels() # Set the new kernel manager. self._kernel_manager = kernel_manager if kernel_manager is None: return # Connect the new kernel manager. kernel_manager.started_kernel.connect(self._started_kernel) kernel_manager.started_channels.connect(self._started_channels) kernel_manager.stopped_channels.connect(self._stopped_channels) # Connect the new kernel manager's channels. kernel_manager.sub_channel.message_received.connect(self._dispatch) kernel_manager.shell_channel.message_received.connect(self._dispatch) kernel_manager.stdin_channel.message_received.connect(self._dispatch) kernel_manager.hb_channel.kernel_died.connect(self._handle_kernel_died) # Handle the case where the kernel manager started channels before # we connected. if kernel_manager.channels_running: self._started_channels()
[ "Disconnect", "from", "the", "current", "kernel", "manager", "(", "if", "any", ")", "and", "set", "a", "new", "kernel", "manager", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/base_frontend_mixin.py#L21-L62
[ "def", "_set_kernel_manager", "(", "self", ",", "kernel_manager", ")", ":", "# Disconnect the old kernel manager, if necessary.", "old_manager", "=", "self", ".", "_kernel_manager", "if", "old_manager", "is", "not", "None", ":", "old_manager", ".", "started_kernel", ".", "disconnect", "(", "self", ".", "_started_kernel", ")", "old_manager", ".", "started_channels", ".", "disconnect", "(", "self", ".", "_started_channels", ")", "old_manager", ".", "stopped_channels", ".", "disconnect", "(", "self", ".", "_stopped_channels", ")", "# Disconnect the old kernel manager's channels.", "old_manager", ".", "sub_channel", ".", "message_received", ".", "disconnect", "(", "self", ".", "_dispatch", ")", "old_manager", ".", "shell_channel", ".", "message_received", ".", "disconnect", "(", "self", ".", "_dispatch", ")", "old_manager", ".", "stdin_channel", ".", "message_received", ".", "disconnect", "(", "self", ".", "_dispatch", ")", "old_manager", ".", "hb_channel", ".", "kernel_died", ".", "disconnect", "(", "self", ".", "_handle_kernel_died", ")", "# Handle the case where the old kernel manager is still listening.", "if", "old_manager", ".", "channels_running", ":", "self", ".", "_stopped_channels", "(", ")", "# Set the new kernel manager.", "self", ".", "_kernel_manager", "=", "kernel_manager", "if", "kernel_manager", "is", "None", ":", "return", "# Connect the new kernel manager.", "kernel_manager", ".", "started_kernel", ".", "connect", "(", "self", ".", "_started_kernel", ")", "kernel_manager", ".", "started_channels", ".", "connect", "(", "self", ".", "_started_channels", ")", "kernel_manager", ".", "stopped_channels", ".", "connect", "(", "self", ".", "_stopped_channels", ")", "# Connect the new kernel manager's channels.", "kernel_manager", ".", "sub_channel", ".", "message_received", ".", "connect", "(", "self", ".", "_dispatch", ")", "kernel_manager", ".", "shell_channel", ".", "message_received", ".", "connect", "(", "self", ".", "_dispatch", ")", "kernel_manager", ".", "stdin_channel", ".", "message_received", ".", "connect", "(", "self", ".", "_dispatch", ")", "kernel_manager", ".", "hb_channel", ".", "kernel_died", ".", "connect", "(", "self", ".", "_handle_kernel_died", ")", "# Handle the case where the kernel manager started channels before", "# we connected.", "if", "kernel_manager", ".", "channels_running", ":", "self", ".", "_started_channels", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseFrontendMixin._dispatch
Calls the frontend handler associated with the message type of the given message.
environment/lib/python2.7/site-packages/IPython/frontend/qt/base_frontend_mixin.py
def _dispatch(self, msg): """ Calls the frontend handler associated with the message type of the given message. """ msg_type = msg['header']['msg_type'] handler = getattr(self, '_handle_' + msg_type, None) if handler: handler(msg)
def _dispatch(self, msg): """ Calls the frontend handler associated with the message type of the given message. """ msg_type = msg['header']['msg_type'] handler = getattr(self, '_handle_' + msg_type, None) if handler: handler(msg)
[ "Calls", "the", "frontend", "handler", "associated", "with", "the", "message", "type", "of", "the", "given", "message", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/base_frontend_mixin.py#L102-L109
[ "def", "_dispatch", "(", "self", ",", "msg", ")", ":", "msg_type", "=", "msg", "[", "'header'", "]", "[", "'msg_type'", "]", "handler", "=", "getattr", "(", "self", ",", "'_handle_'", "+", "msg_type", ",", "None", ")", "if", "handler", ":", "handler", "(", "msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseFrontendMixin._is_from_this_session
Returns whether a reply from the kernel originated from a request from this frontend.
environment/lib/python2.7/site-packages/IPython/frontend/qt/base_frontend_mixin.py
def _is_from_this_session(self, msg): """ Returns whether a reply from the kernel originated from a request from this frontend. """ session = self._kernel_manager.session.session parent = msg['parent_header'] if not parent: # if the message has no parent, assume it is meant for all frontends return True else: return parent.get('session') == session
def _is_from_this_session(self, msg): """ Returns whether a reply from the kernel originated from a request from this frontend. """ session = self._kernel_manager.session.session parent = msg['parent_header'] if not parent: # if the message has no parent, assume it is meant for all frontends return True else: return parent.get('session') == session
[ "Returns", "whether", "a", "reply", "from", "the", "kernel", "originated", "from", "a", "request", "from", "this", "frontend", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/base_frontend_mixin.py#L111-L121
[ "def", "_is_from_this_session", "(", "self", ",", "msg", ")", ":", "session", "=", "self", ".", "_kernel_manager", ".", "session", ".", "session", "parent", "=", "msg", "[", "'parent_header'", "]", "if", "not", "parent", ":", "# if the message has no parent, assume it is meant for all frontends", "return", "True", "else", ":", "return", "parent", ".", "get", "(", "'session'", ")", "==", "session" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AnnotateReporter.report
Run the report. See `coverage.report()` for arguments.
virtualEnvironment/lib/python2.7/site-packages/coverage/annotate.py
def report(self, morfs, directory=None): """Run the report. See `coverage.report()` for arguments. """ self.report_files(self.annotate_file, morfs, directory)
def report(self, morfs, directory=None): """Run the report. See `coverage.report()` for arguments. """ self.report_files(self.annotate_file, morfs, directory)
[ "Run", "the", "report", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/annotate.py#L37-L43
[ "def", "report", "(", "self", ",", "morfs", ",", "directory", "=", "None", ")", ":", "self", ".", "report_files", "(", "self", ".", "annotate_file", ",", "morfs", ",", "directory", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
AnnotateReporter.annotate_file
Annotate a single file. `cu` is the CodeUnit for the file to annotate.
virtualEnvironment/lib/python2.7/site-packages/coverage/annotate.py
def annotate_file(self, cu, analysis): """Annotate a single file. `cu` is the CodeUnit for the file to annotate. """ if not cu.relative: return filename = cu.filename source = cu.source_file() if self.directory: dest_file = os.path.join(self.directory, cu.flat_rootname()) dest_file += ".py,cover" else: dest_file = filename + ",cover" dest = open(dest_file, 'w') statements = sorted(analysis.statements) missing = sorted(analysis.missing) excluded = sorted(analysis.excluded) lineno = 0 i = 0 j = 0 covered = True while True: line = source.readline() if line == '': break lineno += 1 while i < len(statements) and statements[i] < lineno: i += 1 while j < len(missing) and missing[j] < lineno: j += 1 if i < len(statements) and statements[i] == lineno: covered = j >= len(missing) or missing[j] > lineno if self.blank_re.match(line): dest.write(' ') elif self.else_re.match(line): # Special logic for lines containing only 'else:'. if i >= len(statements) and j >= len(missing): dest.write('! ') elif i >= len(statements) or j >= len(missing): dest.write('> ') elif statements[i] == missing[j]: dest.write('! ') else: dest.write('> ') elif lineno in excluded: dest.write('- ') elif covered: dest.write('> ') else: dest.write('! ') dest.write(line) source.close() dest.close()
def annotate_file(self, cu, analysis): """Annotate a single file. `cu` is the CodeUnit for the file to annotate. """ if not cu.relative: return filename = cu.filename source = cu.source_file() if self.directory: dest_file = os.path.join(self.directory, cu.flat_rootname()) dest_file += ".py,cover" else: dest_file = filename + ",cover" dest = open(dest_file, 'w') statements = sorted(analysis.statements) missing = sorted(analysis.missing) excluded = sorted(analysis.excluded) lineno = 0 i = 0 j = 0 covered = True while True: line = source.readline() if line == '': break lineno += 1 while i < len(statements) and statements[i] < lineno: i += 1 while j < len(missing) and missing[j] < lineno: j += 1 if i < len(statements) and statements[i] == lineno: covered = j >= len(missing) or missing[j] > lineno if self.blank_re.match(line): dest.write(' ') elif self.else_re.match(line): # Special logic for lines containing only 'else:'. if i >= len(statements) and j >= len(missing): dest.write('! ') elif i >= len(statements) or j >= len(missing): dest.write('> ') elif statements[i] == missing[j]: dest.write('! ') else: dest.write('> ') elif lineno in excluded: dest.write('- ') elif covered: dest.write('> ') else: dest.write('! ') dest.write(line) source.close() dest.close()
[ "Annotate", "a", "single", "file", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/annotate.py#L45-L102
[ "def", "annotate_file", "(", "self", ",", "cu", ",", "analysis", ")", ":", "if", "not", "cu", ".", "relative", ":", "return", "filename", "=", "cu", ".", "filename", "source", "=", "cu", ".", "source_file", "(", ")", "if", "self", ".", "directory", ":", "dest_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "directory", ",", "cu", ".", "flat_rootname", "(", ")", ")", "dest_file", "+=", "\".py,cover\"", "else", ":", "dest_file", "=", "filename", "+", "\",cover\"", "dest", "=", "open", "(", "dest_file", ",", "'w'", ")", "statements", "=", "sorted", "(", "analysis", ".", "statements", ")", "missing", "=", "sorted", "(", "analysis", ".", "missing", ")", "excluded", "=", "sorted", "(", "analysis", ".", "excluded", ")", "lineno", "=", "0", "i", "=", "0", "j", "=", "0", "covered", "=", "True", "while", "True", ":", "line", "=", "source", ".", "readline", "(", ")", "if", "line", "==", "''", ":", "break", "lineno", "+=", "1", "while", "i", "<", "len", "(", "statements", ")", "and", "statements", "[", "i", "]", "<", "lineno", ":", "i", "+=", "1", "while", "j", "<", "len", "(", "missing", ")", "and", "missing", "[", "j", "]", "<", "lineno", ":", "j", "+=", "1", "if", "i", "<", "len", "(", "statements", ")", "and", "statements", "[", "i", "]", "==", "lineno", ":", "covered", "=", "j", ">=", "len", "(", "missing", ")", "or", "missing", "[", "j", "]", ">", "lineno", "if", "self", ".", "blank_re", ".", "match", "(", "line", ")", ":", "dest", ".", "write", "(", "' '", ")", "elif", "self", ".", "else_re", ".", "match", "(", "line", ")", ":", "# Special logic for lines containing only 'else:'.", "if", "i", ">=", "len", "(", "statements", ")", "and", "j", ">=", "len", "(", "missing", ")", ":", "dest", ".", "write", "(", "'! '", ")", "elif", "i", ">=", "len", "(", "statements", ")", "or", "j", ">=", "len", "(", "missing", ")", ":", "dest", ".", "write", "(", "'> '", ")", "elif", "statements", "[", "i", "]", "==", "missing", "[", "j", "]", ":", "dest", ".", "write", "(", "'! '", ")", "else", ":", "dest", ".", "write", "(", "'> '", ")", "elif", "lineno", "in", "excluded", ":", "dest", ".", "write", "(", "'- '", ")", "elif", "covered", ":", "dest", ".", "write", "(", "'> '", ")", "else", ":", "dest", ".", "write", "(", "'! '", ")", "dest", ".", "write", "(", "line", ")", "source", ".", "close", "(", ")", "dest", ".", "close", "(", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
find
returns a list of tuples (package_name, description) for apt-cache search results
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/linux2/apt.py
def find(name): ''' returns a list of tuples (package_name, description) for apt-cache search results ''' cmd = 'apt-cache search %s' % name args = shlex.split(cmd) try: output = subprocess.check_output(args) except CalledProcessError: return [] lines = output.splitlines() packages = [] for line in lines: package, _, desc = line.partition(' - ') packages.append((package, desc)) return packages
def find(name): ''' returns a list of tuples (package_name, description) for apt-cache search results ''' cmd = 'apt-cache search %s' % name args = shlex.split(cmd) try: output = subprocess.check_output(args) except CalledProcessError: return [] lines = output.splitlines() packages = [] for line in lines: package, _, desc = line.partition(' - ') packages.append((package, desc)) return packages
[ "returns", "a", "list", "of", "tuples", "(", "package_name", "description", ")", "for", "apt", "-", "cache", "search", "results" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/linux2/apt.py#L7-L22
[ "def", "find", "(", "name", ")", ":", "cmd", "=", "'apt-cache search %s'", "%", "name", "args", "=", "shlex", ".", "split", "(", "cmd", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "args", ")", "except", "CalledProcessError", ":", "return", "[", "]", "lines", "=", "output", ".", "splitlines", "(", ")", "packages", "=", "[", "]", "for", "line", "in", "lines", ":", "package", ",", "_", ",", "desc", "=", "line", ".", "partition", "(", "' - '", ")", "packages", ".", "append", "(", "(", "package", ",", "desc", ")", ")", "return", "packages" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_installed_version
returns installed package version and None if package is not installed
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/linux2/apt.py
def get_installed_version(name): ''' returns installed package version and None if package is not installed ''' pattern = re.compile(r'''Installed:\s+(?P<version>.*)''') cmd = 'apt-cache policy %s' % name args = shlex.split(cmd) try: output = subprocess.check_output(args) if not output: return None except CalledProcessError: return None # check output match = pattern.search(output) if match: version = match.groupdict()['version'] if version == '(none)': return None else: return version
def get_installed_version(name): ''' returns installed package version and None if package is not installed ''' pattern = re.compile(r'''Installed:\s+(?P<version>.*)''') cmd = 'apt-cache policy %s' % name args = shlex.split(cmd) try: output = subprocess.check_output(args) if not output: return None except CalledProcessError: return None # check output match = pattern.search(output) if match: version = match.groupdict()['version'] if version == '(none)': return None else: return version
[ "returns", "installed", "package", "version", "and", "None", "if", "package", "is", "not", "installed" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/linux2/apt.py#L30-L50
[ "def", "get_installed_version", "(", "name", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'''Installed:\\s+(?P<version>.*)'''", ")", "cmd", "=", "'apt-cache policy %s'", "%", "name", "args", "=", "shlex", ".", "split", "(", "cmd", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "args", ")", "if", "not", "output", ":", "return", "None", "except", "CalledProcessError", ":", "return", "None", "# check output", "match", "=", "pattern", ".", "search", "(", "output", ")", "if", "match", ":", "version", "=", "match", ".", "groupdict", "(", ")", "[", "'version'", "]", "if", "version", "==", "'(none)'", ":", "return", "None", "else", ":", "return", "version" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
squash_unicode
coerce unicode back to bytestrings.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def squash_unicode(obj): """coerce unicode back to bytestrings.""" if isinstance(obj,dict): for key in obj.keys(): obj[key] = squash_unicode(obj[key]) if isinstance(key, unicode): obj[squash_unicode(key)] = obj.pop(key) elif isinstance(obj, list): for i,v in enumerate(obj): obj[i] = squash_unicode(v) elif isinstance(obj, unicode): obj = obj.encode('utf8') return obj
def squash_unicode(obj): """coerce unicode back to bytestrings.""" if isinstance(obj,dict): for key in obj.keys(): obj[key] = squash_unicode(obj[key]) if isinstance(key, unicode): obj[squash_unicode(key)] = obj.pop(key) elif isinstance(obj, list): for i,v in enumerate(obj): obj[i] = squash_unicode(v) elif isinstance(obj, unicode): obj = obj.encode('utf8') return obj
[ "coerce", "unicode", "back", "to", "bytestrings", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L58-L70
[ "def", "squash_unicode", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "key", "in", "obj", ".", "keys", "(", ")", ":", "obj", "[", "key", "]", "=", "squash_unicode", "(", "obj", "[", "key", "]", ")", "if", "isinstance", "(", "key", ",", "unicode", ")", ":", "obj", "[", "squash_unicode", "(", "key", ")", "]", "=", "obj", ".", "pop", "(", "key", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "i", ",", "v", "in", "enumerate", "(", "obj", ")", ":", "obj", "[", "i", "]", "=", "squash_unicode", "(", "v", ")", "elif", "isinstance", "(", "obj", ",", "unicode", ")", ":", "obj", "=", "obj", ".", "encode", "(", "'utf8'", ")", "return", "obj" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
default_secure
Set the default behavior for a config environment to be secure. If Session.key/keyfile have not been set, set Session.key to a new random UUID.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def default_secure(cfg): """Set the default behavior for a config environment to be secure. If Session.key/keyfile have not been set, set Session.key to a new random UUID. """ if 'Session' in cfg: if 'key' in cfg.Session or 'keyfile' in cfg.Session: return # key/keyfile not specified, generate new UUID: cfg.Session.key = str_to_bytes(str(uuid.uuid4()))
def default_secure(cfg): """Set the default behavior for a config environment to be secure. If Session.key/keyfile have not been set, set Session.key to a new random UUID. """ if 'Session' in cfg: if 'key' in cfg.Session or 'keyfile' in cfg.Session: return # key/keyfile not specified, generate new UUID: cfg.Session.key = str_to_bytes(str(uuid.uuid4()))
[ "Set", "the", "default", "behavior", "for", "a", "config", "environment", "to", "be", "secure", ".", "If", "Session", ".", "key", "/", "keyfile", "have", "not", "been", "set", "set", "Session", ".", "key", "to", "a", "new", "random", "UUID", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L110-L121
[ "def", "default_secure", "(", "cfg", ")", ":", "if", "'Session'", "in", "cfg", ":", "if", "'key'", "in", "cfg", ".", "Session", "or", "'keyfile'", "in", "cfg", ".", "Session", ":", "return", "# key/keyfile not specified, generate new UUID:", "cfg", ".", "Session", ".", "key", "=", "str_to_bytes", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
extract_header
Given a message or header, return the header.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header['header'] except KeyError: try: # See if msg_or_header is just the header h = msg_or_header['msg_id'] except KeyError: raise else: h = msg_or_header if not isinstance(h, dict): h = dict(h) return h
def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header['header'] except KeyError: try: # See if msg_or_header is just the header h = msg_or_header['msg_id'] except KeyError: raise else: h = msg_or_header if not isinstance(h, dict): h = dict(h) return h
[ "Given", "a", "message", "or", "header", "return", "the", "header", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L190-L207
[ "def", "extract_header", "(", "msg_or_header", ")", ":", "if", "not", "msg_or_header", ":", "return", "{", "}", "try", ":", "# See if msg_or_header is the entire message.", "h", "=", "msg_or_header", "[", "'header'", "]", "except", "KeyError", ":", "try", ":", "# See if msg_or_header is just the header", "h", "=", "msg_or_header", "[", "'msg_id'", "]", "except", "KeyError", ":", "raise", "else", ":", "h", "=", "msg_or_header", "if", "not", "isinstance", "(", "h", ",", "dict", ")", ":", "h", "=", "dict", "(", "h", ")", "return", "h" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session._check_packers
check packers for binary data and datetime support.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def _check_packers(self): """check packers for binary data and datetime support.""" pack = self.pack unpack = self.unpack # check simple serialization msg = dict(a=[1,'hi']) try: packed = pack(msg) except Exception: raise ValueError("packer could not serialize a simple message") # ensure packed message is bytes if not isinstance(packed, bytes): raise ValueError("message packed to %r, but bytes are required"%type(packed)) # check that unpack is pack's inverse try: unpacked = unpack(packed) except Exception: raise ValueError("unpacker could not handle the packer's output") # check datetime support msg = dict(t=datetime.now()) try: unpacked = unpack(pack(msg)) except Exception: self.pack = lambda o: pack(squash_dates(o)) self.unpack = lambda s: extract_dates(unpack(s))
def _check_packers(self): """check packers for binary data and datetime support.""" pack = self.pack unpack = self.unpack # check simple serialization msg = dict(a=[1,'hi']) try: packed = pack(msg) except Exception: raise ValueError("packer could not serialize a simple message") # ensure packed message is bytes if not isinstance(packed, bytes): raise ValueError("message packed to %r, but bytes are required"%type(packed)) # check that unpack is pack's inverse try: unpacked = unpack(packed) except Exception: raise ValueError("unpacker could not handle the packer's output") # check datetime support msg = dict(t=datetime.now()) try: unpacked = unpack(pack(msg)) except Exception: self.pack = lambda o: pack(squash_dates(o)) self.unpack = lambda s: extract_dates(unpack(s))
[ "check", "packers", "for", "binary", "data", "and", "datetime", "support", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L372-L400
[ "def", "_check_packers", "(", "self", ")", ":", "pack", "=", "self", ".", "pack", "unpack", "=", "self", ".", "unpack", "# check simple serialization", "msg", "=", "dict", "(", "a", "=", "[", "1", ",", "'hi'", "]", ")", "try", ":", "packed", "=", "pack", "(", "msg", ")", "except", "Exception", ":", "raise", "ValueError", "(", "\"packer could not serialize a simple message\"", ")", "# ensure packed message is bytes", "if", "not", "isinstance", "(", "packed", ",", "bytes", ")", ":", "raise", "ValueError", "(", "\"message packed to %r, but bytes are required\"", "%", "type", "(", "packed", ")", ")", "# check that unpack is pack's inverse", "try", ":", "unpacked", "=", "unpack", "(", "packed", ")", "except", "Exception", ":", "raise", "ValueError", "(", "\"unpacker could not handle the packer's output\"", ")", "# check datetime support", "msg", "=", "dict", "(", "t", "=", "datetime", ".", "now", "(", ")", ")", "try", ":", "unpacked", "=", "unpack", "(", "pack", "(", "msg", ")", ")", "except", "Exception", ":", "self", ".", "pack", "=", "lambda", "o", ":", "pack", "(", "squash_dates", "(", "o", ")", ")", "self", ".", "unpack", "=", "lambda", "s", ":", "extract_dates", "(", "unpack", "(", "s", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.msg
Return the nested message dict. This format is different from what is sent over the wire. The serialize/unserialize methods converts this nested message dict to the wire format, which is a list of message parts.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def msg(self, msg_type, content=None, parent=None, subheader=None, header=None): """Return the nested message dict. This format is different from what is sent over the wire. The serialize/unserialize methods converts this nested message dict to the wire format, which is a list of message parts. """ msg = {} header = self.msg_header(msg_type) if header is None else header msg['header'] = header msg['msg_id'] = header['msg_id'] msg['msg_type'] = header['msg_type'] msg['parent_header'] = {} if parent is None else extract_header(parent) msg['content'] = {} if content is None else content sub = {} if subheader is None else subheader msg['header'].update(sub) return msg
def msg(self, msg_type, content=None, parent=None, subheader=None, header=None): """Return the nested message dict. This format is different from what is sent over the wire. The serialize/unserialize methods converts this nested message dict to the wire format, which is a list of message parts. """ msg = {} header = self.msg_header(msg_type) if header is None else header msg['header'] = header msg['msg_id'] = header['msg_id'] msg['msg_type'] = header['msg_type'] msg['parent_header'] = {} if parent is None else extract_header(parent) msg['content'] = {} if content is None else content sub = {} if subheader is None else subheader msg['header'].update(sub) return msg
[ "Return", "the", "nested", "message", "dict", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L405-L421
[ "def", "msg", "(", "self", ",", "msg_type", ",", "content", "=", "None", ",", "parent", "=", "None", ",", "subheader", "=", "None", ",", "header", "=", "None", ")", ":", "msg", "=", "{", "}", "header", "=", "self", ".", "msg_header", "(", "msg_type", ")", "if", "header", "is", "None", "else", "header", "msg", "[", "'header'", "]", "=", "header", "msg", "[", "'msg_id'", "]", "=", "header", "[", "'msg_id'", "]", "msg", "[", "'msg_type'", "]", "=", "header", "[", "'msg_type'", "]", "msg", "[", "'parent_header'", "]", "=", "{", "}", "if", "parent", "is", "None", "else", "extract_header", "(", "parent", ")", "msg", "[", "'content'", "]", "=", "{", "}", "if", "content", "is", "None", "else", "content", "sub", "=", "{", "}", "if", "subheader", "is", "None", "else", "subheader", "msg", "[", "'header'", "]", ".", "update", "(", "sub", ")", "return", "msg" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.sign
Sign a message with HMAC digest. If no auth, return b''. Parameters ---------- msg_list : list The [p_header,p_parent,p_content] part of the message list.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def sign(self, msg_list): """Sign a message with HMAC digest. If no auth, return b''. Parameters ---------- msg_list : list The [p_header,p_parent,p_content] part of the message list. """ if self.auth is None: return b'' h = self.auth.copy() for m in msg_list: h.update(m) return str_to_bytes(h.hexdigest())
def sign(self, msg_list): """Sign a message with HMAC digest. If no auth, return b''. Parameters ---------- msg_list : list The [p_header,p_parent,p_content] part of the message list. """ if self.auth is None: return b'' h = self.auth.copy() for m in msg_list: h.update(m) return str_to_bytes(h.hexdigest())
[ "Sign", "a", "message", "with", "HMAC", "digest", ".", "If", "no", "auth", "return", "b", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L423-L436
[ "def", "sign", "(", "self", ",", "msg_list", ")", ":", "if", "self", ".", "auth", "is", "None", ":", "return", "b''", "h", "=", "self", ".", "auth", ".", "copy", "(", ")", "for", "m", "in", "msg_list", ":", "h", ".", "update", "(", "m", ")", "return", "str_to_bytes", "(", "h", ".", "hexdigest", "(", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.serialize
Serialize the message components to bytes. This is roughly the inverse of unserialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters ---------- msg : dict or Message The nexted message dict as returned by the self.msg method. Returns ------- msg_list : list The list of bytes objects to be sent with the format: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...]. In this list, the p_* entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def serialize(self, msg, ident=None): """Serialize the message components to bytes. This is roughly the inverse of unserialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters ---------- msg : dict or Message The nexted message dict as returned by the self.msg method. Returns ------- msg_list : list The list of bytes objects to be sent with the format: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...]. In this list, the p_* entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings. """ content = msg.get('content', {}) if content is None: content = self.none elif isinstance(content, dict): content = self.pack(content) elif isinstance(content, bytes): # content is already packed, as in a relayed message pass elif isinstance(content, unicode): # should be bytes, but JSON often spits out unicode content = content.encode('utf8') else: raise TypeError("Content incorrect type: %s"%type(content)) real_message = [self.pack(msg['header']), self.pack(msg['parent_header']), content ] to_send = [] if isinstance(ident, list): # accept list of idents to_send.extend(ident) elif ident is not None: to_send.append(ident) to_send.append(DELIM) signature = self.sign(real_message) to_send.append(signature) to_send.extend(real_message) return to_send
def serialize(self, msg, ident=None): """Serialize the message components to bytes. This is roughly the inverse of unserialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters ---------- msg : dict or Message The nexted message dict as returned by the self.msg method. Returns ------- msg_list : list The list of bytes objects to be sent with the format: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...]. In this list, the p_* entities are the packed or serialized versions, so if JSON is used, these are utf8 encoded JSON strings. """ content = msg.get('content', {}) if content is None: content = self.none elif isinstance(content, dict): content = self.pack(content) elif isinstance(content, bytes): # content is already packed, as in a relayed message pass elif isinstance(content, unicode): # should be bytes, but JSON often spits out unicode content = content.encode('utf8') else: raise TypeError("Content incorrect type: %s"%type(content)) real_message = [self.pack(msg['header']), self.pack(msg['parent_header']), content ] to_send = [] if isinstance(ident, list): # accept list of idents to_send.extend(ident) elif ident is not None: to_send.append(ident) to_send.append(DELIM) signature = self.sign(real_message) to_send.append(signature) to_send.extend(real_message) return to_send
[ "Serialize", "the", "message", "components", "to", "bytes", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L438-L492
[ "def", "serialize", "(", "self", ",", "msg", ",", "ident", "=", "None", ")", ":", "content", "=", "msg", ".", "get", "(", "'content'", ",", "{", "}", ")", "if", "content", "is", "None", ":", "content", "=", "self", ".", "none", "elif", "isinstance", "(", "content", ",", "dict", ")", ":", "content", "=", "self", ".", "pack", "(", "content", ")", "elif", "isinstance", "(", "content", ",", "bytes", ")", ":", "# content is already packed, as in a relayed message", "pass", "elif", "isinstance", "(", "content", ",", "unicode", ")", ":", "# should be bytes, but JSON often spits out unicode", "content", "=", "content", ".", "encode", "(", "'utf8'", ")", "else", ":", "raise", "TypeError", "(", "\"Content incorrect type: %s\"", "%", "type", "(", "content", ")", ")", "real_message", "=", "[", "self", ".", "pack", "(", "msg", "[", "'header'", "]", ")", ",", "self", ".", "pack", "(", "msg", "[", "'parent_header'", "]", ")", ",", "content", "]", "to_send", "=", "[", "]", "if", "isinstance", "(", "ident", ",", "list", ")", ":", "# accept list of idents", "to_send", ".", "extend", "(", "ident", ")", "elif", "ident", "is", "not", "None", ":", "to_send", ".", "append", "(", "ident", ")", "to_send", ".", "append", "(", "DELIM", ")", "signature", "=", "self", ".", "sign", "(", "real_message", ")", "to_send", ".", "append", "(", "signature", ")", "to_send", ".", "extend", "(", "real_message", ")", "return", "to_send" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.send
Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unserialize methods convert the nested message dict into this format. Parameters ---------- stream : zmq.Socket or ZMQStream The socket-like object used to send the data. msg_or_type : str or Message/dict Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header. content : dict or None The content of the message (ignored if msg_or_type is a message). header : dict or None The header dict for the message (ignores if msg_to_type is a message). parent : Message or dict or None The parent or parent header describing the parent of this message (ignored if msg_or_type is a message). ident : bytes or list of bytes The zmq.IDENTITY routing path. subheader : dict or None Extra header keys for this message's header (ignored if msg_or_type is a message). buffers : list or None The already-serialized buffers to be appended to the message. track : bool Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages. Returns ------- msg : dict The constructed message. (msg,tracker) : (dict, MessageTracker) if track=True, then a 2-tuple will be returned, the first element being the constructed message, and the second being the MessageTracker
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, subheader=None, track=False, header=None): """Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unserialize methods convert the nested message dict into this format. Parameters ---------- stream : zmq.Socket or ZMQStream The socket-like object used to send the data. msg_or_type : str or Message/dict Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header. content : dict or None The content of the message (ignored if msg_or_type is a message). header : dict or None The header dict for the message (ignores if msg_to_type is a message). parent : Message or dict or None The parent or parent header describing the parent of this message (ignored if msg_or_type is a message). ident : bytes or list of bytes The zmq.IDENTITY routing path. subheader : dict or None Extra header keys for this message's header (ignored if msg_or_type is a message). buffers : list or None The already-serialized buffers to be appended to the message. track : bool Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages. Returns ------- msg : dict The constructed message. (msg,tracker) : (dict, MessageTracker) if track=True, then a 2-tuple will be returned, the first element being the constructed message, and the second being the MessageTracker """ if not isinstance(stream, (zmq.Socket, ZMQStream)): raise TypeError("stream must be Socket or ZMQStream, not %r"%type(stream)) elif track and isinstance(stream, ZMQStream): raise TypeError("ZMQStream cannot track messages") if isinstance(msg_or_type, (Message, dict)): # We got a Message or message dict, not a msg_type so don't # build a new Message. msg = msg_or_type else: msg = self.msg(msg_or_type, content=content, parent=parent, subheader=subheader, header=header) buffers = [] if buffers is None else buffers to_send = self.serialize(msg, ident) flag = 0 if buffers: flag = zmq.SNDMORE _track = False else: _track=track if track: tracker = stream.send_multipart(to_send, flag, copy=False, track=_track) else: tracker = stream.send_multipart(to_send, flag, copy=False) for b in buffers[:-1]: stream.send(b, flag, copy=False) if buffers: if track: tracker = stream.send(buffers[-1], copy=False, track=track) else: tracker = stream.send(buffers[-1], copy=False) # omsg = Message(msg) if self.debug: pprint.pprint(msg) pprint.pprint(to_send) pprint.pprint(buffers) msg['tracker'] = tracker return msg
def send(self, stream, msg_or_type, content=None, parent=None, ident=None, buffers=None, subheader=None, track=False, header=None): """Build and send a message via stream or socket. The message format used by this function internally is as follows: [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content, buffer1,buffer2,...] The serialize/unserialize methods convert the nested message dict into this format. Parameters ---------- stream : zmq.Socket or ZMQStream The socket-like object used to send the data. msg_or_type : str or Message/dict Normally, msg_or_type will be a msg_type unless a message is being sent more than once. If a header is supplied, this can be set to None and the msg_type will be pulled from the header. content : dict or None The content of the message (ignored if msg_or_type is a message). header : dict or None The header dict for the message (ignores if msg_to_type is a message). parent : Message or dict or None The parent or parent header describing the parent of this message (ignored if msg_or_type is a message). ident : bytes or list of bytes The zmq.IDENTITY routing path. subheader : dict or None Extra header keys for this message's header (ignored if msg_or_type is a message). buffers : list or None The already-serialized buffers to be appended to the message. track : bool Whether to track. Only for use with Sockets, because ZMQStream objects cannot track messages. Returns ------- msg : dict The constructed message. (msg,tracker) : (dict, MessageTracker) if track=True, then a 2-tuple will be returned, the first element being the constructed message, and the second being the MessageTracker """ if not isinstance(stream, (zmq.Socket, ZMQStream)): raise TypeError("stream must be Socket or ZMQStream, not %r"%type(stream)) elif track and isinstance(stream, ZMQStream): raise TypeError("ZMQStream cannot track messages") if isinstance(msg_or_type, (Message, dict)): # We got a Message or message dict, not a msg_type so don't # build a new Message. msg = msg_or_type else: msg = self.msg(msg_or_type, content=content, parent=parent, subheader=subheader, header=header) buffers = [] if buffers is None else buffers to_send = self.serialize(msg, ident) flag = 0 if buffers: flag = zmq.SNDMORE _track = False else: _track=track if track: tracker = stream.send_multipart(to_send, flag, copy=False, track=_track) else: tracker = stream.send_multipart(to_send, flag, copy=False) for b in buffers[:-1]: stream.send(b, flag, copy=False) if buffers: if track: tracker = stream.send(buffers[-1], copy=False, track=track) else: tracker = stream.send(buffers[-1], copy=False) # omsg = Message(msg) if self.debug: pprint.pprint(msg) pprint.pprint(to_send) pprint.pprint(buffers) msg['tracker'] = tracker return msg
[ "Build", "and", "send", "a", "message", "via", "stream", "or", "socket", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L494-L586
[ "def", "send", "(", "self", ",", "stream", ",", "msg_or_type", ",", "content", "=", "None", ",", "parent", "=", "None", ",", "ident", "=", "None", ",", "buffers", "=", "None", ",", "subheader", "=", "None", ",", "track", "=", "False", ",", "header", "=", "None", ")", ":", "if", "not", "isinstance", "(", "stream", ",", "(", "zmq", ".", "Socket", ",", "ZMQStream", ")", ")", ":", "raise", "TypeError", "(", "\"stream must be Socket or ZMQStream, not %r\"", "%", "type", "(", "stream", ")", ")", "elif", "track", "and", "isinstance", "(", "stream", ",", "ZMQStream", ")", ":", "raise", "TypeError", "(", "\"ZMQStream cannot track messages\"", ")", "if", "isinstance", "(", "msg_or_type", ",", "(", "Message", ",", "dict", ")", ")", ":", "# We got a Message or message dict, not a msg_type so don't", "# build a new Message.", "msg", "=", "msg_or_type", "else", ":", "msg", "=", "self", ".", "msg", "(", "msg_or_type", ",", "content", "=", "content", ",", "parent", "=", "parent", ",", "subheader", "=", "subheader", ",", "header", "=", "header", ")", "buffers", "=", "[", "]", "if", "buffers", "is", "None", "else", "buffers", "to_send", "=", "self", ".", "serialize", "(", "msg", ",", "ident", ")", "flag", "=", "0", "if", "buffers", ":", "flag", "=", "zmq", ".", "SNDMORE", "_track", "=", "False", "else", ":", "_track", "=", "track", "if", "track", ":", "tracker", "=", "stream", ".", "send_multipart", "(", "to_send", ",", "flag", ",", "copy", "=", "False", ",", "track", "=", "_track", ")", "else", ":", "tracker", "=", "stream", ".", "send_multipart", "(", "to_send", ",", "flag", ",", "copy", "=", "False", ")", "for", "b", "in", "buffers", "[", ":", "-", "1", "]", ":", "stream", ".", "send", "(", "b", ",", "flag", ",", "copy", "=", "False", ")", "if", "buffers", ":", "if", "track", ":", "tracker", "=", "stream", ".", "send", "(", "buffers", "[", "-", "1", "]", ",", "copy", "=", "False", ",", "track", "=", "track", ")", "else", ":", "tracker", "=", "stream", ".", "send", "(", "buffers", "[", "-", "1", "]", ",", "copy", "=", "False", ")", "# omsg = Message(msg)", "if", "self", ".", "debug", ":", "pprint", ".", "pprint", "(", "msg", ")", "pprint", ".", "pprint", "(", "to_send", ")", "pprint", ".", "pprint", "(", "buffers", ")", "msg", "[", "'tracker'", "]", "=", "tracker", "return", "msg" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.send_raw
Send a raw message via ident path. This method is used to send a already serialized message. Parameters ---------- stream : ZMQStream or Socket The ZMQ stream or socket to use for sending the message. msg_list : list The serialized list of messages to send. This only includes the [p_header,p_parent,p_content,buffer1,buffer2,...] portion of the message. ident : ident or list A single ident or a list of idents to use in sending.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def send_raw(self, stream, msg_list, flags=0, copy=True, ident=None): """Send a raw message via ident path. This method is used to send a already serialized message. Parameters ---------- stream : ZMQStream or Socket The ZMQ stream or socket to use for sending the message. msg_list : list The serialized list of messages to send. This only includes the [p_header,p_parent,p_content,buffer1,buffer2,...] portion of the message. ident : ident or list A single ident or a list of idents to use in sending. """ to_send = [] if isinstance(ident, bytes): ident = [ident] if ident is not None: to_send.extend(ident) to_send.append(DELIM) to_send.append(self.sign(msg_list)) to_send.extend(msg_list) stream.send_multipart(msg_list, flags, copy=copy)
def send_raw(self, stream, msg_list, flags=0, copy=True, ident=None): """Send a raw message via ident path. This method is used to send a already serialized message. Parameters ---------- stream : ZMQStream or Socket The ZMQ stream or socket to use for sending the message. msg_list : list The serialized list of messages to send. This only includes the [p_header,p_parent,p_content,buffer1,buffer2,...] portion of the message. ident : ident or list A single ident or a list of idents to use in sending. """ to_send = [] if isinstance(ident, bytes): ident = [ident] if ident is not None: to_send.extend(ident) to_send.append(DELIM) to_send.append(self.sign(msg_list)) to_send.extend(msg_list) stream.send_multipart(msg_list, flags, copy=copy)
[ "Send", "a", "raw", "message", "via", "ident", "path", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L588-L613
[ "def", "send_raw", "(", "self", ",", "stream", ",", "msg_list", ",", "flags", "=", "0", ",", "copy", "=", "True", ",", "ident", "=", "None", ")", ":", "to_send", "=", "[", "]", "if", "isinstance", "(", "ident", ",", "bytes", ")", ":", "ident", "=", "[", "ident", "]", "if", "ident", "is", "not", "None", ":", "to_send", ".", "extend", "(", "ident", ")", "to_send", ".", "append", "(", "DELIM", ")", "to_send", ".", "append", "(", "self", ".", "sign", "(", "msg_list", ")", ")", "to_send", ".", "extend", "(", "msg_list", ")", "stream", ".", "send_multipart", "(", "msg_list", ",", "flags", ",", "copy", "=", "copy", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.recv
Receive and unpack a message. Parameters ---------- socket : ZMQStream or Socket The socket or stream to use in receiving. Returns ------- [idents], msg [idents] is a list of idents and msg is a nested message dict of same format as self.msg returns.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def recv(self, socket, mode=zmq.NOBLOCK, content=True, copy=True): """Receive and unpack a message. Parameters ---------- socket : ZMQStream or Socket The socket or stream to use in receiving. Returns ------- [idents], msg [idents] is a list of idents and msg is a nested message dict of same format as self.msg returns. """ if isinstance(socket, ZMQStream): socket = socket.socket try: msg_list = socket.recv_multipart(mode, copy=copy) except zmq.ZMQError as e: if e.errno == zmq.EAGAIN: # We can convert EAGAIN to None as we know in this case # recv_multipart won't return None. return None,None else: raise # split multipart message into identity list and message dict # invalid large messages can cause very expensive string comparisons idents, msg_list = self.feed_identities(msg_list, copy) try: return idents, self.unserialize(msg_list, content=content, copy=copy) except Exception as e: # TODO: handle it raise e
def recv(self, socket, mode=zmq.NOBLOCK, content=True, copy=True): """Receive and unpack a message. Parameters ---------- socket : ZMQStream or Socket The socket or stream to use in receiving. Returns ------- [idents], msg [idents] is a list of idents and msg is a nested message dict of same format as self.msg returns. """ if isinstance(socket, ZMQStream): socket = socket.socket try: msg_list = socket.recv_multipart(mode, copy=copy) except zmq.ZMQError as e: if e.errno == zmq.EAGAIN: # We can convert EAGAIN to None as we know in this case # recv_multipart won't return None. return None,None else: raise # split multipart message into identity list and message dict # invalid large messages can cause very expensive string comparisons idents, msg_list = self.feed_identities(msg_list, copy) try: return idents, self.unserialize(msg_list, content=content, copy=copy) except Exception as e: # TODO: handle it raise e
[ "Receive", "and", "unpack", "a", "message", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L615-L647
[ "def", "recv", "(", "self", ",", "socket", ",", "mode", "=", "zmq", ".", "NOBLOCK", ",", "content", "=", "True", ",", "copy", "=", "True", ")", ":", "if", "isinstance", "(", "socket", ",", "ZMQStream", ")", ":", "socket", "=", "socket", ".", "socket", "try", ":", "msg_list", "=", "socket", ".", "recv_multipart", "(", "mode", ",", "copy", "=", "copy", ")", "except", "zmq", ".", "ZMQError", "as", "e", ":", "if", "e", ".", "errno", "==", "zmq", ".", "EAGAIN", ":", "# We can convert EAGAIN to None as we know in this case", "# recv_multipart won't return None.", "return", "None", ",", "None", "else", ":", "raise", "# split multipart message into identity list and message dict", "# invalid large messages can cause very expensive string comparisons", "idents", ",", "msg_list", "=", "self", ".", "feed_identities", "(", "msg_list", ",", "copy", ")", "try", ":", "return", "idents", ",", "self", ".", "unserialize", "(", "msg_list", ",", "content", "=", "content", ",", "copy", "=", "copy", ")", "except", "Exception", "as", "e", ":", "# TODO: handle it", "raise", "e" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.feed_identities
Split the identities from the rest of the message. Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly. Parameters ---------- msg_list : a list of Message or bytes objects The message to be split. copy : bool flag determining whether the arguments are bytes or Messages Returns ------- (idents, msg_list) : two lists idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,...] and should be unpackable/unserializable via self.unserialize at this point.
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def feed_identities(self, msg_list, copy=True): """Split the identities from the rest of the message. Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly. Parameters ---------- msg_list : a list of Message or bytes objects The message to be split. copy : bool flag determining whether the arguments are bytes or Messages Returns ------- (idents, msg_list) : two lists idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,...] and should be unpackable/unserializable via self.unserialize at this point. """ if copy: idx = msg_list.index(DELIM) return msg_list[:idx], msg_list[idx+1:] else: failed = True for idx,m in enumerate(msg_list): if m.bytes == DELIM: failed = False break if failed: raise ValueError("DELIM not in msg_list") idents, msg_list = msg_list[:idx], msg_list[idx+1:] return [m.bytes for m in idents], msg_list
def feed_identities(self, msg_list, copy=True): """Split the identities from the rest of the message. Feed until DELIM is reached, then return the prefix as idents and remainder as msg_list. This is easily broken by setting an IDENT to DELIM, but that would be silly. Parameters ---------- msg_list : a list of Message or bytes objects The message to be split. copy : bool flag determining whether the arguments are bytes or Messages Returns ------- (idents, msg_list) : two lists idents will always be a list of bytes, each of which is a ZMQ identity. msg_list will be a list of bytes or zmq.Messages of the form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,...] and should be unpackable/unserializable via self.unserialize at this point. """ if copy: idx = msg_list.index(DELIM) return msg_list[:idx], msg_list[idx+1:] else: failed = True for idx,m in enumerate(msg_list): if m.bytes == DELIM: failed = False break if failed: raise ValueError("DELIM not in msg_list") idents, msg_list = msg_list[:idx], msg_list[idx+1:] return [m.bytes for m in idents], msg_list
[ "Split", "the", "identities", "from", "the", "rest", "of", "the", "message", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L649-L684
[ "def", "feed_identities", "(", "self", ",", "msg_list", ",", "copy", "=", "True", ")", ":", "if", "copy", ":", "idx", "=", "msg_list", ".", "index", "(", "DELIM", ")", "return", "msg_list", "[", ":", "idx", "]", ",", "msg_list", "[", "idx", "+", "1", ":", "]", "else", ":", "failed", "=", "True", "for", "idx", ",", "m", "in", "enumerate", "(", "msg_list", ")", ":", "if", "m", ".", "bytes", "==", "DELIM", ":", "failed", "=", "False", "break", "if", "failed", ":", "raise", "ValueError", "(", "\"DELIM not in msg_list\"", ")", "idents", ",", "msg_list", "=", "msg_list", "[", ":", "idx", "]", ",", "msg_list", "[", "idx", "+", "1", ":", "]", "return", "[", "m", ".", "bytes", "for", "m", "in", "idents", "]", ",", "msg_list" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Session.unserialize
Unserialize a msg_list to a nested message dict. This is roughly the inverse of serialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters: ----------- msg_list : list of bytes or Message objects The list of message parts of the form [HMAC,p_header,p_parent, p_content,buffer1,buffer2,...]. content : bool (True) Whether to unpack the content dict (True), or leave it packed (False). copy : bool (True) Whether to return the bytes (True), or the non-copying Message object in each place (False). Returns ------- msg : dict The nested message dict with top-level keys [header, parent_header, content, buffers].
environment/lib/python2.7/site-packages/IPython/zmq/session.py
def unserialize(self, msg_list, content=True, copy=True): """Unserialize a msg_list to a nested message dict. This is roughly the inverse of serialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters: ----------- msg_list : list of bytes or Message objects The list of message parts of the form [HMAC,p_header,p_parent, p_content,buffer1,buffer2,...]. content : bool (True) Whether to unpack the content dict (True), or leave it packed (False). copy : bool (True) Whether to return the bytes (True), or the non-copying Message object in each place (False). Returns ------- msg : dict The nested message dict with top-level keys [header, parent_header, content, buffers]. """ minlen = 4 message = {} if not copy: for i in range(minlen): msg_list[i] = msg_list[i].bytes if self.auth is not None: signature = msg_list[0] if not signature: raise ValueError("Unsigned Message") if signature in self.digest_history: raise ValueError("Duplicate Signature: %r"%signature) self.digest_history.add(signature) check = self.sign(msg_list[1:4]) if not signature == check: raise ValueError("Invalid Signature: %r"%signature) if not len(msg_list) >= minlen: raise TypeError("malformed message, must have at least %i elements"%minlen) header = self.unpack(msg_list[1]) message['header'] = header message['msg_id'] = header['msg_id'] message['msg_type'] = header['msg_type'] message['parent_header'] = self.unpack(msg_list[2]) if content: message['content'] = self.unpack(msg_list[3]) else: message['content'] = msg_list[3] message['buffers'] = msg_list[4:] return message
def unserialize(self, msg_list, content=True, copy=True): """Unserialize a msg_list to a nested message dict. This is roughly the inverse of serialize. The serialize/unserialize methods work with full message lists, whereas pack/unpack work with the individual message parts in the message list. Parameters: ----------- msg_list : list of bytes or Message objects The list of message parts of the form [HMAC,p_header,p_parent, p_content,buffer1,buffer2,...]. content : bool (True) Whether to unpack the content dict (True), or leave it packed (False). copy : bool (True) Whether to return the bytes (True), or the non-copying Message object in each place (False). Returns ------- msg : dict The nested message dict with top-level keys [header, parent_header, content, buffers]. """ minlen = 4 message = {} if not copy: for i in range(minlen): msg_list[i] = msg_list[i].bytes if self.auth is not None: signature = msg_list[0] if not signature: raise ValueError("Unsigned Message") if signature in self.digest_history: raise ValueError("Duplicate Signature: %r"%signature) self.digest_history.add(signature) check = self.sign(msg_list[1:4]) if not signature == check: raise ValueError("Invalid Signature: %r"%signature) if not len(msg_list) >= minlen: raise TypeError("malformed message, must have at least %i elements"%minlen) header = self.unpack(msg_list[1]) message['header'] = header message['msg_id'] = header['msg_id'] message['msg_type'] = header['msg_type'] message['parent_header'] = self.unpack(msg_list[2]) if content: message['content'] = self.unpack(msg_list[3]) else: message['content'] = msg_list[3] message['buffers'] = msg_list[4:] return message
[ "Unserialize", "a", "msg_list", "to", "a", "nested", "message", "dict", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/session.py#L686-L739
[ "def", "unserialize", "(", "self", ",", "msg_list", ",", "content", "=", "True", ",", "copy", "=", "True", ")", ":", "minlen", "=", "4", "message", "=", "{", "}", "if", "not", "copy", ":", "for", "i", "in", "range", "(", "minlen", ")", ":", "msg_list", "[", "i", "]", "=", "msg_list", "[", "i", "]", ".", "bytes", "if", "self", ".", "auth", "is", "not", "None", ":", "signature", "=", "msg_list", "[", "0", "]", "if", "not", "signature", ":", "raise", "ValueError", "(", "\"Unsigned Message\"", ")", "if", "signature", "in", "self", ".", "digest_history", ":", "raise", "ValueError", "(", "\"Duplicate Signature: %r\"", "%", "signature", ")", "self", ".", "digest_history", ".", "add", "(", "signature", ")", "check", "=", "self", ".", "sign", "(", "msg_list", "[", "1", ":", "4", "]", ")", "if", "not", "signature", "==", "check", ":", "raise", "ValueError", "(", "\"Invalid Signature: %r\"", "%", "signature", ")", "if", "not", "len", "(", "msg_list", ")", ">=", "minlen", ":", "raise", "TypeError", "(", "\"malformed message, must have at least %i elements\"", "%", "minlen", ")", "header", "=", "self", ".", "unpack", "(", "msg_list", "[", "1", "]", ")", "message", "[", "'header'", "]", "=", "header", "message", "[", "'msg_id'", "]", "=", "header", "[", "'msg_id'", "]", "message", "[", "'msg_type'", "]", "=", "header", "[", "'msg_type'", "]", "message", "[", "'parent_header'", "]", "=", "self", ".", "unpack", "(", "msg_list", "[", "2", "]", ")", "if", "content", ":", "message", "[", "'content'", "]", "=", "self", ".", "unpack", "(", "msg_list", "[", "3", "]", ")", "else", ":", "message", "[", "'content'", "]", "=", "msg_list", "[", "3", "]", "message", "[", "'buffers'", "]", "=", "msg_list", "[", "4", ":", "]", "return", "message" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
save_svg
Prompts the user to save an SVG document to disk. Parameters: ----------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns: -------- The name of the file to which the document was saved, or None if the save was cancelled.
environment/lib/python2.7/site-packages/IPython/frontend/qt/svg.py
def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. Parameters: ----------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns: -------- The name of the file to which the document was saved, or None if the save was cancelled. """ if isinstance(string, unicode): string = string.encode('utf-8') dialog = QtGui.QFileDialog(parent, 'Save SVG Document') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix('svg') dialog.setNameFilter('SVG document (*.svg)') if dialog.exec_(): filename = dialog.selectedFiles()[0] f = open(filename, 'w') try: f.write(string) finally: f.close() return filename return None
def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. Parameters: ----------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns: -------- The name of the file to which the document was saved, or None if the save was cancelled. """ if isinstance(string, unicode): string = string.encode('utf-8') dialog = QtGui.QFileDialog(parent, 'Save SVG Document') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix('svg') dialog.setNameFilter('SVG document (*.svg)') if dialog.exec_(): filename = dialog.selectedFiles()[0] f = open(filename, 'w') try: f.write(string) finally: f.close() return filename return None
[ "Prompts", "the", "user", "to", "save", "an", "SVG", "document", "to", "disk", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/svg.py#L8-L39
[ "def", "save_svg", "(", "string", ",", "parent", "=", "None", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf-8'", ")", "dialog", "=", "QtGui", ".", "QFileDialog", "(", "parent", ",", "'Save SVG Document'", ")", "dialog", ".", "setAcceptMode", "(", "QtGui", ".", "QFileDialog", ".", "AcceptSave", ")", "dialog", ".", "setDefaultSuffix", "(", "'svg'", ")", "dialog", ".", "setNameFilter", "(", "'SVG document (*.svg)'", ")", "if", "dialog", ".", "exec_", "(", ")", ":", "filename", "=", "dialog", ".", "selectedFiles", "(", ")", "[", "0", "]", "f", "=", "open", "(", "filename", ",", "'w'", ")", "try", ":", "f", ".", "write", "(", "string", ")", "finally", ":", "f", ".", "close", "(", ")", "return", "filename", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
svg_to_clipboard
Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document.
environment/lib/python2.7/site-packages/IPython/frontend/qt/svg.py
def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document. """ if isinstance(string, unicode): string = string.encode('utf-8') mime_data = QtCore.QMimeData() mime_data.setData('image/svg+xml', string) QtGui.QApplication.clipboard().setMimeData(mime_data)
def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameters: ----------- string : basestring A Python string containing a SVG document. """ if isinstance(string, unicode): string = string.encode('utf-8') mime_data = QtCore.QMimeData() mime_data.setData('image/svg+xml', string) QtGui.QApplication.clipboard().setMimeData(mime_data)
[ "Copy", "a", "SVG", "document", "to", "the", "clipboard", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/svg.py#L41-L54
[ "def", "svg_to_clipboard", "(", "string", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf-8'", ")", "mime_data", "=", "QtCore", ".", "QMimeData", "(", ")", "mime_data", ".", "setData", "(", "'image/svg+xml'", ",", "string", ")", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setMimeData", "(", "mime_data", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
svg_to_image
Convert a SVG document to a QImage. Parameters: ----------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises: ------- ValueError If an invalid SVG string is provided. Returns: -------- A QImage of format QImage.Format_ARGB32.
environment/lib/python2.7/site-packages/IPython/frontend/qt/svg.py
def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. Parameters: ----------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises: ------- ValueError If an invalid SVG string is provided. Returns: -------- A QImage of format QImage.Format_ARGB32. """ if isinstance(string, unicode): string = string.encode('utf-8') renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string)) if not renderer.isValid(): raise ValueError('Invalid SVG data.') if size is None: size = renderer.defaultSize() image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32) painter = QtGui.QPainter(image) renderer.render(painter) return image
def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. Parameters: ----------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises: ------- ValueError If an invalid SVG string is provided. Returns: -------- A QImage of format QImage.Format_ARGB32. """ if isinstance(string, unicode): string = string.encode('utf-8') renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string)) if not renderer.isValid(): raise ValueError('Invalid SVG data.') if size is None: size = renderer.defaultSize() image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32) painter = QtGui.QPainter(image) renderer.render(painter) return image
[ "Convert", "a", "SVG", "document", "to", "a", "QImage", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/svg.py#L56-L89
[ "def", "svg_to_image", "(", "string", ",", "size", "=", "None", ")", ":", "if", "isinstance", "(", "string", ",", "unicode", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf-8'", ")", "renderer", "=", "QtSvg", ".", "QSvgRenderer", "(", "QtCore", ".", "QByteArray", "(", "string", ")", ")", "if", "not", "renderer", ".", "isValid", "(", ")", ":", "raise", "ValueError", "(", "'Invalid SVG data.'", ")", "if", "size", "is", "None", ":", "size", "=", "renderer", ".", "defaultSize", "(", ")", "image", "=", "QtGui", ".", "QImage", "(", "size", ",", "QtGui", ".", "QImage", ".", "Format_ARGB32", ")", "painter", "=", "QtGui", ".", "QPainter", "(", "image", ")", "renderer", ".", "render", "(", "painter", ")", "return", "image" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
object_info
Make an object info dict with all fields present.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def object_info(**kw): """Make an object info dict with all fields present.""" infodict = dict(izip_longest(info_fields, [None])) infodict.update(kw) return infodict
def object_info(**kw): """Make an object info dict with all fields present.""" infodict = dict(izip_longest(info_fields, [None])) infodict.update(kw) return infodict
[ "Make", "an", "object", "info", "dict", "with", "all", "fields", "present", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L85-L89
[ "def", "object_info", "(", "*", "*", "kw", ")", ":", "infodict", "=", "dict", "(", "izip_longest", "(", "info_fields", ",", "[", "None", "]", ")", ")", "infodict", ".", "update", "(", "kw", ")", "return", "infodict" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getdoc
Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipython's ? system.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def getdoc(obj): """Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipython's ? system.""" # Allow objects to offer customized documentation via a getdoc method: try: ds = obj.getdoc() except Exception: pass else: # if we get extra info, we add it to the normal docstring. if isinstance(ds, basestring): return inspect.cleandoc(ds) try: return inspect.getdoc(obj) except Exception: # Harden against an inspect failure, which can occur with # SWIG-wrapped extensions. return None
def getdoc(obj): """Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be inspected by ipython's ? system.""" # Allow objects to offer customized documentation via a getdoc method: try: ds = obj.getdoc() except Exception: pass else: # if we get extra info, we add it to the normal docstring. if isinstance(ds, basestring): return inspect.cleandoc(ds) try: return inspect.getdoc(obj) except Exception: # Harden against an inspect failure, which can occur with # SWIG-wrapped extensions. return None
[ "Stable", "wrapper", "around", "inspect", ".", "getdoc", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L92-L115
[ "def", "getdoc", "(", "obj", ")", ":", "# Allow objects to offer customized documentation via a getdoc method:", "try", ":", "ds", "=", "obj", ".", "getdoc", "(", ")", "except", "Exception", ":", "pass", "else", ":", "# if we get extra info, we add it to the normal docstring.", "if", "isinstance", "(", "ds", ",", "basestring", ")", ":", "return", "inspect", ".", "cleandoc", "(", "ds", ")", "try", ":", "return", "inspect", ".", "getdoc", "(", "obj", ")", "except", "Exception", ":", "# Harden against an inspect failure, which can occur with", "# SWIG-wrapped extensions.", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getsource
Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to come from a binary source. This implementation will skip returning any output for binary objects, but custom extractors may know how to meaningfully process them.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def getsource(obj,is_binary=False): """Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to come from a binary source. This implementation will skip returning any output for binary objects, but custom extractors may know how to meaningfully process them.""" if is_binary: return None else: # get source if obj was decorated with @decorator if hasattr(obj,"__wrapped__"): obj = obj.__wrapped__ try: src = inspect.getsource(obj) except TypeError: if hasattr(obj,'__class__'): src = inspect.getsource(obj.__class__) return src
def getsource(obj,is_binary=False): """Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to come from a binary source. This implementation will skip returning any output for binary objects, but custom extractors may know how to meaningfully process them.""" if is_binary: return None else: # get source if obj was decorated with @decorator if hasattr(obj,"__wrapped__"): obj = obj.__wrapped__ try: src = inspect.getsource(obj) except TypeError: if hasattr(obj,'__class__'): src = inspect.getsource(obj.__class__) return src
[ "Wrapper", "around", "inspect", ".", "getsource", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L118-L145
[ "def", "getsource", "(", "obj", ",", "is_binary", "=", "False", ")", ":", "if", "is_binary", ":", "return", "None", "else", ":", "# get source if obj was decorated with @decorator", "if", "hasattr", "(", "obj", ",", "\"__wrapped__\"", ")", ":", "obj", "=", "obj", ".", "__wrapped__", "try", ":", "src", "=", "inspect", ".", "getsource", "(", "obj", ")", "except", "TypeError", ":", "if", "hasattr", "(", "obj", ",", "'__class__'", ")", ":", "src", "=", "inspect", ".", "getsource", "(", "obj", ".", "__class__", ")", "return", "src" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getargspec
Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Modified version of inspect.getargspec from the Python Standard Library.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def getargspec(obj): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Modified version of inspect.getargspec from the Python Standard Library.""" if inspect.isfunction(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = obj.im_func elif hasattr(obj, '__call__'): func_obj = obj.__call__ else: raise TypeError('arg is not a Python function') args, varargs, varkw = inspect.getargs(func_obj.func_code) return args, varargs, varkw, func_obj.func_defaults
def getargspec(obj): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Modified version of inspect.getargspec from the Python Standard Library.""" if inspect.isfunction(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = obj.im_func elif hasattr(obj, '__call__'): func_obj = obj.__call__ else: raise TypeError('arg is not a Python function') args, varargs, varkw = inspect.getargs(func_obj.func_code) return args, varargs, varkw, func_obj.func_defaults
[ "Get", "the", "names", "and", "default", "values", "of", "a", "function", "s", "arguments", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L147-L167
[ "def", "getargspec", "(", "obj", ")", ":", "if", "inspect", ".", "isfunction", "(", "obj", ")", ":", "func_obj", "=", "obj", "elif", "inspect", ".", "ismethod", "(", "obj", ")", ":", "func_obj", "=", "obj", ".", "im_func", "elif", "hasattr", "(", "obj", ",", "'__call__'", ")", ":", "func_obj", "=", "obj", ".", "__call__", "else", ":", "raise", "TypeError", "(", "'arg is not a Python function'", ")", "args", ",", "varargs", ",", "varkw", "=", "inspect", ".", "getargs", "(", "func_obj", ".", "func_code", ")", "return", "args", ",", "varargs", ",", "varkw", ",", "func_obj", ".", "func_defaults" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
call_tip
Extract call tip data from an oinfo dict. Parameters ---------- oinfo : dict format_call : bool, optional If True, the call line is formatted and returned as a string. If not, a tuple of (name, argspec) is returned. Returns ------- call_info : None, str or (str, dict) tuple. When format_call is True, the whole call information is formattted as a single string. Otherwise, the object's name and its argspec dict are returned. If no call information is available, None is returned. docstring : str or None The most relevant docstring for calling purposes is returned, if available. The priority is: call docstring for callable instances, then constructor docstring for classes, then main object's docstring otherwise (regular functions).
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def call_tip(oinfo, format_call=True): """Extract call tip data from an oinfo dict. Parameters ---------- oinfo : dict format_call : bool, optional If True, the call line is formatted and returned as a string. If not, a tuple of (name, argspec) is returned. Returns ------- call_info : None, str or (str, dict) tuple. When format_call is True, the whole call information is formattted as a single string. Otherwise, the object's name and its argspec dict are returned. If no call information is available, None is returned. docstring : str or None The most relevant docstring for calling purposes is returned, if available. The priority is: call docstring for callable instances, then constructor docstring for classes, then main object's docstring otherwise (regular functions). """ # Get call definition argspec = oinfo.get('argspec') if argspec is None: call_line = None else: # Callable objects will have 'self' as their first argument, prune # it out if it's there for clarity (since users do *not* pass an # extra first argument explicitly). try: has_self = argspec['args'][0] == 'self' except (KeyError, IndexError): pass else: if has_self: argspec['args'] = argspec['args'][1:] call_line = oinfo['name']+format_argspec(argspec) # Now get docstring. # The priority is: call docstring, constructor docstring, main one. doc = oinfo.get('call_docstring') if doc is None: doc = oinfo.get('init_docstring') if doc is None: doc = oinfo.get('docstring','') return call_line, doc
def call_tip(oinfo, format_call=True): """Extract call tip data from an oinfo dict. Parameters ---------- oinfo : dict format_call : bool, optional If True, the call line is formatted and returned as a string. If not, a tuple of (name, argspec) is returned. Returns ------- call_info : None, str or (str, dict) tuple. When format_call is True, the whole call information is formattted as a single string. Otherwise, the object's name and its argspec dict are returned. If no call information is available, None is returned. docstring : str or None The most relevant docstring for calling purposes is returned, if available. The priority is: call docstring for callable instances, then constructor docstring for classes, then main object's docstring otherwise (regular functions). """ # Get call definition argspec = oinfo.get('argspec') if argspec is None: call_line = None else: # Callable objects will have 'self' as their first argument, prune # it out if it's there for clarity (since users do *not* pass an # extra first argument explicitly). try: has_self = argspec['args'][0] == 'self' except (KeyError, IndexError): pass else: if has_self: argspec['args'] = argspec['args'][1:] call_line = oinfo['name']+format_argspec(argspec) # Now get docstring. # The priority is: call docstring, constructor docstring, main one. doc = oinfo.get('call_docstring') if doc is None: doc = oinfo.get('init_docstring') if doc is None: doc = oinfo.get('docstring','') return call_line, doc
[ "Extract", "call", "tip", "data", "from", "an", "oinfo", "dict", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L180-L230
[ "def", "call_tip", "(", "oinfo", ",", "format_call", "=", "True", ")", ":", "# Get call definition", "argspec", "=", "oinfo", ".", "get", "(", "'argspec'", ")", "if", "argspec", "is", "None", ":", "call_line", "=", "None", "else", ":", "# Callable objects will have 'self' as their first argument, prune", "# it out if it's there for clarity (since users do *not* pass an", "# extra first argument explicitly).", "try", ":", "has_self", "=", "argspec", "[", "'args'", "]", "[", "0", "]", "==", "'self'", "except", "(", "KeyError", ",", "IndexError", ")", ":", "pass", "else", ":", "if", "has_self", ":", "argspec", "[", "'args'", "]", "=", "argspec", "[", "'args'", "]", "[", "1", ":", "]", "call_line", "=", "oinfo", "[", "'name'", "]", "+", "format_argspec", "(", "argspec", ")", "# Now get docstring.", "# The priority is: call docstring, constructor docstring, main one.", "doc", "=", "oinfo", ".", "get", "(", "'call_docstring'", ")", "if", "doc", "is", "None", ":", "doc", "=", "oinfo", ".", "get", "(", "'init_docstring'", ")", "if", "doc", "is", "None", ":", "doc", "=", "oinfo", ".", "get", "(", "'docstring'", ",", "''", ")", "return", "call_line", ",", "doc" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_file
Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absolute path to the file where the object was defined.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def find_file(obj): """Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absolute path to the file where the object was defined. """ # get source if obj was decorated with @decorator if hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ fname = None try: fname = inspect.getabsfile(obj) except TypeError: # For an instance, the file that matters is where its class was # declared. if hasattr(obj, '__class__'): try: fname = inspect.getabsfile(obj.__class__) except TypeError: # Can happen for builtins pass except: pass return fname
def find_file(obj): """Find the absolute path to the file where an object was defined. This is essentially a robust wrapper around `inspect.getabsfile`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- fname : str The absolute path to the file where the object was defined. """ # get source if obj was decorated with @decorator if hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ fname = None try: fname = inspect.getabsfile(obj) except TypeError: # For an instance, the file that matters is where its class was # declared. if hasattr(obj, '__class__'): try: fname = inspect.getabsfile(obj.__class__) except TypeError: # Can happen for builtins pass except: pass return fname
[ "Find", "the", "absolute", "path", "to", "the", "file", "where", "an", "object", "was", "defined", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L233-L267
[ "def", "find_file", "(", "obj", ")", ":", "# get source if obj was decorated with @decorator", "if", "hasattr", "(", "obj", ",", "'__wrapped__'", ")", ":", "obj", "=", "obj", ".", "__wrapped__", "fname", "=", "None", "try", ":", "fname", "=", "inspect", ".", "getabsfile", "(", "obj", ")", "except", "TypeError", ":", "# For an instance, the file that matters is where its class was", "# declared.", "if", "hasattr", "(", "obj", ",", "'__class__'", ")", ":", "try", ":", "fname", "=", "inspect", ".", "getabsfile", "(", "obj", ".", "__class__", ")", "except", "TypeError", ":", "# Can happen for builtins", "pass", "except", ":", "pass", "return", "fname" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_source_lines
Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def find_source_lines(obj): """Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts. """ # get source if obj was decorated with @decorator if hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ try: try: lineno = inspect.getsourcelines(obj)[1] except TypeError: # For instances, try the class object like getsource() does if hasattr(obj, '__class__'): lineno = inspect.getsourcelines(obj.__class__)[1] except: return None return lineno
def find_source_lines(obj): """Find the line number in a file where an object was defined. This is essentially a robust wrapper around `inspect.getsourcelines`. Returns None if no file can be found. Parameters ---------- obj : any Python object Returns ------- lineno : int The line number where the object definition starts. """ # get source if obj was decorated with @decorator if hasattr(obj, '__wrapped__'): obj = obj.__wrapped__ try: try: lineno = inspect.getsourcelines(obj)[1] except TypeError: # For instances, try the class object like getsource() does if hasattr(obj, '__class__'): lineno = inspect.getsourcelines(obj.__class__)[1] except: return None return lineno
[ "Find", "the", "line", "number", "in", "a", "file", "where", "an", "object", "was", "defined", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L270-L300
[ "def", "find_source_lines", "(", "obj", ")", ":", "# get source if obj was decorated with @decorator", "if", "hasattr", "(", "obj", ",", "'__wrapped__'", ")", ":", "obj", "=", "obj", ".", "__wrapped__", "try", ":", "try", ":", "lineno", "=", "inspect", ".", "getsourcelines", "(", "obj", ")", "[", "1", "]", "except", "TypeError", ":", "# For instances, try the class object like getsource() does", "if", "hasattr", "(", "obj", ",", "'__class__'", ")", ":", "lineno", "=", "inspect", ".", "getsourcelines", "(", "obj", ".", "__class__", ")", "[", "1", "]", "except", ":", "return", "None", "return", "lineno" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector._getdef
Return the definition header for any callable object. If any exception is generated, None is returned instead and the exception is suppressed.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def _getdef(self,obj,oname=''): """Return the definition header for any callable object. If any exception is generated, None is returned instead and the exception is suppressed.""" try: # We need a plain string here, NOT unicode! hdef = oname + inspect.formatargspec(*getargspec(obj)) return py3compat.unicode_to_str(hdef, 'ascii') except: return None
def _getdef(self,obj,oname=''): """Return the definition header for any callable object. If any exception is generated, None is returned instead and the exception is suppressed.""" try: # We need a plain string here, NOT unicode! hdef = oname + inspect.formatargspec(*getargspec(obj)) return py3compat.unicode_to_str(hdef, 'ascii') except: return None
[ "Return", "the", "definition", "header", "for", "any", "callable", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L314-L325
[ "def", "_getdef", "(", "self", ",", "obj", ",", "oname", "=", "''", ")", ":", "try", ":", "# We need a plain string here, NOT unicode!", "hdef", "=", "oname", "+", "inspect", ".", "formatargspec", "(", "*", "getargspec", "(", "obj", ")", ")", "return", "py3compat", ".", "unicode_to_str", "(", "hdef", ",", "'ascii'", ")", "except", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.__head
Return a header string with proper colors.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def __head(self,h): """Return a header string with proper colors.""" return '%s%s%s' % (self.color_table.active_colors.header,h, self.color_table.active_colors.normal)
def __head(self,h): """Return a header string with proper colors.""" return '%s%s%s' % (self.color_table.active_colors.header,h, self.color_table.active_colors.normal)
[ "Return", "a", "header", "string", "with", "proper", "colors", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L327-L330
[ "def", "__head", "(", "self", ",", "h", ")", ":", "return", "'%s%s%s'", "%", "(", "self", ".", "color_table", ".", "active_colors", ".", "header", ",", "h", ",", "self", ".", "color_table", ".", "active_colors", ".", "normal", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.noinfo
Generic message when no information is found.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def noinfo(self, msg, oname): """Generic message when no information is found.""" print 'No %s found' % msg, if oname: print 'for %s' % oname else: print
def noinfo(self, msg, oname): """Generic message when no information is found.""" print 'No %s found' % msg, if oname: print 'for %s' % oname else: print
[ "Generic", "message", "when", "no", "information", "is", "found", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L336-L342
[ "def", "noinfo", "(", "self", ",", "msg", ",", "oname", ")", ":", "print", "'No %s found'", "%", "msg", ",", "if", "oname", ":", "print", "'for %s'", "%", "oname", "else", ":", "print" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.pdef
Print the definition header for any callable object. If the object is a class, print the constructor information.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def pdef(self, obj, oname=''): """Print the definition header for any callable object. If the object is a class, print the constructor information.""" if not callable(obj): print 'Object is not callable.' return header = '' if inspect.isclass(obj): header = self.__head('Class constructor information:\n') obj = obj.__init__ elif (not py3compat.PY3) and type(obj) is types.InstanceType: obj = obj.__call__ output = self._getdef(obj,oname) if output is None: self.noinfo('definition header',oname) else: print >>io.stdout, header,self.format(output),
def pdef(self, obj, oname=''): """Print the definition header for any callable object. If the object is a class, print the constructor information.""" if not callable(obj): print 'Object is not callable.' return header = '' if inspect.isclass(obj): header = self.__head('Class constructor information:\n') obj = obj.__init__ elif (not py3compat.PY3) and type(obj) is types.InstanceType: obj = obj.__call__ output = self._getdef(obj,oname) if output is None: self.noinfo('definition header',oname) else: print >>io.stdout, header,self.format(output),
[ "Print", "the", "definition", "header", "for", "any", "callable", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L344-L365
[ "def", "pdef", "(", "self", ",", "obj", ",", "oname", "=", "''", ")", ":", "if", "not", "callable", "(", "obj", ")", ":", "print", "'Object is not callable.'", "return", "header", "=", "''", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "header", "=", "self", ".", "__head", "(", "'Class constructor information:\\n'", ")", "obj", "=", "obj", ".", "__init__", "elif", "(", "not", "py3compat", ".", "PY3", ")", "and", "type", "(", "obj", ")", "is", "types", ".", "InstanceType", ":", "obj", "=", "obj", ".", "__call__", "output", "=", "self", ".", "_getdef", "(", "obj", ",", "oname", ")", "if", "output", "is", "None", ":", "self", ".", "noinfo", "(", "'definition header'", ",", "oname", ")", "else", ":", "print", ">>", "io", ".", "stdout", ",", "header", ",", "self", ".", "format", "(", "output", ")", "," ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.pdoc
Print the docstring for any object. Optional: -formatter: a function to run the docstring through for specially formatted docstrings. Examples -------- In [1]: class NoInit: ...: pass In [2]: class NoDoc: ...: def __init__(self): ...: pass In [3]: %pdoc NoDoc No documentation found for NoDoc In [4]: %pdoc NoInit No documentation found for NoInit In [5]: obj = NoInit() In [6]: %pdoc obj No documentation found for obj In [5]: obj2 = NoDoc() In [6]: %pdoc obj2 No documentation found for obj2
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def pdoc(self,obj,oname='',formatter = None): """Print the docstring for any object. Optional: -formatter: a function to run the docstring through for specially formatted docstrings. Examples -------- In [1]: class NoInit: ...: pass In [2]: class NoDoc: ...: def __init__(self): ...: pass In [3]: %pdoc NoDoc No documentation found for NoDoc In [4]: %pdoc NoInit No documentation found for NoInit In [5]: obj = NoInit() In [6]: %pdoc obj No documentation found for obj In [5]: obj2 = NoDoc() In [6]: %pdoc obj2 No documentation found for obj2 """ head = self.__head # For convenience lines = [] ds = getdoc(obj) if formatter: ds = formatter(ds) if ds: lines.append(head("Class Docstring:")) lines.append(indent(ds)) if inspect.isclass(obj) and hasattr(obj, '__init__'): init_ds = getdoc(obj.__init__) if init_ds is not None: lines.append(head("Constructor Docstring:")) lines.append(indent(init_ds)) elif hasattr(obj,'__call__'): call_ds = getdoc(obj.__call__) if call_ds: lines.append(head("Calling Docstring:")) lines.append(indent(call_ds)) if not lines: self.noinfo('documentation',oname) else: page.page('\n'.join(lines))
def pdoc(self,obj,oname='',formatter = None): """Print the docstring for any object. Optional: -formatter: a function to run the docstring through for specially formatted docstrings. Examples -------- In [1]: class NoInit: ...: pass In [2]: class NoDoc: ...: def __init__(self): ...: pass In [3]: %pdoc NoDoc No documentation found for NoDoc In [4]: %pdoc NoInit No documentation found for NoInit In [5]: obj = NoInit() In [6]: %pdoc obj No documentation found for obj In [5]: obj2 = NoDoc() In [6]: %pdoc obj2 No documentation found for obj2 """ head = self.__head # For convenience lines = [] ds = getdoc(obj) if formatter: ds = formatter(ds) if ds: lines.append(head("Class Docstring:")) lines.append(indent(ds)) if inspect.isclass(obj) and hasattr(obj, '__init__'): init_ds = getdoc(obj.__init__) if init_ds is not None: lines.append(head("Constructor Docstring:")) lines.append(indent(init_ds)) elif hasattr(obj,'__call__'): call_ds = getdoc(obj.__call__) if call_ds: lines.append(head("Calling Docstring:")) lines.append(indent(call_ds)) if not lines: self.noinfo('documentation',oname) else: page.page('\n'.join(lines))
[ "Print", "the", "docstring", "for", "any", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L369-L425
[ "def", "pdoc", "(", "self", ",", "obj", ",", "oname", "=", "''", ",", "formatter", "=", "None", ")", ":", "head", "=", "self", ".", "__head", "# For convenience", "lines", "=", "[", "]", "ds", "=", "getdoc", "(", "obj", ")", "if", "formatter", ":", "ds", "=", "formatter", "(", "ds", ")", "if", "ds", ":", "lines", ".", "append", "(", "head", "(", "\"Class Docstring:\"", ")", ")", "lines", ".", "append", "(", "indent", "(", "ds", ")", ")", "if", "inspect", ".", "isclass", "(", "obj", ")", "and", "hasattr", "(", "obj", ",", "'__init__'", ")", ":", "init_ds", "=", "getdoc", "(", "obj", ".", "__init__", ")", "if", "init_ds", "is", "not", "None", ":", "lines", ".", "append", "(", "head", "(", "\"Constructor Docstring:\"", ")", ")", "lines", ".", "append", "(", "indent", "(", "init_ds", ")", ")", "elif", "hasattr", "(", "obj", ",", "'__call__'", ")", ":", "call_ds", "=", "getdoc", "(", "obj", ".", "__call__", ")", "if", "call_ds", ":", "lines", ".", "append", "(", "head", "(", "\"Calling Docstring:\"", ")", ")", "lines", ".", "append", "(", "indent", "(", "call_ds", ")", ")", "if", "not", "lines", ":", "self", ".", "noinfo", "(", "'documentation'", ",", "oname", ")", "else", ":", "page", ".", "page", "(", "'\\n'", ".", "join", "(", "lines", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.psource
Print the source code for an object.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def psource(self,obj,oname=''): """Print the source code for an object.""" # Flush the source cache because inspect can return out-of-date source linecache.checkcache() try: src = getsource(obj) except: self.noinfo('source',oname) else: page.page(self.format(py3compat.unicode_to_str(src)))
def psource(self,obj,oname=''): """Print the source code for an object.""" # Flush the source cache because inspect can return out-of-date source linecache.checkcache() try: src = getsource(obj) except: self.noinfo('source',oname) else: page.page(self.format(py3compat.unicode_to_str(src)))
[ "Print", "the", "source", "code", "for", "an", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L427-L437
[ "def", "psource", "(", "self", ",", "obj", ",", "oname", "=", "''", ")", ":", "# Flush the source cache because inspect can return out-of-date source", "linecache", ".", "checkcache", "(", ")", "try", ":", "src", "=", "getsource", "(", "obj", ")", "except", ":", "self", ".", "noinfo", "(", "'source'", ",", "oname", ")", "else", ":", "page", ".", "page", "(", "self", ".", "format", "(", "py3compat", ".", "unicode_to_str", "(", "src", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.pfile
Show the whole file where an object was defined.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def pfile(self, obj, oname=''): """Show the whole file where an object was defined.""" lineno = find_source_lines(obj) if lineno is None: self.noinfo('file', oname) return ofile = find_file(obj) # run contents of file through pager starting at line where the object # is defined, as long as the file isn't binary and is actually on the # filesystem. if ofile.endswith(('.so', '.dll', '.pyd')): print 'File %r is binary, not printing.' % ofile elif not os.path.isfile(ofile): print 'File %r does not exist, not printing.' % ofile else: # Print only text files, not extension binaries. Note that # getsourcelines returns lineno with 1-offset and page() uses # 0-offset, so we must adjust. page.page(self.format(open(ofile).read()), lineno-1)
def pfile(self, obj, oname=''): """Show the whole file where an object was defined.""" lineno = find_source_lines(obj) if lineno is None: self.noinfo('file', oname) return ofile = find_file(obj) # run contents of file through pager starting at line where the object # is defined, as long as the file isn't binary and is actually on the # filesystem. if ofile.endswith(('.so', '.dll', '.pyd')): print 'File %r is binary, not printing.' % ofile elif not os.path.isfile(ofile): print 'File %r does not exist, not printing.' % ofile else: # Print only text files, not extension binaries. Note that # getsourcelines returns lineno with 1-offset and page() uses # 0-offset, so we must adjust. page.page(self.format(open(ofile).read()), lineno-1)
[ "Show", "the", "whole", "file", "where", "an", "object", "was", "defined", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L439-L459
[ "def", "pfile", "(", "self", ",", "obj", ",", "oname", "=", "''", ")", ":", "lineno", "=", "find_source_lines", "(", "obj", ")", "if", "lineno", "is", "None", ":", "self", ".", "noinfo", "(", "'file'", ",", "oname", ")", "return", "ofile", "=", "find_file", "(", "obj", ")", "# run contents of file through pager starting at line where the object", "# is defined, as long as the file isn't binary and is actually on the", "# filesystem.", "if", "ofile", ".", "endswith", "(", "(", "'.so'", ",", "'.dll'", ",", "'.pyd'", ")", ")", ":", "print", "'File %r is binary, not printing.'", "%", "ofile", "elif", "not", "os", ".", "path", ".", "isfile", "(", "ofile", ")", ":", "print", "'File %r does not exist, not printing.'", "%", "ofile", "else", ":", "# Print only text files, not extension binaries. Note that", "# getsourcelines returns lineno with 1-offset and page() uses", "# 0-offset, so we must adjust.", "page", ".", "page", "(", "self", ".", "format", "(", "open", "(", "ofile", ")", ".", "read", "(", ")", ")", ",", "lineno", "-", "1", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector._format_fields
Formats a list of fields for display. Parameters ---------- fields : list A list of 2-tuples: (field_title, field_content) title_width : int How many characters to pad titles to. Default 12.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def _format_fields(self, fields, title_width=12): """Formats a list of fields for display. Parameters ---------- fields : list A list of 2-tuples: (field_title, field_content) title_width : int How many characters to pad titles to. Default 12. """ out = [] header = self.__head for title, content in fields: if len(content.splitlines()) > 1: title = header(title + ":") + "\n" else: title = header((title+":").ljust(title_width)) out.append(title + content) return "\n".join(out)
def _format_fields(self, fields, title_width=12): """Formats a list of fields for display. Parameters ---------- fields : list A list of 2-tuples: (field_title, field_content) title_width : int How many characters to pad titles to. Default 12. """ out = [] header = self.__head for title, content in fields: if len(content.splitlines()) > 1: title = header(title + ":") + "\n" else: title = header((title+":").ljust(title_width)) out.append(title + content) return "\n".join(out)
[ "Formats", "a", "list", "of", "fields", "for", "display", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L461-L479
[ "def", "_format_fields", "(", "self", ",", "fields", ",", "title_width", "=", "12", ")", ":", "out", "=", "[", "]", "header", "=", "self", ".", "__head", "for", "title", ",", "content", "in", "fields", ":", "if", "len", "(", "content", ".", "splitlines", "(", ")", ")", ">", "1", ":", "title", "=", "header", "(", "title", "+", "\":\"", ")", "+", "\"\\n\"", "else", ":", "title", "=", "header", "(", "(", "title", "+", "\":\"", ")", ".", "ljust", "(", "title_width", ")", ")", "out", ".", "append", "(", "title", "+", "content", ")", "return", "\"\\n\"", ".", "join", "(", "out", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.pinfo
Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): """Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given. """ info = self.info(obj, oname=oname, formatter=formatter, info=info, detail_level=detail_level) displayfields = [] def add_fields(fields): for title, key in fields: field = info[key] if field is not None: displayfields.append((title, field.rstrip())) add_fields(self.pinfo_fields1) # Base class for old-style instances if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']: displayfields.append(("Base Class", info['base_class'].rstrip())) add_fields(self.pinfo_fields2) # Namespace if info['namespace'] != 'Interactive': displayfields.append(("Namespace", info['namespace'].rstrip())) add_fields(self.pinfo_fields3) # Source or docstring, depending on detail level and whether # source found. if detail_level > 0 and info['source'] is not None: displayfields.append(("Source", self.format(py3compat.cast_bytes_py2(info['source'])))) elif info['docstring'] is not None: displayfields.append(("Docstring", info["docstring"])) # Constructor info for classes if info['isclass']: if info['init_definition'] or info['init_docstring']: displayfields.append(("Constructor information", "")) if info['init_definition'] is not None: displayfields.append((" Definition", info['init_definition'].rstrip())) if info['init_docstring'] is not None: displayfields.append((" Docstring", indent(info['init_docstring']))) # Info for objects: else: add_fields(self.pinfo_fields_obj) # Finally send to printer/pager: if displayfields: page.page(self._format_fields(displayfields))
def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): """Show detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given. """ info = self.info(obj, oname=oname, formatter=formatter, info=info, detail_level=detail_level) displayfields = [] def add_fields(fields): for title, key in fields: field = info[key] if field is not None: displayfields.append((title, field.rstrip())) add_fields(self.pinfo_fields1) # Base class for old-style instances if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']: displayfields.append(("Base Class", info['base_class'].rstrip())) add_fields(self.pinfo_fields2) # Namespace if info['namespace'] != 'Interactive': displayfields.append(("Namespace", info['namespace'].rstrip())) add_fields(self.pinfo_fields3) # Source or docstring, depending on detail level and whether # source found. if detail_level > 0 and info['source'] is not None: displayfields.append(("Source", self.format(py3compat.cast_bytes_py2(info['source'])))) elif info['docstring'] is not None: displayfields.append(("Docstring", info["docstring"])) # Constructor info for classes if info['isclass']: if info['init_definition'] or info['init_docstring']: displayfields.append(("Constructor information", "")) if info['init_definition'] is not None: displayfields.append((" Definition", info['init_definition'].rstrip())) if info['init_docstring'] is not None: displayfields.append((" Docstring", indent(info['init_docstring']))) # Info for objects: else: add_fields(self.pinfo_fields_obj) # Finally send to printer/pager: if displayfields: page.page(self._format_fields(displayfields))
[ "Show", "detailed", "information", "about", "an", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L498-L559
[ "def", "pinfo", "(", "self", ",", "obj", ",", "oname", "=", "''", ",", "formatter", "=", "None", ",", "info", "=", "None", ",", "detail_level", "=", "0", ")", ":", "info", "=", "self", ".", "info", "(", "obj", ",", "oname", "=", "oname", ",", "formatter", "=", "formatter", ",", "info", "=", "info", ",", "detail_level", "=", "detail_level", ")", "displayfields", "=", "[", "]", "def", "add_fields", "(", "fields", ")", ":", "for", "title", ",", "key", "in", "fields", ":", "field", "=", "info", "[", "key", "]", "if", "field", "is", "not", "None", ":", "displayfields", ".", "append", "(", "(", "title", ",", "field", ".", "rstrip", "(", ")", ")", ")", "add_fields", "(", "self", ".", "pinfo_fields1", ")", "# Base class for old-style instances", "if", "(", "not", "py3compat", ".", "PY3", ")", "and", "isinstance", "(", "obj", ",", "types", ".", "InstanceType", ")", "and", "info", "[", "'base_class'", "]", ":", "displayfields", ".", "append", "(", "(", "\"Base Class\"", ",", "info", "[", "'base_class'", "]", ".", "rstrip", "(", ")", ")", ")", "add_fields", "(", "self", ".", "pinfo_fields2", ")", "# Namespace", "if", "info", "[", "'namespace'", "]", "!=", "'Interactive'", ":", "displayfields", ".", "append", "(", "(", "\"Namespace\"", ",", "info", "[", "'namespace'", "]", ".", "rstrip", "(", ")", ")", ")", "add_fields", "(", "self", ".", "pinfo_fields3", ")", "# Source or docstring, depending on detail level and whether", "# source found.", "if", "detail_level", ">", "0", "and", "info", "[", "'source'", "]", "is", "not", "None", ":", "displayfields", ".", "append", "(", "(", "\"Source\"", ",", "self", ".", "format", "(", "py3compat", ".", "cast_bytes_py2", "(", "info", "[", "'source'", "]", ")", ")", ")", ")", "elif", "info", "[", "'docstring'", "]", "is", "not", "None", ":", "displayfields", ".", "append", "(", "(", "\"Docstring\"", ",", "info", "[", "\"docstring\"", "]", ")", ")", "# Constructor info for classes", "if", "info", "[", "'isclass'", "]", ":", "if", "info", "[", "'init_definition'", "]", "or", "info", "[", "'init_docstring'", "]", ":", "displayfields", ".", "append", "(", "(", "\"Constructor information\"", ",", "\"\"", ")", ")", "if", "info", "[", "'init_definition'", "]", "is", "not", "None", ":", "displayfields", ".", "append", "(", "(", "\" Definition\"", ",", "info", "[", "'init_definition'", "]", ".", "rstrip", "(", ")", ")", ")", "if", "info", "[", "'init_docstring'", "]", "is", "not", "None", ":", "displayfields", ".", "append", "(", "(", "\" Docstring\"", ",", "indent", "(", "info", "[", "'init_docstring'", "]", ")", ")", ")", "# Info for objects:", "else", ":", "add_fields", "(", "self", ".", "pinfo_fields_obj", ")", "# Finally send to printer/pager:", "if", "displayfields", ":", "page", ".", "page", "(", "self", ".", "_format_fields", "(", "displayfields", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.info
Compute a dict with detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def info(self, obj, oname='', formatter=None, info=None, detail_level=0): """Compute a dict with detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given. """ obj_type = type(obj) header = self.__head if info is None: ismagic = 0 isalias = 0 ospace = '' else: ismagic = info.ismagic isalias = info.isalias ospace = info.namespace # Get docstring, special-casing aliases: if isalias: if not callable(obj): try: ds = "Alias to the system command:\n %s" % obj[1] except: ds = "Alias: " + str(obj) else: ds = "Alias to " + str(obj) if obj.__doc__: ds += "\nDocstring:\n" + obj.__doc__ else: ds = getdoc(obj) if ds is None: ds = '<no docstring>' if formatter is not None: ds = formatter(ds) # store output in a dict, we initialize it here and fill it as we go out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) string_max = 200 # max size of strings to show (snipped if longer) shalf = int((string_max -5)/2) if ismagic: obj_type_name = 'Magic function' elif isalias: obj_type_name = 'System alias' else: obj_type_name = obj_type.__name__ out['type_name'] = obj_type_name try: bclass = obj.__class__ out['base_class'] = str(bclass) except: pass # String form, but snip if too long in ? form (full in ??) if detail_level >= self.str_detail_level: try: ostr = str(obj) str_head = 'string_form' if not detail_level and len(ostr)>string_max: ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] ostr = ("\n" + " " * len(str_head.expandtabs())).\ join(q.strip() for q in ostr.split("\n")) out[str_head] = ostr except: pass if ospace: out['namespace'] = ospace # Length (for strings and lists) try: out['length'] = str(len(obj)) except: pass # Filename where object was defined binary_file = False fname = find_file(obj) if fname is None: # if anything goes wrong, we don't want to show source, so it's as # if the file was binary binary_file = True else: if fname.endswith(('.so', '.dll', '.pyd')): binary_file = True elif fname.endswith('<string>'): fname = 'Dynamically generated function. No source code available.' out['file'] = fname # reconstruct the function definition and print it: defln = self._getdef(obj, oname) if defln: out['definition'] = self.format(defln) # Docstrings only in detail 0 mode, since source contains them (we # avoid repetitions). If source fails, we add them back, see below. if ds and detail_level == 0: out['docstring'] = ds # Original source code for any callable if detail_level: # Flush the source cache because inspect can return out-of-date # source linecache.checkcache() source = None try: try: source = getsource(obj, binary_file) except TypeError: if hasattr(obj, '__class__'): source = getsource(obj.__class__, binary_file) if source is not None: out['source'] = source.rstrip() except Exception: pass if ds and source is None: out['docstring'] = ds # Constructor docstring for classes if inspect.isclass(obj): out['isclass'] = True # reconstruct the function definition and print it: try: obj_init = obj.__init__ except AttributeError: init_def = init_ds = None else: init_def = self._getdef(obj_init,oname) init_ds = getdoc(obj_init) # Skip Python's auto-generated docstrings if init_ds and \ init_ds.startswith('x.__init__(...) initializes'): init_ds = None if init_def or init_ds: if init_def: out['init_definition'] = self.format(init_def) if init_ds: out['init_docstring'] = init_ds # and class docstring for instances: else: # First, check whether the instance docstring is identical to the # class one, and print it separately if they don't coincide. In # most cases they will, but it's nice to print all the info for # objects which use instance-customized docstrings. if ds: try: cls = getattr(obj,'__class__') except: class_ds = None else: class_ds = getdoc(cls) # Skip Python's auto-generated docstrings if class_ds and \ (class_ds.startswith('function(code, globals[,') or \ class_ds.startswith('instancemethod(function, instance,') or \ class_ds.startswith('module(name[,') ): class_ds = None if class_ds and ds != class_ds: out['class_docstring'] = class_ds # Next, try to show constructor docstrings try: init_ds = getdoc(obj.__init__) # Skip Python's auto-generated docstrings if init_ds and \ init_ds.startswith('x.__init__(...) initializes'): init_ds = None except AttributeError: init_ds = None if init_ds: out['init_docstring'] = init_ds # Call form docstring for callable instances if hasattr(obj, '__call__'): call_def = self._getdef(obj.__call__, oname) if call_def is not None: out['call_def'] = self.format(call_def) call_ds = getdoc(obj.__call__) # Skip Python's auto-generated docstrings if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): call_ds = None if call_ds: out['call_docstring'] = call_ds # Compute the object's argspec as a callable. The key is to decide # whether to pull it from the object itself, from its __init__ or # from its __call__ method. if inspect.isclass(obj): # Old-style classes need not have an __init__ callable_obj = getattr(obj, "__init__", None) elif callable(obj): callable_obj = obj else: callable_obj = None if callable_obj: try: args, varargs, varkw, defaults = getargspec(callable_obj) except (TypeError, AttributeError): # For extensions/builtins we can't retrieve the argspec pass else: out['argspec'] = dict(args=args, varargs=varargs, varkw=varkw, defaults=defaults) return object_info(**out)
def info(self, obj, oname='', formatter=None, info=None, detail_level=0): """Compute a dict with detailed information about an object. Optional arguments: - oname: name of the variable pointing to the object. - formatter: special formatter for docstrings (see pdoc) - info: a structure with some information fields which may have been precomputed already. - detail_level: if set to 1, more information is given. """ obj_type = type(obj) header = self.__head if info is None: ismagic = 0 isalias = 0 ospace = '' else: ismagic = info.ismagic isalias = info.isalias ospace = info.namespace # Get docstring, special-casing aliases: if isalias: if not callable(obj): try: ds = "Alias to the system command:\n %s" % obj[1] except: ds = "Alias: " + str(obj) else: ds = "Alias to " + str(obj) if obj.__doc__: ds += "\nDocstring:\n" + obj.__doc__ else: ds = getdoc(obj) if ds is None: ds = '<no docstring>' if formatter is not None: ds = formatter(ds) # store output in a dict, we initialize it here and fill it as we go out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) string_max = 200 # max size of strings to show (snipped if longer) shalf = int((string_max -5)/2) if ismagic: obj_type_name = 'Magic function' elif isalias: obj_type_name = 'System alias' else: obj_type_name = obj_type.__name__ out['type_name'] = obj_type_name try: bclass = obj.__class__ out['base_class'] = str(bclass) except: pass # String form, but snip if too long in ? form (full in ??) if detail_level >= self.str_detail_level: try: ostr = str(obj) str_head = 'string_form' if not detail_level and len(ostr)>string_max: ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] ostr = ("\n" + " " * len(str_head.expandtabs())).\ join(q.strip() for q in ostr.split("\n")) out[str_head] = ostr except: pass if ospace: out['namespace'] = ospace # Length (for strings and lists) try: out['length'] = str(len(obj)) except: pass # Filename where object was defined binary_file = False fname = find_file(obj) if fname is None: # if anything goes wrong, we don't want to show source, so it's as # if the file was binary binary_file = True else: if fname.endswith(('.so', '.dll', '.pyd')): binary_file = True elif fname.endswith('<string>'): fname = 'Dynamically generated function. No source code available.' out['file'] = fname # reconstruct the function definition and print it: defln = self._getdef(obj, oname) if defln: out['definition'] = self.format(defln) # Docstrings only in detail 0 mode, since source contains them (we # avoid repetitions). If source fails, we add them back, see below. if ds and detail_level == 0: out['docstring'] = ds # Original source code for any callable if detail_level: # Flush the source cache because inspect can return out-of-date # source linecache.checkcache() source = None try: try: source = getsource(obj, binary_file) except TypeError: if hasattr(obj, '__class__'): source = getsource(obj.__class__, binary_file) if source is not None: out['source'] = source.rstrip() except Exception: pass if ds and source is None: out['docstring'] = ds # Constructor docstring for classes if inspect.isclass(obj): out['isclass'] = True # reconstruct the function definition and print it: try: obj_init = obj.__init__ except AttributeError: init_def = init_ds = None else: init_def = self._getdef(obj_init,oname) init_ds = getdoc(obj_init) # Skip Python's auto-generated docstrings if init_ds and \ init_ds.startswith('x.__init__(...) initializes'): init_ds = None if init_def or init_ds: if init_def: out['init_definition'] = self.format(init_def) if init_ds: out['init_docstring'] = init_ds # and class docstring for instances: else: # First, check whether the instance docstring is identical to the # class one, and print it separately if they don't coincide. In # most cases they will, but it's nice to print all the info for # objects which use instance-customized docstrings. if ds: try: cls = getattr(obj,'__class__') except: class_ds = None else: class_ds = getdoc(cls) # Skip Python's auto-generated docstrings if class_ds and \ (class_ds.startswith('function(code, globals[,') or \ class_ds.startswith('instancemethod(function, instance,') or \ class_ds.startswith('module(name[,') ): class_ds = None if class_ds and ds != class_ds: out['class_docstring'] = class_ds # Next, try to show constructor docstrings try: init_ds = getdoc(obj.__init__) # Skip Python's auto-generated docstrings if init_ds and \ init_ds.startswith('x.__init__(...) initializes'): init_ds = None except AttributeError: init_ds = None if init_ds: out['init_docstring'] = init_ds # Call form docstring for callable instances if hasattr(obj, '__call__'): call_def = self._getdef(obj.__call__, oname) if call_def is not None: out['call_def'] = self.format(call_def) call_ds = getdoc(obj.__call__) # Skip Python's auto-generated docstrings if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): call_ds = None if call_ds: out['call_docstring'] = call_ds # Compute the object's argspec as a callable. The key is to decide # whether to pull it from the object itself, from its __init__ or # from its __call__ method. if inspect.isclass(obj): # Old-style classes need not have an __init__ callable_obj = getattr(obj, "__init__", None) elif callable(obj): callable_obj = obj else: callable_obj = None if callable_obj: try: args, varargs, varkw, defaults = getargspec(callable_obj) except (TypeError, AttributeError): # For extensions/builtins we can't retrieve the argspec pass else: out['argspec'] = dict(args=args, varargs=varargs, varkw=varkw, defaults=defaults) return object_info(**out)
[ "Compute", "a", "dict", "with", "detailed", "information", "about", "an", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L561-L781
[ "def", "info", "(", "self", ",", "obj", ",", "oname", "=", "''", ",", "formatter", "=", "None", ",", "info", "=", "None", ",", "detail_level", "=", "0", ")", ":", "obj_type", "=", "type", "(", "obj", ")", "header", "=", "self", ".", "__head", "if", "info", "is", "None", ":", "ismagic", "=", "0", "isalias", "=", "0", "ospace", "=", "''", "else", ":", "ismagic", "=", "info", ".", "ismagic", "isalias", "=", "info", ".", "isalias", "ospace", "=", "info", ".", "namespace", "# Get docstring, special-casing aliases:", "if", "isalias", ":", "if", "not", "callable", "(", "obj", ")", ":", "try", ":", "ds", "=", "\"Alias to the system command:\\n %s\"", "%", "obj", "[", "1", "]", "except", ":", "ds", "=", "\"Alias: \"", "+", "str", "(", "obj", ")", "else", ":", "ds", "=", "\"Alias to \"", "+", "str", "(", "obj", ")", "if", "obj", ".", "__doc__", ":", "ds", "+=", "\"\\nDocstring:\\n\"", "+", "obj", ".", "__doc__", "else", ":", "ds", "=", "getdoc", "(", "obj", ")", "if", "ds", "is", "None", ":", "ds", "=", "'<no docstring>'", "if", "formatter", "is", "not", "None", ":", "ds", "=", "formatter", "(", "ds", ")", "# store output in a dict, we initialize it here and fill it as we go", "out", "=", "dict", "(", "name", "=", "oname", ",", "found", "=", "True", ",", "isalias", "=", "isalias", ",", "ismagic", "=", "ismagic", ")", "string_max", "=", "200", "# max size of strings to show (snipped if longer)", "shalf", "=", "int", "(", "(", "string_max", "-", "5", ")", "/", "2", ")", "if", "ismagic", ":", "obj_type_name", "=", "'Magic function'", "elif", "isalias", ":", "obj_type_name", "=", "'System alias'", "else", ":", "obj_type_name", "=", "obj_type", ".", "__name__", "out", "[", "'type_name'", "]", "=", "obj_type_name", "try", ":", "bclass", "=", "obj", ".", "__class__", "out", "[", "'base_class'", "]", "=", "str", "(", "bclass", ")", "except", ":", "pass", "# String form, but snip if too long in ? form (full in ??)", "if", "detail_level", ">=", "self", ".", "str_detail_level", ":", "try", ":", "ostr", "=", "str", "(", "obj", ")", "str_head", "=", "'string_form'", "if", "not", "detail_level", "and", "len", "(", "ostr", ")", ">", "string_max", ":", "ostr", "=", "ostr", "[", ":", "shalf", "]", "+", "' <...> '", "+", "ostr", "[", "-", "shalf", ":", "]", "ostr", "=", "(", "\"\\n\"", "+", "\" \"", "*", "len", "(", "str_head", ".", "expandtabs", "(", ")", ")", ")", ".", "join", "(", "q", ".", "strip", "(", ")", "for", "q", "in", "ostr", ".", "split", "(", "\"\\n\"", ")", ")", "out", "[", "str_head", "]", "=", "ostr", "except", ":", "pass", "if", "ospace", ":", "out", "[", "'namespace'", "]", "=", "ospace", "# Length (for strings and lists)", "try", ":", "out", "[", "'length'", "]", "=", "str", "(", "len", "(", "obj", ")", ")", "except", ":", "pass", "# Filename where object was defined", "binary_file", "=", "False", "fname", "=", "find_file", "(", "obj", ")", "if", "fname", "is", "None", ":", "# if anything goes wrong, we don't want to show source, so it's as", "# if the file was binary", "binary_file", "=", "True", "else", ":", "if", "fname", ".", "endswith", "(", "(", "'.so'", ",", "'.dll'", ",", "'.pyd'", ")", ")", ":", "binary_file", "=", "True", "elif", "fname", ".", "endswith", "(", "'<string>'", ")", ":", "fname", "=", "'Dynamically generated function. No source code available.'", "out", "[", "'file'", "]", "=", "fname", "# reconstruct the function definition and print it:", "defln", "=", "self", ".", "_getdef", "(", "obj", ",", "oname", ")", "if", "defln", ":", "out", "[", "'definition'", "]", "=", "self", ".", "format", "(", "defln", ")", "# Docstrings only in detail 0 mode, since source contains them (we", "# avoid repetitions). If source fails, we add them back, see below.", "if", "ds", "and", "detail_level", "==", "0", ":", "out", "[", "'docstring'", "]", "=", "ds", "# Original source code for any callable", "if", "detail_level", ":", "# Flush the source cache because inspect can return out-of-date", "# source", "linecache", ".", "checkcache", "(", ")", "source", "=", "None", "try", ":", "try", ":", "source", "=", "getsource", "(", "obj", ",", "binary_file", ")", "except", "TypeError", ":", "if", "hasattr", "(", "obj", ",", "'__class__'", ")", ":", "source", "=", "getsource", "(", "obj", ".", "__class__", ",", "binary_file", ")", "if", "source", "is", "not", "None", ":", "out", "[", "'source'", "]", "=", "source", ".", "rstrip", "(", ")", "except", "Exception", ":", "pass", "if", "ds", "and", "source", "is", "None", ":", "out", "[", "'docstring'", "]", "=", "ds", "# Constructor docstring for classes", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "out", "[", "'isclass'", "]", "=", "True", "# reconstruct the function definition and print it:", "try", ":", "obj_init", "=", "obj", ".", "__init__", "except", "AttributeError", ":", "init_def", "=", "init_ds", "=", "None", "else", ":", "init_def", "=", "self", ".", "_getdef", "(", "obj_init", ",", "oname", ")", "init_ds", "=", "getdoc", "(", "obj_init", ")", "# Skip Python's auto-generated docstrings", "if", "init_ds", "and", "init_ds", ".", "startswith", "(", "'x.__init__(...) initializes'", ")", ":", "init_ds", "=", "None", "if", "init_def", "or", "init_ds", ":", "if", "init_def", ":", "out", "[", "'init_definition'", "]", "=", "self", ".", "format", "(", "init_def", ")", "if", "init_ds", ":", "out", "[", "'init_docstring'", "]", "=", "init_ds", "# and class docstring for instances:", "else", ":", "# First, check whether the instance docstring is identical to the", "# class one, and print it separately if they don't coincide. In", "# most cases they will, but it's nice to print all the info for", "# objects which use instance-customized docstrings.", "if", "ds", ":", "try", ":", "cls", "=", "getattr", "(", "obj", ",", "'__class__'", ")", "except", ":", "class_ds", "=", "None", "else", ":", "class_ds", "=", "getdoc", "(", "cls", ")", "# Skip Python's auto-generated docstrings", "if", "class_ds", "and", "(", "class_ds", ".", "startswith", "(", "'function(code, globals[,'", ")", "or", "class_ds", ".", "startswith", "(", "'instancemethod(function, instance,'", ")", "or", "class_ds", ".", "startswith", "(", "'module(name[,'", ")", ")", ":", "class_ds", "=", "None", "if", "class_ds", "and", "ds", "!=", "class_ds", ":", "out", "[", "'class_docstring'", "]", "=", "class_ds", "# Next, try to show constructor docstrings", "try", ":", "init_ds", "=", "getdoc", "(", "obj", ".", "__init__", ")", "# Skip Python's auto-generated docstrings", "if", "init_ds", "and", "init_ds", ".", "startswith", "(", "'x.__init__(...) initializes'", ")", ":", "init_ds", "=", "None", "except", "AttributeError", ":", "init_ds", "=", "None", "if", "init_ds", ":", "out", "[", "'init_docstring'", "]", "=", "init_ds", "# Call form docstring for callable instances", "if", "hasattr", "(", "obj", ",", "'__call__'", ")", ":", "call_def", "=", "self", ".", "_getdef", "(", "obj", ".", "__call__", ",", "oname", ")", "if", "call_def", "is", "not", "None", ":", "out", "[", "'call_def'", "]", "=", "self", ".", "format", "(", "call_def", ")", "call_ds", "=", "getdoc", "(", "obj", ".", "__call__", ")", "# Skip Python's auto-generated docstrings", "if", "call_ds", "and", "call_ds", ".", "startswith", "(", "'x.__call__(...) <==> x(...)'", ")", ":", "call_ds", "=", "None", "if", "call_ds", ":", "out", "[", "'call_docstring'", "]", "=", "call_ds", "# Compute the object's argspec as a callable. The key is to decide", "# whether to pull it from the object itself, from its __init__ or", "# from its __call__ method.", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "# Old-style classes need not have an __init__", "callable_obj", "=", "getattr", "(", "obj", ",", "\"__init__\"", ",", "None", ")", "elif", "callable", "(", "obj", ")", ":", "callable_obj", "=", "obj", "else", ":", "callable_obj", "=", "None", "if", "callable_obj", ":", "try", ":", "args", ",", "varargs", ",", "varkw", ",", "defaults", "=", "getargspec", "(", "callable_obj", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "# For extensions/builtins we can't retrieve the argspec", "pass", "else", ":", "out", "[", "'argspec'", "]", "=", "dict", "(", "args", "=", "args", ",", "varargs", "=", "varargs", ",", "varkw", "=", "varkw", ",", "defaults", "=", "defaults", ")", "return", "object_info", "(", "*", "*", "out", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Inspector.psearch
Search namespaces with wildcards for objects. Arguments: - pattern: string containing shell-like wildcards to use in namespace searches and optionally a type specification to narrow the search to objects of that type. - ns_table: dict of name->namespaces for search. Optional arguments: - ns_search: list of namespace names to include in search. - ignore_case(False): make the search case-insensitive. - show_all(False): show all names, including those starting with underscores.
environment/lib/python2.7/site-packages/IPython/core/oinspect.py
def psearch(self,pattern,ns_table,ns_search=[], ignore_case=False,show_all=False): """Search namespaces with wildcards for objects. Arguments: - pattern: string containing shell-like wildcards to use in namespace searches and optionally a type specification to narrow the search to objects of that type. - ns_table: dict of name->namespaces for search. Optional arguments: - ns_search: list of namespace names to include in search. - ignore_case(False): make the search case-insensitive. - show_all(False): show all names, including those starting with underscores. """ #print 'ps pattern:<%r>' % pattern # dbg # defaults type_pattern = 'all' filter = '' cmds = pattern.split() len_cmds = len(cmds) if len_cmds == 1: # Only filter pattern given filter = cmds[0] elif len_cmds == 2: # Both filter and type specified filter,type_pattern = cmds else: raise ValueError('invalid argument string for psearch: <%s>' % pattern) # filter search namespaces for name in ns_search: if name not in ns_table: raise ValueError('invalid namespace <%s>. Valid names: %s' % (name,ns_table.keys())) #print 'type_pattern:',type_pattern # dbg search_result, namespaces_seen = set(), set() for ns_name in ns_search: ns = ns_table[ns_name] # Normally, locals and globals are the same, so we just check one. if id(ns) in namespaces_seen: continue namespaces_seen.add(id(ns)) tmp_res = list_namespace(ns, type_pattern, filter, ignore_case=ignore_case, show_all=show_all) search_result.update(tmp_res) page.page('\n'.join(sorted(search_result)))
def psearch(self,pattern,ns_table,ns_search=[], ignore_case=False,show_all=False): """Search namespaces with wildcards for objects. Arguments: - pattern: string containing shell-like wildcards to use in namespace searches and optionally a type specification to narrow the search to objects of that type. - ns_table: dict of name->namespaces for search. Optional arguments: - ns_search: list of namespace names to include in search. - ignore_case(False): make the search case-insensitive. - show_all(False): show all names, including those starting with underscores. """ #print 'ps pattern:<%r>' % pattern # dbg # defaults type_pattern = 'all' filter = '' cmds = pattern.split() len_cmds = len(cmds) if len_cmds == 1: # Only filter pattern given filter = cmds[0] elif len_cmds == 2: # Both filter and type specified filter,type_pattern = cmds else: raise ValueError('invalid argument string for psearch: <%s>' % pattern) # filter search namespaces for name in ns_search: if name not in ns_table: raise ValueError('invalid namespace <%s>. Valid names: %s' % (name,ns_table.keys())) #print 'type_pattern:',type_pattern # dbg search_result, namespaces_seen = set(), set() for ns_name in ns_search: ns = ns_table[ns_name] # Normally, locals and globals are the same, so we just check one. if id(ns) in namespaces_seen: continue namespaces_seen.add(id(ns)) tmp_res = list_namespace(ns, type_pattern, filter, ignore_case=ignore_case, show_all=show_all) search_result.update(tmp_res) page.page('\n'.join(sorted(search_result)))
[ "Search", "namespaces", "with", "wildcards", "for", "objects", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/oinspect.py#L784-L841
[ "def", "psearch", "(", "self", ",", "pattern", ",", "ns_table", ",", "ns_search", "=", "[", "]", ",", "ignore_case", "=", "False", ",", "show_all", "=", "False", ")", ":", "#print 'ps pattern:<%r>' % pattern # dbg", "# defaults", "type_pattern", "=", "'all'", "filter", "=", "''", "cmds", "=", "pattern", ".", "split", "(", ")", "len_cmds", "=", "len", "(", "cmds", ")", "if", "len_cmds", "==", "1", ":", "# Only filter pattern given", "filter", "=", "cmds", "[", "0", "]", "elif", "len_cmds", "==", "2", ":", "# Both filter and type specified", "filter", ",", "type_pattern", "=", "cmds", "else", ":", "raise", "ValueError", "(", "'invalid argument string for psearch: <%s>'", "%", "pattern", ")", "# filter search namespaces", "for", "name", "in", "ns_search", ":", "if", "name", "not", "in", "ns_table", ":", "raise", "ValueError", "(", "'invalid namespace <%s>. Valid names: %s'", "%", "(", "name", ",", "ns_table", ".", "keys", "(", ")", ")", ")", "#print 'type_pattern:',type_pattern # dbg", "search_result", ",", "namespaces_seen", "=", "set", "(", ")", ",", "set", "(", ")", "for", "ns_name", "in", "ns_search", ":", "ns", "=", "ns_table", "[", "ns_name", "]", "# Normally, locals and globals are the same, so we just check one.", "if", "id", "(", "ns", ")", "in", "namespaces_seen", ":", "continue", "namespaces_seen", ".", "add", "(", "id", "(", "ns", ")", ")", "tmp_res", "=", "list_namespace", "(", "ns", ",", "type_pattern", ",", "filter", ",", "ignore_case", "=", "ignore_case", ",", "show_all", "=", "show_all", ")", "search_result", ".", "update", "(", "tmp_res", ")", "page", ".", "page", "(", "'\\n'", ".", "join", "(", "sorted", "(", "search_result", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
threaded_reactor
Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done.
environment/lib/python2.7/site-packages/nose/twistedtools.py
def threaded_reactor(): """ Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done. """ global _twisted_thread try: from twisted.internet import reactor except ImportError: return None, None if not _twisted_thread: from twisted.python import threadable from threading import Thread _twisted_thread = Thread(target=lambda: reactor.run( \ installSignalHandlers=False)) _twisted_thread.setDaemon(True) _twisted_thread.start() return reactor, _twisted_thread
def threaded_reactor(): """ Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done. """ global _twisted_thread try: from twisted.internet import reactor except ImportError: return None, None if not _twisted_thread: from twisted.python import threadable from threading import Thread _twisted_thread = Thread(target=lambda: reactor.run( \ installSignalHandlers=False)) _twisted_thread.setDaemon(True) _twisted_thread.start() return reactor, _twisted_thread
[ "Start", "the", "Twisted", "reactor", "in", "a", "separate", "thread", "if", "not", "already", "done", ".", "Returns", "the", "reactor", ".", "The", "thread", "will", "automatically", "be", "destroyed", "when", "all", "the", "tests", "are", "done", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/twistedtools.py#L42-L60
[ "def", "threaded_reactor", "(", ")", ":", "global", "_twisted_thread", "try", ":", "from", "twisted", ".", "internet", "import", "reactor", "except", "ImportError", ":", "return", "None", ",", "None", "if", "not", "_twisted_thread", ":", "from", "twisted", ".", "python", "import", "threadable", "from", "threading", "import", "Thread", "_twisted_thread", "=", "Thread", "(", "target", "=", "lambda", ":", "reactor", ".", "run", "(", "installSignalHandlers", "=", "False", ")", ")", "_twisted_thread", ".", "setDaemon", "(", "True", ")", "_twisted_thread", ".", "start", "(", ")", "return", "reactor", ",", "_twisted_thread" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
stop_reactor
Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using twisted.trial.
environment/lib/python2.7/site-packages/nose/twistedtools.py
def stop_reactor(): """Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using twisted.trial. """ global _twisted_thread def stop_reactor(): '''Helper for calling stop from withing the thread.''' reactor.stop() reactor.callFromThread(stop_reactor) reactor_thread.join() for p in reactor.getDelayedCalls(): if p.active(): p.cancel() _twisted_thread = None
def stop_reactor(): """Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using twisted.trial. """ global _twisted_thread def stop_reactor(): '''Helper for calling stop from withing the thread.''' reactor.stop() reactor.callFromThread(stop_reactor) reactor_thread.join() for p in reactor.getDelayedCalls(): if p.active(): p.cancel() _twisted_thread = None
[ "Stop", "the", "reactor", "and", "join", "the", "reactor", "thread", "until", "it", "stops", ".", "Call", "this", "function", "in", "teardown", "at", "the", "module", "or", "package", "level", "to", "reset", "the", "twisted", "system", "after", "your", "tests", ".", "You", "*", "must", "*", "do", "this", "if", "you", "mix", "tests", "using", "these", "tools", "and", "tests", "using", "twisted", ".", "trial", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/twistedtools.py#L66-L83
[ "def", "stop_reactor", "(", ")", ":", "global", "_twisted_thread", "def", "stop_reactor", "(", ")", ":", "'''Helper for calling stop from withing the thread.'''", "reactor", ".", "stop", "(", ")", "reactor", ".", "callFromThread", "(", "stop_reactor", ")", "reactor_thread", ".", "join", "(", ")", "for", "p", "in", "reactor", ".", "getDelayedCalls", "(", ")", ":", "if", "p", ".", "active", "(", ")", ":", "p", ".", "cancel", "(", ")", "_twisted_thread", "=", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
deferred
By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with timed() is that timed() will still wait for the test to end, while deferred() will stop the test when its timeout has expired. The latter is more desireable when dealing with network tests, because the result may actually never arrive. If the callback is triggered, the test has passed. If the errback is triggered or the timeout expires, the test has failed. Example:: @deferred(timeout=5.0) def test_resolve(): return reactor.resolve("www.python.org") Attention! If you combine this decorator with other decorators (like "raises"), deferred() must be called *first*! In other words, this is good:: @raises(DNSLookupError) @deferred() def test_error(): return reactor.resolve("xxxjhjhj.biz") and this is bad:: @deferred() @raises(DNSLookupError) def test_error(): return reactor.resolve("xxxjhjhj.biz")
environment/lib/python2.7/site-packages/nose/twistedtools.py
def deferred(timeout=None): """ By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with timed() is that timed() will still wait for the test to end, while deferred() will stop the test when its timeout has expired. The latter is more desireable when dealing with network tests, because the result may actually never arrive. If the callback is triggered, the test has passed. If the errback is triggered or the timeout expires, the test has failed. Example:: @deferred(timeout=5.0) def test_resolve(): return reactor.resolve("www.python.org") Attention! If you combine this decorator with other decorators (like "raises"), deferred() must be called *first*! In other words, this is good:: @raises(DNSLookupError) @deferred() def test_error(): return reactor.resolve("xxxjhjhj.biz") and this is bad:: @deferred() @raises(DNSLookupError) def test_error(): return reactor.resolve("xxxjhjhj.biz") """ reactor, reactor_thread = threaded_reactor() if reactor is None: raise ImportError("twisted is not available or could not be imported") # Check for common syntax mistake # (otherwise, tests can be silently ignored # if one writes "@deferred" instead of "@deferred()") try: timeout is None or timeout + 0 except TypeError: raise TypeError("'timeout' argument must be a number or None") def decorate(func): def wrapper(*args, **kargs): q = Queue() def callback(value): q.put(None) def errback(failure): # Retrieve and save full exception info try: failure.raiseException() except: q.put(sys.exc_info()) def g(): try: d = func(*args, **kargs) try: d.addCallbacks(callback, errback) # Check for a common mistake and display a nice error # message except AttributeError: raise TypeError("you must return a twisted Deferred " "from your test case!") # Catch exceptions raised in the test body (from the # Twisted thread) except: q.put(sys.exc_info()) reactor.callFromThread(g) try: error = q.get(timeout=timeout) except Empty: raise TimeExpired("timeout expired before end of test (%f s.)" % timeout) # Re-raise all exceptions if error is not None: exc_type, exc_value, tb = error raise exc_type, exc_value, tb wrapper = make_decorator(func)(wrapper) return wrapper return decorate
def deferred(timeout=None): """ By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with timed() is that timed() will still wait for the test to end, while deferred() will stop the test when its timeout has expired. The latter is more desireable when dealing with network tests, because the result may actually never arrive. If the callback is triggered, the test has passed. If the errback is triggered or the timeout expires, the test has failed. Example:: @deferred(timeout=5.0) def test_resolve(): return reactor.resolve("www.python.org") Attention! If you combine this decorator with other decorators (like "raises"), deferred() must be called *first*! In other words, this is good:: @raises(DNSLookupError) @deferred() def test_error(): return reactor.resolve("xxxjhjhj.biz") and this is bad:: @deferred() @raises(DNSLookupError) def test_error(): return reactor.resolve("xxxjhjhj.biz") """ reactor, reactor_thread = threaded_reactor() if reactor is None: raise ImportError("twisted is not available or could not be imported") # Check for common syntax mistake # (otherwise, tests can be silently ignored # if one writes "@deferred" instead of "@deferred()") try: timeout is None or timeout + 0 except TypeError: raise TypeError("'timeout' argument must be a number or None") def decorate(func): def wrapper(*args, **kargs): q = Queue() def callback(value): q.put(None) def errback(failure): # Retrieve and save full exception info try: failure.raiseException() except: q.put(sys.exc_info()) def g(): try: d = func(*args, **kargs) try: d.addCallbacks(callback, errback) # Check for a common mistake and display a nice error # message except AttributeError: raise TypeError("you must return a twisted Deferred " "from your test case!") # Catch exceptions raised in the test body (from the # Twisted thread) except: q.put(sys.exc_info()) reactor.callFromThread(g) try: error = q.get(timeout=timeout) except Empty: raise TimeExpired("timeout expired before end of test (%f s.)" % timeout) # Re-raise all exceptions if error is not None: exc_type, exc_value, tb = error raise exc_type, exc_value, tb wrapper = make_decorator(func)(wrapper) return wrapper return decorate
[ "By", "wrapping", "a", "test", "function", "with", "this", "decorator", "you", "can", "return", "a", "twisted", "Deferred", "and", "the", "test", "will", "wait", "for", "the", "deferred", "to", "be", "triggered", ".", "The", "whole", "test", "function", "will", "run", "inside", "the", "Twisted", "event", "loop", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/twistedtools.py#L86-L172
[ "def", "deferred", "(", "timeout", "=", "None", ")", ":", "reactor", ",", "reactor_thread", "=", "threaded_reactor", "(", ")", "if", "reactor", "is", "None", ":", "raise", "ImportError", "(", "\"twisted is not available or could not be imported\"", ")", "# Check for common syntax mistake", "# (otherwise, tests can be silently ignored", "# if one writes \"@deferred\" instead of \"@deferred()\")", "try", ":", "timeout", "is", "None", "or", "timeout", "+", "0", "except", "TypeError", ":", "raise", "TypeError", "(", "\"'timeout' argument must be a number or None\"", ")", "def", "decorate", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kargs", ")", ":", "q", "=", "Queue", "(", ")", "def", "callback", "(", "value", ")", ":", "q", ".", "put", "(", "None", ")", "def", "errback", "(", "failure", ")", ":", "# Retrieve and save full exception info", "try", ":", "failure", ".", "raiseException", "(", ")", "except", ":", "q", ".", "put", "(", "sys", ".", "exc_info", "(", ")", ")", "def", "g", "(", ")", ":", "try", ":", "d", "=", "func", "(", "*", "args", ",", "*", "*", "kargs", ")", "try", ":", "d", ".", "addCallbacks", "(", "callback", ",", "errback", ")", "# Check for a common mistake and display a nice error", "# message", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"you must return a twisted Deferred \"", "\"from your test case!\"", ")", "# Catch exceptions raised in the test body (from the", "# Twisted thread)", "except", ":", "q", ".", "put", "(", "sys", ".", "exc_info", "(", ")", ")", "reactor", ".", "callFromThread", "(", "g", ")", "try", ":", "error", "=", "q", ".", "get", "(", "timeout", "=", "timeout", ")", "except", "Empty", ":", "raise", "TimeExpired", "(", "\"timeout expired before end of test (%f s.)\"", "%", "timeout", ")", "# Re-raise all exceptions", "if", "error", "is", "not", "None", ":", "exc_type", ",", "exc_value", ",", "tb", "=", "error", "raise", "exc_type", ",", "exc_value", ",", "tb", "wrapper", "=", "make_decorator", "(", "func", ")", "(", "wrapper", ")", "return", "wrapper", "return", "decorate" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_best_string
Return best matching substring of corpus. Parameters ---------- query : str corpus : str step : int Step size of first match-value scan through corpus. Can be thought of as a sort of "scan resolution". Should not exceed length of query. flex : int Max. left/right substring position adjustment value. Should not exceed length of query / 2. Outputs ------- output0 : str Best matching substring. output1 : float Match ratio of best matching substring. 1 is perfect match.
src/find_best_string/main.py
def find_best_string(query, corpus, step=4, flex=3, case_sensitive=False): """Return best matching substring of corpus. Parameters ---------- query : str corpus : str step : int Step size of first match-value scan through corpus. Can be thought of as a sort of "scan resolution". Should not exceed length of query. flex : int Max. left/right substring position adjustment value. Should not exceed length of query / 2. Outputs ------- output0 : str Best matching substring. output1 : float Match ratio of best matching substring. 1 is perfect match. """ def ratio(a, b): """Compact alias for SequenceMatcher.""" return SequenceMatcher(None, a, b).ratio() def scan_corpus(step): """Return list of match values from corpus-wide scan.""" match_values = [] m = 0 while m + qlen - step <= len(corpus): match_values.append(ratio(query, corpus[m : m-1+qlen])) m += step return match_values def index_max(v): """Return index of max value.""" return max(range(len(v)), key=v.__getitem__) def adjust_left_right_positions(): """Return left/right positions for best string match.""" # bp_* is synonym for 'Best Position Left/Right' and are adjusted # to optimize bmv_* p_l, bp_l = [pos] * 2 p_r, bp_r = [pos + qlen] * 2 # bmv_* are declared here in case they are untouched in optimization bmv_l = match_values[round_decimal(p_l / step)] bmv_r = match_values[round_decimal(p_r / step)] for f in range(flex): ll = ratio(query, corpus[p_l - f: p_r]) if ll > bmv_l: bmv_l = ll bp_l = p_l - f lr = ratio(query, corpus[p_l + f: p_r]) if lr > bmv_l: bmv_l = lr bp_l = p_l + f rl = ratio(query, corpus[p_l: p_r - f]) if rl > bmv_r: bmv_r = rl bp_r = p_r - f rr = ratio(query, corpus[p_l: p_r + f]) if rr > bmv_r: bmv_r = rr bp_r = p_r + f return bp_l, bp_r, ratio(query, corpus[bp_l : bp_r]) if not case_sensitive: query = query.lower() corpus = corpus.lower() qlen = len(query) if flex >= qlen/2: print("Warning: flex exceeds length of query / 2. Setting to default.") flex = 3 match_values = scan_corpus(step) pos = index_max(match_values) * step pos_left, pos_right, match_value = adjust_left_right_positions() return corpus[pos_left: pos_right].strip(), match_value
def find_best_string(query, corpus, step=4, flex=3, case_sensitive=False): """Return best matching substring of corpus. Parameters ---------- query : str corpus : str step : int Step size of first match-value scan through corpus. Can be thought of as a sort of "scan resolution". Should not exceed length of query. flex : int Max. left/right substring position adjustment value. Should not exceed length of query / 2. Outputs ------- output0 : str Best matching substring. output1 : float Match ratio of best matching substring. 1 is perfect match. """ def ratio(a, b): """Compact alias for SequenceMatcher.""" return SequenceMatcher(None, a, b).ratio() def scan_corpus(step): """Return list of match values from corpus-wide scan.""" match_values = [] m = 0 while m + qlen - step <= len(corpus): match_values.append(ratio(query, corpus[m : m-1+qlen])) m += step return match_values def index_max(v): """Return index of max value.""" return max(range(len(v)), key=v.__getitem__) def adjust_left_right_positions(): """Return left/right positions for best string match.""" # bp_* is synonym for 'Best Position Left/Right' and are adjusted # to optimize bmv_* p_l, bp_l = [pos] * 2 p_r, bp_r = [pos + qlen] * 2 # bmv_* are declared here in case they are untouched in optimization bmv_l = match_values[round_decimal(p_l / step)] bmv_r = match_values[round_decimal(p_r / step)] for f in range(flex): ll = ratio(query, corpus[p_l - f: p_r]) if ll > bmv_l: bmv_l = ll bp_l = p_l - f lr = ratio(query, corpus[p_l + f: p_r]) if lr > bmv_l: bmv_l = lr bp_l = p_l + f rl = ratio(query, corpus[p_l: p_r - f]) if rl > bmv_r: bmv_r = rl bp_r = p_r - f rr = ratio(query, corpus[p_l: p_r + f]) if rr > bmv_r: bmv_r = rr bp_r = p_r + f return bp_l, bp_r, ratio(query, corpus[bp_l : bp_r]) if not case_sensitive: query = query.lower() corpus = corpus.lower() qlen = len(query) if flex >= qlen/2: print("Warning: flex exceeds length of query / 2. Setting to default.") flex = 3 match_values = scan_corpus(step) pos = index_max(match_values) * step pos_left, pos_right, match_value = adjust_left_right_positions() return corpus[pos_left: pos_right].strip(), match_value
[ "Return", "best", "matching", "substring", "of", "corpus", "." ]
alexseitsinger/find_best_string
python
https://github.com/alexseitsinger/find_best_string/blob/833499113d9c560c91fe4761921a4d5717939ae7/src/find_best_string/main.py#L8-L101
[ "def", "find_best_string", "(", "query", ",", "corpus", ",", "step", "=", "4", ",", "flex", "=", "3", ",", "case_sensitive", "=", "False", ")", ":", "def", "ratio", "(", "a", ",", "b", ")", ":", "\"\"\"Compact alias for SequenceMatcher.\"\"\"", "return", "SequenceMatcher", "(", "None", ",", "a", ",", "b", ")", ".", "ratio", "(", ")", "def", "scan_corpus", "(", "step", ")", ":", "\"\"\"Return list of match values from corpus-wide scan.\"\"\"", "match_values", "=", "[", "]", "m", "=", "0", "while", "m", "+", "qlen", "-", "step", "<=", "len", "(", "corpus", ")", ":", "match_values", ".", "append", "(", "ratio", "(", "query", ",", "corpus", "[", "m", ":", "m", "-", "1", "+", "qlen", "]", ")", ")", "m", "+=", "step", "return", "match_values", "def", "index_max", "(", "v", ")", ":", "\"\"\"Return index of max value.\"\"\"", "return", "max", "(", "range", "(", "len", "(", "v", ")", ")", ",", "key", "=", "v", ".", "__getitem__", ")", "def", "adjust_left_right_positions", "(", ")", ":", "\"\"\"Return left/right positions for best string match.\"\"\"", "# bp_* is synonym for 'Best Position Left/Right' and are adjusted", "# to optimize bmv_*", "p_l", ",", "bp_l", "=", "[", "pos", "]", "*", "2", "p_r", ",", "bp_r", "=", "[", "pos", "+", "qlen", "]", "*", "2", "# bmv_* are declared here in case they are untouched in optimization", "bmv_l", "=", "match_values", "[", "round_decimal", "(", "p_l", "/", "step", ")", "]", "bmv_r", "=", "match_values", "[", "round_decimal", "(", "p_r", "/", "step", ")", "]", "for", "f", "in", "range", "(", "flex", ")", ":", "ll", "=", "ratio", "(", "query", ",", "corpus", "[", "p_l", "-", "f", ":", "p_r", "]", ")", "if", "ll", ">", "bmv_l", ":", "bmv_l", "=", "ll", "bp_l", "=", "p_l", "-", "f", "lr", "=", "ratio", "(", "query", ",", "corpus", "[", "p_l", "+", "f", ":", "p_r", "]", ")", "if", "lr", ">", "bmv_l", ":", "bmv_l", "=", "lr", "bp_l", "=", "p_l", "+", "f", "rl", "=", "ratio", "(", "query", ",", "corpus", "[", "p_l", ":", "p_r", "-", "f", "]", ")", "if", "rl", ">", "bmv_r", ":", "bmv_r", "=", "rl", "bp_r", "=", "p_r", "-", "f", "rr", "=", "ratio", "(", "query", ",", "corpus", "[", "p_l", ":", "p_r", "+", "f", "]", ")", "if", "rr", ">", "bmv_r", ":", "bmv_r", "=", "rr", "bp_r", "=", "p_r", "+", "f", "return", "bp_l", ",", "bp_r", ",", "ratio", "(", "query", ",", "corpus", "[", "bp_l", ":", "bp_r", "]", ")", "if", "not", "case_sensitive", ":", "query", "=", "query", ".", "lower", "(", ")", "corpus", "=", "corpus", ".", "lower", "(", ")", "qlen", "=", "len", "(", "query", ")", "if", "flex", ">=", "qlen", "/", "2", ":", "print", "(", "\"Warning: flex exceeds length of query / 2. Setting to default.\"", ")", "flex", "=", "3", "match_values", "=", "scan_corpus", "(", "step", ")", "pos", "=", "index_max", "(", "match_values", ")", "*", "step", "pos_left", ",", "pos_right", ",", "match_value", "=", "adjust_left_right_positions", "(", ")", "return", "corpus", "[", "pos_left", ":", "pos_right", "]", ".", "strip", "(", ")", ",", "match_value" ]
833499113d9c560c91fe4761921a4d5717939ae7
test
_singleton_method
Return a function to the `name` method on a singleton `coverage` object. The singleton object is created the first time one of these functions is called.
virtualEnvironment/lib/python2.7/site-packages/coverage/__init__.py
def _singleton_method(name): """Return a function to the `name` method on a singleton `coverage` object. The singleton object is created the first time one of these functions is called. """ # Disable pylint msg W0612, because a bunch of variables look unused, but # they're accessed via locals(). # pylint: disable=W0612 def wrapper(*args, **kwargs): """Singleton wrapper around a coverage method.""" global _the_coverage if not _the_coverage: _the_coverage = coverage(auto_data=True) return getattr(_the_coverage, name)(*args, **kwargs) import inspect meth = getattr(coverage, name) args, varargs, kw, defaults = inspect.getargspec(meth) argspec = inspect.formatargspec(args[1:], varargs, kw, defaults) docstring = meth.__doc__ wrapper.__doc__ = ("""\ A first-use-singleton wrapper around coverage.%(name)s. This wrapper is provided for backward compatibility with legacy code. New code should use coverage.%(name)s directly. %(name)s%(argspec)s: %(docstring)s """ % locals() ) return wrapper
def _singleton_method(name): """Return a function to the `name` method on a singleton `coverage` object. The singleton object is created the first time one of these functions is called. """ # Disable pylint msg W0612, because a bunch of variables look unused, but # they're accessed via locals(). # pylint: disable=W0612 def wrapper(*args, **kwargs): """Singleton wrapper around a coverage method.""" global _the_coverage if not _the_coverage: _the_coverage = coverage(auto_data=True) return getattr(_the_coverage, name)(*args, **kwargs) import inspect meth = getattr(coverage, name) args, varargs, kw, defaults = inspect.getargspec(meth) argspec = inspect.formatargspec(args[1:], varargs, kw, defaults) docstring = meth.__doc__ wrapper.__doc__ = ("""\ A first-use-singleton wrapper around coverage.%(name)s. This wrapper is provided for backward compatibility with legacy code. New code should use coverage.%(name)s directly. %(name)s%(argspec)s: %(docstring)s """ % locals() ) return wrapper
[ "Return", "a", "function", "to", "the", "name", "method", "on", "a", "singleton", "coverage", "object", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/__init__.py#L26-L61
[ "def", "_singleton_method", "(", "name", ")", ":", "# Disable pylint msg W0612, because a bunch of variables look unused, but", "# they're accessed via locals().", "# pylint: disable=W0612", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Singleton wrapper around a coverage method.\"\"\"", "global", "_the_coverage", "if", "not", "_the_coverage", ":", "_the_coverage", "=", "coverage", "(", "auto_data", "=", "True", ")", "return", "getattr", "(", "_the_coverage", ",", "name", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", "import", "inspect", "meth", "=", "getattr", "(", "coverage", ",", "name", ")", "args", ",", "varargs", ",", "kw", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "meth", ")", "argspec", "=", "inspect", ".", "formatargspec", "(", "args", "[", "1", ":", "]", ",", "varargs", ",", "kw", ",", "defaults", ")", "docstring", "=", "meth", ".", "__doc__", "wrapper", ".", "__doc__", "=", "(", "\"\"\"\\\n A first-use-singleton wrapper around coverage.%(name)s.\n\n This wrapper is provided for backward compatibility with legacy code.\n New code should use coverage.%(name)s directly.\n\n %(name)s%(argspec)s:\n\n %(docstring)s\n \"\"\"", "%", "locals", "(", ")", ")", "return", "wrapper" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
XMLEncoder.to_string
Encodes the stored ``data`` to XML and returns a ``string``. Setting ``indent`` to ``False`` will forego any pretty-printing and return a condensed value. Setting ``declaration`` to ``False`` will skip inserting the XML declaration.
exemelopy/__init__.py
def to_string(self, indent=True, declaration=True): """Encodes the stored ``data`` to XML and returns a ``string``. Setting ``indent`` to ``False`` will forego any pretty-printing and return a condensed value. Setting ``declaration`` to ``False`` will skip inserting the XML declaration. """ return etree.tostring(self.to_xml(), encoding=self.encoding, xml_declaration=declaration, pretty_print=indent )
def to_string(self, indent=True, declaration=True): """Encodes the stored ``data`` to XML and returns a ``string``. Setting ``indent`` to ``False`` will forego any pretty-printing and return a condensed value. Setting ``declaration`` to ``False`` will skip inserting the XML declaration. """ return etree.tostring(self.to_xml(), encoding=self.encoding, xml_declaration=declaration, pretty_print=indent )
[ "Encodes", "the", "stored", "data", "to", "XML", "and", "returns", "a", "string", "." ]
OldhamMade/exemelopy
python
https://github.com/OldhamMade/exemelopy/blob/5f5141b169e61a5b6912146a995917f5d862ee9c/exemelopy/__init__.py#L52-L66
[ "def", "to_string", "(", "self", ",", "indent", "=", "True", ",", "declaration", "=", "True", ")", ":", "return", "etree", ".", "tostring", "(", "self", ".", "to_xml", "(", ")", ",", "encoding", "=", "self", ".", "encoding", ",", "xml_declaration", "=", "declaration", ",", "pretty_print", "=", "indent", ")" ]
5f5141b169e61a5b6912146a995917f5d862ee9c
test
XMLEncoder.to_xml
Encodes the stored ``data`` to XML and returns an ``lxml.etree`` value.
exemelopy/__init__.py
def to_xml(self): """Encodes the stored ``data`` to XML and returns an ``lxml.etree`` value. """ if self.data: self.document = self._update_document(self.document, self.data) return self.document
def to_xml(self): """Encodes the stored ``data`` to XML and returns an ``lxml.etree`` value. """ if self.data: self.document = self._update_document(self.document, self.data) return self.document
[ "Encodes", "the", "stored", "data", "to", "XML", "and", "returns", "an", "lxml", ".", "etree", "value", "." ]
OldhamMade/exemelopy
python
https://github.com/OldhamMade/exemelopy/blob/5f5141b169e61a5b6912146a995917f5d862ee9c/exemelopy/__init__.py#L68-L75
[ "def", "to_xml", "(", "self", ")", ":", "if", "self", ".", "data", ":", "self", ".", "document", "=", "self", ".", "_update_document", "(", "self", ".", "document", ",", "self", ".", "data", ")", "return", "self", ".", "document" ]
5f5141b169e61a5b6912146a995917f5d862ee9c
test
load_all_modules_in_packages
Recursively loads all modules from a package object, or set of package objects :param package_or_set_of_packages: package object, or iterable of package objects :return: list of all unique modules discovered by the function
module_discovery_utils/module_discovery_utils.py
def load_all_modules_in_packages(package_or_set_of_packages): """ Recursively loads all modules from a package object, or set of package objects :param package_or_set_of_packages: package object, or iterable of package objects :return: list of all unique modules discovered by the function """ if isinstance(package_or_set_of_packages, types.ModuleType): packages = [package_or_set_of_packages] elif isinstance(package_or_set_of_packages, Iterable) and not isinstance(package_or_set_of_packages, (dict, str)): packages = package_or_set_of_packages else: raise Exception("This function only accepts a module reference, or an iterable of said objects") imported = packages.copy() for package in packages: if not hasattr(package, '__path__'): raise Exception( 'Package object passed in has no __path__ attribute. ' 'Make sure to pass in imported references to the packages in question.' ) for module_finder, name, ispkg in pkgutil.walk_packages(package.__path__): module_name = '{}.{}'.format(package.__name__, name) current_module = importlib.import_module(module_name) imported.append(current_module) if ispkg: imported += load_all_modules_in_packages(current_module) for module in imported: # This is to cover cases where simply importing a module doesn't execute all the code/definitions within # I don't totally understand the reasons for this, but I do know enumerating a module's context (like with dir) # seems to solve things dir(module) return list( { module.__name__: module for module in imported }.values() )
def load_all_modules_in_packages(package_or_set_of_packages): """ Recursively loads all modules from a package object, or set of package objects :param package_or_set_of_packages: package object, or iterable of package objects :return: list of all unique modules discovered by the function """ if isinstance(package_or_set_of_packages, types.ModuleType): packages = [package_or_set_of_packages] elif isinstance(package_or_set_of_packages, Iterable) and not isinstance(package_or_set_of_packages, (dict, str)): packages = package_or_set_of_packages else: raise Exception("This function only accepts a module reference, or an iterable of said objects") imported = packages.copy() for package in packages: if not hasattr(package, '__path__'): raise Exception( 'Package object passed in has no __path__ attribute. ' 'Make sure to pass in imported references to the packages in question.' ) for module_finder, name, ispkg in pkgutil.walk_packages(package.__path__): module_name = '{}.{}'.format(package.__name__, name) current_module = importlib.import_module(module_name) imported.append(current_module) if ispkg: imported += load_all_modules_in_packages(current_module) for module in imported: # This is to cover cases where simply importing a module doesn't execute all the code/definitions within # I don't totally understand the reasons for this, but I do know enumerating a module's context (like with dir) # seems to solve things dir(module) return list( { module.__name__: module for module in imported }.values() )
[ "Recursively", "loads", "all", "modules", "from", "a", "package", "object", "or", "set", "of", "package", "objects" ]
zsennenga/module-discovery-utils
python
https://github.com/zsennenga/module-discovery-utils/blob/146d31051915f2347483fff9549eb272bd6b7d45/module_discovery_utils/module_discovery_utils.py#L8-L50
[ "def", "load_all_modules_in_packages", "(", "package_or_set_of_packages", ")", ":", "if", "isinstance", "(", "package_or_set_of_packages", ",", "types", ".", "ModuleType", ")", ":", "packages", "=", "[", "package_or_set_of_packages", "]", "elif", "isinstance", "(", "package_or_set_of_packages", ",", "Iterable", ")", "and", "not", "isinstance", "(", "package_or_set_of_packages", ",", "(", "dict", ",", "str", ")", ")", ":", "packages", "=", "package_or_set_of_packages", "else", ":", "raise", "Exception", "(", "\"This function only accepts a module reference, or an iterable of said objects\"", ")", "imported", "=", "packages", ".", "copy", "(", ")", "for", "package", "in", "packages", ":", "if", "not", "hasattr", "(", "package", ",", "'__path__'", ")", ":", "raise", "Exception", "(", "'Package object passed in has no __path__ attribute. '", "'Make sure to pass in imported references to the packages in question.'", ")", "for", "module_finder", ",", "name", ",", "ispkg", "in", "pkgutil", ".", "walk_packages", "(", "package", ".", "__path__", ")", ":", "module_name", "=", "'{}.{}'", ".", "format", "(", "package", ".", "__name__", ",", "name", ")", "current_module", "=", "importlib", ".", "import_module", "(", "module_name", ")", "imported", ".", "append", "(", "current_module", ")", "if", "ispkg", ":", "imported", "+=", "load_all_modules_in_packages", "(", "current_module", ")", "for", "module", "in", "imported", ":", "# This is to cover cases where simply importing a module doesn't execute all the code/definitions within", "# I don't totally understand the reasons for this, but I do know enumerating a module's context (like with dir)", "# seems to solve things", "dir", "(", "module", ")", "return", "list", "(", "{", "module", ".", "__name__", ":", "module", "for", "module", "in", "imported", "}", ".", "values", "(", ")", ")" ]
146d31051915f2347483fff9549eb272bd6b7d45
test
Struct.__dict_invert
Helper function for merge. Takes a dictionary whose values are lists and returns a dict with the elements of each list as keys and the original keys as values.
environment/lib/python2.7/site-packages/IPython/utils/ipstruct.py
def __dict_invert(self, data): """Helper function for merge. Takes a dictionary whose values are lists and returns a dict with the elements of each list as keys and the original keys as values. """ outdict = {} for k,lst in data.items(): if isinstance(lst, str): lst = lst.split() for entry in lst: outdict[entry] = k return outdict
def __dict_invert(self, data): """Helper function for merge. Takes a dictionary whose values are lists and returns a dict with the elements of each list as keys and the original keys as values. """ outdict = {} for k,lst in data.items(): if isinstance(lst, str): lst = lst.split() for entry in lst: outdict[entry] = k return outdict
[ "Helper", "function", "for", "merge", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/ipstruct.py#L219-L231
[ "def", "__dict_invert", "(", "self", ",", "data", ")", ":", "outdict", "=", "{", "}", "for", "k", ",", "lst", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "lst", ",", "str", ")", ":", "lst", "=", "lst", ".", "split", "(", ")", "for", "entry", "in", "lst", ":", "outdict", "[", "entry", "]", "=", "k", "return", "outdict" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Struct.merge
Merge two Structs with customizable conflict resolution. This is similar to :meth:`update`, but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional dictionary 'conflict' is used to decide what to do. If conflict is not given, the default behavior is to preserve any keys with their current value (the opposite of the :meth:`update` method's behavior). Parameters ---------- __loc_data : dict, Struct The data to merge into self __conflict_solve : dict The conflict policy dict. The keys are binary functions used to resolve the conflict and the values are lists of strings naming the keys the conflict resolution function applies to. Instead of a list of strings a space separated string can be used, like 'a b c'. kw : dict Additional key, value pairs to merge in Notes ----- The `__conflict_solve` dict is a dictionary of binary functions which will be used to solve key conflicts. Here is an example:: __conflict_solve = dict( func1=['a','b','c'], func2=['d','e'] ) In this case, the function :func:`func1` will be used to resolve keys 'a', 'b' and 'c' and the function :func:`func2` will be used for keys 'd' and 'e'. This could also be written as:: __conflict_solve = dict(func1='a b c',func2='d e') These functions will be called for each key they apply to with the form:: func1(self['a'], other['a']) The return value is used as the final merged value. As a convenience, merge() provides five (the most commonly needed) pre-defined policies: preserve, update, add, add_flip and add_s. The easiest explanation is their implementation:: preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # only for str! You can use those four words (as strings) as keys instead of defining them as functions, and the merge method will substitute the appropriate functions for you. For more complicated conflict resolution policies, you still need to construct your own functions. Examples -------- This show the default policy: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s.merge(s2) >>> sorted(s.items()) [('a', 10), ('b', 30), ('c', 40)] Now, show how to specify a conflict dict: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,b=40) >>> conflict = {'update':'a','add':'b'} >>> s.merge(s2,conflict) >>> sorted(s.items()) [('a', 20), ('b', 70)]
environment/lib/python2.7/site-packages/IPython/utils/ipstruct.py
def merge(self, __loc_data__=None, __conflict_solve=None, **kw): """Merge two Structs with customizable conflict resolution. This is similar to :meth:`update`, but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional dictionary 'conflict' is used to decide what to do. If conflict is not given, the default behavior is to preserve any keys with their current value (the opposite of the :meth:`update` method's behavior). Parameters ---------- __loc_data : dict, Struct The data to merge into self __conflict_solve : dict The conflict policy dict. The keys are binary functions used to resolve the conflict and the values are lists of strings naming the keys the conflict resolution function applies to. Instead of a list of strings a space separated string can be used, like 'a b c'. kw : dict Additional key, value pairs to merge in Notes ----- The `__conflict_solve` dict is a dictionary of binary functions which will be used to solve key conflicts. Here is an example:: __conflict_solve = dict( func1=['a','b','c'], func2=['d','e'] ) In this case, the function :func:`func1` will be used to resolve keys 'a', 'b' and 'c' and the function :func:`func2` will be used for keys 'd' and 'e'. This could also be written as:: __conflict_solve = dict(func1='a b c',func2='d e') These functions will be called for each key they apply to with the form:: func1(self['a'], other['a']) The return value is used as the final merged value. As a convenience, merge() provides five (the most commonly needed) pre-defined policies: preserve, update, add, add_flip and add_s. The easiest explanation is their implementation:: preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # only for str! You can use those four words (as strings) as keys instead of defining them as functions, and the merge method will substitute the appropriate functions for you. For more complicated conflict resolution policies, you still need to construct your own functions. Examples -------- This show the default policy: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s.merge(s2) >>> sorted(s.items()) [('a', 10), ('b', 30), ('c', 40)] Now, show how to specify a conflict dict: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,b=40) >>> conflict = {'update':'a','add':'b'} >>> s.merge(s2,conflict) >>> sorted(s.items()) [('a', 20), ('b', 70)] """ data_dict = dict(__loc_data__,**kw) # policies for conflict resolution: two argument functions which return # the value that will go in the new struct preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # default policy is to keep current keys when there's a conflict conflict_solve = list2dict2(self.keys(), default = preserve) # the conflict_solve dictionary is given by the user 'inverted': we # need a name-function mapping, it comes as a function -> names # dict. Make a local copy (b/c we'll make changes), replace user # strings for the three builtin policies and invert it. if __conflict_solve: inv_conflict_solve_user = __conflict_solve.copy() for name, func in [('preserve',preserve), ('update',update), ('add',add), ('add_flip',add_flip), ('add_s',add_s)]: if name in inv_conflict_solve_user.keys(): inv_conflict_solve_user[func] = inv_conflict_solve_user[name] del inv_conflict_solve_user[name] conflict_solve.update(self.__dict_invert(inv_conflict_solve_user)) for key in data_dict: if key not in self: self[key] = data_dict[key] else: self[key] = conflict_solve[key](self[key],data_dict[key])
def merge(self, __loc_data__=None, __conflict_solve=None, **kw): """Merge two Structs with customizable conflict resolution. This is similar to :meth:`update`, but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional dictionary 'conflict' is used to decide what to do. If conflict is not given, the default behavior is to preserve any keys with their current value (the opposite of the :meth:`update` method's behavior). Parameters ---------- __loc_data : dict, Struct The data to merge into self __conflict_solve : dict The conflict policy dict. The keys are binary functions used to resolve the conflict and the values are lists of strings naming the keys the conflict resolution function applies to. Instead of a list of strings a space separated string can be used, like 'a b c'. kw : dict Additional key, value pairs to merge in Notes ----- The `__conflict_solve` dict is a dictionary of binary functions which will be used to solve key conflicts. Here is an example:: __conflict_solve = dict( func1=['a','b','c'], func2=['d','e'] ) In this case, the function :func:`func1` will be used to resolve keys 'a', 'b' and 'c' and the function :func:`func2` will be used for keys 'd' and 'e'. This could also be written as:: __conflict_solve = dict(func1='a b c',func2='d e') These functions will be called for each key they apply to with the form:: func1(self['a'], other['a']) The return value is used as the final merged value. As a convenience, merge() provides five (the most commonly needed) pre-defined policies: preserve, update, add, add_flip and add_s. The easiest explanation is their implementation:: preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # only for str! You can use those four words (as strings) as keys instead of defining them as functions, and the merge method will substitute the appropriate functions for you. For more complicated conflict resolution policies, you still need to construct your own functions. Examples -------- This show the default policy: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s.merge(s2) >>> sorted(s.items()) [('a', 10), ('b', 30), ('c', 40)] Now, show how to specify a conflict dict: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,b=40) >>> conflict = {'update':'a','add':'b'} >>> s.merge(s2,conflict) >>> sorted(s.items()) [('a', 20), ('b', 70)] """ data_dict = dict(__loc_data__,**kw) # policies for conflict resolution: two argument functions which return # the value that will go in the new struct preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # default policy is to keep current keys when there's a conflict conflict_solve = list2dict2(self.keys(), default = preserve) # the conflict_solve dictionary is given by the user 'inverted': we # need a name-function mapping, it comes as a function -> names # dict. Make a local copy (b/c we'll make changes), replace user # strings for the three builtin policies and invert it. if __conflict_solve: inv_conflict_solve_user = __conflict_solve.copy() for name, func in [('preserve',preserve), ('update',update), ('add',add), ('add_flip',add_flip), ('add_s',add_s)]: if name in inv_conflict_solve_user.keys(): inv_conflict_solve_user[func] = inv_conflict_solve_user[name] del inv_conflict_solve_user[name] conflict_solve.update(self.__dict_invert(inv_conflict_solve_user)) for key in data_dict: if key not in self: self[key] = data_dict[key] else: self[key] = conflict_solve[key](self[key],data_dict[key])
[ "Merge", "two", "Structs", "with", "customizable", "conflict", "resolution", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/ipstruct.py#L275-L392
[ "def", "merge", "(", "self", ",", "__loc_data__", "=", "None", ",", "__conflict_solve", "=", "None", ",", "*", "*", "kw", ")", ":", "data_dict", "=", "dict", "(", "__loc_data__", ",", "*", "*", "kw", ")", "# policies for conflict resolution: two argument functions which return", "# the value that will go in the new struct", "preserve", "=", "lambda", "old", ",", "new", ":", "old", "update", "=", "lambda", "old", ",", "new", ":", "new", "add", "=", "lambda", "old", ",", "new", ":", "old", "+", "new", "add_flip", "=", "lambda", "old", ",", "new", ":", "new", "+", "old", "# note change of order!", "add_s", "=", "lambda", "old", ",", "new", ":", "old", "+", "' '", "+", "new", "# default policy is to keep current keys when there's a conflict", "conflict_solve", "=", "list2dict2", "(", "self", ".", "keys", "(", ")", ",", "default", "=", "preserve", ")", "# the conflict_solve dictionary is given by the user 'inverted': we", "# need a name-function mapping, it comes as a function -> names", "# dict. Make a local copy (b/c we'll make changes), replace user", "# strings for the three builtin policies and invert it.", "if", "__conflict_solve", ":", "inv_conflict_solve_user", "=", "__conflict_solve", ".", "copy", "(", ")", "for", "name", ",", "func", "in", "[", "(", "'preserve'", ",", "preserve", ")", ",", "(", "'update'", ",", "update", ")", ",", "(", "'add'", ",", "add", ")", ",", "(", "'add_flip'", ",", "add_flip", ")", ",", "(", "'add_s'", ",", "add_s", ")", "]", ":", "if", "name", "in", "inv_conflict_solve_user", ".", "keys", "(", ")", ":", "inv_conflict_solve_user", "[", "func", "]", "=", "inv_conflict_solve_user", "[", "name", "]", "del", "inv_conflict_solve_user", "[", "name", "]", "conflict_solve", ".", "update", "(", "self", ".", "__dict_invert", "(", "inv_conflict_solve_user", ")", ")", "for", "key", "in", "data_dict", ":", "if", "key", "not", "in", "self", ":", "self", "[", "key", "]", "=", "data_dict", "[", "key", "]", "else", ":", "self", "[", "key", "]", "=", "conflict_solve", "[", "key", "]", "(", "self", "[", "key", "]", ",", "data_dict", "[", "key", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
fullvars
like `vars()` but support `__slots__`.
jasily/data/fullvars.py
def fullvars(obj): ''' like `vars()` but support `__slots__`. ''' try: return vars(obj) except TypeError: pass # __slots__ slotsnames = set() for cls in type(obj).__mro__: __slots__ = getattr(cls, '__slots__', None) if __slots__: if isinstance(__slots__, str): slotsnames.add(__slots__) else: slotsnames.update(__slots__) return _SlotsProxy(obj, slotsnames)
def fullvars(obj): ''' like `vars()` but support `__slots__`. ''' try: return vars(obj) except TypeError: pass # __slots__ slotsnames = set() for cls in type(obj).__mro__: __slots__ = getattr(cls, '__slots__', None) if __slots__: if isinstance(__slots__, str): slotsnames.add(__slots__) else: slotsnames.update(__slots__) return _SlotsProxy(obj, slotsnames)
[ "like", "vars", "()", "but", "support", "__slots__", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/data/fullvars.py#L32-L51
[ "def", "fullvars", "(", "obj", ")", ":", "try", ":", "return", "vars", "(", "obj", ")", "except", "TypeError", ":", "pass", "# __slots__", "slotsnames", "=", "set", "(", ")", "for", "cls", "in", "type", "(", "obj", ")", ".", "__mro__", ":", "__slots__", "=", "getattr", "(", "cls", ",", "'__slots__'", ",", "None", ")", "if", "__slots__", ":", "if", "isinstance", "(", "__slots__", ",", "str", ")", ":", "slotsnames", ".", "add", "(", "__slots__", ")", "else", ":", "slotsnames", ".", "update", "(", "__slots__", ")", "return", "_SlotsProxy", "(", "obj", ",", "slotsnames", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
object_to_primitive
convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None
jasily/format/utils.py
def object_to_primitive(obj): ''' convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ''' if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isinstance(obj, (list, frozenset, set)): return [object_to_primitive(x) for x in obj] if isinstance(obj, dict): return dict([(object_to_primitive(k), object_to_primitive(v)) for k, v in obj.items()]) data = vars(obj) assert isinstance(data, dict) return object_to_primitive(data)
def object_to_primitive(obj): ''' convert object to primitive type so we can serialize it to data format like python. all primitive types: dict, list, int, float, bool, str, None ''' if obj is None: return obj if isinstance(obj, (int, float, bool, str)): return obj if isinstance(obj, (list, frozenset, set)): return [object_to_primitive(x) for x in obj] if isinstance(obj, dict): return dict([(object_to_primitive(k), object_to_primitive(v)) for k, v in obj.items()]) data = vars(obj) assert isinstance(data, dict) return object_to_primitive(data)
[ "convert", "object", "to", "primitive", "type", "so", "we", "can", "serialize", "it", "to", "data", "format", "like", "python", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/format/utils.py#L9-L29
[ "def", "object_to_primitive", "(", "obj", ")", ":", "if", "obj", "is", "None", ":", "return", "obj", "if", "isinstance", "(", "obj", ",", "(", "int", ",", "float", ",", "bool", ",", "str", ")", ")", ":", "return", "obj", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "frozenset", ",", "set", ")", ")", ":", "return", "[", "object_to_primitive", "(", "x", ")", "for", "x", "in", "obj", "]", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "dict", "(", "[", "(", "object_to_primitive", "(", "k", ")", ",", "object_to_primitive", "(", "v", ")", ")", "for", "k", ",", "v", "in", "obj", ".", "items", "(", ")", "]", ")", "data", "=", "vars", "(", "obj", ")", "assert", "isinstance", "(", "data", ",", "dict", ")", "return", "object_to_primitive", "(", "data", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
main
Run as a command-line script: colorize a python file or stdin using ANSI color escapes and print to stdout. Inputs: - argv(None): a list of strings like sys.argv[1:] giving the command-line arguments. If None, use sys.argv[1:].
environment/lib/python2.7/site-packages/IPython/utils/PyColorize.py
def main(argv=None): """Run as a command-line script: colorize a python file or stdin using ANSI color escapes and print to stdout. Inputs: - argv(None): a list of strings like sys.argv[1:] giving the command-line arguments. If None, use sys.argv[1:]. """ usage_msg = """%prog [options] [filename] Colorize a python file or stdin using ANSI color escapes and print to stdout. If no filename is given, or if filename is -, read standard input.""" parser = optparse.OptionParser(usage=usage_msg) newopt = parser.add_option newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store', choices=['Linux','LightBG','NoColor'],default=_scheme_default, help="give the color scheme to use. Currently only 'Linux'\ (default) and 'LightBG' and 'NoColor' are implemented (give without\ quotes)") opts,args = parser.parse_args(argv) if len(args) > 1: parser.error("you must give at most one filename.") if len(args) == 0: fname = '-' # no filename given; setup to read from stdin else: fname = args[0] if fname == '-': stream = sys.stdin else: try: stream = open(fname) except IOError,msg: print >> sys.stderr, msg sys.exit(1) parser = Parser() # we need nested try blocks because pre-2.5 python doesn't support unified # try-except-finally try: try: # write colorized version to stdout parser.format(stream.read(),scheme=opts.scheme_name) except IOError,msg: # if user reads through a pager and quits, don't print traceback if msg.args != (32,'Broken pipe'): raise finally: if stream is not sys.stdin: stream.close()
def main(argv=None): """Run as a command-line script: colorize a python file or stdin using ANSI color escapes and print to stdout. Inputs: - argv(None): a list of strings like sys.argv[1:] giving the command-line arguments. If None, use sys.argv[1:]. """ usage_msg = """%prog [options] [filename] Colorize a python file or stdin using ANSI color escapes and print to stdout. If no filename is given, or if filename is -, read standard input.""" parser = optparse.OptionParser(usage=usage_msg) newopt = parser.add_option newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store', choices=['Linux','LightBG','NoColor'],default=_scheme_default, help="give the color scheme to use. Currently only 'Linux'\ (default) and 'LightBG' and 'NoColor' are implemented (give without\ quotes)") opts,args = parser.parse_args(argv) if len(args) > 1: parser.error("you must give at most one filename.") if len(args) == 0: fname = '-' # no filename given; setup to read from stdin else: fname = args[0] if fname == '-': stream = sys.stdin else: try: stream = open(fname) except IOError,msg: print >> sys.stderr, msg sys.exit(1) parser = Parser() # we need nested try blocks because pre-2.5 python doesn't support unified # try-except-finally try: try: # write colorized version to stdout parser.format(stream.read(),scheme=opts.scheme_name) except IOError,msg: # if user reads through a pager and quits, don't print traceback if msg.args != (32,'Broken pipe'): raise finally: if stream is not sys.stdin: stream.close()
[ "Run", "as", "a", "command", "-", "line", "script", ":", "colorize", "a", "python", "file", "or", "stdin", "using", "ANSI", "color", "escapes", "and", "print", "to", "stdout", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/PyColorize.py#L247-L303
[ "def", "main", "(", "argv", "=", "None", ")", ":", "usage_msg", "=", "\"\"\"%prog [options] [filename]\n\nColorize a python file or stdin using ANSI color escapes and print to stdout.\nIf no filename is given, or if filename is -, read standard input.\"\"\"", "parser", "=", "optparse", ".", "OptionParser", "(", "usage", "=", "usage_msg", ")", "newopt", "=", "parser", ".", "add_option", "newopt", "(", "'-s'", ",", "'--scheme'", ",", "metavar", "=", "'NAME'", ",", "dest", "=", "'scheme_name'", ",", "action", "=", "'store'", ",", "choices", "=", "[", "'Linux'", ",", "'LightBG'", ",", "'NoColor'", "]", ",", "default", "=", "_scheme_default", ",", "help", "=", "\"give the color scheme to use. Currently only 'Linux'\\\n (default) and 'LightBG' and 'NoColor' are implemented (give without\\\n quotes)\"", ")", "opts", ",", "args", "=", "parser", ".", "parse_args", "(", "argv", ")", "if", "len", "(", "args", ")", ">", "1", ":", "parser", ".", "error", "(", "\"you must give at most one filename.\"", ")", "if", "len", "(", "args", ")", "==", "0", ":", "fname", "=", "'-'", "# no filename given; setup to read from stdin", "else", ":", "fname", "=", "args", "[", "0", "]", "if", "fname", "==", "'-'", ":", "stream", "=", "sys", ".", "stdin", "else", ":", "try", ":", "stream", "=", "open", "(", "fname", ")", "except", "IOError", ",", "msg", ":", "print", ">>", "sys", ".", "stderr", ",", "msg", "sys", ".", "exit", "(", "1", ")", "parser", "=", "Parser", "(", ")", "# we need nested try blocks because pre-2.5 python doesn't support unified", "# try-except-finally", "try", ":", "try", ":", "# write colorized version to stdout", "parser", ".", "format", "(", "stream", ".", "read", "(", ")", ",", "scheme", "=", "opts", ".", "scheme_name", ")", "except", "IOError", ",", "msg", ":", "# if user reads through a pager and quits, don't print traceback", "if", "msg", ".", "args", "!=", "(", "32", ",", "'Broken pipe'", ")", ":", "raise", "finally", ":", "if", "stream", "is", "not", "sys", ".", "stdin", ":", "stream", ".", "close", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Parser.format2
Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string 'str' and the parser will automatically return the output in a string.
environment/lib/python2.7/site-packages/IPython/utils/PyColorize.py
def format2(self, raw, out = None, scheme = ''): """ Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string 'str' and the parser will automatically return the output in a string.""" string_output = 0 if out == 'str' or self.out == 'str' or \ isinstance(self.out,StringIO.StringIO): # XXX - I don't really like this state handling logic, but at this # point I don't want to make major changes, so adding the # isinstance() check is the simplest I can do to ensure correct # behavior. out_old = self.out self.out = StringIO.StringIO() string_output = 1 elif out is not None: self.out = out # Fast return of the unmodified input for NoColor scheme if scheme == 'NoColor': error = False self.out.write(raw) if string_output: return raw,error else: return None,error # local shorthands colors = self.color_table[scheme].colors self.colors = colors # put in object so __call__ sees it # Remove trailing whitespace and normalize tabs self.raw = raw.expandtabs().rstrip() # store line offsets in self.lines self.lines = [0, 0] pos = 0 raw_find = self.raw.find lines_append = self.lines.append while 1: pos = raw_find('\n', pos) + 1 if not pos: break lines_append(pos) lines_append(len(self.raw)) # parse the source and write it self.pos = 0 text = StringIO.StringIO(self.raw) error = False try: for atoken in generate_tokens(text.readline): self(*atoken) except tokenize.TokenError as ex: msg = ex.args[0] line = ex.args[1][0] self.out.write("%s\n\n*** ERROR: %s%s%s\n" % (colors[token.ERRORTOKEN], msg, self.raw[self.lines[line]:], colors.normal) ) error = True self.out.write(colors.normal+'\n') if string_output: output = self.out.getvalue() self.out = out_old return (output, error) return (None, error)
def format2(self, raw, out = None, scheme = ''): """ Parse and send the colored source. If out and scheme are not specified, the defaults (given to constructor) are used. out should be a file-type object. Optionally, out can be given as the string 'str' and the parser will automatically return the output in a string.""" string_output = 0 if out == 'str' or self.out == 'str' or \ isinstance(self.out,StringIO.StringIO): # XXX - I don't really like this state handling logic, but at this # point I don't want to make major changes, so adding the # isinstance() check is the simplest I can do to ensure correct # behavior. out_old = self.out self.out = StringIO.StringIO() string_output = 1 elif out is not None: self.out = out # Fast return of the unmodified input for NoColor scheme if scheme == 'NoColor': error = False self.out.write(raw) if string_output: return raw,error else: return None,error # local shorthands colors = self.color_table[scheme].colors self.colors = colors # put in object so __call__ sees it # Remove trailing whitespace and normalize tabs self.raw = raw.expandtabs().rstrip() # store line offsets in self.lines self.lines = [0, 0] pos = 0 raw_find = self.raw.find lines_append = self.lines.append while 1: pos = raw_find('\n', pos) + 1 if not pos: break lines_append(pos) lines_append(len(self.raw)) # parse the source and write it self.pos = 0 text = StringIO.StringIO(self.raw) error = False try: for atoken in generate_tokens(text.readline): self(*atoken) except tokenize.TokenError as ex: msg = ex.args[0] line = ex.args[1][0] self.out.write("%s\n\n*** ERROR: %s%s%s\n" % (colors[token.ERRORTOKEN], msg, self.raw[self.lines[line]:], colors.normal) ) error = True self.out.write(colors.normal+'\n') if string_output: output = self.out.getvalue() self.out = out_old return (output, error) return (None, error)
[ "Parse", "and", "send", "the", "colored", "source", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/PyColorize.py#L131-L203
[ "def", "format2", "(", "self", ",", "raw", ",", "out", "=", "None", ",", "scheme", "=", "''", ")", ":", "string_output", "=", "0", "if", "out", "==", "'str'", "or", "self", ".", "out", "==", "'str'", "or", "isinstance", "(", "self", ".", "out", ",", "StringIO", ".", "StringIO", ")", ":", "# XXX - I don't really like this state handling logic, but at this", "# point I don't want to make major changes, so adding the", "# isinstance() check is the simplest I can do to ensure correct", "# behavior.", "out_old", "=", "self", ".", "out", "self", ".", "out", "=", "StringIO", ".", "StringIO", "(", ")", "string_output", "=", "1", "elif", "out", "is", "not", "None", ":", "self", ".", "out", "=", "out", "# Fast return of the unmodified input for NoColor scheme", "if", "scheme", "==", "'NoColor'", ":", "error", "=", "False", "self", ".", "out", ".", "write", "(", "raw", ")", "if", "string_output", ":", "return", "raw", ",", "error", "else", ":", "return", "None", ",", "error", "# local shorthands", "colors", "=", "self", ".", "color_table", "[", "scheme", "]", ".", "colors", "self", ".", "colors", "=", "colors", "# put in object so __call__ sees it", "# Remove trailing whitespace and normalize tabs", "self", ".", "raw", "=", "raw", ".", "expandtabs", "(", ")", ".", "rstrip", "(", ")", "# store line offsets in self.lines", "self", ".", "lines", "=", "[", "0", ",", "0", "]", "pos", "=", "0", "raw_find", "=", "self", ".", "raw", ".", "find", "lines_append", "=", "self", ".", "lines", ".", "append", "while", "1", ":", "pos", "=", "raw_find", "(", "'\\n'", ",", "pos", ")", "+", "1", "if", "not", "pos", ":", "break", "lines_append", "(", "pos", ")", "lines_append", "(", "len", "(", "self", ".", "raw", ")", ")", "# parse the source and write it", "self", ".", "pos", "=", "0", "text", "=", "StringIO", ".", "StringIO", "(", "self", ".", "raw", ")", "error", "=", "False", "try", ":", "for", "atoken", "in", "generate_tokens", "(", "text", ".", "readline", ")", ":", "self", "(", "*", "atoken", ")", "except", "tokenize", ".", "TokenError", "as", "ex", ":", "msg", "=", "ex", ".", "args", "[", "0", "]", "line", "=", "ex", ".", "args", "[", "1", "]", "[", "0", "]", "self", ".", "out", ".", "write", "(", "\"%s\\n\\n*** ERROR: %s%s%s\\n\"", "%", "(", "colors", "[", "token", ".", "ERRORTOKEN", "]", ",", "msg", ",", "self", ".", "raw", "[", "self", ".", "lines", "[", "line", "]", ":", "]", ",", "colors", ".", "normal", ")", ")", "error", "=", "True", "self", ".", "out", ".", "write", "(", "colors", ".", "normal", "+", "'\\n'", ")", "if", "string_output", ":", "output", "=", "self", ".", "out", ".", "getvalue", "(", ")", "self", ".", "out", "=", "out_old", "return", "(", "output", ",", "error", ")", "return", "(", "None", ",", "error", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getfigs
Get a list of matplotlib figures by figure numbers. If no arguments are given, all available figures are returned. If the argument list contains references to invalid figures, a warning is printed but the function continues pasting further figures. Parameters ---------- figs : tuple A tuple of ints giving the figure numbers of the figures to return.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def getfigs(*fig_nums): """Get a list of matplotlib figures by figure numbers. If no arguments are given, all available figures are returned. If the argument list contains references to invalid figures, a warning is printed but the function continues pasting further figures. Parameters ---------- figs : tuple A tuple of ints giving the figure numbers of the figures to return. """ from matplotlib._pylab_helpers import Gcf if not fig_nums: fig_managers = Gcf.get_all_fig_managers() return [fm.canvas.figure for fm in fig_managers] else: figs = [] for num in fig_nums: f = Gcf.figs.get(num) if f is None: print('Warning: figure %s not available.' % num) else: figs.append(f.canvas.figure) return figs
def getfigs(*fig_nums): """Get a list of matplotlib figures by figure numbers. If no arguments are given, all available figures are returned. If the argument list contains references to invalid figures, a warning is printed but the function continues pasting further figures. Parameters ---------- figs : tuple A tuple of ints giving the figure numbers of the figures to return. """ from matplotlib._pylab_helpers import Gcf if not fig_nums: fig_managers = Gcf.get_all_fig_managers() return [fm.canvas.figure for fm in fig_managers] else: figs = [] for num in fig_nums: f = Gcf.figs.get(num) if f is None: print('Warning: figure %s not available.' % num) else: figs.append(f.canvas.figure) return figs
[ "Get", "a", "list", "of", "matplotlib", "figures", "by", "figure", "numbers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L53-L77
[ "def", "getfigs", "(", "*", "fig_nums", ")", ":", "from", "matplotlib", ".", "_pylab_helpers", "import", "Gcf", "if", "not", "fig_nums", ":", "fig_managers", "=", "Gcf", ".", "get_all_fig_managers", "(", ")", "return", "[", "fm", ".", "canvas", ".", "figure", "for", "fm", "in", "fig_managers", "]", "else", ":", "figs", "=", "[", "]", "for", "num", "in", "fig_nums", ":", "f", "=", "Gcf", ".", "figs", ".", "get", "(", "num", ")", "if", "f", "is", "None", ":", "print", "(", "'Warning: figure %s not available.'", "%", "num", ")", "else", ":", "figs", ".", "append", "(", "f", ".", "canvas", ".", "figure", ")", "return", "figs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
print_figure
Convert a figure to svg or png for inline display.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def print_figure(fig, fmt='png'): """Convert a figure to svg or png for inline display.""" # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return fc = fig.get_facecolor() ec = fig.get_edgecolor() fig.set_facecolor('white') fig.set_edgecolor('white') try: bytes_io = BytesIO() fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight') data = bytes_io.getvalue() finally: fig.set_facecolor(fc) fig.set_edgecolor(ec) return data
def print_figure(fig, fmt='png'): """Convert a figure to svg or png for inline display.""" # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return fc = fig.get_facecolor() ec = fig.get_edgecolor() fig.set_facecolor('white') fig.set_edgecolor('white') try: bytes_io = BytesIO() fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='tight') data = bytes_io.getvalue() finally: fig.set_facecolor(fc) fig.set_edgecolor(ec) return data
[ "Convert", "a", "figure", "to", "svg", "or", "png", "for", "inline", "display", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L91-L109
[ "def", "print_figure", "(", "fig", ",", "fmt", "=", "'png'", ")", ":", "# When there's an empty figure, we shouldn't return anything, otherwise we", "# get big blank areas in the qt console.", "if", "not", "fig", ".", "axes", "and", "not", "fig", ".", "lines", ":", "return", "fc", "=", "fig", ".", "get_facecolor", "(", ")", "ec", "=", "fig", ".", "get_edgecolor", "(", ")", "fig", ".", "set_facecolor", "(", "'white'", ")", "fig", ".", "set_edgecolor", "(", "'white'", ")", "try", ":", "bytes_io", "=", "BytesIO", "(", ")", "fig", ".", "canvas", ".", "print_figure", "(", "bytes_io", ",", "format", "=", "fmt", ",", "bbox_inches", "=", "'tight'", ")", "data", "=", "bytes_io", ".", "getvalue", "(", ")", "finally", ":", "fig", ".", "set_facecolor", "(", "fc", ")", "fig", ".", "set_edgecolor", "(", "ec", ")", "return", "data" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
mpl_runner
Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. """ def mpl_execfile(fname,*where,**kw): """matplotlib-aware wrapper around safe_execfile. Its interface is identical to that of the :func:`execfile` builtin. This is ultimately a call to execfile(), but wrapped in safeties to properly handle interactive rendering.""" import matplotlib import matplotlib.pylab as pylab #print '*** Matplotlib runner ***' # dbg # turn off rendering until end of script is_interactive = matplotlib.rcParams['interactive'] matplotlib.interactive(False) safe_execfile(fname,*where,**kw) matplotlib.interactive(is_interactive) # make rendering call now, if the user tried to do it if pylab.draw_if_interactive.called: pylab.draw() pylab.draw_if_interactive.called = False return mpl_execfile
def mpl_runner(safe_execfile): """Factory to return a matplotlib-enabled runner for %run. Parameters ---------- safe_execfile : function This must be a function with the same interface as the :meth:`safe_execfile` method of IPython. Returns ------- A function suitable for use as the ``runner`` argument of the %run magic function. """ def mpl_execfile(fname,*where,**kw): """matplotlib-aware wrapper around safe_execfile. Its interface is identical to that of the :func:`execfile` builtin. This is ultimately a call to execfile(), but wrapped in safeties to properly handle interactive rendering.""" import matplotlib import matplotlib.pylab as pylab #print '*** Matplotlib runner ***' # dbg # turn off rendering until end of script is_interactive = matplotlib.rcParams['interactive'] matplotlib.interactive(False) safe_execfile(fname,*where,**kw) matplotlib.interactive(is_interactive) # make rendering call now, if the user tried to do it if pylab.draw_if_interactive.called: pylab.draw() pylab.draw_if_interactive.called = False return mpl_execfile
[ "Factory", "to", "return", "a", "matplotlib", "-", "enabled", "runner", "for", "%run", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L114-L151
[ "def", "mpl_runner", "(", "safe_execfile", ")", ":", "def", "mpl_execfile", "(", "fname", ",", "*", "where", ",", "*", "*", "kw", ")", ":", "\"\"\"matplotlib-aware wrapper around safe_execfile.\n\n Its interface is identical to that of the :func:`execfile` builtin.\n\n This is ultimately a call to execfile(), but wrapped in safeties to\n properly handle interactive rendering.\"\"\"", "import", "matplotlib", "import", "matplotlib", ".", "pylab", "as", "pylab", "#print '*** Matplotlib runner ***' # dbg", "# turn off rendering until end of script", "is_interactive", "=", "matplotlib", ".", "rcParams", "[", "'interactive'", "]", "matplotlib", ".", "interactive", "(", "False", ")", "safe_execfile", "(", "fname", ",", "*", "where", ",", "*", "*", "kw", ")", "matplotlib", ".", "interactive", "(", "is_interactive", ")", "# make rendering call now, if the user tried to do it", "if", "pylab", ".", "draw_if_interactive", ".", "called", ":", "pylab", ".", "draw", "(", ")", "pylab", ".", "draw_if_interactive", ".", "called", "=", "False", "return", "mpl_execfile" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
select_figure_format
Select figure format for inline backend, either 'png' or 'svg'. Using this method ensures only one figure format is active at a time.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def select_figure_format(shell, fmt): """Select figure format for inline backend, either 'png' or 'svg'. Using this method ensures only one figure format is active at a time. """ from matplotlib.figure import Figure from IPython.zmq.pylab import backend_inline svg_formatter = shell.display_formatter.formatters['image/svg+xml'] png_formatter = shell.display_formatter.formatters['image/png'] if fmt=='png': svg_formatter.type_printers.pop(Figure, None) png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png')) elif fmt=='svg': png_formatter.type_printers.pop(Figure, None) svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg')) else: raise ValueError("supported formats are: 'png', 'svg', not %r"%fmt) # set the format to be used in the backend() backend_inline._figure_format = fmt
def select_figure_format(shell, fmt): """Select figure format for inline backend, either 'png' or 'svg'. Using this method ensures only one figure format is active at a time. """ from matplotlib.figure import Figure from IPython.zmq.pylab import backend_inline svg_formatter = shell.display_formatter.formatters['image/svg+xml'] png_formatter = shell.display_formatter.formatters['image/png'] if fmt=='png': svg_formatter.type_printers.pop(Figure, None) png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png')) elif fmt=='svg': png_formatter.type_printers.pop(Figure, None) svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg')) else: raise ValueError("supported formats are: 'png', 'svg', not %r"%fmt) # set the format to be used in the backend() backend_inline._figure_format = fmt
[ "Select", "figure", "format", "for", "inline", "backend", "either", "png", "or", "svg", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L154-L175
[ "def", "select_figure_format", "(", "shell", ",", "fmt", ")", ":", "from", "matplotlib", ".", "figure", "import", "Figure", "from", "IPython", ".", "zmq", ".", "pylab", "import", "backend_inline", "svg_formatter", "=", "shell", ".", "display_formatter", ".", "formatters", "[", "'image/svg+xml'", "]", "png_formatter", "=", "shell", ".", "display_formatter", ".", "formatters", "[", "'image/png'", "]", "if", "fmt", "==", "'png'", ":", "svg_formatter", ".", "type_printers", ".", "pop", "(", "Figure", ",", "None", ")", "png_formatter", ".", "for_type", "(", "Figure", ",", "lambda", "fig", ":", "print_figure", "(", "fig", ",", "'png'", ")", ")", "elif", "fmt", "==", "'svg'", ":", "png_formatter", ".", "type_printers", ".", "pop", "(", "Figure", ",", "None", ")", "svg_formatter", ".", "for_type", "(", "Figure", ",", "lambda", "fig", ":", "print_figure", "(", "fig", ",", "'svg'", ")", ")", "else", ":", "raise", "ValueError", "(", "\"supported formats are: 'png', 'svg', not %r\"", "%", "fmt", ")", "# set the format to be used in the backend()", "backend_inline", ".", "_figure_format", "=", "fmt" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_gui_and_backend
Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def find_gui_and_backend(gui=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). """ import matplotlib if gui and gui != 'auto': # select backend based on requested gui backend = backends[gui] else: backend = matplotlib.rcParams['backend'] # In this case, we need to find what the appropriate gui selection call # should be for IPython, so we can activate inputhook accordingly gui = backend2gui.get(backend, None) return gui, backend
def find_gui_and_backend(gui=None): """Given a gui string return the gui and mpl backend. Parameters ---------- gui : str Can be one of ('tk','gtk','wx','qt','qt4','inline'). Returns ------- A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). """ import matplotlib if gui and gui != 'auto': # select backend based on requested gui backend = backends[gui] else: backend = matplotlib.rcParams['backend'] # In this case, we need to find what the appropriate gui selection call # should be for IPython, so we can activate inputhook accordingly gui = backend2gui.get(backend, None) return gui, backend
[ "Given", "a", "gui", "string", "return", "the", "gui", "and", "mpl", "backend", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L182-L206
[ "def", "find_gui_and_backend", "(", "gui", "=", "None", ")", ":", "import", "matplotlib", "if", "gui", "and", "gui", "!=", "'auto'", ":", "# select backend based on requested gui", "backend", "=", "backends", "[", "gui", "]", "else", ":", "backend", "=", "matplotlib", ".", "rcParams", "[", "'backend'", "]", "# In this case, we need to find what the appropriate gui selection call", "# should be for IPython, so we can activate inputhook accordingly", "gui", "=", "backend2gui", ".", "get", "(", "backend", ",", "None", ")", "return", "gui", ",", "backend" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
activate_matplotlib
Activate the given backend and set interactive to True.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib if backend.startswith('module://'): # Work around bug in matplotlib: matplotlib.use converts the # backend_id to lowercase even if a module name is specified! matplotlib.rcParams['backend'] = backend else: matplotlib.use(backend) matplotlib.interactive(True) # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made import matplotlib.pylab as pylab # XXX For now leave this commented out, but depending on discussions with # mpl-dev, we may be able to allow interactive switching... #import matplotlib.pyplot #matplotlib.pyplot.switch_backend(backend) pylab.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib if backend.startswith('module://'): # Work around bug in matplotlib: matplotlib.use converts the # backend_id to lowercase even if a module name is specified! matplotlib.rcParams['backend'] = backend else: matplotlib.use(backend) matplotlib.interactive(True) # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made import matplotlib.pylab as pylab # XXX For now leave this commented out, but depending on discussions with # mpl-dev, we may be able to allow interactive switching... #import matplotlib.pyplot #matplotlib.pyplot.switch_backend(backend) pylab.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
[ "Activate", "the", "given", "backend", "and", "set", "interactive", "to", "True", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L209-L233
[ "def", "activate_matplotlib", "(", "backend", ")", ":", "import", "matplotlib", "if", "backend", ".", "startswith", "(", "'module://'", ")", ":", "# Work around bug in matplotlib: matplotlib.use converts the", "# backend_id to lowercase even if a module name is specified!", "matplotlib", ".", "rcParams", "[", "'backend'", "]", "=", "backend", "else", ":", "matplotlib", ".", "use", "(", "backend", ")", "matplotlib", ".", "interactive", "(", "True", ")", "# This must be imported last in the matplotlib series, after", "# backend/interactivity choices have been made", "import", "matplotlib", ".", "pylab", "as", "pylab", "# XXX For now leave this commented out, but depending on discussions with", "# mpl-dev, we may be able to allow interactive switching...", "#import matplotlib.pyplot", "#matplotlib.pyplot.switch_backend(backend)", "pylab", ".", "show", ".", "_needmain", "=", "False", "# We need to detect at runtime whether show() is called by the user.", "# For this, we wrap it into a decorator which adds a 'called' flag.", "pylab", ".", "draw_if_interactive", "=", "flag_calls", "(", "pylab", ".", "draw_if_interactive", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
import_pylab
Import the standard pylab symbols into user_ns.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def import_pylab(user_ns, import_all=True): """Import the standard pylab symbols into user_ns.""" # Import numpy as np/pyplot as plt are conventions we're trying to # somewhat standardize on. Making them available to users by default # will greatly help this. s = ("import numpy\n" "import matplotlib\n" "from matplotlib import pylab, mlab, pyplot\n" "np = numpy\n" "plt = pyplot\n" ) exec s in user_ns if import_all: s = ("from matplotlib.pylab import *\n" "from numpy import *\n") exec s in user_ns
def import_pylab(user_ns, import_all=True): """Import the standard pylab symbols into user_ns.""" # Import numpy as np/pyplot as plt are conventions we're trying to # somewhat standardize on. Making them available to users by default # will greatly help this. s = ("import numpy\n" "import matplotlib\n" "from matplotlib import pylab, mlab, pyplot\n" "np = numpy\n" "plt = pyplot\n" ) exec s in user_ns if import_all: s = ("from matplotlib.pylab import *\n" "from numpy import *\n") exec s in user_ns
[ "Import", "the", "standard", "pylab", "symbols", "into", "user_ns", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L236-L253
[ "def", "import_pylab", "(", "user_ns", ",", "import_all", "=", "True", ")", ":", "# Import numpy as np/pyplot as plt are conventions we're trying to", "# somewhat standardize on. Making them available to users by default", "# will greatly help this.", "s", "=", "(", "\"import numpy\\n\"", "\"import matplotlib\\n\"", "\"from matplotlib import pylab, mlab, pyplot\\n\"", "\"np = numpy\\n\"", "\"plt = pyplot\\n\"", ")", "exec", "s", "in", "user_ns", "if", "import_all", ":", "s", "=", "(", "\"from matplotlib.pylab import *\\n\"", "\"from numpy import *\\n\"", ")", "exec", "s", "in", "user_ns" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
configure_inline_support
Configure an IPython shell object for matplotlib use. Parameters ---------- shell : InteractiveShell instance backend : matplotlib backend user_ns : dict A namespace where all configured variables will be placed. If not given, the `user_ns` attribute of the shell object is used.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def configure_inline_support(shell, backend, user_ns=None): """Configure an IPython shell object for matplotlib use. Parameters ---------- shell : InteractiveShell instance backend : matplotlib backend user_ns : dict A namespace where all configured variables will be placed. If not given, the `user_ns` attribute of the shell object is used. """ # If using our svg payload backend, register the post-execution # function that will pick up the results for display. This can only be # done with access to the real shell object. # Note: if we can't load the inline backend, then there's no point # continuing (such as in terminal-only shells in environments without # zeromq available). try: from IPython.zmq.pylab.backend_inline import InlineBackend except ImportError: return user_ns = shell.user_ns if user_ns is None else user_ns cfg = InlineBackend.instance(config=shell.config) cfg.shell = shell if cfg not in shell.configurables: shell.configurables.append(cfg) if backend == backends['inline']: from IPython.zmq.pylab.backend_inline import flush_figures from matplotlib import pyplot shell.register_post_execute(flush_figures) # load inline_rc pyplot.rcParams.update(cfg.rc) # Add 'figsize' to pyplot and to the user's namespace user_ns['figsize'] = pyplot.figsize = figsize # Setup the default figure format fmt = cfg.figure_format select_figure_format(shell, fmt) # The old pastefig function has been replaced by display from IPython.core.display import display # Add display and getfigs to the user's namespace user_ns['display'] = display user_ns['getfigs'] = getfigs
def configure_inline_support(shell, backend, user_ns=None): """Configure an IPython shell object for matplotlib use. Parameters ---------- shell : InteractiveShell instance backend : matplotlib backend user_ns : dict A namespace where all configured variables will be placed. If not given, the `user_ns` attribute of the shell object is used. """ # If using our svg payload backend, register the post-execution # function that will pick up the results for display. This can only be # done with access to the real shell object. # Note: if we can't load the inline backend, then there's no point # continuing (such as in terminal-only shells in environments without # zeromq available). try: from IPython.zmq.pylab.backend_inline import InlineBackend except ImportError: return user_ns = shell.user_ns if user_ns is None else user_ns cfg = InlineBackend.instance(config=shell.config) cfg.shell = shell if cfg not in shell.configurables: shell.configurables.append(cfg) if backend == backends['inline']: from IPython.zmq.pylab.backend_inline import flush_figures from matplotlib import pyplot shell.register_post_execute(flush_figures) # load inline_rc pyplot.rcParams.update(cfg.rc) # Add 'figsize' to pyplot and to the user's namespace user_ns['figsize'] = pyplot.figsize = figsize # Setup the default figure format fmt = cfg.figure_format select_figure_format(shell, fmt) # The old pastefig function has been replaced by display from IPython.core.display import display # Add display and getfigs to the user's namespace user_ns['display'] = display user_ns['getfigs'] = getfigs
[ "Configure", "an", "IPython", "shell", "object", "for", "matplotlib", "use", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L256-L305
[ "def", "configure_inline_support", "(", "shell", ",", "backend", ",", "user_ns", "=", "None", ")", ":", "# If using our svg payload backend, register the post-execution", "# function that will pick up the results for display. This can only be", "# done with access to the real shell object.", "# Note: if we can't load the inline backend, then there's no point", "# continuing (such as in terminal-only shells in environments without", "# zeromq available).", "try", ":", "from", "IPython", ".", "zmq", ".", "pylab", ".", "backend_inline", "import", "InlineBackend", "except", "ImportError", ":", "return", "user_ns", "=", "shell", ".", "user_ns", "if", "user_ns", "is", "None", "else", "user_ns", "cfg", "=", "InlineBackend", ".", "instance", "(", "config", "=", "shell", ".", "config", ")", "cfg", ".", "shell", "=", "shell", "if", "cfg", "not", "in", "shell", ".", "configurables", ":", "shell", ".", "configurables", ".", "append", "(", "cfg", ")", "if", "backend", "==", "backends", "[", "'inline'", "]", ":", "from", "IPython", ".", "zmq", ".", "pylab", ".", "backend_inline", "import", "flush_figures", "from", "matplotlib", "import", "pyplot", "shell", ".", "register_post_execute", "(", "flush_figures", ")", "# load inline_rc", "pyplot", ".", "rcParams", ".", "update", "(", "cfg", ".", "rc", ")", "# Add 'figsize' to pyplot and to the user's namespace", "user_ns", "[", "'figsize'", "]", "=", "pyplot", ".", "figsize", "=", "figsize", "# Setup the default figure format", "fmt", "=", "cfg", ".", "figure_format", "select_figure_format", "(", "shell", ",", "fmt", ")", "# The old pastefig function has been replaced by display", "from", "IPython", ".", "core", ".", "display", "import", "display", "# Add display and getfigs to the user's namespace", "user_ns", "[", "'display'", "]", "=", "display", "user_ns", "[", "'getfigs'", "]", "=", "getfigs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
pylab_activate
Activate pylab mode in the user's namespace. Loads and initializes numpy, matplotlib and friends for interactive use. Parameters ---------- user_ns : dict Namespace where the imports will occur. gui : optional, string A valid gui name following the conventions of the %gui magic. import_all : optional, boolean If true, an 'import *' is done from numpy and pylab. Returns ------- The actual gui used (if not given as input, it was obtained from matplotlib itself, and will be needed next to configure IPython's gui integration.
environment/lib/python2.7/site-packages/IPython/core/pylabtools.py
def pylab_activate(user_ns, gui=None, import_all=True, shell=None): """Activate pylab mode in the user's namespace. Loads and initializes numpy, matplotlib and friends for interactive use. Parameters ---------- user_ns : dict Namespace where the imports will occur. gui : optional, string A valid gui name following the conventions of the %gui magic. import_all : optional, boolean If true, an 'import *' is done from numpy and pylab. Returns ------- The actual gui used (if not given as input, it was obtained from matplotlib itself, and will be needed next to configure IPython's gui integration. """ gui, backend = find_gui_and_backend(gui) activate_matplotlib(backend) import_pylab(user_ns, import_all) if shell is not None: configure_inline_support(shell, backend, user_ns) print """ Welcome to pylab, a matplotlib-based Python environment [backend: %s]. For more information, type 'help(pylab)'.""" % backend # flush stdout, just to be safe sys.stdout.flush() return gui
def pylab_activate(user_ns, gui=None, import_all=True, shell=None): """Activate pylab mode in the user's namespace. Loads and initializes numpy, matplotlib and friends for interactive use. Parameters ---------- user_ns : dict Namespace where the imports will occur. gui : optional, string A valid gui name following the conventions of the %gui magic. import_all : optional, boolean If true, an 'import *' is done from numpy and pylab. Returns ------- The actual gui used (if not given as input, it was obtained from matplotlib itself, and will be needed next to configure IPython's gui integration. """ gui, backend = find_gui_and_backend(gui) activate_matplotlib(backend) import_pylab(user_ns, import_all) if shell is not None: configure_inline_support(shell, backend, user_ns) print """ Welcome to pylab, a matplotlib-based Python environment [backend: %s]. For more information, type 'help(pylab)'.""" % backend # flush stdout, just to be safe sys.stdout.flush() return gui
[ "Activate", "pylab", "mode", "in", "the", "user", "s", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/pylabtools.py#L308-L341
[ "def", "pylab_activate", "(", "user_ns", ",", "gui", "=", "None", ",", "import_all", "=", "True", ",", "shell", "=", "None", ")", ":", "gui", ",", "backend", "=", "find_gui_and_backend", "(", "gui", ")", "activate_matplotlib", "(", "backend", ")", "import_pylab", "(", "user_ns", ",", "import_all", ")", "if", "shell", "is", "not", "None", ":", "configure_inline_support", "(", "shell", ",", "backend", ",", "user_ns", ")", "print", "\"\"\"\nWelcome to pylab, a matplotlib-based Python environment [backend: %s].\nFor more information, type 'help(pylab)'.\"\"\"", "%", "backend", "# flush stdout, just to be safe", "sys", ".", "stdout", ".", "flush", "(", ")", "return", "gui" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PyTracer._trace
The trace function passed to sys.settrace.
virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py
def _trace(self, frame, event, arg_unused): """The trace function passed to sys.settrace.""" if self.stopped: return if 0: sys.stderr.write("trace event: %s %r @%d\n" % ( event, frame.f_code.co_filename, frame.f_lineno )) if self.last_exc_back: if frame == self.last_exc_back: # Someone forgot a return event. if self.arcs and self.cur_file_data: pair = (self.last_line, -self.last_exc_firstlineno) self.cur_file_data[pair] = None self.cur_file_data, self.last_line = self.data_stack.pop() self.last_exc_back = None if event == 'call': # Entering a new function context. Decide if we should trace # in this file. self.data_stack.append((self.cur_file_data, self.last_line)) filename = frame.f_code.co_filename if filename not in self.should_trace_cache: tracename = self.should_trace(filename, frame) self.should_trace_cache[filename] = tracename else: tracename = self.should_trace_cache[filename] #print("called, stack is %d deep, tracename is %r" % ( # len(self.data_stack), tracename)) if tracename: if tracename not in self.data: self.data[tracename] = {} self.cur_file_data = self.data[tracename] else: self.cur_file_data = None # Set the last_line to -1 because the next arc will be entering a # code block, indicated by (-1, n). self.last_line = -1 elif event == 'line': # Record an executed line. if self.cur_file_data is not None: if self.arcs: #print("lin", self.last_line, frame.f_lineno) self.cur_file_data[(self.last_line, frame.f_lineno)] = None else: #print("lin", frame.f_lineno) self.cur_file_data[frame.f_lineno] = None self.last_line = frame.f_lineno elif event == 'return': if self.arcs and self.cur_file_data: first = frame.f_code.co_firstlineno self.cur_file_data[(self.last_line, -first)] = None # Leaving this function, pop the filename stack. self.cur_file_data, self.last_line = self.data_stack.pop() #print("returned, stack is %d deep" % (len(self.data_stack))) elif event == 'exception': #print("exc", self.last_line, frame.f_lineno) self.last_exc_back = frame.f_back self.last_exc_firstlineno = frame.f_code.co_firstlineno return self._trace
def _trace(self, frame, event, arg_unused): """The trace function passed to sys.settrace.""" if self.stopped: return if 0: sys.stderr.write("trace event: %s %r @%d\n" % ( event, frame.f_code.co_filename, frame.f_lineno )) if self.last_exc_back: if frame == self.last_exc_back: # Someone forgot a return event. if self.arcs and self.cur_file_data: pair = (self.last_line, -self.last_exc_firstlineno) self.cur_file_data[pair] = None self.cur_file_data, self.last_line = self.data_stack.pop() self.last_exc_back = None if event == 'call': # Entering a new function context. Decide if we should trace # in this file. self.data_stack.append((self.cur_file_data, self.last_line)) filename = frame.f_code.co_filename if filename not in self.should_trace_cache: tracename = self.should_trace(filename, frame) self.should_trace_cache[filename] = tracename else: tracename = self.should_trace_cache[filename] #print("called, stack is %d deep, tracename is %r" % ( # len(self.data_stack), tracename)) if tracename: if tracename not in self.data: self.data[tracename] = {} self.cur_file_data = self.data[tracename] else: self.cur_file_data = None # Set the last_line to -1 because the next arc will be entering a # code block, indicated by (-1, n). self.last_line = -1 elif event == 'line': # Record an executed line. if self.cur_file_data is not None: if self.arcs: #print("lin", self.last_line, frame.f_lineno) self.cur_file_data[(self.last_line, frame.f_lineno)] = None else: #print("lin", frame.f_lineno) self.cur_file_data[frame.f_lineno] = None self.last_line = frame.f_lineno elif event == 'return': if self.arcs and self.cur_file_data: first = frame.f_code.co_firstlineno self.cur_file_data[(self.last_line, -first)] = None # Leaving this function, pop the filename stack. self.cur_file_data, self.last_line = self.data_stack.pop() #print("returned, stack is %d deep" % (len(self.data_stack))) elif event == 'exception': #print("exc", self.last_line, frame.f_lineno) self.last_exc_back = frame.f_back self.last_exc_firstlineno = frame.f_code.co_firstlineno return self._trace
[ "The", "trace", "function", "passed", "to", "sys", ".", "settrace", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py#L57-L119
[ "def", "_trace", "(", "self", ",", "frame", ",", "event", ",", "arg_unused", ")", ":", "if", "self", ".", "stopped", ":", "return", "if", "0", ":", "sys", ".", "stderr", ".", "write", "(", "\"trace event: %s %r @%d\\n\"", "%", "(", "event", ",", "frame", ".", "f_code", ".", "co_filename", ",", "frame", ".", "f_lineno", ")", ")", "if", "self", ".", "last_exc_back", ":", "if", "frame", "==", "self", ".", "last_exc_back", ":", "# Someone forgot a return event.", "if", "self", ".", "arcs", "and", "self", ".", "cur_file_data", ":", "pair", "=", "(", "self", ".", "last_line", ",", "-", "self", ".", "last_exc_firstlineno", ")", "self", ".", "cur_file_data", "[", "pair", "]", "=", "None", "self", ".", "cur_file_data", ",", "self", ".", "last_line", "=", "self", ".", "data_stack", ".", "pop", "(", ")", "self", ".", "last_exc_back", "=", "None", "if", "event", "==", "'call'", ":", "# Entering a new function context. Decide if we should trace", "# in this file.", "self", ".", "data_stack", ".", "append", "(", "(", "self", ".", "cur_file_data", ",", "self", ".", "last_line", ")", ")", "filename", "=", "frame", ".", "f_code", ".", "co_filename", "if", "filename", "not", "in", "self", ".", "should_trace_cache", ":", "tracename", "=", "self", ".", "should_trace", "(", "filename", ",", "frame", ")", "self", ".", "should_trace_cache", "[", "filename", "]", "=", "tracename", "else", ":", "tracename", "=", "self", ".", "should_trace_cache", "[", "filename", "]", "#print(\"called, stack is %d deep, tracename is %r\" % (", "# len(self.data_stack), tracename))", "if", "tracename", ":", "if", "tracename", "not", "in", "self", ".", "data", ":", "self", ".", "data", "[", "tracename", "]", "=", "{", "}", "self", ".", "cur_file_data", "=", "self", ".", "data", "[", "tracename", "]", "else", ":", "self", ".", "cur_file_data", "=", "None", "# Set the last_line to -1 because the next arc will be entering a", "# code block, indicated by (-1, n).", "self", ".", "last_line", "=", "-", "1", "elif", "event", "==", "'line'", ":", "# Record an executed line.", "if", "self", ".", "cur_file_data", "is", "not", "None", ":", "if", "self", ".", "arcs", ":", "#print(\"lin\", self.last_line, frame.f_lineno)", "self", ".", "cur_file_data", "[", "(", "self", ".", "last_line", ",", "frame", ".", "f_lineno", ")", "]", "=", "None", "else", ":", "#print(\"lin\", frame.f_lineno)", "self", ".", "cur_file_data", "[", "frame", ".", "f_lineno", "]", "=", "None", "self", ".", "last_line", "=", "frame", ".", "f_lineno", "elif", "event", "==", "'return'", ":", "if", "self", ".", "arcs", "and", "self", ".", "cur_file_data", ":", "first", "=", "frame", ".", "f_code", ".", "co_firstlineno", "self", ".", "cur_file_data", "[", "(", "self", ".", "last_line", ",", "-", "first", ")", "]", "=", "None", "# Leaving this function, pop the filename stack.", "self", ".", "cur_file_data", ",", "self", ".", "last_line", "=", "self", ".", "data_stack", ".", "pop", "(", ")", "#print(\"returned, stack is %d deep\" % (len(self.data_stack)))", "elif", "event", "==", "'exception'", ":", "#print(\"exc\", self.last_line, frame.f_lineno)", "self", ".", "last_exc_back", "=", "frame", ".", "f_back", "self", ".", "last_exc_firstlineno", "=", "frame", ".", "f_code", ".", "co_firstlineno", "return", "self", ".", "_trace" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
PyTracer.start
Start this Tracer. Return a Python function suitable for use with sys.settrace().
virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py
def start(self): """Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.thread = threading.currentThread() sys.settrace(self._trace) return self._trace
def start(self): """Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ self.thread = threading.currentThread() sys.settrace(self._trace) return self._trace
[ "Start", "this", "Tracer", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py#L121-L129
[ "def", "start", "(", "self", ")", ":", "self", ".", "thread", "=", "threading", ".", "currentThread", "(", ")", "sys", ".", "settrace", "(", "self", ".", "_trace", ")", "return", "self", ".", "_trace" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
PyTracer.stop
Stop this Tracer.
virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py
def stop(self): """Stop this Tracer.""" self.stopped = True if self.thread != threading.currentThread(): # Called on a different thread than started us: we can't unhook # ourseves, but we've set the flag that we should stop, so we won't # do any more tracing. return if hasattr(sys, "gettrace") and self.warn: if sys.gettrace() != self._trace: msg = "Trace function changed, measurement is likely wrong: %r" self.warn(msg % (sys.gettrace(),)) #print("Stopping tracer on %s" % threading.current_thread().ident) sys.settrace(None)
def stop(self): """Stop this Tracer.""" self.stopped = True if self.thread != threading.currentThread(): # Called on a different thread than started us: we can't unhook # ourseves, but we've set the flag that we should stop, so we won't # do any more tracing. return if hasattr(sys, "gettrace") and self.warn: if sys.gettrace() != self._trace: msg = "Trace function changed, measurement is likely wrong: %r" self.warn(msg % (sys.gettrace(),)) #print("Stopping tracer on %s" % threading.current_thread().ident) sys.settrace(None)
[ "Stop", "this", "Tracer", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py#L131-L145
[ "def", "stop", "(", "self", ")", ":", "self", ".", "stopped", "=", "True", "if", "self", ".", "thread", "!=", "threading", ".", "currentThread", "(", ")", ":", "# Called on a different thread than started us: we can't unhook", "# ourseves, but we've set the flag that we should stop, so we won't", "# do any more tracing.", "return", "if", "hasattr", "(", "sys", ",", "\"gettrace\"", ")", "and", "self", ".", "warn", ":", "if", "sys", ".", "gettrace", "(", ")", "!=", "self", ".", "_trace", ":", "msg", "=", "\"Trace function changed, measurement is likely wrong: %r\"", "self", ".", "warn", "(", "msg", "%", "(", "sys", ".", "gettrace", "(", ")", ",", ")", ")", "#print(\"Stopping tracer on %s\" % threading.current_thread().ident)", "sys", ".", "settrace", "(", "None", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
Collector._start_tracer
Start a new Tracer object, and store it in self.tracers.
virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py
def _start_tracer(self): """Start a new Tracer object, and store it in self.tracers.""" tracer = self._trace_class() tracer.data = self.data tracer.arcs = self.branch tracer.should_trace = self.should_trace tracer.should_trace_cache = self.should_trace_cache tracer.warn = self.warn fn = tracer.start() self.tracers.append(tracer) return fn
def _start_tracer(self): """Start a new Tracer object, and store it in self.tracers.""" tracer = self._trace_class() tracer.data = self.data tracer.arcs = self.branch tracer.should_trace = self.should_trace tracer.should_trace_cache = self.should_trace_cache tracer.warn = self.warn fn = tracer.start() self.tracers.append(tracer) return fn
[ "Start", "a", "new", "Tracer", "object", "and", "store", "it", "in", "self", ".", "tracers", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/collector.py#L227-L237
[ "def", "_start_tracer", "(", "self", ")", ":", "tracer", "=", "self", ".", "_trace_class", "(", ")", "tracer", ".", "data", "=", "self", ".", "data", "tracer", ".", "arcs", "=", "self", ".", "branch", "tracer", ".", "should_trace", "=", "self", ".", "should_trace", "tracer", ".", "should_trace_cache", "=", "self", ".", "should_trace_cache", "tracer", ".", "warn", "=", "self", ".", "warn", "fn", "=", "tracer", ".", "start", "(", ")", "self", ".", "tracers", ".", "append", "(", "tracer", ")", "return", "fn" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb