code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for node_id, node_attribs in docgraph.nodes_iter(data=True):
if attribute is None:
has_attrib = True # don't filter nodes
else:
has_attrib = attribute in node_attribs
if has_attrib:
if value is None:
has_value = True
elif ... | def select_nodes_by_attribute(docgraph, attribute=None, value=None, data=False) | Get all nodes with the given attribute (and attribute value).
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
attribute : str or None
Name of the node attribute that all nodes must posess.
If None, returns all nodes.
... | 2.292059 | 2.320146 | 0.987895 |
for (src_id, target_id, edge_attribs) in docgraph.edges(data=True):
# if all conditions are fulfilled
# we need to add edge_attribs to the namespace eval is working in
if all((eval(cond, {'edge_attribs': edge_attribs})
for cond in conditions)):
if data:
... | def select_edges(docgraph, conditions, data) | yields all edges that meet the conditions given as eval strings | 4.226437 | 3.747453 | 1.127816 |
if attribute:
attrib_key_eval = "'{}' in edge_attribs".format(attribute)
if value is not None:
if isinstance(value, basestring):
attrib_val_eval = \
"edge_attribs['{0}'] == '{1}'".format(attribute, value)
return select_edges(
... | def select_edges_by_attribute(docgraph, attribute=None, value=None, data=False) | get all edges with the given edge type and layer.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
attribute : str or None
Name of the node attribute that all nodes must posess.
If None, returns all nodes.
value : ... | 2.64759 | 2.738622 | 0.96676 |
edge_type_eval = "edge_attribs['edge_type'] == '{}'".format(edge_type)
layer_eval = "'{}' in edge_attribs['layers']".format(layer)
if layer is not None:
if edge_type is not None:
return select_edges(docgraph, data=data,
conditions=[edge_type_eval, la... | def select_edges_by(docgraph, layer=None, edge_type=None, data=False) | get all edges with the given edge type and layer.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str
name of the layer
edge_type : str
Type of the edges to be extracted (Edge types are defined in the
... | 2.622863 | 2.952786 | 0.888267 |
paths_starting_with_id = []
for target_id in rel_dict[src_id]:
if target_id in rel_dict:
for tail in __walk_chain(rel_dict, target_id):
paths_starting_with_id.append([src_id] + tail)
else:
paths_starting_with_id.append([src_id, target_id])
return ... | def __walk_chain(rel_dict, src_id) | given a dict of pointing relations and a start node, this function
will return a list of paths (each path is represented as a list of
node IDs -- from the first node of the path to the last).
Parameters
----------
rel_dict : dict
a dictionary mapping from an edge source node (node ID str)
... | 2.114984 | 1.95009 | 1.084557 |
pointing_relations = select_edges_by(docgraph, layer=layer,
edge_type=EdgeTypes.pointing_relation)
# a markable can point to more than one antecedent, cf. Issue #40
rel_dict = defaultdict(set)
for src_id, target_id in pointing_relations:
rel_dict[sr... | def get_pointing_chains(docgraph, layer=None) | returns a list of chained pointing relations (e.g. coreference chains)
found in the given document graph.
Parameters
----------
docgraph : DiscourseDocumentGraph
a text with annotations, represented by a document graph
layer : str or None
If layer is specifid, this function will onl... | 4.297204 | 4.572443 | 0.939805 |
if offset_ns is None:
offset_ns = self.ns
onset = 0
offset = 0
for token_id, token_str in self.get_tokens():
offset = onset + len(token_str)
self.node[token_id]['{0}:{1}'.format(offset_ns, 'onset')] = onset
self.node[token_id]['{... | def add_offsets(self, offset_ns=None) | adds the onset and offset to each token in the document graph, i.e.
the character position where each token starts and ends. | 2.89159 | 2.34276 | 1.234266 |
if offset_ns is None:
offset_ns = self.ns
try:
if token_node_id is not None:
assert istoken(self, token_node_id), \
"'{}' is not a token node.".format(token_node_id)
onset = self.node[token_node_id]['{0}:{1}'.format(of... | def get_offsets(self, token_node_id=None, offset_ns=None) | returns the offsets (character starting and end position) of a token
or of all tokens occurring in the document.
Parameters
----------
token_node_id : str, int or None
Node ID of a token from which we want to retrieve the start and end
position. If no node ID is ... | 2.831053 | 2.714034 | 1.043117 |
for token_id, _token_str in self.get_tokens():
onset = self.node[token_id]['{0}:{1}'.format(offset_ns, 'onset')]
offset = self.node[token_id]['{0}:{1}'.format(offset_ns, 'offset')]
yield (token_id, onset, offset) | def _get_all_offsets(self, offset_ns=None) | returns all token offsets of this document as a generator of
(token node ID str, character onset int, character offset int) tuples.
Parameters
----------
offset_ns : str or None
The namespace from which the offsets will be retrieved. If no
namespace is given, the... | 3.669817 | 2.874185 | 1.27682 |
if not ns:
ns = self.ns
for node_id in select_nodes_by_layer(self, '{0}:{1}'.format(ns, layer)):
if self.node[node_id][self.ns+':'+cat_key] == cat_val:
yield node_id | def get_phrases(self, ns=None, layer='syntax', cat_key='cat', cat_val='NP') | yield all node IDs that dominate the given phrase type, e.g. all NPs | 3.928691 | 3.259908 | 1.205154 |
if not layers:
layers = {self.ns}
assert isinstance(layers, set), \
"'layers' parameter must be given as a set of strings."
assert all((isinstance(layer, str) for layer in layers)), \
"All elements of the 'layers' set must be strings."
# add l... | def add_node(self, n, layers=None, attr_dict=None, **attr) | Add a single node n and update node attributes.
Parameters
----------
n : node
A node can be any hashable Python object except None.
layers : set of str or None
the set of layers the node belongs to,
e.g. {'tiger:token', 'anaphoricity:annotation'}.
... | 2.984076 | 2.759199 | 1.081501 |
additional_attribs = attr # will be added to each node
for n in nodes:
try: # check, if n is a node_id or a (node_id, attrib dict) tuple
newnode = n not in self.succ # is node in the graph, yet?
except TypeError: # n is a (node_id, attribute dict) tup... | def add_nodes_from(self, nodes, **attr) | Add multiple nodes.
Parameters
----------
nodes : iterable container
A container of nodes (list, dict, set, etc.).
OR
A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword argume... | 3.22291 | 3.404459 | 0.946673 |
assert isinstance(layer, str), "Layers must be strings!"
if isinstance(element, tuple): # edge repr. by (source, target)
assert len(element) == 2
assert all(isinstance(node, (str, int)) for node in element)
source_id, target_id = element
# this cl... | def add_layer(self, element, layer) | add a layer to an existing node or edge
Parameters
----------
element : str, int, (str/int, str/int)
the ID of a node or edge (source node ID, target node ID)
layer : str
the layer that the element shall be added to | 3.687769 | 3.342352 | 1.103346 |
return self.node[token_node_id][self.ns+':'+token_attrib] | def get_token(self, token_node_id, token_attrib='token') | given a token node ID, returns the token unicode string.
Parameters
----------
token_node_id : str
the ID of the token node
token_attrib : str
name of the node attribute that contains the token string as its
value (default: token).
Returns
... | 7.818397 | 11.311362 | 0.691198 |
if token_strings_only:
for token_id in self.tokens:
yield self.get_token(token_id, token_attrib)
else:
for token_id in self.tokens:
yield (token_id, self.get_token(token_id, token_attrib)) | def get_tokens(self, token_attrib='token', token_strings_only=False) | returns a list of (token node ID, token) which represent the tokens
of the input document (in the order they occur).
Parameters
----------
token_attrib : str
name of the node attribute that contains the token string as its
value (default: token).
Yields
... | 1.914024 | 2.134509 | 0.896705 |
# keep track of all merged/old root nodes in case we need to
# delete them or their attributes (e.g. 'metadata')
if hasattr(self, 'merged_rootnodes'):
self.merged_rootnodes.append(other_docgraph.root)
else:
self.merged_rootnodes = [other_docgraph.root]
... | def merge_graphs(self, other_docgraph, verbose=False) | Merges another document graph into the current one, thereby adding all
the necessary nodes and edges (with attributes, layers etc.).
NOTE: This will only work if both graphs have exactly the same
tokenization. | 3.617311 | 3.595463 | 1.006077 |
# copy metadata from other graph, cf. #136
if 'metadata' in other_docgraph.node[other_docgraph.root]:
other_meta = other_docgraph.node[other_docgraph.root]['metadata']
self.node[self.root]['metadata'].update(other_meta)
assert not other_docgraph.in_edges(other_d... | def merge_rootnodes(self, other_docgraph) | Copy all the metadata from the root node of the other graph into this
one. Then, move all edges belonging to the other root node to this
one. Finally, remove the root node of the other graph from this one. | 3.127822 | 2.956118 | 1.058084 |
assert len(self.tokens) > 1, \
"There are no tokens to add precedence relations to."
self.add_edge(self.root, self.tokens[0],
layers={self.ns, self.ns+':precedence'},
edge_type=EdgeTypes.precedence_relation)
for i, token_node_id in... | def add_precedence_relations(self) | add precedence relations to the document graph (i.e. an edge from the
root node to the first token node, an edge from the first token node to
the second one etc.) | 3.137473 | 2.723036 | 1.152197 |
return etree.tostring(
tree, pretty_print=True, xml_declaration=True,
encoding="UTF-8", standalone='no',
doctype='<!DOCTYPE paula SYSTEM "{0}">'.format(dtd_filename)) | def paula_etree_to_string(tree, dtd_filename) | convert a PAULA etree into an XML string. | 2.617843 | 2.455246 | 1.066224 |
E = ElementMaker(nsmap=NSMAP)
tree = E('paula', version='1.1')
tree.append(E('header', paula_id=paula_id))
return E, tree | def gen_paula_etree(paula_id) | creates an element tree representation of an empty PAULA XML file. | 4.678524 | 4.200725 | 1.113742 |
onset = 1
for (token_id, token) in token_tuples:
yield (token_id, onset, len(token))
onset += (len(token) + 1) | def get_onsets(token_tuples) | Parameters
----------
token_tuples : list of (str, unicode)
a list/generator of (token ID, token string) tuples
Returns
-------
onset_tuples : generator of (str, int, int)
A list/generator of (token ID, onset, token length) tuples.
Note that PAULA starts counting string onse... | 3.198009 | 2.603616 | 1.228295 |
paula_document = PaulaDocument(docgraph, human_readable=human_readable)
error_msg = ("Please specify an output directory.\nPaula documents consist"
" of multiple files, so we can't just pipe them to STDOUT.")
assert isinstance(output_root_dir, str), error_msg
document_dir = os.path... | def write_paula(docgraph, output_root_dir, human_readable=False) | converts a DiscourseDocumentGraph into a set of PAULA XML files
representing the same document.
Parameters
----------
docgraph : DiscourseDocumentGraph
the document graph to be converted | 3.280229 | 3.564152 | 0.920339 |
node_id_map = {node: ensure_xpointer_compatibility(node)
for node in self.dg.nodes_iter()}
old_token_ids = self.dg.tokens
# replace document graph with node relabeled version
self.dg = relabel_nodes(self.dg, node_id_map, copy=True)
self.dg.tokens... | def __make_xpointer_compatible(self) | ensure that all node and IDs in the document graph are valid
xpointer IDs. this will relabel all node IDs in place in the discourse
graph and change its ``.tokens`` list accordingly. | 5.757974 | 3.845083 | 1.49749 |
paula_id = '{0}.{1}.text'.format(self.corpus_name, self.name)
E, tree = gen_paula_etree(paula_id)
tree.append(E.body(get_text(self.dg)))
self.files[paula_id] = tree
self.file2dtd[paula_id] = PaulaDTDs.text
return paula_id | def __gen_primary_text_file(self) | generate the PAULA file that contains the primary text of the document
graph. (PAULA documents can have more than one primary text, but
discoursegraphs only works with documents that are based on exactly one
primary text.)
Example
-------
<?xml version="1.0" standalone="... | 9.289343 | 6.479608 | 1.433627 |
paula_id = '{0}.{1}.tok'.format(self.corpus_name, self.name)
E, tree = gen_paula_etree(paula_id)
self.paulamap['tokenization'] = paula_id
base_paula_id = '{0}.{1}.text'.format(self.corpus_name, self.name)
mlist = E('markList',
{'type': 'tok',
... | def __gen_tokenization_file(self) | generate the PAULA file that contains the tokenization of the document
graph. (In general, a PAULA document may contain more than one
tokenization, but in discoursegraphs we'll only work with documents
that have exactly one tokenization.)
Example
-------
<?xml version="1... | 8.94662 | 6.131045 | 1.459233 |
paula_id = '{0}.{1}.{2}_{3}_seg'.format(layer, self.corpus_name,
self.name, layer)
E, tree = gen_paula_etree(paula_id)
base_paula_id = '{0}.{1}.tok'.format(self.corpus_name, self.name)
mlist = E('markList',
{'type': l... | def __gen_span_markables_file(self, layer, saltnpepper_compatible=True) | <mark> elements are used to group tokens (continuous or discontinuos
spans) for further annotation.
A span markable file (*_seg.xml) contains a list of spans and the type
of annotation that is applied to them
(stored in <markList type="annotation type..."). As a consequence,
each... | 5.074592 | 4.852625 | 1.045742 |
base_paula_id = '{0}.{1}.tok'.format(self.corpus_name, self.name)
paula_id = '{0}.{1}.{2}.tok_multiFeat'.format(top_level_layer,
self.corpus_name,
self.name)
E, tree = gen_paula_etree(p... | def __gen_token_anno_file(self, top_level_layer) | creates an etree representation of a <multiFeat> file that describes
all the annotations that only span one token (e.g. POS, lemma etc.).
Note: discoursegraphs will create one token annotation file for each
top level layer (e.g. conano, tiger etc.). | 6.148499 | 5.457442 | 1.126626 |
paula_id = '{0}.{1}.{2}_{3}'.format(layer, self.corpus_name, self.name,
layer)
self.paulamap['hierarchy'][layer] = paula_id
E, tree = gen_paula_etree(paula_id)
dominance_edges = select_edges_by(
self.dg, layer=layer, edge_type... | def __gen_hierarchy_file(self, layer) | Hierarchical structures (<structList> elements) are used to create
hierarchically nested annotation graphs (e.g. to express consists-of
relationships or dominance-edges in syntax trees, RST).
A <struct> element will be created for each hierarchical node
(e.g. an NP) with edges (<rel> ele... | 3.720389 | 3.499715 | 1.063055 |
paula_id = '{0}.{1}.{2}_{3}_struct'.format(top_level_layer,
self.corpus_name, self.name,
top_level_layer)
E, tree = gen_paula_etree(paula_id)
base_paula_id = self.paulamap['hierarchy'][top_lev... | def __gen_struct_anno_files(self, top_level_layer) | A struct annotation file contains node (struct) attributes (of
non-token nodes). It is e.g. used to annotate the type of a syntactic
category (NP, VP etc.).
See also: __gen_hierarchy_file() | 5.735793 | 5.422404 | 1.057795 |
paula_id = '{0}.{1}.{2}_{3}_rel'.format(top_level_layer, self.corpus_name,
self.name, top_level_layer)
E, tree = gen_paula_etree(paula_id)
dominance_edges = select_edges_by(
self.dg, layer=top_level_layer,
edge_type=Ed... | def __gen_rel_anno_file(self, top_level_layer) | A rel annotation file contains edge (rel)
attributes. It is e.g. used to annotate the type of a dependency
relation (subj, obj etc.).
See also: __gen_hierarchy_file() | 3.85739 | 3.835115 | 1.005808 |
paula_id = '{0}.{1}.{2}_{3}_pointing'.format(top_level_layer,
self.corpus_name, self.name,
top_level_layer)
self.paulamap['pointing'][top_level_layer] = paula_id
E, tree = gen_paula_etree(p... | def __gen_pointing_file(self, top_level_layer) | Creates etree representations of PAULA XML files modeling pointing
relations. Pointing relations are ahierarchical edges between any
two nodes (``tok``, ``mark`` or ``struct``). They are used to signal
pointing relations between tokens (e.g. in a dependency parse tree)
or the coreference... | 4.010489 | 3.541761 | 1.132343 |
paula_id = '{0}.{1}.anno'.format(self.corpus_name, self.name)
E, tree = gen_paula_etree(paula_id)
slist = E('structList', {'type': 'annoSet'})
# NOTE: we could group all the annotations into different structs
# but I don't see the point. We're already using namespaces, ... | def __gen_annoset_file(self) | An ``annoSet`` file describes the set of annotations contained in a
document (i.e. it lists all annotation files that belong to a PAULA
document). Each PAULA document must contain an annoSet file.
An ``annoSet`` file can also be used to list the contents of a
(sub)corpus, but we're not ... | 7.716218 | 6.90929 | 1.116789 |
if istoken(self.dg, node_id):
base_paula_id = self.paulamap['tokenization']
else:
base_paula_id = self.paulamap['hierarchy'][layer]
return '{0}.xml#{1}'.format(base_paula_id, node_id) | def __gen_node_href(self, layer, node_id) | generates a complete xlink:href for any node (token node,
structure node etc.) in the docgraph. This will only work AFTER
the corresponding PAULA files have been created (and their file names
are registered in ``self.paulamap``). | 8.511162 | 5.266068 | 1.616227 |
# Created a namedtuple to store the "key" for the choices_dict
TZOffset = namedtuple('TZOffset', 'value offset_string')
choices_dict = defaultdict(list)
# Iterate through the timezones and populate the timezone choices
for tz in iter(timezones):
# Retrieve a datetime object in this t... | def get_choices(timezones, grouped=False) | Retrieves timezone choices from any iterable (normally pytz). | 2.954797 | 2.933575 | 1.007234 |
return cls(name=etree_element.attrib['name'],
value=etree_element.attrib['valueString'],
xsi_type=get_xsi_type(etree_element),
namespace=etree_element.attrib.get('namespace'),
hexvalue=etree_element.attrib['value']) | def from_etree(cls, etree_element) | creates a ``SaltLabel`` from an etree element representing a label
element in a SaltXMI file.
A label element in SaltXMI looks like this::
<labels xsi:type="saltCore:SFeature" namespace="salt"
name="SNAME" value="ACED0005740007735370616E3139"
valueString="sS... | 3.942894 | 3.496758 | 1.127585 |
attribs = {
'{{{pre}}}type'.format(pre=NAMESPACES['xsi']): self.xsi_type,
'namespace': self.namespace, 'name': self.name,
'value': self.hexvalue, 'valueString': self.value}
non_empty_attribs = {key: val for (key, val) in attribs.items()
... | def to_etree(self) | creates an etree element of a ``SaltLabel`` that mimicks a SaltXMI
<labels> element | 5.646573 | 5.219983 | 1.081722 |
# we can't rely on the .ns attribute of a merged graph
if layer:
namespace = dg.layer2namespace(layer)
else:
namespace = docgraph.ns
pointing_chains = dg.get_pointing_chains(docgraph, layer=layer)
markables = sorted(itertools.chain(*pointing_chains),
key=... | def gen_bracket_mappings(docgraph, layer=None) | extract all pointing chains (e.g. coreference chains) from a document
graph (or just from the specified layer). return dictionaries describing
which token signals the beginning of markables, the end of markables,
as well as a mapping from a markable to the chain it belongs to.
Parameters
----------... | 3.73238 | 3.397879 | 1.098444 |
bracketed_str = gen_bracketed_output(docgraph, layer=layer)
assert isinstance(output_file, (str, file))
if isinstance(output_file, str):
path_to_file = os.path.dirname(output_file)
if not os.path.isdir(path_to_file):
create_dir(path_to_file)
with codecs.open(output_f... | def write_brackets(docgraph, output_file, layer='mmax') | converts a document graph into a plain text file with brackets.
Parameters
----------
layer : str or None
The layer from which the pointing chains/relations
(i.e. coreference relations) should be extracted.
If no layer is selected, all pointing relations will be considered.
... | 2.275697 | 2.504339 | 0.908702 |
if properties:
return '({0} {1})'.format(node_name,
encoder.encode(properties))
else:
return '({0})'.format(node_name) | def node2geoff(node_name, properties, encoder) | converts a NetworkX node into a Geoff string.
Parameters
----------
node_name : str or int
the ID of a NetworkX node
properties : dict
a dictionary of node attributes
encoder : json.JSONEncoder
an instance of a JSON encoder (e.g. `json.JSONEncoder`)
Returns
-------
... | 3.196212 | 3.858329 | 0.828393 |
edge_string = None
if properties:
args = [from_node, edge_relationship_name,
encoder.encode(properties), to_node]
edge_string = '({0})-[:{1} {2}]->({3})'.format(*args)
else:
args = [from_node, edge_relationship_name, to_node]
edge_string = '({0})-[:{1}]->... | def edge2geoff(from_node, to_node, properties, edge_relationship_name, encoder) | converts a NetworkX edge into a Geoff string.
Parameters
----------
from_node : str or int
the ID of a NetworkX source node
to_node : str or int
the ID of a NetworkX target node
properties : dict
a dictionary of edge attributes
edge_relationship_name : str
string... | 2.094699 | 2.445253 | 0.856639 |
if encoder is None:
encoder = json.JSONEncoder()
is_digraph = isinstance(graph, nx.DiGraph)
lines = []
lapp = lines.append
for node_name, properties in graph.nodes(data=True):
lapp(node2geoff(node_name, properties, encoder))
for from_node, to_node, properties in graph.edge... | def graph2geoff(graph, edge_rel_name, encoder=None) | Get the `graph` as Geoff string. The edges between the nodes
have relationship name `edge_rel_name`. The code
below shows a simple example::
# create a graph
import networkx as nx
G = nx.Graph()
G.add_nodes_from([1, 2, 3])
G.add_edge(1, 2)
G.add_edge(2, 3)
... | 2.144568 | 2.460896 | 0.871458 |
match = HS2015_REL_RE.match(tree[subtree_index].label())
relname = match.group('relname')
return relname.capitalize() | def get_capitalized_relname(tree, subtree_index) | Returns the capitalized relation name from a tree's satellite
subtree label, e.g. 'satellite:contrast' becomes 'Contrast'. | 5.405776 | 5.062884 | 1.067727 |
with open(heilman_filepath, 'r') as parsed_file:
heilman_json = json.load(parsed_file)
edus = heilman_json['edu_tokens']
# the Heilman/Sagae parser can theoretically produce more than one parse,
# but I've never seen more than one, so we'll just the that.
scored_rst_tree = heilman_jso... | def parse_hs2015(heilman_filepath) | convert the output of the Heilman and Sagae (2015) discourse parser
into a nltk.ParentedTree instance.
Parameters
----------
heilman_filepath : str
path to a file containing the output of Heilman and Sagae's 2015
discourse parser
Returns
-------
parented_tree : nltk.Parente... | 5.089817 | 3.399116 | 1.497394 |
assert text_subtree.label() == SubtreeType.text
return u' '.join(word.decode('utf-8') for word in text_subtree.leaves()) | def get_edu_text(text_subtree) | return the text of the given EDU subtree | 4.684547 | 4.697965 | 0.997144 |
if is_leaf_node(tree):
return SubtreeType.leaf
tree_type = tree.label().lower().split(':')[0]
assert tree_type in SUBTREE_TYPES
return tree_type | def get_tree_type(tree) | Return the (sub)tree type: 'root', 'nucleus', 'satellite', 'text' or 'leaf'
Parameters
----------
tree : nltk.tree.ParentedTree
a tree representing a rhetorical structure (or a part of it) | 5.309382 | 5.486702 | 0.967682 |
child_types = defaultdict(list)
for i, child in enumerate(tree):
child_types[get_tree_type(child)].append(i)
return child_types | def get_child_types(tree) | Take a tree and check what types of children (i.e. 'nucleus' or
'satellite') it has. Returns a map from child tree type to the indices of
all children with that type. | 2.557832 | 2.229932 | 1.147045 |
if 'text' in child_types and len(child_types) == 1:
return NucType.edu
assert 'nucleus' in child_types, \
"This is not a relational node. child_types: {}".format(child_types)
if 'satellite' not in child_types:
assert len(child_types['nucleus']) > 1
return NucType.multi... | def get_nuclearity_type(child_types) | Returns the nuclearity type of an RST relation (i.e. 'multinuc',
'nucsat' or 'multisat') or 'edu' if the node is below the relation
level. | 3.095438 | 2.572402 | 1.203326 |
for i, child in enumerate(parented_tree):
if isinstance(child, nltk.Tree):
_add_edus_to_tree(child, edus)
else:
edu_index = int(child)
edu_tokens = edus[edu_index]
parented_tree[i] = u" ".join(edu_tokens) | def _add_edus_to_tree(parented_tree, edus) | replace EDU indices with the text of the EDUs
in a parented tree.
Parameters
----------
parented_tree : nltk.ParentedTree
a parented tree that only contains EDU indices
as leaves
edus : list(list(unicode))
a list of EDUs, where each EDU is represented as
a list of to... | 2.300155 | 2.244132 | 1.024964 |
def transform(hs2015_tree):
if is_leaf_node(hs2015_tree):
return hs2015_tree
tree_type = get_tree_type(hs2015_tree)
if tree_type in (SubtreeType.root, SubtreeType.nucleus, SubtreeType.satellite):
child_types = get_child_t... | def hs2015tree2dgparentedtree(self) | Convert the tree from Heilman/Sagae 2015 format into a conventional binary tree,
which can be easily converted into output formats like RS3. | 2.717437 | 2.700362 | 1.006323 |
segment_prefix = segment_type[0] if segment_type else '_'
if tokenized:
segment_label = u'[{0}]:{1}:segment:{2}'.format(
segment_prefix, ns, segment.attrib['id'])
else:
# if the graph is not tokenized, put (the beginning of) the
# segment's text into its label
... | def get_segment_label(segment, segment_type, segment_text, ns, tokenized) | generates an appropriate node label for a segment (useful for dot
visualization). | 4.139058 | 3.844074 | 1.076737 |
controller_instance = self.controllers[controller_id]
controller_instance.last_command_at = self.last_command_at
ret_val = getattr(controller_instance, command)(*args, **kwargs)
self.last_command_at = controller_instance.last_command_at
return ret_val | def execute(self, controller_id, command, *args, **kwargs) | Execute a single command, and sets sleep times properly.
- controller_id = index of controller, zero-based
- command is normal LedController command as a string
- *args and **kwargs are passed to command
For example, .execute(0, "on", 1) sends "on" command to group 1 on controller 0 (f... | 2.410563 | 2.791419 | 0.863562 |
if bulb_type not in ("rgbw", "white"):
raise AttributeError("Bulb type must be either rgbw or white")
self.group[group] = bulb_type
self.has_white = "white" in self.group.values()
self.has_rgbw = "rgbw" in self.group.values() | def set_group_type(self, group, bulb_type) | Set bulb type for specified group.
Group must be int between 1 and 4.
Type must be "rgbw" or "white".
Alternatively, use constructor keywords group_1, group_2 etc. to set bulb types. | 2.894729 | 2.648959 | 1.09278 |
if input_command is None:
return
time_since_last_command = time.time() - self.last_command_at
if time_since_last_command < self.pause_between_commands:
# Wifi gateway requires 100ms pause between commands to function at least somewhat reliably.
time.s... | def _send_command(self, input_command) | You shouldn't use this method directly.
Send a single command. If previous command was sent
recently, sleep for 100ms (configurable with pause_between_commands
constructor keyword). | 2.621714 | 2.443053 | 1.07313 |
retries = kwargs.get("retries", self.repeat_commands)
for _ in range(retries):
if kwargs.get("send_on", True):
self.on(group)
if group is None or group == 0:
self._send_to_all_groups(**kwargs)
continue
if group... | def _send_to_group(self, group, **kwargs) | You shouldn't use this method directly.
Send a single command to specific group.
Handles automatically sending command to white or rgbw group. | 3.437264 | 3.094939 | 1.110608 |
self._send_to_group(group, send_on=False, command="all_on")
return
self._send_to_group(group, per_group=True, white_cmd=self.WHITE_GROUP_X_ON, rgbw_cmd=self.RGBW_GROUP_X_ON, send_on=False) | def on(self, group=None): # pylint: disable=invalid-name
if group is None or group == 0 | Switch lights on. If group (1-4) is not specified,
all four groups will be switched on. | 8.264935 | 5.993182 | 1.379056 |
if group is None or group == 0:
self._send_to_group(group, send_on=False, command="all_off")
return
self._send_to_group(group, per_group=True, send_on=False, rgbw_cmd=self.RGBW_GROUP_X_OFF, white_cmd=self.WHITE_GROUP_X_OFF) | def off(self, group=None) | Switch lights off. If group (1-4) is not specified,
all four groups will be switched off. | 5.475634 | 5.208134 | 1.051362 |
if group is None or group == 0:
self._send_to_group(group, command="all_white")
return
self._send_to_group(group, per_group=True, rgbw_cmd=self.RGBW_GROUP_X_TO_WHITE) | def white(self, group=None) | Switch lights on and change color to white.
If group (1-4) is not specified, all four groups
will be switched on and to white. | 7.945929 | 6.945932 | 1.143969 |
if color == "white": # hack, as commands for setting color to white differ from other colors.
self.white(group)
elif isinstance(color, int):
if color < 0 or color > 255:
raise AttributeError("Color must be color keyword or 0-255")
self._send_... | def set_color(self, color, group=None) | Switch lights on and change color. Available colors:
- violet
- royal_blue
- baby_blue
- aqua
- royal_mint
- seafoam_green
- green
- lime_green
- yellow
- yellow_orange
- orang... | 4.525744 | 4.398074 | 1.029029 |
# Clamp to appropriate range.
percent = min(100, max(0, percent))
# Map 0-100 to 2-27
value = int(2 + ((float(percent) / 100) * 25))
return percent, value | def get_brightness_level(cls, percent) | Convert percents to bulbs internal range.
percent should be integer from 0 to 100.
Return value is 2 (minimum brightness) - 27 (maximum brightness) | 4.984509 | 4.177319 | 1.193232 |
# If input is float, assume it is percent value from 0 to 1.
if isinstance(percent, float):
if percent > 1:
percent = int(percent)
else:
percent = int(percent * 100)
percent, value = self.get_brightness_level(percent)
self.... | def set_brightness(self, percent, group=None) | Set brightness.
Percent is int between 0 (minimum brightness) and 100 (maximum brightness), or
float between 0.0 (minimum brightness) and 1.0 (maximum brightness).
See also .nightmode().
If group (1-4) is not specified, brightness of all four groups will be adjusted. | 4.624411 | 5.400978 | 0.856217 |
self.off(group)
if group is None or group == 0:
if self.has_rgbw:
self._send_command(self.RGBW_COMMANDS["all_nightmode"])
if self.has_white:
self._send_command(self.WHITE_COMMANDS["all_nightmode"])
else:
self._send_to_g... | def nightmode(self, group=None) | Enable nightmode (very dim white light).
The command is sent only once, as multiple commands would blink lights rapidly.
There is no way to automatically detect whether transmitting the command succeeded or not.
This does not work with wifi gateway v3.
Contrary to limi... | 4.113909 | 3.811949 | 1.079214 |
original_retries = self.repeat_commands
self.repeat_commands = 1
for _ in range(original_retries):
for command in commands:
cmd = command[0]
args = command[1:]
cmd(*args)
self.repeat_commands = original_retries | def batch_run(self, *commands) | Run batch of commands in sequence.
Input is positional arguments with (function pointer, *args) tuples.
This method is useful for executing commands to multiple groups with retries,
without having too long delays. For example,
- Set group 1 to red and brightness to 10%... | 3.466222 | 3.723175 | 0.930986 |
message = ejson.dumps(msg_dict)
super(DDPSocket, self).send(message)
self._debug_log('<<<{}'.format(message)) | def send(self, msg_dict) | Send a message through the websocket client and wait for the
answer if the message being sent contains an id attribute. | 9.259924 | 9.283325 | 0.997479 |
if not self.debug:
return
sys.stderr.write('{}\n'.format(msg)) | def _debug_log(self, msg) | Debug log messages if debug=True | 3.910499 | 3.460058 | 1.130183 |
# destroy the connection if it already exists
if self.ddpsocket:
self.ddpsocket.remove_all_listeners('received_message')
self.ddpsocket.remove_all_listeners('closed')
self.ddpsocket.remove_all_listeners('opened')
self.ddpsocket.close_connection()
... | def _init_socket(self) | Initialize the ddp socket | 2.538662 | 2.30773 | 1.100069 |
if self.auto_reconnect and not self._is_closing:
connected = False
while not connected:
log_msg = "* ATTEMPTING RECONNECT"
if self._retry_new_version:
log_msg = "* RETRYING DIFFERENT DDP VERSION"
self.ddpsocket.... | def _recover_network_failure(self) | Recover from a network failure | 4.355288 | 4.179688 | 1.042013 |
# give up if there are no more ddp versions to try
if self._ddp_version_index == len(DDP_VERSIONS):
self.ddpsocket._debug_log('* DDP VERSION MISMATCH')
self.emit('version_mismatch', DDP_VERSIONS)
return
# use server recommended version if we support ... | def opened(self) | Send the connect message to the server. | 4.62311 | 4.288356 | 1.078061 |
self.emit('socket_closed', code, reason)
self._recover_network_failure() | def closed(self, code, reason=None) | Called when the connection is closed | 13.816899 | 12.533517 | 1.102396 |
data = ejson.loads(str(data))
if not data.get('msg'):
return
elif data['msg'] == 'failed':
self._ddp_version_index += 1
self._retry_new_version = data.get('version', True)
self.emit('failed', data)
elif data['msg'] == 'connected'... | def received_message(self, data) | Incomming messages | 2.398005 | 2.400091 | 0.999131 |
cur_id = self._next_id()
if callback:
self._callbacks[cur_id] = callback
self.send({'msg': 'method', 'id': cur_id, 'method': method, 'params': params}) | def call(self, method, params, callback=None) | Call a method on the server
Arguments:
method - the remote server method
params - an array of commands to send to the method
Keyword Arguments:
callback - a callback function containing the return data | 2.809555 | 3.975409 | 0.706734 |
cur_id = self._next_id()
if callback:
self._callbacks[cur_id] = callback
self.send({'msg': 'sub', 'id': cur_id, 'name': name, 'params': params})
return cur_id | def subscribe(self, name, params, callback=None) | Subcribe to add/change/remove events for a collection
Arguments:
name - the name of the publication to subscribe
params - params to subscribe (parsed as ejson)
Keyword Arguments:
callback - a callback function that gets executed when the subscription has completed | 2.55207 | 3.735562 | 0.683182 |
with open(input_filepath, 'r') as input_file:
input_file_str = input_file.read()
merge_file_str, parsetree_str = input_file_str.split('ParentedTree', 1)
return merge_file_str, 'ParentedTree' + parsetree_str | def split_input(self, input_filepath) | Splits the input file into the 'merge file' (which contains
the EDUs) and the 'parsetree file'. | 4.052066 | 2.752188 | 1.472307 |
lines = merge_file_str.splitlines()
edus = defaultdict(list)
for line in lines:
if line.strip(): # ignore empty lines
token = line.split('\t')[2]
edu_id = int(line.split('\t')[9])
edus[edu_id].append(token)
return edu... | def extract_edus(merge_file_str) | Extract EDUs from DPLPs .merge output files.
Returns
-------
edus : dict from EDU IDs (int) to words (list(str)) | 2.745702 | 2.879446 | 0.953552 |
def transform(dplp_tree):
if isinstance(dplp_tree, basestring) or not hasattr(dplp_tree, 'label'):
return dplp_tree
assert len(dplp_tree) == 2, "We can only handle binary trees."
match = DPLP_REL_RE.match(dplp_tree.label())
a... | def dplptree2dgparentedtree(self) | Convert the tree from DPLP's format into a conventional binary tree,
which can be easily converted into output formats like RS3. | 2.998444 | 2.955196 | 1.014635 |
terminals = set()
nonterminals = set()
for node_id in sentence_graph.nodes_iter():
if sentence_graph.out_degree(node_id) > 0:
# all nonterminals (incl. root)
nonterminals.add(node_id)
else: # terminals
terminals.add(node_id)
return sorted(list(te... | def _get_terminals_and_nonterminals(sentence_graph) | Given a TigerSentenceGraph, returns a sorted list of terminal node
IDs, as well as a sorted list of nonterminal node IDs.
Parameters
----------
sentence_graph : TigerSentenceGraph
a directed graph representing one syntax annotated sentence from
a TigerXML file
Returns
-------
... | 2.134984 | 2.323427 | 0.918895 |
return [node for node in sentence_graph.nodes_iter()
if sentence_graph.degree(node) == 0 and
sentence_graph.number_of_nodes() > 1] | def get_unconnected_nodes(sentence_graph) | Takes a TigerSentenceGraph and returns a list of node IDs of
unconnected nodes.
A node is unconnected, if it doesn't have any in- or outgoing edges.
A node is NOT considered unconnected, if the graph only consists of
that particular node.
Parameters
----------
sentence_graph : TigerSentenc... | 2.860553 | 4.354866 | 0.656864 |
subord_clause_rels = \
dg.select_edges_by_attribute(
tiger_docgraph, attribute='tiger:label',
value=['MO', 'RC', 'SB'])
subord_clause_nodes = []
for src_id, target_id in subord_clause_rels:
src_cat = tiger_docgraph.node[src_id].get('tiger:cat')
if src_ca... | def get_subordinate_clauses(tiger_docgraph) | given a document graph of a TIGER syntax tree, return all
node IDs of nodes representing subordinate clause constituents.
Parameters
----------
tiger_docgraph : DiscourseDocumentGraph or TigerDocumentGraph
document graph from which subordinate clauses will be extracted
Returns
-------
... | 3.862953 | 4.044661 | 0.955075 |
sentence_graph = TigerSentenceGraph(sentence)
self.tokens.extend(sentence_graph.tokens)
sentence_root_node_id = sentence_graph.root
self.add_nodes_from(sentence_graph.nodes(data=True))
self.add_edges_from(sentence_graph.edges(data=True))
self.add_edge(self.root,... | def __add_sentence_to_document(self, sentence) | Converts a sentence into a TigerSentenceGraph and adds all
its nodes, edges (and their features) to this document graph.
This also adds a ``dominance_relation`` edge from the root node of this
document graph to the root node of the sentence and appends the
sentence root node ID to ``sel... | 3.807619 | 2.970532 | 1.281797 |
unconnected_node_ids = get_unconnected_nodes(self)
if dg.istoken(self, self.root):
# This sentence has no hierarchical structure, i.e. the root
# node is also a terminal / token node.
# We will add a virtual root node to compensate for this.
self.... | def __repair_unconnected_nodes(self) | Adds a (``dominance_relation``) edge from the sentence root node to all
previously unconnected nodes (token nodes, that either represent a
punctuation mark or are part of a headline 'sentence' that has no
full syntax structure annotation). | 6.028183 | 5.066279 | 1.189864 |
ins = SaltElement.from_etree(etree_element)
# TODO: this looks dangerous, ask Stackoverflow about it!
# convert SaltElement into SaltLayer
ins.__class__ = SaltLayer.mro()[0]
# add nodes and edges that belong to this layer (if any)
for element in ('nodes', 'edges... | def from_etree(cls, etree_element) | creates a ``SaltLayer`` instance from the etree representation of an
<layers> element from a SaltXMI file. | 6.215862 | 5.679791 | 1.094382 |
nodes_attrib_val = ' '.join('//@nodes.{}'.format(node_id)
for node_id in self.nodes)
edges_attrib_val = ' '.join('//@edges.{}'.format(edge_id)
for edge_id in self.edges)
attribs = {
'{{{pre}}}type'.form... | def to_etree(self) | creates an etree element of a ``SaltLayer`` that mimicks a SaltXMI
<layers> element | 4.022055 | 3.67705 | 1.093826 |
self._add_dominance_relation(self.root, 'intro')
self._add_token_span_to_document(tree.find('/intro'))
for turn in tree.iterfind('/turn'):
turn_id = 'turn_{}'.format(turn.attrib['nrgen'])
self._add_dominance_relation(self.root, turn_id)
self.turns.ap... | def _parse_decour(self, tree) | <!ELEMENT hearing (header, intro, turn+, conclu?)>
# <!ELEMENT turn (act?|utterance+)*>
# <!ELEMENT utterance (#PCDATA|token|lemma|pos)*> | 2.576803 | 2.140928 | 1.203591 |
token_feat = {self.ns+':token': token_string}
if token_attrs:
token_attrs.update(token_feat)
else:
token_attrs = token_feat
token_id = 'token_{}'.format(self.token_count)
self.add_node(token_id, layers={self.ns, self.ns+':token'},
... | def _add_token_to_document(self, token_string, token_attrs=None) | add a token node to this document graph | 3.040014 | 2.852197 | 1.06585 |
utter_id = 'utterance_{}'.format(utterance.attrib['nrgen'])
norm, lemma, pos = [elem.text.split()
for elem in utterance.iterchildren()]
for i, word in enumerate(utterance.text.split()):
token_id = self._add_token_to_document(
word,... | def _add_utterance_to_document(self, utterance) | add an utterance to this docgraph (as a spanning relation) | 4.088604 | 3.763523 | 1.086377 |
for token in span_element.text.split():
token_id = self._add_token_to_document(token)
if span_element.tag == 'act': # doc can have 0+ acts
self._add_spanning_relation('act_{}'.format(self.act_count),
token_id)
... | def _add_token_span_to_document(self, span_element) | adds an <intro>, <act> or <conclu> token span to the document. | 3.802974 | 2.987399 | 1.273005 |
# TODO: fix #39, so we don't need to add nodes by hand
self.add_node(target, layers={self.ns, self.ns+':unit'})
self.add_edge(source, target,
layers={self.ns, self.ns+':discourse'},
edge_type=EdgeTypes.dominance_relation) | def _add_dominance_relation(self, source, target) | add a dominance relation to this docgraph | 7.278317 | 6.65048 | 1.094405 |
self.add_edge(source, target, layers={self.ns, self.ns+':unit'},
edge_type=EdgeTypes.spanning_relation) | def _add_spanning_relation(self, source, target) | add a spanning relation to this docgraph | 9.793451 | 8.281555 | 1.182562 |
for leafpos in self.tree.treepositions('leaves'):
edu_str = self.tree[leafpos]
edu_str = EDU_START_RE.sub("", edu_str)
edu_str = TRIPLE_ESCAPE_RE.sub('"', edu_str)
edu_str = EDU_END_RE.sub("", edu_str)
self.tree[leafpos] = edu_str | def cleanup_codra_edus(self) | Remove leading/trailing '_!' from CODRA EDUs and unescape its double quotes. | 3.591063 | 2.963683 | 1.211689 |
if not isinstance(data, dict):
error('Data must be a dictionary.')
for value in data.values():
if not isinstance(value, basestring):
error('Values must be strings.') | def validate(data) | Query data and result data must have keys who's values are strings. | 3.171796 | 2.666176 | 1.189643 |
@wraps(function)
def wrapper(*args, **kwargs):
query = json.loads(sys.stdin.read())
validate(query)
try:
result = function(query, *args, **kwargs)
except Exception as e:
# Terraform wants one-line errors so we catch all exceptions and trim down to jus... | def terraform_external_data(function) | Query data is received on stdin as a JSON object.
Result data must be returned on stdout as a JSON object.
The wrapped function must expect its first positional argument to be a dictionary of the query data. | 4.396454 | 3.906866 | 1.125315 |
rs3_etree = etree.parse(rs3_file)
reltypes = extract_relationtypes(rs3_etree)
elements = defaultdict(lambda: defaultdict(str))
children = defaultdict(list)
ordered_edus = []
for elem in rs3_etree.iter('segment', 'group'):
elem_id = elem.attrib['id']
parent_id = elem.attrib... | def get_rs3_data(rs3_file, word_wrap=0) | helper function to build RSTTrees: data on parent-child relations
and node attributes.
TODO: add proper documentation | 3.155746 | 3.111168 | 1.014329 |
root_label = tree.label()
expected_n_root = debug_root_label('N', debug=debug, root_id=tree.root_id)
expected_s_root = debug_root_label('S', debug=debug, root_id=tree.root_id)
if root_label == expected_n_root:
return tree
elif root_label == expected_s_root:
tree.set_label(expe... | def n_wrap(tree, debug=False, root_id=None) | Ensure the given tree has a nucleus as its root.
If the root of the tree is a nucleus, return it.
If the root of the tree is a satellite, replace the satellite
with a nucleus and return the tree.
If the root of the tree is a relation, place a nucleus on top
and return the tree. | 3.028603 | 3.048659 | 0.993421 |
if hasattr(dgtree, 'reltypes'):
# dgtree is an RSTTree or a DisTree that contains a DGParentedTree
return dgtree.reltypes
if relations is None:
relations = {}
if is_leaf(dgtree):
return relations
root_label = dgtree.label()
if root_label == '':
assert ... | def extract_relations(dgtree, relations=None) | Extracts relations from a DGParentedTree.
Given a DGParentedTree, returns a (relation name, relation type) dict
of all the RST relations occurring in that tree. | 3.770476 | 3.409444 | 1.105892 |
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(rs3_string)
temp.close()
rst_tree = cls(rs3_file=temp.name)
os.unlink(temp.name)
return rst_tree | def fromstring(cls, rs3_string) | Create an RSTTree instance from a string content an *.rs3 file. | 2.763616 | 2.063773 | 1.339108 |
if start_node is None:
return self.root2tree(start_node=start_node)
elem_id = start_node
if elem_id not in self.elem_dict:
return []
elem = self.elem_dict[elem_id]
elem_type = elem['element_type']
assert elem_type in ('segment', 'group'... | def dt(self, start_node=None) | main method to create an RSTTree from the output of get_rs3_data().
TODO: add proper documentation | 2.735267 | 2.637685 | 1.036995 |
nuc_tree, nuc_pos = nuc_tuple
sat_tuples = inner_sat_tuples + outer_sat_tuples
last_sat_tuple_pos = len(sat_tuples)-1
for i, (sat_tree, sat_pos) in enumerate(sat_tuples):
relname = self.get_relname(sat_tree.root_id)
if sat_pos < nuc_pos:
... | def convert_schema(self, nuc_tuple, inner_sat_tuples, outer_sat_tuples) | subtrees are represented as (tree, linear tree position) tuples.
returns relation as root node. | 2.658604 | 2.494219 | 1.065907 |
subtrees_desc_height = sorted(subtrees,
key=methodcaller('node_height', self),
reverse=True)
return sorted(subtrees_desc_height,
key=methodcaller('get_position', self)) | def sort_subtrees(self, *subtrees) | sort the given subtrees (of type DGParentedTree) based on their
linear position in this RSTTree. If two subtrees have the same
linear position in the RSTTree (i.e. one is a child of the other),
they are sorted by their height in reverse order (i.e. the child
appears before its parent). | 5.349082 | 4.935158 | 1.083872 |
if root_id is None:
root_id = tree.root_id
elem = self.elem_dict[root_id]
if elem['nuclearity'] == 'nucleus':
return n_wrap(tree, debug=debug, root_id=root_id)
else:
return s_wrap(tree, debug=debug, root_id=root_id) | def elem_wrap(self, tree, debug=False, root_id=None) | takes a DGParentedTree and puts a nucleus or satellite on top,
depending on the nuclearity of the root element of the tree. | 2.898331 | 2.024374 | 1.431717 |
"Cut a new release"
version = run('python setup.py --version').stdout.strip()
assert version, 'No version found in setup.py?'
print('### Releasing new version: {0}'.format(version))
run('git tag {0}'.format(version))
run('git push --tags')
run('python setup.py sdist bdist_wheel')
run('... | def release() | Cut a new release | 4.03202 | 3.564552 | 1.131144 |
'''
bgwrite - Start a background writing process
@param fileObj <stream> - A stream backed by an fd
@param data <str/bytes/list> - The data to write. If a list is given, each successive element will be written to the fileObj and flushed. If a string/bytes is provided, it will be... | def bgwrite(fileObj, data, closeWhenFinished=False, chainAfter=None, ioPrio=4) | bgwrite - Start a background writing process
@param fileObj <stream> - A stream backed by an fd
@param data <str/bytes/list> - The data to write. If a list is given, each successive element will be written to the fileObj and flushed. If a string/bytes is provided, it will be chunked accordi... | 9.881913 | 1.282064 | 7.707817 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.