repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
niemasd/TreeSwift | treeswift/Tree.py | Tree.coalescence_times | def coalescence_times(self, backward=True):
'''Generator over the times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
'''
if not isinstance(backward, bool):
raise TypeError("backward must be a bool")
for dist in sorted((d for n,d in self.distances_from_root() if len(n.children) > 1), reverse=backward):
yield dist | python | def coalescence_times(self, backward=True):
'''Generator over the times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
'''
if not isinstance(backward, bool):
raise TypeError("backward must be a bool")
for dist in sorted((d for n,d in self.distances_from_root() if len(n.children) > 1), reverse=backward):
yield dist | [
"def",
"coalescence_times",
"(",
"self",
",",
"backward",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"backward",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"backward must be a bool\"",
")",
"for",
"dist",
"in",
"sorted",
"(",
"(",
"d",... | Generator over the times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False`` | [
"Generator",
"over",
"the",
"times",
"of",
"successive",
"coalescence",
"events"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L100-L109 | train | 32,800 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.coalescence_waiting_times | def coalescence_waiting_times(self, backward=True):
'''Generator over the waiting times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
'''
if not isinstance(backward, bool):
raise TypeError("backward must be a bool")
times = list(); lowest_leaf_dist = float('-inf')
for n,d in self.distances_from_root():
if len(n.children) > 1:
times.append(d)
elif len(n.children) == 0 and d > lowest_leaf_dist:
lowest_leaf_dist = d
times.append(lowest_leaf_dist)
times.sort(reverse=backward)
for i in range(len(times)-1):
yield abs(times[i]-times[i+1]) | python | def coalescence_waiting_times(self, backward=True):
'''Generator over the waiting times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
'''
if not isinstance(backward, bool):
raise TypeError("backward must be a bool")
times = list(); lowest_leaf_dist = float('-inf')
for n,d in self.distances_from_root():
if len(n.children) > 1:
times.append(d)
elif len(n.children) == 0 and d > lowest_leaf_dist:
lowest_leaf_dist = d
times.append(lowest_leaf_dist)
times.sort(reverse=backward)
for i in range(len(times)-1):
yield abs(times[i]-times[i+1]) | [
"def",
"coalescence_waiting_times",
"(",
"self",
",",
"backward",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"backward",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"backward must be a bool\"",
")",
"times",
"=",
"list",
"(",
")",
"lowest... | Generator over the waiting times of successive coalescence events
Args:
``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False`` | [
"Generator",
"over",
"the",
"waiting",
"times",
"of",
"successive",
"coalescence",
"events"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L111-L128 | train | 32,801 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.colless | def colless(self, normalize='leaves'):
'''Compute the Colless balance index of this ``Tree``. If the tree has polytomies, they will be randomly resolved
Args:
``normalize`` (``str``): How to normalize the Colless index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable Arrangements model
Returns:
``float``: Colless index (either normalized or not)
'''
t_res = copy(self); t_res.resolve_polytomies(); leaves_below = dict(); n = 0; I = 0
for node in t_res.traverse_postorder():
if node.is_leaf():
leaves_below[node] = 1; n += 1
else:
cl,cr = node.children; nl = leaves_below[cl]; nr = leaves_below[cr]
leaves_below[node] = nl+nr; I += abs(nl-nr)
if normalize is None or normalize is False:
return I
elif not isinstance(normalize,str):
raise TypeError("normalize must be None or a string")
normalize = normalize.lower()
if normalize == 'leaves':
return (2.*I)/((n-1)*(n-2))
elif normalize == 'yule':
return (I - n*log(n) - n*(EULER_GAMMA-1-log(2)))/n
elif normalize == 'pda':
return I/(n**1.5)
else:
raise RuntimeError("normalize must be None, 'leaves', 'yule', or 'pda'") | python | def colless(self, normalize='leaves'):
'''Compute the Colless balance index of this ``Tree``. If the tree has polytomies, they will be randomly resolved
Args:
``normalize`` (``str``): How to normalize the Colless index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable Arrangements model
Returns:
``float``: Colless index (either normalized or not)
'''
t_res = copy(self); t_res.resolve_polytomies(); leaves_below = dict(); n = 0; I = 0
for node in t_res.traverse_postorder():
if node.is_leaf():
leaves_below[node] = 1; n += 1
else:
cl,cr = node.children; nl = leaves_below[cl]; nr = leaves_below[cr]
leaves_below[node] = nl+nr; I += abs(nl-nr)
if normalize is None or normalize is False:
return I
elif not isinstance(normalize,str):
raise TypeError("normalize must be None or a string")
normalize = normalize.lower()
if normalize == 'leaves':
return (2.*I)/((n-1)*(n-2))
elif normalize == 'yule':
return (I - n*log(n) - n*(EULER_GAMMA-1-log(2)))/n
elif normalize == 'pda':
return I/(n**1.5)
else:
raise RuntimeError("normalize must be None, 'leaves', 'yule', or 'pda'") | [
"def",
"colless",
"(",
"self",
",",
"normalize",
"=",
"'leaves'",
")",
":",
"t_res",
"=",
"copy",
"(",
"self",
")",
"t_res",
".",
"resolve_polytomies",
"(",
")",
"leaves_below",
"=",
"dict",
"(",
")",
"n",
"=",
"0",
"I",
"=",
"0",
"for",
"node",
"i... | Compute the Colless balance index of this ``Tree``. If the tree has polytomies, they will be randomly resolved
Args:
``normalize`` (``str``): How to normalize the Colless index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable Arrangements model
Returns:
``float``: Colless index (either normalized or not) | [
"Compute",
"the",
"Colless",
"balance",
"index",
"of",
"this",
"Tree",
".",
"If",
"the",
"tree",
"has",
"polytomies",
"they",
"will",
"be",
"randomly",
"resolved"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L152-L188 | train | 32,802 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.condense | def condense(self):
'''If siblings have the same label, merge them. If they have edge lengths, the resulting ``Node`` will have the larger of the lengths'''
self.resolve_polytomies(); labels_below = dict(); longest_leaf_dist = dict()
for node in self.traverse_postorder():
if node.is_leaf():
labels_below[node] = [node.label]; longest_leaf_dist[node] = None
else:
labels_below[node] = set()
for c in node.children:
labels_below[node].update(labels_below[c])
d = longest_leaf_dist[c]
if c.edge_length is not None:
if d is None:
d = 0
d += c.edge_length
if node not in longest_leaf_dist or longest_leaf_dist[node] is None or (d is not None and d > longest_leaf_dist[node]):
longest_leaf_dist[node] = d
nodes = deque(); nodes.append(self.root)
while len(nodes) != 0:
node = nodes.pop()
if node.is_leaf():
continue
if len(labels_below[node]) == 1:
node.label = labels_below[node].pop(); node.children = list()
if longest_leaf_dist[node] is not None:
if node.edge_length is None:
node.edge_length = 0
node.edge_length += longest_leaf_dist[node]
else:
nodes.extend(node.children) | python | def condense(self):
'''If siblings have the same label, merge them. If they have edge lengths, the resulting ``Node`` will have the larger of the lengths'''
self.resolve_polytomies(); labels_below = dict(); longest_leaf_dist = dict()
for node in self.traverse_postorder():
if node.is_leaf():
labels_below[node] = [node.label]; longest_leaf_dist[node] = None
else:
labels_below[node] = set()
for c in node.children:
labels_below[node].update(labels_below[c])
d = longest_leaf_dist[c]
if c.edge_length is not None:
if d is None:
d = 0
d += c.edge_length
if node not in longest_leaf_dist or longest_leaf_dist[node] is None or (d is not None and d > longest_leaf_dist[node]):
longest_leaf_dist[node] = d
nodes = deque(); nodes.append(self.root)
while len(nodes) != 0:
node = nodes.pop()
if node.is_leaf():
continue
if len(labels_below[node]) == 1:
node.label = labels_below[node].pop(); node.children = list()
if longest_leaf_dist[node] is not None:
if node.edge_length is None:
node.edge_length = 0
node.edge_length += longest_leaf_dist[node]
else:
nodes.extend(node.children) | [
"def",
"condense",
"(",
"self",
")",
":",
"self",
".",
"resolve_polytomies",
"(",
")",
"labels_below",
"=",
"dict",
"(",
")",
"longest_leaf_dist",
"=",
"dict",
"(",
")",
"for",
"node",
"in",
"self",
".",
"traverse_postorder",
"(",
")",
":",
"if",
"node",... | If siblings have the same label, merge them. If they have edge lengths, the resulting ``Node`` will have the larger of the lengths | [
"If",
"siblings",
"have",
"the",
"same",
"label",
"merge",
"them",
".",
"If",
"they",
"have",
"edge",
"lengths",
"the",
"resulting",
"Node",
"will",
"have",
"the",
"larger",
"of",
"the",
"lengths"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L190-L219 | train | 32,803 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.deroot | def deroot(self, label='OLDROOT'):
'''If the tree has a root edge, drop the edge to be a child of the root node
Args:
``label`` (``str``): The desired label of the new child
'''
if self.root.edge_length is not None:
self.root.add_child(Node(edge_length=self.root.edge_length,label=label))
self.root.edge_length = None | python | def deroot(self, label='OLDROOT'):
'''If the tree has a root edge, drop the edge to be a child of the root node
Args:
``label`` (``str``): The desired label of the new child
'''
if self.root.edge_length is not None:
self.root.add_child(Node(edge_length=self.root.edge_length,label=label))
self.root.edge_length = None | [
"def",
"deroot",
"(",
"self",
",",
"label",
"=",
"'OLDROOT'",
")",
":",
"if",
"self",
".",
"root",
".",
"edge_length",
"is",
"not",
"None",
":",
"self",
".",
"root",
".",
"add_child",
"(",
"Node",
"(",
"edge_length",
"=",
"self",
".",
"root",
".",
... | If the tree has a root edge, drop the edge to be a child of the root node
Args:
``label`` (``str``): The desired label of the new child | [
"If",
"the",
"tree",
"has",
"a",
"root",
"edge",
"drop",
"the",
"edge",
"to",
"be",
"a",
"child",
"of",
"the",
"root",
"node"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L238-L246 | train | 32,804 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.distance_between | def distance_between(self, u, v):
'''Return the distance between nodes ``u`` and ``v`` in this ``Tree``
Args:
``u`` (``Node``): Node ``u``
``v`` (``Node``): Node ``v``
Returns:
``float``: The distance between nodes ``u`` and ``v``
'''
if not isinstance(u, Node):
raise TypeError("u must be a Node")
if not isinstance(v, Node):
raise TypeError("v must be a Node")
if u == v:
return 0.
u_dists = {u:0.}; v_dists = {v:0.}
c = u; p = u.parent # u traversal
while p is not None:
u_dists[p] = u_dists[c]
if c.edge_length is not None:
u_dists[p] += c.edge_length
c = p; p = p.parent
c = v; p = v.parent # v traversal
while p is not None:
v_dists[p] = v_dists[c]
if c.edge_length is not None:
v_dists[p] += c.edge_length
if p in u_dists:
return u_dists[p] + v_dists[p]
c = p; p = p.parent
raise RuntimeError("u and v are not in the same Tree") | python | def distance_between(self, u, v):
'''Return the distance between nodes ``u`` and ``v`` in this ``Tree``
Args:
``u`` (``Node``): Node ``u``
``v`` (``Node``): Node ``v``
Returns:
``float``: The distance between nodes ``u`` and ``v``
'''
if not isinstance(u, Node):
raise TypeError("u must be a Node")
if not isinstance(v, Node):
raise TypeError("v must be a Node")
if u == v:
return 0.
u_dists = {u:0.}; v_dists = {v:0.}
c = u; p = u.parent # u traversal
while p is not None:
u_dists[p] = u_dists[c]
if c.edge_length is not None:
u_dists[p] += c.edge_length
c = p; p = p.parent
c = v; p = v.parent # v traversal
while p is not None:
v_dists[p] = v_dists[c]
if c.edge_length is not None:
v_dists[p] += c.edge_length
if p in u_dists:
return u_dists[p] + v_dists[p]
c = p; p = p.parent
raise RuntimeError("u and v are not in the same Tree") | [
"def",
"distance_between",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"if",
"not",
"isinstance",
"(",
"u",
",",
"Node",
")",
":",
"raise",
"TypeError",
"(",
"\"u must be a Node\"",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"Node",
")",
":",
"rai... | Return the distance between nodes ``u`` and ``v`` in this ``Tree``
Args:
``u`` (``Node``): Node ``u``
``v`` (``Node``): Node ``v``
Returns:
``float``: The distance between nodes ``u`` and ``v`` | [
"Return",
"the",
"distance",
"between",
"nodes",
"u",
"and",
"v",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L265-L297 | train | 32,805 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.edge_length_sum | def edge_length_sum(self, terminal=True, internal=True):
'''Compute the sum of all selected edge lengths in this ``Tree``
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
Returns:
``float``: Sum of all selected edge lengths in this ``Tree``
'''
if not isinstance(terminal, bool):
raise TypeError("leaves must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
return sum(node.edge_length for node in self.traverse_preorder() if node.edge_length is not None and ((terminal and node.is_leaf()) or (internal and not node.is_leaf()))) | python | def edge_length_sum(self, terminal=True, internal=True):
'''Compute the sum of all selected edge lengths in this ``Tree``
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
Returns:
``float``: Sum of all selected edge lengths in this ``Tree``
'''
if not isinstance(terminal, bool):
raise TypeError("leaves must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
return sum(node.edge_length for node in self.traverse_preorder() if node.edge_length is not None and ((terminal and node.is_leaf()) or (internal and not node.is_leaf()))) | [
"def",
"edge_length_sum",
"(",
"self",
",",
"terminal",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"terminal",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"leaves must be a bool\"",
")",
"if",
"not",
"isins... | Compute the sum of all selected edge lengths in this ``Tree``
Args:
``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False``
Returns:
``float``: Sum of all selected edge lengths in this ``Tree`` | [
"Compute",
"the",
"sum",
"of",
"all",
"selected",
"edge",
"lengths",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L391-L406 | train | 32,806 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.extract_subtree | def extract_subtree(self, node):
'''Return a copy of the subtree rooted at ``node``
Args:
``node`` (``Node``): The root of the desired subtree
Returns:
``Tree``: A copy of the subtree rooted at ``node``
'''
if not isinstance(node, Node):
raise TypeError("node must be a Node")
r = self.root; self.root = node; o = copy(self); self.root = r; return o | python | def extract_subtree(self, node):
'''Return a copy of the subtree rooted at ``node``
Args:
``node`` (``Node``): The root of the desired subtree
Returns:
``Tree``: A copy of the subtree rooted at ``node``
'''
if not isinstance(node, Node):
raise TypeError("node must be a Node")
r = self.root; self.root = node; o = copy(self); self.root = r; return o | [
"def",
"extract_subtree",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"Node",
")",
":",
"raise",
"TypeError",
"(",
"\"node must be a Node\"",
")",
"r",
"=",
"self",
".",
"root",
"self",
".",
"root",
"=",
"node",
"o"... | Return a copy of the subtree rooted at ``node``
Args:
``node`` (``Node``): The root of the desired subtree
Returns:
``Tree``: A copy of the subtree rooted at ``node`` | [
"Return",
"a",
"copy",
"of",
"the",
"subtree",
"rooted",
"at",
"node"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L408-L419 | train | 32,807 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.extract_tree_without | def extract_tree_without(self, labels, suppress_unifurcations=True):
'''Extract a copy of this ``Tree`` without the leaves labeled by the strings in ``labels``
Args:
``labels`` (``set``): Set of leaf labels to exclude
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
``Tree``: Copy of this ``Tree``, exluding the leaves labeled by the strings in ``labels``
'''
return self.extract_tree(labels, True, suppress_unifurcations) | python | def extract_tree_without(self, labels, suppress_unifurcations=True):
'''Extract a copy of this ``Tree`` without the leaves labeled by the strings in ``labels``
Args:
``labels`` (``set``): Set of leaf labels to exclude
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
``Tree``: Copy of this ``Tree``, exluding the leaves labeled by the strings in ``labels``
'''
return self.extract_tree(labels, True, suppress_unifurcations) | [
"def",
"extract_tree_without",
"(",
"self",
",",
"labels",
",",
"suppress_unifurcations",
"=",
"True",
")",
":",
"return",
"self",
".",
"extract_tree",
"(",
"labels",
",",
"True",
",",
"suppress_unifurcations",
")"
] | Extract a copy of this ``Tree`` without the leaves labeled by the strings in ``labels``
Args:
``labels`` (``set``): Set of leaf labels to exclude
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
``Tree``: Copy of this ``Tree``, exluding the leaves labeled by the strings in ``labels`` | [
"Extract",
"a",
"copy",
"of",
"this",
"Tree",
"without",
"the",
"leaves",
"labeled",
"by",
"the",
"strings",
"in",
"labels"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L451-L462 | train | 32,808 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.extract_tree_with | def extract_tree_with(self, labels, suppress_unifurcations=True):
'''Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels``
Args:
``leaves`` (``set``): Set of leaf labels to include.
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
Tree: Copy of this Tree, including only the leaves labeled by the strings in ``labels``
'''
return self.extract_tree(labels, False, suppress_unifurcations) | python | def extract_tree_with(self, labels, suppress_unifurcations=True):
'''Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels``
Args:
``leaves`` (``set``): Set of leaf labels to include.
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
Tree: Copy of this Tree, including only the leaves labeled by the strings in ``labels``
'''
return self.extract_tree(labels, False, suppress_unifurcations) | [
"def",
"extract_tree_with",
"(",
"self",
",",
"labels",
",",
"suppress_unifurcations",
"=",
"True",
")",
":",
"return",
"self",
".",
"extract_tree",
"(",
"labels",
",",
"False",
",",
"suppress_unifurcations",
")"
] | Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels``
Args:
``leaves`` (``set``): Set of leaf labels to include.
``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False``
Returns:
Tree: Copy of this Tree, including only the leaves labeled by the strings in ``labels`` | [
"Extract",
"a",
"copy",
"of",
"this",
"Tree",
"with",
"only",
"the",
"leaves",
"labeled",
"by",
"the",
"strings",
"in",
"labels"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L464-L475 | train | 32,809 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.furthest_from_root | def furthest_from_root(self):
'''Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding distance
'''
best = (self.root,0); d = dict()
for node in self.traverse_preorder():
if node.edge_length is None:
d[node] = 0
else:
d[node] = node.edge_length
if not node.is_root():
d[node] += d[node.parent]
if d[node] > best[1]:
best = (node,d[node])
return best | python | def furthest_from_root(self):
'''Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding distance
'''
best = (self.root,0); d = dict()
for node in self.traverse_preorder():
if node.edge_length is None:
d[node] = 0
else:
d[node] = node.edge_length
if not node.is_root():
d[node] += d[node.parent]
if d[node] > best[1]:
best = (node,d[node])
return best | [
"def",
"furthest_from_root",
"(",
"self",
")",
":",
"best",
"=",
"(",
"self",
".",
"root",
",",
"0",
")",
"d",
"=",
"dict",
"(",
")",
"for",
"node",
"in",
"self",
".",
"traverse_preorder",
"(",
")",
":",
"if",
"node",
".",
"edge_length",
"is",
"Non... | Return the ``Node`` that is furthest from the root and the corresponding distance. Edges with no length will be considered to have a length of 0
Returns:
``tuple``: First value is the furthest ``Node`` from the root, and second value is the corresponding distance | [
"Return",
"the",
"Node",
"that",
"is",
"furthest",
"from",
"the",
"root",
"and",
"the",
"corresponding",
"distance",
".",
"Edges",
"with",
"no",
"length",
"will",
"be",
"considered",
"to",
"have",
"a",
"length",
"of",
"0"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L477-L493 | train | 32,810 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.indent | def indent(self, space=4):
'''Return an indented Newick string, just like ``nw_indent`` in Newick Utilities
Args:
``space`` (``int``): The number of spaces a tab should equal
Returns:
``str``: An indented Newick string
'''
if not isinstance(space,int):
raise TypeError("space must be an int")
if space < 0:
raise ValueError("space must be a non-negative integer")
space = ' '*space; o = []; l = 0
for c in self.newick():
if c == '(':
o.append('(\n'); l += 1; o.append(space*l)
elif c == ')':
o.append('\n'); l -= 1; o.append(space*l); o.append(')')
elif c == ',':
o.append(',\n'); o.append(space*l)
else:
o.append(c)
return ''.join(o) | python | def indent(self, space=4):
'''Return an indented Newick string, just like ``nw_indent`` in Newick Utilities
Args:
``space`` (``int``): The number of spaces a tab should equal
Returns:
``str``: An indented Newick string
'''
if not isinstance(space,int):
raise TypeError("space must be an int")
if space < 0:
raise ValueError("space must be a non-negative integer")
space = ' '*space; o = []; l = 0
for c in self.newick():
if c == '(':
o.append('(\n'); l += 1; o.append(space*l)
elif c == ')':
o.append('\n'); l -= 1; o.append(space*l); o.append(')')
elif c == ',':
o.append(',\n'); o.append(space*l)
else:
o.append(c)
return ''.join(o) | [
"def",
"indent",
"(",
"self",
",",
"space",
"=",
"4",
")",
":",
"if",
"not",
"isinstance",
"(",
"space",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"space must be an int\"",
")",
"if",
"space",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"spac... | Return an indented Newick string, just like ``nw_indent`` in Newick Utilities
Args:
``space`` (``int``): The number of spaces a tab should equal
Returns:
``str``: An indented Newick string | [
"Return",
"an",
"indented",
"Newick",
"string",
"just",
"like",
"nw_indent",
"in",
"Newick",
"Utilities"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L525-L548 | train | 32,811 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.lineages_through_time | def lineages_through_time(self, present_day=None, show_plot=True, color='#000000', xmin=None, xmax=None, ymin=None, ymax=None, title=None, xlabel=None, ylabel=None):
'''Compute the number of lineages through time. If seaborn is installed, a plot is shown as well
Args:
``present_day`` (``float``): The time of the furthest node from the root. If ``None``, the top of the tree will be placed at time 0
``show_plot`` (``bool``): ``True`` to show the plot, otherwise ``False`` to only return the dictionary. To plot multiple LTTs on the same figure, set ``show_plot`` to False for all but the last plot
``color`` (``str``): The color of the resulting plot
``title`` (``str``): The title of the resulting plot
``xmin`` (``float``): The minimum value of the horizontal axis in the resulting plot
``xmax`` (``float``): The maximum value of the horizontal axis in the resulting plot
``xlabel`` (``str``): The label of the horizontal axis in the resulting plot
``ymin`` (``float``): The minimum value of the vertical axis in the resulting plot
``ymax`` (``float``): The maximum value of the vertical axis in the resulting plot
``ylabel`` (``str``): The label of the vertical axis in the resulting plot
Returns:
``dict``: A dictionary in which each ``(t,n)`` pair denotes the number of lineages ``n`` that existed at time ``t``
'''
if present_day is not None and not isinstance(present_day,int) and not isinstance(present_day,float):
raise TypeError("present_day must be a float")
time = dict()
if self.root.edge_length is None:
tmproot = self.root
else:
tmproot = Node(); tmproot.add_child(self.root)
for node in tmproot.traverse_preorder():
if node.is_root():
time[node] = 0.
else:
time[node] = time[node.parent]
if node.edge_length is not None:
time[node] += node.edge_length
nodes = sorted((time[node],node) for node in time)
lineages = {nodes[0][0]:0}
for i in range(len(nodes)):
if nodes[i][0] not in lineages:
lineages[nodes[i][0]] = lineages[nodes[i-1][0]]
if nodes[i][1].edge_length is not None:
if nodes[i][1].edge_length >= 0:
lineages[nodes[i][0]] -= 1
else:
lineages[nodes[i][0]] += 1
for c in nodes[i][1].children:
if c.edge_length >= 0:
lineages[nodes[i][0]] += 1
else:
lineages[nodes[i][0]] -= 1
if present_day is not None:
shift = present_day - max(lineages.keys())
else:
shift = max(0,-min(lineages.keys()))
if shift != 0:
tmp = dict()
for t in lineages:
tmp[t+shift] = lineages[t]
lineages = tmp
if tmproot != self.root:
self.root.parent = None
try:
plot_ltt(lineages, show_plot=show_plot, color=color, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, title=title, xlabel=xlabel, ylabel=ylabel)
except Exception as e:
warn("Unable to produce visualization (but dictionary will still be returned)"); print(e)
return lineages | python | def lineages_through_time(self, present_day=None, show_plot=True, color='#000000', xmin=None, xmax=None, ymin=None, ymax=None, title=None, xlabel=None, ylabel=None):
'''Compute the number of lineages through time. If seaborn is installed, a plot is shown as well
Args:
``present_day`` (``float``): The time of the furthest node from the root. If ``None``, the top of the tree will be placed at time 0
``show_plot`` (``bool``): ``True`` to show the plot, otherwise ``False`` to only return the dictionary. To plot multiple LTTs on the same figure, set ``show_plot`` to False for all but the last plot
``color`` (``str``): The color of the resulting plot
``title`` (``str``): The title of the resulting plot
``xmin`` (``float``): The minimum value of the horizontal axis in the resulting plot
``xmax`` (``float``): The maximum value of the horizontal axis in the resulting plot
``xlabel`` (``str``): The label of the horizontal axis in the resulting plot
``ymin`` (``float``): The minimum value of the vertical axis in the resulting plot
``ymax`` (``float``): The maximum value of the vertical axis in the resulting plot
``ylabel`` (``str``): The label of the vertical axis in the resulting plot
Returns:
``dict``: A dictionary in which each ``(t,n)`` pair denotes the number of lineages ``n`` that existed at time ``t``
'''
if present_day is not None and not isinstance(present_day,int) and not isinstance(present_day,float):
raise TypeError("present_day must be a float")
time = dict()
if self.root.edge_length is None:
tmproot = self.root
else:
tmproot = Node(); tmproot.add_child(self.root)
for node in tmproot.traverse_preorder():
if node.is_root():
time[node] = 0.
else:
time[node] = time[node.parent]
if node.edge_length is not None:
time[node] += node.edge_length
nodes = sorted((time[node],node) for node in time)
lineages = {nodes[0][0]:0}
for i in range(len(nodes)):
if nodes[i][0] not in lineages:
lineages[nodes[i][0]] = lineages[nodes[i-1][0]]
if nodes[i][1].edge_length is not None:
if nodes[i][1].edge_length >= 0:
lineages[nodes[i][0]] -= 1
else:
lineages[nodes[i][0]] += 1
for c in nodes[i][1].children:
if c.edge_length >= 0:
lineages[nodes[i][0]] += 1
else:
lineages[nodes[i][0]] -= 1
if present_day is not None:
shift = present_day - max(lineages.keys())
else:
shift = max(0,-min(lineages.keys()))
if shift != 0:
tmp = dict()
for t in lineages:
tmp[t+shift] = lineages[t]
lineages = tmp
if tmproot != self.root:
self.root.parent = None
try:
plot_ltt(lineages, show_plot=show_plot, color=color, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, title=title, xlabel=xlabel, ylabel=ylabel)
except Exception as e:
warn("Unable to produce visualization (but dictionary will still be returned)"); print(e)
return lineages | [
"def",
"lineages_through_time",
"(",
"self",
",",
"present_day",
"=",
"None",
",",
"show_plot",
"=",
"True",
",",
"color",
"=",
"'#000000'",
",",
"xmin",
"=",
"None",
",",
"xmax",
"=",
"None",
",",
"ymin",
"=",
"None",
",",
"ymax",
"=",
"None",
",",
... | Compute the number of lineages through time. If seaborn is installed, a plot is shown as well
Args:
``present_day`` (``float``): The time of the furthest node from the root. If ``None``, the top of the tree will be placed at time 0
``show_plot`` (``bool``): ``True`` to show the plot, otherwise ``False`` to only return the dictionary. To plot multiple LTTs on the same figure, set ``show_plot`` to False for all but the last plot
``color`` (``str``): The color of the resulting plot
``title`` (``str``): The title of the resulting plot
``xmin`` (``float``): The minimum value of the horizontal axis in the resulting plot
``xmax`` (``float``): The maximum value of the horizontal axis in the resulting plot
``xlabel`` (``str``): The label of the horizontal axis in the resulting plot
``ymin`` (``float``): The minimum value of the vertical axis in the resulting plot
``ymax`` (``float``): The maximum value of the vertical axis in the resulting plot
``ylabel`` (``str``): The label of the vertical axis in the resulting plot
Returns:
``dict``: A dictionary in which each ``(t,n)`` pair denotes the number of lineages ``n`` that existed at time ``t`` | [
"Compute",
"the",
"number",
"of",
"lineages",
"through",
"time",
".",
"If",
"seaborn",
"is",
"installed",
"a",
"plot",
"is",
"shown",
"as",
"well"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L615-L686 | train | 32,812 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.newick | def newick(self):
'''Output this ``Tree`` as a Newick string
Returns:
``str``: Newick string of this ``Tree``
'''
if self.root.edge_length is None:
suffix = ';'
elif isinstance(self.root.edge_length,int):
suffix = ':%d;' % self.root.edge_length
elif isinstance(self.root.edge_length,float) and self.root.edge_length.is_integer():
suffix = ':%d;' % int(self.root.edge_length)
else:
suffix = ':%s;' % str(self.root.edge_length)
if self.is_rooted:
return '[&R] %s%s' % (self.root.newick(),suffix)
else:
return '%s%s' % (self.root.newick(),suffix) | python | def newick(self):
'''Output this ``Tree`` as a Newick string
Returns:
``str``: Newick string of this ``Tree``
'''
if self.root.edge_length is None:
suffix = ';'
elif isinstance(self.root.edge_length,int):
suffix = ':%d;' % self.root.edge_length
elif isinstance(self.root.edge_length,float) and self.root.edge_length.is_integer():
suffix = ':%d;' % int(self.root.edge_length)
else:
suffix = ':%s;' % str(self.root.edge_length)
if self.is_rooted:
return '[&R] %s%s' % (self.root.newick(),suffix)
else:
return '%s%s' % (self.root.newick(),suffix) | [
"def",
"newick",
"(",
"self",
")",
":",
"if",
"self",
".",
"root",
".",
"edge_length",
"is",
"None",
":",
"suffix",
"=",
"';'",
"elif",
"isinstance",
"(",
"self",
".",
"root",
".",
"edge_length",
",",
"int",
")",
":",
"suffix",
"=",
"':%d;'",
"%",
... | Output this ``Tree`` as a Newick string
Returns:
``str``: Newick string of this ``Tree`` | [
"Output",
"this",
"Tree",
"as",
"a",
"Newick",
"string"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L738-L755 | train | 32,813 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.num_lineages_at | def num_lineages_at(self, distance):
'''Returns the number of lineages of this ``Tree`` that exist ``distance`` away from the root
Args:
``distance`` (``float``): The distance away from the root
Returns:
``int``: The number of lineages that exist ``distance`` away from the root
'''
if not isinstance(distance, float) and not isinstance(distance, int):
raise TypeError("distance must be an int or a float")
if distance < 0:
raise RuntimeError("distance cannot be negative")
d = dict(); q = deque(); q.append(self.root); count = 0
while len(q) != 0:
node = q.popleft()
if node.is_root():
d[node] = 0
else:
d[node] = d[node.parent]
if node.edge_length is not None:
d[node] += node.edge_length
if d[node] < distance:
q.extend(node.children)
elif node.parent is None or d[node.parent] < distance:
count += 1
return count | python | def num_lineages_at(self, distance):
'''Returns the number of lineages of this ``Tree`` that exist ``distance`` away from the root
Args:
``distance`` (``float``): The distance away from the root
Returns:
``int``: The number of lineages that exist ``distance`` away from the root
'''
if not isinstance(distance, float) and not isinstance(distance, int):
raise TypeError("distance must be an int or a float")
if distance < 0:
raise RuntimeError("distance cannot be negative")
d = dict(); q = deque(); q.append(self.root); count = 0
while len(q) != 0:
node = q.popleft()
if node.is_root():
d[node] = 0
else:
d[node] = d[node.parent]
if node.edge_length is not None:
d[node] += node.edge_length
if d[node] < distance:
q.extend(node.children)
elif node.parent is None or d[node.parent] < distance:
count += 1
return count | [
"def",
"num_lineages_at",
"(",
"self",
",",
"distance",
")",
":",
"if",
"not",
"isinstance",
"(",
"distance",
",",
"float",
")",
"and",
"not",
"isinstance",
"(",
"distance",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"distance must be an int or a float... | Returns the number of lineages of this ``Tree`` that exist ``distance`` away from the root
Args:
``distance`` (``float``): The distance away from the root
Returns:
``int``: The number of lineages that exist ``distance`` away from the root | [
"Returns",
"the",
"number",
"of",
"lineages",
"of",
"this",
"Tree",
"that",
"exist",
"distance",
"away",
"from",
"the",
"root"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L757-L783 | train | 32,814 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.num_nodes | def num_nodes(self, leaves=True, internal=True):
'''Compute the total number of selected nodes in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
Returns:
``int``: The total number of selected nodes in this ``Tree``
'''
if not isinstance(leaves, bool):
raise TypeError("leaves must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
num = 0
for node in self.traverse_preorder():
if (leaves and node.is_leaf()) or (internal and not node.is_leaf()):
num += 1
return num | python | def num_nodes(self, leaves=True, internal=True):
'''Compute the total number of selected nodes in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
Returns:
``int``: The total number of selected nodes in this ``Tree``
'''
if not isinstance(leaves, bool):
raise TypeError("leaves must be a bool")
if not isinstance(internal, bool):
raise TypeError("internal must be a bool")
num = 0
for node in self.traverse_preorder():
if (leaves and node.is_leaf()) or (internal and not node.is_leaf()):
num += 1
return num | [
"def",
"num_nodes",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"leaves",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"leaves must be a bool\"",
")",
"if",
"not",
"isinstance",
... | Compute the total number of selected nodes in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
Returns:
``int``: The total number of selected nodes in this ``Tree`` | [
"Compute",
"the",
"total",
"number",
"of",
"selected",
"nodes",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L785-L804 | train | 32,815 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.rename_nodes | def rename_nodes(self, renaming_map):
'''Rename nodes in this ``Tree``
Args:
``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values)
'''
if not isinstance(renaming_map, dict):
raise TypeError("renaming_map must be a dict")
for node in self.traverse_preorder():
if node.label in renaming_map:
node.label = renaming_map[node.label] | python | def rename_nodes(self, renaming_map):
'''Rename nodes in this ``Tree``
Args:
``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values)
'''
if not isinstance(renaming_map, dict):
raise TypeError("renaming_map must be a dict")
for node in self.traverse_preorder():
if node.label in renaming_map:
node.label = renaming_map[node.label] | [
"def",
"rename_nodes",
"(",
"self",
",",
"renaming_map",
")",
":",
"if",
"not",
"isinstance",
"(",
"renaming_map",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"renaming_map must be a dict\"",
")",
"for",
"node",
"in",
"self",
".",
"traverse_preorder",
... | Rename nodes in this ``Tree``
Args:
``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values) | [
"Rename",
"nodes",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L890-L900 | train | 32,816 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.sackin | def sackin(self, normalize='leaves'):
'''Compute the Sackin balance index of this ``Tree``
Args:
``normalize`` (``str``): How to normalize the Sackin index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable Arrangements model
Returns:
``float``: Sackin index (either normalized or not)
'''
num_nodes_from_root = dict(); sackin = 0; num_leaves = 0
for node in self.traverse_preorder():
num_nodes_from_root[node] = 1
if not node.is_root():
num_nodes_from_root[node] += num_nodes_from_root[node.parent]
if node.is_leaf():
num_nodes_from_root[node] -= 1; sackin += num_nodes_from_root[node]; num_leaves += 1
if normalize is None or normalize is False:
return sackin
elif not isinstance(normalize,str):
raise TypeError("normalize must be None or a string")
normalize = normalize.lower()
if normalize == 'leaves':
return float(sackin)/num_leaves
elif normalize == 'yule':
x = sum(1./i for i in range(2, num_leaves+1))
return (sackin - (2*num_leaves*x)) / num_leaves
elif normalize == 'pda':
return sackin/(num_leaves**1.5)
else:
raise RuntimeError("normalize must be None, 'leaves', 'yule', or 'pda'") | python | def sackin(self, normalize='leaves'):
'''Compute the Sackin balance index of this ``Tree``
Args:
``normalize`` (``str``): How to normalize the Sackin index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable Arrangements model
Returns:
``float``: Sackin index (either normalized or not)
'''
num_nodes_from_root = dict(); sackin = 0; num_leaves = 0
for node in self.traverse_preorder():
num_nodes_from_root[node] = 1
if not node.is_root():
num_nodes_from_root[node] += num_nodes_from_root[node.parent]
if node.is_leaf():
num_nodes_from_root[node] -= 1; sackin += num_nodes_from_root[node]; num_leaves += 1
if normalize is None or normalize is False:
return sackin
elif not isinstance(normalize,str):
raise TypeError("normalize must be None or a string")
normalize = normalize.lower()
if normalize == 'leaves':
return float(sackin)/num_leaves
elif normalize == 'yule':
x = sum(1./i for i in range(2, num_leaves+1))
return (sackin - (2*num_leaves*x)) / num_leaves
elif normalize == 'pda':
return sackin/(num_leaves**1.5)
else:
raise RuntimeError("normalize must be None, 'leaves', 'yule', or 'pda'") | [
"def",
"sackin",
"(",
"self",
",",
"normalize",
"=",
"'leaves'",
")",
":",
"num_nodes_from_root",
"=",
"dict",
"(",
")",
"sackin",
"=",
"0",
"num_leaves",
"=",
"0",
"for",
"node",
"in",
"self",
".",
"traverse_preorder",
"(",
")",
":",
"num_nodes_from_root"... | Compute the Sackin balance index of this ``Tree``
Args:
``normalize`` (``str``): How to normalize the Sackin index (if at all)
* ``None`` to not normalize
* ``"leaves"`` to normalize by the number of leaves
* ``"yule"`` to normalize to the Yule model
* ``"pda"`` to normalize to the Proportional to Distinguishable Arrangements model
Returns:
``float``: Sackin index (either normalized or not) | [
"Compute",
"the",
"Sackin",
"balance",
"index",
"of",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L947-L984 | train | 32,817 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.scale_edges | def scale_edges(self, multiplier):
'''Multiply all edges in this ``Tree`` by ``multiplier``'''
if not isinstance(multiplier,int) and not isinstance(multiplier,float):
raise TypeError("multiplier must be an int or float")
for node in self.traverse_preorder():
if node.edge_length is not None:
node.edge_length *= multiplier | python | def scale_edges(self, multiplier):
'''Multiply all edges in this ``Tree`` by ``multiplier``'''
if not isinstance(multiplier,int) and not isinstance(multiplier,float):
raise TypeError("multiplier must be an int or float")
for node in self.traverse_preorder():
if node.edge_length is not None:
node.edge_length *= multiplier | [
"def",
"scale_edges",
"(",
"self",
",",
"multiplier",
")",
":",
"if",
"not",
"isinstance",
"(",
"multiplier",
",",
"int",
")",
"and",
"not",
"isinstance",
"(",
"multiplier",
",",
"float",
")",
":",
"raise",
"TypeError",
"(",
"\"multiplier must be an int or flo... | Multiply all edges in this ``Tree`` by ``multiplier`` | [
"Multiply",
"all",
"edges",
"in",
"this",
"Tree",
"by",
"multiplier"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L986-L992 | train | 32,818 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.suppress_unifurcations | def suppress_unifurcations(self):
'''Remove all nodes with only one child and directly attach child to parent'''
q = deque(); q.append(self.root)
while len(q) != 0:
node = q.popleft()
if len(node.children) != 1:
q.extend(node.children); continue
child = node.children.pop()
if node.is_root():
self.root = child; child.parent = None
else:
parent = node.parent; parent.remove_child(node); parent.add_child(child)
if node.edge_length is not None:
if child.edge_length is None:
child.edge_length = 0
child.edge_length += node.edge_length
if child.label is None and node.label is not None:
child.label = node.label
q.append(child) | python | def suppress_unifurcations(self):
'''Remove all nodes with only one child and directly attach child to parent'''
q = deque(); q.append(self.root)
while len(q) != 0:
node = q.popleft()
if len(node.children) != 1:
q.extend(node.children); continue
child = node.children.pop()
if node.is_root():
self.root = child; child.parent = None
else:
parent = node.parent; parent.remove_child(node); parent.add_child(child)
if node.edge_length is not None:
if child.edge_length is None:
child.edge_length = 0
child.edge_length += node.edge_length
if child.label is None and node.label is not None:
child.label = node.label
q.append(child) | [
"def",
"suppress_unifurcations",
"(",
"self",
")",
":",
"q",
"=",
"deque",
"(",
")",
"q",
".",
"append",
"(",
"self",
".",
"root",
")",
"while",
"len",
"(",
"q",
")",
"!=",
"0",
":",
"node",
"=",
"q",
".",
"popleft",
"(",
")",
"if",
"len",
"(",... | Remove all nodes with only one child and directly attach child to parent | [
"Remove",
"all",
"nodes",
"with",
"only",
"one",
"child",
"and",
"directly",
"attach",
"child",
"to",
"parent"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L994-L1012 | train | 32,819 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.traverse_inorder | def traverse_inorder(self, leaves=True, internal=True):
'''Perform an inorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
for node in self.root.traverse_inorder(leaves=leaves, internal=internal):
yield node | python | def traverse_inorder(self, leaves=True, internal=True):
'''Perform an inorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
for node in self.root.traverse_inorder(leaves=leaves, internal=internal):
yield node | [
"def",
"traverse_inorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"for",
"node",
"in",
"self",
".",
"root",
".",
"traverse_inorder",
"(",
"leaves",
"=",
"leaves",
",",
"internal",
"=",
"internal",
")",
":",
"yi... | Perform an inorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` | [
"Perform",
"an",
"inorder",
"traversal",
"of",
"the",
"Node",
"objects",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1014-L1023 | train | 32,820 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.traverse_levelorder | def traverse_levelorder(self, leaves=True, internal=True):
'''Perform a levelorder traversal of the ``Node`` objects in this ``Tree``'''
for node in self.root.traverse_levelorder(leaves=leaves, internal=internal):
yield node | python | def traverse_levelorder(self, leaves=True, internal=True):
'''Perform a levelorder traversal of the ``Node`` objects in this ``Tree``'''
for node in self.root.traverse_levelorder(leaves=leaves, internal=internal):
yield node | [
"def",
"traverse_levelorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"for",
"node",
"in",
"self",
".",
"root",
".",
"traverse_levelorder",
"(",
"leaves",
"=",
"leaves",
",",
"internal",
"=",
"internal",
")",
":",... | Perform a levelorder traversal of the ``Node`` objects in this ``Tree`` | [
"Perform",
"a",
"levelorder",
"traversal",
"of",
"the",
"Node",
"objects",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1035-L1038 | train | 32,821 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.traverse_postorder | def traverse_postorder(self, leaves=True, internal=True):
'''Perform a postorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
for node in self.root.traverse_postorder(leaves=leaves, internal=internal):
yield node | python | def traverse_postorder(self, leaves=True, internal=True):
'''Perform a postorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
for node in self.root.traverse_postorder(leaves=leaves, internal=internal):
yield node | [
"def",
"traverse_postorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"for",
"node",
"in",
"self",
".",
"root",
".",
"traverse_postorder",
"(",
"leaves",
"=",
"leaves",
",",
"internal",
"=",
"internal",
")",
":",
... | Perform a postorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` | [
"Perform",
"a",
"postorder",
"traversal",
"of",
"the",
"Node",
"objects",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1040-L1049 | train | 32,822 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.traverse_preorder | def traverse_preorder(self, leaves=True, internal=True):
'''Perform a preorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
for node in self.root.traverse_preorder(leaves=leaves, internal=internal):
yield node | python | def traverse_preorder(self, leaves=True, internal=True):
'''Perform a preorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
'''
for node in self.root.traverse_preorder(leaves=leaves, internal=internal):
yield node | [
"def",
"traverse_preorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"for",
"node",
"in",
"self",
".",
"root",
".",
"traverse_preorder",
"(",
"leaves",
"=",
"leaves",
",",
"internal",
"=",
"internal",
")",
":",
"... | Perform a preorder traversal of the ``Node`` objects in this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` | [
"Perform",
"a",
"preorder",
"traversal",
"of",
"the",
"Node",
"objects",
"in",
"this",
"Tree"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1051-L1060 | train | 32,823 |
niemasd/TreeSwift | treeswift/Tree.py | Tree.write_tree_newick | def write_tree_newick(self, filename, hide_rooted_prefix=False):
'''Write this ``Tree`` to a Newick file
Args:
``filename`` (``str``): Path to desired output file (plain-text or gzipped)
'''
if not isinstance(filename, str):
raise TypeError("filename must be a str")
treestr = self.newick()
if hide_rooted_prefix:
if treestr.startswith('[&R]'):
treestr = treestr[4:].strip()
else:
warn("Specified hide_rooted_prefix, but tree was not rooted")
if filename.lower().endswith('.gz'): # gzipped file
f = gopen(expanduser(filename),'wb',9); f.write(treestr.encode()); f.close()
else: # plain-text file
f = open(expanduser(filename),'w'); f.write(treestr); f.close() | python | def write_tree_newick(self, filename, hide_rooted_prefix=False):
'''Write this ``Tree`` to a Newick file
Args:
``filename`` (``str``): Path to desired output file (plain-text or gzipped)
'''
if not isinstance(filename, str):
raise TypeError("filename must be a str")
treestr = self.newick()
if hide_rooted_prefix:
if treestr.startswith('[&R]'):
treestr = treestr[4:].strip()
else:
warn("Specified hide_rooted_prefix, but tree was not rooted")
if filename.lower().endswith('.gz'): # gzipped file
f = gopen(expanduser(filename),'wb',9); f.write(treestr.encode()); f.close()
else: # plain-text file
f = open(expanduser(filename),'w'); f.write(treestr); f.close() | [
"def",
"write_tree_newick",
"(",
"self",
",",
"filename",
",",
"hide_rooted_prefix",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"filename must be a str\"",
")",
"treestr",
"=",
"self",... | Write this ``Tree`` to a Newick file
Args:
``filename`` (``str``): Path to desired output file (plain-text or gzipped) | [
"Write",
"this",
"Tree",
"to",
"a",
"Newick",
"file"
] | 7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917 | https://github.com/niemasd/TreeSwift/blob/7e0cbc770fcc2ee1194ef7c2a0ab9fb82f089917/treeswift/Tree.py#L1089-L1106 | train | 32,824 |
LogicalDash/LiSE | allegedb/allegedb/window.py | update_window | def update_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
"""Iterate over a window of time in ``branchd`` and call ``updfun`` on the values"""
if turn_from in branchd:
# Not including the exact tick you started from because deltas are *changes*
for past_state in branchd[turn_from][tick_from+1:]:
updfun(*past_state)
for midturn in range(turn_from+1, turn_to):
if midturn in branchd:
for past_state in branchd[midturn][:]:
updfun(*past_state)
if turn_to in branchd:
for past_state in branchd[turn_to][:tick_to+1]:
updfun(*past_state) | python | def update_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
"""Iterate over a window of time in ``branchd`` and call ``updfun`` on the values"""
if turn_from in branchd:
# Not including the exact tick you started from because deltas are *changes*
for past_state in branchd[turn_from][tick_from+1:]:
updfun(*past_state)
for midturn in range(turn_from+1, turn_to):
if midturn in branchd:
for past_state in branchd[midturn][:]:
updfun(*past_state)
if turn_to in branchd:
for past_state in branchd[turn_to][:tick_to+1]:
updfun(*past_state) | [
"def",
"update_window",
"(",
"turn_from",
",",
"tick_from",
",",
"turn_to",
",",
"tick_to",
",",
"updfun",
",",
"branchd",
")",
":",
"if",
"turn_from",
"in",
"branchd",
":",
"# Not including the exact tick you started from because deltas are *changes*",
"for",
"past_sta... | Iterate over a window of time in ``branchd`` and call ``updfun`` on the values | [
"Iterate",
"over",
"a",
"window",
"of",
"time",
"in",
"branchd",
"and",
"call",
"updfun",
"on",
"the",
"values"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L46-L58 | train | 32,825 |
LogicalDash/LiSE | allegedb/allegedb/window.py | update_backward_window | def update_backward_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
"""Iterate backward over a window of time in ``branchd`` and call ``updfun`` on the values"""
if turn_from in branchd:
for future_state in reversed(branchd[turn_from][:tick_from]):
updfun(*future_state)
for midturn in range(turn_from-1, turn_to, -1):
if midturn in branchd:
for future_state in reversed(branchd[midturn][:]):
updfun(*future_state)
if turn_to in branchd:
for future_state in reversed(branchd[turn_to][tick_to+1:]):
updfun(*future_state) | python | def update_backward_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
"""Iterate backward over a window of time in ``branchd`` and call ``updfun`` on the values"""
if turn_from in branchd:
for future_state in reversed(branchd[turn_from][:tick_from]):
updfun(*future_state)
for midturn in range(turn_from-1, turn_to, -1):
if midturn in branchd:
for future_state in reversed(branchd[midturn][:]):
updfun(*future_state)
if turn_to in branchd:
for future_state in reversed(branchd[turn_to][tick_to+1:]):
updfun(*future_state) | [
"def",
"update_backward_window",
"(",
"turn_from",
",",
"tick_from",
",",
"turn_to",
",",
"tick_to",
",",
"updfun",
",",
"branchd",
")",
":",
"if",
"turn_from",
"in",
"branchd",
":",
"for",
"future_state",
"in",
"reversed",
"(",
"branchd",
"[",
"turn_from",
... | Iterate backward over a window of time in ``branchd`` and call ``updfun`` on the values | [
"Iterate",
"backward",
"over",
"a",
"window",
"of",
"time",
"in",
"branchd",
"and",
"call",
"updfun",
"on",
"the",
"values"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L61-L72 | train | 32,826 |
LogicalDash/LiSE | allegedb/allegedb/window.py | within_history | def within_history(rev, windowdict):
"""Return whether the windowdict has history at the revision."""
if not windowdict:
return False
begin = windowdict._past[0][0] if windowdict._past else \
windowdict._future[-1][0]
end = windowdict._future[0][0] if windowdict._future else \
windowdict._past[-1][0]
return begin <= rev <= end | python | def within_history(rev, windowdict):
"""Return whether the windowdict has history at the revision."""
if not windowdict:
return False
begin = windowdict._past[0][0] if windowdict._past else \
windowdict._future[-1][0]
end = windowdict._future[0][0] if windowdict._future else \
windowdict._past[-1][0]
return begin <= rev <= end | [
"def",
"within_history",
"(",
"rev",
",",
"windowdict",
")",
":",
"if",
"not",
"windowdict",
":",
"return",
"False",
"begin",
"=",
"windowdict",
".",
"_past",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"windowdict",
".",
"_past",
"else",
"windowdict",
".",
"_... | Return whether the windowdict has history at the revision. | [
"Return",
"whether",
"the",
"windowdict",
"has",
"history",
"at",
"the",
"revision",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L83-L91 | train | 32,827 |
LogicalDash/LiSE | allegedb/allegedb/window.py | WindowDict.future | def future(self, rev=None):
"""Return a Mapping of items after the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev)
return WindowDictFutureView(self._future) | python | def future(self, rev=None):
"""Return a Mapping of items after the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev)
return WindowDictFutureView(self._future) | [
"def",
"future",
"(",
"self",
",",
"rev",
"=",
"None",
")",
":",
"if",
"rev",
"is",
"not",
"None",
":",
"self",
".",
"seek",
"(",
"rev",
")",
"return",
"WindowDictFutureView",
"(",
"self",
".",
"_future",
")"
] | Return a Mapping of items after the given revision.
Default revision is the last one looked up. | [
"Return",
"a",
"Mapping",
"of",
"items",
"after",
"the",
"given",
"revision",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L429-L437 | train | 32,828 |
LogicalDash/LiSE | allegedb/allegedb/window.py | WindowDict.past | def past(self, rev=None):
"""Return a Mapping of items at or before the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev)
return WindowDictPastView(self._past) | python | def past(self, rev=None):
"""Return a Mapping of items at or before the given revision.
Default revision is the last one looked up.
"""
if rev is not None:
self.seek(rev)
return WindowDictPastView(self._past) | [
"def",
"past",
"(",
"self",
",",
"rev",
"=",
"None",
")",
":",
"if",
"rev",
"is",
"not",
"None",
":",
"self",
".",
"seek",
"(",
"rev",
")",
"return",
"WindowDictPastView",
"(",
"self",
".",
"_past",
")"
] | Return a Mapping of items at or before the given revision.
Default revision is the last one looked up. | [
"Return",
"a",
"Mapping",
"of",
"items",
"at",
"or",
"before",
"the",
"given",
"revision",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L439-L447 | train | 32,829 |
LogicalDash/LiSE | allegedb/allegedb/window.py | WindowDict.seek | def seek(self, rev):
"""Arrange the caches to help look up the given revision."""
# TODO: binary search? Perhaps only when one or the other
# stack is very large?
if not self:
return
if type(rev) is not int:
raise TypeError("rev must be int")
past = self._past
future = self._future
if future:
appender = past.append
popper = future.pop
future_start = future[-1][0]
while future_start <= rev:
appender(popper())
if future:
future_start = future[-1][0]
else:
break
if past:
popper = past.pop
appender = future.append
past_end = past[-1][0]
while past_end > rev:
appender(popper())
if past:
past_end = past[-1][0]
else:
break | python | def seek(self, rev):
"""Arrange the caches to help look up the given revision."""
# TODO: binary search? Perhaps only when one or the other
# stack is very large?
if not self:
return
if type(rev) is not int:
raise TypeError("rev must be int")
past = self._past
future = self._future
if future:
appender = past.append
popper = future.pop
future_start = future[-1][0]
while future_start <= rev:
appender(popper())
if future:
future_start = future[-1][0]
else:
break
if past:
popper = past.pop
appender = future.append
past_end = past[-1][0]
while past_end > rev:
appender(popper())
if past:
past_end = past[-1][0]
else:
break | [
"def",
"seek",
"(",
"self",
",",
"rev",
")",
":",
"# TODO: binary search? Perhaps only when one or the other",
"# stack is very large?",
"if",
"not",
"self",
":",
"return",
"if",
"type",
"(",
"rev",
")",
"is",
"not",
"int",
":",
"raise",
"TypeError",
"(",
"\"rev... | Arrange the caches to help look up the given revision. | [
"Arrange",
"the",
"caches",
"to",
"help",
"look",
"up",
"the",
"given",
"revision",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L450-L479 | train | 32,830 |
LogicalDash/LiSE | allegedb/allegedb/window.py | WindowDict.rev_before | def rev_before(self, rev: int) -> int:
"""Return the latest past rev on which the value changed."""
self.seek(rev)
if self._past:
return self._past[-1][0] | python | def rev_before(self, rev: int) -> int:
"""Return the latest past rev on which the value changed."""
self.seek(rev)
if self._past:
return self._past[-1][0] | [
"def",
"rev_before",
"(",
"self",
",",
"rev",
":",
"int",
")",
"->",
"int",
":",
"self",
".",
"seek",
"(",
"rev",
")",
"if",
"self",
".",
"_past",
":",
"return",
"self",
".",
"_past",
"[",
"-",
"1",
"]",
"[",
"0",
"]"
] | Return the latest past rev on which the value changed. | [
"Return",
"the",
"latest",
"past",
"rev",
"on",
"which",
"the",
"value",
"changed",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L487-L491 | train | 32,831 |
LogicalDash/LiSE | allegedb/allegedb/window.py | WindowDict.rev_after | def rev_after(self, rev: int) -> int:
"""Return the earliest future rev on which the value will change."""
self.seek(rev)
if self._future:
return self._future[-1][0] | python | def rev_after(self, rev: int) -> int:
"""Return the earliest future rev on which the value will change."""
self.seek(rev)
if self._future:
return self._future[-1][0] | [
"def",
"rev_after",
"(",
"self",
",",
"rev",
":",
"int",
")",
"->",
"int",
":",
"self",
".",
"seek",
"(",
"rev",
")",
"if",
"self",
".",
"_future",
":",
"return",
"self",
".",
"_future",
"[",
"-",
"1",
"]",
"[",
"0",
"]"
] | Return the earliest future rev on which the value will change. | [
"Return",
"the",
"earliest",
"future",
"rev",
"on",
"which",
"the",
"value",
"will",
"change",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L493-L497 | train | 32,832 |
LogicalDash/LiSE | allegedb/allegedb/window.py | WindowDict.truncate | def truncate(self, rev: int) -> None:
"""Delete everything after the given revision."""
self.seek(rev)
self._keys.difference_update(map(get0, self._future))
self._future = []
if not self._past:
self._beginning = None | python | def truncate(self, rev: int) -> None:
"""Delete everything after the given revision."""
self.seek(rev)
self._keys.difference_update(map(get0, self._future))
self._future = []
if not self._past:
self._beginning = None | [
"def",
"truncate",
"(",
"self",
",",
"rev",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"seek",
"(",
"rev",
")",
"self",
".",
"_keys",
".",
"difference_update",
"(",
"map",
"(",
"get0",
",",
"self",
".",
"_future",
")",
")",
"self",
".",
"_f... | Delete everything after the given revision. | [
"Delete",
"everything",
"after",
"the",
"given",
"revision",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/window.py#L499-L505 | train | 32,833 |
LogicalDash/LiSE | ELiDE/ELiDE/app.py | ELiDEApp.build_config | def build_config(self, config):
"""Set config defaults"""
for sec in 'LiSE', 'ELiDE':
config.adddefaultsection(sec)
config.setdefaults(
'LiSE',
{
'world': 'sqlite:///LiSEworld.db',
'language': 'eng',
'logfile': '',
'loglevel': 'info'
}
)
config.setdefaults(
'ELiDE',
{
'boardchar': 'physical',
'debugger': 'no',
'inspector': 'no',
'user_kv': 'yes',
'play_speed': '1',
'thing_graphics': json.dumps([
("Marsh Davies' Island", 'marsh_davies_island_fg.atlas'),
('RLTiles: Body', 'base.atlas'),
('RLTiles: Basic clothes', 'body.atlas'),
('RLTiles: Armwear', 'arm.atlas'),
('RLTiles: Legwear', 'leg.atlas'),
('RLTiles: Right hand', 'hand1.atlas'),
('RLTiles: Left hand', 'hand2.atlas'),
('RLTiles: Boots', 'boot.atlas'),
('RLTiles: Hair', 'hair.atlas'),
('RLTiles: Beard', 'beard.atlas'),
('RLTiles: Headwear', 'head.atlas')
]),
'place_graphics': json.dumps([
("Marsh Davies' Island", 'marsh_davies_island_bg.atlas'),
("Marsh Davies' Crypt", 'marsh_davies_crypt.atlas'),
('RLTiles: Dungeon', 'dungeon.atlas')
])
}
)
config.write() | python | def build_config(self, config):
"""Set config defaults"""
for sec in 'LiSE', 'ELiDE':
config.adddefaultsection(sec)
config.setdefaults(
'LiSE',
{
'world': 'sqlite:///LiSEworld.db',
'language': 'eng',
'logfile': '',
'loglevel': 'info'
}
)
config.setdefaults(
'ELiDE',
{
'boardchar': 'physical',
'debugger': 'no',
'inspector': 'no',
'user_kv': 'yes',
'play_speed': '1',
'thing_graphics': json.dumps([
("Marsh Davies' Island", 'marsh_davies_island_fg.atlas'),
('RLTiles: Body', 'base.atlas'),
('RLTiles: Basic clothes', 'body.atlas'),
('RLTiles: Armwear', 'arm.atlas'),
('RLTiles: Legwear', 'leg.atlas'),
('RLTiles: Right hand', 'hand1.atlas'),
('RLTiles: Left hand', 'hand2.atlas'),
('RLTiles: Boots', 'boot.atlas'),
('RLTiles: Hair', 'hair.atlas'),
('RLTiles: Beard', 'beard.atlas'),
('RLTiles: Headwear', 'head.atlas')
]),
'place_graphics': json.dumps([
("Marsh Davies' Island", 'marsh_davies_island_bg.atlas'),
("Marsh Davies' Crypt", 'marsh_davies_crypt.atlas'),
('RLTiles: Dungeon', 'dungeon.atlas')
])
}
)
config.write() | [
"def",
"build_config",
"(",
"self",
",",
"config",
")",
":",
"for",
"sec",
"in",
"'LiSE'",
",",
"'ELiDE'",
":",
"config",
".",
"adddefaultsection",
"(",
"sec",
")",
"config",
".",
"setdefaults",
"(",
"'LiSE'",
",",
"{",
"'world'",
":",
"'sqlite:///LiSEworl... | Set config defaults | [
"Set",
"config",
"defaults"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/app.py#L121-L162 | train | 32,834 |
LogicalDash/LiSE | ELiDE/ELiDE/app.py | ELiDEApp.build | def build(self):
"""Make sure I can use the database, create the tables as needed, and
return the root widget.
"""
self.icon = 'icon_24px.png'
config = self.config
Logger.debug(
"ELiDEApp: starting with world {}, path {}".format(
config['LiSE']['world'],
LiSE.__path__[-1]
)
)
if config['ELiDE']['debugger'] == 'yes':
import pdb
pdb.set_trace()
self.manager = ScreenManager(transition=NoTransition())
if config['ELiDE']['inspector'] == 'yes':
from kivy.core.window import Window
from kivy.modules import inspector
inspector.create_inspector(Window, self.manager)
self._start_subprocess()
self._add_screens()
return self.manager | python | def build(self):
"""Make sure I can use the database, create the tables as needed, and
return the root widget.
"""
self.icon = 'icon_24px.png'
config = self.config
Logger.debug(
"ELiDEApp: starting with world {}, path {}".format(
config['LiSE']['world'],
LiSE.__path__[-1]
)
)
if config['ELiDE']['debugger'] == 'yes':
import pdb
pdb.set_trace()
self.manager = ScreenManager(transition=NoTransition())
if config['ELiDE']['inspector'] == 'yes':
from kivy.core.window import Window
from kivy.modules import inspector
inspector.create_inspector(Window, self.manager)
self._start_subprocess()
self._add_screens()
return self.manager | [
"def",
"build",
"(",
"self",
")",
":",
"self",
".",
"icon",
"=",
"'icon_24px.png'",
"config",
"=",
"self",
".",
"config",
"Logger",
".",
"debug",
"(",
"\"ELiDEApp: starting with world {}, path {}\"",
".",
"format",
"(",
"config",
"[",
"'LiSE'",
"]",
"[",
"'w... | Make sure I can use the database, create the tables as needed, and
return the root widget. | [
"Make",
"sure",
"I",
"can",
"use",
"the",
"database",
"create",
"the",
"tables",
"as",
"needed",
"and",
"return",
"the",
"root",
"widget",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/app.py#L164-L191 | train | 32,835 |
LogicalDash/LiSE | ELiDE/ELiDE/app.py | ELiDEApp.on_pause | def on_pause(self):
"""Sync the database with the current state of the game."""
self.engine.commit()
self.strings.save()
self.funcs.save()
self.config.write() | python | def on_pause(self):
"""Sync the database with the current state of the game."""
self.engine.commit()
self.strings.save()
self.funcs.save()
self.config.write() | [
"def",
"on_pause",
"(",
"self",
")",
":",
"self",
".",
"engine",
".",
"commit",
"(",
")",
"self",
".",
"strings",
".",
"save",
"(",
")",
"self",
".",
"funcs",
".",
"save",
"(",
")",
"self",
".",
"config",
".",
"write",
"(",
")"
] | Sync the database with the current state of the game. | [
"Sync",
"the",
"database",
"with",
"the",
"current",
"state",
"of",
"the",
"game",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/app.py#L370-L375 | train | 32,836 |
LogicalDash/LiSE | ELiDE/ELiDE/app.py | ELiDEApp.on_stop | def on_stop(self, *largs):
"""Sync the database, wrap up the game, and halt."""
self.strings.save()
self.funcs.save()
self.engine.commit()
self.procman.shutdown()
self.config.write() | python | def on_stop(self, *largs):
"""Sync the database, wrap up the game, and halt."""
self.strings.save()
self.funcs.save()
self.engine.commit()
self.procman.shutdown()
self.config.write() | [
"def",
"on_stop",
"(",
"self",
",",
"*",
"largs",
")",
":",
"self",
".",
"strings",
".",
"save",
"(",
")",
"self",
".",
"funcs",
".",
"save",
"(",
")",
"self",
".",
"engine",
".",
"commit",
"(",
")",
"self",
".",
"procman",
".",
"shutdown",
"(",
... | Sync the database, wrap up the game, and halt. | [
"Sync",
"the",
"database",
"wrap",
"up",
"the",
"game",
"and",
"halt",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/app.py#L377-L383 | train | 32,837 |
LogicalDash/LiSE | ELiDE/ELiDE/app.py | ELiDEApp.delete_selection | def delete_selection(self):
"""Delete both the selected widget and whatever it represents."""
selection = self.selection
if selection is None:
return
if isinstance(selection, ArrowWidget):
self.mainscreen.boardview.board.rm_arrow(
selection.origin.name,
selection.destination.name
)
selection.portal.delete()
elif isinstance(selection, Spot):
self.mainscreen.boardview.board.rm_spot(selection.name)
selection.proxy.delete()
else:
assert isinstance(selection, Pawn)
self.mainscreen.boardview.board.rm_pawn(selection.name)
selection.proxy.delete()
self.selection = None | python | def delete_selection(self):
"""Delete both the selected widget and whatever it represents."""
selection = self.selection
if selection is None:
return
if isinstance(selection, ArrowWidget):
self.mainscreen.boardview.board.rm_arrow(
selection.origin.name,
selection.destination.name
)
selection.portal.delete()
elif isinstance(selection, Spot):
self.mainscreen.boardview.board.rm_spot(selection.name)
selection.proxy.delete()
else:
assert isinstance(selection, Pawn)
self.mainscreen.boardview.board.rm_pawn(selection.name)
selection.proxy.delete()
self.selection = None | [
"def",
"delete_selection",
"(",
"self",
")",
":",
"selection",
"=",
"self",
".",
"selection",
"if",
"selection",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"selection",
",",
"ArrowWidget",
")",
":",
"self",
".",
"mainscreen",
".",
"boardview",
"... | Delete both the selected widget and whatever it represents. | [
"Delete",
"both",
"the",
"selected",
"widget",
"and",
"whatever",
"it",
"represents",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/app.py#L385-L403 | train | 32,838 |
LogicalDash/LiSE | ELiDE/ELiDE/app.py | ELiDEApp.new_board | def new_board(self, name):
"""Make a board for a character name, and switch to it."""
char = self.engine.character[name]
board = Board(character=char)
self.mainscreen.boards[name] = board
self.character = char | python | def new_board(self, name):
"""Make a board for a character name, and switch to it."""
char = self.engine.character[name]
board = Board(character=char)
self.mainscreen.boards[name] = board
self.character = char | [
"def",
"new_board",
"(",
"self",
",",
"name",
")",
":",
"char",
"=",
"self",
".",
"engine",
".",
"character",
"[",
"name",
"]",
"board",
"=",
"Board",
"(",
"character",
"=",
"char",
")",
"self",
".",
"mainscreen",
".",
"boards",
"[",
"name",
"]",
"... | Make a board for a character name, and switch to it. | [
"Make",
"a",
"board",
"for",
"a",
"character",
"name",
"and",
"switch",
"to",
"it",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/app.py#L405-L410 | train | 32,839 |
LogicalDash/LiSE | ELiDE/ELiDE/util.py | dummynum | def dummynum(character, name):
"""Count how many nodes there already are in the character whose name
starts the same.
"""
num = 0
for nodename in character.node:
nodename = str(nodename)
if not nodename.startswith(name):
continue
try:
nodenum = int(nodename.lstrip(name))
except ValueError:
continue
num = max((nodenum, num))
return num | python | def dummynum(character, name):
"""Count how many nodes there already are in the character whose name
starts the same.
"""
num = 0
for nodename in character.node:
nodename = str(nodename)
if not nodename.startswith(name):
continue
try:
nodenum = int(nodename.lstrip(name))
except ValueError:
continue
num = max((nodenum, num))
return num | [
"def",
"dummynum",
"(",
"character",
",",
"name",
")",
":",
"num",
"=",
"0",
"for",
"nodename",
"in",
"character",
".",
"node",
":",
"nodename",
"=",
"str",
"(",
"nodename",
")",
"if",
"not",
"nodename",
".",
"startswith",
"(",
"name",
")",
":",
"con... | Count how many nodes there already are in the character whose name
starts the same. | [
"Count",
"how",
"many",
"nodes",
"there",
"already",
"are",
"in",
"the",
"character",
"whose",
"name",
"starts",
"the",
"same",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/util.py#L81-L96 | train | 32,840 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | lru_append | def lru_append(kc, lru, kckey, maxsize):
"""Delete old data from ``kc``, then add the new ``kckey``.
:param kc: a three-layer keycache
:param lru: an :class:`OrderedDict` with a key for each triple that should fill out ``kc``'s three layers
:param kckey: a triple that indexes into ``kc``, which will be added to ``lru`` if needed
:param maxsize: maximum number of entries in ``lru`` and, therefore, ``kc``
"""
if kckey in lru:
return
while len(lru) >= maxsize:
(peb, turn, tick), _ = lru.popitem(False)
if peb not in kc:
continue
kcpeb = kc[peb]
if turn not in kcpeb:
continue
kcpebturn = kcpeb[turn]
if tick not in kcpebturn:
continue
del kcpebturn[tick]
if not kcpebturn:
del kcpeb[turn]
if not kcpeb:
del kc[peb]
lru[kckey] = True | python | def lru_append(kc, lru, kckey, maxsize):
"""Delete old data from ``kc``, then add the new ``kckey``.
:param kc: a three-layer keycache
:param lru: an :class:`OrderedDict` with a key for each triple that should fill out ``kc``'s three layers
:param kckey: a triple that indexes into ``kc``, which will be added to ``lru`` if needed
:param maxsize: maximum number of entries in ``lru`` and, therefore, ``kc``
"""
if kckey in lru:
return
while len(lru) >= maxsize:
(peb, turn, tick), _ = lru.popitem(False)
if peb not in kc:
continue
kcpeb = kc[peb]
if turn not in kcpeb:
continue
kcpebturn = kcpeb[turn]
if tick not in kcpebturn:
continue
del kcpebturn[tick]
if not kcpebturn:
del kcpeb[turn]
if not kcpeb:
del kc[peb]
lru[kckey] = True | [
"def",
"lru_append",
"(",
"kc",
",",
"lru",
",",
"kckey",
",",
"maxsize",
")",
":",
"if",
"kckey",
"in",
"lru",
":",
"return",
"while",
"len",
"(",
"lru",
")",
">=",
"maxsize",
":",
"(",
"peb",
",",
"turn",
",",
"tick",
")",
",",
"_",
"=",
"lru... | Delete old data from ``kc``, then add the new ``kckey``.
:param kc: a three-layer keycache
:param lru: an :class:`OrderedDict` with a key for each triple that should fill out ``kc``'s three layers
:param kckey: a triple that indexes into ``kc``, which will be added to ``lru`` if needed
:param maxsize: maximum number of entries in ``lru`` and, therefore, ``kc`` | [
"Delete",
"old",
"data",
"from",
"kc",
"then",
"add",
"the",
"new",
"kckey",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L146-L172 | train | 32,841 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache.load | def load(self, data):
"""Add a bunch of data. Must be in chronological order.
But it doesn't need to all be from the same branch, as long as
each branch is chronological of itself.
"""
branches = defaultdict(list)
for row in data:
branches[row[-4]].append(row)
# Make keycaches and valcaches. Must be done chronologically
# to make forwarding work.
childbranch = self.db._childbranch
branch2do = deque(['trunk'])
store = self._store
while branch2do:
branch = branch2do.popleft()
for row in branches[branch]:
store(*row, planning=False, loading=True)
if branch in childbranch:
branch2do.extend(childbranch[branch]) | python | def load(self, data):
"""Add a bunch of data. Must be in chronological order.
But it doesn't need to all be from the same branch, as long as
each branch is chronological of itself.
"""
branches = defaultdict(list)
for row in data:
branches[row[-4]].append(row)
# Make keycaches and valcaches. Must be done chronologically
# to make forwarding work.
childbranch = self.db._childbranch
branch2do = deque(['trunk'])
store = self._store
while branch2do:
branch = branch2do.popleft()
for row in branches[branch]:
store(*row, planning=False, loading=True)
if branch in childbranch:
branch2do.extend(childbranch[branch]) | [
"def",
"load",
"(",
"self",
",",
"data",
")",
":",
"branches",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"row",
"in",
"data",
":",
"branches",
"[",
"row",
"[",
"-",
"4",
"]",
"]",
".",
"append",
"(",
"row",
")",
"# Make keycaches and valcaches. Must... | Add a bunch of data. Must be in chronological order.
But it doesn't need to all be from the same branch, as long as
each branch is chronological of itself. | [
"Add",
"a",
"bunch",
"of",
"data",
".",
"Must",
"be",
"in",
"chronological",
"order",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L233-L254 | train | 32,842 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache._valcache_lookup | def _valcache_lookup(self, cache, branch, turn, tick):
"""Return the value at the given time in ``cache``"""
if branch in cache:
branc = cache[branch]
try:
if turn in branc and branc[turn].rev_gettable(tick):
return branc[turn][tick]
elif branc.rev_gettable(turn-1):
turnd = branc[turn-1]
return turnd[turnd.end]
except HistoryError as ex:
# probably shouldn't ever happen, empty branches shouldn't be kept in the cache at all...
# but it's easy to handle
if ex.deleted:
raise
for b, r, t in self.db._iter_parent_btt(branch, turn, tick):
if b in cache:
if r in cache[b] and cache[b][r].rev_gettable(t):
try:
return cache[b][r][t]
except HistoryError as ex:
if ex.deleted:
raise
elif cache[b].rev_gettable(r-1):
cbr = cache[b][r-1]
try:
return cbr[cbr.end]
except HistoryError as ex:
if ex.deleted:
raise | python | def _valcache_lookup(self, cache, branch, turn, tick):
"""Return the value at the given time in ``cache``"""
if branch in cache:
branc = cache[branch]
try:
if turn in branc and branc[turn].rev_gettable(tick):
return branc[turn][tick]
elif branc.rev_gettable(turn-1):
turnd = branc[turn-1]
return turnd[turnd.end]
except HistoryError as ex:
# probably shouldn't ever happen, empty branches shouldn't be kept in the cache at all...
# but it's easy to handle
if ex.deleted:
raise
for b, r, t in self.db._iter_parent_btt(branch, turn, tick):
if b in cache:
if r in cache[b] and cache[b][r].rev_gettable(t):
try:
return cache[b][r][t]
except HistoryError as ex:
if ex.deleted:
raise
elif cache[b].rev_gettable(r-1):
cbr = cache[b][r-1]
try:
return cbr[cbr.end]
except HistoryError as ex:
if ex.deleted:
raise | [
"def",
"_valcache_lookup",
"(",
"self",
",",
"cache",
",",
"branch",
",",
"turn",
",",
"tick",
")",
":",
"if",
"branch",
"in",
"cache",
":",
"branc",
"=",
"cache",
"[",
"branch",
"]",
"try",
":",
"if",
"turn",
"in",
"branc",
"and",
"branc",
"[",
"t... | Return the value at the given time in ``cache`` | [
"Return",
"the",
"value",
"at",
"the",
"given",
"time",
"in",
"cache"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L256-L285 | train | 32,843 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache._get_keycache | def _get_keycache(self, parentity, branch, turn, tick, *, forward):
"""Get a frozenset of keys that exist in the entity at the moment.
With ``forward=True``, enable an optimization that copies old key sets
forward and updates them.
"""
lru_append(self.keycache, self._kc_lru, (parentity+(branch,), turn, tick), KEYCACHE_MAXSIZE)
return self._get_keycachelike(
self.keycache, self.keys, self._get_adds_dels,
parentity, branch, turn, tick, forward=forward
) | python | def _get_keycache(self, parentity, branch, turn, tick, *, forward):
"""Get a frozenset of keys that exist in the entity at the moment.
With ``forward=True``, enable an optimization that copies old key sets
forward and updates them.
"""
lru_append(self.keycache, self._kc_lru, (parentity+(branch,), turn, tick), KEYCACHE_MAXSIZE)
return self._get_keycachelike(
self.keycache, self.keys, self._get_adds_dels,
parentity, branch, turn, tick, forward=forward
) | [
"def",
"_get_keycache",
"(",
"self",
",",
"parentity",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
")",
":",
"lru_append",
"(",
"self",
".",
"keycache",
",",
"self",
".",
"_kc_lru",
",",
"(",
"parentity",
"+",
"(",
"branch",
",... | Get a frozenset of keys that exist in the entity at the moment.
With ``forward=True``, enable an optimization that copies old key sets
forward and updates them. | [
"Get",
"a",
"frozenset",
"of",
"keys",
"that",
"exist",
"in",
"the",
"entity",
"at",
"the",
"moment",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L388-L399 | train | 32,844 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache._update_keycache | def _update_keycache(self, *args, forward):
"""Add or remove a key in the set describing the keys that exist."""
entity, key, branch, turn, tick, value = args[-6:]
parent = args[:-6]
kc = self._get_keycache(parent + (entity,), branch, turn, tick, forward=forward)
if value is None:
kc = kc.difference((key,))
else:
kc = kc.union((key,))
self.keycache[parent+(entity, branch)][turn][tick] = kc | python | def _update_keycache(self, *args, forward):
"""Add or remove a key in the set describing the keys that exist."""
entity, key, branch, turn, tick, value = args[-6:]
parent = args[:-6]
kc = self._get_keycache(parent + (entity,), branch, turn, tick, forward=forward)
if value is None:
kc = kc.difference((key,))
else:
kc = kc.union((key,))
self.keycache[parent+(entity, branch)][turn][tick] = kc | [
"def",
"_update_keycache",
"(",
"self",
",",
"*",
"args",
",",
"forward",
")",
":",
"entity",
",",
"key",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"value",
"=",
"args",
"[",
"-",
"6",
":",
"]",
"parent",
"=",
"args",
"[",
":",
"-",
"6",
"]... | Add or remove a key in the set describing the keys that exist. | [
"Add",
"or",
"remove",
"a",
"key",
"in",
"the",
"set",
"describing",
"the",
"keys",
"that",
"exist",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L401-L410 | train | 32,845 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache.remove | def remove(self, branch, turn, tick):
"""Delete all data from a specific tick"""
time_entity, parents, branches, keys, settings, presettings, remove_keycache, send = self._remove_stuff
parent, entity, key = time_entity[branch, turn, tick]
branchkey = parent + (entity, key)
keykey = parent + (entity,)
if parent in parents:
parentt = parents[parent]
if entity in parentt:
entty = parentt[entity]
if key in entty:
kee = entty[key]
if branch in kee:
branhc = kee[branch]
if turn in branhc:
trn = branhc[turn]
del trn[tick]
if not trn:
del branhc[turn]
if not branhc:
del kee[branch]
if not kee:
del entty[key]
if not entty:
del parentt[entity]
if not parentt:
del parents[parent]
if branchkey in branches:
entty = branches[branchkey]
if branch in entty:
branhc = entty[branch]
if turn in branhc:
trn = branhc[turn]
if tick in trn:
del trn[tick]
if not trn:
del branhc[turn]
if not branhc:
del entty[branch]
if not entty:
del branches[branchkey]
if keykey in keys:
entty = keys[keykey]
if key in entty:
kee = entty[key]
if branch in kee:
branhc = kee[branch]
if turn in branhc:
trn = entty[turn]
if tick in trn:
del trn[tick]
if not trn:
del branhc[turn]
if not branhc:
del kee[branch]
if not kee:
del entty[key]
if not entty:
del keys[keykey]
branhc = settings[branch]
pbranhc = presettings[branch]
trn = branhc[turn]
ptrn = pbranhc[turn]
if tick in trn:
del trn[tick]
if tick in ptrn:
del ptrn[tick]
if not ptrn:
del pbranhc[turn]
del branhc[turn]
if not pbranhc:
del settings[branch]
del presettings[branch]
self.shallowest = OrderedDict()
remove_keycache(parent + (entity, branch), turn, tick)
send(self, branch=branch, turn=turn, tick=tick, action='remove') | python | def remove(self, branch, turn, tick):
"""Delete all data from a specific tick"""
time_entity, parents, branches, keys, settings, presettings, remove_keycache, send = self._remove_stuff
parent, entity, key = time_entity[branch, turn, tick]
branchkey = parent + (entity, key)
keykey = parent + (entity,)
if parent in parents:
parentt = parents[parent]
if entity in parentt:
entty = parentt[entity]
if key in entty:
kee = entty[key]
if branch in kee:
branhc = kee[branch]
if turn in branhc:
trn = branhc[turn]
del trn[tick]
if not trn:
del branhc[turn]
if not branhc:
del kee[branch]
if not kee:
del entty[key]
if not entty:
del parentt[entity]
if not parentt:
del parents[parent]
if branchkey in branches:
entty = branches[branchkey]
if branch in entty:
branhc = entty[branch]
if turn in branhc:
trn = branhc[turn]
if tick in trn:
del trn[tick]
if not trn:
del branhc[turn]
if not branhc:
del entty[branch]
if not entty:
del branches[branchkey]
if keykey in keys:
entty = keys[keykey]
if key in entty:
kee = entty[key]
if branch in kee:
branhc = kee[branch]
if turn in branhc:
trn = entty[turn]
if tick in trn:
del trn[tick]
if not trn:
del branhc[turn]
if not branhc:
del kee[branch]
if not kee:
del entty[key]
if not entty:
del keys[keykey]
branhc = settings[branch]
pbranhc = presettings[branch]
trn = branhc[turn]
ptrn = pbranhc[turn]
if tick in trn:
del trn[tick]
if tick in ptrn:
del ptrn[tick]
if not ptrn:
del pbranhc[turn]
del branhc[turn]
if not pbranhc:
del settings[branch]
del presettings[branch]
self.shallowest = OrderedDict()
remove_keycache(parent + (entity, branch), turn, tick)
send(self, branch=branch, turn=turn, tick=tick, action='remove') | [
"def",
"remove",
"(",
"self",
",",
"branch",
",",
"turn",
",",
"tick",
")",
":",
"time_entity",
",",
"parents",
",",
"branches",
",",
"keys",
",",
"settings",
",",
"presettings",
",",
"remove_keycache",
",",
"send",
"=",
"self",
".",
"_remove_stuff",
"pa... | Delete all data from a specific tick | [
"Delete",
"all",
"data",
"from",
"a",
"specific",
"tick"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L475-L550 | train | 32,846 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache._remove_keycache | def _remove_keycache(self, entity_branch, turn, tick):
"""Remove the future of a given entity from a branch in the keycache"""
keycache = self.keycache
if entity_branch in keycache:
kc = keycache[entity_branch]
if turn in kc:
kcturn = kc[turn]
if tick in kcturn:
del kcturn[tick]
kcturn.truncate(tick)
if not kcturn:
del kc[turn]
kc.truncate(turn)
if not kc:
del keycache[entity_branch] | python | def _remove_keycache(self, entity_branch, turn, tick):
"""Remove the future of a given entity from a branch in the keycache"""
keycache = self.keycache
if entity_branch in keycache:
kc = keycache[entity_branch]
if turn in kc:
kcturn = kc[turn]
if tick in kcturn:
del kcturn[tick]
kcturn.truncate(tick)
if not kcturn:
del kc[turn]
kc.truncate(turn)
if not kc:
del keycache[entity_branch] | [
"def",
"_remove_keycache",
"(",
"self",
",",
"entity_branch",
",",
"turn",
",",
"tick",
")",
":",
"keycache",
"=",
"self",
".",
"keycache",
"if",
"entity_branch",
"in",
"keycache",
":",
"kc",
"=",
"keycache",
"[",
"entity_branch",
"]",
"if",
"turn",
"in",
... | Remove the future of a given entity from a branch in the keycache | [
"Remove",
"the",
"future",
"of",
"a",
"given",
"entity",
"from",
"a",
"branch",
"in",
"the",
"keycache"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L552-L566 | train | 32,847 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | Cache.count_entities_or_keys | def count_entities_or_keys(self, *args, forward=None):
"""Return the number of keys an entity has, if you specify an entity.
Otherwise return the number of entities.
"""
if forward is None:
forward = self.db._forward
entity = args[:-3]
branch, turn, tick = args[-3:]
if self.db._no_kc:
return len(self._get_adds_dels(self.keys[entity], branch, turn, tick)[0])
return len(self._get_keycache(entity, branch, turn, tick, forward=forward)) | python | def count_entities_or_keys(self, *args, forward=None):
"""Return the number of keys an entity has, if you specify an entity.
Otherwise return the number of entities.
"""
if forward is None:
forward = self.db._forward
entity = args[:-3]
branch, turn, tick = args[-3:]
if self.db._no_kc:
return len(self._get_adds_dels(self.keys[entity], branch, turn, tick)[0])
return len(self._get_keycache(entity, branch, turn, tick, forward=forward)) | [
"def",
"count_entities_or_keys",
"(",
"self",
",",
"*",
"args",
",",
"forward",
"=",
"None",
")",
":",
"if",
"forward",
"is",
"None",
":",
"forward",
"=",
"self",
".",
"db",
".",
"_forward",
"entity",
"=",
"args",
"[",
":",
"-",
"3",
"]",
"branch",
... | Return the number of keys an entity has, if you specify an entity.
Otherwise return the number of entities. | [
"Return",
"the",
"number",
"of",
"keys",
"an",
"entity",
"has",
"if",
"you",
"specify",
"an",
"entity",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L799-L811 | train | 32,848 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache._adds_dels_sucpred | def _adds_dels_sucpred(self, cache, branch, turn, tick, *, stoptime=None):
"""Take the successors or predecessors cache and get nodes added or deleted from it
Operates like ``_get_adds_dels``.
"""
added = set()
deleted = set()
for node, nodes in cache.items():
addidx, delidx = self._get_adds_dels(nodes, branch, turn, tick, stoptime=stoptime)
if addidx and not delidx:
added.add(node)
elif delidx and not addidx:
deleted.add(node)
return added, deleted | python | def _adds_dels_sucpred(self, cache, branch, turn, tick, *, stoptime=None):
"""Take the successors or predecessors cache and get nodes added or deleted from it
Operates like ``_get_adds_dels``.
"""
added = set()
deleted = set()
for node, nodes in cache.items():
addidx, delidx = self._get_adds_dels(nodes, branch, turn, tick, stoptime=stoptime)
if addidx and not delidx:
added.add(node)
elif delidx and not addidx:
deleted.add(node)
return added, deleted | [
"def",
"_adds_dels_sucpred",
"(",
"self",
",",
"cache",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"stoptime",
"=",
"None",
")",
":",
"added",
"=",
"set",
"(",
")",
"deleted",
"=",
"set",
"(",
")",
"for",
"node",
",",
"nodes",
"in",
... | Take the successors or predecessors cache and get nodes added or deleted from it
Operates like ``_get_adds_dels``. | [
"Take",
"the",
"successors",
"or",
"predecessors",
"cache",
"and",
"get",
"nodes",
"added",
"or",
"deleted",
"from",
"it"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L888-L902 | train | 32,849 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache._get_destcache | def _get_destcache(self, graph, orig, branch, turn, tick, *, forward):
"""Return a set of destination nodes succeeding ``orig``"""
destcache, destcache_lru, get_keycachelike, successors, adds_dels_sucpred = self._get_destcache_stuff
lru_append(destcache, destcache_lru, ((graph, orig, branch), turn, tick), KEYCACHE_MAXSIZE)
return get_keycachelike(
destcache, successors, adds_dels_sucpred, (graph, orig),
branch, turn, tick, forward=forward
) | python | def _get_destcache(self, graph, orig, branch, turn, tick, *, forward):
"""Return a set of destination nodes succeeding ``orig``"""
destcache, destcache_lru, get_keycachelike, successors, adds_dels_sucpred = self._get_destcache_stuff
lru_append(destcache, destcache_lru, ((graph, orig, branch), turn, tick), KEYCACHE_MAXSIZE)
return get_keycachelike(
destcache, successors, adds_dels_sucpred, (graph, orig),
branch, turn, tick, forward=forward
) | [
"def",
"_get_destcache",
"(",
"self",
",",
"graph",
",",
"orig",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
")",
":",
"destcache",
",",
"destcache_lru",
",",
"get_keycachelike",
",",
"successors",
",",
"adds_dels_sucpred",
"=",
"sel... | Return a set of destination nodes succeeding ``orig`` | [
"Return",
"a",
"set",
"of",
"destination",
"nodes",
"succeeding",
"orig"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L904-L911 | train | 32,850 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache._get_origcache | def _get_origcache(self, graph, dest, branch, turn, tick, *, forward):
"""Return a set of origin nodes leading to ``dest``"""
origcache, origcache_lru, get_keycachelike, predecessors, adds_dels_sucpred = self._get_origcache_stuff
lru_append(origcache, origcache_lru, ((graph, dest, branch), turn, tick), KEYCACHE_MAXSIZE)
return get_keycachelike(
origcache, predecessors, adds_dels_sucpred, (graph, dest),
branch, turn, tick, forward=forward
) | python | def _get_origcache(self, graph, dest, branch, turn, tick, *, forward):
"""Return a set of origin nodes leading to ``dest``"""
origcache, origcache_lru, get_keycachelike, predecessors, adds_dels_sucpred = self._get_origcache_stuff
lru_append(origcache, origcache_lru, ((graph, dest, branch), turn, tick), KEYCACHE_MAXSIZE)
return get_keycachelike(
origcache, predecessors, adds_dels_sucpred, (graph, dest),
branch, turn, tick, forward=forward
) | [
"def",
"_get_origcache",
"(",
"self",
",",
"graph",
",",
"dest",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
")",
":",
"origcache",
",",
"origcache_lru",
",",
"get_keycachelike",
",",
"predecessors",
",",
"adds_dels_sucpred",
"=",
"s... | Return a set of origin nodes leading to ``dest`` | [
"Return",
"a",
"set",
"of",
"origin",
"nodes",
"leading",
"to",
"dest"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L913-L920 | train | 32,851 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache.iter_successors | def iter_successors(self, graph, orig, branch, turn, tick, *, forward=None):
"""Iterate over successors of a given origin node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.successors[graph, orig], branch, turn, tick)[0]
return
if forward is None:
forward = self.db._forward
yield from self._get_destcache(graph, orig, branch, turn, tick, forward=forward) | python | def iter_successors(self, graph, orig, branch, turn, tick, *, forward=None):
"""Iterate over successors of a given origin node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.successors[graph, orig], branch, turn, tick)[0]
return
if forward is None:
forward = self.db._forward
yield from self._get_destcache(graph, orig, branch, turn, tick, forward=forward) | [
"def",
"iter_successors",
"(",
"self",
",",
"graph",
",",
"orig",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
"=",
"None",
")",
":",
"if",
"self",
".",
"db",
".",
"_no_kc",
":",
"yield",
"from",
"self",
".",
"_adds_dels_sucpred... | Iterate over successors of a given origin node at a given time. | [
"Iterate",
"over",
"successors",
"of",
"a",
"given",
"origin",
"node",
"at",
"a",
"given",
"time",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L922-L929 | train | 32,852 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache.iter_predecessors | def iter_predecessors(self, graph, dest, branch, turn, tick, *, forward=None):
"""Iterate over predecessors to a given destination node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.predecessors[graph, dest], branch, turn, tick)[0]
return
if forward is None:
forward = self.db._forward
yield from self._get_origcache(graph, dest, branch, turn, tick, forward=forward) | python | def iter_predecessors(self, graph, dest, branch, turn, tick, *, forward=None):
"""Iterate over predecessors to a given destination node at a given time."""
if self.db._no_kc:
yield from self._adds_dels_sucpred(self.predecessors[graph, dest], branch, turn, tick)[0]
return
if forward is None:
forward = self.db._forward
yield from self._get_origcache(graph, dest, branch, turn, tick, forward=forward) | [
"def",
"iter_predecessors",
"(",
"self",
",",
"graph",
",",
"dest",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
"=",
"None",
")",
":",
"if",
"self",
".",
"db",
".",
"_no_kc",
":",
"yield",
"from",
"self",
".",
"_adds_dels_sucpr... | Iterate over predecessors to a given destination node at a given time. | [
"Iterate",
"over",
"predecessors",
"to",
"a",
"given",
"destination",
"node",
"at",
"a",
"given",
"time",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L931-L938 | train | 32,853 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache.has_successor | def has_successor(self, graph, orig, dest, branch, turn, tick, *, forward=None):
"""Return whether an edge connects the origin to the destination at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge.
"""
if forward is None:
forward = self.db._forward
return dest in self._get_destcache(graph, orig, branch, turn, tick, forward=forward) | python | def has_successor(self, graph, orig, dest, branch, turn, tick, *, forward=None):
"""Return whether an edge connects the origin to the destination at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge.
"""
if forward is None:
forward = self.db._forward
return dest in self._get_destcache(graph, orig, branch, turn, tick, forward=forward) | [
"def",
"has_successor",
"(",
"self",
",",
"graph",
",",
"orig",
",",
"dest",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
"=",
"None",
")",
":",
"if",
"forward",
"is",
"None",
":",
"forward",
"=",
"self",
".",
"db",
".",
"_f... | Return whether an edge connects the origin to the destination at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge. | [
"Return",
"whether",
"an",
"edge",
"connects",
"the",
"origin",
"to",
"the",
"destination",
"at",
"the",
"given",
"time",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L956-L965 | train | 32,854 |
LogicalDash/LiSE | allegedb/allegedb/cache.py | EdgesCache.has_predecessor | def has_predecessor(self, graph, dest, orig, branch, turn, tick, *, forward=None):
"""Return whether an edge connects the destination to the origin at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge.
"""
if forward is None:
forward = self.db._forward
return orig in self._get_origcache(graph, dest, branch, turn, tick, forward=forward) | python | def has_predecessor(self, graph, dest, orig, branch, turn, tick, *, forward=None):
"""Return whether an edge connects the destination to the origin at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge.
"""
if forward is None:
forward = self.db._forward
return orig in self._get_origcache(graph, dest, branch, turn, tick, forward=forward) | [
"def",
"has_predecessor",
"(",
"self",
",",
"graph",
",",
"dest",
",",
"orig",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"*",
",",
"forward",
"=",
"None",
")",
":",
"if",
"forward",
"is",
"None",
":",
"forward",
"=",
"self",
".",
"db",
".",
"... | Return whether an edge connects the destination to the origin at the given time.
Doesn't require the edge's index, which makes it slower than retrieving a
particular edge. | [
"Return",
"whether",
"an",
"edge",
"connects",
"the",
"destination",
"to",
"the",
"origin",
"at",
"the",
"given",
"time",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L967-L976 | train | 32,855 |
LogicalDash/LiSE | ELiDE/ELiDE/board/spot.py | Spot.push_pos | def push_pos(self, *args):
"""Set my current position, expressed as proportions of the board's
width and height, into the ``_x`` and ``_y`` keys of the
entity in my ``proxy`` property, such that it will be
recorded in the database.
"""
self.proxy['_x'] = self.x / self.board.width
self.proxy['_y'] = self.y / self.board.height | python | def push_pos(self, *args):
"""Set my current position, expressed as proportions of the board's
width and height, into the ``_x`` and ``_y`` keys of the
entity in my ``proxy`` property, such that it will be
recorded in the database.
"""
self.proxy['_x'] = self.x / self.board.width
self.proxy['_y'] = self.y / self.board.height | [
"def",
"push_pos",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"proxy",
"[",
"'_x'",
"]",
"=",
"self",
".",
"x",
"/",
"self",
".",
"board",
".",
"width",
"self",
".",
"proxy",
"[",
"'_y'",
"]",
"=",
"self",
".",
"y",
"/",
"self",
".... | Set my current position, expressed as proportions of the board's
width and height, into the ``_x`` and ``_y`` keys of the
entity in my ``proxy`` property, such that it will be
recorded in the database. | [
"Set",
"my",
"current",
"position",
"expressed",
"as",
"proportions",
"of",
"the",
"board",
"s",
"width",
"and",
"height",
"into",
"the",
"_x",
"and",
"_y",
"keys",
"of",
"the",
"entity",
"in",
"my",
"proxy",
"property",
"such",
"that",
"it",
"will",
"be... | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/spot.py#L81-L89 | train | 32,856 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | convert_to_networkx_graph | def convert_to_networkx_graph(data, create_using=None, multigraph_input=False):
"""Convert an AllegedGraph to the corresponding NetworkX graph type."""
if isinstance(data, AllegedGraph):
result = networkx.convert.from_dict_of_dicts(
data.adj,
create_using=create_using,
multigraph_input=data.is_multigraph()
)
result.graph = dict(data.graph)
result.node = {k: dict(v) for k, v in data.node.items()}
return result
return networkx.convert.to_networkx_graph(
data, create_using, multigraph_input
) | python | def convert_to_networkx_graph(data, create_using=None, multigraph_input=False):
"""Convert an AllegedGraph to the corresponding NetworkX graph type."""
if isinstance(data, AllegedGraph):
result = networkx.convert.from_dict_of_dicts(
data.adj,
create_using=create_using,
multigraph_input=data.is_multigraph()
)
result.graph = dict(data.graph)
result.node = {k: dict(v) for k, v in data.node.items()}
return result
return networkx.convert.to_networkx_graph(
data, create_using, multigraph_input
) | [
"def",
"convert_to_networkx_graph",
"(",
"data",
",",
"create_using",
"=",
"None",
",",
"multigraph_input",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"AllegedGraph",
")",
":",
"result",
"=",
"networkx",
".",
"convert",
".",
"from_dict_of_di... | Convert an AllegedGraph to the corresponding NetworkX graph type. | [
"Convert",
"an",
"AllegedGraph",
"to",
"the",
"corresponding",
"NetworkX",
"graph",
"type",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L32-L45 | train | 32,857 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | AllegedMapping.connect | def connect(self, func):
"""Arrange to call this function whenever something changes here.
The arguments will be this object, the key changed, and the value set.
"""
l = _alleged_receivers[id(self)]
if func not in l:
l.append(func) | python | def connect(self, func):
"""Arrange to call this function whenever something changes here.
The arguments will be this object, the key changed, and the value set.
"""
l = _alleged_receivers[id(self)]
if func not in l:
l.append(func) | [
"def",
"connect",
"(",
"self",
",",
"func",
")",
":",
"l",
"=",
"_alleged_receivers",
"[",
"id",
"(",
"self",
")",
"]",
"if",
"func",
"not",
"in",
"l",
":",
"l",
".",
"append",
"(",
"func",
")"
] | Arrange to call this function whenever something changes here.
The arguments will be this object, the key changed, and the value set. | [
"Arrange",
"to",
"call",
"this",
"function",
"whenever",
"something",
"changes",
"here",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L55-L63 | train | 32,858 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | AllegedMapping.disconnect | def disconnect(self, func):
"""No longer call the function when something changes here."""
if id(self) not in _alleged_receivers:
return
l = _alleged_receivers[id(self)]
try:
l.remove(func)
except ValueError:
return
if not l:
del _alleged_receivers[id(self)] | python | def disconnect(self, func):
"""No longer call the function when something changes here."""
if id(self) not in _alleged_receivers:
return
l = _alleged_receivers[id(self)]
try:
l.remove(func)
except ValueError:
return
if not l:
del _alleged_receivers[id(self)] | [
"def",
"disconnect",
"(",
"self",
",",
"func",
")",
":",
"if",
"id",
"(",
"self",
")",
"not",
"in",
"_alleged_receivers",
":",
"return",
"l",
"=",
"_alleged_receivers",
"[",
"id",
"(",
"self",
")",
"]",
"try",
":",
"l",
".",
"remove",
"(",
"func",
... | No longer call the function when something changes here. | [
"No",
"longer",
"call",
"the",
"function",
"when",
"something",
"changes",
"here",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L65-L75 | train | 32,859 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | AllegedMapping.send | def send(self, sender, **kwargs):
"""Internal. Call connected functions."""
if id(self) not in _alleged_receivers:
return
for func in _alleged_receivers[id(self)]:
func(sender, **kwargs) | python | def send(self, sender, **kwargs):
"""Internal. Call connected functions."""
if id(self) not in _alleged_receivers:
return
for func in _alleged_receivers[id(self)]:
func(sender, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"id",
"(",
"self",
")",
"not",
"in",
"_alleged_receivers",
":",
"return",
"for",
"func",
"in",
"_alleged_receivers",
"[",
"id",
"(",
"self",
")",
"]",
":",
"func",
... | Internal. Call connected functions. | [
"Internal",
".",
"Call",
"connected",
"functions",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L77-L82 | train | 32,860 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | AllegedMapping.update | def update(self, other, **kwargs):
"""Version of ``update`` that doesn't clobber the database so much"""
from itertools import chain
if hasattr(other, 'items'):
other = other.items()
for (k, v) in chain(other, kwargs.items()):
if (
k not in self or
self[k] != v
):
self[k] = v | python | def update(self, other, **kwargs):
"""Version of ``update`` that doesn't clobber the database so much"""
from itertools import chain
if hasattr(other, 'items'):
other = other.items()
for (k, v) in chain(other, kwargs.items()):
if (
k not in self or
self[k] != v
):
self[k] = v | [
"def",
"update",
"(",
"self",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"itertools",
"import",
"chain",
"if",
"hasattr",
"(",
"other",
",",
"'items'",
")",
":",
"other",
"=",
"other",
".",
"items",
"(",
")",
"for",
"(",
"k",
",",
"... | Version of ``update`` that doesn't clobber the database so much | [
"Version",
"of",
"update",
"that",
"doesn",
"t",
"clobber",
"the",
"database",
"so",
"much"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L89-L99 | train | 32,861 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | AllegedGraph.clear | def clear(self):
"""Remove all nodes and edges from the graph.
Unlike the regular networkx implementation, this does *not*
remove the graph's name. But all the other graph, node, and
edge attributes go away.
"""
self.adj.clear()
self.node.clear()
self.graph.clear() | python | def clear(self):
"""Remove all nodes and edges from the graph.
Unlike the regular networkx implementation, this does *not*
remove the graph's name. But all the other graph, node, and
edge attributes go away.
"""
self.adj.clear()
self.node.clear()
self.graph.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"adj",
".",
"clear",
"(",
")",
"self",
".",
"node",
".",
"clear",
"(",
")",
"self",
".",
"graph",
".",
"clear",
"(",
")"
] | Remove all nodes and edges from the graph.
Unlike the regular networkx implementation, this does *not*
remove the graph's name. But all the other graph, node, and
edge attributes go away. | [
"Remove",
"all",
"nodes",
"and",
"edges",
"from",
"the",
"graph",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L1297-L1307 | train | 32,862 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | DiGraph.remove_edges_from | def remove_edges_from(self, ebunch):
"""Version of remove_edges_from that's much like normal networkx but only
deletes once, since the database doesn't keep separate adj and
succ mappings
"""
for e in ebunch:
(u, v) = e[:2]
if u in self.succ and v in self.succ[u]:
del self.succ[u][v] | python | def remove_edges_from(self, ebunch):
"""Version of remove_edges_from that's much like normal networkx but only
deletes once, since the database doesn't keep separate adj and
succ mappings
"""
for e in ebunch:
(u, v) = e[:2]
if u in self.succ and v in self.succ[u]:
del self.succ[u][v] | [
"def",
"remove_edges_from",
"(",
"self",
",",
"ebunch",
")",
":",
"for",
"e",
"in",
"ebunch",
":",
"(",
"u",
",",
"v",
")",
"=",
"e",
"[",
":",
"2",
"]",
"if",
"u",
"in",
"self",
".",
"succ",
"and",
"v",
"in",
"self",
".",
"succ",
"[",
"u",
... | Version of remove_edges_from that's much like normal networkx but only
deletes once, since the database doesn't keep separate adj and
succ mappings | [
"Version",
"of",
"remove_edges_from",
"that",
"s",
"much",
"like",
"normal",
"networkx",
"but",
"only",
"deletes",
"once",
"since",
"the",
"database",
"doesn",
"t",
"keep",
"separate",
"adj",
"and",
"succ",
"mappings"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L1339-L1348 | train | 32,863 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | DiGraph.add_edge | def add_edge(self, u, v, attr_dict=None, **attr):
"""Version of add_edge that only writes to the database once"""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dictionary."
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
if u in self.adj:
datadict = self.adj[u].get(v, {})
else:
self.adj[u] = {v: {}}
datadict = self.adj[u][v]
datadict.update(attr_dict)
self.succ[u][v] = datadict
assert u in self.succ, "Failed to add edge {u}->{v} ({u} not in successors)".format(u=u, v=v)
assert v in self.succ[u], "Failed to add edge {u}->{v} ({v} not in succ[{u}])".format(u=u, v=v) | python | def add_edge(self, u, v, attr_dict=None, **attr):
"""Version of add_edge that only writes to the database once"""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dictionary."
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
if u in self.adj:
datadict = self.adj[u].get(v, {})
else:
self.adj[u] = {v: {}}
datadict = self.adj[u][v]
datadict.update(attr_dict)
self.succ[u][v] = datadict
assert u in self.succ, "Failed to add edge {u}->{v} ({u} not in successors)".format(u=u, v=v)
assert v in self.succ[u], "Failed to add edge {u}->{v} ({v} not in succ[{u}])".format(u=u, v=v) | [
"def",
"add_edge",
"(",
"self",
",",
"u",
",",
"v",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"attr",
"else",
":",
"try",
":",
"attr_dict",
".",
"update",
"(",
"attr",
... | Version of add_edge that only writes to the database once | [
"Version",
"of",
"add_edge",
"that",
"only",
"writes",
"to",
"the",
"database",
"once"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L1350-L1373 | train | 32,864 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | DiGraph.add_edges_from | def add_edges_from(self, ebunch, attr_dict=None, **attr):
"""Version of add_edges_from that only writes to the database once"""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dict."
)
for e in ebunch:
ne = len(e)
if ne == 3:
u, v, dd = e
assert hasattr(dd, "update")
elif ne == 2:
u, v = e
dd = {}
else:
raise NetworkXError(
"Edge tupse {} must be a 2-tuple or 3-tuple.".format(e)
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
datadict = self.adj.get(u, {}).get(v, {})
datadict.update(attr_dict)
datadict.update(dd)
self.succ[u][v] = datadict
assert(u in self.succ)
assert(v in self.succ[u]) | python | def add_edges_from(self, ebunch, attr_dict=None, **attr):
"""Version of add_edges_from that only writes to the database once"""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dict."
)
for e in ebunch:
ne = len(e)
if ne == 3:
u, v, dd = e
assert hasattr(dd, "update")
elif ne == 2:
u, v = e
dd = {}
else:
raise NetworkXError(
"Edge tupse {} must be a 2-tuple or 3-tuple.".format(e)
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
datadict = self.adj.get(u, {}).get(v, {})
datadict.update(attr_dict)
datadict.update(dd)
self.succ[u][v] = datadict
assert(u in self.succ)
assert(v in self.succ[u]) | [
"def",
"add_edges_from",
"(",
"self",
",",
"ebunch",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"attr",
"else",
":",
"try",
":",
"attr_dict",
".",
"update",
"(",
"attr",
")"... | Version of add_edges_from that only writes to the database once | [
"Version",
"of",
"add_edges_from",
"that",
"only",
"writes",
"to",
"the",
"database",
"once"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L1375-L1407 | train | 32,865 |
LogicalDash/LiSE | allegedb/allegedb/graph.py | MultiDiGraph.add_edge | def add_edge(self, u, v, key=None, attr_dict=None, **attr):
"""Version of add_edge that only writes to the database once."""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dictionary."
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
if v in self.succ[u]:
keydict = self.adj[u][v]
if key is None:
key = len(keydict)
while key in keydict:
key += 1
datadict = keydict.get(key, {})
datadict.update(attr_dict)
keydict[key] = datadict
else:
if key is None:
key = 0
datadict = {}
datadict.update(attr_dict)
keydict = {key: datadict}
self.succ[u][v] = keydict
return key | python | def add_edge(self, u, v, key=None, attr_dict=None, **attr):
"""Version of add_edge that only writes to the database once."""
if attr_dict is None:
attr_dict = attr
else:
try:
attr_dict.update(attr)
except AttributeError:
raise NetworkXError(
"The attr_dict argument must be a dictionary."
)
if u not in self.node:
self.node[u] = {}
if v not in self.node:
self.node[v] = {}
if v in self.succ[u]:
keydict = self.adj[u][v]
if key is None:
key = len(keydict)
while key in keydict:
key += 1
datadict = keydict.get(key, {})
datadict.update(attr_dict)
keydict[key] = datadict
else:
if key is None:
key = 0
datadict = {}
datadict.update(attr_dict)
keydict = {key: datadict}
self.succ[u][v] = keydict
return key | [
"def",
"add_edge",
"(",
"self",
",",
"u",
",",
"v",
",",
"key",
"=",
"None",
",",
"attr_dict",
"=",
"None",
",",
"*",
"*",
"attr",
")",
":",
"if",
"attr_dict",
"is",
"None",
":",
"attr_dict",
"=",
"attr",
"else",
":",
"try",
":",
"attr_dict",
"."... | Version of add_edge that only writes to the database once. | [
"Version",
"of",
"add_edge",
"that",
"only",
"writes",
"to",
"the",
"database",
"once",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/graph.py#L1462-L1493 | train | 32,866 |
LogicalDash/LiSE | LiSE/LiSE/place.py | Place.delete | def delete(self):
"""Remove myself from the world model immediately."""
super().delete()
self.character.place.send(self.character.place, key=self.name, val=None) | python | def delete(self):
"""Remove myself from the world model immediately."""
super().delete()
self.character.place.send(self.character.place, key=self.name, val=None) | [
"def",
"delete",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"delete",
"(",
")",
"self",
".",
"character",
".",
"place",
".",
"send",
"(",
"self",
".",
"character",
".",
"place",
",",
"key",
"=",
"self",
".",
"name",
",",
"val",
"=",
"None",
... | Remove myself from the world model immediately. | [
"Remove",
"myself",
"from",
"the",
"world",
"model",
"immediately",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/place.py#L49-L52 | train | 32,867 |
LogicalDash/LiSE | LiSE/LiSE/proxy.py | NodeMapProxy.patch | def patch(self, patch):
"""Change a bunch of node stats at once.
This works similarly to ``update``, but only accepts a dict-like argument,
and it recurses one level.
The patch is sent to the LiSE core all at once, so this is faster than
using ``update``, too.
:param patch: a dictionary. Keys are node names, values are other dicts
describing updates to the nodes, where a value of None means delete the stat.
Other values overwrite.
"""
self.engine.handle(
'update_nodes',
char=self.character.name,
patch=patch,
block=False
)
for node, stats in patch.items():
nodeproxycache = self[node]._cache
for k, v in stats.items():
if v is None:
del nodeproxycache[k]
else:
nodeproxycache[k] = v | python | def patch(self, patch):
"""Change a bunch of node stats at once.
This works similarly to ``update``, but only accepts a dict-like argument,
and it recurses one level.
The patch is sent to the LiSE core all at once, so this is faster than
using ``update``, too.
:param patch: a dictionary. Keys are node names, values are other dicts
describing updates to the nodes, where a value of None means delete the stat.
Other values overwrite.
"""
self.engine.handle(
'update_nodes',
char=self.character.name,
patch=patch,
block=False
)
for node, stats in patch.items():
nodeproxycache = self[node]._cache
for k, v in stats.items():
if v is None:
del nodeproxycache[k]
else:
nodeproxycache[k] = v | [
"def",
"patch",
"(",
"self",
",",
"patch",
")",
":",
"self",
".",
"engine",
".",
"handle",
"(",
"'update_nodes'",
",",
"char",
"=",
"self",
".",
"character",
".",
"name",
",",
"patch",
"=",
"patch",
",",
"block",
"=",
"False",
")",
"for",
"node",
"... | Change a bunch of node stats at once.
This works similarly to ``update``, but only accepts a dict-like argument,
and it recurses one level.
The patch is sent to the LiSE core all at once, so this is faster than
using ``update``, too.
:param patch: a dictionary. Keys are node names, values are other dicts
describing updates to the nodes, where a value of None means delete the stat.
Other values overwrite. | [
"Change",
"a",
"bunch",
"of",
"node",
"stats",
"at",
"once",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/proxy.py#L580-L606 | train | 32,868 |
LogicalDash/LiSE | LiSE/LiSE/proxy.py | EngineProxy.handle | def handle(self, cmd=None, **kwargs):
"""Send a command to the LiSE core.
The only positional argument should be the name of a
method in :class:``EngineHandle``. All keyword arguments
will be passed to it, with the exceptions of
``cb``, ``branching``, and ``silent``.
With ``block=False``, don't wait for a result.
This is best for when you want to make some change to the game
state and already know what effect it will have.
With ``branching=True``, handle paradoxes by creating new
branches of history. I will switch to the new branch if needed.
If I have an attribute ``branching_cb``, I'll call it if and
only if the branch changes upon completing a command with
``branching=True``.
With a function ``cb``, I will call ``cb`` when I get
a result. If ``block=False`` this will happen in a thread.
``cb`` will be called with keyword arguments ``command``,
the same command you asked for; ``result``, the value returned
by it, possibly ``None``; and the present ``branch``,
``turn``, and ``tick``, possibly different than when you called
``handle``.
If any of ``branching``, ``cb``, or ``future`` are ``True``,
I will return a ``Future``. The ``Future``'s return value
is a tuple of ``(command, branch, turn, tick, result)``.
"""
if 'command' in kwargs:
cmd = kwargs['command']
elif cmd:
kwargs['command'] = cmd
else:
raise TypeError("No command")
branching = kwargs.get('branching', False)
cb = kwargs.pop('cb', None)
future = kwargs.pop('future', False)
self._handle_lock.acquire()
if kwargs.pop('block', True):
assert not kwargs.get('silent')
self.debug('EngineProxy: sending {}'.format(kwargs))
self.send(self.pack(kwargs))
command, branch, turn, tick, result = self.recv()
assert cmd == command, \
"Sent command {} but received results for {}".format(
cmd, command
)
r = self.unpack(result)
self.debug('EngineProxy: received {}'.format((command, branch, turn, tick, r)))
if (branch, turn, tick) != self._btt():
self._branch = branch
self._turn = turn
self._tick = tick
self.time.send(self, branch=branch, turn=turn, tick=tick)
if isinstance(r, Exception):
self._handle_lock.release()
raise r
if cb:
cb(command=command, branch=branch, turn=turn, tick=tick, result=r)
self._handle_lock.release()
return r
else:
kwargs['silent'] = not (branching or cb or future)
self.debug('EngineProxy: asynchronously sending {}'.format(kwargs))
self.send(self.pack(kwargs))
if branching:
# what happens if more than one branching call is happening at once?
return self._submit(self._branching, cb)
elif cb:
return self._submit(self._callback, cb)
if future:
return self._submit(self._unpack_recv)
self._handle_lock.release() | python | def handle(self, cmd=None, **kwargs):
"""Send a command to the LiSE core.
The only positional argument should be the name of a
method in :class:``EngineHandle``. All keyword arguments
will be passed to it, with the exceptions of
``cb``, ``branching``, and ``silent``.
With ``block=False``, don't wait for a result.
This is best for when you want to make some change to the game
state and already know what effect it will have.
With ``branching=True``, handle paradoxes by creating new
branches of history. I will switch to the new branch if needed.
If I have an attribute ``branching_cb``, I'll call it if and
only if the branch changes upon completing a command with
``branching=True``.
With a function ``cb``, I will call ``cb`` when I get
a result. If ``block=False`` this will happen in a thread.
``cb`` will be called with keyword arguments ``command``,
the same command you asked for; ``result``, the value returned
by it, possibly ``None``; and the present ``branch``,
``turn``, and ``tick``, possibly different than when you called
``handle``.
If any of ``branching``, ``cb``, or ``future`` are ``True``,
I will return a ``Future``. The ``Future``'s return value
is a tuple of ``(command, branch, turn, tick, result)``.
"""
if 'command' in kwargs:
cmd = kwargs['command']
elif cmd:
kwargs['command'] = cmd
else:
raise TypeError("No command")
branching = kwargs.get('branching', False)
cb = kwargs.pop('cb', None)
future = kwargs.pop('future', False)
self._handle_lock.acquire()
if kwargs.pop('block', True):
assert not kwargs.get('silent')
self.debug('EngineProxy: sending {}'.format(kwargs))
self.send(self.pack(kwargs))
command, branch, turn, tick, result = self.recv()
assert cmd == command, \
"Sent command {} but received results for {}".format(
cmd, command
)
r = self.unpack(result)
self.debug('EngineProxy: received {}'.format((command, branch, turn, tick, r)))
if (branch, turn, tick) != self._btt():
self._branch = branch
self._turn = turn
self._tick = tick
self.time.send(self, branch=branch, turn=turn, tick=tick)
if isinstance(r, Exception):
self._handle_lock.release()
raise r
if cb:
cb(command=command, branch=branch, turn=turn, tick=tick, result=r)
self._handle_lock.release()
return r
else:
kwargs['silent'] = not (branching or cb or future)
self.debug('EngineProxy: asynchronously sending {}'.format(kwargs))
self.send(self.pack(kwargs))
if branching:
# what happens if more than one branching call is happening at once?
return self._submit(self._branching, cb)
elif cb:
return self._submit(self._callback, cb)
if future:
return self._submit(self._unpack_recv)
self._handle_lock.release() | [
"def",
"handle",
"(",
"self",
",",
"cmd",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'command'",
"in",
"kwargs",
":",
"cmd",
"=",
"kwargs",
"[",
"'command'",
"]",
"elif",
"cmd",
":",
"kwargs",
"[",
"'command'",
"]",
"=",
"cmd",
"else",
... | Send a command to the LiSE core.
The only positional argument should be the name of a
method in :class:``EngineHandle``. All keyword arguments
will be passed to it, with the exceptions of
``cb``, ``branching``, and ``silent``.
With ``block=False``, don't wait for a result.
This is best for when you want to make some change to the game
state and already know what effect it will have.
With ``branching=True``, handle paradoxes by creating new
branches of history. I will switch to the new branch if needed.
If I have an attribute ``branching_cb``, I'll call it if and
only if the branch changes upon completing a command with
``branching=True``.
With a function ``cb``, I will call ``cb`` when I get
a result. If ``block=False`` this will happen in a thread.
``cb`` will be called with keyword arguments ``command``,
the same command you asked for; ``result``, the value returned
by it, possibly ``None``; and the present ``branch``,
``turn``, and ``tick``, possibly different than when you called
``handle``.
If any of ``branching``, ``cb``, or ``future`` are ``True``,
I will return a ``Future``. The ``Future``'s return value
is a tuple of ``(command, branch, turn, tick, result)``. | [
"Send",
"a",
"command",
"to",
"the",
"LiSE",
"core",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/proxy.py#L2154-L2229 | train | 32,869 |
LogicalDash/LiSE | LiSE/LiSE/proxy.py | EngineProxy.pull | def pull(self, chars='all', cb=None, block=True):
"""Update the state of all my proxy objects from the real objects."""
if block:
deltas = self.handle('get_char_deltas', chars=chars)
self._upd_caches(deltas)
if cb:
cb(deltas)
else:
return self._submit(self._pull_async, chars, cb) | python | def pull(self, chars='all', cb=None, block=True):
"""Update the state of all my proxy objects from the real objects."""
if block:
deltas = self.handle('get_char_deltas', chars=chars)
self._upd_caches(deltas)
if cb:
cb(deltas)
else:
return self._submit(self._pull_async, chars, cb) | [
"def",
"pull",
"(",
"self",
",",
"chars",
"=",
"'all'",
",",
"cb",
"=",
"None",
",",
"block",
"=",
"True",
")",
":",
"if",
"block",
":",
"deltas",
"=",
"self",
".",
"handle",
"(",
"'get_char_deltas'",
",",
"chars",
"=",
"chars",
")",
"self",
".",
... | Update the state of all my proxy objects from the real objects. | [
"Update",
"the",
"state",
"of",
"all",
"my",
"proxy",
"objects",
"from",
"the",
"real",
"objects",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/proxy.py#L2345-L2353 | train | 32,870 |
LogicalDash/LiSE | LiSE/LiSE/proxy.py | EngineProxy.time_travel | def time_travel(self, branch, turn, tick=None, chars='all', cb=None, block=True):
"""Move to a different point in the timestream.
Needs ``branch`` and ``turn`` arguments. The ``tick`` is optional; if unspecified,
you'll travel to the last tick in the turn.
May take a callback function ``cb``, which will receive a dictionary describing
changes to the characters in ``chars``. ``chars`` defaults to 'all', indicating
that every character should be included, but may be a list of character names
to include.
With ``block=True`` (the default), wait until finished computing differences
before returning. Otherwise my ``branch``, ``turn``, and ``tick`` will stay
where they are until that's done.
"""
if cb and not chars:
raise TypeError("Callbacks require chars")
if cb is not None and not callable(cb):
raise TypeError("Uncallable callback")
return self.handle(
'time_travel',
block=block,
branch=branch,
turn=turn,
tick=tick,
chars=chars,
cb=partial(self._upd_and_cb, cb)
) | python | def time_travel(self, branch, turn, tick=None, chars='all', cb=None, block=True):
"""Move to a different point in the timestream.
Needs ``branch`` and ``turn`` arguments. The ``tick`` is optional; if unspecified,
you'll travel to the last tick in the turn.
May take a callback function ``cb``, which will receive a dictionary describing
changes to the characters in ``chars``. ``chars`` defaults to 'all', indicating
that every character should be included, but may be a list of character names
to include.
With ``block=True`` (the default), wait until finished computing differences
before returning. Otherwise my ``branch``, ``turn``, and ``tick`` will stay
where they are until that's done.
"""
if cb and not chars:
raise TypeError("Callbacks require chars")
if cb is not None and not callable(cb):
raise TypeError("Uncallable callback")
return self.handle(
'time_travel',
block=block,
branch=branch,
turn=turn,
tick=tick,
chars=chars,
cb=partial(self._upd_and_cb, cb)
) | [
"def",
"time_travel",
"(",
"self",
",",
"branch",
",",
"turn",
",",
"tick",
"=",
"None",
",",
"chars",
"=",
"'all'",
",",
"cb",
"=",
"None",
",",
"block",
"=",
"True",
")",
":",
"if",
"cb",
"and",
"not",
"chars",
":",
"raise",
"TypeError",
"(",
"... | Move to a different point in the timestream.
Needs ``branch`` and ``turn`` arguments. The ``tick`` is optional; if unspecified,
you'll travel to the last tick in the turn.
May take a callback function ``cb``, which will receive a dictionary describing
changes to the characters in ``chars``. ``chars`` defaults to 'all', indicating
that every character should be included, but may be a list of character names
to include.
With ``block=True`` (the default), wait until finished computing differences
before returning. Otherwise my ``branch``, ``turn``, and ``tick`` will stay
where they are until that's done. | [
"Move",
"to",
"a",
"different",
"point",
"in",
"the",
"timestream",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/proxy.py#L2371-L2399 | train | 32,871 |
LogicalDash/LiSE | LiSE/LiSE/cache.py | NodeContentsCache.truncate_loc | def truncate_loc(self, character, location, branch, turn, tick):
"""Remove future data about a particular location
Return True if I deleted anything, False otherwise.
"""
r = False
branches_turns = self.branches[character, location][branch]
branches_turns.truncate(turn)
if turn in branches_turns:
bttrn = branches_turns[turn]
if bttrn.future(tick):
bttrn.truncate(tick)
r = True
keyses = self.keys[character, location]
for keysbranches in keyses.values():
if branch not in keysbranches:
continue
keysbranch = keysbranches[branch]
if keysbranch.future(turn):
keysbranch.truncate(turn)
r = True
if turn in keysbranch:
keysbranchturn = keysbranch[turn]
if keysbranchturn.future(tick):
keysbranchturn.truncate(tick)
r = True
if branch in self.settings:
for sets in (self.settings, self.presettings):
sets_branch = sets[branch]
if turn in sets_branch:
sets_turn = sets_branch[turn]
for tic, setting in list(sets_turn.future(tick).items()):
if setting[:2] == (character, location):
del sets_turn[tic]
r = True
if not sets_turn:
del sets_branch[turn]
assert r, "Found an empty cache when I didn't delete anything"
for trn, tics in list(sets_branch.future(turn).items()):
for tic, setting in list(tics.future(tick).items()):
if setting[:2] == (character, location):
del tics[tic]
r = True
if not tics:
del sets_branch[trn]
assert r, "Found an empty cache when I didn't delete anything"
if not sets_branch:
del sets[branch]
assert r, "Found an empty cache when I didn't delete anything"
self.shallowest = OrderedDict()
return r | python | def truncate_loc(self, character, location, branch, turn, tick):
"""Remove future data about a particular location
Return True if I deleted anything, False otherwise.
"""
r = False
branches_turns = self.branches[character, location][branch]
branches_turns.truncate(turn)
if turn in branches_turns:
bttrn = branches_turns[turn]
if bttrn.future(tick):
bttrn.truncate(tick)
r = True
keyses = self.keys[character, location]
for keysbranches in keyses.values():
if branch not in keysbranches:
continue
keysbranch = keysbranches[branch]
if keysbranch.future(turn):
keysbranch.truncate(turn)
r = True
if turn in keysbranch:
keysbranchturn = keysbranch[turn]
if keysbranchturn.future(tick):
keysbranchturn.truncate(tick)
r = True
if branch in self.settings:
for sets in (self.settings, self.presettings):
sets_branch = sets[branch]
if turn in sets_branch:
sets_turn = sets_branch[turn]
for tic, setting in list(sets_turn.future(tick).items()):
if setting[:2] == (character, location):
del sets_turn[tic]
r = True
if not sets_turn:
del sets_branch[turn]
assert r, "Found an empty cache when I didn't delete anything"
for trn, tics in list(sets_branch.future(turn).items()):
for tic, setting in list(tics.future(tick).items()):
if setting[:2] == (character, location):
del tics[tic]
r = True
if not tics:
del sets_branch[trn]
assert r, "Found an empty cache when I didn't delete anything"
if not sets_branch:
del sets[branch]
assert r, "Found an empty cache when I didn't delete anything"
self.shallowest = OrderedDict()
return r | [
"def",
"truncate_loc",
"(",
"self",
",",
"character",
",",
"location",
",",
"branch",
",",
"turn",
",",
"tick",
")",
":",
"r",
"=",
"False",
"branches_turns",
"=",
"self",
".",
"branches",
"[",
"character",
",",
"location",
"]",
"[",
"branch",
"]",
"br... | Remove future data about a particular location
Return True if I deleted anything, False otherwise. | [
"Remove",
"future",
"data",
"about",
"a",
"particular",
"location"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/cache.py#L635-L686 | train | 32,872 |
LogicalDash/LiSE | ELiDE/ELiDE/statcfg.py | StatScreen.new_stat | def new_stat(self):
"""Look at the key and value that the user has entered into the stat
configurator, and set them on the currently selected
entity.
"""
key = self.ids.newstatkey.text
value = self.ids.newstatval.text
if not (key and value):
# TODO implement some feedback to the effect that
# you need to enter things
return
try:
self.proxy[key] = self.engine.unpack(value)
except (TypeError, ValueError):
self.proxy[key] = value
self.ids.newstatkey.text = ''
self.ids.newstatval.text = '' | python | def new_stat(self):
"""Look at the key and value that the user has entered into the stat
configurator, and set them on the currently selected
entity.
"""
key = self.ids.newstatkey.text
value = self.ids.newstatval.text
if not (key and value):
# TODO implement some feedback to the effect that
# you need to enter things
return
try:
self.proxy[key] = self.engine.unpack(value)
except (TypeError, ValueError):
self.proxy[key] = value
self.ids.newstatkey.text = ''
self.ids.newstatval.text = '' | [
"def",
"new_stat",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"ids",
".",
"newstatkey",
".",
"text",
"value",
"=",
"self",
".",
"ids",
".",
"newstatval",
".",
"text",
"if",
"not",
"(",
"key",
"and",
"value",
")",
":",
"# TODO implement some feedba... | Look at the key and value that the user has entered into the stat
configurator, and set them on the currently selected
entity. | [
"Look",
"at",
"the",
"key",
"and",
"value",
"that",
"the",
"user",
"has",
"entered",
"into",
"the",
"stat",
"configurator",
"and",
"set",
"them",
"on",
"the",
"currently",
"selected",
"entity",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/statcfg.py#L212-L229 | train | 32,873 |
LogicalDash/LiSE | ELiDE/ELiDE/board/pawnspot.py | PawnSpot.on_touch_move | def on_touch_move(self, touch):
"""If I'm being dragged, move to follow the touch."""
if touch.grab_current is not self:
return False
self.center = touch.pos
return True | python | def on_touch_move(self, touch):
"""If I'm being dragged, move to follow the touch."""
if touch.grab_current is not self:
return False
self.center = touch.pos
return True | [
"def",
"on_touch_move",
"(",
"self",
",",
"touch",
")",
":",
"if",
"touch",
".",
"grab_current",
"is",
"not",
"self",
":",
"return",
"False",
"self",
".",
"center",
"=",
"touch",
".",
"pos",
"return",
"True"
] | If I'm being dragged, move to follow the touch. | [
"If",
"I",
"m",
"being",
"dragged",
"move",
"to",
"follow",
"the",
"touch",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/pawnspot.py#L84-L89 | train | 32,874 |
LogicalDash/LiSE | ELiDE/ELiDE/board/pawnspot.py | PawnSpot.finalize | def finalize(self, initial=True):
"""Call this after you've created all the PawnSpot you need and are ready to add them to the board."""
if getattr(self, '_finalized', False):
return
if (
self.proxy is None or
not hasattr(self.proxy, 'name')
):
Clock.schedule_once(self.finalize, 0)
return
if initial:
self.name = self.proxy.name
self.paths = self.proxy.setdefault(
'_image_paths', self.default_image_paths
)
zeroes = [0] * len(self.paths)
self.offxs = self.proxy.setdefault('_offxs', zeroes)
self.offys = self.proxy.setdefault('_offys', zeroes)
self.proxy.connect(self._trigger_pull_from_proxy)
self.bind(
paths=self._trigger_push_image_paths,
offxs=self._trigger_push_offxs,
offys=self._trigger_push_offys
)
self._finalized = True
self.finalize_children() | python | def finalize(self, initial=True):
"""Call this after you've created all the PawnSpot you need and are ready to add them to the board."""
if getattr(self, '_finalized', False):
return
if (
self.proxy is None or
not hasattr(self.proxy, 'name')
):
Clock.schedule_once(self.finalize, 0)
return
if initial:
self.name = self.proxy.name
self.paths = self.proxy.setdefault(
'_image_paths', self.default_image_paths
)
zeroes = [0] * len(self.paths)
self.offxs = self.proxy.setdefault('_offxs', zeroes)
self.offys = self.proxy.setdefault('_offys', zeroes)
self.proxy.connect(self._trigger_pull_from_proxy)
self.bind(
paths=self._trigger_push_image_paths,
offxs=self._trigger_push_offxs,
offys=self._trigger_push_offys
)
self._finalized = True
self.finalize_children() | [
"def",
"finalize",
"(",
"self",
",",
"initial",
"=",
"True",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_finalized'",
",",
"False",
")",
":",
"return",
"if",
"(",
"self",
".",
"proxy",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"self",
".",
"pr... | Call this after you've created all the PawnSpot you need and are ready to add them to the board. | [
"Call",
"this",
"after",
"you",
"ve",
"created",
"all",
"the",
"PawnSpot",
"you",
"need",
"and",
"are",
"ready",
"to",
"add",
"them",
"to",
"the",
"board",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/pawnspot.py#L91-L116 | train | 32,875 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | normalize_layout | def normalize_layout(l):
"""Make sure all the spots in a layout are where you can click.
Returns a copy of the layout with all spot coordinates are
normalized to within (0.0, 0.98).
"""
xs = []
ys = []
ks = []
for (k, (x, y)) in l.items():
xs.append(x)
ys.append(y)
ks.append(k)
minx = np.min(xs)
maxx = np.max(xs)
try:
xco = 0.98 / (maxx - minx)
xnorm = np.multiply(np.subtract(xs, [minx] * len(xs)), xco)
except ZeroDivisionError:
xnorm = np.array([0.5] * len(xs))
miny = np.min(ys)
maxy = np.max(ys)
try:
yco = 0.98 / (maxy - miny)
ynorm = np.multiply(np.subtract(ys, [miny] * len(ys)), yco)
except ZeroDivisionError:
ynorm = np.array([0.5] * len(ys))
return dict(zip(ks, zip(map(float, xnorm), map(float, ynorm)))) | python | def normalize_layout(l):
"""Make sure all the spots in a layout are where you can click.
Returns a copy of the layout with all spot coordinates are
normalized to within (0.0, 0.98).
"""
xs = []
ys = []
ks = []
for (k, (x, y)) in l.items():
xs.append(x)
ys.append(y)
ks.append(k)
minx = np.min(xs)
maxx = np.max(xs)
try:
xco = 0.98 / (maxx - minx)
xnorm = np.multiply(np.subtract(xs, [minx] * len(xs)), xco)
except ZeroDivisionError:
xnorm = np.array([0.5] * len(xs))
miny = np.min(ys)
maxy = np.max(ys)
try:
yco = 0.98 / (maxy - miny)
ynorm = np.multiply(np.subtract(ys, [miny] * len(ys)), yco)
except ZeroDivisionError:
ynorm = np.array([0.5] * len(ys))
return dict(zip(ks, zip(map(float, xnorm), map(float, ynorm)))) | [
"def",
"normalize_layout",
"(",
"l",
")",
":",
"xs",
"=",
"[",
"]",
"ys",
"=",
"[",
"]",
"ks",
"=",
"[",
"]",
"for",
"(",
"k",
",",
"(",
"x",
",",
"y",
")",
")",
"in",
"l",
".",
"items",
"(",
")",
":",
"xs",
".",
"append",
"(",
"x",
")"... | Make sure all the spots in a layout are where you can click.
Returns a copy of the layout with all spot coordinates are
normalized to within (0.0, 0.98). | [
"Make",
"sure",
"all",
"the",
"spots",
"in",
"a",
"layout",
"are",
"where",
"you",
"can",
"click",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L44-L72 | train | 32,876 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.on_touch_down | def on_touch_down(self, touch):
"""Check for collisions and select an appropriate entity."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
if not self.collide_point(*touch.pos):
return
touch.push()
touch.apply_transform_2d(self.to_local)
if self.app.selection:
if self.app.selection.collide_point(*touch.pos):
Logger.debug("Board: hit selection")
touch.grab(self.app.selection)
pawns = list(self.pawns_at(*touch.pos))
if pawns:
Logger.debug("Board: hit {} pawns".format(len(pawns)))
self.selection_candidates = pawns
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
touch.pop()
return True
spots = list(self.spots_at(*touch.pos))
if spots:
Logger.debug("Board: hit {} spots".format(len(spots)))
self.selection_candidates = spots
if self.adding_portal:
self.origspot = self.selection_candidates.pop(0)
self.protodest = Dummy(
name='protodest',
pos=touch.pos,
size=(0, 0)
)
self.add_widget(self.protodest)
self.protodest.on_touch_down(touch)
self.protoportal = self.proto_arrow_cls(
origin=self.origspot,
destination=self.protodest
)
self.add_widget(self.protoportal)
if self.reciprocal_portal:
self.protoportal2 = self.proto_arrow_cls(
destination=self.origspot,
origin=self.protodest
)
self.add_widget(self.protoportal2)
touch.pop()
return True
arrows = list(self.arrows_at(*touch.pos))
if arrows:
Logger.debug("Board: hit {} arrows".format(len(arrows)))
self.selection_candidates = arrows
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
touch.pop()
return True
touch.pop() | python | def on_touch_down(self, touch):
"""Check for collisions and select an appropriate entity."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
if not self.collide_point(*touch.pos):
return
touch.push()
touch.apply_transform_2d(self.to_local)
if self.app.selection:
if self.app.selection.collide_point(*touch.pos):
Logger.debug("Board: hit selection")
touch.grab(self.app.selection)
pawns = list(self.pawns_at(*touch.pos))
if pawns:
Logger.debug("Board: hit {} pawns".format(len(pawns)))
self.selection_candidates = pawns
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
touch.pop()
return True
spots = list(self.spots_at(*touch.pos))
if spots:
Logger.debug("Board: hit {} spots".format(len(spots)))
self.selection_candidates = spots
if self.adding_portal:
self.origspot = self.selection_candidates.pop(0)
self.protodest = Dummy(
name='protodest',
pos=touch.pos,
size=(0, 0)
)
self.add_widget(self.protodest)
self.protodest.on_touch_down(touch)
self.protoportal = self.proto_arrow_cls(
origin=self.origspot,
destination=self.protodest
)
self.add_widget(self.protoportal)
if self.reciprocal_portal:
self.protoportal2 = self.proto_arrow_cls(
destination=self.origspot,
origin=self.protodest
)
self.add_widget(self.protoportal2)
touch.pop()
return True
arrows = list(self.arrows_at(*touch.pos))
if arrows:
Logger.debug("Board: hit {} arrows".format(len(arrows)))
self.selection_candidates = arrows
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
touch.pop()
return True
touch.pop() | [
"def",
"on_touch_down",
"(",
"self",
",",
"touch",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_lasttouch'",
")",
"and",
"self",
".",
"_lasttouch",
"==",
"touch",
":",
"return",
"if",
"not",
"self",
".",
"collide_point",
"(",
"*",
"touch",
".",
"pos... | Check for collisions and select an appropriate entity. | [
"Check",
"for",
"collisions",
"and",
"select",
"an",
"appropriate",
"entity",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L147-L201 | train | 32,877 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.on_touch_move | def on_touch_move(self, touch):
"""If an entity is selected, drag it."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
if self.app.selection:
if not self.selection_candidates:
self.keep_selection = True
ret = super().on_touch_move(touch)
return ret
elif self.selection_candidates:
for cand in self.selection_candidates:
if cand.collide_point(*touch.pos):
self.app.selection = cand
cand.selected = True
touch.grab(cand)
ret = super().on_touch_move(touch)
return ret | python | def on_touch_move(self, touch):
"""If an entity is selected, drag it."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
if self.app.selection in self.selection_candidates:
self.selection_candidates.remove(self.app.selection)
if self.app.selection:
if not self.selection_candidates:
self.keep_selection = True
ret = super().on_touch_move(touch)
return ret
elif self.selection_candidates:
for cand in self.selection_candidates:
if cand.collide_point(*touch.pos):
self.app.selection = cand
cand.selected = True
touch.grab(cand)
ret = super().on_touch_move(touch)
return ret | [
"def",
"on_touch_move",
"(",
"self",
",",
"touch",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_lasttouch'",
")",
"and",
"self",
".",
"_lasttouch",
"==",
"touch",
":",
"return",
"if",
"self",
".",
"app",
".",
"selection",
"in",
"self",
".",
"selecti... | If an entity is selected, drag it. | [
"If",
"an",
"entity",
"is",
"selected",
"drag",
"it",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L203-L221 | train | 32,878 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.portal_touch_up | def portal_touch_up(self, touch):
"""Try to create a portal between the spots the user chose."""
try:
# If the touch ended upon a spot, and there isn't
# already a portal between the origin and this
# destination, create one.
destspot = next(self.spots_at(*touch.pos))
orig = self.origspot.proxy
dest = destspot.proxy
if not(
orig.name in self.character.portal and
dest.name in self.character.portal[orig.name]
):
port = self.character.new_portal(
orig.name,
dest.name
)
self.arrowlayout.add_widget(
self.make_arrow(port)
)
# And another in the opposite direction if needed
if (
hasattr(self, 'protoportal2') and not(
orig.name in self.character.preportal and
dest.name in self.character.preportal[orig.name]
)
):
deport = self.character.new_portal(
dest.name,
orig.name
)
self.arrowlayout.add_widget(
self.make_arrow(deport)
)
except StopIteration:
pass
self.remove_widget(self.protoportal)
if hasattr(self, 'protoportal2'):
self.remove_widget(self.protoportal2)
del self.protoportal2
self.remove_widget(self.protodest)
del self.protoportal
del self.protodest | python | def portal_touch_up(self, touch):
"""Try to create a portal between the spots the user chose."""
try:
# If the touch ended upon a spot, and there isn't
# already a portal between the origin and this
# destination, create one.
destspot = next(self.spots_at(*touch.pos))
orig = self.origspot.proxy
dest = destspot.proxy
if not(
orig.name in self.character.portal and
dest.name in self.character.portal[orig.name]
):
port = self.character.new_portal(
orig.name,
dest.name
)
self.arrowlayout.add_widget(
self.make_arrow(port)
)
# And another in the opposite direction if needed
if (
hasattr(self, 'protoportal2') and not(
orig.name in self.character.preportal and
dest.name in self.character.preportal[orig.name]
)
):
deport = self.character.new_portal(
dest.name,
orig.name
)
self.arrowlayout.add_widget(
self.make_arrow(deport)
)
except StopIteration:
pass
self.remove_widget(self.protoportal)
if hasattr(self, 'protoportal2'):
self.remove_widget(self.protoportal2)
del self.protoportal2
self.remove_widget(self.protodest)
del self.protoportal
del self.protodest | [
"def",
"portal_touch_up",
"(",
"self",
",",
"touch",
")",
":",
"try",
":",
"# If the touch ended upon a spot, and there isn't",
"# already a portal between the origin and this",
"# destination, create one.",
"destspot",
"=",
"next",
"(",
"self",
".",
"spots_at",
"(",
"*",
... | Try to create a portal between the spots the user chose. | [
"Try",
"to",
"create",
"a",
"portal",
"between",
"the",
"spots",
"the",
"user",
"chose",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L223-L265 | train | 32,879 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.on_touch_up | def on_touch_up(self, touch):
"""Delegate touch handling if possible, else select something."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
self._lasttouch = touch
touch.push()
touch.apply_transform_2d(self.to_local)
if hasattr(self, 'protodest'):
Logger.debug("Board: on_touch_up making a portal")
touch.ungrab(self)
ret = self.portal_touch_up(touch)
touch.pop()
return ret
if self.app.selection and hasattr(self.app.selection, 'on_touch_up'):
self.app.selection.dispatch('on_touch_up', touch)
for candidate in self.selection_candidates:
if candidate == self.app.selection:
continue
if candidate.collide_point(*touch.pos):
Logger.debug("Board: selecting " + repr(candidate))
if hasattr(candidate, 'selected'):
candidate.selected = True
if hasattr(self.app.selection, 'selected'):
self.app.selection.selected = False
self.app.selection = candidate
self.keep_selection = True
parent = candidate.parent
parent.remove_widget(candidate)
parent.add_widget(candidate)
break
if not self.keep_selection:
Logger.debug("Board: deselecting " + repr(self.app.selection))
if hasattr(self.app.selection, 'selected'):
self.app.selection.selected = False
self.app.selection = None
self.keep_selection = False
touch.ungrab(self)
touch.pop()
return | python | def on_touch_up(self, touch):
"""Delegate touch handling if possible, else select something."""
if hasattr(self, '_lasttouch') and self._lasttouch == touch:
return
self._lasttouch = touch
touch.push()
touch.apply_transform_2d(self.to_local)
if hasattr(self, 'protodest'):
Logger.debug("Board: on_touch_up making a portal")
touch.ungrab(self)
ret = self.portal_touch_up(touch)
touch.pop()
return ret
if self.app.selection and hasattr(self.app.selection, 'on_touch_up'):
self.app.selection.dispatch('on_touch_up', touch)
for candidate in self.selection_candidates:
if candidate == self.app.selection:
continue
if candidate.collide_point(*touch.pos):
Logger.debug("Board: selecting " + repr(candidate))
if hasattr(candidate, 'selected'):
candidate.selected = True
if hasattr(self.app.selection, 'selected'):
self.app.selection.selected = False
self.app.selection = candidate
self.keep_selection = True
parent = candidate.parent
parent.remove_widget(candidate)
parent.add_widget(candidate)
break
if not self.keep_selection:
Logger.debug("Board: deselecting " + repr(self.app.selection))
if hasattr(self.app.selection, 'selected'):
self.app.selection.selected = False
self.app.selection = None
self.keep_selection = False
touch.ungrab(self)
touch.pop()
return | [
"def",
"on_touch_up",
"(",
"self",
",",
"touch",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_lasttouch'",
")",
"and",
"self",
".",
"_lasttouch",
"==",
"touch",
":",
"return",
"self",
".",
"_lasttouch",
"=",
"touch",
"touch",
".",
"push",
"(",
")",
... | Delegate touch handling if possible, else select something. | [
"Delegate",
"touch",
"handling",
"if",
"possible",
"else",
"select",
"something",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L267-L305 | train | 32,880 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.on_parent | def on_parent(self, *args):
"""Create some subwidgets and trigger the first update."""
if not self.parent or hasattr(self, '_parented'):
return
if not self.wallpaper_path:
Logger.debug("Board: waiting for wallpaper_path")
Clock.schedule_once(self.on_parent, 0)
return
self._parented = True
self.wallpaper = Image(source=self.wallpaper_path)
self.bind(wallpaper_path=self._pull_image)
self._pull_size()
self.kvlayoutback = KvLayoutBack(**self.widkwargs)
self.arrowlayout = ArrowLayout(**self.widkwargs)
self.spotlayout = FinalLayout(**self.widkwargs)
self.kvlayoutfront = KvLayoutFront(**self.widkwargs)
for wid in self.wids:
self.add_widget(wid)
wid.pos = 0, 0
wid.size = self.size
if wid is not self.wallpaper:
self.bind(size=wid.setter('size'))
self.update() | python | def on_parent(self, *args):
"""Create some subwidgets and trigger the first update."""
if not self.parent or hasattr(self, '_parented'):
return
if not self.wallpaper_path:
Logger.debug("Board: waiting for wallpaper_path")
Clock.schedule_once(self.on_parent, 0)
return
self._parented = True
self.wallpaper = Image(source=self.wallpaper_path)
self.bind(wallpaper_path=self._pull_image)
self._pull_size()
self.kvlayoutback = KvLayoutBack(**self.widkwargs)
self.arrowlayout = ArrowLayout(**self.widkwargs)
self.spotlayout = FinalLayout(**self.widkwargs)
self.kvlayoutfront = KvLayoutFront(**self.widkwargs)
for wid in self.wids:
self.add_widget(wid)
wid.pos = 0, 0
wid.size = self.size
if wid is not self.wallpaper:
self.bind(size=wid.setter('size'))
self.update() | [
"def",
"on_parent",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"not",
"self",
".",
"parent",
"or",
"hasattr",
"(",
"self",
",",
"'_parented'",
")",
":",
"return",
"if",
"not",
"self",
".",
"wallpaper_path",
":",
"Logger",
".",
"debug",
"(",
"\"Bo... | Create some subwidgets and trigger the first update. | [
"Create",
"some",
"subwidgets",
"and",
"trigger",
"the",
"first",
"update",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L317-L339 | train | 32,881 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.update | def update(self, *args):
"""Force an update to match the current state of my character.
This polls every element of the character, and therefore
causes me to sync with the LiSE core for a long time. Avoid
when possible.
"""
# remove widgets that don't represent anything anymore
Logger.debug("Board: updating")
self.remove_absent_pawns()
self.remove_absent_spots()
self.remove_absent_arrows()
# add widgets to represent new stuff
self.add_new_spots()
if self.arrow_cls:
self.add_new_arrows()
self.add_new_pawns()
self.spotlayout.finalize_all()
Logger.debug("Board: updated") | python | def update(self, *args):
"""Force an update to match the current state of my character.
This polls every element of the character, and therefore
causes me to sync with the LiSE core for a long time. Avoid
when possible.
"""
# remove widgets that don't represent anything anymore
Logger.debug("Board: updating")
self.remove_absent_pawns()
self.remove_absent_spots()
self.remove_absent_arrows()
# add widgets to represent new stuff
self.add_new_spots()
if self.arrow_cls:
self.add_new_arrows()
self.add_new_pawns()
self.spotlayout.finalize_all()
Logger.debug("Board: updated") | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
")",
":",
"# remove widgets that don't represent anything anymore",
"Logger",
".",
"debug",
"(",
"\"Board: updating\"",
")",
"self",
".",
"remove_absent_pawns",
"(",
")",
"self",
".",
"remove_absent_spots",
"(",
")",
... | Force an update to match the current state of my character.
This polls every element of the character, and therefore
causes me to sync with the LiSE core for a long time. Avoid
when possible. | [
"Force",
"an",
"update",
"to",
"match",
"the",
"current",
"state",
"of",
"my",
"character",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L719-L739 | train | 32,882 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.update_from_delta | def update_from_delta(self, delta, *args):
"""Apply the changes described in the dict ``delta``."""
for (node, extant) in delta.get('nodes', {}).items():
if extant:
if node in delta.get('node_val', {}) \
and 'location' in delta['node_val'][node]\
and node not in self.pawn:
self.add_pawn(node)
elif node not in self.spot:
self.add_spot(node)
spot = self.spot[node]
if '_x' not in spot.place or '_y' not in spot.place:
self.spots_unposd.append(spot)
else:
if node in self.pawn:
self.rm_pawn(node)
if node in self.spot:
self.rm_spot(node)
for (node, stats) in delta.get('node_val', {}).items():
if node in self.spot:
spot = self.spot[node]
x = stats.get('_x')
y = stats.get('_y')
if x is not None:
spot.x = x * self.width
if y is not None:
spot.y = y * self.height
if '_image_paths' in stats:
spot.paths = stats['_image_paths'] or spot.default_image_paths
elif node in self.pawn:
pawn = self.pawn[node]
if 'location' in stats:
pawn.loc_name = stats['location']
if '_image_paths' in stats:
pawn.paths = stats['_image_paths'] or pawn.default_image_paths
else:
Logger.warning(
"Board: diff tried to change stats of node {} "
"but I don't have a widget for it".format(node)
)
for (orig, dests) in delta.get('edges', {}).items():
for (dest, extant) in dests.items():
if extant and (orig not in self.arrow or dest not in self.arrow[orig]):
self.add_arrow(orig, dest)
elif not extant and orig in self.arrow and dest in self.arrow[orig]:
self.rm_arrow(orig, dest) | python | def update_from_delta(self, delta, *args):
"""Apply the changes described in the dict ``delta``."""
for (node, extant) in delta.get('nodes', {}).items():
if extant:
if node in delta.get('node_val', {}) \
and 'location' in delta['node_val'][node]\
and node not in self.pawn:
self.add_pawn(node)
elif node not in self.spot:
self.add_spot(node)
spot = self.spot[node]
if '_x' not in spot.place or '_y' not in spot.place:
self.spots_unposd.append(spot)
else:
if node in self.pawn:
self.rm_pawn(node)
if node in self.spot:
self.rm_spot(node)
for (node, stats) in delta.get('node_val', {}).items():
if node in self.spot:
spot = self.spot[node]
x = stats.get('_x')
y = stats.get('_y')
if x is not None:
spot.x = x * self.width
if y is not None:
spot.y = y * self.height
if '_image_paths' in stats:
spot.paths = stats['_image_paths'] or spot.default_image_paths
elif node in self.pawn:
pawn = self.pawn[node]
if 'location' in stats:
pawn.loc_name = stats['location']
if '_image_paths' in stats:
pawn.paths = stats['_image_paths'] or pawn.default_image_paths
else:
Logger.warning(
"Board: diff tried to change stats of node {} "
"but I don't have a widget for it".format(node)
)
for (orig, dests) in delta.get('edges', {}).items():
for (dest, extant) in dests.items():
if extant and (orig not in self.arrow or dest not in self.arrow[orig]):
self.add_arrow(orig, dest)
elif not extant and orig in self.arrow and dest in self.arrow[orig]:
self.rm_arrow(orig, dest) | [
"def",
"update_from_delta",
"(",
"self",
",",
"delta",
",",
"*",
"args",
")",
":",
"for",
"(",
"node",
",",
"extant",
")",
"in",
"delta",
".",
"get",
"(",
"'nodes'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"if",
"extant",
":",
"if",
"n... | Apply the changes described in the dict ``delta``. | [
"Apply",
"the",
"changes",
"described",
"in",
"the",
"dict",
"delta",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L742-L787 | train | 32,883 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.arrows | def arrows(self):
"""Iterate over all my arrows."""
for o in self.arrow.values():
for arro in o.values():
yield arro | python | def arrows(self):
"""Iterate over all my arrows."""
for o in self.arrow.values():
for arro in o.values():
yield arro | [
"def",
"arrows",
"(",
"self",
")",
":",
"for",
"o",
"in",
"self",
".",
"arrow",
".",
"values",
"(",
")",
":",
"for",
"arro",
"in",
"o",
".",
"values",
"(",
")",
":",
"yield",
"arro"
] | Iterate over all my arrows. | [
"Iterate",
"over",
"all",
"my",
"arrows",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L846-L850 | train | 32,884 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.pawns_at | def pawns_at(self, x, y):
"""Iterate over pawns that collide the given point."""
for pawn in self.pawn.values():
if pawn.collide_point(x, y):
yield pawn | python | def pawns_at(self, x, y):
"""Iterate over pawns that collide the given point."""
for pawn in self.pawn.values():
if pawn.collide_point(x, y):
yield pawn | [
"def",
"pawns_at",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"for",
"pawn",
"in",
"self",
".",
"pawn",
".",
"values",
"(",
")",
":",
"if",
"pawn",
".",
"collide_point",
"(",
"x",
",",
"y",
")",
":",
"yield",
"pawn"
] | Iterate over pawns that collide the given point. | [
"Iterate",
"over",
"pawns",
"that",
"collide",
"the",
"given",
"point",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L852-L856 | train | 32,885 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.spots_at | def spots_at(self, x, y):
"""Iterate over spots that collide the given point."""
for spot in self.spot.values():
if spot.collide_point(x, y):
yield spot | python | def spots_at(self, x, y):
"""Iterate over spots that collide the given point."""
for spot in self.spot.values():
if spot.collide_point(x, y):
yield spot | [
"def",
"spots_at",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"for",
"spot",
"in",
"self",
".",
"spot",
".",
"values",
"(",
")",
":",
"if",
"spot",
".",
"collide_point",
"(",
"x",
",",
"y",
")",
":",
"yield",
"spot"
] | Iterate over spots that collide the given point. | [
"Iterate",
"over",
"spots",
"that",
"collide",
"the",
"given",
"point",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L858-L862 | train | 32,886 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | Board.arrows_at | def arrows_at(self, x, y):
"""Iterate over arrows that collide the given point."""
for arrow in self.arrows():
if arrow.collide_point(x, y):
yield arrow | python | def arrows_at(self, x, y):
"""Iterate over arrows that collide the given point."""
for arrow in self.arrows():
if arrow.collide_point(x, y):
yield arrow | [
"def",
"arrows_at",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"for",
"arrow",
"in",
"self",
".",
"arrows",
"(",
")",
":",
"if",
"arrow",
".",
"collide_point",
"(",
"x",
",",
"y",
")",
":",
"yield",
"arrow"
] | Iterate over arrows that collide the given point. | [
"Iterate",
"over",
"arrows",
"that",
"collide",
"the",
"given",
"point",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L864-L868 | train | 32,887 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | BoardScatterPlane.spot_from_dummy | def spot_from_dummy(self, dummy):
"""Make a real place and its spot from a dummy spot.
Create a new :class:`board.Spot` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
position, and imagery of the provided dummy.
"""
(x, y) = self.to_local(*dummy.pos_up)
x /= self.board.width
y /= self.board.height
self.board.spotlayout.add_widget(
self.board.make_spot(
self.board.character.new_place(
dummy.name,
_x=x,
_y=y,
_image_paths=list(dummy.paths)
)
)
)
dummy.num += 1 | python | def spot_from_dummy(self, dummy):
"""Make a real place and its spot from a dummy spot.
Create a new :class:`board.Spot` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
position, and imagery of the provided dummy.
"""
(x, y) = self.to_local(*dummy.pos_up)
x /= self.board.width
y /= self.board.height
self.board.spotlayout.add_widget(
self.board.make_spot(
self.board.character.new_place(
dummy.name,
_x=x,
_y=y,
_image_paths=list(dummy.paths)
)
)
)
dummy.num += 1 | [
"def",
"spot_from_dummy",
"(",
"self",
",",
"dummy",
")",
":",
"(",
"x",
",",
"y",
")",
"=",
"self",
".",
"to_local",
"(",
"*",
"dummy",
".",
"pos_up",
")",
"x",
"/=",
"self",
".",
"board",
".",
"width",
"y",
"/=",
"self",
".",
"board",
".",
"h... | Make a real place and its spot from a dummy spot.
Create a new :class:`board.Spot` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
position, and imagery of the provided dummy. | [
"Make",
"a",
"real",
"place",
"and",
"its",
"spot",
"from",
"a",
"dummy",
"spot",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L879-L900 | train | 32,888 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | BoardScatterPlane.pawn_from_dummy | def pawn_from_dummy(self, dummy):
"""Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy.
"""
dummy.pos = self.to_local(*dummy.pos)
for spot in self.board.spotlayout.children:
if spot.collide_widget(dummy):
whereat = spot
break
else:
return
whereat.add_widget(
self.board.make_pawn(
self.board.character.new_thing(
dummy.name,
whereat.place.name,
_image_paths=list(dummy.paths)
)
)
)
dummy.num += 1 | python | def pawn_from_dummy(self, dummy):
"""Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy.
"""
dummy.pos = self.to_local(*dummy.pos)
for spot in self.board.spotlayout.children:
if spot.collide_widget(dummy):
whereat = spot
break
else:
return
whereat.add_widget(
self.board.make_pawn(
self.board.character.new_thing(
dummy.name,
whereat.place.name,
_image_paths=list(dummy.paths)
)
)
)
dummy.num += 1 | [
"def",
"pawn_from_dummy",
"(",
"self",
",",
"dummy",
")",
":",
"dummy",
".",
"pos",
"=",
"self",
".",
"to_local",
"(",
"*",
"dummy",
".",
"pos",
")",
"for",
"spot",
"in",
"self",
".",
"board",
".",
"spotlayout",
".",
"children",
":",
"if",
"spot",
... | Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy. | [
"Make",
"a",
"real",
"thing",
"and",
"its",
"pawn",
"from",
"a",
"dummy",
"pawn",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L902-L926 | train | 32,889 |
LogicalDash/LiSE | ELiDE/ELiDE/board/board.py | BoardScatterPlane.arrow_from_wid | def arrow_from_wid(self, wid):
"""Make a real portal and its arrow from a dummy arrow.
This doesn't handle touch events. It takes a widget as its
argument: the one the user has been dragging to indicate where
they want the arrow to go. Said widget ought to be invisible.
It checks if the dummy arrow connects two real spots first,
and does nothing if it doesn't.
"""
for spot in self.board.spotlayout.children:
if spot.collide_widget(wid):
whereto = spot
break
else:
return
self.board.arrowlayout.add_widget(
self.board.make_arrow(
self.board.character.new_portal(
self.board.grabbed.place.name,
whereto.place.name,
reciprocal=self.reciprocal_portal
)
)
) | python | def arrow_from_wid(self, wid):
"""Make a real portal and its arrow from a dummy arrow.
This doesn't handle touch events. It takes a widget as its
argument: the one the user has been dragging to indicate where
they want the arrow to go. Said widget ought to be invisible.
It checks if the dummy arrow connects two real spots first,
and does nothing if it doesn't.
"""
for spot in self.board.spotlayout.children:
if spot.collide_widget(wid):
whereto = spot
break
else:
return
self.board.arrowlayout.add_widget(
self.board.make_arrow(
self.board.character.new_portal(
self.board.grabbed.place.name,
whereto.place.name,
reciprocal=self.reciprocal_portal
)
)
) | [
"def",
"arrow_from_wid",
"(",
"self",
",",
"wid",
")",
":",
"for",
"spot",
"in",
"self",
".",
"board",
".",
"spotlayout",
".",
"children",
":",
"if",
"spot",
".",
"collide_widget",
"(",
"wid",
")",
":",
"whereto",
"=",
"spot",
"break",
"else",
":",
"... | Make a real portal and its arrow from a dummy arrow.
This doesn't handle touch events. It takes a widget as its
argument: the one the user has been dragging to indicate where
they want the arrow to go. Said widget ought to be invisible.
It checks if the dummy arrow connects two real spots first,
and does nothing if it doesn't. | [
"Make",
"a",
"real",
"portal",
"and",
"its",
"arrow",
"from",
"a",
"dummy",
"arrow",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L928-L952 | train | 32,890 |
LogicalDash/LiSE | LiSE/LiSE/util.py | sort_set | def sort_set(s):
"""Return a sorted list of the contents of a set
This is intended to be used to iterate over world state, where you just need keys
to be in some deterministic order, but the sort order should be obvious from the key.
Non-strings come before strings and then tuples. Tuples compare element-wise as normal.
But ultimately all comparisons are between values' ``repr``.
This is memoized.
"""
if not isinstance(s, Set):
raise TypeError("sets only")
s = frozenset(s)
if s not in _sort_set_memo:
_sort_set_memo[s] = sorted(s, key=_sort_set_key)
return _sort_set_memo[s] | python | def sort_set(s):
"""Return a sorted list of the contents of a set
This is intended to be used to iterate over world state, where you just need keys
to be in some deterministic order, but the sort order should be obvious from the key.
Non-strings come before strings and then tuples. Tuples compare element-wise as normal.
But ultimately all comparisons are between values' ``repr``.
This is memoized.
"""
if not isinstance(s, Set):
raise TypeError("sets only")
s = frozenset(s)
if s not in _sort_set_memo:
_sort_set_memo[s] = sorted(s, key=_sort_set_key)
return _sort_set_memo[s] | [
"def",
"sort_set",
"(",
"s",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"Set",
")",
":",
"raise",
"TypeError",
"(",
"\"sets only\"",
")",
"s",
"=",
"frozenset",
"(",
"s",
")",
"if",
"s",
"not",
"in",
"_sort_set_memo",
":",
"_sort_set_memo",
... | Return a sorted list of the contents of a set
This is intended to be used to iterate over world state, where you just need keys
to be in some deterministic order, but the sort order should be obvious from the key.
Non-strings come before strings and then tuples. Tuples compare element-wise as normal.
But ultimately all comparisons are between values' ``repr``.
This is memoized. | [
"Return",
"a",
"sorted",
"list",
"of",
"the",
"contents",
"of",
"a",
"set"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/util.py#L170-L187 | train | 32,891 |
LogicalDash/LiSE | LiSE/LiSE/portal.py | Portal.reciprocal | def reciprocal(self):
"""If there's another Portal connecting the same origin and
destination that I do, but going the opposite way, return
it. Else raise KeyError.
"""
try:
return self.character.portal[self.dest][self.orig]
except KeyError:
raise KeyError("This portal has no reciprocal") | python | def reciprocal(self):
"""If there's another Portal connecting the same origin and
destination that I do, but going the opposite way, return
it. Else raise KeyError.
"""
try:
return self.character.portal[self.dest][self.orig]
except KeyError:
raise KeyError("This portal has no reciprocal") | [
"def",
"reciprocal",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"character",
".",
"portal",
"[",
"self",
".",
"dest",
"]",
"[",
"self",
".",
"orig",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"This portal has no reciprocal\"... | If there's another Portal connecting the same origin and
destination that I do, but going the opposite way, return
it. Else raise KeyError. | [
"If",
"there",
"s",
"another",
"Portal",
"connecting",
"the",
"same",
"origin",
"and",
"destination",
"that",
"I",
"do",
"but",
"going",
"the",
"opposite",
"way",
"return",
"it",
".",
"Else",
"raise",
"KeyError",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/portal.py#L197-L206 | train | 32,892 |
LogicalDash/LiSE | LiSE/LiSE/portal.py | Portal.update | def update(self, d):
"""Works like regular update, but only actually updates when the new
value and the old value differ. This is necessary to prevent
certain infinite loops.
:arg d: a dictionary
"""
for (k, v) in d.items():
if k not in self or self[k] != v:
self[k] = v | python | def update(self, d):
"""Works like regular update, but only actually updates when the new
value and the old value differ. This is necessary to prevent
certain infinite loops.
:arg d: a dictionary
"""
for (k, v) in d.items():
if k not in self or self[k] != v:
self[k] = v | [
"def",
"update",
"(",
"self",
",",
"d",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
"or",
"self",
"[",
"k",
"]",
"!=",
"v",
":",
"self",
"[",
"k",
"]",
"=",
"v"
] | Works like regular update, but only actually updates when the new
value and the old value differ. This is necessary to prevent
certain infinite loops.
:arg d: a dictionary | [
"Works",
"like",
"regular",
"update",
"but",
"only",
"actually",
"updates",
"when",
"the",
"new",
"value",
"and",
"the",
"old",
"value",
"differ",
".",
"This",
"is",
"necessary",
"to",
"prevent",
"certain",
"infinite",
"loops",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/portal.py#L221-L231 | train | 32,893 |
LogicalDash/LiSE | ELiDE/ELiDE/charmenu.py | CharMenu.toggle_rules | def toggle_rules(self, *args):
"""Display or hide the view for constructing rules out of cards."""
if self.app.manager.current != 'rules' and not isinstance(self.app.selected_proxy, CharStatProxy):
self.app.rules.entity = self.app.selected_proxy
self.app.rules.rulebook = self.app.selected_proxy.rulebook
if isinstance(self.app.selected_proxy, CharStatProxy):
self.app.charrules.character = self.app.selected_proxy
self.app.charrules.toggle()
else:
self.app.rules.toggle() | python | def toggle_rules(self, *args):
"""Display or hide the view for constructing rules out of cards."""
if self.app.manager.current != 'rules' and not isinstance(self.app.selected_proxy, CharStatProxy):
self.app.rules.entity = self.app.selected_proxy
self.app.rules.rulebook = self.app.selected_proxy.rulebook
if isinstance(self.app.selected_proxy, CharStatProxy):
self.app.charrules.character = self.app.selected_proxy
self.app.charrules.toggle()
else:
self.app.rules.toggle() | [
"def",
"toggle_rules",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"app",
".",
"manager",
".",
"current",
"!=",
"'rules'",
"and",
"not",
"isinstance",
"(",
"self",
".",
"app",
".",
"selected_proxy",
",",
"CharStatProxy",
")",
":",
"self... | Display or hide the view for constructing rules out of cards. | [
"Display",
"or",
"hide",
"the",
"view",
"for",
"constructing",
"rules",
"out",
"of",
"cards",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/charmenu.py#L82-L91 | train | 32,894 |
LogicalDash/LiSE | ELiDE/ELiDE/charmenu.py | CharMenu.toggle_spot_cfg | def toggle_spot_cfg(self):
"""Show the dialog where you select graphics and a name for a place,
or hide it if already showing.
"""
if self.app.manager.current == 'spotcfg':
dummyplace = self.screendummyplace
self.ids.placetab.remove_widget(dummyplace)
dummyplace.clear()
if self.app.spotcfg.prefix:
dummyplace.prefix = self.app.spotcfg.prefix
dummyplace.num = dummynum(
self.app.character, dummyplace.prefix
) + 1
dummyplace.paths = self.app.spotcfg.imgpaths
self.ids.placetab.add_widget(dummyplace)
else:
self.app.spotcfg.prefix = self.ids.dummyplace.prefix
self.app.spotcfg.toggle() | python | def toggle_spot_cfg(self):
"""Show the dialog where you select graphics and a name for a place,
or hide it if already showing.
"""
if self.app.manager.current == 'spotcfg':
dummyplace = self.screendummyplace
self.ids.placetab.remove_widget(dummyplace)
dummyplace.clear()
if self.app.spotcfg.prefix:
dummyplace.prefix = self.app.spotcfg.prefix
dummyplace.num = dummynum(
self.app.character, dummyplace.prefix
) + 1
dummyplace.paths = self.app.spotcfg.imgpaths
self.ids.placetab.add_widget(dummyplace)
else:
self.app.spotcfg.prefix = self.ids.dummyplace.prefix
self.app.spotcfg.toggle() | [
"def",
"toggle_spot_cfg",
"(",
"self",
")",
":",
"if",
"self",
".",
"app",
".",
"manager",
".",
"current",
"==",
"'spotcfg'",
":",
"dummyplace",
"=",
"self",
".",
"screendummyplace",
"self",
".",
"ids",
".",
"placetab",
".",
"remove_widget",
"(",
"dummypla... | Show the dialog where you select graphics and a name for a place,
or hide it if already showing. | [
"Show",
"the",
"dialog",
"where",
"you",
"select",
"graphics",
"and",
"a",
"name",
"for",
"a",
"place",
"or",
"hide",
"it",
"if",
"already",
"showing",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/charmenu.py#L100-L118 | train | 32,895 |
LogicalDash/LiSE | ELiDE/ELiDE/charmenu.py | CharMenu.toggle_pawn_cfg | def toggle_pawn_cfg(self):
"""Show or hide the pop-over where you can configure the dummy pawn"""
if self.app.manager.current == 'pawncfg':
dummything = self.app.dummything
self.ids.thingtab.remove_widget(dummything)
dummything.clear()
if self.app.pawncfg.prefix:
dummything.prefix = self.app.pawncfg.prefix
dummything.num = dummynum(
self.app.character, dummything.prefix
) + 1
if self.app.pawncfg.imgpaths:
dummything.paths = self.app.pawncfg.imgpaths
else:
dummything.paths = ['atlas://rltiles/base/unseen']
self.ids.thingtab.add_widget(dummything)
else:
self.app.pawncfg.prefix = self.ids.dummything.prefix
self.app.pawncfg.toggle() | python | def toggle_pawn_cfg(self):
"""Show or hide the pop-over where you can configure the dummy pawn"""
if self.app.manager.current == 'pawncfg':
dummything = self.app.dummything
self.ids.thingtab.remove_widget(dummything)
dummything.clear()
if self.app.pawncfg.prefix:
dummything.prefix = self.app.pawncfg.prefix
dummything.num = dummynum(
self.app.character, dummything.prefix
) + 1
if self.app.pawncfg.imgpaths:
dummything.paths = self.app.pawncfg.imgpaths
else:
dummything.paths = ['atlas://rltiles/base/unseen']
self.ids.thingtab.add_widget(dummything)
else:
self.app.pawncfg.prefix = self.ids.dummything.prefix
self.app.pawncfg.toggle() | [
"def",
"toggle_pawn_cfg",
"(",
"self",
")",
":",
"if",
"self",
".",
"app",
".",
"manager",
".",
"current",
"==",
"'pawncfg'",
":",
"dummything",
"=",
"self",
".",
"app",
".",
"dummything",
"self",
".",
"ids",
".",
"thingtab",
".",
"remove_widget",
"(",
... | Show or hide the pop-over where you can configure the dummy pawn | [
"Show",
"or",
"hide",
"the",
"pop",
"-",
"over",
"where",
"you",
"can",
"configure",
"the",
"dummy",
"pawn"
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/charmenu.py#L120-L138 | train | 32,896 |
LogicalDash/LiSE | LiSE/LiSE/handle.py | dict_delta | def dict_delta(old, new):
"""Return a dictionary containing the items of ``new`` that are either
absent from ``old`` or whose values are different; as well as the
value ``None`` for those keys that are present in ``old``, but
absent from ``new``.
Useful for describing changes between two versions of a dict.
"""
r = {}
oldkeys = set(old.keys())
newkeys = set(new.keys())
r.update((k, new[k]) for k in newkeys.difference(oldkeys))
r.update((k, None) for k in oldkeys.difference(newkeys))
for k in oldkeys.intersection(newkeys):
if old[k] != new[k]:
r[k] = new[k]
return r | python | def dict_delta(old, new):
"""Return a dictionary containing the items of ``new`` that are either
absent from ``old`` or whose values are different; as well as the
value ``None`` for those keys that are present in ``old``, but
absent from ``new``.
Useful for describing changes between two versions of a dict.
"""
r = {}
oldkeys = set(old.keys())
newkeys = set(new.keys())
r.update((k, new[k]) for k in newkeys.difference(oldkeys))
r.update((k, None) for k in oldkeys.difference(newkeys))
for k in oldkeys.intersection(newkeys):
if old[k] != new[k]:
r[k] = new[k]
return r | [
"def",
"dict_delta",
"(",
"old",
",",
"new",
")",
":",
"r",
"=",
"{",
"}",
"oldkeys",
"=",
"set",
"(",
"old",
".",
"keys",
"(",
")",
")",
"newkeys",
"=",
"set",
"(",
"new",
".",
"keys",
"(",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",... | Return a dictionary containing the items of ``new`` that are either
absent from ``old`` or whose values are different; as well as the
value ``None`` for those keys that are present in ``old``, but
absent from ``new``.
Useful for describing changes between two versions of a dict. | [
"Return",
"a",
"dictionary",
"containing",
"the",
"items",
"of",
"new",
"that",
"are",
"either",
"absent",
"from",
"old",
"or",
"whose",
"values",
"are",
"different",
";",
"as",
"well",
"as",
"the",
"value",
"None",
"for",
"those",
"keys",
"that",
"are",
... | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/handle.py#L28-L45 | train | 32,897 |
LogicalDash/LiSE | LiSE/LiSE/handle.py | EngineHandle.character_copy | def character_copy(self, char):
"""Return a dictionary describing character ``char``."""
ret = self.character_stat_copy(char)
chara = self._real.character[char]
nv = self.character_nodes_stat_copy(char)
if nv:
ret['node_val'] = nv
ev = self.character_portals_stat_copy(char)
if ev:
ret['edge_val'] = ev
avs = self.character_avatars_copy(char)
if avs:
ret['avatars'] = avs
rbs = self.character_rulebooks_copy(char)
if rbs:
ret['rulebooks'] = rbs
nrbs = self.character_nodes_rulebooks_copy(char)
if nrbs:
for node, rb in nrbs.items():
assert node in chara.node
if 'node_val' not in ret:
ret['node_val'] = {}
nv = ret['node_val']
if node not in nv:
nv[node] = {}
nv[node]['rulebook'] = rb
porbs = self.character_portals_rulebooks_copy(char)
if porbs:
for orig, dests in porbs.items():
ports = chara.portal[orig]
for dest, rb in dests.items():
assert dest in ports
if 'edge_val' not in ret:
ret['edge_val'] = {}
ev = ret['edge_val']
if orig not in ev:
ev[orig] = {}
ov = ev[orig]
if dest not in ov:
ov[dest] = {}
ov[dest]['rulebook'] = rb
return ret | python | def character_copy(self, char):
"""Return a dictionary describing character ``char``."""
ret = self.character_stat_copy(char)
chara = self._real.character[char]
nv = self.character_nodes_stat_copy(char)
if nv:
ret['node_val'] = nv
ev = self.character_portals_stat_copy(char)
if ev:
ret['edge_val'] = ev
avs = self.character_avatars_copy(char)
if avs:
ret['avatars'] = avs
rbs = self.character_rulebooks_copy(char)
if rbs:
ret['rulebooks'] = rbs
nrbs = self.character_nodes_rulebooks_copy(char)
if nrbs:
for node, rb in nrbs.items():
assert node in chara.node
if 'node_val' not in ret:
ret['node_val'] = {}
nv = ret['node_val']
if node not in nv:
nv[node] = {}
nv[node]['rulebook'] = rb
porbs = self.character_portals_rulebooks_copy(char)
if porbs:
for orig, dests in porbs.items():
ports = chara.portal[orig]
for dest, rb in dests.items():
assert dest in ports
if 'edge_val' not in ret:
ret['edge_val'] = {}
ev = ret['edge_val']
if orig not in ev:
ev[orig] = {}
ov = ev[orig]
if dest not in ov:
ov[dest] = {}
ov[dest]['rulebook'] = rb
return ret | [
"def",
"character_copy",
"(",
"self",
",",
"char",
")",
":",
"ret",
"=",
"self",
".",
"character_stat_copy",
"(",
"char",
")",
"chara",
"=",
"self",
".",
"_real",
".",
"character",
"[",
"char",
"]",
"nv",
"=",
"self",
".",
"character_nodes_stat_copy",
"(... | Return a dictionary describing character ``char``. | [
"Return",
"a",
"dictionary",
"describing",
"character",
"char",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/handle.py#L570-L611 | train | 32,898 |
LogicalDash/LiSE | LiSE/LiSE/handle.py | EngineHandle.character_delta | def character_delta(self, char, *, store=True):
"""Return a dictionary of changes to ``char`` since previous call."""
ret = self.character_stat_delta(char, store=store)
nodes = self.character_nodes_delta(char, store=store)
chara = self._real.character[char]
if nodes:
ret['nodes'] = nodes
edges = self.character_portals_delta(char, store=store)
if edges:
ret['edges'] = edges
avs = self.character_avatars_delta(char, store=store)
if avs:
ret['avatars'] = avs
rbs = self.character_rulebooks_delta(char, store=store)
if rbs:
ret['rulebooks'] = rbs
nrbs = self.character_nodes_rulebooks_delta(char, store=store)
if nrbs:
for node, rb in nrbs.items():
if node not in chara.node:
continue
ret.setdefault('node_val', {}).setdefault(node, {})['rulebook'] = rb
porbs = self.character_portals_rulebooks_delta(char, store=store)
if porbs:
for orig, dests in porbs.items():
if orig not in chara.portal:
continue
portals = chara.portal[orig]
for dest, rb in dests.items():
if dest not in portals:
continue
ret.setdefault('edge_val', {}).setdefault(orig, {}).setdefault(dest, {})['rulebook'] = rb
nv = self.character_nodes_stat_delta(char, store=store)
if nv:
ret['node_val'] = nv
ev = self.character_portals_stat_delta(char, store=store)
if ev:
ret['edge_val'] = ev
return ret | python | def character_delta(self, char, *, store=True):
"""Return a dictionary of changes to ``char`` since previous call."""
ret = self.character_stat_delta(char, store=store)
nodes = self.character_nodes_delta(char, store=store)
chara = self._real.character[char]
if nodes:
ret['nodes'] = nodes
edges = self.character_portals_delta(char, store=store)
if edges:
ret['edges'] = edges
avs = self.character_avatars_delta(char, store=store)
if avs:
ret['avatars'] = avs
rbs = self.character_rulebooks_delta(char, store=store)
if rbs:
ret['rulebooks'] = rbs
nrbs = self.character_nodes_rulebooks_delta(char, store=store)
if nrbs:
for node, rb in nrbs.items():
if node not in chara.node:
continue
ret.setdefault('node_val', {}).setdefault(node, {})['rulebook'] = rb
porbs = self.character_portals_rulebooks_delta(char, store=store)
if porbs:
for orig, dests in porbs.items():
if orig not in chara.portal:
continue
portals = chara.portal[orig]
for dest, rb in dests.items():
if dest not in portals:
continue
ret.setdefault('edge_val', {}).setdefault(orig, {}).setdefault(dest, {})['rulebook'] = rb
nv = self.character_nodes_stat_delta(char, store=store)
if nv:
ret['node_val'] = nv
ev = self.character_portals_stat_delta(char, store=store)
if ev:
ret['edge_val'] = ev
return ret | [
"def",
"character_delta",
"(",
"self",
",",
"char",
",",
"*",
",",
"store",
"=",
"True",
")",
":",
"ret",
"=",
"self",
".",
"character_stat_delta",
"(",
"char",
",",
"store",
"=",
"store",
")",
"nodes",
"=",
"self",
".",
"character_nodes_delta",
"(",
"... | Return a dictionary of changes to ``char`` since previous call. | [
"Return",
"a",
"dictionary",
"of",
"changes",
"to",
"char",
"since",
"previous",
"call",
"."
] | fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84 | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/LiSE/LiSE/handle.py#L613-L651 | train | 32,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.