partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
test
|
main
|
Runs Godot.
|
godot/run.py
|
def main():
""" Runs Godot.
"""
application = GodotApplication( id="godot",
plugins=[CorePlugin(),
PuddlePlugin(),
WorkbenchPlugin(),
ResourcePlugin(),
GodotPlugin()] )
application.run()
|
def main():
""" Runs Godot.
"""
application = GodotApplication( id="godot",
plugins=[CorePlugin(),
PuddlePlugin(),
WorkbenchPlugin(),
ResourcePlugin(),
GodotPlugin()] )
application.run()
|
[
"Runs",
"Godot",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/run.py#L25-L35
|
[
"def",
"main",
"(",
")",
":",
"application",
"=",
"GodotApplication",
"(",
"id",
"=",
"\"godot\"",
",",
"plugins",
"=",
"[",
"CorePlugin",
"(",
")",
",",
"PuddlePlugin",
"(",
")",
",",
"WorkbenchPlugin",
"(",
")",
",",
"ResourcePlugin",
"(",
")",
",",
"GodotPlugin",
"(",
")",
"]",
")",
"application",
".",
"run",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BaseGraphTreeNode.get_children
|
Gets the object's children.
|
godot/ui/graph_tree.py
|
def get_children ( self, object ):
""" Gets the object's children.
"""
children = []
children.extend( object.subgraphs )
children.extend( object.clusters )
children.extend( object.nodes )
children.extend( object.edges )
return children
|
def get_children ( self, object ):
""" Gets the object's children.
"""
children = []
children.extend( object.subgraphs )
children.extend( object.clusters )
children.extend( object.nodes )
children.extend( object.edges )
return children
|
[
"Gets",
"the",
"object",
"s",
"children",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L79-L87
|
[
"def",
"get_children",
"(",
"self",
",",
"object",
")",
":",
"children",
"=",
"[",
"]",
"children",
".",
"extend",
"(",
"object",
".",
"subgraphs",
")",
"children",
".",
"extend",
"(",
"object",
".",
"clusters",
")",
"children",
".",
"extend",
"(",
"object",
".",
"nodes",
")",
"children",
".",
"extend",
"(",
"object",
".",
"edges",
")",
"return",
"children"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BaseGraphTreeNode.append_child
|
Appends a child to the object's children.
|
godot/ui/graph_tree.py
|
def append_child ( self, object, child ):
""" Appends a child to the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.append( child )
elif isinstance( child, Cluster ):
object.clusters.append( child )
elif isinstance( child, Node ):
object.nodes.append( child )
elif isinstance( child, Edge ):
object.edges.append( child )
else:
pass
|
def append_child ( self, object, child ):
""" Appends a child to the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.append( child )
elif isinstance( child, Cluster ):
object.clusters.append( child )
elif isinstance( child, Node ):
object.nodes.append( child )
elif isinstance( child, Edge ):
object.edges.append( child )
else:
pass
|
[
"Appends",
"a",
"child",
"to",
"the",
"object",
"s",
"children",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L90-L106
|
[
"def",
"append_child",
"(",
"self",
",",
"object",
",",
"child",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"Subgraph",
")",
":",
"object",
".",
"subgraphs",
".",
"append",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Cluster",
")",
":",
"object",
".",
"clusters",
".",
"append",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Node",
")",
":",
"object",
".",
"nodes",
".",
"append",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Edge",
")",
":",
"object",
".",
"edges",
".",
"append",
"(",
"child",
")",
"else",
":",
"pass"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BaseGraphTreeNode.insert_child
|
Inserts a child into the object's children.
|
godot/ui/graph_tree.py
|
def insert_child ( self, object, index, child ):
""" Inserts a child into the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.insert( index, child )
elif isinstance( child, Cluster ):
object.clusters.insert( index, child )
elif isinstance( child, Node ):
object.nodes.insert( index, child )
elif isinstance( child, Edge ):
object.edges.insert( index, child )
else:
pass
|
def insert_child ( self, object, index, child ):
""" Inserts a child into the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.insert( index, child )
elif isinstance( child, Cluster ):
object.clusters.insert( index, child )
elif isinstance( child, Node ):
object.nodes.insert( index, child )
elif isinstance( child, Edge ):
object.edges.insert( index, child )
else:
pass
|
[
"Inserts",
"a",
"child",
"into",
"the",
"object",
"s",
"children",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L109-L125
|
[
"def",
"insert_child",
"(",
"self",
",",
"object",
",",
"index",
",",
"child",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"Subgraph",
")",
":",
"object",
".",
"subgraphs",
".",
"insert",
"(",
"index",
",",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Cluster",
")",
":",
"object",
".",
"clusters",
".",
"insert",
"(",
"index",
",",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Node",
")",
":",
"object",
".",
"nodes",
".",
"insert",
"(",
"index",
",",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Edge",
")",
":",
"object",
".",
"edges",
".",
"insert",
"(",
"index",
",",
"child",
")",
"else",
":",
"pass"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BaseGraphTreeNode.delete_child
|
Deletes a child at a specified index from the object's children.
|
godot/ui/graph_tree.py
|
def delete_child ( self, object, index ):
""" Deletes a child at a specified index from the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.pop(index)
elif isinstance( child, Cluster ):
object.clusters.pop( index )
elif isinstance( child, Node ):
object.nodes.pop( index )
elif isinstance( child, Edge ):
object.edges.pop( index )
else:
pass
|
def delete_child ( self, object, index ):
""" Deletes a child at a specified index from the object's children.
"""
if isinstance( child, Subgraph ):
object.subgraphs.pop(index)
elif isinstance( child, Cluster ):
object.clusters.pop( index )
elif isinstance( child, Node ):
object.nodes.pop( index )
elif isinstance( child, Edge ):
object.edges.pop( index )
else:
pass
|
[
"Deletes",
"a",
"child",
"at",
"a",
"specified",
"index",
"from",
"the",
"object",
"s",
"children",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L128-L144
|
[
"def",
"delete_child",
"(",
"self",
",",
"object",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"Subgraph",
")",
":",
"object",
".",
"subgraphs",
".",
"pop",
"(",
"index",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Cluster",
")",
":",
"object",
".",
"clusters",
".",
"pop",
"(",
"index",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Node",
")",
":",
"object",
".",
"nodes",
".",
"pop",
"(",
"index",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Edge",
")",
":",
"object",
".",
"edges",
".",
"pop",
"(",
"index",
")",
"else",
":",
"pass"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BaseGraphTreeNode.when_children_replaced
|
Sets up or removes a listener for children being replaced on a
specified object.
|
godot/ui/graph_tree.py
|
def when_children_replaced ( self, object, listener, remove ):
""" Sets up or removes a listener for children being replaced on a
specified object.
"""
object.on_trait_change( listener, "subgraphs", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "clusters", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "nodes", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "edges", remove = remove,
dispatch = "fast_ui" )
|
def when_children_replaced ( self, object, listener, remove ):
""" Sets up or removes a listener for children being replaced on a
specified object.
"""
object.on_trait_change( listener, "subgraphs", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "clusters", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "nodes", remove = remove,
dispatch = "fast_ui" )
object.on_trait_change( listener, "edges", remove = remove,
dispatch = "fast_ui" )
|
[
"Sets",
"up",
"or",
"removes",
"a",
"listener",
"for",
"children",
"being",
"replaced",
"on",
"a",
"specified",
"object",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L147-L158
|
[
"def",
"when_children_replaced",
"(",
"self",
",",
"object",
",",
"listener",
",",
"remove",
")",
":",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"subgraphs\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"clusters\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"nodes\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"edges\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BaseGraphTreeNode.when_children_changed
|
Sets up or removes a listener for children being changed on a
specified object.
|
godot/ui/graph_tree.py
|
def when_children_changed ( self, object, listener, remove ):
""" Sets up or removes a listener for children being changed on a
specified object.
"""
object.on_trait_change( listener, "subgraphs_items",
remove = remove, dispatch = "fast_ui" )
object.on_trait_change( listener, "clusters_items",
remove = remove, dispatch = "fast_ui" )
object.on_trait_change( listener, "nodes_items",
remove = remove, dispatch = "fast_ui" )
object.on_trait_change( listener, "edges_items",
remove = remove, dispatch = "fast_ui" )
|
def when_children_changed ( self, object, listener, remove ):
""" Sets up or removes a listener for children being changed on a
specified object.
"""
object.on_trait_change( listener, "subgraphs_items",
remove = remove, dispatch = "fast_ui" )
object.on_trait_change( listener, "clusters_items",
remove = remove, dispatch = "fast_ui" )
object.on_trait_change( listener, "nodes_items",
remove = remove, dispatch = "fast_ui" )
object.on_trait_change( listener, "edges_items",
remove = remove, dispatch = "fast_ui" )
|
[
"Sets",
"up",
"or",
"removes",
"a",
"listener",
"for",
"children",
"being",
"changed",
"on",
"a",
"specified",
"object",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_tree.py#L161-L172
|
[
"def",
"when_children_changed",
"(",
"self",
",",
"object",
",",
"listener",
",",
"remove",
")",
":",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"subgraphs_items\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"clusters_items\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"nodes_items\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"\"edges_items\"",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"\"fast_ui\"",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
GraphNode.get_label
|
Gets the label to display for a specified object.
|
godot/ui/graph_editor.py
|
def get_label ( self, object ):
""" Gets the label to display for a specified object.
"""
label = self.label
if label[:1] == '=':
return label[1:]
label = xgetattr( object, label, '' )
if self.formatter is None:
return label
return self.formatter( object, label )
|
def get_label ( self, object ):
""" Gets the label to display for a specified object.
"""
label = self.label
if label[:1] == '=':
return label[1:]
label = xgetattr( object, label, '' )
if self.formatter is None:
return label
return self.formatter( object, label )
|
[
"Gets",
"the",
"label",
"to",
"display",
"for",
"a",
"specified",
"object",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L104-L116
|
[
"def",
"get_label",
"(",
"self",
",",
"object",
")",
":",
"label",
"=",
"self",
".",
"label",
"if",
"label",
"[",
":",
"1",
"]",
"==",
"'='",
":",
"return",
"label",
"[",
"1",
":",
"]",
"label",
"=",
"xgetattr",
"(",
"object",
",",
"label",
",",
"''",
")",
"if",
"self",
".",
"formatter",
"is",
"None",
":",
"return",
"label",
"return",
"self",
".",
"formatter",
"(",
"object",
",",
"label",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
GraphNode.set_label
|
Sets the label for a specified object.
|
godot/ui/graph_editor.py
|
def set_label ( self, object, label ):
""" Sets the label for a specified object.
"""
label_name = self.label
if label_name[:1] != '=':
xsetattr( object, label_name, label )
|
def set_label ( self, object, label ):
""" Sets the label for a specified object.
"""
label_name = self.label
if label_name[:1] != '=':
xsetattr( object, label_name, label )
|
[
"Sets",
"the",
"label",
"for",
"a",
"specified",
"object",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L122-L127
|
[
"def",
"set_label",
"(",
"self",
",",
"object",
",",
"label",
")",
":",
"label_name",
"=",
"self",
".",
"label",
"if",
"label_name",
"[",
":",
"1",
"]",
"!=",
"'='",
":",
"xsetattr",
"(",
"object",
",",
"label_name",
",",
"label",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
GraphNode.when_label_changed
|
Sets up or removes a listener for the label being changed on a
specified object.
|
godot/ui/graph_editor.py
|
def when_label_changed ( self, object, listener, remove ):
""" Sets up or removes a listener for the label being changed on a
specified object.
"""
label = self.label
if label[:1] != '=':
object.on_trait_change( listener, label, remove = remove,
dispatch = 'ui' )
|
def when_label_changed ( self, object, listener, remove ):
""" Sets up or removes a listener for the label being changed on a
specified object.
"""
label = self.label
if label[:1] != '=':
object.on_trait_change( listener, label, remove = remove,
dispatch = 'ui' )
|
[
"Sets",
"up",
"or",
"removes",
"a",
"listener",
"for",
"the",
"label",
"being",
"changed",
"on",
"a",
"specified",
"object",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L133-L140
|
[
"def",
"when_label_changed",
"(",
"self",
",",
"object",
",",
"listener",
",",
"remove",
")",
":",
"label",
"=",
"self",
".",
"label",
"if",
"label",
"[",
":",
"1",
"]",
"!=",
"'='",
":",
"object",
".",
"on_trait_change",
"(",
"listener",
",",
"label",
",",
"remove",
"=",
"remove",
",",
"dispatch",
"=",
"'ui'",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor.init
|
Finishes initialising the editor by creating the underlying toolkit
widget.
|
godot/ui/graph_editor.py
|
def init ( self, parent ):
""" Finishes initialising the editor by creating the underlying toolkit
widget.
"""
self._graph = graph = Graph()
ui = graph.edit_traits(parent=parent, kind="panel")
self.control = ui.control
|
def init ( self, parent ):
""" Finishes initialising the editor by creating the underlying toolkit
widget.
"""
self._graph = graph = Graph()
ui = graph.edit_traits(parent=parent, kind="panel")
self.control = ui.control
|
[
"Finishes",
"initialising",
"the",
"editor",
"by",
"creating",
"the",
"underlying",
"toolkit",
"widget",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L187-L193
|
[
"def",
"init",
"(",
"self",
",",
"parent",
")",
":",
"self",
".",
"_graph",
"=",
"graph",
"=",
"Graph",
"(",
")",
"ui",
"=",
"graph",
".",
"edit_traits",
"(",
"parent",
"=",
"parent",
",",
"kind",
"=",
"\"panel\"",
")",
"self",
".",
"control",
"=",
"ui",
".",
"control"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor.update_editor
|
Updates the editor when the object trait changes externally to the
editor.
|
godot/ui/graph_editor.py
|
def update_editor ( self ):
""" Updates the editor when the object trait changes externally to the
editor.
"""
object = self.value
# Graph the new object...
canvas = self.factory.canvas
if canvas is not None:
for nodes_name in canvas.node_children:
node_children = getattr(object, nodes_name)
self._add_nodes(node_children)
for edges_name in canvas.edge_children:
edge_children = getattr(object, edges_name)
self._add_edges(edge_children)
# ...then listen for changes.
self._add_listeners()
|
def update_editor ( self ):
""" Updates the editor when the object trait changes externally to the
editor.
"""
object = self.value
# Graph the new object...
canvas = self.factory.canvas
if canvas is not None:
for nodes_name in canvas.node_children:
node_children = getattr(object, nodes_name)
self._add_nodes(node_children)
for edges_name in canvas.edge_children:
edge_children = getattr(object, edges_name)
self._add_edges(edge_children)
# ...then listen for changes.
self._add_listeners()
|
[
"Updates",
"the",
"editor",
"when",
"the",
"object",
"trait",
"changes",
"externally",
"to",
"the",
"editor",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L218-L235
|
[
"def",
"update_editor",
"(",
"self",
")",
":",
"object",
"=",
"self",
".",
"value",
"# Graph the new object...",
"canvas",
"=",
"self",
".",
"factory",
".",
"canvas",
"if",
"canvas",
"is",
"not",
"None",
":",
"for",
"nodes_name",
"in",
"canvas",
".",
"node_children",
":",
"node_children",
"=",
"getattr",
"(",
"object",
",",
"nodes_name",
")",
"self",
".",
"_add_nodes",
"(",
"node_children",
")",
"for",
"edges_name",
"in",
"canvas",
".",
"edge_children",
":",
"edge_children",
"=",
"getattr",
"(",
"object",
",",
"edges_name",
")",
"self",
".",
"_add_edges",
"(",
"edge_children",
")",
"# ...then listen for changes.",
"self",
".",
"_add_listeners",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._add_listeners
|
Adds the event listeners for a specified object.
|
godot/ui/graph_editor.py
|
def _add_listeners ( self ):
""" Adds the event listeners for a specified object.
"""
object = self.value
canvas = self.factory.canvas
if canvas is not None:
for name in canvas.node_children:
object.on_trait_change(self._nodes_replaced, name)
object.on_trait_change(self._nodes_changed, name + "_items")
for name in canvas.edge_children:
object.on_trait_change(self._edges_replaced, name)
object.on_trait_change(self._edges_changed, name + "_items")
else:
raise ValueError("Graph canvas not set for graph editor.")
|
def _add_listeners ( self ):
""" Adds the event listeners for a specified object.
"""
object = self.value
canvas = self.factory.canvas
if canvas is not None:
for name in canvas.node_children:
object.on_trait_change(self._nodes_replaced, name)
object.on_trait_change(self._nodes_changed, name + "_items")
for name in canvas.edge_children:
object.on_trait_change(self._edges_replaced, name)
object.on_trait_change(self._edges_changed, name + "_items")
else:
raise ValueError("Graph canvas not set for graph editor.")
|
[
"Adds",
"the",
"event",
"listeners",
"for",
"a",
"specified",
"object",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L241-L255
|
[
"def",
"_add_listeners",
"(",
"self",
")",
":",
"object",
"=",
"self",
".",
"value",
"canvas",
"=",
"self",
".",
"factory",
".",
"canvas",
"if",
"canvas",
"is",
"not",
"None",
":",
"for",
"name",
"in",
"canvas",
".",
"node_children",
":",
"object",
".",
"on_trait_change",
"(",
"self",
".",
"_nodes_replaced",
",",
"name",
")",
"object",
".",
"on_trait_change",
"(",
"self",
".",
"_nodes_changed",
",",
"name",
"+",
"\"_items\"",
")",
"for",
"name",
"in",
"canvas",
".",
"edge_children",
":",
"object",
".",
"on_trait_change",
"(",
"self",
".",
"_edges_replaced",
",",
"name",
")",
"object",
".",
"on_trait_change",
"(",
"self",
".",
"_edges_changed",
",",
"name",
"+",
"\"_items\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Graph canvas not set for graph editor.\"",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._nodes_replaced
|
Handles a list of nodes being set.
|
godot/ui/graph_editor.py
|
def _nodes_replaced(self, object, name, old, new):
""" Handles a list of nodes being set.
"""
self._delete_nodes(old)
self._add_nodes(new)
|
def _nodes_replaced(self, object, name, old, new):
""" Handles a list of nodes being set.
"""
self._delete_nodes(old)
self._add_nodes(new)
|
[
"Handles",
"a",
"list",
"of",
"nodes",
"being",
"set",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L263-L267
|
[
"def",
"_nodes_replaced",
"(",
"self",
",",
"object",
",",
"name",
",",
"old",
",",
"new",
")",
":",
"self",
".",
"_delete_nodes",
"(",
"old",
")",
"self",
".",
"_add_nodes",
"(",
"new",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._nodes_changed
|
Handles addition and removal of nodes.
|
godot/ui/graph_editor.py
|
def _nodes_changed(self, object, name, undefined, event):
""" Handles addition and removal of nodes.
"""
self._delete_nodes(event.removed)
self._add_nodes(event.added)
|
def _nodes_changed(self, object, name, undefined, event):
""" Handles addition and removal of nodes.
"""
self._delete_nodes(event.removed)
self._add_nodes(event.added)
|
[
"Handles",
"addition",
"and",
"removal",
"of",
"nodes",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L270-L274
|
[
"def",
"_nodes_changed",
"(",
"self",
",",
"object",
",",
"name",
",",
"undefined",
",",
"event",
")",
":",
"self",
".",
"_delete_nodes",
"(",
"event",
".",
"removed",
")",
"self",
".",
"_add_nodes",
"(",
"event",
".",
"added",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._add_nodes
|
Adds a node to the graph for each item in 'features' using
the GraphNodes from the editor factory.
|
godot/ui/graph_editor.py
|
def _add_nodes(self, features):
""" Adds a node to the graph for each item in 'features' using
the GraphNodes from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_node in self.factory.nodes:
if feature.__class__ in graph_node.node_for:
graph.add_node( id(feature), **graph_node.dot_attr )
break
graph.arrange_all()
|
def _add_nodes(self, features):
""" Adds a node to the graph for each item in 'features' using
the GraphNodes from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_node in self.factory.nodes:
if feature.__class__ in graph_node.node_for:
graph.add_node( id(feature), **graph_node.dot_attr )
break
graph.arrange_all()
|
[
"Adds",
"a",
"node",
"to",
"the",
"graph",
"for",
"each",
"item",
"in",
"features",
"using",
"the",
"GraphNodes",
"from",
"the",
"editor",
"factory",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L277-L290
|
[
"def",
"_add_nodes",
"(",
"self",
",",
"features",
")",
":",
"graph",
"=",
"self",
".",
"_graph",
"if",
"graph",
"is",
"not",
"None",
":",
"for",
"feature",
"in",
"features",
":",
"for",
"graph_node",
"in",
"self",
".",
"factory",
".",
"nodes",
":",
"if",
"feature",
".",
"__class__",
"in",
"graph_node",
".",
"node_for",
":",
"graph",
".",
"add_node",
"(",
"id",
"(",
"feature",
")",
",",
"*",
"*",
"graph_node",
".",
"dot_attr",
")",
"break",
"graph",
".",
"arrange_all",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._delete_nodes
|
Removes the node corresponding to each item in 'features'.
|
godot/ui/graph_editor.py
|
def _delete_nodes(self, features):
""" Removes the node corresponding to each item in 'features'.
"""
graph = self._graph
if graph is not None:
for feature in features:
graph.delete_node( id(feature) )
graph.arrange_all()
|
def _delete_nodes(self, features):
""" Removes the node corresponding to each item in 'features'.
"""
graph = self._graph
if graph is not None:
for feature in features:
graph.delete_node( id(feature) )
graph.arrange_all()
|
[
"Removes",
"the",
"node",
"corresponding",
"to",
"each",
"item",
"in",
"features",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L293-L302
|
[
"def",
"_delete_nodes",
"(",
"self",
",",
"features",
")",
":",
"graph",
"=",
"self",
".",
"_graph",
"if",
"graph",
"is",
"not",
"None",
":",
"for",
"feature",
"in",
"features",
":",
"graph",
".",
"delete_node",
"(",
"id",
"(",
"feature",
")",
")",
"graph",
".",
"arrange_all",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._edges_replaced
|
Handles a list of edges being set.
|
godot/ui/graph_editor.py
|
def _edges_replaced(self, object, name, old, new):
""" Handles a list of edges being set.
"""
self._delete_edges(old)
self._add_edges(new)
|
def _edges_replaced(self, object, name, old, new):
""" Handles a list of edges being set.
"""
self._delete_edges(old)
self._add_edges(new)
|
[
"Handles",
"a",
"list",
"of",
"edges",
"being",
"set",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L308-L312
|
[
"def",
"_edges_replaced",
"(",
"self",
",",
"object",
",",
"name",
",",
"old",
",",
"new",
")",
":",
"self",
".",
"_delete_edges",
"(",
"old",
")",
"self",
".",
"_add_edges",
"(",
"new",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._edges_changed
|
Handles addition and removal of edges.
|
godot/ui/graph_editor.py
|
def _edges_changed(self, object, name, undefined, event):
""" Handles addition and removal of edges.
"""
self._delete_edges(event.removed)
self._add_edges(event.added)
|
def _edges_changed(self, object, name, undefined, event):
""" Handles addition and removal of edges.
"""
self._delete_edges(event.removed)
self._add_edges(event.added)
|
[
"Handles",
"addition",
"and",
"removal",
"of",
"edges",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L315-L319
|
[
"def",
"_edges_changed",
"(",
"self",
",",
"object",
",",
"name",
",",
"undefined",
",",
"event",
")",
":",
"self",
".",
"_delete_edges",
"(",
"event",
".",
"removed",
")",
"self",
".",
"_add_edges",
"(",
"event",
".",
"added",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._add_edges
|
Adds an edge to the graph for each item in 'features' using
the GraphEdges from the editor factory.
|
godot/ui/graph_editor.py
|
def _add_edges(self, features):
""" Adds an edge to the graph for each item in 'features' using
the GraphEdges from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_edge in self.factory.edges:
if feature.__class__ in graph_edge.edge_for:
tail_feature = getattr(feature, graph_edge.tail_name)
head_feature = getattr(feature, graph_edge.head_name)
graph.add_edge( id(tail_feature), id(head_feature),
**graph_edge.dot_attr )
break
graph.arrange_all()
|
def _add_edges(self, features):
""" Adds an edge to the graph for each item in 'features' using
the GraphEdges from the editor factory.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_edge in self.factory.edges:
if feature.__class__ in graph_edge.edge_for:
tail_feature = getattr(feature, graph_edge.tail_name)
head_feature = getattr(feature, graph_edge.head_name)
graph.add_edge( id(tail_feature), id(head_feature),
**graph_edge.dot_attr )
break
graph.arrange_all()
|
[
"Adds",
"an",
"edge",
"to",
"the",
"graph",
"for",
"each",
"item",
"in",
"features",
"using",
"the",
"GraphEdges",
"from",
"the",
"editor",
"factory",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L322-L340
|
[
"def",
"_add_edges",
"(",
"self",
",",
"features",
")",
":",
"graph",
"=",
"self",
".",
"_graph",
"if",
"graph",
"is",
"not",
"None",
":",
"for",
"feature",
"in",
"features",
":",
"for",
"graph_edge",
"in",
"self",
".",
"factory",
".",
"edges",
":",
"if",
"feature",
".",
"__class__",
"in",
"graph_edge",
".",
"edge_for",
":",
"tail_feature",
"=",
"getattr",
"(",
"feature",
",",
"graph_edge",
".",
"tail_name",
")",
"head_feature",
"=",
"getattr",
"(",
"feature",
",",
"graph_edge",
".",
"head_name",
")",
"graph",
".",
"add_edge",
"(",
"id",
"(",
"tail_feature",
")",
",",
"id",
"(",
"head_feature",
")",
",",
"*",
"*",
"graph_edge",
".",
"dot_attr",
")",
"break",
"graph",
".",
"arrange_all",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
SimpleGraphEditor._delete_edges
|
Removes the node corresponding to each item in 'features'.
|
godot/ui/graph_editor.py
|
def _delete_edges(self, features):
""" Removes the node corresponding to each item in 'features'.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_edge in self.factory.edges:
if feature.__class__ in graph_edge.edge_for:
tail_feature = getattr(feature, graph_edge.tail_name)
head_feature = getattr(feature, graph_edge.head_name)
graph.delete_edge( id(tail_feature), id(head_feature) )
graph.arrange_all()
|
def _delete_edges(self, features):
""" Removes the node corresponding to each item in 'features'.
"""
graph = self._graph
if graph is not None:
for feature in features:
for graph_edge in self.factory.edges:
if feature.__class__ in graph_edge.edge_for:
tail_feature = getattr(feature, graph_edge.tail_name)
head_feature = getattr(feature, graph_edge.head_name)
graph.delete_edge( id(tail_feature), id(head_feature) )
graph.arrange_all()
|
[
"Removes",
"the",
"node",
"corresponding",
"to",
"each",
"item",
"in",
"features",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_editor.py#L343-L357
|
[
"def",
"_delete_edges",
"(",
"self",
",",
"features",
")",
":",
"graph",
"=",
"self",
".",
"_graph",
"if",
"graph",
"is",
"not",
"None",
":",
"for",
"feature",
"in",
"features",
":",
"for",
"graph_edge",
"in",
"self",
".",
"factory",
".",
"edges",
":",
"if",
"feature",
".",
"__class__",
"in",
"graph_edge",
".",
"edge_for",
":",
"tail_feature",
"=",
"getattr",
"(",
"feature",
",",
"graph_edge",
".",
"tail_name",
")",
"head_feature",
"=",
"getattr",
"(",
"feature",
",",
"graph_edge",
".",
"head_name",
")",
"graph",
".",
"delete_edge",
"(",
"id",
"(",
"tail_feature",
")",
",",
"id",
"(",
"head_feature",
")",
")",
"graph",
".",
"arrange_all",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Edge._get_name
|
Property getter.
|
godot/edge.py
|
def _get_name(self):
""" Property getter.
"""
if (self.tail_node is not None) and (self.head_node is not None):
return "%s %s %s" % (self.tail_node.ID, self.conn,
self.head_node.ID)
else:
return "Edge"
|
def _get_name(self):
""" Property getter.
"""
if (self.tail_node is not None) and (self.head_node is not None):
return "%s %s %s" % (self.tail_node.ID, self.conn,
self.head_node.ID)
else:
return "Edge"
|
[
"Property",
"getter",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/edge.py#L693-L700
|
[
"def",
"_get_name",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"tail_node",
"is",
"not",
"None",
")",
"and",
"(",
"self",
".",
"head_node",
"is",
"not",
"None",
")",
":",
"return",
"\"%s %s %s\"",
"%",
"(",
"self",
".",
"tail_node",
".",
"ID",
",",
"self",
".",
"conn",
",",
"self",
".",
"head_node",
".",
"ID",
")",
"else",
":",
"return",
"\"Edge\""
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Edge.arrange_all
|
Arrange the components of the node using Graphviz.
|
godot/edge.py
|
def arrange_all(self):
""" Arrange the components of the node using Graphviz.
"""
# FIXME: Circular reference avoidance.
import godot.dot_data_parser
import godot.graph
graph = godot.graph.Graph( ID="g", directed=True )
self.conn = "->"
graph.edges.append( self )
xdot_data = graph.create( format="xdot" )
# print "XDOT DATA:", xdot_data
parser = godot.dot_data_parser.GodotDataParser()
ndata = xdot_data.replace('\\\n','')
tokens = parser.dotparser.parseString(ndata)[0]
for element in tokens[3]:
cmd = element[0]
if cmd == "add_edge":
cmd, src, dest, opts = element
self.set( **opts )
|
def arrange_all(self):
""" Arrange the components of the node using Graphviz.
"""
# FIXME: Circular reference avoidance.
import godot.dot_data_parser
import godot.graph
graph = godot.graph.Graph( ID="g", directed=True )
self.conn = "->"
graph.edges.append( self )
xdot_data = graph.create( format="xdot" )
# print "XDOT DATA:", xdot_data
parser = godot.dot_data_parser.GodotDataParser()
ndata = xdot_data.replace('\\\n','')
tokens = parser.dotparser.parseString(ndata)[0]
for element in tokens[3]:
cmd = element[0]
if cmd == "add_edge":
cmd, src, dest, opts = element
self.set( **opts )
|
[
"Arrange",
"the",
"components",
"of",
"the",
"node",
"using",
"Graphviz",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/edge.py#L707-L729
|
[
"def",
"arrange_all",
"(",
"self",
")",
":",
"# FIXME: Circular reference avoidance.",
"import",
"godot",
".",
"dot_data_parser",
"import",
"godot",
".",
"graph",
"graph",
"=",
"godot",
".",
"graph",
".",
"Graph",
"(",
"ID",
"=",
"\"g\"",
",",
"directed",
"=",
"True",
")",
"self",
".",
"conn",
"=",
"\"->\"",
"graph",
".",
"edges",
".",
"append",
"(",
"self",
")",
"xdot_data",
"=",
"graph",
".",
"create",
"(",
"format",
"=",
"\"xdot\"",
")",
"# print \"XDOT DATA:\", xdot_data",
"parser",
"=",
"godot",
".",
"dot_data_parser",
".",
"GodotDataParser",
"(",
")",
"ndata",
"=",
"xdot_data",
".",
"replace",
"(",
"'\\\\\\n'",
",",
"''",
")",
"tokens",
"=",
"parser",
".",
"dotparser",
".",
"parseString",
"(",
"ndata",
")",
"[",
"0",
"]",
"for",
"element",
"in",
"tokens",
"[",
"3",
"]",
":",
"cmd",
"=",
"element",
"[",
"0",
"]",
"if",
"cmd",
"==",
"\"add_edge\"",
":",
"cmd",
",",
"src",
",",
"dest",
",",
"opts",
"=",
"element",
"self",
".",
"set",
"(",
"*",
"*",
"opts",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Edge._parse_xdot_directive
|
Handles parsing Xdot drawing directives.
|
godot/edge.py
|
def _parse_xdot_directive(self, name, new):
""" Handles parsing Xdot drawing directives.
"""
parser = XdotAttrParser()
components = parser.parse_xdot_data(new)
# The absolute coordinate of the drawing container wrt graph origin.
x1 = min( [c.x for c in components] )
y1 = min( [c.y for c in components] )
print "X1/Y1:", name, x1, y1
# Components are positioned relative to their container. This
# function positions the bottom-left corner of the components at
# their origin rather than relative to the graph.
# move_to_origin( components )
for c in components:
if isinstance(c, Ellipse):
component.x_origin -= x1
component.y_origin -= y1
# c.position = [ c.x - x1, c.y - y1 ]
elif isinstance(c, (Polygon, BSpline)):
print "Points:", c.points
c.points = [ (t[0] - x1, t[1] - y1) for t in c.points ]
print "Points:", c.points
elif isinstance(c, Text):
# font = str_to_font( str(c.pen.font) )
c.text_x, c.text_y = c.x - x1, c.y - y1
container = Container(auto_size=True,
position=[ x1, y1 ],
bgcolor="yellow")
container.add( *components )
if name == "_draw_":
self.drawing = container
elif name == "_hdraw_":
self.arrowhead_drawing = container
else:
raise
|
def _parse_xdot_directive(self, name, new):
""" Handles parsing Xdot drawing directives.
"""
parser = XdotAttrParser()
components = parser.parse_xdot_data(new)
# The absolute coordinate of the drawing container wrt graph origin.
x1 = min( [c.x for c in components] )
y1 = min( [c.y for c in components] )
print "X1/Y1:", name, x1, y1
# Components are positioned relative to their container. This
# function positions the bottom-left corner of the components at
# their origin rather than relative to the graph.
# move_to_origin( components )
for c in components:
if isinstance(c, Ellipse):
component.x_origin -= x1
component.y_origin -= y1
# c.position = [ c.x - x1, c.y - y1 ]
elif isinstance(c, (Polygon, BSpline)):
print "Points:", c.points
c.points = [ (t[0] - x1, t[1] - y1) for t in c.points ]
print "Points:", c.points
elif isinstance(c, Text):
# font = str_to_font( str(c.pen.font) )
c.text_x, c.text_y = c.x - x1, c.y - y1
container = Container(auto_size=True,
position=[ x1, y1 ],
bgcolor="yellow")
container.add( *components )
if name == "_draw_":
self.drawing = container
elif name == "_hdraw_":
self.arrowhead_drawing = container
else:
raise
|
[
"Handles",
"parsing",
"Xdot",
"drawing",
"directives",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/edge.py#L733-L776
|
[
"def",
"_parse_xdot_directive",
"(",
"self",
",",
"name",
",",
"new",
")",
":",
"parser",
"=",
"XdotAttrParser",
"(",
")",
"components",
"=",
"parser",
".",
"parse_xdot_data",
"(",
"new",
")",
"# The absolute coordinate of the drawing container wrt graph origin.",
"x1",
"=",
"min",
"(",
"[",
"c",
".",
"x",
"for",
"c",
"in",
"components",
"]",
")",
"y1",
"=",
"min",
"(",
"[",
"c",
".",
"y",
"for",
"c",
"in",
"components",
"]",
")",
"print",
"\"X1/Y1:\"",
",",
"name",
",",
"x1",
",",
"y1",
"# Components are positioned relative to their container. This",
"# function positions the bottom-left corner of the components at",
"# their origin rather than relative to the graph.",
"# move_to_origin( components )",
"for",
"c",
"in",
"components",
":",
"if",
"isinstance",
"(",
"c",
",",
"Ellipse",
")",
":",
"component",
".",
"x_origin",
"-=",
"x1",
"component",
".",
"y_origin",
"-=",
"y1",
"# c.position = [ c.x - x1, c.y - y1 ]",
"elif",
"isinstance",
"(",
"c",
",",
"(",
"Polygon",
",",
"BSpline",
")",
")",
":",
"print",
"\"Points:\"",
",",
"c",
".",
"points",
"c",
".",
"points",
"=",
"[",
"(",
"t",
"[",
"0",
"]",
"-",
"x1",
",",
"t",
"[",
"1",
"]",
"-",
"y1",
")",
"for",
"t",
"in",
"c",
".",
"points",
"]",
"print",
"\"Points:\"",
",",
"c",
".",
"points",
"elif",
"isinstance",
"(",
"c",
",",
"Text",
")",
":",
"# font = str_to_font( str(c.pen.font) )",
"c",
".",
"text_x",
",",
"c",
".",
"text_y",
"=",
"c",
".",
"x",
"-",
"x1",
",",
"c",
".",
"y",
"-",
"y1",
"container",
"=",
"Container",
"(",
"auto_size",
"=",
"True",
",",
"position",
"=",
"[",
"x1",
",",
"y1",
"]",
",",
"bgcolor",
"=",
"\"yellow\"",
")",
"container",
".",
"add",
"(",
"*",
"components",
")",
"if",
"name",
"==",
"\"_draw_\"",
":",
"self",
".",
"drawing",
"=",
"container",
"elif",
"name",
"==",
"\"_hdraw_\"",
":",
"self",
".",
"arrowhead_drawing",
"=",
"container",
"else",
":",
"raise"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Edge._on_drawing
|
Handles the containers of drawing components being set.
|
godot/edge.py
|
def _on_drawing(self, object, name, old, new):
""" Handles the containers of drawing components being set.
"""
attrs = [ "drawing", "arrowhead_drawing" ]
others = [getattr(self, a) for a in attrs \
if (a != name) and (getattr(self, a) is not None)]
x, y = self.component.position
print "POS:", x, y, self.component.position
abs_x = [d.x + x for d in others]
abs_y = [d.y + y for d in others]
print "ABS:", abs_x, abs_y
# Assume that he new drawing is positioned relative to graph origin.
x1 = min( abs_x + [new.x] )
y1 = min( abs_y + [new.y] )
print "DRAW:", new.position
new.position = [ new.x - x1, new.y - y1 ]
print "DRAW:", new.position
# for i, b in enumerate( others ):
# self.drawing.position = [100, 100]
# self.drawing.request_redraw()
# print "OTHER:", b.position, abs_x[i] - x1
# b.position = [ abs_x[i] - x1, abs_y[i] - y1 ]
# b.x = 50
# b.y = 50
# print "OTHER:", b.position, abs_x[i], x1
# for attr in attrs:
# if attr != name:
# if getattr(self, attr) is not None:
# drawing = getattr(self, attr)
# drawing.position = [50, 50]
if old is not None:
self.component.remove( old )
if new is not None:
self.component.add( new )
print "POS NEW:", self.component.position
self.component.position = [ x1, y1 ]
print "POS NEW:", self.component.position
self.component.request_redraw()
print "POS NEW:", self.component.position
|
def _on_drawing(self, object, name, old, new):
""" Handles the containers of drawing components being set.
"""
attrs = [ "drawing", "arrowhead_drawing" ]
others = [getattr(self, a) for a in attrs \
if (a != name) and (getattr(self, a) is not None)]
x, y = self.component.position
print "POS:", x, y, self.component.position
abs_x = [d.x + x for d in others]
abs_y = [d.y + y for d in others]
print "ABS:", abs_x, abs_y
# Assume that he new drawing is positioned relative to graph origin.
x1 = min( abs_x + [new.x] )
y1 = min( abs_y + [new.y] )
print "DRAW:", new.position
new.position = [ new.x - x1, new.y - y1 ]
print "DRAW:", new.position
# for i, b in enumerate( others ):
# self.drawing.position = [100, 100]
# self.drawing.request_redraw()
# print "OTHER:", b.position, abs_x[i] - x1
# b.position = [ abs_x[i] - x1, abs_y[i] - y1 ]
# b.x = 50
# b.y = 50
# print "OTHER:", b.position, abs_x[i], x1
# for attr in attrs:
# if attr != name:
# if getattr(self, attr) is not None:
# drawing = getattr(self, attr)
# drawing.position = [50, 50]
if old is not None:
self.component.remove( old )
if new is not None:
self.component.add( new )
print "POS NEW:", self.component.position
self.component.position = [ x1, y1 ]
print "POS NEW:", self.component.position
self.component.request_redraw()
print "POS NEW:", self.component.position
|
[
"Handles",
"the",
"containers",
"of",
"drawing",
"components",
"being",
"set",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/edge.py#L780-L828
|
[
"def",
"_on_drawing",
"(",
"self",
",",
"object",
",",
"name",
",",
"old",
",",
"new",
")",
":",
"attrs",
"=",
"[",
"\"drawing\"",
",",
"\"arrowhead_drawing\"",
"]",
"others",
"=",
"[",
"getattr",
"(",
"self",
",",
"a",
")",
"for",
"a",
"in",
"attrs",
"if",
"(",
"a",
"!=",
"name",
")",
"and",
"(",
"getattr",
"(",
"self",
",",
"a",
")",
"is",
"not",
"None",
")",
"]",
"x",
",",
"y",
"=",
"self",
".",
"component",
".",
"position",
"print",
"\"POS:\"",
",",
"x",
",",
"y",
",",
"self",
".",
"component",
".",
"position",
"abs_x",
"=",
"[",
"d",
".",
"x",
"+",
"x",
"for",
"d",
"in",
"others",
"]",
"abs_y",
"=",
"[",
"d",
".",
"y",
"+",
"y",
"for",
"d",
"in",
"others",
"]",
"print",
"\"ABS:\"",
",",
"abs_x",
",",
"abs_y",
"# Assume that he new drawing is positioned relative to graph origin.",
"x1",
"=",
"min",
"(",
"abs_x",
"+",
"[",
"new",
".",
"x",
"]",
")",
"y1",
"=",
"min",
"(",
"abs_y",
"+",
"[",
"new",
".",
"y",
"]",
")",
"print",
"\"DRAW:\"",
",",
"new",
".",
"position",
"new",
".",
"position",
"=",
"[",
"new",
".",
"x",
"-",
"x1",
",",
"new",
".",
"y",
"-",
"y1",
"]",
"print",
"\"DRAW:\"",
",",
"new",
".",
"position",
"# for i, b in enumerate( others ):",
"# self.drawing.position = [100, 100]",
"# self.drawing.request_redraw()",
"# print \"OTHER:\", b.position, abs_x[i] - x1",
"# b.position = [ abs_x[i] - x1, abs_y[i] - y1 ]",
"# b.x = 50",
"# b.y = 50",
"# print \"OTHER:\", b.position, abs_x[i], x1",
"# for attr in attrs:",
"# if attr != name:",
"# if getattr(self, attr) is not None:",
"# drawing = getattr(self, attr)",
"# drawing.position = [50, 50]",
"if",
"old",
"is",
"not",
"None",
":",
"self",
".",
"component",
".",
"remove",
"(",
"old",
")",
"if",
"new",
"is",
"not",
"None",
":",
"self",
".",
"component",
".",
"add",
"(",
"new",
")",
"print",
"\"POS NEW:\"",
",",
"self",
".",
"component",
".",
"position",
"self",
".",
"component",
".",
"position",
"=",
"[",
"x1",
",",
"y1",
"]",
"print",
"\"POS NEW:\"",
",",
"self",
".",
"component",
".",
"position",
"self",
".",
"component",
".",
"request_redraw",
"(",
")",
"print",
"\"POS NEW:\"",
",",
"self",
".",
"component",
".",
"position"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
node_factory
|
Give new nodes a unique ID.
|
godot/ui/graph_view.py
|
def node_factory(**row_factory_kw):
""" Give new nodes a unique ID. """
if "__table_editor__" in row_factory_kw:
graph = row_factory_kw["__table_editor__"].object
ID = make_unique_name("n", [node.ID for node in graph.nodes])
del row_factory_kw["__table_editor__"]
return godot.node.Node(ID)
else:
return godot.node.Node(uuid.uuid4().hex[:6])
|
def node_factory(**row_factory_kw):
""" Give new nodes a unique ID. """
if "__table_editor__" in row_factory_kw:
graph = row_factory_kw["__table_editor__"].object
ID = make_unique_name("n", [node.ID for node in graph.nodes])
del row_factory_kw["__table_editor__"]
return godot.node.Node(ID)
else:
return godot.node.Node(uuid.uuid4().hex[:6])
|
[
"Give",
"new",
"nodes",
"a",
"unique",
"ID",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view.py#L58-L67
|
[
"def",
"node_factory",
"(",
"*",
"*",
"row_factory_kw",
")",
":",
"if",
"\"__table_editor__\"",
"in",
"row_factory_kw",
":",
"graph",
"=",
"row_factory_kw",
"[",
"\"__table_editor__\"",
"]",
".",
"object",
"ID",
"=",
"make_unique_name",
"(",
"\"n\"",
",",
"[",
"node",
".",
"ID",
"for",
"node",
"in",
"graph",
".",
"nodes",
"]",
")",
"del",
"row_factory_kw",
"[",
"\"__table_editor__\"",
"]",
"return",
"godot",
".",
"node",
".",
"Node",
"(",
"ID",
")",
"else",
":",
"return",
"godot",
".",
"node",
".",
"Node",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
"[",
":",
"6",
"]",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
edge_factory
|
Give new edges a unique ID.
|
godot/ui/graph_view.py
|
def edge_factory(**row_factory_kw):
""" Give new edges a unique ID. """
if "__table_editor__" in row_factory_kw:
table_editor = row_factory_kw["__table_editor__"]
graph = table_editor.object
ID = make_unique_name("node", [node.ID for node in graph.nodes])
n_nodes = len(graph.nodes)
IDs = [v.ID for v in graph.nodes]
if n_nodes == 0:
tail_node = godot.Node(ID=make_unique_name("n", IDs))
head_node = godot.Node(ID=make_unique_name("n", IDs))
elif n_nodes == 1:
tail_node = graph.nodes[0]
head_node = godot.Node(ID=make_unique_name("n", IDs))
else:
tail_node = graph.nodes[0]
head_node = graph.nodes[1]
return godot.edge.Edge(tail_node, head_node, _nodes=graph.nodes)
else:
return None
|
def edge_factory(**row_factory_kw):
""" Give new edges a unique ID. """
if "__table_editor__" in row_factory_kw:
table_editor = row_factory_kw["__table_editor__"]
graph = table_editor.object
ID = make_unique_name("node", [node.ID for node in graph.nodes])
n_nodes = len(graph.nodes)
IDs = [v.ID for v in graph.nodes]
if n_nodes == 0:
tail_node = godot.Node(ID=make_unique_name("n", IDs))
head_node = godot.Node(ID=make_unique_name("n", IDs))
elif n_nodes == 1:
tail_node = graph.nodes[0]
head_node = godot.Node(ID=make_unique_name("n", IDs))
else:
tail_node = graph.nodes[0]
head_node = graph.nodes[1]
return godot.edge.Edge(tail_node, head_node, _nodes=graph.nodes)
else:
return None
|
[
"Give",
"new",
"edges",
"a",
"unique",
"ID",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/ui/graph_view.py#L99-L122
|
[
"def",
"edge_factory",
"(",
"*",
"*",
"row_factory_kw",
")",
":",
"if",
"\"__table_editor__\"",
"in",
"row_factory_kw",
":",
"table_editor",
"=",
"row_factory_kw",
"[",
"\"__table_editor__\"",
"]",
"graph",
"=",
"table_editor",
".",
"object",
"ID",
"=",
"make_unique_name",
"(",
"\"node\"",
",",
"[",
"node",
".",
"ID",
"for",
"node",
"in",
"graph",
".",
"nodes",
"]",
")",
"n_nodes",
"=",
"len",
"(",
"graph",
".",
"nodes",
")",
"IDs",
"=",
"[",
"v",
".",
"ID",
"for",
"v",
"in",
"graph",
".",
"nodes",
"]",
"if",
"n_nodes",
"==",
"0",
":",
"tail_node",
"=",
"godot",
".",
"Node",
"(",
"ID",
"=",
"make_unique_name",
"(",
"\"n\"",
",",
"IDs",
")",
")",
"head_node",
"=",
"godot",
".",
"Node",
"(",
"ID",
"=",
"make_unique_name",
"(",
"\"n\"",
",",
"IDs",
")",
")",
"elif",
"n_nodes",
"==",
"1",
":",
"tail_node",
"=",
"graph",
".",
"nodes",
"[",
"0",
"]",
"head_node",
"=",
"godot",
".",
"Node",
"(",
"ID",
"=",
"make_unique_name",
"(",
"\"n\"",
",",
"IDs",
")",
")",
"else",
":",
"tail_node",
"=",
"graph",
".",
"nodes",
"[",
"0",
"]",
"head_node",
"=",
"graph",
".",
"nodes",
"[",
"1",
"]",
"return",
"godot",
".",
"edge",
".",
"Edge",
"(",
"tail_node",
",",
"head_node",
",",
"_nodes",
"=",
"graph",
".",
"nodes",
")",
"else",
":",
"return",
"None"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
MongoEngineConnection.start
|
Initialize the database connection.
|
web/db/me.py
|
def start(self, context):
"""Initialize the database connection."""
self.config['alias'] = self.alias
safe_config = dict(self.config)
del safe_config['host']
log.info("Connecting MongoEngine database layer.", extra=dict(
uri = redact_uri(self.config['host']),
config = self.config,
))
self.connection = connect(**self.config)
|
def start(self, context):
"""Initialize the database connection."""
self.config['alias'] = self.alias
safe_config = dict(self.config)
del safe_config['host']
log.info("Connecting MongoEngine database layer.", extra=dict(
uri = redact_uri(self.config['host']),
config = self.config,
))
self.connection = connect(**self.config)
|
[
"Initialize",
"the",
"database",
"connection",
"."
] |
marrow/web.db
|
python
|
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/db/me.py#L71-L83
|
[
"def",
"start",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"config",
"[",
"'alias'",
"]",
"=",
"self",
".",
"alias",
"safe_config",
"=",
"dict",
"(",
"self",
".",
"config",
")",
"del",
"safe_config",
"[",
"'host'",
"]",
"log",
".",
"info",
"(",
"\"Connecting MongoEngine database layer.\"",
",",
"extra",
"=",
"dict",
"(",
"uri",
"=",
"redact_uri",
"(",
"self",
".",
"config",
"[",
"'host'",
"]",
")",
",",
"config",
"=",
"self",
".",
"config",
",",
")",
")",
"self",
".",
"connection",
"=",
"connect",
"(",
"*",
"*",
"self",
".",
"config",
")"
] |
c755fbff7028a5edc223d6a631b8421858274fc4
|
test
|
MongoEngineConnection.prepare
|
Attach this connection's default database to the context using our alias.
|
web/db/me.py
|
def prepare(self, context):
"""Attach this connection's default database to the context using our alias."""
context.db[self.alias] = MongoEngineProxy(self.connection)
|
def prepare(self, context):
"""Attach this connection's default database to the context using our alias."""
context.db[self.alias] = MongoEngineProxy(self.connection)
|
[
"Attach",
"this",
"connection",
"s",
"default",
"database",
"to",
"the",
"context",
"using",
"our",
"alias",
"."
] |
marrow/web.db
|
python
|
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/db/me.py#L85-L88
|
[
"def",
"prepare",
"(",
"self",
",",
"context",
")",
":",
"context",
".",
"db",
"[",
"self",
".",
"alias",
"]",
"=",
"MongoEngineProxy",
"(",
"self",
".",
"connection",
")"
] |
c755fbff7028a5edc223d6a631b8421858274fc4
|
test
|
Node._component_default
|
Trait initialiser.
|
godot/node.py
|
def _component_default(self):
""" Trait initialiser.
"""
component = Container(fit_window=False, auto_size=True,
bgcolor="green")#, position=list(self.pos) )
component.tools.append( MoveTool(component) )
# component.tools.append( TraitsTool(component) )
return component
|
def _component_default(self):
""" Trait initialiser.
"""
component = Container(fit_window=False, auto_size=True,
bgcolor="green")#, position=list(self.pos) )
component.tools.append( MoveTool(component) )
# component.tools.append( TraitsTool(component) )
return component
|
[
"Trait",
"initialiser",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L569-L576
|
[
"def",
"_component_default",
"(",
"self",
")",
":",
"component",
"=",
"Container",
"(",
"fit_window",
"=",
"False",
",",
"auto_size",
"=",
"True",
",",
"bgcolor",
"=",
"\"green\"",
")",
"#, position=list(self.pos) )",
"component",
".",
"tools",
".",
"append",
"(",
"MoveTool",
"(",
"component",
")",
")",
"# component.tools.append( TraitsTool(component) )",
"return",
"component"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node._vp_default
|
Trait initialiser.
|
godot/node.py
|
def _vp_default(self):
""" Trait initialiser.
"""
vp = Viewport(component=self.component)
vp.enable_zoom=True
# vp.view_position = [-10, -10]
vp.tools.append(ViewportPanTool(vp))
return vp
|
def _vp_default(self):
""" Trait initialiser.
"""
vp = Viewport(component=self.component)
vp.enable_zoom=True
# vp.view_position = [-10, -10]
vp.tools.append(ViewportPanTool(vp))
return vp
|
[
"Trait",
"initialiser",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L579-L586
|
[
"def",
"_vp_default",
"(",
"self",
")",
":",
"vp",
"=",
"Viewport",
"(",
"component",
"=",
"self",
".",
"component",
")",
"vp",
".",
"enable_zoom",
"=",
"True",
"# vp.view_position = [-10, -10]",
"vp",
".",
"tools",
".",
"append",
"(",
"ViewportPanTool",
"(",
"vp",
")",
")",
"return",
"vp"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node.arrange_all
|
Arrange the components of the node using Graphviz.
|
godot/node.py
|
def arrange_all(self):
""" Arrange the components of the node using Graphviz.
"""
# FIXME: Circular reference avoidance.
import godot.dot_data_parser
import godot.graph
graph = godot.graph.Graph(ID="g")
graph.add_node(self)
print "GRAPH DOT:\n", str(graph)
xdot_data = graph.create( format = "xdot" )
print "XDOT DATA:\n", xdot_data
parser = godot.dot_data_parser.GodotDataParser()
# parser.parse_dot_data(xdot_data)
flat_data = xdot_data.replace('\\\n','')
tokens = parser.dotparser.parseString(flat_data)[0]
for element in tokens[3]:
print "TOK:", element
cmd = element[0]
if cmd == 'add_node':
cmd, nodename, opts = element
assert nodename == self.ID
print "OPTIONS:", opts
self.set( **opts )
|
def arrange_all(self):
""" Arrange the components of the node using Graphviz.
"""
# FIXME: Circular reference avoidance.
import godot.dot_data_parser
import godot.graph
graph = godot.graph.Graph(ID="g")
graph.add_node(self)
print "GRAPH DOT:\n", str(graph)
xdot_data = graph.create( format = "xdot" )
print "XDOT DATA:\n", xdot_data
parser = godot.dot_data_parser.GodotDataParser()
# parser.parse_dot_data(xdot_data)
flat_data = xdot_data.replace('\\\n','')
tokens = parser.dotparser.parseString(flat_data)[0]
for element in tokens[3]:
print "TOK:", element
cmd = element[0]
if cmd == 'add_node':
cmd, nodename, opts = element
assert nodename == self.ID
print "OPTIONS:", opts
self.set( **opts )
|
[
"Arrange",
"the",
"components",
"of",
"the",
"node",
"using",
"Graphviz",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L593-L622
|
[
"def",
"arrange_all",
"(",
"self",
")",
":",
"# FIXME: Circular reference avoidance.",
"import",
"godot",
".",
"dot_data_parser",
"import",
"godot",
".",
"graph",
"graph",
"=",
"godot",
".",
"graph",
".",
"Graph",
"(",
"ID",
"=",
"\"g\"",
")",
"graph",
".",
"add_node",
"(",
"self",
")",
"print",
"\"GRAPH DOT:\\n\"",
",",
"str",
"(",
"graph",
")",
"xdot_data",
"=",
"graph",
".",
"create",
"(",
"format",
"=",
"\"xdot\"",
")",
"print",
"\"XDOT DATA:\\n\"",
",",
"xdot_data",
"parser",
"=",
"godot",
".",
"dot_data_parser",
".",
"GodotDataParser",
"(",
")",
"# parser.parse_dot_data(xdot_data)",
"flat_data",
"=",
"xdot_data",
".",
"replace",
"(",
"'\\\\\\n'",
",",
"''",
")",
"tokens",
"=",
"parser",
".",
"dotparser",
".",
"parseString",
"(",
"flat_data",
")",
"[",
"0",
"]",
"for",
"element",
"in",
"tokens",
"[",
"3",
"]",
":",
"print",
"\"TOK:\"",
",",
"element",
"cmd",
"=",
"element",
"[",
"0",
"]",
"if",
"cmd",
"==",
"'add_node'",
":",
"cmd",
",",
"nodename",
",",
"opts",
"=",
"element",
"assert",
"nodename",
"==",
"self",
".",
"ID",
"print",
"\"OPTIONS:\"",
",",
"opts",
"self",
".",
"set",
"(",
"*",
"*",
"opts",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node.parse_xdot_drawing_directive
|
Parses the drawing directive, updating the node components.
|
godot/node.py
|
def parse_xdot_drawing_directive(self, new):
""" Parses the drawing directive, updating the node components.
"""
components = XdotAttrParser().parse_xdot_data(new)
max_x = max( [c.bounds[0] for c in components] + [1] )
max_y = max( [c.bounds[1] for c in components] + [1] )
pos_x = min( [c.x for c in components] )
pos_y = min( [c.y for c in components] )
move_to_origin(components)
container = Container(auto_size=True,
position=[pos_x-self.pos[0], pos_y-self.pos[1]],
bgcolor="blue")
# self.bounds = bounds=[max_x, max_y]
# container = Container(fit_window=False, auto_size=True, bgcolor="blue")
container.add( *components )
self.drawing = container
|
def parse_xdot_drawing_directive(self, new):
""" Parses the drawing directive, updating the node components.
"""
components = XdotAttrParser().parse_xdot_data(new)
max_x = max( [c.bounds[0] for c in components] + [1] )
max_y = max( [c.bounds[1] for c in components] + [1] )
pos_x = min( [c.x for c in components] )
pos_y = min( [c.y for c in components] )
move_to_origin(components)
container = Container(auto_size=True,
position=[pos_x-self.pos[0], pos_y-self.pos[1]],
bgcolor="blue")
# self.bounds = bounds=[max_x, max_y]
# container = Container(fit_window=False, auto_size=True, bgcolor="blue")
container.add( *components )
self.drawing = container
|
[
"Parses",
"the",
"drawing",
"directive",
"updating",
"the",
"node",
"components",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L633-L655
|
[
"def",
"parse_xdot_drawing_directive",
"(",
"self",
",",
"new",
")",
":",
"components",
"=",
"XdotAttrParser",
"(",
")",
".",
"parse_xdot_data",
"(",
"new",
")",
"max_x",
"=",
"max",
"(",
"[",
"c",
".",
"bounds",
"[",
"0",
"]",
"for",
"c",
"in",
"components",
"]",
"+",
"[",
"1",
"]",
")",
"max_y",
"=",
"max",
"(",
"[",
"c",
".",
"bounds",
"[",
"1",
"]",
"for",
"c",
"in",
"components",
"]",
"+",
"[",
"1",
"]",
")",
"pos_x",
"=",
"min",
"(",
"[",
"c",
".",
"x",
"for",
"c",
"in",
"components",
"]",
")",
"pos_y",
"=",
"min",
"(",
"[",
"c",
".",
"y",
"for",
"c",
"in",
"components",
"]",
")",
"move_to_origin",
"(",
"components",
")",
"container",
"=",
"Container",
"(",
"auto_size",
"=",
"True",
",",
"position",
"=",
"[",
"pos_x",
"-",
"self",
".",
"pos",
"[",
"0",
"]",
",",
"pos_y",
"-",
"self",
".",
"pos",
"[",
"1",
"]",
"]",
",",
"bgcolor",
"=",
"\"blue\"",
")",
"# self.bounds = bounds=[max_x, max_y]",
"# container = Container(fit_window=False, auto_size=True, bgcolor=\"blue\")",
"container",
".",
"add",
"(",
"*",
"components",
")",
"self",
".",
"drawing",
"=",
"container"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node.parse_xdot_label_directive
|
Parses the label drawing directive, updating the label
components.
|
godot/node.py
|
def parse_xdot_label_directive(self, new):
""" Parses the label drawing directive, updating the label
components.
"""
components = XdotAttrParser().parse_xdot_data(new)
pos_x = min( [c.x for c in components] )
pos_y = min( [c.y for c in components] )
move_to_origin(components)
container = Container(auto_size=True,
position=[pos_x-self.pos[0], pos_y-self.pos[1]],
bgcolor="red")
container.add( *components )
self.label_drawing = container
|
def parse_xdot_label_directive(self, new):
""" Parses the label drawing directive, updating the label
components.
"""
components = XdotAttrParser().parse_xdot_data(new)
pos_x = min( [c.x for c in components] )
pos_y = min( [c.y for c in components] )
move_to_origin(components)
container = Container(auto_size=True,
position=[pos_x-self.pos[0], pos_y-self.pos[1]],
bgcolor="red")
container.add( *components )
self.label_drawing = container
|
[
"Parses",
"the",
"label",
"drawing",
"directive",
"updating",
"the",
"label",
"components",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L659-L676
|
[
"def",
"parse_xdot_label_directive",
"(",
"self",
",",
"new",
")",
":",
"components",
"=",
"XdotAttrParser",
"(",
")",
".",
"parse_xdot_data",
"(",
"new",
")",
"pos_x",
"=",
"min",
"(",
"[",
"c",
".",
"x",
"for",
"c",
"in",
"components",
"]",
")",
"pos_y",
"=",
"min",
"(",
"[",
"c",
".",
"y",
"for",
"c",
"in",
"components",
"]",
")",
"move_to_origin",
"(",
"components",
")",
"container",
"=",
"Container",
"(",
"auto_size",
"=",
"True",
",",
"position",
"=",
"[",
"pos_x",
"-",
"self",
".",
"pos",
"[",
"0",
"]",
",",
"pos_y",
"-",
"self",
".",
"pos",
"[",
"1",
"]",
"]",
",",
"bgcolor",
"=",
"\"red\"",
")",
"container",
".",
"add",
"(",
"*",
"components",
")",
"self",
".",
"label_drawing",
"=",
"container"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node._drawing_changed
|
Handles the container of drawing components changing.
|
godot/node.py
|
def _drawing_changed(self, old, new):
""" Handles the container of drawing components changing.
"""
if old is not None:
self.component.remove( old )
if new is not None:
# new.bgcolor="pink"
self.component.add( new )
w, h = self.component.bounds
self.component.position = [ self.pos[0] - (w/2), self.pos[1] - (h/2) ]
# self.component.position = [ self.pos[0], self.pos[1] ]
self.component.request_redraw()
|
def _drawing_changed(self, old, new):
""" Handles the container of drawing components changing.
"""
if old is not None:
self.component.remove( old )
if new is not None:
# new.bgcolor="pink"
self.component.add( new )
w, h = self.component.bounds
self.component.position = [ self.pos[0] - (w/2), self.pos[1] - (h/2) ]
# self.component.position = [ self.pos[0], self.pos[1] ]
self.component.request_redraw()
|
[
"Handles",
"the",
"container",
"of",
"drawing",
"components",
"changing",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L679-L691
|
[
"def",
"_drawing_changed",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"if",
"old",
"is",
"not",
"None",
":",
"self",
".",
"component",
".",
"remove",
"(",
"old",
")",
"if",
"new",
"is",
"not",
"None",
":",
"# new.bgcolor=\"pink\"",
"self",
".",
"component",
".",
"add",
"(",
"new",
")",
"w",
",",
"h",
"=",
"self",
".",
"component",
".",
"bounds",
"self",
".",
"component",
".",
"position",
"=",
"[",
"self",
".",
"pos",
"[",
"0",
"]",
"-",
"(",
"w",
"/",
"2",
")",
",",
"self",
".",
"pos",
"[",
"1",
"]",
"-",
"(",
"h",
"/",
"2",
")",
"]",
"# self.component.position = [ self.pos[0], self.pos[1] ]",
"self",
".",
"component",
".",
"request_redraw",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node._on_position_change
|
Handles the poition of the component changing.
|
godot/node.py
|
def _on_position_change(self, new):
""" Handles the poition of the component changing.
"""
w, h = self.component.bounds
self.pos = tuple([ new[0] + (w/2), new[1] + (h/2) ])
|
def _on_position_change(self, new):
""" Handles the poition of the component changing.
"""
w, h = self.component.bounds
self.pos = tuple([ new[0] + (w/2), new[1] + (h/2) ])
|
[
"Handles",
"the",
"poition",
"of",
"the",
"component",
"changing",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L709-L713
|
[
"def",
"_on_position_change",
"(",
"self",
",",
"new",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"component",
".",
"bounds",
"self",
".",
"pos",
"=",
"tuple",
"(",
"[",
"new",
"[",
"0",
"]",
"+",
"(",
"w",
"/",
"2",
")",
",",
"new",
"[",
"1",
"]",
"+",
"(",
"h",
"/",
"2",
")",
"]",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Node._pos_changed
|
Handles the Graphviz position attribute changing.
|
godot/node.py
|
def _pos_changed(self, new):
""" Handles the Graphviz position attribute changing.
"""
w, h = self.component.bounds
self.component.position = [ new[0] - (w/2), new[1] - (h/2) ]
# self.component.position = list( new )
self.component.request_redraw()
|
def _pos_changed(self, new):
""" Handles the Graphviz position attribute changing.
"""
w, h = self.component.bounds
self.component.position = [ new[0] - (w/2), new[1] - (h/2) ]
# self.component.position = list( new )
self.component.request_redraw()
|
[
"Handles",
"the",
"Graphviz",
"position",
"attribute",
"changing",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/node.py#L717-L723
|
[
"def",
"_pos_changed",
"(",
"self",
",",
"new",
")",
":",
"w",
",",
"h",
"=",
"self",
".",
"component",
".",
"bounds",
"self",
".",
"component",
".",
"position",
"=",
"[",
"new",
"[",
"0",
"]",
"-",
"(",
"w",
"/",
"2",
")",
",",
"new",
"[",
"1",
"]",
"-",
"(",
"h",
"/",
"2",
")",
"]",
"# self.component.position = list( new )",
"self",
".",
"component",
".",
"request_redraw",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
ContextMenuTool.normal_right_down
|
Handles the right mouse button being clicked when the tool is in
the 'normal' state.
If the event occurred on this tool's component (or any contained
component of that component), the method opens a context menu with
menu items from any tool of the parent component that implements
MenuItemTool interface i.e. has a get_item() method.
|
godot/tool/context_menu_tool.py
|
def normal_right_down(self, event):
""" Handles the right mouse button being clicked when the tool is in
the 'normal' state.
If the event occurred on this tool's component (or any contained
component of that component), the method opens a context menu with
menu items from any tool of the parent component that implements
MenuItemTool interface i.e. has a get_item() method.
"""
x = event.x
y = event.y
# First determine what component or components we are going to hittest
# on. If our component is a container, then we add its non-container
# components to the list of candidates.
# candidates = []
component = self.component
# if isinstance(component, Container):
# candidates = get_nested_components(self.component)
# else:
# # We don't support clicking on unrecognized components
# return
#
# # Hittest against all the candidate and take the first one
# item = None
# for candidate, offset in candidates:
# if candidate.is_in(x-offset[0], y-offset[1]):
# item = candidate
# break
for tool in component.tools:
component.active_tool = self
# Do it
event.handled = True
component.active_tool = None
component.request_redraw()
return
|
def normal_right_down(self, event):
""" Handles the right mouse button being clicked when the tool is in
the 'normal' state.
If the event occurred on this tool's component (or any contained
component of that component), the method opens a context menu with
menu items from any tool of the parent component that implements
MenuItemTool interface i.e. has a get_item() method.
"""
x = event.x
y = event.y
# First determine what component or components we are going to hittest
# on. If our component is a container, then we add its non-container
# components to the list of candidates.
# candidates = []
component = self.component
# if isinstance(component, Container):
# candidates = get_nested_components(self.component)
# else:
# # We don't support clicking on unrecognized components
# return
#
# # Hittest against all the candidate and take the first one
# item = None
# for candidate, offset in candidates:
# if candidate.is_in(x-offset[0], y-offset[1]):
# item = candidate
# break
for tool in component.tools:
component.active_tool = self
# Do it
event.handled = True
component.active_tool = None
component.request_redraw()
return
|
[
"Handles",
"the",
"right",
"mouse",
"button",
"being",
"clicked",
"when",
"the",
"tool",
"is",
"in",
"the",
"normal",
"state",
"."
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/tool/context_menu_tool.py#L17-L56
|
[
"def",
"normal_right_down",
"(",
"self",
",",
"event",
")",
":",
"x",
"=",
"event",
".",
"x",
"y",
"=",
"event",
".",
"y",
"# First determine what component or components we are going to hittest",
"# on. If our component is a container, then we add its non-container",
"# components to the list of candidates.",
"# candidates = []",
"component",
"=",
"self",
".",
"component",
"# if isinstance(component, Container):",
"# candidates = get_nested_components(self.component)",
"# else:",
"# # We don't support clicking on unrecognized components",
"# return",
"#",
"# # Hittest against all the candidate and take the first one",
"# item = None",
"# for candidate, offset in candidates:",
"# if candidate.is_in(x-offset[0], y-offset[1]):",
"# item = candidate",
"# break",
"for",
"tool",
"in",
"component",
".",
"tools",
":",
"component",
".",
"active_tool",
"=",
"self",
"# Do it",
"event",
".",
"handled",
"=",
"True",
"component",
".",
"active_tool",
"=",
"None",
"component",
".",
"request_redraw",
"(",
")",
"return"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
highlight_info
|
Outputs the CSS which can be customized for highlighted code
|
combine/cli.py
|
def highlight_info(ctx, style):
"""Outputs the CSS which can be customized for highlighted code"""
click.secho("The following styles are available to choose from:", fg="green")
click.echo(list(pygments.styles.get_all_styles()))
click.echo()
click.secho(
f'The following CSS for the "{style}" style can be customized:', fg="green"
)
click.echo(pygments.formatters.HtmlFormatter(style=style).get_style_defs())
|
def highlight_info(ctx, style):
"""Outputs the CSS which can be customized for highlighted code"""
click.secho("The following styles are available to choose from:", fg="green")
click.echo(list(pygments.styles.get_all_styles()))
click.echo()
click.secho(
f'The following CSS for the "{style}" style can be customized:', fg="green"
)
click.echo(pygments.formatters.HtmlFormatter(style=style).get_style_defs())
|
[
"Outputs",
"the",
"CSS",
"which",
"can",
"be",
"customized",
"for",
"highlighted",
"code"
] |
dropseed/combine
|
python
|
https://github.com/dropseed/combine/blob/b0d622d09fcb121bc12e65f6044cb3a940b6b052/combine/cli.py#L65-L73
|
[
"def",
"highlight_info",
"(",
"ctx",
",",
"style",
")",
":",
"click",
".",
"secho",
"(",
"\"The following styles are available to choose from:\"",
",",
"fg",
"=",
"\"green\"",
")",
"click",
".",
"echo",
"(",
"list",
"(",
"pygments",
".",
"styles",
".",
"get_all_styles",
"(",
")",
")",
")",
"click",
".",
"echo",
"(",
")",
"click",
".",
"secho",
"(",
"f'The following CSS for the \"{style}\" style can be customized:'",
",",
"fg",
"=",
"\"green\"",
")",
"click",
".",
"echo",
"(",
"pygments",
".",
"formatters",
".",
"HtmlFormatter",
"(",
"style",
"=",
"style",
")",
".",
"get_style_defs",
"(",
")",
")"
] |
b0d622d09fcb121bc12e65f6044cb3a940b6b052
|
test
|
Polygon._draw_mainlayer
|
Draws a closed polygon
|
godot/component/polygon.py
|
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws a closed polygon """
gc.save_state()
try:
# self._draw_bounds(gc)
if len(self.points) >= 2:
# Set the drawing parameters.
gc.set_fill_color(self.pen.fill_color_)
gc.set_stroke_color(self.pen.color_)
gc.set_line_width(self.pen.line_width)
# Draw the path.
gc.begin_path()
# x0 = self.points[0][0] - self.x
# y0 = self.points[0][1] + self.y
# gc.move_to(x0, y0)
# offset_points = [(x-self.x, y+self.y) for x, y in self.points]
gc.lines(self.points)
gc.close_path()
if self.filled:
gc.draw_path(self.inside_rule_)
else:
gc.stroke_path()
finally:
gc.restore_state()
|
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws a closed polygon """
gc.save_state()
try:
# self._draw_bounds(gc)
if len(self.points) >= 2:
# Set the drawing parameters.
gc.set_fill_color(self.pen.fill_color_)
gc.set_stroke_color(self.pen.color_)
gc.set_line_width(self.pen.line_width)
# Draw the path.
gc.begin_path()
# x0 = self.points[0][0] - self.x
# y0 = self.points[0][1] + self.y
# gc.move_to(x0, y0)
# offset_points = [(x-self.x, y+self.y) for x, y in self.points]
gc.lines(self.points)
gc.close_path()
if self.filled:
gc.draw_path(self.inside_rule_)
else:
gc.stroke_path()
finally:
gc.restore_state()
|
[
"Draws",
"a",
"closed",
"polygon"
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/polygon.py#L93-L119
|
[
"def",
"_draw_mainlayer",
"(",
"self",
",",
"gc",
",",
"view_bounds",
"=",
"None",
",",
"mode",
"=",
"\"default\"",
")",
":",
"gc",
".",
"save_state",
"(",
")",
"try",
":",
"# self._draw_bounds(gc)",
"if",
"len",
"(",
"self",
".",
"points",
")",
">=",
"2",
":",
"# Set the drawing parameters.",
"gc",
".",
"set_fill_color",
"(",
"self",
".",
"pen",
".",
"fill_color_",
")",
"gc",
".",
"set_stroke_color",
"(",
"self",
".",
"pen",
".",
"color_",
")",
"gc",
".",
"set_line_width",
"(",
"self",
".",
"pen",
".",
"line_width",
")",
"# Draw the path.",
"gc",
".",
"begin_path",
"(",
")",
"# x0 = self.points[0][0] - self.x",
"# y0 = self.points[0][1] + self.y",
"# gc.move_to(x0, y0)",
"# offset_points = [(x-self.x, y+self.y) for x, y in self.points]",
"gc",
".",
"lines",
"(",
"self",
".",
"points",
")",
"gc",
".",
"close_path",
"(",
")",
"if",
"self",
".",
"filled",
":",
"gc",
".",
"draw_path",
"(",
"self",
".",
"inside_rule_",
")",
"else",
":",
"gc",
".",
"stroke_path",
"(",
")",
"finally",
":",
"gc",
".",
"restore_state",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
Polygon.is_in
|
Test if a point is within this polygonal region
|
godot/component/polygon.py
|
def is_in(self, point_x, point_y):
""" Test if a point is within this polygonal region """
point_array = array(((point_x, point_y),))
vertices = array(self.points)
winding = self.inside_rule == "winding"
result = points_in_polygon(point_array, vertices, winding)
return result[0]
|
def is_in(self, point_x, point_y):
""" Test if a point is within this polygonal region """
point_array = array(((point_x, point_y),))
vertices = array(self.points)
winding = self.inside_rule == "winding"
result = points_in_polygon(point_array, vertices, winding)
return result[0]
|
[
"Test",
"if",
"a",
"point",
"is",
"within",
"this",
"polygonal",
"region"
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/polygon.py#L122-L129
|
[
"def",
"is_in",
"(",
"self",
",",
"point_x",
",",
"point_y",
")",
":",
"point_array",
"=",
"array",
"(",
"(",
"(",
"point_x",
",",
"point_y",
")",
",",
")",
")",
"vertices",
"=",
"array",
"(",
"self",
".",
"points",
")",
"winding",
"=",
"self",
".",
"inside_rule",
"==",
"\"winding\"",
"result",
"=",
"points_in_polygon",
"(",
"point_array",
",",
"vertices",
",",
"winding",
")",
"return",
"result",
"[",
"0",
"]"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
BSpline._draw_mainlayer
|
Draws the Bezier component
|
godot/component/bspline.py
|
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws the Bezier component """
if not self.points: return
gc.save_state()
try:
gc.set_fill_color(self.pen.fill_color_)
gc.set_line_width(self.pen.line_width)
gc.set_stroke_color(self.pen.color_)
gc.begin_path()
start_x, start_y = self.points[0]
gc.move_to(start_x, start_y)
for triple in nsplit(self.points[1:], 3):
x1, y1 = triple[0]
x2, y2 = triple[1]
end_x, end_y = triple[2]
gc.curve_to(x1, y1, x2, y2, end_x, end_y)
# One point overlap
gc.move_to(end_x, end_y)
gc.stroke_path()
finally:
gc.restore_state()
|
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):
""" Draws the Bezier component """
if not self.points: return
gc.save_state()
try:
gc.set_fill_color(self.pen.fill_color_)
gc.set_line_width(self.pen.line_width)
gc.set_stroke_color(self.pen.color_)
gc.begin_path()
start_x, start_y = self.points[0]
gc.move_to(start_x, start_y)
for triple in nsplit(self.points[1:], 3):
x1, y1 = triple[0]
x2, y2 = triple[1]
end_x, end_y = triple[2]
gc.curve_to(x1, y1, x2, y2, end_x, end_y)
# One point overlap
gc.move_to(end_x, end_y)
gc.stroke_path()
finally:
gc.restore_state()
|
[
"Draws",
"the",
"Bezier",
"component"
] |
rwl/godot
|
python
|
https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/component/bspline.py#L124-L147
|
[
"def",
"_draw_mainlayer",
"(",
"self",
",",
"gc",
",",
"view_bounds",
"=",
"None",
",",
"mode",
"=",
"\"default\"",
")",
":",
"if",
"not",
"self",
".",
"points",
":",
"return",
"gc",
".",
"save_state",
"(",
")",
"try",
":",
"gc",
".",
"set_fill_color",
"(",
"self",
".",
"pen",
".",
"fill_color_",
")",
"gc",
".",
"set_line_width",
"(",
"self",
".",
"pen",
".",
"line_width",
")",
"gc",
".",
"set_stroke_color",
"(",
"self",
".",
"pen",
".",
"color_",
")",
"gc",
".",
"begin_path",
"(",
")",
"start_x",
",",
"start_y",
"=",
"self",
".",
"points",
"[",
"0",
"]",
"gc",
".",
"move_to",
"(",
"start_x",
",",
"start_y",
")",
"for",
"triple",
"in",
"nsplit",
"(",
"self",
".",
"points",
"[",
"1",
":",
"]",
",",
"3",
")",
":",
"x1",
",",
"y1",
"=",
"triple",
"[",
"0",
"]",
"x2",
",",
"y2",
"=",
"triple",
"[",
"1",
"]",
"end_x",
",",
"end_y",
"=",
"triple",
"[",
"2",
"]",
"gc",
".",
"curve_to",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"end_x",
",",
"end_y",
")",
"# One point overlap",
"gc",
".",
"move_to",
"(",
"end_x",
",",
"end_y",
")",
"gc",
".",
"stroke_path",
"(",
")",
"finally",
":",
"gc",
".",
"restore_state",
"(",
")"
] |
013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f
|
test
|
DBAPIConnection._connect
|
Initialize the database connection.
|
web/db/dbapi.py
|
def _connect(self, context):
"""Initialize the database connection."""
if __debug__:
log.info("Connecting " + self.engine.partition(':')[0] + " database layer.", extra=dict(
uri = redact_uri(self.uri, self.protect),
config = self.config,
alias = self.alias,
))
self.connection = context.db[self.alias] = self._connector(self.uri, **self.config)
|
def _connect(self, context):
"""Initialize the database connection."""
if __debug__:
log.info("Connecting " + self.engine.partition(':')[0] + " database layer.", extra=dict(
uri = redact_uri(self.uri, self.protect),
config = self.config,
alias = self.alias,
))
self.connection = context.db[self.alias] = self._connector(self.uri, **self.config)
|
[
"Initialize",
"the",
"database",
"connection",
"."
] |
marrow/web.db
|
python
|
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/db/dbapi.py#L42-L52
|
[
"def",
"_connect",
"(",
"self",
",",
"context",
")",
":",
"if",
"__debug__",
":",
"log",
".",
"info",
"(",
"\"Connecting \"",
"+",
"self",
".",
"engine",
".",
"partition",
"(",
"':'",
")",
"[",
"0",
"]",
"+",
"\" database layer.\"",
",",
"extra",
"=",
"dict",
"(",
"uri",
"=",
"redact_uri",
"(",
"self",
".",
"uri",
",",
"self",
".",
"protect",
")",
",",
"config",
"=",
"self",
".",
"config",
",",
"alias",
"=",
"self",
".",
"alias",
",",
")",
")",
"self",
".",
"connection",
"=",
"context",
".",
"db",
"[",
"self",
".",
"alias",
"]",
"=",
"self",
".",
"_connector",
"(",
"self",
".",
"uri",
",",
"*",
"*",
"self",
".",
"config",
")"
] |
c755fbff7028a5edc223d6a631b8421858274fc4
|
test
|
DatabaseExtension._handle_event
|
Broadcast an event to the database connections registered.
|
web/ext/db.py
|
def _handle_event(self, event, *args, **kw):
"""Broadcast an event to the database connections registered."""
for engine in self.engines.values():
if hasattr(engine, event):
getattr(engine, event)(*args, **kw)
|
def _handle_event(self, event, *args, **kw):
"""Broadcast an event to the database connections registered."""
for engine in self.engines.values():
if hasattr(engine, event):
getattr(engine, event)(*args, **kw)
|
[
"Broadcast",
"an",
"event",
"to",
"the",
"database",
"connections",
"registered",
"."
] |
marrow/web.db
|
python
|
https://github.com/marrow/web.db/blob/c755fbff7028a5edc223d6a631b8421858274fc4/web/ext/db.py#L52-L57
|
[
"def",
"_handle_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"for",
"engine",
"in",
"self",
".",
"engines",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"engine",
",",
"event",
")",
":",
"getattr",
"(",
"engine",
",",
"event",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")"
] |
c755fbff7028a5edc223d6a631b8421858274fc4
|
test
|
Worker.run
|
Method that gets run when the Worker thread is started.
When there's an item in in_queue, it takes it out, passes it to func as an argument, and puts the result in out_queue.
|
music2storage/worker.py
|
def run(self):
"""
Method that gets run when the Worker thread is started.
When there's an item in in_queue, it takes it out, passes it to func as an argument, and puts the result in out_queue.
"""
while not self.stopper.is_set():
try:
item = self.in_queue.get(timeout=5)
except queue.Empty:
continue
try:
result = self.func(item)
except TypeError:
continue
else:
self.out_queue.put(result)
|
def run(self):
"""
Method that gets run when the Worker thread is started.
When there's an item in in_queue, it takes it out, passes it to func as an argument, and puts the result in out_queue.
"""
while not self.stopper.is_set():
try:
item = self.in_queue.get(timeout=5)
except queue.Empty:
continue
try:
result = self.func(item)
except TypeError:
continue
else:
self.out_queue.put(result)
|
[
"Method",
"that",
"gets",
"run",
"when",
"the",
"Worker",
"thread",
"is",
"started",
"."
] |
Music-Moo/music2storage
|
python
|
https://github.com/Music-Moo/music2storage/blob/de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2/music2storage/worker.py#L26-L44
|
[
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"stopper",
".",
"is_set",
"(",
")",
":",
"try",
":",
"item",
"=",
"self",
".",
"in_queue",
".",
"get",
"(",
"timeout",
"=",
"5",
")",
"except",
"queue",
".",
"Empty",
":",
"continue",
"try",
":",
"result",
"=",
"self",
".",
"func",
"(",
"item",
")",
"except",
"TypeError",
":",
"continue",
"else",
":",
"self",
".",
"out_queue",
".",
"put",
"(",
"result",
")"
] |
de12b9046dd227fc8c1512b5060e7f5fcd8b0ee2
|
test
|
Pager.get_full_page_url
|
Get the full, external URL for this page, optinally with the passed in URL scheme
|
littlefish/pager.py
|
def get_full_page_url(self, page_number, scheme=None):
"""Get the full, external URL for this page, optinally with the passed in URL scheme"""
args = dict(
request.view_args,
_external=True,
)
if scheme is not None:
args['_scheme'] = scheme
if page_number != 1:
args['page'] = page_number
return url_for(request.endpoint, **args)
|
def get_full_page_url(self, page_number, scheme=None):
"""Get the full, external URL for this page, optinally with the passed in URL scheme"""
args = dict(
request.view_args,
_external=True,
)
if scheme is not None:
args['_scheme'] = scheme
if page_number != 1:
args['page'] = page_number
return url_for(request.endpoint, **args)
|
[
"Get",
"the",
"full",
"external",
"URL",
"for",
"this",
"page",
"optinally",
"with",
"the",
"passed",
"in",
"URL",
"scheme"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/pager.py#L118-L131
|
[
"def",
"get_full_page_url",
"(",
"self",
",",
"page_number",
",",
"scheme",
"=",
"None",
")",
":",
"args",
"=",
"dict",
"(",
"request",
".",
"view_args",
",",
"_external",
"=",
"True",
",",
")",
"if",
"scheme",
"is",
"not",
"None",
":",
"args",
"[",
"'_scheme'",
"]",
"=",
"scheme",
"if",
"page_number",
"!=",
"1",
":",
"args",
"[",
"'page'",
"]",
"=",
"page_number",
"return",
"url_for",
"(",
"request",
".",
"endpoint",
",",
"*",
"*",
"args",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
Pager.render_prev_next_links
|
Render the rel=prev and rel=next links to a Markup object for injection into a template
|
littlefish/pager.py
|
def render_prev_next_links(self, scheme=None):
"""Render the rel=prev and rel=next links to a Markup object for injection into a template"""
output = ''
if self.has_prev:
output += '<link rel="prev" href="{}" />\n'.format(self.get_full_page_url(self.prev, scheme=scheme))
if self.has_next:
output += '<link rel="next" href="{}" />\n'.format(self.get_full_page_url(self.next, scheme=scheme))
return Markup(output)
|
def render_prev_next_links(self, scheme=None):
"""Render the rel=prev and rel=next links to a Markup object for injection into a template"""
output = ''
if self.has_prev:
output += '<link rel="prev" href="{}" />\n'.format(self.get_full_page_url(self.prev, scheme=scheme))
if self.has_next:
output += '<link rel="next" href="{}" />\n'.format(self.get_full_page_url(self.next, scheme=scheme))
return Markup(output)
|
[
"Render",
"the",
"rel",
"=",
"prev",
"and",
"rel",
"=",
"next",
"links",
"to",
"a",
"Markup",
"object",
"for",
"injection",
"into",
"a",
"template"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/pager.py#L137-L147
|
[
"def",
"render_prev_next_links",
"(",
"self",
",",
"scheme",
"=",
"None",
")",
":",
"output",
"=",
"''",
"if",
"self",
".",
"has_prev",
":",
"output",
"+=",
"'<link rel=\"prev\" href=\"{}\" />\\n'",
".",
"format",
"(",
"self",
".",
"get_full_page_url",
"(",
"self",
".",
"prev",
",",
"scheme",
"=",
"scheme",
")",
")",
"if",
"self",
".",
"has_next",
":",
"output",
"+=",
"'<link rel=\"next\" href=\"{}\" />\\n'",
".",
"format",
"(",
"self",
".",
"get_full_page_url",
"(",
"self",
".",
"next",
",",
"scheme",
"=",
"scheme",
")",
")",
"return",
"Markup",
"(",
"output",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
Pager.render_seo_links
|
Render the rel=canonical, rel=prev and rel=next links to a Markup object for injection into a template
|
littlefish/pager.py
|
def render_seo_links(self, scheme=None):
"""Render the rel=canonical, rel=prev and rel=next links to a Markup object for injection into a template"""
out = self.render_prev_next_links(scheme=scheme)
if self.total_pages == 1:
out += self.render_canonical_link(scheme=scheme)
return out
|
def render_seo_links(self, scheme=None):
"""Render the rel=canonical, rel=prev and rel=next links to a Markup object for injection into a template"""
out = self.render_prev_next_links(scheme=scheme)
if self.total_pages == 1:
out += self.render_canonical_link(scheme=scheme)
return out
|
[
"Render",
"the",
"rel",
"=",
"canonical",
"rel",
"=",
"prev",
"and",
"rel",
"=",
"next",
"links",
"to",
"a",
"Markup",
"object",
"for",
"injection",
"into",
"a",
"template"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/pager.py#L153-L160
|
[
"def",
"render_seo_links",
"(",
"self",
",",
"scheme",
"=",
"None",
")",
":",
"out",
"=",
"self",
".",
"render_prev_next_links",
"(",
"scheme",
"=",
"scheme",
")",
"if",
"self",
".",
"total_pages",
"==",
"1",
":",
"out",
"+=",
"self",
".",
"render_canonical_link",
"(",
"scheme",
"=",
"scheme",
")",
"return",
"out"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
Pager.last_item_number
|
:return: The last "item number", used when displaying messages to the user
like "Displaying items 1 to 10 of 123" - in this example 10 would be returned
|
littlefish/pager.py
|
def last_item_number(self):
"""
:return: The last "item number", used when displaying messages to the user
like "Displaying items 1 to 10 of 123" - in this example 10 would be returned
"""
n = self.first_item_number + self.page_size - 1
if n > self.total_items:
return self.total_items
return n
|
def last_item_number(self):
"""
:return: The last "item number", used when displaying messages to the user
like "Displaying items 1 to 10 of 123" - in this example 10 would be returned
"""
n = self.first_item_number + self.page_size - 1
if n > self.total_items:
return self.total_items
return n
|
[
":",
"return",
":",
"The",
"last",
"item",
"number",
"used",
"when",
"displaying",
"messages",
"to",
"the",
"user",
"like",
"Displaying",
"items",
"1",
"to",
"10",
"of",
"123",
"-",
"in",
"this",
"example",
"10",
"would",
"be",
"returned"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/pager.py#L171-L179
|
[
"def",
"last_item_number",
"(",
"self",
")",
":",
"n",
"=",
"self",
".",
"first_item_number",
"+",
"self",
".",
"page_size",
"-",
"1",
"if",
"n",
">",
"self",
".",
"total_items",
":",
"return",
"self",
".",
"total_items",
"return",
"n"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
_content_type_matches
|
Is ``candidate`` an exact match or sub-type of ``pattern``?
|
ietfparse/algorithms.py
|
def _content_type_matches(candidate, pattern):
"""Is ``candidate`` an exact match or sub-type of ``pattern``?"""
def _wildcard_compare(type_spec, type_pattern):
return type_pattern == '*' or type_spec == type_pattern
return (
_wildcard_compare(candidate.content_type, pattern.content_type) and
_wildcard_compare(candidate.content_subtype, pattern.content_subtype)
)
|
def _content_type_matches(candidate, pattern):
"""Is ``candidate`` an exact match or sub-type of ``pattern``?"""
def _wildcard_compare(type_spec, type_pattern):
return type_pattern == '*' or type_spec == type_pattern
return (
_wildcard_compare(candidate.content_type, pattern.content_type) and
_wildcard_compare(candidate.content_subtype, pattern.content_subtype)
)
|
[
"Is",
"candidate",
"an",
"exact",
"match",
"or",
"sub",
"-",
"type",
"of",
"pattern",
"?"
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/algorithms.py#L60-L68
|
[
"def",
"_content_type_matches",
"(",
"candidate",
",",
"pattern",
")",
":",
"def",
"_wildcard_compare",
"(",
"type_spec",
",",
"type_pattern",
")",
":",
"return",
"type_pattern",
"==",
"'*'",
"or",
"type_spec",
"==",
"type_pattern",
"return",
"(",
"_wildcard_compare",
"(",
"candidate",
".",
"content_type",
",",
"pattern",
".",
"content_type",
")",
"and",
"_wildcard_compare",
"(",
"candidate",
".",
"content_subtype",
",",
"pattern",
".",
"content_subtype",
")",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
select_content_type
|
Selects the best content type.
:param requested: a sequence of :class:`.ContentType` instances
:param available: a sequence of :class:`.ContentType` instances
that the server is capable of producing
:returns: the selected content type (from ``available``) and the
pattern that it matched (from ``requested``)
:rtype: :class:`tuple` of :class:`.ContentType` instances
:raises: :class:`.NoMatch` when a suitable match was not found
This function implements the *Proactive Content Negotiation*
algorithm as described in sections 3.4.1 and 5.3 of :rfc:`7231`.
The input is the `Accept`_ header as parsed by
:func:`.parse_http_accept_header` and a list of
parsed :class:`.ContentType` instances. The ``available`` sequence
should be a sequence of content types that the server is capable of
producing. The selected value should ultimately be used as the
`Content-Type`_ header in the generated response.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
.. _Content-Type: http://tools.ietf.org/html/rfc7231#section-3.1.1.5
|
ietfparse/algorithms.py
|
def select_content_type(requested, available):
"""Selects the best content type.
:param requested: a sequence of :class:`.ContentType` instances
:param available: a sequence of :class:`.ContentType` instances
that the server is capable of producing
:returns: the selected content type (from ``available``) and the
pattern that it matched (from ``requested``)
:rtype: :class:`tuple` of :class:`.ContentType` instances
:raises: :class:`.NoMatch` when a suitable match was not found
This function implements the *Proactive Content Negotiation*
algorithm as described in sections 3.4.1 and 5.3 of :rfc:`7231`.
The input is the `Accept`_ header as parsed by
:func:`.parse_http_accept_header` and a list of
parsed :class:`.ContentType` instances. The ``available`` sequence
should be a sequence of content types that the server is capable of
producing. The selected value should ultimately be used as the
`Content-Type`_ header in the generated response.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
.. _Content-Type: http://tools.ietf.org/html/rfc7231#section-3.1.1.5
"""
class Match(object):
"""Sorting assistant.
Sorting matches is a tricky business. We need a way to
prefer content types by *specificity*. The definition of
*more specific* is a little less than clear. This class
treats the strength of a match as the most important thing.
Wild cards are less specific in all cases. This is tracked
by the ``match_type`` attribute.
If we the candidate and pattern differ only by parameters,
then the strength is based on the number of pattern parameters
that match parameters from the candidate. The easiest way to
track this is to count the number of candidate parameters that
are matched by the pattern. This is what ``parameter_distance``
tracks.
The final key to the solution is to order the result set such
that the most specific matches are first in the list. This
is done by carefully choosing values for ``match_type`` such
that full matches bubble up to the front. We also need a
scheme of counting matching parameters that pushes stronger
matches to the front of the list. The ``parameter_distance``
attribute starts at the number of candidate parameters and
decreases for each matching parameter - the lesser the value,
the stronger the match.
"""
WILDCARD, PARTIAL, FULL_TYPE, = 2, 1, 0
def __init__(self, candidate, pattern):
self.candidate = candidate
self.pattern = pattern
if pattern.content_type == pattern.content_subtype == '*':
self.match_type = self.WILDCARD
elif pattern.content_subtype == '*':
self.match_type = self.PARTIAL
else:
self.match_type = self.FULL_TYPE
self.parameter_distance = len(self.candidate.parameters)
for key, value in candidate.parameters.items():
if key in pattern.parameters:
if pattern.parameters[key] == value:
self.parameter_distance -= 1
else:
self.parameter_distance += 1
def extract_quality(obj):
return getattr(obj, 'quality', 1.0)
matches = []
for pattern in sorted(requested, key=extract_quality, reverse=True):
for candidate in sorted(available):
if _content_type_matches(candidate, pattern):
if candidate == pattern: # exact match!!!
if extract_quality(pattern) == 0.0:
raise errors.NoMatch # quality of 0 means NO
return candidate, pattern
matches.append(Match(candidate, pattern))
if not matches:
raise errors.NoMatch
matches = sorted(matches,
key=attrgetter('match_type', 'parameter_distance'))
return matches[0].candidate, matches[0].pattern
|
def select_content_type(requested, available):
"""Selects the best content type.
:param requested: a sequence of :class:`.ContentType` instances
:param available: a sequence of :class:`.ContentType` instances
that the server is capable of producing
:returns: the selected content type (from ``available``) and the
pattern that it matched (from ``requested``)
:rtype: :class:`tuple` of :class:`.ContentType` instances
:raises: :class:`.NoMatch` when a suitable match was not found
This function implements the *Proactive Content Negotiation*
algorithm as described in sections 3.4.1 and 5.3 of :rfc:`7231`.
The input is the `Accept`_ header as parsed by
:func:`.parse_http_accept_header` and a list of
parsed :class:`.ContentType` instances. The ``available`` sequence
should be a sequence of content types that the server is capable of
producing. The selected value should ultimately be used as the
`Content-Type`_ header in the generated response.
.. _Accept: http://tools.ietf.org/html/rfc7231#section-5.3.2
.. _Content-Type: http://tools.ietf.org/html/rfc7231#section-3.1.1.5
"""
class Match(object):
"""Sorting assistant.
Sorting matches is a tricky business. We need a way to
prefer content types by *specificity*. The definition of
*more specific* is a little less than clear. This class
treats the strength of a match as the most important thing.
Wild cards are less specific in all cases. This is tracked
by the ``match_type`` attribute.
If we the candidate and pattern differ only by parameters,
then the strength is based on the number of pattern parameters
that match parameters from the candidate. The easiest way to
track this is to count the number of candidate parameters that
are matched by the pattern. This is what ``parameter_distance``
tracks.
The final key to the solution is to order the result set such
that the most specific matches are first in the list. This
is done by carefully choosing values for ``match_type`` such
that full matches bubble up to the front. We also need a
scheme of counting matching parameters that pushes stronger
matches to the front of the list. The ``parameter_distance``
attribute starts at the number of candidate parameters and
decreases for each matching parameter - the lesser the value,
the stronger the match.
"""
WILDCARD, PARTIAL, FULL_TYPE, = 2, 1, 0
def __init__(self, candidate, pattern):
self.candidate = candidate
self.pattern = pattern
if pattern.content_type == pattern.content_subtype == '*':
self.match_type = self.WILDCARD
elif pattern.content_subtype == '*':
self.match_type = self.PARTIAL
else:
self.match_type = self.FULL_TYPE
self.parameter_distance = len(self.candidate.parameters)
for key, value in candidate.parameters.items():
if key in pattern.parameters:
if pattern.parameters[key] == value:
self.parameter_distance -= 1
else:
self.parameter_distance += 1
def extract_quality(obj):
return getattr(obj, 'quality', 1.0)
matches = []
for pattern in sorted(requested, key=extract_quality, reverse=True):
for candidate in sorted(available):
if _content_type_matches(candidate, pattern):
if candidate == pattern: # exact match!!!
if extract_quality(pattern) == 0.0:
raise errors.NoMatch # quality of 0 means NO
return candidate, pattern
matches.append(Match(candidate, pattern))
if not matches:
raise errors.NoMatch
matches = sorted(matches,
key=attrgetter('match_type', 'parameter_distance'))
return matches[0].candidate, matches[0].pattern
|
[
"Selects",
"the",
"best",
"content",
"type",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/algorithms.py#L71-L164
|
[
"def",
"select_content_type",
"(",
"requested",
",",
"available",
")",
":",
"class",
"Match",
"(",
"object",
")",
":",
"\"\"\"Sorting assistant.\n\n Sorting matches is a tricky business. We need a way to\n prefer content types by *specificity*. The definition of\n *more specific* is a little less than clear. This class\n treats the strength of a match as the most important thing.\n Wild cards are less specific in all cases. This is tracked\n by the ``match_type`` attribute.\n\n If we the candidate and pattern differ only by parameters,\n then the strength is based on the number of pattern parameters\n that match parameters from the candidate. The easiest way to\n track this is to count the number of candidate parameters that\n are matched by the pattern. This is what ``parameter_distance``\n tracks.\n\n The final key to the solution is to order the result set such\n that the most specific matches are first in the list. This\n is done by carefully choosing values for ``match_type`` such\n that full matches bubble up to the front. We also need a\n scheme of counting matching parameters that pushes stronger\n matches to the front of the list. The ``parameter_distance``\n attribute starts at the number of candidate parameters and\n decreases for each matching parameter - the lesser the value,\n the stronger the match.\n\n \"\"\"",
"WILDCARD",
",",
"PARTIAL",
",",
"FULL_TYPE",
",",
"=",
"2",
",",
"1",
",",
"0",
"def",
"__init__",
"(",
"self",
",",
"candidate",
",",
"pattern",
")",
":",
"self",
".",
"candidate",
"=",
"candidate",
"self",
".",
"pattern",
"=",
"pattern",
"if",
"pattern",
".",
"content_type",
"==",
"pattern",
".",
"content_subtype",
"==",
"'*'",
":",
"self",
".",
"match_type",
"=",
"self",
".",
"WILDCARD",
"elif",
"pattern",
".",
"content_subtype",
"==",
"'*'",
":",
"self",
".",
"match_type",
"=",
"self",
".",
"PARTIAL",
"else",
":",
"self",
".",
"match_type",
"=",
"self",
".",
"FULL_TYPE",
"self",
".",
"parameter_distance",
"=",
"len",
"(",
"self",
".",
"candidate",
".",
"parameters",
")",
"for",
"key",
",",
"value",
"in",
"candidate",
".",
"parameters",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"pattern",
".",
"parameters",
":",
"if",
"pattern",
".",
"parameters",
"[",
"key",
"]",
"==",
"value",
":",
"self",
".",
"parameter_distance",
"-=",
"1",
"else",
":",
"self",
".",
"parameter_distance",
"+=",
"1",
"def",
"extract_quality",
"(",
"obj",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"'quality'",
",",
"1.0",
")",
"matches",
"=",
"[",
"]",
"for",
"pattern",
"in",
"sorted",
"(",
"requested",
",",
"key",
"=",
"extract_quality",
",",
"reverse",
"=",
"True",
")",
":",
"for",
"candidate",
"in",
"sorted",
"(",
"available",
")",
":",
"if",
"_content_type_matches",
"(",
"candidate",
",",
"pattern",
")",
":",
"if",
"candidate",
"==",
"pattern",
":",
"# exact match!!!",
"if",
"extract_quality",
"(",
"pattern",
")",
"==",
"0.0",
":",
"raise",
"errors",
".",
"NoMatch",
"# quality of 0 means NO",
"return",
"candidate",
",",
"pattern",
"matches",
".",
"append",
"(",
"Match",
"(",
"candidate",
",",
"pattern",
")",
")",
"if",
"not",
"matches",
":",
"raise",
"errors",
".",
"NoMatch",
"matches",
"=",
"sorted",
"(",
"matches",
",",
"key",
"=",
"attrgetter",
"(",
"'match_type'",
",",
"'parameter_distance'",
")",
")",
"return",
"matches",
"[",
"0",
"]",
".",
"candidate",
",",
"matches",
"[",
"0",
"]",
".",
"pattern"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
rewrite_url
|
Create a new URL from `input_url` with modifications applied.
:param str input_url: the URL to modify
:keyword str fragment: if specified, this keyword sets the
fragment portion of the URL. A value of :data:`None`
will remove the fragment portion of the URL.
:keyword str host: if specified, this keyword sets the host
portion of the network location. A value of :data:`None`
will remove the network location portion of the URL.
:keyword str password: if specified, this keyword sets the
password portion of the URL. A value of :data:`None` will
remove the password from the URL.
:keyword str path: if specified, this keyword sets the path
portion of the URL. A value of :data:`None` will remove
the path from the URL.
:keyword int port: if specified, this keyword sets the port
portion of the network location. A value of :data:`None`
will remove the port from the URL.
:keyword query: if specified, this keyword sets the query portion
of the URL. See the comments for a description of this
parameter.
:keyword str scheme: if specified, this keyword sets the scheme
portion of the URL. A value of :data:`None` will remove
the scheme. Note that this will make the URL relative and
may have unintended consequences.
:keyword str user: if specified, this keyword sets the user
portion of the URL. A value of :data:`None` will remove
the user and password portions.
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:return: the modified URL
:raises ValueError: when a keyword parameter is given an invalid
value
If the `host` parameter is specified and not :data:`None`, then
it will be processed as an Internationalized Domain Name (IDN)
if the scheme appears in :data:`IDNA_SCHEMES`. Otherwise, it
will be encoded as UTF-8 and percent encoded.
The handling of the `query` parameter requires some additional
explanation. You can specify a query value in three different
ways - as a *mapping*, as a *sequence* of pairs, or as a *string*.
This flexibility makes it possible to meet the wide range of
finicky use cases.
*If the query parameter is a mapping*, then the key + value pairs
are *sorted by the key* before they are encoded. Use this method
whenever possible.
*If the query parameter is a sequence of pairs*, then each pair
is encoded *in the given order*. Use this method if you require
that parameter order is controlled.
*If the query parameter is a string*, then it is *used as-is*.
This form SHOULD BE AVOIDED since it can easily result in broken
URLs since *no URL escaping is performed*. This is the obvious
pass through case that is almost always present.
|
ietfparse/algorithms.py
|
def rewrite_url(input_url, **kwargs):
"""
Create a new URL from `input_url` with modifications applied.
:param str input_url: the URL to modify
:keyword str fragment: if specified, this keyword sets the
fragment portion of the URL. A value of :data:`None`
will remove the fragment portion of the URL.
:keyword str host: if specified, this keyword sets the host
portion of the network location. A value of :data:`None`
will remove the network location portion of the URL.
:keyword str password: if specified, this keyword sets the
password portion of the URL. A value of :data:`None` will
remove the password from the URL.
:keyword str path: if specified, this keyword sets the path
portion of the URL. A value of :data:`None` will remove
the path from the URL.
:keyword int port: if specified, this keyword sets the port
portion of the network location. A value of :data:`None`
will remove the port from the URL.
:keyword query: if specified, this keyword sets the query portion
of the URL. See the comments for a description of this
parameter.
:keyword str scheme: if specified, this keyword sets the scheme
portion of the URL. A value of :data:`None` will remove
the scheme. Note that this will make the URL relative and
may have unintended consequences.
:keyword str user: if specified, this keyword sets the user
portion of the URL. A value of :data:`None` will remove
the user and password portions.
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:return: the modified URL
:raises ValueError: when a keyword parameter is given an invalid
value
If the `host` parameter is specified and not :data:`None`, then
it will be processed as an Internationalized Domain Name (IDN)
if the scheme appears in :data:`IDNA_SCHEMES`. Otherwise, it
will be encoded as UTF-8 and percent encoded.
The handling of the `query` parameter requires some additional
explanation. You can specify a query value in three different
ways - as a *mapping*, as a *sequence* of pairs, or as a *string*.
This flexibility makes it possible to meet the wide range of
finicky use cases.
*If the query parameter is a mapping*, then the key + value pairs
are *sorted by the key* before they are encoded. Use this method
whenever possible.
*If the query parameter is a sequence of pairs*, then each pair
is encoded *in the given order*. Use this method if you require
that parameter order is controlled.
*If the query parameter is a string*, then it is *used as-is*.
This form SHOULD BE AVOIDED since it can easily result in broken
URLs since *no URL escaping is performed*. This is the obvious
pass through case that is almost always present.
"""
scheme, netloc, path, query, fragment = parse.urlsplit(input_url)
if 'scheme' in kwargs:
scheme = kwargs['scheme']
ident, host_n_port = parse.splituser(netloc)
user, password = parse.splitpasswd(ident) if ident else (None, None)
if 'user' in kwargs:
user = kwargs['user']
elif user is not None:
user = parse.unquote_to_bytes(user).decode('utf-8')
if 'password' in kwargs:
password = kwargs['password']
elif password is not None:
password = parse.unquote_to_bytes(password).decode('utf-8')
ident = _create_url_identifier(user, password)
host, port = parse.splitnport(host_n_port, defport=None)
if 'host' in kwargs:
host = kwargs['host']
if host is not None:
host = _normalize_host(
host,
enable_long_host=kwargs.get('enable_long_host', False),
encode_with_idna=kwargs.get('encode_with_idna', None),
scheme=scheme,
)
if 'port' in kwargs:
port = kwargs['port']
if port is not None:
port = int(kwargs['port'])
if port < 0:
raise ValueError('port is required to be non-negative')
if host is None or host == '':
host_n_port = None
elif port is None:
host_n_port = host
else:
host_n_port = '{0}:{1}'.format(host, port)
if 'path' in kwargs:
path = kwargs['path']
if path is None:
path = '/'
else:
path = parse.quote(path.encode('utf-8'), safe=PATH_SAFE_CHARS)
netloc = '{0}@{1}'.format(ident, host_n_port) if ident else host_n_port
if 'query' in kwargs:
new_query = kwargs['query']
if new_query is None:
query = None
else:
params = []
try:
for param in sorted(new_query.keys()):
params.append((param, new_query[param]))
except AttributeError: # arg is None or not a dict
pass
if not params: # maybe a sequence of tuples?
try:
params = [(param, value) for param, value in new_query]
except ValueError: # guess not...
pass
if params:
query = parse.urlencode(params)
else:
query = new_query
if 'fragment' in kwargs:
fragment = kwargs['fragment']
if fragment is not None:
fragment = parse.quote(fragment.encode('utf-8'),
safe=FRAGMENT_SAFE_CHARS)
# The following is necessary to get around some interesting special
# case code in urllib.parse._coerce_args in Python 3.4. Setting
# scheme to None causes urlunsplit to assume that all non-``None``
# parameters with be byte strings....
if scheme is None:
scheme = ''
return parse.urlunsplit((scheme, netloc, path, query, fragment))
|
def rewrite_url(input_url, **kwargs):
"""
Create a new URL from `input_url` with modifications applied.
:param str input_url: the URL to modify
:keyword str fragment: if specified, this keyword sets the
fragment portion of the URL. A value of :data:`None`
will remove the fragment portion of the URL.
:keyword str host: if specified, this keyword sets the host
portion of the network location. A value of :data:`None`
will remove the network location portion of the URL.
:keyword str password: if specified, this keyword sets the
password portion of the URL. A value of :data:`None` will
remove the password from the URL.
:keyword str path: if specified, this keyword sets the path
portion of the URL. A value of :data:`None` will remove
the path from the URL.
:keyword int port: if specified, this keyword sets the port
portion of the network location. A value of :data:`None`
will remove the port from the URL.
:keyword query: if specified, this keyword sets the query portion
of the URL. See the comments for a description of this
parameter.
:keyword str scheme: if specified, this keyword sets the scheme
portion of the URL. A value of :data:`None` will remove
the scheme. Note that this will make the URL relative and
may have unintended consequences.
:keyword str user: if specified, this keyword sets the user
portion of the URL. A value of :data:`None` will remove
the user and password portions.
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:return: the modified URL
:raises ValueError: when a keyword parameter is given an invalid
value
If the `host` parameter is specified and not :data:`None`, then
it will be processed as an Internationalized Domain Name (IDN)
if the scheme appears in :data:`IDNA_SCHEMES`. Otherwise, it
will be encoded as UTF-8 and percent encoded.
The handling of the `query` parameter requires some additional
explanation. You can specify a query value in three different
ways - as a *mapping*, as a *sequence* of pairs, or as a *string*.
This flexibility makes it possible to meet the wide range of
finicky use cases.
*If the query parameter is a mapping*, then the key + value pairs
are *sorted by the key* before they are encoded. Use this method
whenever possible.
*If the query parameter is a sequence of pairs*, then each pair
is encoded *in the given order*. Use this method if you require
that parameter order is controlled.
*If the query parameter is a string*, then it is *used as-is*.
This form SHOULD BE AVOIDED since it can easily result in broken
URLs since *no URL escaping is performed*. This is the obvious
pass through case that is almost always present.
"""
scheme, netloc, path, query, fragment = parse.urlsplit(input_url)
if 'scheme' in kwargs:
scheme = kwargs['scheme']
ident, host_n_port = parse.splituser(netloc)
user, password = parse.splitpasswd(ident) if ident else (None, None)
if 'user' in kwargs:
user = kwargs['user']
elif user is not None:
user = parse.unquote_to_bytes(user).decode('utf-8')
if 'password' in kwargs:
password = kwargs['password']
elif password is not None:
password = parse.unquote_to_bytes(password).decode('utf-8')
ident = _create_url_identifier(user, password)
host, port = parse.splitnport(host_n_port, defport=None)
if 'host' in kwargs:
host = kwargs['host']
if host is not None:
host = _normalize_host(
host,
enable_long_host=kwargs.get('enable_long_host', False),
encode_with_idna=kwargs.get('encode_with_idna', None),
scheme=scheme,
)
if 'port' in kwargs:
port = kwargs['port']
if port is not None:
port = int(kwargs['port'])
if port < 0:
raise ValueError('port is required to be non-negative')
if host is None or host == '':
host_n_port = None
elif port is None:
host_n_port = host
else:
host_n_port = '{0}:{1}'.format(host, port)
if 'path' in kwargs:
path = kwargs['path']
if path is None:
path = '/'
else:
path = parse.quote(path.encode('utf-8'), safe=PATH_SAFE_CHARS)
netloc = '{0}@{1}'.format(ident, host_n_port) if ident else host_n_port
if 'query' in kwargs:
new_query = kwargs['query']
if new_query is None:
query = None
else:
params = []
try:
for param in sorted(new_query.keys()):
params.append((param, new_query[param]))
except AttributeError: # arg is None or not a dict
pass
if not params: # maybe a sequence of tuples?
try:
params = [(param, value) for param, value in new_query]
except ValueError: # guess not...
pass
if params:
query = parse.urlencode(params)
else:
query = new_query
if 'fragment' in kwargs:
fragment = kwargs['fragment']
if fragment is not None:
fragment = parse.quote(fragment.encode('utf-8'),
safe=FRAGMENT_SAFE_CHARS)
# The following is necessary to get around some interesting special
# case code in urllib.parse._coerce_args in Python 3.4. Setting
# scheme to None causes urlunsplit to assume that all non-``None``
# parameters with be byte strings....
if scheme is None:
scheme = ''
return parse.urlunsplit((scheme, netloc, path, query, fragment))
|
[
"Create",
"a",
"new",
"URL",
"from",
"input_url",
"with",
"modifications",
"applied",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/algorithms.py#L167-L326
|
[
"def",
"rewrite_url",
"(",
"input_url",
",",
"*",
"*",
"kwargs",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"parse",
".",
"urlsplit",
"(",
"input_url",
")",
"if",
"'scheme'",
"in",
"kwargs",
":",
"scheme",
"=",
"kwargs",
"[",
"'scheme'",
"]",
"ident",
",",
"host_n_port",
"=",
"parse",
".",
"splituser",
"(",
"netloc",
")",
"user",
",",
"password",
"=",
"parse",
".",
"splitpasswd",
"(",
"ident",
")",
"if",
"ident",
"else",
"(",
"None",
",",
"None",
")",
"if",
"'user'",
"in",
"kwargs",
":",
"user",
"=",
"kwargs",
"[",
"'user'",
"]",
"elif",
"user",
"is",
"not",
"None",
":",
"user",
"=",
"parse",
".",
"unquote_to_bytes",
"(",
"user",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"'password'",
"in",
"kwargs",
":",
"password",
"=",
"kwargs",
"[",
"'password'",
"]",
"elif",
"password",
"is",
"not",
"None",
":",
"password",
"=",
"parse",
".",
"unquote_to_bytes",
"(",
"password",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"ident",
"=",
"_create_url_identifier",
"(",
"user",
",",
"password",
")",
"host",
",",
"port",
"=",
"parse",
".",
"splitnport",
"(",
"host_n_port",
",",
"defport",
"=",
"None",
")",
"if",
"'host'",
"in",
"kwargs",
":",
"host",
"=",
"kwargs",
"[",
"'host'",
"]",
"if",
"host",
"is",
"not",
"None",
":",
"host",
"=",
"_normalize_host",
"(",
"host",
",",
"enable_long_host",
"=",
"kwargs",
".",
"get",
"(",
"'enable_long_host'",
",",
"False",
")",
",",
"encode_with_idna",
"=",
"kwargs",
".",
"get",
"(",
"'encode_with_idna'",
",",
"None",
")",
",",
"scheme",
"=",
"scheme",
",",
")",
"if",
"'port'",
"in",
"kwargs",
":",
"port",
"=",
"kwargs",
"[",
"'port'",
"]",
"if",
"port",
"is",
"not",
"None",
":",
"port",
"=",
"int",
"(",
"kwargs",
"[",
"'port'",
"]",
")",
"if",
"port",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'port is required to be non-negative'",
")",
"if",
"host",
"is",
"None",
"or",
"host",
"==",
"''",
":",
"host_n_port",
"=",
"None",
"elif",
"port",
"is",
"None",
":",
"host_n_port",
"=",
"host",
"else",
":",
"host_n_port",
"=",
"'{0}:{1}'",
".",
"format",
"(",
"host",
",",
"port",
")",
"if",
"'path'",
"in",
"kwargs",
":",
"path",
"=",
"kwargs",
"[",
"'path'",
"]",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"'/'",
"else",
":",
"path",
"=",
"parse",
".",
"quote",
"(",
"path",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"PATH_SAFE_CHARS",
")",
"netloc",
"=",
"'{0}@{1}'",
".",
"format",
"(",
"ident",
",",
"host_n_port",
")",
"if",
"ident",
"else",
"host_n_port",
"if",
"'query'",
"in",
"kwargs",
":",
"new_query",
"=",
"kwargs",
"[",
"'query'",
"]",
"if",
"new_query",
"is",
"None",
":",
"query",
"=",
"None",
"else",
":",
"params",
"=",
"[",
"]",
"try",
":",
"for",
"param",
"in",
"sorted",
"(",
"new_query",
".",
"keys",
"(",
")",
")",
":",
"params",
".",
"append",
"(",
"(",
"param",
",",
"new_query",
"[",
"param",
"]",
")",
")",
"except",
"AttributeError",
":",
"# arg is None or not a dict",
"pass",
"if",
"not",
"params",
":",
"# maybe a sequence of tuples?",
"try",
":",
"params",
"=",
"[",
"(",
"param",
",",
"value",
")",
"for",
"param",
",",
"value",
"in",
"new_query",
"]",
"except",
"ValueError",
":",
"# guess not...",
"pass",
"if",
"params",
":",
"query",
"=",
"parse",
".",
"urlencode",
"(",
"params",
")",
"else",
":",
"query",
"=",
"new_query",
"if",
"'fragment'",
"in",
"kwargs",
":",
"fragment",
"=",
"kwargs",
"[",
"'fragment'",
"]",
"if",
"fragment",
"is",
"not",
"None",
":",
"fragment",
"=",
"parse",
".",
"quote",
"(",
"fragment",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"FRAGMENT_SAFE_CHARS",
")",
"# The following is necessary to get around some interesting special",
"# case code in urllib.parse._coerce_args in Python 3.4. Setting",
"# scheme to None causes urlunsplit to assume that all non-``None``",
"# parameters with be byte strings....",
"if",
"scheme",
"is",
"None",
":",
"scheme",
"=",
"''",
"return",
"parse",
".",
"urlunsplit",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
")",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
remove_url_auth
|
Removes the user & password and returns them along with a new url.
:param str url: the URL to sanitize
:return: a :class:`tuple` containing the authorization portion and
the sanitized URL. The authorization is a simple user & password
:class:`tuple`.
>>> auth, sanitized = remove_url_auth('http://foo:bar@example.com')
>>> auth
('foo', 'bar')
>>> sanitized
'http://example.com'
The return value from this function is simple named tuple with the
following fields:
- *auth* the username and password as a tuple
- *username* the username portion of the URL or :data:`None`
- *password* the password portion of the URL or :data:`None`
- *url* the sanitized URL
>>> result = remove_url_auth('http://me:secret@example.com')
>>> result.username
'me'
>>> result.password
'secret'
>>> result.url
'http://example.com'
|
ietfparse/algorithms.py
|
def remove_url_auth(url):
"""
Removes the user & password and returns them along with a new url.
:param str url: the URL to sanitize
:return: a :class:`tuple` containing the authorization portion and
the sanitized URL. The authorization is a simple user & password
:class:`tuple`.
>>> auth, sanitized = remove_url_auth('http://foo:bar@example.com')
>>> auth
('foo', 'bar')
>>> sanitized
'http://example.com'
The return value from this function is simple named tuple with the
following fields:
- *auth* the username and password as a tuple
- *username* the username portion of the URL or :data:`None`
- *password* the password portion of the URL or :data:`None`
- *url* the sanitized URL
>>> result = remove_url_auth('http://me:secret@example.com')
>>> result.username
'me'
>>> result.password
'secret'
>>> result.url
'http://example.com'
"""
parts = parse.urlsplit(url)
return RemoveUrlAuthResult(auth=(parts.username or None, parts.password),
url=rewrite_url(url, user=None, password=None))
|
def remove_url_auth(url):
"""
Removes the user & password and returns them along with a new url.
:param str url: the URL to sanitize
:return: a :class:`tuple` containing the authorization portion and
the sanitized URL. The authorization is a simple user & password
:class:`tuple`.
>>> auth, sanitized = remove_url_auth('http://foo:bar@example.com')
>>> auth
('foo', 'bar')
>>> sanitized
'http://example.com'
The return value from this function is simple named tuple with the
following fields:
- *auth* the username and password as a tuple
- *username* the username portion of the URL or :data:`None`
- *password* the password portion of the URL or :data:`None`
- *url* the sanitized URL
>>> result = remove_url_auth('http://me:secret@example.com')
>>> result.username
'me'
>>> result.password
'secret'
>>> result.url
'http://example.com'
"""
parts = parse.urlsplit(url)
return RemoveUrlAuthResult(auth=(parts.username or None, parts.password),
url=rewrite_url(url, user=None, password=None))
|
[
"Removes",
"the",
"user",
"&",
"password",
"and",
"returns",
"them",
"along",
"with",
"a",
"new",
"url",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/algorithms.py#L329-L363
|
[
"def",
"remove_url_auth",
"(",
"url",
")",
":",
"parts",
"=",
"parse",
".",
"urlsplit",
"(",
"url",
")",
"return",
"RemoveUrlAuthResult",
"(",
"auth",
"=",
"(",
"parts",
".",
"username",
"or",
"None",
",",
"parts",
".",
"password",
")",
",",
"url",
"=",
"rewrite_url",
"(",
"url",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
")",
")"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
_create_url_identifier
|
Generate the user+password portion of a URL.
:param str user: the user name or :data:`None`
:param str password: the password or :data:`None`
|
ietfparse/algorithms.py
|
def _create_url_identifier(user, password):
"""
Generate the user+password portion of a URL.
:param str user: the user name or :data:`None`
:param str password: the password or :data:`None`
"""
if user is not None:
user = parse.quote(user.encode('utf-8'), safe=USERINFO_SAFE_CHARS)
if password:
password = parse.quote(password.encode('utf-8'),
safe=USERINFO_SAFE_CHARS)
return '{0}:{1}'.format(user, password)
return user
return None
|
def _create_url_identifier(user, password):
"""
Generate the user+password portion of a URL.
:param str user: the user name or :data:`None`
:param str password: the password or :data:`None`
"""
if user is not None:
user = parse.quote(user.encode('utf-8'), safe=USERINFO_SAFE_CHARS)
if password:
password = parse.quote(password.encode('utf-8'),
safe=USERINFO_SAFE_CHARS)
return '{0}:{1}'.format(user, password)
return user
return None
|
[
"Generate",
"the",
"user",
"+",
"password",
"portion",
"of",
"a",
"URL",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/algorithms.py#L366-L381
|
[
"def",
"_create_url_identifier",
"(",
"user",
",",
"password",
")",
":",
"if",
"user",
"is",
"not",
"None",
":",
"user",
"=",
"parse",
".",
"quote",
"(",
"user",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"USERINFO_SAFE_CHARS",
")",
"if",
"password",
":",
"password",
"=",
"parse",
".",
"quote",
"(",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"USERINFO_SAFE_CHARS",
")",
"return",
"'{0}:{1}'",
".",
"format",
"(",
"user",
",",
"password",
")",
"return",
"user",
"return",
"None"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
_normalize_host
|
Normalize a host for a URL.
:param str host: the host name to normalize
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:keyword str scheme: if this keyword is specified, then it is
used to determine whether to apply IDN rules or not. This
parameter is ignored if `encode_with_idna` is not :data:`None`.
:return: the normalized and encoded string ready for inclusion
into a URL
|
ietfparse/algorithms.py
|
def _normalize_host(host, enable_long_host=False, encode_with_idna=None,
scheme=None):
"""
Normalize a host for a URL.
:param str host: the host name to normalize
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:keyword str scheme: if this keyword is specified, then it is
used to determine whether to apply IDN rules or not. This
parameter is ignored if `encode_with_idna` is not :data:`None`.
:return: the normalized and encoded string ready for inclusion
into a URL
"""
if encode_with_idna is not None:
enable_idna = encode_with_idna
else:
enable_idna = scheme.lower() in IDNA_SCHEMES if scheme else False
if enable_idna:
try:
host = '.'.join(segment.encode('idna').decode()
for segment in host.split('.'))
except UnicodeError as exc:
raise ValueError('host is invalid - {0}'.format(exc))
else:
host = parse.quote(host.encode('utf-8'), safe=HOST_SAFE_CHARS)
if len(host) > 255 and not enable_long_host:
raise ValueError('host too long')
return host
|
def _normalize_host(host, enable_long_host=False, encode_with_idna=None,
scheme=None):
"""
Normalize a host for a URL.
:param str host: the host name to normalize
:keyword bool enable_long_host: if this keyword is specified
and it is :data:`True`, then the host name length restriction
from :rfc:`3986#section-3.2.2` is relaxed.
:keyword bool encode_with_idna: if this keyword is specified
and it is :data:`True`, then the ``host`` parameter will be
encoded using IDN. If this value is provided as :data:`False`,
then the percent-encoding scheme is used instead. If this
parameter is omitted or included with a different value, then
the ``host`` parameter is processed using :data:`IDNA_SCHEMES`.
:keyword str scheme: if this keyword is specified, then it is
used to determine whether to apply IDN rules or not. This
parameter is ignored if `encode_with_idna` is not :data:`None`.
:return: the normalized and encoded string ready for inclusion
into a URL
"""
if encode_with_idna is not None:
enable_idna = encode_with_idna
else:
enable_idna = scheme.lower() in IDNA_SCHEMES if scheme else False
if enable_idna:
try:
host = '.'.join(segment.encode('idna').decode()
for segment in host.split('.'))
except UnicodeError as exc:
raise ValueError('host is invalid - {0}'.format(exc))
else:
host = parse.quote(host.encode('utf-8'), safe=HOST_SAFE_CHARS)
if len(host) > 255 and not enable_long_host:
raise ValueError('host too long')
return host
|
[
"Normalize",
"a",
"host",
"for",
"a",
"URL",
"."
] |
dave-shawley/ietfparse
|
python
|
https://github.com/dave-shawley/ietfparse/blob/d28f360941316e45c1596589fa59bc7d25aa20e0/ietfparse/algorithms.py#L384-L424
|
[
"def",
"_normalize_host",
"(",
"host",
",",
"enable_long_host",
"=",
"False",
",",
"encode_with_idna",
"=",
"None",
",",
"scheme",
"=",
"None",
")",
":",
"if",
"encode_with_idna",
"is",
"not",
"None",
":",
"enable_idna",
"=",
"encode_with_idna",
"else",
":",
"enable_idna",
"=",
"scheme",
".",
"lower",
"(",
")",
"in",
"IDNA_SCHEMES",
"if",
"scheme",
"else",
"False",
"if",
"enable_idna",
":",
"try",
":",
"host",
"=",
"'.'",
".",
"join",
"(",
"segment",
".",
"encode",
"(",
"'idna'",
")",
".",
"decode",
"(",
")",
"for",
"segment",
"in",
"host",
".",
"split",
"(",
"'.'",
")",
")",
"except",
"UnicodeError",
"as",
"exc",
":",
"raise",
"ValueError",
"(",
"'host is invalid - {0}'",
".",
"format",
"(",
"exc",
")",
")",
"else",
":",
"host",
"=",
"parse",
".",
"quote",
"(",
"host",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"safe",
"=",
"HOST_SAFE_CHARS",
")",
"if",
"len",
"(",
"host",
")",
">",
"255",
"and",
"not",
"enable_long_host",
":",
"raise",
"ValueError",
"(",
"'host too long'",
")",
"return",
"host"
] |
d28f360941316e45c1596589fa59bc7d25aa20e0
|
test
|
NoiseGenerator.transform
|
:X: numpy ndarray
|
sklearn_utils/noise/noise_preprocessing.py
|
def transform(self, X):
'''
:X: numpy ndarray
'''
noise = self._noise_func(*self._args, size=X.shape)
results = X + noise
self.relative_noise_size_ = self.relative_noise_size(X, results)
return results
|
def transform(self, X):
'''
:X: numpy ndarray
'''
noise = self._noise_func(*self._args, size=X.shape)
results = X + noise
self.relative_noise_size_ = self.relative_noise_size(X, results)
return results
|
[
":",
"X",
":",
"numpy",
"ndarray"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/noise/noise_preprocessing.py#L24-L31
|
[
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"noise",
"=",
"self",
".",
"_noise_func",
"(",
"*",
"self",
".",
"_args",
",",
"size",
"=",
"X",
".",
"shape",
")",
"results",
"=",
"X",
"+",
"noise",
"self",
".",
"relative_noise_size_",
"=",
"self",
".",
"relative_noise_size",
"(",
"X",
",",
"results",
")",
"return",
"results"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
NoiseGenerator.relative_noise_size
|
:data: original data as numpy matrix
:noise: noise matrix as numpy matrix
|
sklearn_utils/noise/noise_preprocessing.py
|
def relative_noise_size(self, data, noise):
'''
:data: original data as numpy matrix
:noise: noise matrix as numpy matrix
'''
return np.mean([
sci_dist.cosine(u / la.norm(u), v / la.norm(v))
for u, v in zip(noise, data)
])
|
def relative_noise_size(self, data, noise):
'''
:data: original data as numpy matrix
:noise: noise matrix as numpy matrix
'''
return np.mean([
sci_dist.cosine(u / la.norm(u), v / la.norm(v))
for u, v in zip(noise, data)
])
|
[
":",
"data",
":",
"original",
"data",
"as",
"numpy",
"matrix",
":",
"noise",
":",
"noise",
"matrix",
"as",
"numpy",
"matrix"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/noise/noise_preprocessing.py#L33-L41
|
[
"def",
"relative_noise_size",
"(",
"self",
",",
"data",
",",
"noise",
")",
":",
"return",
"np",
".",
"mean",
"(",
"[",
"sci_dist",
".",
"cosine",
"(",
"u",
"/",
"la",
".",
"norm",
"(",
"u",
")",
",",
"v",
"/",
"la",
".",
"norm",
"(",
"v",
")",
")",
"for",
"u",
",",
"v",
"in",
"zip",
"(",
"noise",
",",
"data",
")",
"]",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
general
|
将被装饰函数封装为一个 :class:`click.core.Command` 类,
此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个 ``mohand`` 子命令的功能
该装饰器作为一个一般装饰器使用(如: ``@hand.general`` )
.. note::
该装饰器会在插件系统加载外部插件前辈注册到 :data:`.hands.hand` 中。
此处的 ``general`` 装饰器同时兼容有参和无参调用方式
:param int log_level: 当前子命令的日志输出等级,默认为: ``logging.INFO``
:return: 被封装后的函数
:rtype: function
|
source/mohand/decorator.py
|
def general(*dargs, **dkwargs):
"""
将被装饰函数封装为一个 :class:`click.core.Command` 类,
此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个 ``mohand`` 子命令的功能
该装饰器作为一个一般装饰器使用(如: ``@hand.general`` )
.. note::
该装饰器会在插件系统加载外部插件前辈注册到 :data:`.hands.hand` 中。
此处的 ``general`` 装饰器同时兼容有参和无参调用方式
:param int log_level: 当前子命令的日志输出等级,默认为: ``logging.INFO``
:return: 被封装后的函数
:rtype: function
"""
invoked = bool(len(dargs) == 1 and not dkwargs and callable(dargs[0]))
if invoked:
func = dargs[0]
def wrapper(func):
@hand._click.command(
name=func.__name__.lower(),
help=func.__doc__)
def _wrapper(*args, **kwargs):
log_level = dkwargs.pop('log_level', logging.INFO)
log.setLevel(log_level)
log.debug("decrator param: {} {}".format(dargs, dkwargs))
log.debug("function param: {} {}".format(args, kwargs))
func(*args, **kwargs)
return _wrapper
return wrapper if not invoked else wrapper(func)
|
def general(*dargs, **dkwargs):
"""
将被装饰函数封装为一个 :class:`click.core.Command` 类,
此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个 ``mohand`` 子命令的功能
该装饰器作为一个一般装饰器使用(如: ``@hand.general`` )
.. note::
该装饰器会在插件系统加载外部插件前辈注册到 :data:`.hands.hand` 中。
此处的 ``general`` 装饰器同时兼容有参和无参调用方式
:param int log_level: 当前子命令的日志输出等级,默认为: ``logging.INFO``
:return: 被封装后的函数
:rtype: function
"""
invoked = bool(len(dargs) == 1 and not dkwargs and callable(dargs[0]))
if invoked:
func = dargs[0]
def wrapper(func):
@hand._click.command(
name=func.__name__.lower(),
help=func.__doc__)
def _wrapper(*args, **kwargs):
log_level = dkwargs.pop('log_level', logging.INFO)
log.setLevel(log_level)
log.debug("decrator param: {} {}".format(dargs, dkwargs))
log.debug("function param: {} {}".format(args, kwargs))
func(*args, **kwargs)
return _wrapper
return wrapper if not invoked else wrapper(func)
|
[
"将被装饰函数封装为一个",
":",
"class",
":",
"click",
".",
"core",
".",
"Command",
"类,",
"此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个",
"mohand",
"子命令的功能"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/decorator.py#L26-L60
|
[
"def",
"general",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkwargs",
")",
":",
"invoked",
"=",
"bool",
"(",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"not",
"dkwargs",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
")",
"if",
"invoked",
":",
"func",
"=",
"dargs",
"[",
"0",
"]",
"def",
"wrapper",
"(",
"func",
")",
":",
"@",
"hand",
".",
"_click",
".",
"command",
"(",
"name",
"=",
"func",
".",
"__name__",
".",
"lower",
"(",
")",
",",
"help",
"=",
"func",
".",
"__doc__",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log_level",
"=",
"dkwargs",
".",
"pop",
"(",
"'log_level'",
",",
"logging",
".",
"INFO",
")",
"log",
".",
"setLevel",
"(",
"log_level",
")",
"log",
".",
"debug",
"(",
"\"decrator param: {} {}\"",
".",
"format",
"(",
"dargs",
",",
"dkwargs",
")",
")",
"log",
".",
"debug",
"(",
"\"function param: {} {}\"",
".",
"format",
"(",
"args",
",",
"kwargs",
")",
")",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_wrapper",
"return",
"wrapper",
"if",
"not",
"invoked",
"else",
"wrapper",
"(",
"func",
")"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
discover_modules
|
Attempts to list all of the modules and submodules found within a given
directory tree. This function searches the top-level of the directory
tree for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
|
pynsive/reflection.py
|
def discover_modules(directory):
"""
Attempts to list all of the modules and submodules found within a given
directory tree. This function searches the top-level of the directory
tree for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
"""
found = list()
if os.path.isdir(directory):
for entry in os.listdir(directory):
next_dir = os.path.join(directory, entry)
# Scan only if there's an __init__.py file
if os.path.isfile(os.path.join(next_dir, MODULE_INIT_FILE)):
found.append(entry)
return found
|
def discover_modules(directory):
"""
Attempts to list all of the modules and submodules found within a given
directory tree. This function searches the top-level of the directory
tree for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
"""
found = list()
if os.path.isdir(directory):
for entry in os.listdir(directory):
next_dir = os.path.join(directory, entry)
# Scan only if there's an __init__.py file
if os.path.isfile(os.path.join(next_dir, MODULE_INIT_FILE)):
found.append(entry)
return found
|
[
"Attempts",
"to",
"list",
"all",
"of",
"the",
"modules",
"and",
"submodules",
"found",
"within",
"a",
"given",
"directory",
"tree",
".",
"This",
"function",
"searches",
"the",
"top",
"-",
"level",
"of",
"the",
"directory",
"tree",
"for",
"potential",
"python",
"modules",
"and",
"returns",
"a",
"list",
"of",
"candidate",
"names",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/reflection.py#L90-L111
|
[
"def",
"discover_modules",
"(",
"directory",
")",
":",
"found",
"=",
"list",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"next_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"entry",
")",
"# Scan only if there's an __init__.py file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"next_dir",
",",
"MODULE_INIT_FILE",
")",
")",
":",
"found",
".",
"append",
"(",
"entry",
")",
"return",
"found"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
rdiscover_modules
|
Attempts to list all of the modules and submodules found within a given
directory tree. This function recursively searches the directory tree
for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
|
pynsive/reflection.py
|
def rdiscover_modules(directory):
"""
Attempts to list all of the modules and submodules found within a given
directory tree. This function recursively searches the directory tree
for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
"""
found = list()
if os.path.isdir(directory):
for entry in os.listdir(directory):
next_dir = os.path.join(directory, entry)
# Scan only if there's an __init__.py file
if os.path.isfile(os.path.join(next_dir, MODULE_INIT_FILE)):
modules = _search_for_modules(next_dir, True, entry)
found.extend(modules)
return found
|
def rdiscover_modules(directory):
"""
Attempts to list all of the modules and submodules found within a given
directory tree. This function recursively searches the directory tree
for potential python modules and returns a list of candidate names.
**Note:** This function returns a list of strings representing
discovered module names, not the actual, loaded modules.
:param directory: the directory to search for modules.
"""
found = list()
if os.path.isdir(directory):
for entry in os.listdir(directory):
next_dir = os.path.join(directory, entry)
# Scan only if there's an __init__.py file
if os.path.isfile(os.path.join(next_dir, MODULE_INIT_FILE)):
modules = _search_for_modules(next_dir, True, entry)
found.extend(modules)
return found
|
[
"Attempts",
"to",
"list",
"all",
"of",
"the",
"modules",
"and",
"submodules",
"found",
"within",
"a",
"given",
"directory",
"tree",
".",
"This",
"function",
"recursively",
"searches",
"the",
"directory",
"tree",
"for",
"potential",
"python",
"modules",
"and",
"returns",
"a",
"list",
"of",
"candidate",
"names",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/reflection.py#L114-L136
|
[
"def",
"rdiscover_modules",
"(",
"directory",
")",
":",
"found",
"=",
"list",
"(",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"directory",
")",
":",
"next_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"entry",
")",
"# Scan only if there's an __init__.py file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"next_dir",
",",
"MODULE_INIT_FILE",
")",
")",
":",
"modules",
"=",
"_search_for_modules",
"(",
"next_dir",
",",
"True",
",",
"entry",
")",
"found",
".",
"extend",
"(",
"modules",
")",
"return",
"found"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
rlist_modules
|
Attempts to the submodules under a module recursively. This function
works for modules located in the default path as well as extended paths
via the sys.meta_path hooks.
This function carries the expectation that the hidden module variable
'__path__' has been set correctly.
:param mname: the module name to descend into
|
pynsive/reflection.py
|
def rlist_modules(mname):
"""
Attempts to the submodules under a module recursively. This function
works for modules located in the default path as well as extended paths
via the sys.meta_path hooks.
This function carries the expectation that the hidden module variable
'__path__' has been set correctly.
:param mname: the module name to descend into
"""
module = import_module(mname)
if not module:
raise ImportError('Unable to load module {}'.format(mname))
found = list()
if _should_use_module_path(module):
mpath = module.__path__[0]
else:
mpaths = sys.path
mpath = _scan_paths_for(mname, mpaths)
if mpath:
for pmname in _search_for_modules(mpath, recursive=True):
found_mod = MODULE_PATH_SEP.join((mname, pmname))
found.append(found_mod)
return found
|
def rlist_modules(mname):
"""
Attempts to the submodules under a module recursively. This function
works for modules located in the default path as well as extended paths
via the sys.meta_path hooks.
This function carries the expectation that the hidden module variable
'__path__' has been set correctly.
:param mname: the module name to descend into
"""
module = import_module(mname)
if not module:
raise ImportError('Unable to load module {}'.format(mname))
found = list()
if _should_use_module_path(module):
mpath = module.__path__[0]
else:
mpaths = sys.path
mpath = _scan_paths_for(mname, mpaths)
if mpath:
for pmname in _search_for_modules(mpath, recursive=True):
found_mod = MODULE_PATH_SEP.join((mname, pmname))
found.append(found_mod)
return found
|
[
"Attempts",
"to",
"the",
"submodules",
"under",
"a",
"module",
"recursively",
".",
"This",
"function",
"works",
"for",
"modules",
"located",
"in",
"the",
"default",
"path",
"as",
"well",
"as",
"extended",
"paths",
"via",
"the",
"sys",
".",
"meta_path",
"hooks",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/reflection.py#L168-L194
|
[
"def",
"rlist_modules",
"(",
"mname",
")",
":",
"module",
"=",
"import_module",
"(",
"mname",
")",
"if",
"not",
"module",
":",
"raise",
"ImportError",
"(",
"'Unable to load module {}'",
".",
"format",
"(",
"mname",
")",
")",
"found",
"=",
"list",
"(",
")",
"if",
"_should_use_module_path",
"(",
"module",
")",
":",
"mpath",
"=",
"module",
".",
"__path__",
"[",
"0",
"]",
"else",
":",
"mpaths",
"=",
"sys",
".",
"path",
"mpath",
"=",
"_scan_paths_for",
"(",
"mname",
",",
"mpaths",
")",
"if",
"mpath",
":",
"for",
"pmname",
"in",
"_search_for_modules",
"(",
"mpath",
",",
"recursive",
"=",
"True",
")",
":",
"found_mod",
"=",
"MODULE_PATH_SEP",
".",
"join",
"(",
"(",
"mname",
",",
"pmname",
")",
")",
"found",
".",
"append",
"(",
"found_mod",
")",
"return",
"found"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
list_classes
|
Attempts to list all of the classes within a specified module. This
function works for modules located in the default path as well as
extended paths via the sys.meta_path hooks.
If a class filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
the type in the list of returned classes.
:param mname: of the module to descend into
:param cls_filter: a function to call to determine what classes should be
included.
|
pynsive/reflection.py
|
def list_classes(mname, cls_filter=None):
"""
Attempts to list all of the classes within a specified module. This
function works for modules located in the default path as well as
extended paths via the sys.meta_path hooks.
If a class filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
the type in the list of returned classes.
:param mname: of the module to descend into
:param cls_filter: a function to call to determine what classes should be
included.
"""
found = list()
module = import_module(mname)
if inspect.ismodule(module):
[found.append(mod) for mod in _list_classes(module, cls_filter)]
return found
|
def list_classes(mname, cls_filter=None):
"""
Attempts to list all of the classes within a specified module. This
function works for modules located in the default path as well as
extended paths via the sys.meta_path hooks.
If a class filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
the type in the list of returned classes.
:param mname: of the module to descend into
:param cls_filter: a function to call to determine what classes should be
included.
"""
found = list()
module = import_module(mname)
if inspect.ismodule(module):
[found.append(mod) for mod in _list_classes(module, cls_filter)]
return found
|
[
"Attempts",
"to",
"list",
"all",
"of",
"the",
"classes",
"within",
"a",
"specified",
"module",
".",
"This",
"function",
"works",
"for",
"modules",
"located",
"in",
"the",
"default",
"path",
"as",
"well",
"as",
"extended",
"paths",
"via",
"the",
"sys",
".",
"meta_path",
"hooks",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/reflection.py#L197-L217
|
[
"def",
"list_classes",
"(",
"mname",
",",
"cls_filter",
"=",
"None",
")",
":",
"found",
"=",
"list",
"(",
")",
"module",
"=",
"import_module",
"(",
"mname",
")",
"if",
"inspect",
".",
"ismodule",
"(",
"module",
")",
":",
"[",
"found",
".",
"append",
"(",
"mod",
")",
"for",
"mod",
"in",
"_list_classes",
"(",
"module",
",",
"cls_filter",
")",
"]",
"return",
"found"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
rlist_classes
|
Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
the type in the list of returned classes.
:param mname: of the module to descend into
:param cls_filter: a function to call to determine what classes should be
included.
|
pynsive/reflection.py
|
def rlist_classes(module, cls_filter=None):
"""
Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
the type in the list of returned classes.
:param mname: of the module to descend into
:param cls_filter: a function to call to determine what classes should be
included.
"""
found = list()
mnames = rlist_modules(module)
for mname in mnames:
[found.append(c) for c in list_classes(mname, cls_filter)]
return found
|
def rlist_classes(module, cls_filter=None):
"""
Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that evaluate as True will include the type in the
list of returned classes. Results that evaluate as False will exclude
the type in the list of returned classes.
:param mname: of the module to descend into
:param cls_filter: a function to call to determine what classes should be
included.
"""
found = list()
mnames = rlist_modules(module)
for mname in mnames:
[found.append(c) for c in list_classes(mname, cls_filter)]
return found
|
[
"Attempts",
"to",
"list",
"all",
"of",
"the",
"classes",
"within",
"a",
"given",
"module",
"namespace",
".",
"This",
"method",
"unlike",
"list_classes",
"will",
"recurse",
"into",
"discovered",
"submodules",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/reflection.py#L220-L240
|
[
"def",
"rlist_classes",
"(",
"module",
",",
"cls_filter",
"=",
"None",
")",
":",
"found",
"=",
"list",
"(",
")",
"mnames",
"=",
"rlist_modules",
"(",
"module",
")",
"for",
"mname",
"in",
"mnames",
":",
"[",
"found",
".",
"append",
"(",
"c",
")",
"for",
"c",
"in",
"list_classes",
"(",
"mname",
",",
"cls_filter",
")",
"]",
"return",
"found"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
rgb_to_hsl
|
Converts an RGB color value to HSL.
:param r: The red color value
:param g: The green color value
:param b: The blue color value
:return: The HSL representation
|
littlefish/colourutil.py
|
def rgb_to_hsl(r, g, b):
"""
Converts an RGB color value to HSL.
:param r: The red color value
:param g: The green color value
:param b: The blue color value
:return: The HSL representation
"""
r = float(r) / 255.0
g = float(g) / 255.0
b = float(b) / 255.0
max_value = max(r, g, b)
min_value = min(r, g, b)
h = None
s = None
l = (max_value + min_value) / 2
d = max_value - min_value
if d == 0:
# achromatic
h = 0
s = 0
else:
s = d / (1 - abs(2 * l - 1))
if r == max_value:
h = 60 * ((g - b) % 6)
if b > g:
h += 360
if g == max_value:
h = 60 * ((b - r) / d + 2)
if b == max_value:
h = 60 * ((r - g) / d + 4)
return round(h, 2), round(s, 2), round(l, 2)
|
def rgb_to_hsl(r, g, b):
"""
Converts an RGB color value to HSL.
:param r: The red color value
:param g: The green color value
:param b: The blue color value
:return: The HSL representation
"""
r = float(r) / 255.0
g = float(g) / 255.0
b = float(b) / 255.0
max_value = max(r, g, b)
min_value = min(r, g, b)
h = None
s = None
l = (max_value + min_value) / 2
d = max_value - min_value
if d == 0:
# achromatic
h = 0
s = 0
else:
s = d / (1 - abs(2 * l - 1))
if r == max_value:
h = 60 * ((g - b) % 6)
if b > g:
h += 360
if g == max_value:
h = 60 * ((b - r) / d + 2)
if b == max_value:
h = 60 * ((r - g) / d + 4)
return round(h, 2), round(s, 2), round(l, 2)
|
[
"Converts",
"an",
"RGB",
"color",
"value",
"to",
"HSL",
".",
":",
"param",
"r",
":",
"The",
"red",
"color",
"value",
":",
"param",
"g",
":",
"The",
"green",
"color",
"value",
":",
"param",
"b",
":",
"The",
"blue",
"color",
"value",
":",
"return",
":",
"The",
"HSL",
"representation"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/colourutil.py#L13-L49
|
[
"def",
"rgb_to_hsl",
"(",
"r",
",",
"g",
",",
"b",
")",
":",
"r",
"=",
"float",
"(",
"r",
")",
"/",
"255.0",
"g",
"=",
"float",
"(",
"g",
")",
"/",
"255.0",
"b",
"=",
"float",
"(",
"b",
")",
"/",
"255.0",
"max_value",
"=",
"max",
"(",
"r",
",",
"g",
",",
"b",
")",
"min_value",
"=",
"min",
"(",
"r",
",",
"g",
",",
"b",
")",
"h",
"=",
"None",
"s",
"=",
"None",
"l",
"=",
"(",
"max_value",
"+",
"min_value",
")",
"/",
"2",
"d",
"=",
"max_value",
"-",
"min_value",
"if",
"d",
"==",
"0",
":",
"# achromatic",
"h",
"=",
"0",
"s",
"=",
"0",
"else",
":",
"s",
"=",
"d",
"/",
"(",
"1",
"-",
"abs",
"(",
"2",
"*",
"l",
"-",
"1",
")",
")",
"if",
"r",
"==",
"max_value",
":",
"h",
"=",
"60",
"*",
"(",
"(",
"g",
"-",
"b",
")",
"%",
"6",
")",
"if",
"b",
">",
"g",
":",
"h",
"+=",
"360",
"if",
"g",
"==",
"max_value",
":",
"h",
"=",
"60",
"*",
"(",
"(",
"b",
"-",
"r",
")",
"/",
"d",
"+",
"2",
")",
"if",
"b",
"==",
"max_value",
":",
"h",
"=",
"60",
"*",
"(",
"(",
"r",
"-",
"g",
")",
"/",
"d",
"+",
"4",
")",
"return",
"round",
"(",
"h",
",",
"2",
")",
",",
"round",
"(",
"s",
",",
"2",
")",
",",
"round",
"(",
"l",
",",
"2",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
html_color_to_rgba
|
:param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css
|
littlefish/colourutil.py
|
def html_color_to_rgba(html_colour, alpha):
"""
:param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css
"""
html_colour = html_colour.upper()
if html_colour[0] == '#':
html_colour = html_colour[1:]
r_str = html_colour[0:2]
g_str = html_colour[2:4]
b_str = html_colour[4:6]
r = int(r_str, 16)
g = int(g_str, 16)
b = int(b_str, 16)
return 'rgba(%s, %s, %s, %s)' % (r, g, b, alpha)
|
def html_color_to_rgba(html_colour, alpha):
"""
:param html_colour: Colour string like FF0088
:param alpha: Alpha value (opacity)
:return: RGBA semitransparent version of colour for use in css
"""
html_colour = html_colour.upper()
if html_colour[0] == '#':
html_colour = html_colour[1:]
r_str = html_colour[0:2]
g_str = html_colour[2:4]
b_str = html_colour[4:6]
r = int(r_str, 16)
g = int(g_str, 16)
b = int(b_str, 16)
return 'rgba(%s, %s, %s, %s)' % (r, g, b, alpha)
|
[
":",
"param",
"html_colour",
":",
"Colour",
"string",
"like",
"FF0088",
":",
"param",
"alpha",
":",
"Alpha",
"value",
"(",
"opacity",
")",
":",
"return",
":",
"RGBA",
"semitransparent",
"version",
"of",
"colour",
"for",
"use",
"in",
"css"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/colourutil.py#L94-L112
|
[
"def",
"html_color_to_rgba",
"(",
"html_colour",
",",
"alpha",
")",
":",
"html_colour",
"=",
"html_colour",
".",
"upper",
"(",
")",
"if",
"html_colour",
"[",
"0",
"]",
"==",
"'#'",
":",
"html_colour",
"=",
"html_colour",
"[",
"1",
":",
"]",
"r_str",
"=",
"html_colour",
"[",
"0",
":",
"2",
"]",
"g_str",
"=",
"html_colour",
"[",
"2",
":",
"4",
"]",
"b_str",
"=",
"html_colour",
"[",
"4",
":",
"6",
"]",
"r",
"=",
"int",
"(",
"r_str",
",",
"16",
")",
"g",
"=",
"int",
"(",
"g_str",
",",
"16",
")",
"b",
"=",
"int",
"(",
"b_str",
",",
"16",
")",
"return",
"'rgba(%s, %s, %s, %s)'",
"%",
"(",
"r",
",",
"g",
",",
"b",
",",
"alpha",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
blend_html_colour_to_white
|
:param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white
|
littlefish/colourutil.py
|
def blend_html_colour_to_white(html_colour, alpha):
"""
:param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white
"""
html_colour = html_colour.upper()
has_hash = False
if html_colour[0] == '#':
has_hash = True
html_colour = html_colour[1:]
r_str = html_colour[0:2]
g_str = html_colour[2:4]
b_str = html_colour[4:6]
r = int(r_str, 16)
g = int(g_str, 16)
b = int(b_str, 16)
r = int(alpha * r + (1 - alpha) * 255)
g = int(alpha * g + (1 - alpha) * 255)
b = int(alpha * b + (1 - alpha) * 255)
out = '{:02X}{:02X}{:02X}'.format(r, g, b)
if has_hash:
out = '#' + out
return out
|
def blend_html_colour_to_white(html_colour, alpha):
"""
:param html_colour: Colour string like FF552B or #334455
:param alpha: Alpha value
:return: Html colour alpha blended onto white
"""
html_colour = html_colour.upper()
has_hash = False
if html_colour[0] == '#':
has_hash = True
html_colour = html_colour[1:]
r_str = html_colour[0:2]
g_str = html_colour[2:4]
b_str = html_colour[4:6]
r = int(r_str, 16)
g = int(g_str, 16)
b = int(b_str, 16)
r = int(alpha * r + (1 - alpha) * 255)
g = int(alpha * g + (1 - alpha) * 255)
b = int(alpha * b + (1 - alpha) * 255)
out = '{:02X}{:02X}{:02X}'.format(r, g, b)
if has_hash:
out = '#' + out
return out
|
[
":",
"param",
"html_colour",
":",
"Colour",
"string",
"like",
"FF552B",
"or",
"#334455",
":",
"param",
"alpha",
":",
"Alpha",
"value",
":",
"return",
":",
"Html",
"colour",
"alpha",
"blended",
"onto",
"white"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/colourutil.py#L115-L143
|
[
"def",
"blend_html_colour_to_white",
"(",
"html_colour",
",",
"alpha",
")",
":",
"html_colour",
"=",
"html_colour",
".",
"upper",
"(",
")",
"has_hash",
"=",
"False",
"if",
"html_colour",
"[",
"0",
"]",
"==",
"'#'",
":",
"has_hash",
"=",
"True",
"html_colour",
"=",
"html_colour",
"[",
"1",
":",
"]",
"r_str",
"=",
"html_colour",
"[",
"0",
":",
"2",
"]",
"g_str",
"=",
"html_colour",
"[",
"2",
":",
"4",
"]",
"b_str",
"=",
"html_colour",
"[",
"4",
":",
"6",
"]",
"r",
"=",
"int",
"(",
"r_str",
",",
"16",
")",
"g",
"=",
"int",
"(",
"g_str",
",",
"16",
")",
"b",
"=",
"int",
"(",
"b_str",
",",
"16",
")",
"r",
"=",
"int",
"(",
"alpha",
"*",
"r",
"+",
"(",
"1",
"-",
"alpha",
")",
"*",
"255",
")",
"g",
"=",
"int",
"(",
"alpha",
"*",
"g",
"+",
"(",
"1",
"-",
"alpha",
")",
"*",
"255",
")",
"b",
"=",
"int",
"(",
"alpha",
"*",
"b",
"+",
"(",
"1",
"-",
"alpha",
")",
"*",
"255",
")",
"out",
"=",
"'{:02X}{:02X}{:02X}'",
".",
"format",
"(",
"r",
",",
"g",
",",
"b",
")",
"if",
"has_hash",
":",
"out",
"=",
"'#'",
"+",
"out",
"return",
"out"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
FoldChangeScaler.fit
|
:X: list of dict
:y: labels
|
sklearn_utils/preprocessing/fold_change_preprocessing.py
|
def fit(self, X, y):
'''
:X: list of dict
:y: labels
'''
self._avgs = average_by_label(X, y, self.reference_label)
return self
|
def fit(self, X, y):
'''
:X: list of dict
:y: labels
'''
self._avgs = average_by_label(X, y, self.reference_label)
return self
|
[
":",
"X",
":",
"list",
"of",
"dict",
":",
"y",
":",
"labels"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/fold_change_preprocessing.py#L21-L27
|
[
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"self",
".",
"_avgs",
"=",
"average_by_label",
"(",
"X",
",",
"y",
",",
"self",
".",
"reference_label",
")",
"return",
"self"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
FeatureRenaming.transform
|
:X: list of dict
|
sklearn_utils/preprocessing/feature_renaming.py
|
def transform(self, X, y=None):
'''
:X: list of dict
'''
return map_dict_list(
X,
key_func=lambda k, v: self.names[k.lower()],
if_func=lambda k, v: k.lower() in self.names)
|
def transform(self, X, y=None):
'''
:X: list of dict
'''
return map_dict_list(
X,
key_func=lambda k, v: self.names[k.lower()],
if_func=lambda k, v: k.lower() in self.names)
|
[
":",
"X",
":",
"list",
"of",
"dict"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/feature_renaming.py#L21-L28
|
[
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"return",
"map_dict_list",
"(",
"X",
",",
"key_func",
"=",
"lambda",
"k",
",",
"v",
":",
"self",
".",
"names",
"[",
"k",
".",
"lower",
"(",
")",
"]",
",",
"if_func",
"=",
"lambda",
"k",
",",
"v",
":",
"k",
".",
"lower",
"(",
")",
"in",
"self",
".",
"names",
")"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
format_price_commas
|
Formats prices, rounding (i.e. to the nearest whole number of pounds) with commas
|
littlefish/util.py
|
def format_price_commas(price):
"""
Formats prices, rounding (i.e. to the nearest whole number of pounds) with commas
"""
if price is None:
return None
if price >= 0:
return jinja2.Markup('£{:,.2f}'.format(price))
else:
return jinja2.Markup('-£{:,.2f}'.format(-price))
|
def format_price_commas(price):
"""
Formats prices, rounding (i.e. to the nearest whole number of pounds) with commas
"""
if price is None:
return None
if price >= 0:
return jinja2.Markup('£{:,.2f}'.format(price))
else:
return jinja2.Markup('-£{:,.2f}'.format(-price))
|
[
"Formats",
"prices",
"rounding",
"(",
"i",
".",
"e",
".",
"to",
"the",
"nearest",
"whole",
"number",
"of",
"pounds",
")",
"with",
"commas"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/util.py#L166-L175
|
[
"def",
"format_price_commas",
"(",
"price",
")",
":",
"if",
"price",
"is",
"None",
":",
"return",
"None",
"if",
"price",
">=",
"0",
":",
"return",
"jinja2",
".",
"Markup",
"(",
"'£{:,.2f}'",
".",
"format",
"(",
"price",
")",
")",
"else",
":",
"return",
"jinja2",
".",
"Markup",
"(",
"'-£{:,.2f}'",
".",
"format",
"(",
"-",
"price",
")",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
format_multiline_html
|
Turns a string like 'a\nb\nc' into 'a<br>b<br>c' and marks as Markup
Note: Will remove all \r characters from output (if present)
|
littlefish/util.py
|
def format_multiline_html(text):
"""
Turns a string like 'a\nb\nc' into 'a<br>b<br>c' and marks as Markup
Note: Will remove all \r characters from output (if present)
"""
if text is None:
return None
if '\n' not in text:
return text.replace('\r', '')
parts = text.replace('\r', '').split('\n')
out = flask.Markup()
for part in parts:
if out:
out += flask.Markup('<br>')
out += flask.escape(part)
return out
|
def format_multiline_html(text):
"""
Turns a string like 'a\nb\nc' into 'a<br>b<br>c' and marks as Markup
Note: Will remove all \r characters from output (if present)
"""
if text is None:
return None
if '\n' not in text:
return text.replace('\r', '')
parts = text.replace('\r', '').split('\n')
out = flask.Markup()
for part in parts:
if out:
out += flask.Markup('<br>')
out += flask.escape(part)
return out
|
[
"Turns",
"a",
"string",
"like",
"a",
"\\",
"nb",
"\\",
"nc",
"into",
"a<br",
">",
"b<br",
">",
"c",
"and",
"marks",
"as",
"Markup"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/util.py#L196-L214
|
[
"def",
"format_multiline_html",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"None",
"if",
"'\\n'",
"not",
"in",
"text",
":",
"return",
"text",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"parts",
"=",
"text",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
".",
"split",
"(",
"'\\n'",
")",
"out",
"=",
"flask",
".",
"Markup",
"(",
")",
"for",
"part",
"in",
"parts",
":",
"if",
"out",
":",
"out",
"+=",
"flask",
".",
"Markup",
"(",
"'<br>'",
")",
"out",
"+=",
"flask",
".",
"escape",
"(",
"part",
")",
"return",
"out"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
ensure_dir
|
Ensure that a needed directory exists, creating it if it doesn't
|
littlefish/util.py
|
def ensure_dir(path):
"""Ensure that a needed directory exists, creating it if it doesn't"""
try:
log.info('Ensuring directory exists: %s' % path)
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
|
def ensure_dir(path):
"""Ensure that a needed directory exists, creating it if it doesn't"""
try:
log.info('Ensuring directory exists: %s' % path)
os.makedirs(path)
except OSError:
if not os.path.isdir(path):
raise
|
[
"Ensure",
"that",
"a",
"needed",
"directory",
"exists",
"creating",
"it",
"if",
"it",
"doesn",
"t"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/util.py#L267-L274
|
[
"def",
"ensure_dir",
"(",
"path",
")",
":",
"try",
":",
"log",
".",
"info",
"(",
"'Ensuring directory exists: %s'",
"%",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
make_csv_response
|
:param csv_data: A string with the contents of a csv file in it
:param filename: The filename that the file will be saved as when it is downloaded by the user
:return: The response to return to the web connection
|
littlefish/util.py
|
def make_csv_response(csv_data, filename):
"""
:param csv_data: A string with the contents of a csv file in it
:param filename: The filename that the file will be saved as when it is downloaded by the user
:return: The response to return to the web connection
"""
resp = make_response(csv_data)
resp.headers['Content-Type'] = 'application/octet-stream'
resp.headers['Content-Disposition'] = 'attachment; filename=%s' % filename
return resp
|
def make_csv_response(csv_data, filename):
"""
:param csv_data: A string with the contents of a csv file in it
:param filename: The filename that the file will be saved as when it is downloaded by the user
:return: The response to return to the web connection
"""
resp = make_response(csv_data)
resp.headers['Content-Type'] = 'application/octet-stream'
resp.headers['Content-Disposition'] = 'attachment; filename=%s' % filename
return resp
|
[
":",
"param",
"csv_data",
":",
"A",
"string",
"with",
"the",
"contents",
"of",
"a",
"csv",
"file",
"in",
"it",
":",
"param",
"filename",
":",
"The",
"filename",
"that",
"the",
"file",
"will",
"be",
"saved",
"as",
"when",
"it",
"is",
"downloaded",
"by",
"the",
"user",
":",
"return",
":",
"The",
"response",
"to",
"return",
"to",
"the",
"web",
"connection"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/util.py#L277-L287
|
[
"def",
"make_csv_response",
"(",
"csv_data",
",",
"filename",
")",
":",
"resp",
"=",
"make_response",
"(",
"csv_data",
")",
"resp",
".",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/octet-stream'",
"resp",
".",
"headers",
"[",
"'Content-Disposition'",
"]",
"=",
"'attachment; filename=%s'",
"%",
"filename",
"return",
"resp"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
to_base62
|
Converts a number to base 62
:param n: The number to convert
:return: Base 62 representation of number (string)
|
littlefish/util.py
|
def to_base62(n):
"""
Converts a number to base 62
:param n: The number to convert
:return: Base 62 representation of number (string)
"""
remainder = n % 62
result = BASE62_MAP[remainder]
num = n // 62
while num > 0:
remainder = num % 62
result = '%s%s' % (BASE62_MAP[remainder], result)
num = num // 62
return result
|
def to_base62(n):
"""
Converts a number to base 62
:param n: The number to convert
:return: Base 62 representation of number (string)
"""
remainder = n % 62
result = BASE62_MAP[remainder]
num = n // 62
while num > 0:
remainder = num % 62
result = '%s%s' % (BASE62_MAP[remainder], result)
num = num // 62
return result
|
[
"Converts",
"a",
"number",
"to",
"base",
"62",
":",
"param",
"n",
":",
"The",
"number",
"to",
"convert",
":",
"return",
":",
"Base",
"62",
"representation",
"of",
"number",
"(",
"string",
")"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/util.py#L324-L339
|
[
"def",
"to_base62",
"(",
"n",
")",
":",
"remainder",
"=",
"n",
"%",
"62",
"result",
"=",
"BASE62_MAP",
"[",
"remainder",
"]",
"num",
"=",
"n",
"//",
"62",
"while",
"num",
">",
"0",
":",
"remainder",
"=",
"num",
"%",
"62",
"result",
"=",
"'%s%s'",
"%",
"(",
"BASE62_MAP",
"[",
"remainder",
"]",
",",
"result",
")",
"num",
"=",
"num",
"//",
"62",
"return",
"result"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
from_base62
|
Convert a base62 String back into a number
:param s: The base62 encoded String
:return: The number encoded in the String (integer)
|
littlefish/util.py
|
def from_base62(s):
"""
Convert a base62 String back into a number
:param s: The base62 encoded String
:return: The number encoded in the String (integer)
"""
result = 0
for c in s:
if c not in BASE62_MAP:
raise Exception('Invalid base64 string: %s' % s)
result = result * 62 + BASE62_MAP.index(c)
return result
|
def from_base62(s):
"""
Convert a base62 String back into a number
:param s: The base62 encoded String
:return: The number encoded in the String (integer)
"""
result = 0
for c in s:
if c not in BASE62_MAP:
raise Exception('Invalid base64 string: %s' % s)
result = result * 62 + BASE62_MAP.index(c)
return result
|
[
"Convert",
"a",
"base62",
"String",
"back",
"into",
"a",
"number",
":",
"param",
"s",
":",
"The",
"base62",
"encoded",
"String",
":",
"return",
":",
"The",
"number",
"encoded",
"in",
"the",
"String",
"(",
"integer",
")"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/util.py#L342-L356
|
[
"def",
"from_base62",
"(",
"s",
")",
":",
"result",
"=",
"0",
"for",
"c",
"in",
"s",
":",
"if",
"c",
"not",
"in",
"BASE62_MAP",
":",
"raise",
"Exception",
"(",
"'Invalid base64 string: %s'",
"%",
"s",
")",
"result",
"=",
"result",
"*",
"62",
"+",
"BASE62_MAP",
".",
"index",
"(",
"c",
")",
"return",
"result"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
AzureStorageBroker.list_dataset_uris
|
Return list containing URIs with base URI.
|
dtool_azure/storagebroker.py
|
def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
storage_account_name = generous_parse_uri(base_uri).netloc
blobservice = get_blob_service(storage_account_name, config_path)
containers = blobservice.list_containers(include_metadata=True)
uri_list = []
for c in containers:
admin_metadata = c.metadata
uri = cls.generate_uri(
admin_metadata['name'],
admin_metadata['uuid'],
base_uri
)
uri_list.append(uri)
return uri_list
|
def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
storage_account_name = generous_parse_uri(base_uri).netloc
blobservice = get_blob_service(storage_account_name, config_path)
containers = blobservice.list_containers(include_metadata=True)
uri_list = []
for c in containers:
admin_metadata = c.metadata
uri = cls.generate_uri(
admin_metadata['name'],
admin_metadata['uuid'],
base_uri
)
uri_list.append(uri)
return uri_list
|
[
"Return",
"list",
"containing",
"URIs",
"with",
"base",
"URI",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L187-L204
|
[
"def",
"list_dataset_uris",
"(",
"cls",
",",
"base_uri",
",",
"config_path",
")",
":",
"storage_account_name",
"=",
"generous_parse_uri",
"(",
"base_uri",
")",
".",
"netloc",
"blobservice",
"=",
"get_blob_service",
"(",
"storage_account_name",
",",
"config_path",
")",
"containers",
"=",
"blobservice",
".",
"list_containers",
"(",
"include_metadata",
"=",
"True",
")",
"uri_list",
"=",
"[",
"]",
"for",
"c",
"in",
"containers",
":",
"admin_metadata",
"=",
"c",
".",
"metadata",
"uri",
"=",
"cls",
".",
"generate_uri",
"(",
"admin_metadata",
"[",
"'name'",
"]",
",",
"admin_metadata",
"[",
"'uuid'",
"]",
",",
"base_uri",
")",
"uri_list",
".",
"append",
"(",
"uri",
")",
"return",
"uri_list"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
AzureStorageBroker.list_overlay_names
|
Return list of overlay names.
|
dtool_azure/storagebroker.py
|
def list_overlay_names(self):
"""Return list of overlay names."""
overlay_names = []
for blob in self._blobservice.list_blobs(
self.uuid,
prefix=self.overlays_key_prefix
):
overlay_file = blob.name.rsplit('/', 1)[-1]
overlay_name, ext = overlay_file.split('.')
overlay_names.append(overlay_name)
return overlay_names
|
def list_overlay_names(self):
"""Return list of overlay names."""
overlay_names = []
for blob in self._blobservice.list_blobs(
self.uuid,
prefix=self.overlays_key_prefix
):
overlay_file = blob.name.rsplit('/', 1)[-1]
overlay_name, ext = overlay_file.split('.')
overlay_names.append(overlay_name)
return overlay_names
|
[
"Return",
"list",
"of",
"overlay",
"names",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L264-L276
|
[
"def",
"list_overlay_names",
"(",
"self",
")",
":",
"overlay_names",
"=",
"[",
"]",
"for",
"blob",
"in",
"self",
".",
"_blobservice",
".",
"list_blobs",
"(",
"self",
".",
"uuid",
",",
"prefix",
"=",
"self",
".",
"overlays_key_prefix",
")",
":",
"overlay_file",
"=",
"blob",
".",
"name",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"overlay_name",
",",
"ext",
"=",
"overlay_file",
".",
"split",
"(",
"'.'",
")",
"overlay_names",
".",
"append",
"(",
"overlay_name",
")",
"return",
"overlay_names"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
AzureStorageBroker.add_item_metadata
|
Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
|
dtool_azure/storagebroker.py
|
def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
identifier = generate_identifier(handle)
metadata_blob_suffix = "{}.{}.json".format(identifier, key)
metadata_blob_name = self.fragments_key_prefix + metadata_blob_suffix
self._blobservice.create_blob_from_text(
self.uuid,
metadata_blob_name,
json.dumps(value)
)
self._blobservice.set_blob_metadata(
container_name=self.uuid,
blob_name=metadata_blob_name,
metadata={
"type": "item_metadata"
}
)
|
def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
identifier = generate_identifier(handle)
metadata_blob_suffix = "{}.{}.json".format(identifier, key)
metadata_blob_name = self.fragments_key_prefix + metadata_blob_suffix
self._blobservice.create_blob_from_text(
self.uuid,
metadata_blob_name,
json.dumps(value)
)
self._blobservice.set_blob_metadata(
container_name=self.uuid,
blob_name=metadata_blob_name,
metadata={
"type": "item_metadata"
}
)
|
[
"Store",
"the",
"given",
"key",
":",
"value",
"pair",
"for",
"the",
"item",
"associated",
"with",
"handle",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L300-L326
|
[
"def",
"add_item_metadata",
"(",
"self",
",",
"handle",
",",
"key",
",",
"value",
")",
":",
"identifier",
"=",
"generate_identifier",
"(",
"handle",
")",
"metadata_blob_suffix",
"=",
"\"{}.{}.json\"",
".",
"format",
"(",
"identifier",
",",
"key",
")",
"metadata_blob_name",
"=",
"self",
".",
"fragments_key_prefix",
"+",
"metadata_blob_suffix",
"self",
".",
"_blobservice",
".",
"create_blob_from_text",
"(",
"self",
".",
"uuid",
",",
"metadata_blob_name",
",",
"json",
".",
"dumps",
"(",
"value",
")",
")",
"self",
".",
"_blobservice",
".",
"set_blob_metadata",
"(",
"container_name",
"=",
"self",
".",
"uuid",
",",
"blob_name",
"=",
"metadata_blob_name",
",",
"metadata",
"=",
"{",
"\"type\"",
":",
"\"item_metadata\"",
"}",
")"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
AzureStorageBroker.put_text
|
Store the given text contents so that they are later retrievable by
the given key.
|
dtool_azure/storagebroker.py
|
def put_text(self, key, contents):
"""Store the given text contents so that they are later retrievable by
the given key."""
self._blobservice.create_blob_from_text(
self.uuid,
key,
contents
)
|
def put_text(self, key, contents):
"""Store the given text contents so that they are later retrievable by
the given key."""
self._blobservice.create_blob_from_text(
self.uuid,
key,
contents
)
|
[
"Store",
"the",
"given",
"text",
"contents",
"so",
"that",
"they",
"are",
"later",
"retrievable",
"by",
"the",
"given",
"key",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L340-L348
|
[
"def",
"put_text",
"(",
"self",
",",
"key",
",",
"contents",
")",
":",
"self",
".",
"_blobservice",
".",
"create_blob_from_text",
"(",
"self",
".",
"uuid",
",",
"key",
",",
"contents",
")"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
AzureStorageBroker.get_item_abspath
|
Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
|
dtool_azure/storagebroker.py
|
def get_item_abspath(self, identifier):
"""Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
"""
admin_metadata = self.get_admin_metadata()
uuid = admin_metadata["uuid"]
# Create directory for the specific dataset.
dataset_cache_abspath = os.path.join(self._azure_cache_abspath, uuid)
mkdir_parents(dataset_cache_abspath)
metadata = self._blobservice.get_blob_metadata(
self.uuid,
identifier
)
relpath = metadata['relpath']
_, ext = os.path.splitext(relpath)
local_item_abspath = os.path.join(
dataset_cache_abspath,
identifier + ext
)
if not os.path.isfile(local_item_abspath):
tmp_local_item_abspath = local_item_abspath + ".tmp"
self._blobservice.get_blob_to_path(
self.uuid,
identifier,
tmp_local_item_abspath
)
os.rename(tmp_local_item_abspath, local_item_abspath)
return local_item_abspath
|
def get_item_abspath(self, identifier):
"""Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
"""
admin_metadata = self.get_admin_metadata()
uuid = admin_metadata["uuid"]
# Create directory for the specific dataset.
dataset_cache_abspath = os.path.join(self._azure_cache_abspath, uuid)
mkdir_parents(dataset_cache_abspath)
metadata = self._blobservice.get_blob_metadata(
self.uuid,
identifier
)
relpath = metadata['relpath']
_, ext = os.path.splitext(relpath)
local_item_abspath = os.path.join(
dataset_cache_abspath,
identifier + ext
)
if not os.path.isfile(local_item_abspath):
tmp_local_item_abspath = local_item_abspath + ".tmp"
self._blobservice.get_blob_to_path(
self.uuid,
identifier,
tmp_local_item_abspath
)
os.rename(tmp_local_item_abspath, local_item_abspath)
return local_item_abspath
|
[
"Return",
"absolute",
"path",
"at",
"which",
"item",
"content",
"can",
"be",
"accessed",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L350-L384
|
[
"def",
"get_item_abspath",
"(",
"self",
",",
"identifier",
")",
":",
"admin_metadata",
"=",
"self",
".",
"get_admin_metadata",
"(",
")",
"uuid",
"=",
"admin_metadata",
"[",
"\"uuid\"",
"]",
"# Create directory for the specific dataset.",
"dataset_cache_abspath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_azure_cache_abspath",
",",
"uuid",
")",
"mkdir_parents",
"(",
"dataset_cache_abspath",
")",
"metadata",
"=",
"self",
".",
"_blobservice",
".",
"get_blob_metadata",
"(",
"self",
".",
"uuid",
",",
"identifier",
")",
"relpath",
"=",
"metadata",
"[",
"'relpath'",
"]",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"relpath",
")",
"local_item_abspath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataset_cache_abspath",
",",
"identifier",
"+",
"ext",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"local_item_abspath",
")",
":",
"tmp_local_item_abspath",
"=",
"local_item_abspath",
"+",
"\".tmp\"",
"self",
".",
"_blobservice",
".",
"get_blob_to_path",
"(",
"self",
".",
"uuid",
",",
"identifier",
",",
"tmp_local_item_abspath",
")",
"os",
".",
"rename",
"(",
"tmp_local_item_abspath",
",",
"local_item_abspath",
")",
"return",
"local_item_abspath"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
AzureStorageBroker.iter_item_handles
|
Return iterator over item handles.
|
dtool_azure/storagebroker.py
|
def iter_item_handles(self):
"""Return iterator over item handles."""
blob_generator = self._blobservice.list_blobs(
self.uuid,
include='metadata'
)
for blob in blob_generator:
if 'type' in blob.metadata:
if blob.metadata['type'] == 'item':
handle = blob.metadata['relpath']
yield handle
|
def iter_item_handles(self):
"""Return iterator over item handles."""
blob_generator = self._blobservice.list_blobs(
self.uuid,
include='metadata'
)
for blob in blob_generator:
if 'type' in blob.metadata:
if blob.metadata['type'] == 'item':
handle = blob.metadata['relpath']
yield handle
|
[
"Return",
"iterator",
"over",
"item",
"handles",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L387-L399
|
[
"def",
"iter_item_handles",
"(",
"self",
")",
":",
"blob_generator",
"=",
"self",
".",
"_blobservice",
".",
"list_blobs",
"(",
"self",
".",
"uuid",
",",
"include",
"=",
"'metadata'",
")",
"for",
"blob",
"in",
"blob_generator",
":",
"if",
"'type'",
"in",
"blob",
".",
"metadata",
":",
"if",
"blob",
".",
"metadata",
"[",
"'type'",
"]",
"==",
"'item'",
":",
"handle",
"=",
"blob",
".",
"metadata",
"[",
"'relpath'",
"]",
"yield",
"handle"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
AzureStorageBroker.get_item_metadata
|
Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata
|
dtool_azure/storagebroker.py
|
def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata
"""
metadata = {}
identifier = generate_identifier(handle)
prefix = self.fragments_key_prefix + '{}'.format(identifier)
blob_generator = self._blobservice.list_blobs(
self.uuid,
include='metadata',
prefix=prefix
)
for blob in blob_generator:
metadata_key = blob.name.split('.')[-2]
value_as_string = self.get_text(blob.name)
value = json.loads(value_as_string)
metadata[metadata_key] = value
return metadata
|
def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata
"""
metadata = {}
identifier = generate_identifier(handle)
prefix = self.fragments_key_prefix + '{}'.format(identifier)
blob_generator = self._blobservice.list_blobs(
self.uuid,
include='metadata',
prefix=prefix
)
for blob in blob_generator:
metadata_key = blob.name.split('.')[-2]
value_as_string = self.get_text(blob.name)
value = json.loads(value_as_string)
metadata[metadata_key] = value
return metadata
|
[
"Return",
"dictionary",
"containing",
"all",
"metadata",
"associated",
"with",
"handle",
"."
] |
jic-dtool/dtool-azure
|
python
|
https://github.com/jic-dtool/dtool-azure/blob/5f5f1faa040e047e619380faf437a74cdfa09737/dtool_azure/storagebroker.py#L440-L469
|
[
"def",
"get_item_metadata",
"(",
"self",
",",
"handle",
")",
":",
"metadata",
"=",
"{",
"}",
"identifier",
"=",
"generate_identifier",
"(",
"handle",
")",
"prefix",
"=",
"self",
".",
"fragments_key_prefix",
"+",
"'{}'",
".",
"format",
"(",
"identifier",
")",
"blob_generator",
"=",
"self",
".",
"_blobservice",
".",
"list_blobs",
"(",
"self",
".",
"uuid",
",",
"include",
"=",
"'metadata'",
",",
"prefix",
"=",
"prefix",
")",
"for",
"blob",
"in",
"blob_generator",
":",
"metadata_key",
"=",
"blob",
".",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"2",
"]",
"value_as_string",
"=",
"self",
".",
"get_text",
"(",
"blob",
".",
"name",
")",
"value",
"=",
"json",
".",
"loads",
"(",
"value_as_string",
")",
"metadata",
"[",
"metadata_key",
"]",
"=",
"value",
"return",
"metadata"
] |
5f5f1faa040e047e619380faf437a74cdfa09737
|
test
|
file_md5sum
|
:param filename: The filename of the file to process
:returns: The MD5 hash of the file
|
littlefish/fileutil.py
|
def file_md5sum(filename):
"""
:param filename: The filename of the file to process
:returns: The MD5 hash of the file
"""
hash_md5 = hashlib.md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(1024 * 4), b''):
hash_md5.update(chunk)
return hash_md5.hexdigest()
|
def file_md5sum(filename):
"""
:param filename: The filename of the file to process
:returns: The MD5 hash of the file
"""
hash_md5 = hashlib.md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(1024 * 4), b''):
hash_md5.update(chunk)
return hash_md5.hexdigest()
|
[
":",
"param",
"filename",
":",
"The",
"filename",
"of",
"the",
"file",
"to",
"process",
":",
"returns",
":",
"The",
"MD5",
"hash",
"of",
"the",
"file"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/fileutil.py#L28-L37
|
[
"def",
"file_md5sum",
"(",
"filename",
")",
":",
"hash_md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"1024",
"*",
"4",
")",
",",
"b''",
")",
":",
"hash_md5",
".",
"update",
"(",
"chunk",
")",
"return",
"hash_md5",
".",
"hexdigest",
"(",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
luhn_check
|
checks to make sure that the card passes a luhn mod-10 checksum
|
littlefish/validation.py
|
def luhn_check(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not ((count & 1) ^ oddeven):
digit *= 2
if digit > 9:
digit -= 9
sum += digit
return (sum % 10) == 0
|
def luhn_check(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not ((count & 1) ^ oddeven):
digit *= 2
if digit > 9:
digit -= 9
sum += digit
return (sum % 10) == 0
|
[
"checks",
"to",
"make",
"sure",
"that",
"the",
"card",
"passes",
"a",
"luhn",
"mod",
"-",
"10",
"checksum"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/validation.py#L22-L38
|
[
"def",
"luhn_check",
"(",
"card_number",
")",
":",
"sum",
"=",
"0",
"num_digits",
"=",
"len",
"(",
"card_number",
")",
"oddeven",
"=",
"num_digits",
"&",
"1",
"for",
"count",
"in",
"range",
"(",
"0",
",",
"num_digits",
")",
":",
"digit",
"=",
"int",
"(",
"card_number",
"[",
"count",
"]",
")",
"if",
"not",
"(",
"(",
"count",
"&",
"1",
")",
"^",
"oddeven",
")",
":",
"digit",
"*=",
"2",
"if",
"digit",
">",
"9",
":",
"digit",
"-=",
"9",
"sum",
"+=",
"digit",
"return",
"(",
"sum",
"%",
"10",
")",
"==",
"0"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
get_git_version
|
Return the git hash as a string.
Apparently someone got this from numpy's setup.py. It has since been
modified a few times.
|
setup.py
|
def get_git_version():
"""
Return the git hash as a string.
Apparently someone got this from numpy's setup.py. It has since been
modified a few times.
"""
# Return the git revision as a string
# copied from numpy setup.py
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
with open(os.devnull, 'w') as err_out:
out = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=err_out, # maybe debug later?
env=env).communicate()[0]
return out
try:
git_dir = os.path.dirname(os.path.realpath(__file__))
out = _minimal_ext_cmd(['git', '-C', git_dir, 'rev-parse', 'HEAD'])
GIT_REVISION = out.strip().decode('ascii')
except OSError:
GIT_REVISION = 'Unknown'
return GIT_REVISION
|
def get_git_version():
"""
Return the git hash as a string.
Apparently someone got this from numpy's setup.py. It has since been
modified a few times.
"""
# Return the git revision as a string
# copied from numpy setup.py
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LANG'] = 'C'
env['LC_ALL'] = 'C'
with open(os.devnull, 'w') as err_out:
out = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=err_out, # maybe debug later?
env=env).communicate()[0]
return out
try:
git_dir = os.path.dirname(os.path.realpath(__file__))
out = _minimal_ext_cmd(['git', '-C', git_dir, 'rev-parse', 'HEAD'])
GIT_REVISION = out.strip().decode('ascii')
except OSError:
GIT_REVISION = 'Unknown'
return GIT_REVISION
|
[
"Return",
"the",
"git",
"hash",
"as",
"a",
"string",
"."
] |
dwhswenson/autorelease
|
python
|
https://github.com/dwhswenson/autorelease/blob/339c32c3934e4751857f35aaa2bfffaaaf3b39c4/setup.py#L70-L104
|
[
"def",
"get_git_version",
"(",
")",
":",
"# Return the git revision as a string",
"# copied from numpy setup.py",
"def",
"_minimal_ext_cmd",
"(",
"cmd",
")",
":",
"# construct minimal environment",
"env",
"=",
"{",
"}",
"for",
"k",
"in",
"[",
"'SYSTEMROOT'",
",",
"'PATH'",
"]",
":",
"v",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"k",
")",
"if",
"v",
"is",
"not",
"None",
":",
"env",
"[",
"k",
"]",
"=",
"v",
"# LANGUAGE is used on win32",
"env",
"[",
"'LANGUAGE'",
"]",
"=",
"'C'",
"env",
"[",
"'LANG'",
"]",
"=",
"'C'",
"env",
"[",
"'LC_ALL'",
"]",
"=",
"'C'",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"'w'",
")",
"as",
"err_out",
":",
"out",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"err_out",
",",
"# maybe debug later?",
"env",
"=",
"env",
")",
".",
"communicate",
"(",
")",
"[",
"0",
"]",
"return",
"out",
"try",
":",
"git_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"out",
"=",
"_minimal_ext_cmd",
"(",
"[",
"'git'",
",",
"'-C'",
",",
"git_dir",
",",
"'rev-parse'",
",",
"'HEAD'",
"]",
")",
"GIT_REVISION",
"=",
"out",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"OSError",
":",
"GIT_REVISION",
"=",
"'Unknown'",
"return",
"GIT_REVISION"
] |
339c32c3934e4751857f35aaa2bfffaaaf3b39c4
|
test
|
load_hands
|
加载hand扩展插件
:return: 返回hand注册字典(单例)
:rtype: HandDict
|
source/mohand/hands.py
|
def load_hands():
"""
加载hand扩展插件
:return: 返回hand注册字典(单例)
:rtype: HandDict
"""
# 优先进行自带 hand 的注册加载
import mohand.decorator # noqa
# 注册hand插件
mgr = stevedore.ExtensionManager(
namespace=env.plugin_namespace,
invoke_on_load=True)
def register_hand(ext):
_hand = ext.obj.register()
if hasattr(hand, _hand.__name__):
raise HandDuplicationOfNameError(_hand.__name__)
hand[_hand.__name__] = _hand
_pkg, _ver = ext.obj.version()
env.version[_pkg] = _ver
try:
mgr.map(register_hand)
except stevedore.exception.NoMatches:
pass
return hand
|
def load_hands():
"""
加载hand扩展插件
:return: 返回hand注册字典(单例)
:rtype: HandDict
"""
# 优先进行自带 hand 的注册加载
import mohand.decorator # noqa
# 注册hand插件
mgr = stevedore.ExtensionManager(
namespace=env.plugin_namespace,
invoke_on_load=True)
def register_hand(ext):
_hand = ext.obj.register()
if hasattr(hand, _hand.__name__):
raise HandDuplicationOfNameError(_hand.__name__)
hand[_hand.__name__] = _hand
_pkg, _ver = ext.obj.version()
env.version[_pkg] = _ver
try:
mgr.map(register_hand)
except stevedore.exception.NoMatches:
pass
return hand
|
[
"加载hand扩展插件"
] |
littlemo/mohand
|
python
|
https://github.com/littlemo/mohand/blob/9bd4591e457d594f2ce3a0c089ef28d3b4e027e8/source/mohand/hands.py#L50-L78
|
[
"def",
"load_hands",
"(",
")",
":",
"# 优先进行自带 hand 的注册加载",
"import",
"mohand",
".",
"decorator",
"# noqa",
"# 注册hand插件",
"mgr",
"=",
"stevedore",
".",
"ExtensionManager",
"(",
"namespace",
"=",
"env",
".",
"plugin_namespace",
",",
"invoke_on_load",
"=",
"True",
")",
"def",
"register_hand",
"(",
"ext",
")",
":",
"_hand",
"=",
"ext",
".",
"obj",
".",
"register",
"(",
")",
"if",
"hasattr",
"(",
"hand",
",",
"_hand",
".",
"__name__",
")",
":",
"raise",
"HandDuplicationOfNameError",
"(",
"_hand",
".",
"__name__",
")",
"hand",
"[",
"_hand",
".",
"__name__",
"]",
"=",
"_hand",
"_pkg",
",",
"_ver",
"=",
"ext",
".",
"obj",
".",
"version",
"(",
")",
"env",
".",
"version",
"[",
"_pkg",
"]",
"=",
"_ver",
"try",
":",
"mgr",
".",
"map",
"(",
"register_hand",
")",
"except",
"stevedore",
".",
"exception",
".",
"NoMatches",
":",
"pass",
"return",
"hand"
] |
9bd4591e457d594f2ce3a0c089ef28d3b4e027e8
|
test
|
StandardScalerByLabel.partial_fit
|
:X: {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
:y: Healthy 'h' or 'sick_name'
|
sklearn_utils/preprocessing/standard_scale_by_label.py
|
def partial_fit(self, X, y):
"""
:X: {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
:y: Healthy 'h' or 'sick_name'
"""
X, y = filter_by_label(X, y, self.reference_label)
super().partial_fit(X, y)
return self
|
def partial_fit(self, X, y):
"""
:X: {array-like, sparse matrix}, shape [n_samples, n_features]
The data used to compute the mean and standard deviation
used for later scaling along the features axis.
:y: Healthy 'h' or 'sick_name'
"""
X, y = filter_by_label(X, y, self.reference_label)
super().partial_fit(X, y)
return self
|
[
":",
"X",
":",
"{",
"array",
"-",
"like",
"sparse",
"matrix",
"}",
"shape",
"[",
"n_samples",
"n_features",
"]",
"The",
"data",
"used",
"to",
"compute",
"the",
"mean",
"and",
"standard",
"deviation",
"used",
"for",
"later",
"scaling",
"along",
"the",
"features",
"axis",
".",
":",
"y",
":",
"Healthy",
"h",
"or",
"sick_name"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/standard_scale_by_label.py#L15-L24
|
[
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"X",
",",
"y",
"=",
"filter_by_label",
"(",
"X",
",",
"y",
",",
"self",
".",
"reference_label",
")",
"super",
"(",
")",
".",
"partial_fit",
"(",
"X",
",",
"y",
")",
"return",
"self"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
ModuleLoader.load_module
|
Loads a module's code and sets the module's expected hidden
variables. For more information on these variables and what they
are for, please see PEP302.
:param module_name: the full name of the module to load
|
pynsive/plugin/loader.py
|
def load_module(self, module_name):
"""
Loads a module's code and sets the module's expected hidden
variables. For more information on these variables and what they
are for, please see PEP302.
:param module_name: the full name of the module to load
"""
if module_name != self.module_name:
raise LoaderError(
'Requesting a module that the loader is unaware of.')
if module_name in sys.modules:
return sys.modules[module_name]
module = self.load_module_py_path(module_name, self.load_target)
if self.is_pkg:
module.__path__ = [self.module_path]
module.__package__ = module_name
else:
module.__package__ = module_name.rpartition('.')[0]
sys.modules[module_name] = module
return module
|
def load_module(self, module_name):
"""
Loads a module's code and sets the module's expected hidden
variables. For more information on these variables and what they
are for, please see PEP302.
:param module_name: the full name of the module to load
"""
if module_name != self.module_name:
raise LoaderError(
'Requesting a module that the loader is unaware of.')
if module_name in sys.modules:
return sys.modules[module_name]
module = self.load_module_py_path(module_name, self.load_target)
if self.is_pkg:
module.__path__ = [self.module_path]
module.__package__ = module_name
else:
module.__package__ = module_name.rpartition('.')[0]
sys.modules[module_name] = module
return module
|
[
"Loads",
"a",
"module",
"s",
"code",
"and",
"sets",
"the",
"module",
"s",
"expected",
"hidden",
"variables",
".",
"For",
"more",
"information",
"on",
"these",
"variables",
"and",
"what",
"they",
"are",
"for",
"please",
"see",
"PEP302",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/plugin/loader.py#L52-L75
|
[
"def",
"load_module",
"(",
"self",
",",
"module_name",
")",
":",
"if",
"module_name",
"!=",
"self",
".",
"module_name",
":",
"raise",
"LoaderError",
"(",
"'Requesting a module that the loader is unaware of.'",
")",
"if",
"module_name",
"in",
"sys",
".",
"modules",
":",
"return",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"module",
"=",
"self",
".",
"load_module_py_path",
"(",
"module_name",
",",
"self",
".",
"load_target",
")",
"if",
"self",
".",
"is_pkg",
":",
"module",
".",
"__path__",
"=",
"[",
"self",
".",
"module_path",
"]",
"module",
".",
"__package__",
"=",
"module_name",
"else",
":",
"module",
".",
"__package__",
"=",
"module_name",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"0",
"]",
"sys",
".",
"modules",
"[",
"module_name",
"]",
"=",
"module",
"return",
"module"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
ModuleFinder.add_path
|
Adds a path to search through when attempting to look up a module.
:param path: the path the add to the list of searchable paths
|
pynsive/plugin/loader.py
|
def add_path(self, path):
"""
Adds a path to search through when attempting to look up a module.
:param path: the path the add to the list of searchable paths
"""
if path not in self.paths:
self.paths.append(path)
|
def add_path(self, path):
"""
Adds a path to search through when attempting to look up a module.
:param path: the path the add to the list of searchable paths
"""
if path not in self.paths:
self.paths.append(path)
|
[
"Adds",
"a",
"path",
"to",
"search",
"through",
"when",
"attempting",
"to",
"look",
"up",
"a",
"module",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/plugin/loader.py#L93-L100
|
[
"def",
"add_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"path",
"not",
"in",
"self",
".",
"paths",
":",
"self",
".",
"paths",
".",
"append",
"(",
"path",
")"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
ModuleFinder.find_module
|
Searches the paths for the required module.
:param module_name: the full name of the module to find
:param path: set to None when the module in being searched for is a
top-level module - otherwise this is set to
package.__path__ for submodules and subpackages (unused)
|
pynsive/plugin/loader.py
|
def find_module(self, module_name, path=None):
"""
Searches the paths for the required module.
:param module_name: the full name of the module to find
:param path: set to None when the module in being searched for is a
top-level module - otherwise this is set to
package.__path__ for submodules and subpackages (unused)
"""
module_path = os.path.join(*module_name.split(MODULE_PATH_SEP))
for search_root in self.paths:
target_path = os.path.join(search_root, module_path)
is_pkg = False
# If the target references a directory, try to load it as
# a module by referencing the __init__.py file, otherwise
# append .py and attempt to resolve it.
if os.path.isdir(target_path):
target_file = os.path.join(target_path, '__init__.py')
is_pkg = True
else:
target_file = '{}.py'.format(target_path)
if os.path.exists(target_file):
return ModuleLoader(
target_path, module_name, target_file, is_pkg)
return None
|
def find_module(self, module_name, path=None):
"""
Searches the paths for the required module.
:param module_name: the full name of the module to find
:param path: set to None when the module in being searched for is a
top-level module - otherwise this is set to
package.__path__ for submodules and subpackages (unused)
"""
module_path = os.path.join(*module_name.split(MODULE_PATH_SEP))
for search_root in self.paths:
target_path = os.path.join(search_root, module_path)
is_pkg = False
# If the target references a directory, try to load it as
# a module by referencing the __init__.py file, otherwise
# append .py and attempt to resolve it.
if os.path.isdir(target_path):
target_file = os.path.join(target_path, '__init__.py')
is_pkg = True
else:
target_file = '{}.py'.format(target_path)
if os.path.exists(target_file):
return ModuleLoader(
target_path, module_name, target_file, is_pkg)
return None
|
[
"Searches",
"the",
"paths",
"for",
"the",
"required",
"module",
"."
] |
zinic/pynsive
|
python
|
https://github.com/zinic/pynsive/blob/15bc8b35a91be5817979eb327427b6235b1b411e/pynsive/plugin/loader.py#L102-L129
|
[
"def",
"find_module",
"(",
"self",
",",
"module_name",
",",
"path",
"=",
"None",
")",
":",
"module_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"module_name",
".",
"split",
"(",
"MODULE_PATH_SEP",
")",
")",
"for",
"search_root",
"in",
"self",
".",
"paths",
":",
"target_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"search_root",
",",
"module_path",
")",
"is_pkg",
"=",
"False",
"# If the target references a directory, try to load it as",
"# a module by referencing the __init__.py file, otherwise",
"# append .py and attempt to resolve it.",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"target_path",
")",
":",
"target_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_path",
",",
"'__init__.py'",
")",
"is_pkg",
"=",
"True",
"else",
":",
"target_file",
"=",
"'{}.py'",
".",
"format",
"(",
"target_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"target_file",
")",
":",
"return",
"ModuleLoader",
"(",
"target_path",
",",
"module_name",
",",
"target_file",
",",
"is_pkg",
")",
"return",
"None"
] |
15bc8b35a91be5817979eb327427b6235b1b411e
|
test
|
tag_to_text
|
:param tag: Beautiful soup tag
:return: Flattened text
|
littlefish/htmlutil.py
|
def tag_to_text(tag):
"""
:param tag: Beautiful soup tag
:return: Flattened text
"""
out = []
for item in tag.contents:
# If it has a name, it is a tag
if item.name:
out.append(tag_to_text(item))
else:
# Just text!
out.append(item)
return ' '.join(out)
|
def tag_to_text(tag):
"""
:param tag: Beautiful soup tag
:return: Flattened text
"""
out = []
for item in tag.contents:
# If it has a name, it is a tag
if item.name:
out.append(tag_to_text(item))
else:
# Just text!
out.append(item)
return ' '.join(out)
|
[
":",
"param",
"tag",
":",
"Beautiful",
"soup",
"tag",
":",
"return",
":",
"Flattened",
"text"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/htmlutil.py#L23-L37
|
[
"def",
"tag_to_text",
"(",
"tag",
")",
":",
"out",
"=",
"[",
"]",
"for",
"item",
"in",
"tag",
".",
"contents",
":",
"# If it has a name, it is a tag",
"if",
"item",
".",
"name",
":",
"out",
".",
"append",
"(",
"tag_to_text",
"(",
"item",
")",
")",
"else",
":",
"# Just text!",
"out",
".",
"append",
"(",
"item",
")",
"return",
"' '",
".",
"join",
"(",
"out",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
split_line
|
This is designed to work with prettified output from Beautiful Soup which indents with a single space.
:param line: The line to split
:param min_line_length: The minimum desired line length
:param max_line_length: The maximum desired line length
:return: A list of lines
|
littlefish/htmlutil.py
|
def split_line(line, min_line_length=30, max_line_length=100):
"""
This is designed to work with prettified output from Beautiful Soup which indents with a single space.
:param line: The line to split
:param min_line_length: The minimum desired line length
:param max_line_length: The maximum desired line length
:return: A list of lines
"""
if len(line) <= max_line_length:
# No need to split!
return [line]
# First work out the indentation on the beginning of the line
indent = 0
while line[indent] == ' ' and indent < len(line):
indent += 1
# Try to split the line
# Start looking for a space at character max_line_length working backwards
i = max_line_length
split_point = None
while i > min_line_length:
if line[i] == ' ':
split_point = i
break
i -= 1
if split_point is None:
# We didn't find a split point - search beyond the end of the line
i = max_line_length + 1
while i < len(line):
if line[i] == ' ':
split_point = i
break
i += 1
if split_point is None:
# There is nowhere to split the line!
return [line]
else:
# Split it!
line1 = line[:split_point]
line2 = ' ' * indent + line[split_point + 1:]
return [line1] + split_line(line2, min_line_length, max_line_length)
|
def split_line(line, min_line_length=30, max_line_length=100):
"""
This is designed to work with prettified output from Beautiful Soup which indents with a single space.
:param line: The line to split
:param min_line_length: The minimum desired line length
:param max_line_length: The maximum desired line length
:return: A list of lines
"""
if len(line) <= max_line_length:
# No need to split!
return [line]
# First work out the indentation on the beginning of the line
indent = 0
while line[indent] == ' ' and indent < len(line):
indent += 1
# Try to split the line
# Start looking for a space at character max_line_length working backwards
i = max_line_length
split_point = None
while i > min_line_length:
if line[i] == ' ':
split_point = i
break
i -= 1
if split_point is None:
# We didn't find a split point - search beyond the end of the line
i = max_line_length + 1
while i < len(line):
if line[i] == ' ':
split_point = i
break
i += 1
if split_point is None:
# There is nowhere to split the line!
return [line]
else:
# Split it!
line1 = line[:split_point]
line2 = ' ' * indent + line[split_point + 1:]
return [line1] + split_line(line2, min_line_length, max_line_length)
|
[
"This",
"is",
"designed",
"to",
"work",
"with",
"prettified",
"output",
"from",
"Beautiful",
"Soup",
"which",
"indents",
"with",
"a",
"single",
"space",
"."
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/htmlutil.py#L40-L85
|
[
"def",
"split_line",
"(",
"line",
",",
"min_line_length",
"=",
"30",
",",
"max_line_length",
"=",
"100",
")",
":",
"if",
"len",
"(",
"line",
")",
"<=",
"max_line_length",
":",
"# No need to split!",
"return",
"[",
"line",
"]",
"# First work out the indentation on the beginning of the line",
"indent",
"=",
"0",
"while",
"line",
"[",
"indent",
"]",
"==",
"' '",
"and",
"indent",
"<",
"len",
"(",
"line",
")",
":",
"indent",
"+=",
"1",
"# Try to split the line",
"# Start looking for a space at character max_line_length working backwards",
"i",
"=",
"max_line_length",
"split_point",
"=",
"None",
"while",
"i",
">",
"min_line_length",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"' '",
":",
"split_point",
"=",
"i",
"break",
"i",
"-=",
"1",
"if",
"split_point",
"is",
"None",
":",
"# We didn't find a split point - search beyond the end of the line",
"i",
"=",
"max_line_length",
"+",
"1",
"while",
"i",
"<",
"len",
"(",
"line",
")",
":",
"if",
"line",
"[",
"i",
"]",
"==",
"' '",
":",
"split_point",
"=",
"i",
"break",
"i",
"+=",
"1",
"if",
"split_point",
"is",
"None",
":",
"# There is nowhere to split the line!",
"return",
"[",
"line",
"]",
"else",
":",
"# Split it!",
"line1",
"=",
"line",
"[",
":",
"split_point",
"]",
"line2",
"=",
"' '",
"*",
"indent",
"+",
"line",
"[",
"split_point",
"+",
"1",
":",
"]",
"return",
"[",
"line1",
"]",
"+",
"split_line",
"(",
"line2",
",",
"min_line_length",
",",
"max_line_length",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
pretty_print
|
Pretty print HTML, splitting it into lines of a reasonable length (if possible).
This probably needs a whole lot more testing!
:param html: The HTML to format
:param max_line_length: The desired maximum line length. Will not be strictly adhered to
:param min_line_length: The desired minimum line length
:param tab_width: Essentially, the tabs that indent the code will be treated as this many
spaces when counting the length of each line
:return: Beautifully formatted HTML
|
littlefish/htmlutil.py
|
def pretty_print(html, max_line_length=110, tab_width=4):
"""
Pretty print HTML, splitting it into lines of a reasonable length (if possible).
This probably needs a whole lot more testing!
:param html: The HTML to format
:param max_line_length: The desired maximum line length. Will not be strictly adhered to
:param min_line_length: The desired minimum line length
:param tab_width: Essentially, the tabs that indent the code will be treated as this many
spaces when counting the length of each line
:return: Beautifully formatted HTML
"""
if tab_width < 2:
raise ValueError('tab_width must be at least 2 (or bad things would happen!)')
# Double curly brackets to avoid problems with .format()
html = html.replace('{', '{{').replace('}', '}}')
soup = BeautifulSoup(html, 'lxml')
soup.html.unwrap()
soup.body.unwrap()
unformatted_tag_list = []
# Here we are taking the tags out of the content and replacing them with placeholders,
# and adding the tags to a list. I didn't come up with this...
for i, tag in enumerate(soup.find_all(INLINE_TAGS)):
unformatted_tag_list.append(str(tag))
tag.replace_with('{' + 'unformatted_tag_list[{0}]'.format(i) + '}')
# If we prettify this, there will still be some weird indentation going on, based on
# the original markup, so we need to convert it into a string again, and then parse
# it again
processed_html = str(soup)
soup2 = BeautifulSoup(processed_html, 'lxml')
soup2.html.unwrap()
soup2.body.unwrap()
# Prettify it, substitute in the unformatted tags
pretty_markup = soup2.prettify().format(unformatted_tag_list=unformatted_tag_list)
# Convert indendtations to a tab width of 4
pretty_markup = re.sub(r'^(\s+)', r'\1' * tab_width, pretty_markup, flags=re.MULTILINE)
# Final step - pass over the formatted html, convert the indentations into tabs and cut
# the lines to length
lines = pretty_markup.splitlines()
out = ''
for line in lines:
for line_part in split_line(line, max_line_length=max_line_length):
out += line_part
out += '\n'
# Final final step! Convert space indentations into tabs
return out.replace(' ' * tab_width, '\t')
|
def pretty_print(html, max_line_length=110, tab_width=4):
"""
Pretty print HTML, splitting it into lines of a reasonable length (if possible).
This probably needs a whole lot more testing!
:param html: The HTML to format
:param max_line_length: The desired maximum line length. Will not be strictly adhered to
:param min_line_length: The desired minimum line length
:param tab_width: Essentially, the tabs that indent the code will be treated as this many
spaces when counting the length of each line
:return: Beautifully formatted HTML
"""
if tab_width < 2:
raise ValueError('tab_width must be at least 2 (or bad things would happen!)')
# Double curly brackets to avoid problems with .format()
html = html.replace('{', '{{').replace('}', '}}')
soup = BeautifulSoup(html, 'lxml')
soup.html.unwrap()
soup.body.unwrap()
unformatted_tag_list = []
# Here we are taking the tags out of the content and replacing them with placeholders,
# and adding the tags to a list. I didn't come up with this...
for i, tag in enumerate(soup.find_all(INLINE_TAGS)):
unformatted_tag_list.append(str(tag))
tag.replace_with('{' + 'unformatted_tag_list[{0}]'.format(i) + '}')
# If we prettify this, there will still be some weird indentation going on, based on
# the original markup, so we need to convert it into a string again, and then parse
# it again
processed_html = str(soup)
soup2 = BeautifulSoup(processed_html, 'lxml')
soup2.html.unwrap()
soup2.body.unwrap()
# Prettify it, substitute in the unformatted tags
pretty_markup = soup2.prettify().format(unformatted_tag_list=unformatted_tag_list)
# Convert indendtations to a tab width of 4
pretty_markup = re.sub(r'^(\s+)', r'\1' * tab_width, pretty_markup, flags=re.MULTILINE)
# Final step - pass over the formatted html, convert the indentations into tabs and cut
# the lines to length
lines = pretty_markup.splitlines()
out = ''
for line in lines:
for line_part in split_line(line, max_line_length=max_line_length):
out += line_part
out += '\n'
# Final final step! Convert space indentations into tabs
return out.replace(' ' * tab_width, '\t')
|
[
"Pretty",
"print",
"HTML",
"splitting",
"it",
"into",
"lines",
"of",
"a",
"reasonable",
"length",
"(",
"if",
"possible",
")",
"."
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/htmlutil.py#L88-L143
|
[
"def",
"pretty_print",
"(",
"html",
",",
"max_line_length",
"=",
"110",
",",
"tab_width",
"=",
"4",
")",
":",
"if",
"tab_width",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"'tab_width must be at least 2 (or bad things would happen!)'",
")",
"# Double curly brackets to avoid problems with .format()",
"html",
"=",
"html",
".",
"replace",
"(",
"'{'",
",",
"'{{'",
")",
".",
"replace",
"(",
"'}'",
",",
"'}}'",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
",",
"'lxml'",
")",
"soup",
".",
"html",
".",
"unwrap",
"(",
")",
"soup",
".",
"body",
".",
"unwrap",
"(",
")",
"unformatted_tag_list",
"=",
"[",
"]",
"# Here we are taking the tags out of the content and replacing them with placeholders,",
"# and adding the tags to a list. I didn't come up with this...",
"for",
"i",
",",
"tag",
"in",
"enumerate",
"(",
"soup",
".",
"find_all",
"(",
"INLINE_TAGS",
")",
")",
":",
"unformatted_tag_list",
".",
"append",
"(",
"str",
"(",
"tag",
")",
")",
"tag",
".",
"replace_with",
"(",
"'{'",
"+",
"'unformatted_tag_list[{0}]'",
".",
"format",
"(",
"i",
")",
"+",
"'}'",
")",
"# If we prettify this, there will still be some weird indentation going on, based on",
"# the original markup, so we need to convert it into a string again, and then parse",
"# it again",
"processed_html",
"=",
"str",
"(",
"soup",
")",
"soup2",
"=",
"BeautifulSoup",
"(",
"processed_html",
",",
"'lxml'",
")",
"soup2",
".",
"html",
".",
"unwrap",
"(",
")",
"soup2",
".",
"body",
".",
"unwrap",
"(",
")",
"# Prettify it, substitute in the unformatted tags",
"pretty_markup",
"=",
"soup2",
".",
"prettify",
"(",
")",
".",
"format",
"(",
"unformatted_tag_list",
"=",
"unformatted_tag_list",
")",
"# Convert indendtations to a tab width of 4",
"pretty_markup",
"=",
"re",
".",
"sub",
"(",
"r'^(\\s+)'",
",",
"r'\\1'",
"*",
"tab_width",
",",
"pretty_markup",
",",
"flags",
"=",
"re",
".",
"MULTILINE",
")",
"# Final step - pass over the formatted html, convert the indentations into tabs and cut",
"# the lines to length",
"lines",
"=",
"pretty_markup",
".",
"splitlines",
"(",
")",
"out",
"=",
"''",
"for",
"line",
"in",
"lines",
":",
"for",
"line_part",
"in",
"split_line",
"(",
"line",
",",
"max_line_length",
"=",
"max_line_length",
")",
":",
"out",
"+=",
"line_part",
"out",
"+=",
"'\\n'",
"# Final final step! Convert space indentations into tabs",
"return",
"out",
".",
"replace",
"(",
"' '",
"*",
"tab_width",
",",
"'\\t'",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
FunctionalEnrichmentAnalysis.transform
|
:X: list of dict
:y: labels
|
sklearn_utils/preprocessing/functional_enrichment_analysis.py
|
def transform(self, X, y=None):
'''
:X: list of dict
:y: labels
'''
return [{
new_feature: self._fisher_pval(x, old_features)
for new_feature, old_features in self.feature_groups.items()
if len(set(x.keys()) & set(old_features))
} for x in X]
|
def transform(self, X, y=None):
'''
:X: list of dict
:y: labels
'''
return [{
new_feature: self._fisher_pval(x, old_features)
for new_feature, old_features in self.feature_groups.items()
if len(set(x.keys()) & set(old_features))
} for x in X]
|
[
":",
"X",
":",
"list",
"of",
"dict",
":",
"y",
":",
"labels"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/functional_enrichment_analysis.py#L35-L44
|
[
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"return",
"[",
"{",
"new_feature",
":",
"self",
".",
"_fisher_pval",
"(",
"x",
",",
"old_features",
")",
"for",
"new_feature",
",",
"old_features",
"in",
"self",
".",
"feature_groups",
".",
"items",
"(",
")",
"if",
"len",
"(",
"set",
"(",
"x",
".",
"keys",
"(",
")",
")",
"&",
"set",
"(",
"old_features",
")",
")",
"}",
"for",
"x",
"in",
"X",
"]"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
FunctionalEnrichmentAnalysis._filtered_values
|
:x: dict which contains feature names and values
:return: pairs of values which shows number of feature makes filter function true or false
|
sklearn_utils/preprocessing/functional_enrichment_analysis.py
|
def _filtered_values(self, x: dict, feature_set: list=None):
'''
:x: dict which contains feature names and values
:return: pairs of values which shows number of feature makes filter function true or false
'''
feature_set = feature_set or x
n = sum(self.filter_func(x[i]) for i in feature_set if i in x)
return [len(feature_set) - n, n]
|
def _filtered_values(self, x: dict, feature_set: list=None):
'''
:x: dict which contains feature names and values
:return: pairs of values which shows number of feature makes filter function true or false
'''
feature_set = feature_set or x
n = sum(self.filter_func(x[i]) for i in feature_set if i in x)
return [len(feature_set) - n, n]
|
[
":",
"x",
":",
"dict",
"which",
"contains",
"feature",
"names",
"and",
"values",
":",
"return",
":",
"pairs",
"of",
"values",
"which",
"shows",
"number",
"of",
"feature",
"makes",
"filter",
"function",
"true",
"or",
"false"
] |
MuhammedHasan/sklearn_utils
|
python
|
https://github.com/MuhammedHasan/sklearn_utils/blob/337c3b7a27f4921d12da496f66a2b83ef582b413/sklearn_utils/preprocessing/functional_enrichment_analysis.py#L46-L53
|
[
"def",
"_filtered_values",
"(",
"self",
",",
"x",
":",
"dict",
",",
"feature_set",
":",
"list",
"=",
"None",
")",
":",
"feature_set",
"=",
"feature_set",
"or",
"x",
"n",
"=",
"sum",
"(",
"self",
".",
"filter_func",
"(",
"x",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"feature_set",
"if",
"i",
"in",
"x",
")",
"return",
"[",
"len",
"(",
"feature_set",
")",
"-",
"n",
",",
"n",
"]"
] |
337c3b7a27f4921d12da496f66a2b83ef582b413
|
test
|
print_location
|
:param kwargs: Pass in the arguments to the function and they will be printed too!
|
littlefish/debugtools.py
|
def print_location(**kwargs):
"""
:param kwargs: Pass in the arguments to the function and they will be printed too!
"""
stack = inspect.stack()[1]
debug_print('{}:{} {}()'.format(stack[1], stack[2], stack[3]))
for k, v in kwargs.items():
lesser_debug_print('{} = {}'.format(k, v))
|
def print_location(**kwargs):
"""
:param kwargs: Pass in the arguments to the function and they will be printed too!
"""
stack = inspect.stack()[1]
debug_print('{}:{} {}()'.format(stack[1], stack[2], stack[3]))
for k, v in kwargs.items():
lesser_debug_print('{} = {}'.format(k, v))
|
[
":",
"param",
"kwargs",
":",
"Pass",
"in",
"the",
"arguments",
"to",
"the",
"function",
"and",
"they",
"will",
"be",
"printed",
"too!"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/debugtools.py#L59-L67
|
[
"def",
"print_location",
"(",
"*",
"*",
"kwargs",
")",
":",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"debug_print",
"(",
"'{}:{} {}()'",
".",
"format",
"(",
"stack",
"[",
"1",
"]",
",",
"stack",
"[",
"2",
"]",
",",
"stack",
"[",
"3",
"]",
")",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"lesser_debug_print",
"(",
"'{} = {}'",
".",
"format",
"(",
"k",
",",
"v",
")",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
remove_namespaces
|
Call this on an lxml.etree document to remove all namespaces
|
littlefish/xmlutil.py
|
def remove_namespaces(root):
"""Call this on an lxml.etree document to remove all namespaces"""
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'):
continue
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i + 1:]
objectify.deannotate(root, cleanup_namespaces=True)
|
def remove_namespaces(root):
"""Call this on an lxml.etree document to remove all namespaces"""
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'):
continue
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i + 1:]
objectify.deannotate(root, cleanup_namespaces=True)
|
[
"Call",
"this",
"on",
"an",
"lxml",
".",
"etree",
"document",
"to",
"remove",
"all",
"namespaces"
] |
stevelittlefish/littlefish
|
python
|
https://github.com/stevelittlefish/littlefish/blob/6deee7f81fab30716c743efe2e94e786c6e17016/littlefish/xmlutil.py#L14-L24
|
[
"def",
"remove_namespaces",
"(",
"root",
")",
":",
"for",
"elem",
"in",
"root",
".",
"getiterator",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"elem",
".",
"tag",
",",
"'find'",
")",
":",
"continue",
"i",
"=",
"elem",
".",
"tag",
".",
"find",
"(",
"'}'",
")",
"if",
"i",
">=",
"0",
":",
"elem",
".",
"tag",
"=",
"elem",
".",
"tag",
"[",
"i",
"+",
"1",
":",
"]",
"objectify",
".",
"deannotate",
"(",
"root",
",",
"cleanup_namespaces",
"=",
"True",
")"
] |
6deee7f81fab30716c743efe2e94e786c6e17016
|
test
|
VersionReleaseChecks.consistency
|
Checks that the versions are consistent
Parameters
----------
desired_version: str
optional; the version that all of these should match
include_package: bool
whether to check the special 'package' version for consistency
(default False)
strictness: str
|
autorelease/version_checks.py
|
def consistency(self, desired_version=None, include_package=False,
strictness=None):
"""Checks that the versions are consistent
Parameters
----------
desired_version: str
optional; the version that all of these should match
include_package: bool
whether to check the special 'package' version for consistency
(default False)
strictness: str
"""
keys_to_check = list(self.versions.keys())
if not include_package and 'package' in keys_to_check:
keys_to_check.remove('package')
if desired_version is None:
# if we have to guess, we trust setup.py
try:
desired_version = self.versions['setup.py']
except KeyError:
desired_version = self.versions[keys_to_check[0]]
if strictness is None:
strictness = self.strictness
desired = self._version(desired_version, strictness)
error_keys = []
for key in keys_to_check:
test = self._version(self.versions[key], strictness)
if test != desired:
error_keys += [key]
# make the error message
msg = ""
for key in error_keys:
msg += "Error: desired {d} != {v} ({k})\n".format(
d=str(desired),
v=str(self.versions[key]),
k=str(key)
)
return msg
|
def consistency(self, desired_version=None, include_package=False,
strictness=None):
"""Checks that the versions are consistent
Parameters
----------
desired_version: str
optional; the version that all of these should match
include_package: bool
whether to check the special 'package' version for consistency
(default False)
strictness: str
"""
keys_to_check = list(self.versions.keys())
if not include_package and 'package' in keys_to_check:
keys_to_check.remove('package')
if desired_version is None:
# if we have to guess, we trust setup.py
try:
desired_version = self.versions['setup.py']
except KeyError:
desired_version = self.versions[keys_to_check[0]]
if strictness is None:
strictness = self.strictness
desired = self._version(desired_version, strictness)
error_keys = []
for key in keys_to_check:
test = self._version(self.versions[key], strictness)
if test != desired:
error_keys += [key]
# make the error message
msg = ""
for key in error_keys:
msg += "Error: desired {d} != {v} ({k})\n".format(
d=str(desired),
v=str(self.versions[key]),
k=str(key)
)
return msg
|
[
"Checks",
"that",
"the",
"versions",
"are",
"consistent"
] |
dwhswenson/autorelease
|
python
|
https://github.com/dwhswenson/autorelease/blob/339c32c3934e4751857f35aaa2bfffaaaf3b39c4/autorelease/version_checks.py#L23-L66
|
[
"def",
"consistency",
"(",
"self",
",",
"desired_version",
"=",
"None",
",",
"include_package",
"=",
"False",
",",
"strictness",
"=",
"None",
")",
":",
"keys_to_check",
"=",
"list",
"(",
"self",
".",
"versions",
".",
"keys",
"(",
")",
")",
"if",
"not",
"include_package",
"and",
"'package'",
"in",
"keys_to_check",
":",
"keys_to_check",
".",
"remove",
"(",
"'package'",
")",
"if",
"desired_version",
"is",
"None",
":",
"# if we have to guess, we trust setup.py",
"try",
":",
"desired_version",
"=",
"self",
".",
"versions",
"[",
"'setup.py'",
"]",
"except",
"KeyError",
":",
"desired_version",
"=",
"self",
".",
"versions",
"[",
"keys_to_check",
"[",
"0",
"]",
"]",
"if",
"strictness",
"is",
"None",
":",
"strictness",
"=",
"self",
".",
"strictness",
"desired",
"=",
"self",
".",
"_version",
"(",
"desired_version",
",",
"strictness",
")",
"error_keys",
"=",
"[",
"]",
"for",
"key",
"in",
"keys_to_check",
":",
"test",
"=",
"self",
".",
"_version",
"(",
"self",
".",
"versions",
"[",
"key",
"]",
",",
"strictness",
")",
"if",
"test",
"!=",
"desired",
":",
"error_keys",
"+=",
"[",
"key",
"]",
"# make the error message",
"msg",
"=",
"\"\"",
"for",
"key",
"in",
"error_keys",
":",
"msg",
"+=",
"\"Error: desired {d} != {v} ({k})\\n\"",
".",
"format",
"(",
"d",
"=",
"str",
"(",
"desired",
")",
",",
"v",
"=",
"str",
"(",
"self",
".",
"versions",
"[",
"key",
"]",
")",
",",
"k",
"=",
"str",
"(",
"key",
")",
")",
"return",
"msg"
] |
339c32c3934e4751857f35aaa2bfffaaaf3b39c4
|
test
|
setup_is_release
|
Returns
-------
bool or None :
None if we can't tell
|
autorelease/root_dir_checks.py
|
def setup_is_release(setup, expected=True):
"""
Returns
-------
bool or None :
None if we can't tell
"""
try:
is_release = setup.IS_RELEASE
except AttributeError:
return None
else:
if is_release and expected:
return ""
elif not is_release and not expected:
return ""
else:
return ("Unexpected value of setup.py IS_RELEASE. Found "
+ str(is_release) + ".\n")
|
def setup_is_release(setup, expected=True):
"""
Returns
-------
bool or None :
None if we can't tell
"""
try:
is_release = setup.IS_RELEASE
except AttributeError:
return None
else:
if is_release and expected:
return ""
elif not is_release and not expected:
return ""
else:
return ("Unexpected value of setup.py IS_RELEASE. Found "
+ str(is_release) + ".\n")
|
[
"Returns",
"-------",
"bool",
"or",
"None",
":",
"None",
"if",
"we",
"can",
"t",
"tell"
] |
dwhswenson/autorelease
|
python
|
https://github.com/dwhswenson/autorelease/blob/339c32c3934e4751857f35aaa2bfffaaaf3b39c4/autorelease/root_dir_checks.py#L6-L24
|
[
"def",
"setup_is_release",
"(",
"setup",
",",
"expected",
"=",
"True",
")",
":",
"try",
":",
"is_release",
"=",
"setup",
".",
"IS_RELEASE",
"except",
"AttributeError",
":",
"return",
"None",
"else",
":",
"if",
"is_release",
"and",
"expected",
":",
"return",
"\"\"",
"elif",
"not",
"is_release",
"and",
"not",
"expected",
":",
"return",
"\"\"",
"else",
":",
"return",
"(",
"\"Unexpected value of setup.py IS_RELEASE. Found \"",
"+",
"str",
"(",
"is_release",
")",
"+",
"\".\\n\"",
")"
] |
339c32c3934e4751857f35aaa2bfffaaaf3b39c4
|
test
|
Rule.from_yaml
|
Creates a new instance of a rule in relation to the config file.
This updates the dictionary of the class with the added details, which
allows for flexibility in the configuation file.
Only called when parsing the default configuation file.
|
hook/model.py
|
def from_yaml(cls, **kwargs):
"""Creates a new instance of a rule in relation to the config file.
This updates the dictionary of the class with the added details, which
allows for flexibility in the configuation file.
Only called when parsing the default configuation file.
"""
ret = cls()
for k, v in kwargs.iteritems():
ret.__dict__[k] = v
return ret
|
def from_yaml(cls, **kwargs):
"""Creates a new instance of a rule in relation to the config file.
This updates the dictionary of the class with the added details, which
allows for flexibility in the configuation file.
Only called when parsing the default configuation file.
"""
ret = cls()
for k, v in kwargs.iteritems():
ret.__dict__[k] = v
return ret
|
[
"Creates",
"a",
"new",
"instance",
"of",
"a",
"rule",
"in",
"relation",
"to",
"the",
"config",
"file",
"."
] |
ssherar/hook
|
python
|
https://github.com/ssherar/hook/blob/54160df554d8b2ed65d762168e5808487e873ed9/hook/model.py#L26-L38
|
[
"def",
"from_yaml",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"cls",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"ret",
".",
"__dict__",
"[",
"k",
"]",
"=",
"v",
"return",
"ret"
] |
54160df554d8b2ed65d762168e5808487e873ed9
|
test
|
Rule.merge
|
Merges a dictionary into the Rule object.
|
hook/model.py
|
def merge(self, new_dict):
"""Merges a dictionary into the Rule object."""
actions = new_dict.pop("actions")
for action in actions:
self.add_action(action)
self.__dict__.update(new_dict)
|
def merge(self, new_dict):
"""Merges a dictionary into the Rule object."""
actions = new_dict.pop("actions")
for action in actions:
self.add_action(action)
self.__dict__.update(new_dict)
|
[
"Merges",
"a",
"dictionary",
"into",
"the",
"Rule",
"object",
"."
] |
ssherar/hook
|
python
|
https://github.com/ssherar/hook/blob/54160df554d8b2ed65d762168e5808487e873ed9/hook/model.py#L46-L52
|
[
"def",
"merge",
"(",
"self",
",",
"new_dict",
")",
":",
"actions",
"=",
"new_dict",
".",
"pop",
"(",
"\"actions\"",
")",
"for",
"action",
"in",
"actions",
":",
"self",
".",
"add_action",
"(",
"action",
")",
"self",
".",
"__dict__",
".",
"update",
"(",
"new_dict",
")"
] |
54160df554d8b2ed65d762168e5808487e873ed9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.