id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
246,300
zaturox/glin
glin/zmq/messages.py
MessageParser.scene_color
def scene_color(frames): """parse a scene.color message""" # "scene.color" <scene_id> <color> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get() if results.command != "scene.color": raise MessageParserError("Command is not 'scene.color'") return (results.scene_id, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]))
python
def scene_color(frames): """parse a scene.color message""" # "scene.color" <scene_id> <color> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").uint8_3("color").assert_end().get() if results.command != "scene.color": raise MessageParserError("Command is not 'scene.color'") return (results.scene_id, np.array([results.color[0]/255, results.color[1]/255, results.color[2]/255]))
[ "def", "scene_color", "(", "frames", ")", ":", "# \"scene.color\" <scene_id> <color>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "uint8_3", "(", "\"color\"", ")", ".", "assert_end", "(", ")", ".", "get", "(", ")", "if", "results", ".", "command", "!=", "\"scene.color\"", ":", "raise", "MessageParserError", "(", "\"Command is not 'scene.color'\"", ")", "return", "(", "results", ".", "scene_id", ",", "np", ".", "array", "(", "[", "results", ".", "color", "[", "0", "]", "/", "255", ",", "results", ".", "color", "[", "1", "]", "/", "255", ",", "results", ".", "color", "[", "2", "]", "/", "255", "]", ")", ")" ]
parse a scene.color message
[ "parse", "a", "scene", ".", "color", "message" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L136-L143
246,301
zaturox/glin
glin/zmq/messages.py
MessageParser.scene_config
def scene_config(frames): """parse a scene.config message""" # "scene.config" <scene_id> <config> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").string("config").assert_end().get() if results.command != "scene.config": raise MessageParserError("Command is not 'scene.config'") return (results.scene_id, results.config)
python
def scene_config(frames): """parse a scene.config message""" # "scene.config" <scene_id> <config> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").string("config").assert_end().get() if results.command != "scene.config": raise MessageParserError("Command is not 'scene.config'") return (results.scene_id, results.config)
[ "def", "scene_config", "(", "frames", ")", ":", "# \"scene.config\" <scene_id> <config>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "string", "(", "\"config\"", ")", ".", "assert_end", "(", ")", ".", "get", "(", ")", "if", "results", ".", "command", "!=", "\"scene.config\"", ":", "raise", "MessageParserError", "(", "\"Command is not 'scene.config'\"", ")", "return", "(", "results", ".", "scene_id", ",", "results", ".", "config", ")" ]
parse a scene.config message
[ "parse", "a", "scene", ".", "config", "message" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L146-L153
246,302
zaturox/glin
glin/zmq/messages.py
MessageParser.scene_name
def scene_name(frames): """parse a scene.name message""" # "scene.name" <scene_id> <config> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").string("name").assert_end().get() if results.command != "scene.name": raise MessageParserError("Command is not 'scene.name'") return (results.scene_id, results.name)
python
def scene_name(frames): """parse a scene.name message""" # "scene.name" <scene_id> <config> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").string("name").assert_end().get() if results.command != "scene.name": raise MessageParserError("Command is not 'scene.name'") return (results.scene_id, results.name)
[ "def", "scene_name", "(", "frames", ")", ":", "# \"scene.name\" <scene_id> <config>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "string", "(", "\"name\"", ")", ".", "assert_end", "(", ")", ".", "get", "(", ")", "if", "results", ".", "command", "!=", "\"scene.name\"", ":", "raise", "MessageParserError", "(", "\"Command is not 'scene.name'\"", ")", "return", "(", "results", ".", "scene_id", ",", "results", ".", "name", ")" ]
parse a scene.name message
[ "parse", "a", "scene", ".", "name", "message" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L156-L163
246,303
zaturox/glin
glin/zmq/messages.py
MessageParser.scene_remove
def scene_remove(frames): """parse a scene.rm message""" # "scene.rm" <scene_id> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").assert_end().get() if results.command != "scene.rm": raise MessageParserError("Command is not 'scene.rm'") return (results.scene_id,)
python
def scene_remove(frames): """parse a scene.rm message""" # "scene.rm" <scene_id> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").assert_end().get() if results.command != "scene.rm": raise MessageParserError("Command is not 'scene.rm'") return (results.scene_id,)
[ "def", "scene_remove", "(", "frames", ")", ":", "# \"scene.rm\" <scene_id>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "assert_end", "(", ")", ".", "get", "(", ")", "if", "results", ".", "command", "!=", "\"scene.rm\"", ":", "raise", "MessageParserError", "(", "\"Command is not 'scene.rm'\"", ")", "return", "(", "results", ".", "scene_id", ",", ")" ]
parse a scene.rm message
[ "parse", "a", "scene", ".", "rm", "message" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L166-L173
246,304
zaturox/glin
glin/zmq/messages.py
MessageParser.scene_velocity
def scene_velocity(frames): """parse a scene.velocity message""" # "scene.velocity" <scene_id> <velocity> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").uint32("velocity").assert_end().get() if results.command != "scene.velocity": raise MessageParserError("Command is not 'scene.velocity'") return (results.scene_id, results.velocity/1000)
python
def scene_velocity(frames): """parse a scene.velocity message""" # "scene.velocity" <scene_id> <velocity> reader = MessageReader(frames) results = reader.string("command").uint32("scene_id").uint32("velocity").assert_end().get() if results.command != "scene.velocity": raise MessageParserError("Command is not 'scene.velocity'") return (results.scene_id, results.velocity/1000)
[ "def", "scene_velocity", "(", "frames", ")", ":", "# \"scene.velocity\" <scene_id> <velocity>", "reader", "=", "MessageReader", "(", "frames", ")", "results", "=", "reader", ".", "string", "(", "\"command\"", ")", ".", "uint32", "(", "\"scene_id\"", ")", ".", "uint32", "(", "\"velocity\"", ")", ".", "assert_end", "(", ")", ".", "get", "(", ")", "if", "results", ".", "command", "!=", "\"scene.velocity\"", ":", "raise", "MessageParserError", "(", "\"Command is not 'scene.velocity'\"", ")", "return", "(", "results", ".", "scene_id", ",", "results", ".", "velocity", "/", "1000", ")" ]
parse a scene.velocity message
[ "parse", "a", "scene", ".", "velocity", "message" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L186-L193
246,305
zaturox/glin
glin/zmq/messages.py
MessageReader.string
def string(self, name): """parse a string frame""" self._assert_is_string(name) frame = self._next_frame() try: val = frame.decode('utf-8') self.results.__dict__[name] = val except UnicodeError as err: raise MessageParserError("Message contained invalid Unicode characters") \ from err return self
python
def string(self, name): """parse a string frame""" self._assert_is_string(name) frame = self._next_frame() try: val = frame.decode('utf-8') self.results.__dict__[name] = val except UnicodeError as err: raise MessageParserError("Message contained invalid Unicode characters") \ from err return self
[ "def", "string", "(", "self", ",", "name", ")", ":", "self", ".", "_assert_is_string", "(", "name", ")", "frame", "=", "self", ".", "_next_frame", "(", ")", "try", ":", "val", "=", "frame", ".", "decode", "(", "'utf-8'", ")", "self", ".", "results", ".", "__dict__", "[", "name", "]", "=", "val", "except", "UnicodeError", "as", "err", ":", "raise", "MessageParserError", "(", "\"Message contained invalid Unicode characters\"", ")", "from", "err", "return", "self" ]
parse a string frame
[ "parse", "a", "string", "frame" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L219-L229
246,306
zaturox/glin
glin/zmq/messages.py
MessageReader.bool
def bool(self, name): """parse a boolean frame""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 1: raise MessageParserError("Expected exacty 1 byte for boolean value") val = frame != b"\x00" self.results.__dict__[name] = val return self
python
def bool(self, name): """parse a boolean frame""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 1: raise MessageParserError("Expected exacty 1 byte for boolean value") val = frame != b"\x00" self.results.__dict__[name] = val return self
[ "def", "bool", "(", "self", ",", "name", ")", ":", "self", ".", "_assert_is_string", "(", "name", ")", "frame", "=", "self", ".", "_next_frame", "(", ")", "if", "len", "(", "frame", ")", "!=", "1", ":", "raise", "MessageParserError", "(", "\"Expected exacty 1 byte for boolean value\"", ")", "val", "=", "frame", "!=", "b\"\\x00\"", "self", ".", "results", ".", "__dict__", "[", "name", "]", "=", "val", "return", "self" ]
parse a boolean frame
[ "parse", "a", "boolean", "frame" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L231-L239
246,307
zaturox/glin
glin/zmq/messages.py
MessageReader.uint8_3
def uint8_3(self, name): """parse a tuple of 3 uint8 values""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 3: raise MessageParserError("Expected exacty 3 byte for 3 unit8 values") vals = unpack("BBB", frame) self.results.__dict__[name] = vals return self
python
def uint8_3(self, name): """parse a tuple of 3 uint8 values""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 3: raise MessageParserError("Expected exacty 3 byte for 3 unit8 values") vals = unpack("BBB", frame) self.results.__dict__[name] = vals return self
[ "def", "uint8_3", "(", "self", ",", "name", ")", ":", "self", ".", "_assert_is_string", "(", "name", ")", "frame", "=", "self", ".", "_next_frame", "(", ")", "if", "len", "(", "frame", ")", "!=", "3", ":", "raise", "MessageParserError", "(", "\"Expected exacty 3 byte for 3 unit8 values\"", ")", "vals", "=", "unpack", "(", "\"BBB\"", ",", "frame", ")", "self", ".", "results", ".", "__dict__", "[", "name", "]", "=", "vals", "return", "self" ]
parse a tuple of 3 uint8 values
[ "parse", "a", "tuple", "of", "3", "uint8", "values" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L241-L249
246,308
zaturox/glin
glin/zmq/messages.py
MessageReader.uint32
def uint32(self, name): """parse a uint32 value""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 4: raise MessageParserError("Expected exacty 4 byte for uint32 value") (val,) = unpack("!I", frame) self.results.__dict__[name] = val return self
python
def uint32(self, name): """parse a uint32 value""" self._assert_is_string(name) frame = self._next_frame() if len(frame) != 4: raise MessageParserError("Expected exacty 4 byte for uint32 value") (val,) = unpack("!I", frame) self.results.__dict__[name] = val return self
[ "def", "uint32", "(", "self", ",", "name", ")", ":", "self", ".", "_assert_is_string", "(", "name", ")", "frame", "=", "self", ".", "_next_frame", "(", ")", "if", "len", "(", "frame", ")", "!=", "4", ":", "raise", "MessageParserError", "(", "\"Expected exacty 4 byte for uint32 value\"", ")", "(", "val", ",", ")", "=", "unpack", "(", "\"!I\"", ",", "frame", ")", "self", ".", "results", ".", "__dict__", "[", "name", "]", "=", "val", "return", "self" ]
parse a uint32 value
[ "parse", "a", "uint32", "value" ]
55214a579c4e4b4d74765f3f6aa2eb815bac1c3b
https://github.com/zaturox/glin/blob/55214a579c4e4b4d74765f3f6aa2eb815bac1c3b/glin/zmq/messages.py#L250-L258
246,309
tbreitenfeldt/invisible_ui
invisible_ui/elements/group.py
Group.activate
def activate(self, event): """Change the value.""" self._index += 1 if self._index >= len(self._values): self._index = 0 self._selection = self._values[self._index] self.ao2.speak(self._selection)
python
def activate(self, event): """Change the value.""" self._index += 1 if self._index >= len(self._values): self._index = 0 self._selection = self._values[self._index] self.ao2.speak(self._selection)
[ "def", "activate", "(", "self", ",", "event", ")", ":", "self", ".", "_index", "+=", "1", "if", "self", ".", "_index", ">=", "len", "(", "self", ".", "_values", ")", ":", "self", ".", "_index", "=", "0", "self", ".", "_selection", "=", "self", ".", "_values", "[", "self", ".", "_index", "]", "self", ".", "ao2", ".", "speak", "(", "self", ".", "_selection", ")" ]
Change the value.
[ "Change", "the", "value", "." ]
1a6907bfa61bded13fa9fb83ec7778c0df84487f
https://github.com/tbreitenfeldt/invisible_ui/blob/1a6907bfa61bded13fa9fb83ec7778c0df84487f/invisible_ui/elements/group.py#L25-L32
246,310
untergeek/es_stats
es_stats/classes.py
Stats.cached_read
def cached_read(self, kind): """Cache stats calls to prevent hammering the API""" if not kind in self.cache: self.pull_stats(kind) if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout: self.pull_stats(kind) return self.cache[kind]['lastvalue']
python
def cached_read(self, kind): """Cache stats calls to prevent hammering the API""" if not kind in self.cache: self.pull_stats(kind) if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout: self.pull_stats(kind) return self.cache[kind]['lastvalue']
[ "def", "cached_read", "(", "self", ",", "kind", ")", ":", "if", "not", "kind", "in", "self", ".", "cache", ":", "self", ".", "pull_stats", "(", "kind", ")", "if", "self", ".", "epochnow", "(", ")", "-", "self", ".", "cache", "[", "kind", "]", "[", "'lastcall'", "]", ">", "self", ".", "cache_timeout", ":", "self", ".", "pull_stats", "(", "kind", ")", "return", "self", ".", "cache", "[", "kind", "]", "[", "'lastvalue'", "]" ]
Cache stats calls to prevent hammering the API
[ "Cache", "stats", "calls", "to", "prevent", "hammering", "the", "API" ]
107754b703d3f618b849303048af570698ff70b5
https://github.com/untergeek/es_stats/blob/107754b703d3f618b849303048af570698ff70b5/es_stats/classes.py#L41-L47
246,311
untergeek/es_stats
es_stats/classes.py
Stats.get
def get(self, key, name=None): """Return value for specific key""" if name is None: self.nodename = self.local_name self.nodeid = self.local_id else: self.logger.debug('Replacing nodename "{0}" with "{1}"'.format(self.nodename, name)) self.nodename = name self.find_name() return get_value(self.stats(), fix_key(key))
python
def get(self, key, name=None): """Return value for specific key""" if name is None: self.nodename = self.local_name self.nodeid = self.local_id else: self.logger.debug('Replacing nodename "{0}" with "{1}"'.format(self.nodename, name)) self.nodename = name self.find_name() return get_value(self.stats(), fix_key(key))
[ "def", "get", "(", "self", ",", "key", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "self", ".", "nodename", "=", "self", ".", "local_name", "self", ".", "nodeid", "=", "self", ".", "local_id", "else", ":", "self", ".", "logger", ".", "debug", "(", "'Replacing nodename \"{0}\" with \"{1}\"'", ".", "format", "(", "self", ".", "nodename", ",", "name", ")", ")", "self", ".", "nodename", "=", "name", "self", ".", "find_name", "(", ")", "return", "get_value", "(", "self", ".", "stats", "(", ")", ",", "fix_key", "(", "key", ")", ")" ]
Return value for specific key
[ "Return", "value", "for", "specific", "key" ]
107754b703d3f618b849303048af570698ff70b5
https://github.com/untergeek/es_stats/blob/107754b703d3f618b849303048af570698ff70b5/es_stats/classes.py#L65-L74
246,312
refinery29/chassis
chassis/services/dependency_injection/resolver.py
detect_circle
def detect_circle(nodes): """ Wrapper for recursive _detect_circle function """ # Verify nodes and traveled types if not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') dependencies = set(nodes.keys()) traveled = [] heads = _detect_circle(nodes, dependencies, traveled) return DependencyTree(heads)
python
def detect_circle(nodes): """ Wrapper for recursive _detect_circle function """ # Verify nodes and traveled types if not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') dependencies = set(nodes.keys()) traveled = [] heads = _detect_circle(nodes, dependencies, traveled) return DependencyTree(heads)
[ "def", "detect_circle", "(", "nodes", ")", ":", "# Verify nodes and traveled types", "if", "not", "isinstance", "(", "nodes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'\"nodes\" must be a dictionary'", ")", "dependencies", "=", "set", "(", "nodes", ".", "keys", "(", ")", ")", "traveled", "=", "[", "]", "heads", "=", "_detect_circle", "(", "nodes", ",", "dependencies", ",", "traveled", ")", "return", "DependencyTree", "(", "heads", ")" ]
Wrapper for recursive _detect_circle function
[ "Wrapper", "for", "recursive", "_detect_circle", "function" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/resolver.py#L18-L29
246,313
refinery29/chassis
chassis/services/dependency_injection/resolver.py
_detect_circle
def _detect_circle(nodes=None, dependencies=None, traveled=None, path=None): """ Recursively iterate over nodes checking if we've traveled to that node before. """ # Verify nodes and traveled types if nodes is None: nodes = {} elif not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') if dependencies is None: return elif not isinstance(dependencies, set): raise TypeError('"dependencies" must be a set') if traveled is None: traveled = [] elif not isinstance(traveled, list): raise TypeError('"traveled" must be a list') if path is None: path = [] if not dependencies: # We're at the end of a dependency path. return [] # Recursively iterate over nodes, # and gather dependency children nodes. children = [] for name in dependencies: # Path is used for circular dependency exceptions # to display to the user the circular path. new_path = list(path) new_path.append(name) # Check if we've traveled to this node before. if name in traveled: raise CircularDependencyException(new_path) # Make recursive call node_children = _detect_circle(nodes=nodes, dependencies=nodes[name], traveled=traveled + list(name), path=new_path) # Create node for this dependency with children. node = DependencyNode(name) for child in node_children: child.parent = node node.add_child(child) children.append(node) return children
python
def _detect_circle(nodes=None, dependencies=None, traveled=None, path=None): """ Recursively iterate over nodes checking if we've traveled to that node before. """ # Verify nodes and traveled types if nodes is None: nodes = {} elif not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') if dependencies is None: return elif not isinstance(dependencies, set): raise TypeError('"dependencies" must be a set') if traveled is None: traveled = [] elif not isinstance(traveled, list): raise TypeError('"traveled" must be a list') if path is None: path = [] if not dependencies: # We're at the end of a dependency path. return [] # Recursively iterate over nodes, # and gather dependency children nodes. children = [] for name in dependencies: # Path is used for circular dependency exceptions # to display to the user the circular path. new_path = list(path) new_path.append(name) # Check if we've traveled to this node before. if name in traveled: raise CircularDependencyException(new_path) # Make recursive call node_children = _detect_circle(nodes=nodes, dependencies=nodes[name], traveled=traveled + list(name), path=new_path) # Create node for this dependency with children. node = DependencyNode(name) for child in node_children: child.parent = node node.add_child(child) children.append(node) return children
[ "def", "_detect_circle", "(", "nodes", "=", "None", ",", "dependencies", "=", "None", ",", "traveled", "=", "None", ",", "path", "=", "None", ")", ":", "# Verify nodes and traveled types", "if", "nodes", "is", "None", ":", "nodes", "=", "{", "}", "elif", "not", "isinstance", "(", "nodes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'\"nodes\" must be a dictionary'", ")", "if", "dependencies", "is", "None", ":", "return", "elif", "not", "isinstance", "(", "dependencies", ",", "set", ")", ":", "raise", "TypeError", "(", "'\"dependencies\" must be a set'", ")", "if", "traveled", "is", "None", ":", "traveled", "=", "[", "]", "elif", "not", "isinstance", "(", "traveled", ",", "list", ")", ":", "raise", "TypeError", "(", "'\"traveled\" must be a list'", ")", "if", "path", "is", "None", ":", "path", "=", "[", "]", "if", "not", "dependencies", ":", "# We're at the end of a dependency path.", "return", "[", "]", "# Recursively iterate over nodes,", "# and gather dependency children nodes.", "children", "=", "[", "]", "for", "name", "in", "dependencies", ":", "# Path is used for circular dependency exceptions", "# to display to the user the circular path.", "new_path", "=", "list", "(", "path", ")", "new_path", ".", "append", "(", "name", ")", "# Check if we've traveled to this node before.", "if", "name", "in", "traveled", ":", "raise", "CircularDependencyException", "(", "new_path", ")", "# Make recursive call", "node_children", "=", "_detect_circle", "(", "nodes", "=", "nodes", ",", "dependencies", "=", "nodes", "[", "name", "]", ",", "traveled", "=", "traveled", "+", "list", "(", "name", ")", ",", "path", "=", "new_path", ")", "# Create node for this dependency with children.", "node", "=", "DependencyNode", "(", "name", ")", "for", "child", "in", "node_children", ":", "child", ".", "parent", "=", "node", "node", ".", "add_child", "(", "child", ")", "children", ".", "append", "(", "node", ")", "return", "children" ]
Recursively iterate over nodes checking if we've traveled to that node before.
[ "Recursively", "iterate", "over", "nodes", "checking", "if", "we", "ve", "traveled", "to", "that", "node", "before", "." ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/resolver.py#L32-L83
246,314
refinery29/chassis
chassis/services/dependency_injection/resolver.py
Resolver._do
def _do(self, nodes): """ Recursive method to instantiate services """ if not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') if not nodes: # we're done! return starting_num_nodes = len(nodes) newly_instantiated = set() # Instantiate services with an empty dependency set for (name, dependency_set) in six.iteritems(nodes): if dependency_set: # Skip non-empty dependency sets continue # Instantiate config = self._config[name] service = self._factory.create_from_dict(config) self._factory.add_instantiated_service(name, service) newly_instantiated.add(name) # We ALWAYS should have instantiated a new service # or we'll end up in an infinite loop. if not newly_instantiated: raise Exception('No newly instantiated services') # Remove from Nodes for name in newly_instantiated: del nodes[name] # Check if the number of nodes have changed # to prevent infinite loops. # We should ALWAYS have removed a node. if starting_num_nodes == len(nodes): raise Exception('No nodes removed!') # Remove newly instantiated services from dependency sets for (name, dependency_set) in six.iteritems(nodes): nodes[name] = dependency_set.difference(newly_instantiated) # Recursion is recursion is ... self._do(nodes)
python
def _do(self, nodes): """ Recursive method to instantiate services """ if not isinstance(nodes, dict): raise TypeError('"nodes" must be a dictionary') if not nodes: # we're done! return starting_num_nodes = len(nodes) newly_instantiated = set() # Instantiate services with an empty dependency set for (name, dependency_set) in six.iteritems(nodes): if dependency_set: # Skip non-empty dependency sets continue # Instantiate config = self._config[name] service = self._factory.create_from_dict(config) self._factory.add_instantiated_service(name, service) newly_instantiated.add(name) # We ALWAYS should have instantiated a new service # or we'll end up in an infinite loop. if not newly_instantiated: raise Exception('No newly instantiated services') # Remove from Nodes for name in newly_instantiated: del nodes[name] # Check if the number of nodes have changed # to prevent infinite loops. # We should ALWAYS have removed a node. if starting_num_nodes == len(nodes): raise Exception('No nodes removed!') # Remove newly instantiated services from dependency sets for (name, dependency_set) in six.iteritems(nodes): nodes[name] = dependency_set.difference(newly_instantiated) # Recursion is recursion is ... self._do(nodes)
[ "def", "_do", "(", "self", ",", "nodes", ")", ":", "if", "not", "isinstance", "(", "nodes", ",", "dict", ")", ":", "raise", "TypeError", "(", "'\"nodes\" must be a dictionary'", ")", "if", "not", "nodes", ":", "# we're done!", "return", "starting_num_nodes", "=", "len", "(", "nodes", ")", "newly_instantiated", "=", "set", "(", ")", "# Instantiate services with an empty dependency set", "for", "(", "name", ",", "dependency_set", ")", "in", "six", ".", "iteritems", "(", "nodes", ")", ":", "if", "dependency_set", ":", "# Skip non-empty dependency sets", "continue", "# Instantiate", "config", "=", "self", ".", "_config", "[", "name", "]", "service", "=", "self", ".", "_factory", ".", "create_from_dict", "(", "config", ")", "self", ".", "_factory", ".", "add_instantiated_service", "(", "name", ",", "service", ")", "newly_instantiated", ".", "add", "(", "name", ")", "# We ALWAYS should have instantiated a new service", "# or we'll end up in an infinite loop.", "if", "not", "newly_instantiated", ":", "raise", "Exception", "(", "'No newly instantiated services'", ")", "# Remove from Nodes", "for", "name", "in", "newly_instantiated", ":", "del", "nodes", "[", "name", "]", "# Check if the number of nodes have changed", "# to prevent infinite loops.", "# We should ALWAYS have removed a node.", "if", "starting_num_nodes", "==", "len", "(", "nodes", ")", ":", "raise", "Exception", "(", "'No nodes removed!'", ")", "# Remove newly instantiated services from dependency sets", "for", "(", "name", ",", "dependency_set", ")", "in", "six", ".", "iteritems", "(", "nodes", ")", ":", "nodes", "[", "name", "]", "=", "dependency_set", ".", "difference", "(", "newly_instantiated", ")", "# Recursion is recursion is ...", "self", ".", "_do", "(", "nodes", ")" ]
Recursive method to instantiate services
[ "Recursive", "method", "to", "instantiate", "services" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/resolver.py#L131-L175
246,315
refinery29/chassis
chassis/services/dependency_injection/resolver.py
Resolver._init_nodes
def _init_nodes(self, config): """ Gathers dependency sets onto _nodes """ if not isinstance(config, dict): raise TypeError('"config" must be a dictionary') for (name, conf) in six.iteritems(config): args = [] if 'args' not in conf else conf['args'] kwargs = {} if 'kwargs' not in conf else conf['kwargs'] dependencies = set() arg_deps = self._get_dependencies_from_args(args) kwarg_deps = self._get_dependencies_from_kwargs(kwargs) dependencies.update(arg_deps) dependencies.update(kwarg_deps) self._nodes[name] = dependencies
python
def _init_nodes(self, config): """ Gathers dependency sets onto _nodes """ if not isinstance(config, dict): raise TypeError('"config" must be a dictionary') for (name, conf) in six.iteritems(config): args = [] if 'args' not in conf else conf['args'] kwargs = {} if 'kwargs' not in conf else conf['kwargs'] dependencies = set() arg_deps = self._get_dependencies_from_args(args) kwarg_deps = self._get_dependencies_from_kwargs(kwargs) dependencies.update(arg_deps) dependencies.update(kwarg_deps) self._nodes[name] = dependencies
[ "def", "_init_nodes", "(", "self", ",", "config", ")", ":", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "TypeError", "(", "'\"config\" must be a dictionary'", ")", "for", "(", "name", ",", "conf", ")", "in", "six", ".", "iteritems", "(", "config", ")", ":", "args", "=", "[", "]", "if", "'args'", "not", "in", "conf", "else", "conf", "[", "'args'", "]", "kwargs", "=", "{", "}", "if", "'kwargs'", "not", "in", "conf", "else", "conf", "[", "'kwargs'", "]", "dependencies", "=", "set", "(", ")", "arg_deps", "=", "self", ".", "_get_dependencies_from_args", "(", "args", ")", "kwarg_deps", "=", "self", ".", "_get_dependencies_from_kwargs", "(", "kwargs", ")", "dependencies", ".", "update", "(", "arg_deps", ")", "dependencies", ".", "update", "(", "kwarg_deps", ")", "self", ".", "_nodes", "[", "name", "]", "=", "dependencies" ]
Gathers dependency sets onto _nodes
[ "Gathers", "dependency", "sets", "onto", "_nodes" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/resolver.py#L177-L193
246,316
refinery29/chassis
chassis/services/dependency_injection/resolver.py
Resolver._get_dependencies_from_kwargs
def _get_dependencies_from_kwargs(self, args): """ Parse keyed arguments """ if not isinstance(args, dict): raise TypeError('"kwargs" must be a dictionary') dependency_names = set() for arg in args.values(): new_names = self._check_arg(arg) dependency_names.update(new_names) return dependency_names
python
def _get_dependencies_from_kwargs(self, args): """ Parse keyed arguments """ if not isinstance(args, dict): raise TypeError('"kwargs" must be a dictionary') dependency_names = set() for arg in args.values(): new_names = self._check_arg(arg) dependency_names.update(new_names) return dependency_names
[ "def", "_get_dependencies_from_kwargs", "(", "self", ",", "args", ")", ":", "if", "not", "isinstance", "(", "args", ",", "dict", ")", ":", "raise", "TypeError", "(", "'\"kwargs\" must be a dictionary'", ")", "dependency_names", "=", "set", "(", ")", "for", "arg", "in", "args", ".", "values", "(", ")", ":", "new_names", "=", "self", ".", "_check_arg", "(", "arg", ")", "dependency_names", ".", "update", "(", "new_names", ")", "return", "dependency_names" ]
Parse keyed arguments
[ "Parse", "keyed", "arguments" ]
1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/resolver.py#L206-L215
246,317
evetrivia/thanatos
thanatos/database/universe.py
get_all_regions
def get_all_regions(db_connection): """ Gets a list of all regions. :return: A list of all regions. Results have regionID and regionName. :rtype: list """ if not hasattr(get_all_regions, '_results'): sql = 'CALL get_all_regions();' results = execute_sql(sql, db_connection) get_all_regions._results = results return get_all_regions._results
python
def get_all_regions(db_connection): """ Gets a list of all regions. :return: A list of all regions. Results have regionID and regionName. :rtype: list """ if not hasattr(get_all_regions, '_results'): sql = 'CALL get_all_regions();' results = execute_sql(sql, db_connection) get_all_regions._results = results return get_all_regions._results
[ "def", "get_all_regions", "(", "db_connection", ")", ":", "if", "not", "hasattr", "(", "get_all_regions", ",", "'_results'", ")", ":", "sql", "=", "'CALL get_all_regions();'", "results", "=", "execute_sql", "(", "sql", ",", "db_connection", ")", "get_all_regions", ".", "_results", "=", "results", "return", "get_all_regions", ".", "_results" ]
Gets a list of all regions. :return: A list of all regions. Results have regionID and regionName. :rtype: list
[ "Gets", "a", "list", "of", "all", "regions", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/universe.py#L10-L22
246,318
evetrivia/thanatos
thanatos/database/universe.py
get_all_not_wh_regions
def get_all_not_wh_regions(db_connection): """ Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list """ if not hasattr(get_all_not_wh_regions, '_results'): sql = 'CALL get_all_not_wh_regions();' results = execute_sql(sql, db_connection) get_all_not_wh_regions._results = results return get_all_not_wh_regions._results
python
def get_all_not_wh_regions(db_connection): """ Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list """ if not hasattr(get_all_not_wh_regions, '_results'): sql = 'CALL get_all_not_wh_regions();' results = execute_sql(sql, db_connection) get_all_not_wh_regions._results = results return get_all_not_wh_regions._results
[ "def", "get_all_not_wh_regions", "(", "db_connection", ")", ":", "if", "not", "hasattr", "(", "get_all_not_wh_regions", ",", "'_results'", ")", ":", "sql", "=", "'CALL get_all_not_wh_regions();'", "results", "=", "execute_sql", "(", "sql", ",", "db_connection", ")", "get_all_not_wh_regions", ".", "_results", "=", "results", "return", "get_all_not_wh_regions", ".", "_results" ]
Gets a list of all regions that are not WH regions. :return: A list of all regions not including wormhole regions. Results have regionID and regionName. :rtype: list
[ "Gets", "a", "list", "of", "all", "regions", "that", "are", "not", "WH", "regions", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/universe.py#L25-L37
246,319
evetrivia/thanatos
thanatos/database/universe.py
get_all_regions_connected_to_region
def get_all_regions_connected_to_region(db_connection, region_id): """ Gets a list of all regions connected to the region ID passed in. :param region_id: Region ID to find all regions connected to. :type region_id: int :return: A list of all regions connected to the specified region ID. Results have regionID and regionName. :rtype: list """ sql = 'CALL get_all_regions_connected_to_region({});'.format(region_id) results = execute_sql(sql, db_connection) return results
python
def get_all_regions_connected_to_region(db_connection, region_id): """ Gets a list of all regions connected to the region ID passed in. :param region_id: Region ID to find all regions connected to. :type region_id: int :return: A list of all regions connected to the specified region ID. Results have regionID and regionName. :rtype: list """ sql = 'CALL get_all_regions_connected_to_region({});'.format(region_id) results = execute_sql(sql, db_connection) return results
[ "def", "get_all_regions_connected_to_region", "(", "db_connection", ",", "region_id", ")", ":", "sql", "=", "'CALL get_all_regions_connected_to_region({});'", ".", "format", "(", "region_id", ")", "results", "=", "execute_sql", "(", "sql", ",", "db_connection", ")", "return", "results" ]
Gets a list of all regions connected to the region ID passed in. :param region_id: Region ID to find all regions connected to. :type region_id: int :return: A list of all regions connected to the specified region ID. Results have regionID and regionName. :rtype: list
[ "Gets", "a", "list", "of", "all", "regions", "connected", "to", "the", "region", "ID", "passed", "in", "." ]
664c12a8ccf4d27ab0e06e0969bbb6381f74789c
https://github.com/evetrivia/thanatos/blob/664c12a8ccf4d27ab0e06e0969bbb6381f74789c/thanatos/database/universe.py#L40-L53
246,320
edeposit/edeposit.amqp.antivirus
bin/edeposit_clamd_init.py
create_config
def create_config(cnf_file, uid, overwrite): """ Creates configuration file and the directory where it should be stored and set correct permissions. Args: cnf_file (str): Path to the configuration file. uid (int): User ID - will be used for chown. overwrite (bool): Overwrite the configuration with :attr:`CLEAN_CONFIG`. """ conf = None # needed also on suse, because pyClamd module if not os.path.exists(settings.DEB_CONF_PATH): os.makedirs(settings.DEB_CONF_PATH, 0755) os.chown(settings.DEB_CONF_PATH, uid, -1) if not os.path.exists(cnf_file): # create new conf file conf = CLEAN_CONFIG elif overwrite: # ovewrite old conf file backup_name = cnf_file + "_" if not os.path.exists(backup_name): shutil.copyfile(cnf_file, backup_name) os.chown(backup_name, uid, -1) conf = CLEAN_CONFIG else: # switch variables in existing file with open(cnf_file) as f: conf = f.read() # write the conf file with open(cnf_file, "w") as f: f.write(update_configuration(conf)) # permission check (uid) os.chown(cnf_file, uid, -1) os.chmod(cnf_file, 0644) symlink = settings.DEB_CONF_PATH + settings.CONF_FILE if not settings.is_deb_system() and not os.path.exists(symlink): os.symlink(cnf_file, symlink) os.chown(symlink, uid, -1) os.chmod(symlink, 0644)
python
def create_config(cnf_file, uid, overwrite): """ Creates configuration file and the directory where it should be stored and set correct permissions. Args: cnf_file (str): Path to the configuration file. uid (int): User ID - will be used for chown. overwrite (bool): Overwrite the configuration with :attr:`CLEAN_CONFIG`. """ conf = None # needed also on suse, because pyClamd module if not os.path.exists(settings.DEB_CONF_PATH): os.makedirs(settings.DEB_CONF_PATH, 0755) os.chown(settings.DEB_CONF_PATH, uid, -1) if not os.path.exists(cnf_file): # create new conf file conf = CLEAN_CONFIG elif overwrite: # ovewrite old conf file backup_name = cnf_file + "_" if not os.path.exists(backup_name): shutil.copyfile(cnf_file, backup_name) os.chown(backup_name, uid, -1) conf = CLEAN_CONFIG else: # switch variables in existing file with open(cnf_file) as f: conf = f.read() # write the conf file with open(cnf_file, "w") as f: f.write(update_configuration(conf)) # permission check (uid) os.chown(cnf_file, uid, -1) os.chmod(cnf_file, 0644) symlink = settings.DEB_CONF_PATH + settings.CONF_FILE if not settings.is_deb_system() and not os.path.exists(symlink): os.symlink(cnf_file, symlink) os.chown(symlink, uid, -1) os.chmod(symlink, 0644)
[ "def", "create_config", "(", "cnf_file", ",", "uid", ",", "overwrite", ")", ":", "conf", "=", "None", "# needed also on suse, because pyClamd module", "if", "not", "os", ".", "path", ".", "exists", "(", "settings", ".", "DEB_CONF_PATH", ")", ":", "os", ".", "makedirs", "(", "settings", ".", "DEB_CONF_PATH", ",", "0755", ")", "os", ".", "chown", "(", "settings", ".", "DEB_CONF_PATH", ",", "uid", ",", "-", "1", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "cnf_file", ")", ":", "# create new conf file", "conf", "=", "CLEAN_CONFIG", "elif", "overwrite", ":", "# ovewrite old conf file", "backup_name", "=", "cnf_file", "+", "\"_\"", "if", "not", "os", ".", "path", ".", "exists", "(", "backup_name", ")", ":", "shutil", ".", "copyfile", "(", "cnf_file", ",", "backup_name", ")", "os", ".", "chown", "(", "backup_name", ",", "uid", ",", "-", "1", ")", "conf", "=", "CLEAN_CONFIG", "else", ":", "# switch variables in existing file", "with", "open", "(", "cnf_file", ")", "as", "f", ":", "conf", "=", "f", ".", "read", "(", ")", "# write the conf file", "with", "open", "(", "cnf_file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "update_configuration", "(", "conf", ")", ")", "# permission check (uid)", "os", ".", "chown", "(", "cnf_file", ",", "uid", ",", "-", "1", ")", "os", ".", "chmod", "(", "cnf_file", ",", "0644", ")", "symlink", "=", "settings", ".", "DEB_CONF_PATH", "+", "settings", ".", "CONF_FILE", "if", "not", "settings", ".", "is_deb_system", "(", ")", "and", "not", "os", ".", "path", ".", "exists", "(", "symlink", ")", ":", "os", ".", "symlink", "(", "cnf_file", ",", "symlink", ")", "os", ".", "chown", "(", "symlink", ",", "uid", ",", "-", "1", ")", "os", ".", "chmod", "(", "symlink", ",", "0644", ")" ]
Creates configuration file and the directory where it should be stored and set correct permissions. Args: cnf_file (str): Path to the configuration file. uid (int): User ID - will be used for chown. overwrite (bool): Overwrite the configuration with :attr:`CLEAN_CONFIG`.
[ "Creates", "configuration", "file", "and", "the", "directory", "where", "it", "should", "be", "stored", "and", "set", "correct", "permissions", "." ]
011b38bbe920819fab99a5891b1e70732321a598
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/bin/edeposit_clamd_init.py#L218-L260
246,321
edeposit/edeposit.amqp.antivirus
bin/edeposit_clamd_init.py
create_log
def create_log(log_file, uid): """ Create log file and set necessary permissions. Args: log_file (str): Path to the log file. uid (int): User ID - will be used for chown. """ if not os.path.exists(log_file): # create new log file dir_name = os.path.dirname(log_file) if not os.path.exists(dir_name): os.makedirs(dir_name, 0755) os.chown(dir_name, uid, -1) with open(log_file, "w") as f: f.write("") os.chown(log_file, uid, -1) os.chmod(log_file, 0640)
python
def create_log(log_file, uid): """ Create log file and set necessary permissions. Args: log_file (str): Path to the log file. uid (int): User ID - will be used for chown. """ if not os.path.exists(log_file): # create new log file dir_name = os.path.dirname(log_file) if not os.path.exists(dir_name): os.makedirs(dir_name, 0755) os.chown(dir_name, uid, -1) with open(log_file, "w") as f: f.write("") os.chown(log_file, uid, -1) os.chmod(log_file, 0640)
[ "def", "create_log", "(", "log_file", ",", "uid", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "log_file", ")", ":", "# create new log file", "dir_name", "=", "os", ".", "path", ".", "dirname", "(", "log_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_name", ")", ":", "os", ".", "makedirs", "(", "dir_name", ",", "0755", ")", "os", ".", "chown", "(", "dir_name", ",", "uid", ",", "-", "1", ")", "with", "open", "(", "log_file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"\"", ")", "os", ".", "chown", "(", "log_file", ",", "uid", ",", "-", "1", ")", "os", ".", "chmod", "(", "log_file", ",", "0640", ")" ]
Create log file and set necessary permissions. Args: log_file (str): Path to the log file. uid (int): User ID - will be used for chown.
[ "Create", "log", "file", "and", "set", "necessary", "permissions", "." ]
011b38bbe920819fab99a5891b1e70732321a598
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/bin/edeposit_clamd_init.py#L263-L281
246,322
edeposit/edeposit.amqp.antivirus
bin/edeposit_clamd_init.py
main
def main(conf_file, overwrite, logger): """ Create configuration and log file. Restart the daemon when configuration is done. Args: conf_file (str): Path to the configuration file. overwrite (bool): Overwrite the configuration file with `clean` config? """ uid = pwd.getpwnam(get_username()).pw_uid # stop the daemon logger.info("Stopping the daemon.") sh.service(get_service_name(), "stop") # create files logger.info("Creating config file.") create_config( cnf_file=conf_file, uid=uid, overwrite=overwrite ) logger.info("Creating log file.") create_log( log_file=REQUIRED_SETTINGS["LogFile"], uid=uid ) # start the daemon logger.info("Starting the daemon..") sh.service(get_service_name(), "start")
python
def main(conf_file, overwrite, logger): """ Create configuration and log file. Restart the daemon when configuration is done. Args: conf_file (str): Path to the configuration file. overwrite (bool): Overwrite the configuration file with `clean` config? """ uid = pwd.getpwnam(get_username()).pw_uid # stop the daemon logger.info("Stopping the daemon.") sh.service(get_service_name(), "stop") # create files logger.info("Creating config file.") create_config( cnf_file=conf_file, uid=uid, overwrite=overwrite ) logger.info("Creating log file.") create_log( log_file=REQUIRED_SETTINGS["LogFile"], uid=uid ) # start the daemon logger.info("Starting the daemon..") sh.service(get_service_name(), "start")
[ "def", "main", "(", "conf_file", ",", "overwrite", ",", "logger", ")", ":", "uid", "=", "pwd", ".", "getpwnam", "(", "get_username", "(", ")", ")", ".", "pw_uid", "# stop the daemon", "logger", ".", "info", "(", "\"Stopping the daemon.\"", ")", "sh", ".", "service", "(", "get_service_name", "(", ")", ",", "\"stop\"", ")", "# create files", "logger", ".", "info", "(", "\"Creating config file.\"", ")", "create_config", "(", "cnf_file", "=", "conf_file", ",", "uid", "=", "uid", ",", "overwrite", "=", "overwrite", ")", "logger", ".", "info", "(", "\"Creating log file.\"", ")", "create_log", "(", "log_file", "=", "REQUIRED_SETTINGS", "[", "\"LogFile\"", "]", ",", "uid", "=", "uid", ")", "# start the daemon", "logger", ".", "info", "(", "\"Starting the daemon..\"", ")", "sh", ".", "service", "(", "get_service_name", "(", ")", ",", "\"start\"", ")" ]
Create configuration and log file. Restart the daemon when configuration is done. Args: conf_file (str): Path to the configuration file. overwrite (bool): Overwrite the configuration file with `clean` config?
[ "Create", "configuration", "and", "log", "file", ".", "Restart", "the", "daemon", "when", "configuration", "is", "done", "." ]
011b38bbe920819fab99a5891b1e70732321a598
https://github.com/edeposit/edeposit.amqp.antivirus/blob/011b38bbe920819fab99a5891b1e70732321a598/bin/edeposit_clamd_init.py#L292-L322
246,323
20c/xbahn
xbahn/engineer.py
setup_debug_logging
def setup_debug_logging(): """ set up debug logging """ logger = logging.getLogger("xbahn") logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(logging.Formatter("%(name)s: %(message)s")) logger.addHandler(ch)
python
def setup_debug_logging(): """ set up debug logging """ logger = logging.getLogger("xbahn") logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(logging.Formatter("%(name)s: %(message)s")) logger.addHandler(ch)
[ "def", "setup_debug_logging", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"xbahn\"", ")", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "ch", "=", "logging", ".", "StreamHandler", "(", ")", "ch", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "ch", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "\"%(name)s: %(message)s\"", ")", ")", "logger", ".", "addHandler", "(", "ch", ")" ]
set up debug logging
[ "set", "up", "debug", "logging" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L17-L29
246,324
20c/xbahn
xbahn/engineer.py
shell
def shell(ctx): """ open an engineer shell """ shell = code.InteractiveConsole({"engineer": getattr(ctx.parent, "widget", None)}) shell.interact("\n".join([ "Engineer connected to %s" % ctx.parent.params["host"], "Dispatch available through the 'engineer' object" ]))
python
def shell(ctx): """ open an engineer shell """ shell = code.InteractiveConsole({"engineer": getattr(ctx.parent, "widget", None)}) shell.interact("\n".join([ "Engineer connected to %s" % ctx.parent.params["host"], "Dispatch available through the 'engineer' object" ]))
[ "def", "shell", "(", "ctx", ")", ":", "shell", "=", "code", ".", "InteractiveConsole", "(", "{", "\"engineer\"", ":", "getattr", "(", "ctx", ".", "parent", ",", "\"widget\"", ",", "None", ")", "}", ")", "shell", ".", "interact", "(", "\"\\n\"", ".", "join", "(", "[", "\"Engineer connected to %s\"", "%", "ctx", ".", "parent", ".", "params", "[", "\"host\"", "]", ",", "\"Dispatch available through the 'engineer' object\"", "]", ")", ")" ]
open an engineer shell
[ "open", "an", "engineer", "shell" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L258-L267
246,325
20c/xbahn
xbahn/engineer.py
Engineer.connect
def connect(self, ctx): """ establish xbahn connection and store on click context """ if hasattr(ctx,"conn") or "host" not in ctx.params: return ctx.conn = conn = connect(ctx.params["host"]) lnk = link.Link() lnk.wire("main", receive=conn, send=conn) ctx.client = api.Client(link=lnk) ctx.widget = ClientWidget(ctx.client, "engineer")
python
def connect(self, ctx): """ establish xbahn connection and store on click context """ if hasattr(ctx,"conn") or "host" not in ctx.params: return ctx.conn = conn = connect(ctx.params["host"]) lnk = link.Link() lnk.wire("main", receive=conn, send=conn) ctx.client = api.Client(link=lnk) ctx.widget = ClientWidget(ctx.client, "engineer")
[ "def", "connect", "(", "self", ",", "ctx", ")", ":", "if", "hasattr", "(", "ctx", ",", "\"conn\"", ")", "or", "\"host\"", "not", "in", "ctx", ".", "params", ":", "return", "ctx", ".", "conn", "=", "conn", "=", "connect", "(", "ctx", ".", "params", "[", "\"host\"", "]", ")", "lnk", "=", "link", ".", "Link", "(", ")", "lnk", ".", "wire", "(", "\"main\"", ",", "receive", "=", "conn", ",", "send", "=", "conn", ")", "ctx", ".", "client", "=", "api", ".", "Client", "(", "link", "=", "lnk", ")", "ctx", ".", "widget", "=", "ClientWidget", "(", "ctx", ".", "client", ",", "\"engineer\"", ")" ]
establish xbahn connection and store on click context
[ "establish", "xbahn", "connection", "and", "store", "on", "click", "context" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L163-L176
246,326
20c/xbahn
xbahn/engineer.py
Engineer.list_commands
def list_commands(self, ctx): """ list all commands exposed to engineer """ self.connect(ctx) if not hasattr(ctx, "widget"): return super(Engineer, self).list_commands(ctx) return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(ctx)
python
def list_commands(self, ctx): """ list all commands exposed to engineer """ self.connect(ctx) if not hasattr(ctx, "widget"): return super(Engineer, self).list_commands(ctx) return ctx.widget.engineer_list_commands() + super(Engineer, self).list_commands(ctx)
[ "def", "list_commands", "(", "self", ",", "ctx", ")", ":", "self", ".", "connect", "(", "ctx", ")", "if", "not", "hasattr", "(", "ctx", ",", "\"widget\"", ")", ":", "return", "super", "(", "Engineer", ",", "self", ")", ".", "list_commands", "(", "ctx", ")", "return", "ctx", ".", "widget", ".", "engineer_list_commands", "(", ")", "+", "super", "(", "Engineer", ",", "self", ")", ".", "list_commands", "(", "ctx", ")" ]
list all commands exposed to engineer
[ "list", "all", "commands", "exposed", "to", "engineer" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L179-L191
246,327
20c/xbahn
xbahn/engineer.py
Engineer.get_command
def get_command(self, ctx, name): """ get click command from engineer exposed xbahn command specs """ # connect to xbahn self.connect(ctx) if not hasattr(ctx, "widget") or name in ["shell"]: return super(Engineer, self).get_command(ctx, name) if name == "--help": return None # get the command specs (description, arguments and options) info = ctx.widget.engineer_info(name) # make command from specs return self.make_command(ctx, name, info)
python
def get_command(self, ctx, name): """ get click command from engineer exposed xbahn command specs """ # connect to xbahn self.connect(ctx) if not hasattr(ctx, "widget") or name in ["shell"]: return super(Engineer, self).get_command(ctx, name) if name == "--help": return None # get the command specs (description, arguments and options) info = ctx.widget.engineer_info(name) # make command from specs return self.make_command(ctx, name, info)
[ "def", "get_command", "(", "self", ",", "ctx", ",", "name", ")", ":", "# connect to xbahn", "self", ".", "connect", "(", "ctx", ")", "if", "not", "hasattr", "(", "ctx", ",", "\"widget\"", ")", "or", "name", "in", "[", "\"shell\"", "]", ":", "return", "super", "(", "Engineer", ",", "self", ")", ".", "get_command", "(", "ctx", ",", "name", ")", "if", "name", "==", "\"--help\"", ":", "return", "None", "# get the command specs (description, arguments and options)", "info", "=", "ctx", ".", "widget", ".", "engineer_info", "(", "name", ")", "# make command from specs", "return", "self", ".", "make_command", "(", "ctx", ",", "name", ",", "info", ")" ]
get click command from engineer exposed xbahn command specs
[ "get", "click", "command", "from", "engineer", "exposed", "xbahn", "command", "specs" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L193-L212
246,328
20c/xbahn
xbahn/engineer.py
Engineer.make_command
def make_command(self, ctx, name, info): """ make click sub-command from command info gotten from xbahn engineer """ @self.command() @click.option("--debug/--no-debug", default=False, help="Show debug information") @doc(info.get("description")) def func(*args, **kwargs): if "debug" in kwargs: del kwargs["debug"] fn = getattr(ctx.widget, name) result = fn(*args, **kwargs) click.echo("%s: %s> %s" % (ctx.params["host"],name,result)) ctx.conn.close() ctx.info_name = "%s %s" % (ctx.info_name , ctx.params["host"]) for a in info.get("arguments",[]): deco = click.argument(*a["args"], **a["kwargs"]) func = deco(func) for o in info.get("options",[]): deco = click.option(*o["args"], **o["kwargs"]) func = deco(func) return func
python
def make_command(self, ctx, name, info): """ make click sub-command from command info gotten from xbahn engineer """ @self.command() @click.option("--debug/--no-debug", default=False, help="Show debug information") @doc(info.get("description")) def func(*args, **kwargs): if "debug" in kwargs: del kwargs["debug"] fn = getattr(ctx.widget, name) result = fn(*args, **kwargs) click.echo("%s: %s> %s" % (ctx.params["host"],name,result)) ctx.conn.close() ctx.info_name = "%s %s" % (ctx.info_name , ctx.params["host"]) for a in info.get("arguments",[]): deco = click.argument(*a["args"], **a["kwargs"]) func = deco(func) for o in info.get("options",[]): deco = click.option(*o["args"], **o["kwargs"]) func = deco(func) return func
[ "def", "make_command", "(", "self", ",", "ctx", ",", "name", ",", "info", ")", ":", "@", "self", ".", "command", "(", ")", "@", "click", ".", "option", "(", "\"--debug/--no-debug\"", ",", "default", "=", "False", ",", "help", "=", "\"Show debug information\"", ")", "@", "doc", "(", "info", ".", "get", "(", "\"description\"", ")", ")", "def", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"debug\"", "in", "kwargs", ":", "del", "kwargs", "[", "\"debug\"", "]", "fn", "=", "getattr", "(", "ctx", ".", "widget", ",", "name", ")", "result", "=", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "click", ".", "echo", "(", "\"%s: %s> %s\"", "%", "(", "ctx", ".", "params", "[", "\"host\"", "]", ",", "name", ",", "result", ")", ")", "ctx", ".", "conn", ".", "close", "(", ")", "ctx", ".", "info_name", "=", "\"%s %s\"", "%", "(", "ctx", ".", "info_name", ",", "ctx", ".", "params", "[", "\"host\"", "]", ")", "for", "a", "in", "info", ".", "get", "(", "\"arguments\"", ",", "[", "]", ")", ":", "deco", "=", "click", ".", "argument", "(", "*", "a", "[", "\"args\"", "]", ",", "*", "*", "a", "[", "\"kwargs\"", "]", ")", "func", "=", "deco", "(", "func", ")", "for", "o", "in", "info", ".", "get", "(", "\"options\"", ",", "[", "]", ")", ":", "deco", "=", "click", ".", "option", "(", "*", "o", "[", "\"args\"", "]", ",", "*", "*", "o", "[", "\"kwargs\"", "]", ")", "func", "=", "deco", "(", "func", ")", "return", "func" ]
make click sub-command from command info gotten from xbahn engineer
[ "make", "click", "sub", "-", "command", "from", "command", "info", "gotten", "from", "xbahn", "engineer" ]
afb27b0576841338a366d7cac0200a782bd84be6
https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/engineer.py#L214-L241
246,329
RRostami/PyTBot
PyTBot/telegram.py
bot.getMe
def getMe(self): ''' returns User Object ''' response_str = self._command('getMe') if(not response_str): return False response = json.loads(response_str) return response
python
def getMe(self): ''' returns User Object ''' response_str = self._command('getMe') if(not response_str): return False response = json.loads(response_str) return response
[ "def", "getMe", "(", "self", ")", ":", "response_str", "=", "self", ".", "_command", "(", "'getMe'", ")", "if", "(", "not", "response_str", ")", ":", "return", "False", "response", "=", "json", ".", "loads", "(", "response_str", ")", "return", "response" ]
returns User Object
[ "returns", "User", "Object" ]
a95bb9b3d3d19284b60c93b758a8aa26e3357929
https://github.com/RRostami/PyTBot/blob/a95bb9b3d3d19284b60c93b758a8aa26e3357929/PyTBot/telegram.py#L124-L130
246,330
RRostami/PyTBot
PyTBot/telegram.py
bot.sendMessage
def sendMessage(self,chat_id,text,parse_mode=None,disable_web=None,reply_msg_id=None,markup=None): ''' On failure returns False On success returns Message Object ''' payload={'chat_id' : chat_id, 'text' : text, 'parse_mode': parse_mode , 'disable_web_page_preview' : disable_web , 'reply_to_message_id' : reply_msg_id} if(markup): payload['reply_markup']=json.dumps(markup) response_str = self._command('sendMessage',payload,method='post') return _validate_response_msg(response_str)
python
def sendMessage(self,chat_id,text,parse_mode=None,disable_web=None,reply_msg_id=None,markup=None): ''' On failure returns False On success returns Message Object ''' payload={'chat_id' : chat_id, 'text' : text, 'parse_mode': parse_mode , 'disable_web_page_preview' : disable_web , 'reply_to_message_id' : reply_msg_id} if(markup): payload['reply_markup']=json.dumps(markup) response_str = self._command('sendMessage',payload,method='post') return _validate_response_msg(response_str)
[ "def", "sendMessage", "(", "self", ",", "chat_id", ",", "text", ",", "parse_mode", "=", "None", ",", "disable_web", "=", "None", ",", "reply_msg_id", "=", "None", ",", "markup", "=", "None", ")", ":", "payload", "=", "{", "'chat_id'", ":", "chat_id", ",", "'text'", ":", "text", ",", "'parse_mode'", ":", "parse_mode", ",", "'disable_web_page_preview'", ":", "disable_web", ",", "'reply_to_message_id'", ":", "reply_msg_id", "}", "if", "(", "markup", ")", ":", "payload", "[", "'reply_markup'", "]", "=", "json", ".", "dumps", "(", "markup", ")", "response_str", "=", "self", ".", "_command", "(", "'sendMessage'", ",", "payload", ",", "method", "=", "'post'", ")", "return", "_validate_response_msg", "(", "response_str", ")" ]
On failure returns False On success returns Message Object
[ "On", "failure", "returns", "False", "On", "success", "returns", "Message", "Object" ]
a95bb9b3d3d19284b60c93b758a8aa26e3357929
https://github.com/RRostami/PyTBot/blob/a95bb9b3d3d19284b60c93b758a8aa26e3357929/PyTBot/telegram.py#L132-L142
246,331
slarse/pdfebc-core
pdfebc_core/misc_utils.py
if_callable_call_with_formatted_string
def if_callable_call_with_formatted_string(callback, formattable_string, *args): """If the callback is callable, format the string with the args and make a call. Otherwise, do nothing. Args: callback (function): May or may not be callable. formattable_string (str): A string with '{}'s inserted. *args: A variable amount of arguments for the string formatting. Must correspond to the amount of '{}'s in 'formattable_string'. Raises: ValueError """ try: formatted_string = formattable_string.format(*args) except IndexError: raise ValueError("Mismatch metween amount of insertion points in the formattable string\n" "and the amount of args given.") if callable(callback): callback(formatted_string)
python
def if_callable_call_with_formatted_string(callback, formattable_string, *args): """If the callback is callable, format the string with the args and make a call. Otherwise, do nothing. Args: callback (function): May or may not be callable. formattable_string (str): A string with '{}'s inserted. *args: A variable amount of arguments for the string formatting. Must correspond to the amount of '{}'s in 'formattable_string'. Raises: ValueError """ try: formatted_string = formattable_string.format(*args) except IndexError: raise ValueError("Mismatch metween amount of insertion points in the formattable string\n" "and the amount of args given.") if callable(callback): callback(formatted_string)
[ "def", "if_callable_call_with_formatted_string", "(", "callback", ",", "formattable_string", ",", "*", "args", ")", ":", "try", ":", "formatted_string", "=", "formattable_string", ".", "format", "(", "*", "args", ")", "except", "IndexError", ":", "raise", "ValueError", "(", "\"Mismatch metween amount of insertion points in the formattable string\\n\"", "\"and the amount of args given.\"", ")", "if", "callable", "(", "callback", ")", ":", "callback", "(", "formatted_string", ")" ]
If the callback is callable, format the string with the args and make a call. Otherwise, do nothing. Args: callback (function): May or may not be callable. formattable_string (str): A string with '{}'s inserted. *args: A variable amount of arguments for the string formatting. Must correspond to the amount of '{}'s in 'formattable_string'. Raises: ValueError
[ "If", "the", "callback", "is", "callable", "format", "the", "string", "with", "the", "args", "and", "make", "a", "call", ".", "Otherwise", "do", "nothing", "." ]
fc40857bc42365b7434714333e37d7a3487603a0
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/misc_utils.py#L14-L32
246,332
cogniteev/docido-python-sdk
docido_sdk/toolbox/date_ext.py
timestamp_ms.feeling_lucky
def feeling_lucky(cls, obj): """Tries to convert given object to an UTC timestamp is ms, based on its type. """ if isinstance(obj, six.string_types): return cls.from_str(obj) elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP: return cls.from_posix_timestamp(obj) elif isinstance(obj, datetime): return cls.from_datetime(obj) else: raise ValueError( u"Don't know how to get timestamp from '{}'".format(obj) )
python
def feeling_lucky(cls, obj): """Tries to convert given object to an UTC timestamp is ms, based on its type. """ if isinstance(obj, six.string_types): return cls.from_str(obj) elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP: return cls.from_posix_timestamp(obj) elif isinstance(obj, datetime): return cls.from_datetime(obj) else: raise ValueError( u"Don't know how to get timestamp from '{}'".format(obj) )
[ "def", "feeling_lucky", "(", "cls", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "return", "cls", ".", "from_str", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "six", ".", "integer_types", ")", "and", "obj", "<=", "MAX_POSIX_TIMESTAMP", ":", "return", "cls", ".", "from_posix_timestamp", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "datetime", ")", ":", "return", "cls", ".", "from_datetime", "(", "obj", ")", "else", ":", "raise", "ValueError", "(", "u\"Don't know how to get timestamp from '{}'\"", ".", "format", "(", "obj", ")", ")" ]
Tries to convert given object to an UTC timestamp is ms, based on its type.
[ "Tries", "to", "convert", "given", "object", "to", "an", "UTC", "timestamp", "is", "ms", "based", "on", "its", "type", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L38-L51
246,333
cogniteev/docido-python-sdk
docido_sdk/toolbox/date_ext.py
timestamp_ms.fix_mispelled_day
def fix_mispelled_day(cls, timestr): """fix mispelled day when written in english :return: `None` if the day was not modified, the new date otherwise """ day_extraction = cls.START_WITH_DAY_OF_WEEK.match(timestr) if day_extraction is not None: day = day_extraction.group(1).lower() if len(day) == 3: dataset = DAYS_ABBR else: dataset = DAYS if day not in dataset: days = list(dataset) days.sort(key=lambda e: levenshtein(day, e)) return days[0] + day_extraction.group(2)
python
def fix_mispelled_day(cls, timestr): """fix mispelled day when written in english :return: `None` if the day was not modified, the new date otherwise """ day_extraction = cls.START_WITH_DAY_OF_WEEK.match(timestr) if day_extraction is not None: day = day_extraction.group(1).lower() if len(day) == 3: dataset = DAYS_ABBR else: dataset = DAYS if day not in dataset: days = list(dataset) days.sort(key=lambda e: levenshtein(day, e)) return days[0] + day_extraction.group(2)
[ "def", "fix_mispelled_day", "(", "cls", ",", "timestr", ")", ":", "day_extraction", "=", "cls", ".", "START_WITH_DAY_OF_WEEK", ".", "match", "(", "timestr", ")", "if", "day_extraction", "is", "not", "None", ":", "day", "=", "day_extraction", ".", "group", "(", "1", ")", ".", "lower", "(", ")", "if", "len", "(", "day", ")", "==", "3", ":", "dataset", "=", "DAYS_ABBR", "else", ":", "dataset", "=", "DAYS", "if", "day", "not", "in", "dataset", ":", "days", "=", "list", "(", "dataset", ")", "days", ".", "sort", "(", "key", "=", "lambda", "e", ":", "levenshtein", "(", "day", ",", "e", ")", ")", "return", "days", "[", "0", "]", "+", "day_extraction", ".", "group", "(", "2", ")" ]
fix mispelled day when written in english :return: `None` if the day was not modified, the new date otherwise
[ "fix", "mispelled", "day", "when", "written", "in", "english" ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L54-L69
246,334
cogniteev/docido-python-sdk
docido_sdk/toolbox/date_ext.py
timestamp_ms.remove_timezone
def remove_timezone(cls, timestr): """Completely remove timezone information, if any. :return: the new string if timezone was found, `None` otherwise """ if re.match(r".*[\-+]?\d{2}:\d{2}$", timestr): return re.sub( r"(.*)(\s[\+-]?\d\d:\d\d)$", r"\1", timestr )
python
def remove_timezone(cls, timestr): """Completely remove timezone information, if any. :return: the new string if timezone was found, `None` otherwise """ if re.match(r".*[\-+]?\d{2}:\d{2}$", timestr): return re.sub( r"(.*)(\s[\+-]?\d\d:\d\d)$", r"\1", timestr )
[ "def", "remove_timezone", "(", "cls", ",", "timestr", ")", ":", "if", "re", ".", "match", "(", "r\".*[\\-+]?\\d{2}:\\d{2}$\"", ",", "timestr", ")", ":", "return", "re", ".", "sub", "(", "r\"(.*)(\\s[\\+-]?\\d\\d:\\d\\d)$\"", ",", "r\"\\1\"", ",", "timestr", ")" ]
Completely remove timezone information, if any. :return: the new string if timezone was found, `None` otherwise
[ "Completely", "remove", "timezone", "information", "if", "any", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L91-L101
246,335
cogniteev/docido-python-sdk
docido_sdk/toolbox/date_ext.py
timestamp_ms.fix_timezone_separator
def fix_timezone_separator(cls, timestr): """Replace invalid timezone separator to prevent `dateutil.parser.parse` to raise. :return: the new string if invalid separators were found, `None` otherwise """ tz_sep = cls.TIMEZONE_SEPARATOR.match(timestr) if tz_sep is not None: return tz_sep.group(1) + tz_sep.group(2) + ':' + tz_sep.group(3) return timestr
python
def fix_timezone_separator(cls, timestr): """Replace invalid timezone separator to prevent `dateutil.parser.parse` to raise. :return: the new string if invalid separators were found, `None` otherwise """ tz_sep = cls.TIMEZONE_SEPARATOR.match(timestr) if tz_sep is not None: return tz_sep.group(1) + tz_sep.group(2) + ':' + tz_sep.group(3) return timestr
[ "def", "fix_timezone_separator", "(", "cls", ",", "timestr", ")", ":", "tz_sep", "=", "cls", ".", "TIMEZONE_SEPARATOR", ".", "match", "(", "timestr", ")", "if", "tz_sep", "is", "not", "None", ":", "return", "tz_sep", ".", "group", "(", "1", ")", "+", "tz_sep", ".", "group", "(", "2", ")", "+", "':'", "+", "tz_sep", ".", "group", "(", "3", ")", "return", "timestr" ]
Replace invalid timezone separator to prevent `dateutil.parser.parse` to raise. :return: the new string if invalid separators were found, `None` otherwise
[ "Replace", "invalid", "timezone", "separator", "to", "prevent", "dateutil", ".", "parser", ".", "parse", "to", "raise", "." ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L104-L114
246,336
cogniteev/docido-python-sdk
docido_sdk/toolbox/date_ext.py
timestamp_ms.from_str
def from_str(cls, timestr, shaked=False): """Use `dateutil` module to parse the give string :param basestring timestr: string representing a date to parse :param bool shaked: whether the input parameter been already cleaned or not. """ orig = timestr if not shaked: timestr = cls.fix_timezone_separator(timestr) try: date = parser.parse(timestr) except ValueError: if not shaked: shaked = False for shaker in [ cls.fix_mispelled_day, cls.remove_parenthesis_around_tz, cls.remove_quotes_around_tz]: new_timestr = shaker(timestr) if new_timestr is not None: timestr = new_timestr shaked = True if shaked: try: return cls.from_str(timestr, shaked=True) except ValueError: # raise ValueError below with proper message pass msg = u"Unknown string format: {!r}".format(orig) raise ValueError(msg), None, sys.exc_info()[2] else: try: return cls.from_datetime(date) except ValueError: new_str = cls.remove_timezone(orig) if new_str is not None: return cls.from_str(new_str) else: raise
python
def from_str(cls, timestr, shaked=False): """Use `dateutil` module to parse the give string :param basestring timestr: string representing a date to parse :param bool shaked: whether the input parameter been already cleaned or not. """ orig = timestr if not shaked: timestr = cls.fix_timezone_separator(timestr) try: date = parser.parse(timestr) except ValueError: if not shaked: shaked = False for shaker in [ cls.fix_mispelled_day, cls.remove_parenthesis_around_tz, cls.remove_quotes_around_tz]: new_timestr = shaker(timestr) if new_timestr is not None: timestr = new_timestr shaked = True if shaked: try: return cls.from_str(timestr, shaked=True) except ValueError: # raise ValueError below with proper message pass msg = u"Unknown string format: {!r}".format(orig) raise ValueError(msg), None, sys.exc_info()[2] else: try: return cls.from_datetime(date) except ValueError: new_str = cls.remove_timezone(orig) if new_str is not None: return cls.from_str(new_str) else: raise
[ "def", "from_str", "(", "cls", ",", "timestr", ",", "shaked", "=", "False", ")", ":", "orig", "=", "timestr", "if", "not", "shaked", ":", "timestr", "=", "cls", ".", "fix_timezone_separator", "(", "timestr", ")", "try", ":", "date", "=", "parser", ".", "parse", "(", "timestr", ")", "except", "ValueError", ":", "if", "not", "shaked", ":", "shaked", "=", "False", "for", "shaker", "in", "[", "cls", ".", "fix_mispelled_day", ",", "cls", ".", "remove_parenthesis_around_tz", ",", "cls", ".", "remove_quotes_around_tz", "]", ":", "new_timestr", "=", "shaker", "(", "timestr", ")", "if", "new_timestr", "is", "not", "None", ":", "timestr", "=", "new_timestr", "shaked", "=", "True", "if", "shaked", ":", "try", ":", "return", "cls", ".", "from_str", "(", "timestr", ",", "shaked", "=", "True", ")", "except", "ValueError", ":", "# raise ValueError below with proper message", "pass", "msg", "=", "u\"Unknown string format: {!r}\"", ".", "format", "(", "orig", ")", "raise", "ValueError", "(", "msg", ")", ",", "None", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "else", ":", "try", ":", "return", "cls", ".", "from_datetime", "(", "date", ")", "except", "ValueError", ":", "new_str", "=", "cls", ".", "remove_timezone", "(", "orig", ")", "if", "new_str", "is", "not", "None", ":", "return", "cls", ".", "from_str", "(", "new_str", ")", "else", ":", "raise" ]
Use `dateutil` module to parse the give string :param basestring timestr: string representing a date to parse :param bool shaked: whether the input parameter been already cleaned or not.
[ "Use", "dateutil", "module", "to", "parse", "the", "give", "string" ]
58ecb6c6f5757fd40c0601657ab18368da7ddf33
https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/date_ext.py#L117-L156
246,337
tBaxter/tango-comments
build/lib/tango_comments/views/utils.py
next_redirect
def next_redirect(request, fallback, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a ``?next=...`` GET arg or the URL of a given view (``fallback``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = request.POST.get('next') if not is_safe_url(url=next, allowed_hosts=request.get_host()): next = resolve_url(fallback) if get_kwargs: if '#' in next: tmp = next.rsplit('#', 1) next = tmp[0] anchor = '#' + tmp[1] else: anchor = '' joiner = ('?' in next) and '&' or '?' next += joiner + urlencode(get_kwargs) + anchor return HttpResponseRedirect(next)
python
def next_redirect(request, fallback, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a ``?next=...`` GET arg or the URL of a given view (``fallback``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = request.POST.get('next') if not is_safe_url(url=next, allowed_hosts=request.get_host()): next = resolve_url(fallback) if get_kwargs: if '#' in next: tmp = next.rsplit('#', 1) next = tmp[0] anchor = '#' + tmp[1] else: anchor = '' joiner = ('?' in next) and '&' or '?' next += joiner + urlencode(get_kwargs) + anchor return HttpResponseRedirect(next)
[ "def", "next_redirect", "(", "request", ",", "fallback", ",", "*", "*", "get_kwargs", ")", ":", "next", "=", "request", ".", "POST", ".", "get", "(", "'next'", ")", "if", "not", "is_safe_url", "(", "url", "=", "next", ",", "allowed_hosts", "=", "request", ".", "get_host", "(", ")", ")", ":", "next", "=", "resolve_url", "(", "fallback", ")", "if", "get_kwargs", ":", "if", "'#'", "in", "next", ":", "tmp", "=", "next", ".", "rsplit", "(", "'#'", ",", "1", ")", "next", "=", "tmp", "[", "0", "]", "anchor", "=", "'#'", "+", "tmp", "[", "1", "]", "else", ":", "anchor", "=", "''", "joiner", "=", "(", "'?'", "in", "next", ")", "and", "'&'", "or", "'?'", "next", "+=", "joiner", "+", "urlencode", "(", "get_kwargs", ")", "+", "anchor", "return", "HttpResponseRedirect", "(", "next", ")" ]
Handle the "where should I go next?" part of comment views. The next value could be a ``?next=...`` GET arg or the URL of a given view (``fallback``). See the view modules for examples. Returns an ``HttpResponseRedirect``.
[ "Handle", "the", "where", "should", "I", "go", "next?", "part", "of", "comment", "views", "." ]
1fd335c6fc9e81bba158e42e1483f1a149622ab4
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/utils.py#L15-L39
246,338
cbrand/vpnchooser
src/vpnchooser/db/user.py
User.check
def check(self, password: str) -> bool: """ Checks the given password with the one stored in the database """ return ( pbkdf2_sha512.verify(password, self.password) or pbkdf2_sha512.verify(password, pbkdf2_sha512.encrypt(self.api_key)) )
python
def check(self, password: str) -> bool: """ Checks the given password with the one stored in the database """ return ( pbkdf2_sha512.verify(password, self.password) or pbkdf2_sha512.verify(password, pbkdf2_sha512.encrypt(self.api_key)) )
[ "def", "check", "(", "self", ",", "password", ":", "str", ")", "->", "bool", ":", "return", "(", "pbkdf2_sha512", ".", "verify", "(", "password", ",", "self", ".", "password", ")", "or", "pbkdf2_sha512", ".", "verify", "(", "password", ",", "pbkdf2_sha512", ".", "encrypt", "(", "self", ".", "api_key", ")", ")", ")" ]
Checks the given password with the one stored in the database
[ "Checks", "the", "given", "password", "with", "the", "one", "stored", "in", "the", "database" ]
d153e3d05555c23cf5e8e15e507eecad86465923
https://github.com/cbrand/vpnchooser/blob/d153e3d05555c23cf5e8e15e507eecad86465923/src/vpnchooser/db/user.py#L31-L40
246,339
f213/rumetr-client
rumetr/roometr.py
Rumetr.complex_exists
def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) except exceptions.RumetrComplexNotFound: return False return True
python
def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) except exceptions.RumetrComplexNotFound: return False return True
[ "def", "complex_exists", "(", "self", ",", "complex", ":", "str", ")", "->", "bool", ":", "try", ":", "self", ".", "check_complex", "(", "complex", ")", "except", "exceptions", ".", "RumetrComplexNotFound", ":", "return", "False", "return", "True" ]
Shortcut to check if complex exists in our database.
[ "Shortcut", "to", "check", "if", "complex", "exists", "in", "our", "database", "." ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L39-L48
246,340
f213/rumetr-client
rumetr/roometr.py
Rumetr.house_exists
def house_exists(self, complex: str, house: str) -> bool: """ Shortcut to check if house exists in our database. """ try: self.check_house(complex, house) except exceptions.RumetrHouseNotFound: return False return True
python
def house_exists(self, complex: str, house: str) -> bool: """ Shortcut to check if house exists in our database. """ try: self.check_house(complex, house) except exceptions.RumetrHouseNotFound: return False return True
[ "def", "house_exists", "(", "self", ",", "complex", ":", "str", ",", "house", ":", "str", ")", "->", "bool", ":", "try", ":", "self", ".", "check_house", "(", "complex", ",", "house", ")", "except", "exceptions", ".", "RumetrHouseNotFound", ":", "return", "False", "return", "True" ]
Shortcut to check if house exists in our database.
[ "Shortcut", "to", "check", "if", "house", "exists", "in", "our", "database", "." ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L50-L59
246,341
f213/rumetr-client
rumetr/roometr.py
Rumetr.appt_exists
def appt_exists(self, complex: str, house: str, appt: str) -> bool: """ Shortcut to check if appt exists in our database. """ try: self.check_appt(complex, house, appt) except exceptions.RumetrApptNotFound: return False return True
python
def appt_exists(self, complex: str, house: str, appt: str) -> bool: """ Shortcut to check if appt exists in our database. """ try: self.check_appt(complex, house, appt) except exceptions.RumetrApptNotFound: return False return True
[ "def", "appt_exists", "(", "self", ",", "complex", ":", "str", ",", "house", ":", "str", ",", "appt", ":", "str", ")", "->", "bool", ":", "try", ":", "self", ".", "check_appt", "(", "complex", ",", "house", ",", "appt", ")", "except", "exceptions", ".", "RumetrApptNotFound", ":", "return", "False", "return", "True" ]
Shortcut to check if appt exists in our database.
[ "Shortcut", "to", "check", "if", "appt", "exists", "in", "our", "database", "." ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L61-L70
246,342
f213/rumetr-client
rumetr/roometr.py
Rumetr.post
def post(self, url: str, data: str, expected_status_code=201): """ Do a POST request """ r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) self._check_response(r, expected_status_code) return r.json()
python
def post(self, url: str, data: str, expected_status_code=201): """ Do a POST request """ r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) self._check_response(r, expected_status_code) return r.json()
[ "def", "post", "(", "self", ",", "url", ":", "str", ",", "data", ":", "str", ",", "expected_status_code", "=", "201", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "_format_url", "(", "url", ")", ",", "json", "=", "data", ",", "headers", "=", "self", ".", "headers", ",", "timeout", "=", "TIMEOUT", ")", "self", ".", "_check_response", "(", "r", ",", "expected_status_code", ")", "return", "r", ".", "json", "(", ")" ]
Do a POST request
[ "Do", "a", "POST", "request" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L95-L102
246,343
f213/rumetr-client
rumetr/roometr.py
Rumetr.get
def get(self, url): """ Do a GET request """ r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT) self._check_response(r, 200) return r.json()
python
def get(self, url): """ Do a GET request """ r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT) self._check_response(r, 200) return r.json()
[ "def", "get", "(", "self", ",", "url", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "_format_url", "(", "url", ")", ",", "headers", "=", "self", ".", "headers", ",", "timeout", "=", "TIMEOUT", ")", "self", ".", "_check_response", "(", "r", ",", "200", ")", "return", "r", ".", "json", "(", ")" ]
Do a GET request
[ "Do", "a", "GET", "request" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L113-L120
246,344
f213/rumetr-client
rumetr/roometr.py
Rumetr.add_complex
def add_complex(self, **kwargs): """ Add a new complex to the rumetr db """ self.check_developer() self.post('developers/%s/complexes/' % self.developer, data=kwargs)
python
def add_complex(self, **kwargs): """ Add a new complex to the rumetr db """ self.check_developer() self.post('developers/%s/complexes/' % self.developer, data=kwargs)
[ "def", "add_complex", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_developer", "(", ")", "self", ".", "post", "(", "'developers/%s/complexes/'", "%", "self", ".", "developer", ",", "data", "=", "kwargs", ")" ]
Add a new complex to the rumetr db
[ "Add", "a", "new", "complex", "to", "the", "rumetr", "db" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L212-L217
246,345
f213/rumetr-client
rumetr/roometr.py
Rumetr.add_house
def add_house(self, complex: str, **kwargs): """ Add a new house to the rumetr db """ self.check_complex(complex) self.post('developers/{developer}/complexes/{complex}/houses/'.format(developer=self.developer, complex=complex), data=kwargs)
python
def add_house(self, complex: str, **kwargs): """ Add a new house to the rumetr db """ self.check_complex(complex) self.post('developers/{developer}/complexes/{complex}/houses/'.format(developer=self.developer, complex=complex), data=kwargs)
[ "def", "add_house", "(", "self", ",", "complex", ":", "str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_complex", "(", "complex", ")", "self", ".", "post", "(", "'developers/{developer}/complexes/{complex}/houses/'", ".", "format", "(", "developer", "=", "self", ".", "developer", ",", "complex", "=", "complex", ")", ",", "data", "=", "kwargs", ")" ]
Add a new house to the rumetr db
[ "Add", "a", "new", "house", "to", "the", "rumetr", "db" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L219-L224
246,346
f213/rumetr-client
rumetr/roometr.py
Rumetr.add_appt
def add_appt(self, complex: str, house: str, price: str, square: str, **kwargs): """ Add a new appartment to the rumetr db """ self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.post('developers/{developer}/complexes/{complex}/houses/{house}/appts/'.format( developer=self.developer, complex=complex, house=house, ), data=kwargs)
python
def add_appt(self, complex: str, house: str, price: str, square: str, **kwargs): """ Add a new appartment to the rumetr db """ self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.post('developers/{developer}/complexes/{complex}/houses/{house}/appts/'.format( developer=self.developer, complex=complex, house=house, ), data=kwargs)
[ "def", "add_appt", "(", "self", ",", "complex", ":", "str", ",", "house", ":", "str", ",", "price", ":", "str", ",", "square", ":", "str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_house", "(", "complex", ",", "house", ")", "kwargs", "[", "'price'", "]", "=", "self", ".", "_format_decimal", "(", "price", ")", "kwargs", "[", "'square'", "]", "=", "self", ".", "_format_decimal", "(", "square", ")", "self", ".", "post", "(", "'developers/{developer}/complexes/{complex}/houses/{house}/appts/'", ".", "format", "(", "developer", "=", "self", ".", "developer", ",", "complex", "=", "complex", ",", "house", "=", "house", ",", ")", ",", "data", "=", "kwargs", ")" ]
Add a new appartment to the rumetr db
[ "Add", "a", "new", "appartment", "to", "the", "rumetr", "db" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L226-L239
246,347
f213/rumetr-client
rumetr/roometr.py
Rumetr.update_house
def update_house(self, complex: str, id: str, **kwargs): """ Update the existing house """ self.check_house(complex, id) self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format( developer=self.developer, complex=complex, id=id, ), data=kwargs)
python
def update_house(self, complex: str, id: str, **kwargs): """ Update the existing house """ self.check_house(complex, id) self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format( developer=self.developer, complex=complex, id=id, ), data=kwargs)
[ "def", "update_house", "(", "self", ",", "complex", ":", "str", ",", "id", ":", "str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_house", "(", "complex", ",", "id", ")", "self", ".", "put", "(", "'developers/{developer}/complexes/{complex}/houses/{id}'", ".", "format", "(", "developer", "=", "self", ".", "developer", ",", "complex", "=", "complex", ",", "id", "=", "id", ",", ")", ",", "data", "=", "kwargs", ")" ]
Update the existing house
[ "Update", "the", "existing", "house" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L241-L250
246,348
f213/rumetr-client
rumetr/roometr.py
Rumetr.update_appt
def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs): """ Update existing appartment """ self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.put('developers/{developer}/complexes/{complex}/houses/{house}/appts/{id}'.format( developer=self.developer, complex=complex, house=house, id=id, price=self._format_decimal(price), ), data=kwargs)
python
def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs): """ Update existing appartment """ self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.put('developers/{developer}/complexes/{complex}/houses/{house}/appts/{id}'.format( developer=self.developer, complex=complex, house=house, id=id, price=self._format_decimal(price), ), data=kwargs)
[ "def", "update_appt", "(", "self", ",", "complex", ":", "str", ",", "house", ":", "str", ",", "price", ":", "str", ",", "square", ":", "str", ",", "id", ":", "str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "check_house", "(", "complex", ",", "house", ")", "kwargs", "[", "'price'", "]", "=", "self", ".", "_format_decimal", "(", "price", ")", "kwargs", "[", "'square'", "]", "=", "self", ".", "_format_decimal", "(", "square", ")", "self", ".", "put", "(", "'developers/{developer}/complexes/{complex}/houses/{house}/appts/{id}'", ".", "format", "(", "developer", "=", "self", ".", "developer", ",", "complex", "=", "complex", ",", "house", "=", "house", ",", "id", "=", "id", ",", "price", "=", "self", ".", "_format_decimal", "(", "price", ")", ",", ")", ",", "data", "=", "kwargs", ")" ]
Update existing appartment
[ "Update", "existing", "appartment" ]
5180152bcb2eed8246b88035db7c0bb1fe603166
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L252-L267
246,349
dhain/potpy
potpy/context.py
Context.inject
def inject(self, func, **kwargs): """Inject arguments from context into a callable. :param func: The callable to inject arguments into. :param \*\*kwargs: Specify values to override context items. """ args, varargs, keywords, defaults = self._get_argspec(func) if defaults: required_args = args[:-len(defaults)] optional_args = args[len(required_args):] else: required_args = args optional_args = [] values = [ kwargs[arg] if arg in kwargs else self[arg] for arg in required_args ] if defaults: values.extend( kwargs[arg] if arg in kwargs else self.get(arg, default) for arg, default in zip(optional_args, defaults) ) return func(*values)
python
def inject(self, func, **kwargs): """Inject arguments from context into a callable. :param func: The callable to inject arguments into. :param \*\*kwargs: Specify values to override context items. """ args, varargs, keywords, defaults = self._get_argspec(func) if defaults: required_args = args[:-len(defaults)] optional_args = args[len(required_args):] else: required_args = args optional_args = [] values = [ kwargs[arg] if arg in kwargs else self[arg] for arg in required_args ] if defaults: values.extend( kwargs[arg] if arg in kwargs else self.get(arg, default) for arg, default in zip(optional_args, defaults) ) return func(*values)
[ "def", "inject", "(", "self", ",", "func", ",", "*", "*", "kwargs", ")", ":", "args", ",", "varargs", ",", "keywords", ",", "defaults", "=", "self", ".", "_get_argspec", "(", "func", ")", "if", "defaults", ":", "required_args", "=", "args", "[", ":", "-", "len", "(", "defaults", ")", "]", "optional_args", "=", "args", "[", "len", "(", "required_args", ")", ":", "]", "else", ":", "required_args", "=", "args", "optional_args", "=", "[", "]", "values", "=", "[", "kwargs", "[", "arg", "]", "if", "arg", "in", "kwargs", "else", "self", "[", "arg", "]", "for", "arg", "in", "required_args", "]", "if", "defaults", ":", "values", ".", "extend", "(", "kwargs", "[", "arg", "]", "if", "arg", "in", "kwargs", "else", "self", ".", "get", "(", "arg", ",", "default", ")", "for", "arg", ",", "default", "in", "zip", "(", "optional_args", ",", "defaults", ")", ")", "return", "func", "(", "*", "values", ")" ]
Inject arguments from context into a callable. :param func: The callable to inject arguments into. :param \*\*kwargs: Specify values to override context items.
[ "Inject", "arguments", "from", "context", "into", "a", "callable", "." ]
e39a5a84f763fbf144b07a620afb02a5ff3741c9
https://github.com/dhain/potpy/blob/e39a5a84f763fbf144b07a620afb02a5ff3741c9/potpy/context.py#L88-L110
246,350
hoersuppe/hoerapi.py
hoerapi/util.py
parse_date
def parse_date(val, zone='default'): val = parse_isodate(val, None) ''' date has no ISO zone information ''' if not val.tzinfo: val = timezone[zone].localize(val) return val
python
def parse_date(val, zone='default'): val = parse_isodate(val, None) ''' date has no ISO zone information ''' if not val.tzinfo: val = timezone[zone].localize(val) return val
[ "def", "parse_date", "(", "val", ",", "zone", "=", "'default'", ")", ":", "val", "=", "parse_isodate", "(", "val", ",", "None", ")", "if", "not", "val", ".", "tzinfo", ":", "val", "=", "timezone", "[", "zone", "]", ".", "localize", "(", "val", ")", "return", "val" ]
date has no ISO zone information
[ "date", "has", "no", "ISO", "zone", "information" ]
50d6da5c2108e9960391a2bccb06f1d60af6b9e7
https://github.com/hoersuppe/hoerapi.py/blob/50d6da5c2108e9960391a2bccb06f1d60af6b9e7/hoerapi/util.py#L11-L16
246,351
KelSolaar/Oncilla
oncilla/build_api.py
import_sanitizer
def import_sanitizer(sanitizer): """ Imports the sanitizer python module. :param sanitizer: Sanitizer python module file. :type sanitizer: unicode :return: Module. :rtype: object """ directory = os.path.dirname(sanitizer) not directory in sys.path and sys.path.append(directory) namespace = __import__(foundations.strings.get_splitext_basename(sanitizer)) if hasattr(namespace, "bleach"): return namespace else: raise foundations.exceptions.ProgrammingError( "{0} | '{1}' is not a valid sanitizer module file!".format(sanitizer))
python
def import_sanitizer(sanitizer): """ Imports the sanitizer python module. :param sanitizer: Sanitizer python module file. :type sanitizer: unicode :return: Module. :rtype: object """ directory = os.path.dirname(sanitizer) not directory in sys.path and sys.path.append(directory) namespace = __import__(foundations.strings.get_splitext_basename(sanitizer)) if hasattr(namespace, "bleach"): return namespace else: raise foundations.exceptions.ProgrammingError( "{0} | '{1}' is not a valid sanitizer module file!".format(sanitizer))
[ "def", "import_sanitizer", "(", "sanitizer", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "sanitizer", ")", "not", "directory", "in", "sys", ".", "path", "and", "sys", ".", "path", ".", "append", "(", "directory", ")", "namespace", "=", "__import__", "(", "foundations", ".", "strings", ".", "get_splitext_basename", "(", "sanitizer", ")", ")", "if", "hasattr", "(", "namespace", ",", "\"bleach\"", ")", ":", "return", "namespace", "else", ":", "raise", "foundations", ".", "exceptions", ".", "ProgrammingError", "(", "\"{0} | '{1}' is not a valid sanitizer module file!\"", ".", "format", "(", "sanitizer", ")", ")" ]
Imports the sanitizer python module. :param sanitizer: Sanitizer python module file. :type sanitizer: unicode :return: Module. :rtype: object
[ "Imports", "the", "sanitizer", "python", "module", "." ]
2b4db3704cf2c22a09a207681cb041fff555a994
https://github.com/KelSolaar/Oncilla/blob/2b4db3704cf2c22a09a207681cb041fff555a994/oncilla/build_api.py#L78-L96
246,352
gersolar/linketurbidity
linketurbidity/instrument.py
pixels_from_coordinates
def pixels_from_coordinates(lat, lon, max_y, max_x): """ Return the 2 matrix with lat and lon of each pixel. Keyword arguments: lat -- A latitude matrix lon -- A longitude matrix max_y -- The max vertical pixels amount of an orthorectified image. max_x -- The max horizontal pixels amount of an orthorectified image. """ # The degrees by pixel of the orthorectified image. x_ratio, y_ratio = max_x/360., max_y/180. x, y = np.zeros(lon.shape), np.zeros(lat.shape) x = (lon + 180.) * x_ratio y = (lat + 90.) * y_ratio return x, y
python
def pixels_from_coordinates(lat, lon, max_y, max_x): """ Return the 2 matrix with lat and lon of each pixel. Keyword arguments: lat -- A latitude matrix lon -- A longitude matrix max_y -- The max vertical pixels amount of an orthorectified image. max_x -- The max horizontal pixels amount of an orthorectified image. """ # The degrees by pixel of the orthorectified image. x_ratio, y_ratio = max_x/360., max_y/180. x, y = np.zeros(lon.shape), np.zeros(lat.shape) x = (lon + 180.) * x_ratio y = (lat + 90.) * y_ratio return x, y
[ "def", "pixels_from_coordinates", "(", "lat", ",", "lon", ",", "max_y", ",", "max_x", ")", ":", "# The degrees by pixel of the orthorectified image.", "x_ratio", ",", "y_ratio", "=", "max_x", "/", "360.", ",", "max_y", "/", "180.", "x", ",", "y", "=", "np", ".", "zeros", "(", "lon", ".", "shape", ")", ",", "np", ".", "zeros", "(", "lat", ".", "shape", ")", "x", "=", "(", "lon", "+", "180.", ")", "*", "x_ratio", "y", "=", "(", "lat", "+", "90.", ")", "*", "y_ratio", "return", "x", ",", "y" ]
Return the 2 matrix with lat and lon of each pixel. Keyword arguments: lat -- A latitude matrix lon -- A longitude matrix max_y -- The max vertical pixels amount of an orthorectified image. max_x -- The max horizontal pixels amount of an orthorectified image.
[ "Return", "the", "2", "matrix", "with", "lat", "and", "lon", "of", "each", "pixel", "." ]
0ba58fd623bf719d06d1a394d74f706f16d37295
https://github.com/gersolar/linketurbidity/blob/0ba58fd623bf719d06d1a394d74f706f16d37295/linketurbidity/instrument.py#L9-L24
246,353
gersolar/linketurbidity
linketurbidity/instrument.py
obtain_to
def obtain_to(filename, compressed=True): """ Return the linke turbidity projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file. """ files = glob.glob(filename) root, _ = nc.open(filename) lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:] date_str = lambda f: ".".join((f.split('/')[-1]).split('.')[1:-2]) date = lambda f: datetime.strptime(date_str(f), "%Y.%j.%H%M%S") linke = lambda f: transform_data(obtain(date(f), compressed), lat, lon) linkes_projected = map(lambda f: (f, linke(f)), files) nc.close(root) return dict(linkes_projected)
python
def obtain_to(filename, compressed=True): """ Return the linke turbidity projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file. """ files = glob.glob(filename) root, _ = nc.open(filename) lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:] date_str = lambda f: ".".join((f.split('/')[-1]).split('.')[1:-2]) date = lambda f: datetime.strptime(date_str(f), "%Y.%j.%H%M%S") linke = lambda f: transform_data(obtain(date(f), compressed), lat, lon) linkes_projected = map(lambda f: (f, linke(f)), files) nc.close(root) return dict(linkes_projected)
[ "def", "obtain_to", "(", "filename", ",", "compressed", "=", "True", ")", ":", "files", "=", "glob", ".", "glob", "(", "filename", ")", "root", ",", "_", "=", "nc", ".", "open", "(", "filename", ")", "lat", ",", "lon", "=", "nc", ".", "getvar", "(", "root", ",", "'lat'", ")", "[", "0", ",", ":", "]", ",", "nc", ".", "getvar", "(", "root", ",", "'lon'", ")", "[", "0", ",", ":", "]", "date_str", "=", "lambda", "f", ":", "\".\"", ".", "join", "(", "(", "f", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", ".", "split", "(", "'.'", ")", "[", "1", ":", "-", "2", "]", ")", "date", "=", "lambda", "f", ":", "datetime", ".", "strptime", "(", "date_str", "(", "f", ")", ",", "\"%Y.%j.%H%M%S\"", ")", "linke", "=", "lambda", "f", ":", "transform_data", "(", "obtain", "(", "date", "(", "f", ")", ",", "compressed", ")", ",", "lat", ",", "lon", ")", "linkes_projected", "=", "map", "(", "lambda", "f", ":", "(", "f", ",", "linke", "(", "f", ")", ")", ",", "files", ")", "nc", ".", "close", "(", "root", ")", "return", "dict", "(", "linkes_projected", ")" ]
Return the linke turbidity projected to the lat lon matrix coordenates. Keyword arguments: filename -- the name of a netcdf file.
[ "Return", "the", "linke", "turbidity", "projected", "to", "the", "lat", "lon", "matrix", "coordenates", "." ]
0ba58fd623bf719d06d1a394d74f706f16d37295
https://github.com/gersolar/linketurbidity/blob/0ba58fd623bf719d06d1a394d74f706f16d37295/linketurbidity/instrument.py#L58-L73
246,354
ramrod-project/database-brain
schema/brain/queries/reads.py
get_targets
def get_targets(conn=None): """ get_brain_targets function from Brain.Targets table. :return: <generator> yields dict objects """ targets = RBT results = targets.run(conn) for item in results: yield item
python
def get_targets(conn=None): """ get_brain_targets function from Brain.Targets table. :return: <generator> yields dict objects """ targets = RBT results = targets.run(conn) for item in results: yield item
[ "def", "get_targets", "(", "conn", "=", "None", ")", ":", "targets", "=", "RBT", "results", "=", "targets", ".", "run", "(", "conn", ")", "for", "item", "in", "results", ":", "yield", "item" ]
get_brain_targets function from Brain.Targets table. :return: <generator> yields dict objects
[ "get_brain_targets", "function", "from", "Brain", ".", "Targets", "table", "." ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L49-L58
246,355
ramrod-project/database-brain
schema/brain/queries/reads.py
get_targets_by_plugin
def get_targets_by_plugin(plugin_name, conn=None): """ get_targets_by_plugin function from Brain.Targets table :return: <generator> yields dict objects """ targets = RBT results = targets.filter({PLUGIN_NAME_KEY: plugin_name}).run(conn) for item in results: yield item
python
def get_targets_by_plugin(plugin_name, conn=None): """ get_targets_by_plugin function from Brain.Targets table :return: <generator> yields dict objects """ targets = RBT results = targets.filter({PLUGIN_NAME_KEY: plugin_name}).run(conn) for item in results: yield item
[ "def", "get_targets_by_plugin", "(", "plugin_name", ",", "conn", "=", "None", ")", ":", "targets", "=", "RBT", "results", "=", "targets", ".", "filter", "(", "{", "PLUGIN_NAME_KEY", ":", "plugin_name", "}", ")", ".", "run", "(", "conn", ")", "for", "item", "in", "results", ":", "yield", "item" ]
get_targets_by_plugin function from Brain.Targets table :return: <generator> yields dict objects
[ "get_targets_by_plugin", "function", "from", "Brain", ".", "Targets", "table" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L63-L72
246,356
ramrod-project/database-brain
schema/brain/queries/reads.py
get_plugin_command
def get_plugin_command(plugin_name, command_name, conn=None): """ get_specific_command function queries a specific CommandName :param plugin_name: <str> PluginName :param command_name: <str> CommandName :return: <dict> """ commands = RPX.table(plugin_name).filter( {COMMAND_NAME_KEY: command_name}).run(conn) command = None for command in commands: continue # exhausting the cursor return command
python
def get_plugin_command(plugin_name, command_name, conn=None): """ get_specific_command function queries a specific CommandName :param plugin_name: <str> PluginName :param command_name: <str> CommandName :return: <dict> """ commands = RPX.table(plugin_name).filter( {COMMAND_NAME_KEY: command_name}).run(conn) command = None for command in commands: continue # exhausting the cursor return command
[ "def", "get_plugin_command", "(", "plugin_name", ",", "command_name", ",", "conn", "=", "None", ")", ":", "commands", "=", "RPX", ".", "table", "(", "plugin_name", ")", ".", "filter", "(", "{", "COMMAND_NAME_KEY", ":", "command_name", "}", ")", ".", "run", "(", "conn", ")", "command", "=", "None", "for", "command", "in", "commands", ":", "continue", "# exhausting the cursor", "return", "command" ]
get_specific_command function queries a specific CommandName :param plugin_name: <str> PluginName :param command_name: <str> CommandName :return: <dict>
[ "get_specific_command", "function", "queries", "a", "specific", "CommandName" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L93-L106
246,357
ramrod-project/database-brain
schema/brain/queries/reads.py
is_job_done
def is_job_done(job_id, conn=None): """ is_job_done function checks to if Brain.Jobs Status is 'Done' :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if """ result = False get_done = RBJ.get_all(DONE, index=STATUS_FIELD) for item in get_done.filter({ID_FIELD: job_id}).run(conn): result = item return result
python
def is_job_done(job_id, conn=None): """ is_job_done function checks to if Brain.Jobs Status is 'Done' :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if """ result = False get_done = RBJ.get_all(DONE, index=STATUS_FIELD) for item in get_done.filter({ID_FIELD: job_id}).run(conn): result = item return result
[ "def", "is_job_done", "(", "job_id", ",", "conn", "=", "None", ")", ":", "result", "=", "False", "get_done", "=", "RBJ", ".", "get_all", "(", "DONE", ",", "index", "=", "STATUS_FIELD", ")", "for", "item", "in", "get_done", ".", "filter", "(", "{", "ID_FIELD", ":", "job_id", "}", ")", ".", "run", "(", "conn", ")", ":", "result", "=", "item", "return", "result" ]
is_job_done function checks to if Brain.Jobs Status is 'Done' :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if
[ "is_job_done", "function", "checks", "to", "if", "Brain", ".", "Jobs", "Status", "is", "Done" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L125-L137
246,358
ramrod-project/database-brain
schema/brain/queries/reads.py
is_job_complete
def is_job_complete(job_id, conn=None): """ is_job_done function checks to if Brain.Jobs Status is Completed Completed is defined in statics as Done|Stopped|Error :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if """ result = False job = RBJ.get(job_id).run(conn) if job and job.get(STATUS_FIELD) in COMPLETED: result = job return result
python
def is_job_complete(job_id, conn=None): """ is_job_done function checks to if Brain.Jobs Status is Completed Completed is defined in statics as Done|Stopped|Error :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if """ result = False job = RBJ.get(job_id).run(conn) if job and job.get(STATUS_FIELD) in COMPLETED: result = job return result
[ "def", "is_job_complete", "(", "job_id", ",", "conn", "=", "None", ")", ":", "result", "=", "False", "job", "=", "RBJ", ".", "get", "(", "job_id", ")", ".", "run", "(", "conn", ")", "if", "job", "and", "job", ".", "get", "(", "STATUS_FIELD", ")", "in", "COMPLETED", ":", "result", "=", "job", "return", "result" ]
is_job_done function checks to if Brain.Jobs Status is Completed Completed is defined in statics as Done|Stopped|Error :param job_id: <str> id for the job :param conn: (optional)<connection> to run on :return: <dict> if job is done <false> if
[ "is_job_done", "function", "checks", "to", "if", "Brain", ".", "Jobs", "Status", "is", "Completed" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L142-L156
246,359
ramrod-project/database-brain
schema/brain/queries/reads.py
get_output_content
def get_output_content(job_id, max_size=1024, conn=None): """ returns the content buffer for a job_id if that job output exists :param job_id: <str> id for the job :param max_size: <int> truncate after [max_size] bytes :param conn: (optional)<connection> to run on :return: <str> or <bytes> """ content = None if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): # NEW check_status = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).run(conn) else: # OLD check_status = RBO.filter({OUTPUTJOB_FIELD: {ID_FIELD: job_id}}).run(conn) for status_item in check_status: content = _truncate_output_content_if_required(status_item, max_size) return content
python
def get_output_content(job_id, max_size=1024, conn=None): """ returns the content buffer for a job_id if that job output exists :param job_id: <str> id for the job :param max_size: <int> truncate after [max_size] bytes :param conn: (optional)<connection> to run on :return: <str> or <bytes> """ content = None if RBO.index_list().contains(IDX_OUTPUT_JOB_ID).run(conn): # NEW check_status = RBO.get_all(job_id, index=IDX_OUTPUT_JOB_ID).run(conn) else: # OLD check_status = RBO.filter({OUTPUTJOB_FIELD: {ID_FIELD: job_id}}).run(conn) for status_item in check_status: content = _truncate_output_content_if_required(status_item, max_size) return content
[ "def", "get_output_content", "(", "job_id", ",", "max_size", "=", "1024", ",", "conn", "=", "None", ")", ":", "content", "=", "None", "if", "RBO", ".", "index_list", "(", ")", ".", "contains", "(", "IDX_OUTPUT_JOB_ID", ")", ".", "run", "(", "conn", ")", ":", "# NEW", "check_status", "=", "RBO", ".", "get_all", "(", "job_id", ",", "index", "=", "IDX_OUTPUT_JOB_ID", ")", ".", "run", "(", "conn", ")", "else", ":", "# OLD", "check_status", "=", "RBO", ".", "filter", "(", "{", "OUTPUTJOB_FIELD", ":", "{", "ID_FIELD", ":", "job_id", "}", "}", ")", ".", "run", "(", "conn", ")", "for", "status_item", "in", "check_status", ":", "content", "=", "_truncate_output_content_if_required", "(", "status_item", ",", "max_size", ")", "return", "content" ]
returns the content buffer for a job_id if that job output exists :param job_id: <str> id for the job :param max_size: <int> truncate after [max_size] bytes :param conn: (optional)<connection> to run on :return: <str> or <bytes>
[ "returns", "the", "content", "buffer", "for", "a", "job_id", "if", "that", "job", "output", "exists" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L161-L179
246,360
ramrod-project/database-brain
schema/brain/queries/reads.py
get_job_by_id
def get_job_by_id(job_id, conn=None): """returns the job with the given id :param job_id: <str> id of the job :param conn: <rethinkdb.DefaultConnection> :return: <dict> job with the given id """ job = RBJ.get(job_id).run(conn) return job
python
def get_job_by_id(job_id, conn=None): """returns the job with the given id :param job_id: <str> id of the job :param conn: <rethinkdb.DefaultConnection> :return: <dict> job with the given id """ job = RBJ.get(job_id).run(conn) return job
[ "def", "get_job_by_id", "(", "job_id", ",", "conn", "=", "None", ")", ":", "job", "=", "RBJ", ".", "get", "(", "job_id", ")", ".", "run", "(", "conn", ")", "return", "job" ]
returns the job with the given id :param job_id: <str> id of the job :param conn: <rethinkdb.DefaultConnection> :return: <dict> job with the given id
[ "returns", "the", "job", "with", "the", "given", "id" ]
b024cb44f34cabb9d80af38271ddb65c25767083
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/reads.py#L276-L284
246,361
FujiMakoto/IPS-Vagrant
ips_vagrant/downloaders/downloader.py
DownloadManager._setup
def _setup(self): """ Run setup tasks after initialization """ self._populate_local() try: self._populate_latest() except Exception as e: self.log.exception('Unable to retrieve latest %s version information', self.meta_name) self._sort()
python
def _setup(self): """ Run setup tasks after initialization """ self._populate_local() try: self._populate_latest() except Exception as e: self.log.exception('Unable to retrieve latest %s version information', self.meta_name) self._sort()
[ "def", "_setup", "(", "self", ")", ":", "self", ".", "_populate_local", "(", ")", "try", ":", "self", ".", "_populate_latest", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "log", ".", "exception", "(", "'Unable to retrieve latest %s version information'", ",", "self", ".", "meta_name", ")", "self", ".", "_sort", "(", ")" ]
Run setup tasks after initialization
[ "Run", "setup", "tasks", "after", "initialization" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/downloaders/downloader.py#L36-L45
246,362
FujiMakoto/IPS-Vagrant
ips_vagrant/downloaders/downloader.py
DownloadManager._sort
def _sort(self): """ Sort versions by their version number """ self.versions = OrderedDict(sorted(self.versions.items(), key=lambda v: v[0]))
python
def _sort(self): """ Sort versions by their version number """ self.versions = OrderedDict(sorted(self.versions.items(), key=lambda v: v[0]))
[ "def", "_sort", "(", "self", ")", ":", "self", ".", "versions", "=", "OrderedDict", "(", "sorted", "(", "self", ".", "versions", ".", "items", "(", ")", ",", "key", "=", "lambda", "v", ":", "v", "[", "0", "]", ")", ")" ]
Sort versions by their version number
[ "Sort", "versions", "by", "their", "version", "number" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/downloaders/downloader.py#L47-L51
246,363
FujiMakoto/IPS-Vagrant
ips_vagrant/downloaders/downloader.py
DownloadManager._populate_local
def _populate_local(self): """ Populate version data for local archives """ archives = glob(os.path.join(self.path, '*.zip')) for archive in archives: try: version = self._read_zip(archive) self.versions[version.vtuple] = self.meta_class(self, version, filepath=archive) except BadZipfile as e: self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, archive) if self.dev_path: dev_archives = glob(os.path.join(self.dev_path, '*.zip')) dev_versions = [] for dev_archive in dev_archives: try: dev_versions.append((self._read_zip(dev_archive), dev_archive)) except BadZipfile as e: self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, dev_archive) if not dev_versions: self.log.debug('No development releases found') return dev_version = sorted(dev_versions, key=lambda v: v[0].vtuple).pop() self.dev_version = self.meta_class(self, dev_version[0], filepath=dev_version[1])
python
def _populate_local(self): """ Populate version data for local archives """ archives = glob(os.path.join(self.path, '*.zip')) for archive in archives: try: version = self._read_zip(archive) self.versions[version.vtuple] = self.meta_class(self, version, filepath=archive) except BadZipfile as e: self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, archive) if self.dev_path: dev_archives = glob(os.path.join(self.dev_path, '*.zip')) dev_versions = [] for dev_archive in dev_archives: try: dev_versions.append((self._read_zip(dev_archive), dev_archive)) except BadZipfile as e: self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, dev_archive) if not dev_versions: self.log.debug('No development releases found') return dev_version = sorted(dev_versions, key=lambda v: v[0].vtuple).pop() self.dev_version = self.meta_class(self, dev_version[0], filepath=dev_version[1])
[ "def", "_populate_local", "(", "self", ")", ":", "archives", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'*.zip'", ")", ")", "for", "archive", "in", "archives", ":", "try", ":", "version", "=", "self", ".", "_read_zip", "(", "archive", ")", "self", ".", "versions", "[", "version", ".", "vtuple", "]", "=", "self", ".", "meta_class", "(", "self", ",", "version", ",", "filepath", "=", "archive", ")", "except", "BadZipfile", "as", "e", ":", "self", ".", "log", ".", "warn", "(", "'Unreadable zip archive in versions directory (%s): %s'", ",", "e", ".", "message", ",", "archive", ")", "if", "self", ".", "dev_path", ":", "dev_archives", "=", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "dev_path", ",", "'*.zip'", ")", ")", "dev_versions", "=", "[", "]", "for", "dev_archive", "in", "dev_archives", ":", "try", ":", "dev_versions", ".", "append", "(", "(", "self", ".", "_read_zip", "(", "dev_archive", ")", ",", "dev_archive", ")", ")", "except", "BadZipfile", "as", "e", ":", "self", ".", "log", ".", "warn", "(", "'Unreadable zip archive in versions directory (%s): %s'", ",", "e", ".", "message", ",", "dev_archive", ")", "if", "not", "dev_versions", ":", "self", ".", "log", ".", "debug", "(", "'No development releases found'", ")", "return", "dev_version", "=", "sorted", "(", "dev_versions", ",", "key", "=", "lambda", "v", ":", "v", "[", "0", "]", ".", "vtuple", ")", ".", "pop", "(", ")", "self", ".", "dev_version", "=", "self", ".", "meta_class", "(", "self", ",", "dev_version", "[", "0", "]", ",", "filepath", "=", "dev_version", "[", "1", "]", ")" ]
Populate version data for local archives
[ "Populate", "version", "data", "for", "local", "archives" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/downloaders/downloader.py#L53-L79
246,364
FujiMakoto/IPS-Vagrant
ips_vagrant/downloaders/downloader.py
DownloadMeta.download
def download(self): """ Download the latest IPS release @return: Download file path @rtype: str """ # Submit a download request and test the response self.log.debug('Submitting request: %s', self.request) response = self.session.request(*self.request, stream=True) if response.status_code != 200: self.log.error('Download request failed: %d', response.status_code) raise HtmlParserError # If we're re-downloading this version, delete the old file if self.filepath and os.path.isfile(self.filepath): self.log.info('Removing old version download') os.remove(self.filepath) # Make sure our versions data directory exists if not os.path.isdir(self.basedir): self.log.debug('Creating versions data directory') os.makedirs(self.basedir, 0o755) # Process our file download vslug = self.version.vstring.replace(' ', '-') self.filepath = self.filepath or os.path.join(self.basedir, '{v}.zip'.format(v=vslug)) with open(self.filepath, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() self.log.info('Version {v} successfully downloaded to {fn}'.format(v=self.version, fn=self.filepath))
python
def download(self): """ Download the latest IPS release @return: Download file path @rtype: str """ # Submit a download request and test the response self.log.debug('Submitting request: %s', self.request) response = self.session.request(*self.request, stream=True) if response.status_code != 200: self.log.error('Download request failed: %d', response.status_code) raise HtmlParserError # If we're re-downloading this version, delete the old file if self.filepath and os.path.isfile(self.filepath): self.log.info('Removing old version download') os.remove(self.filepath) # Make sure our versions data directory exists if not os.path.isdir(self.basedir): self.log.debug('Creating versions data directory') os.makedirs(self.basedir, 0o755) # Process our file download vslug = self.version.vstring.replace(' ', '-') self.filepath = self.filepath or os.path.join(self.basedir, '{v}.zip'.format(v=vslug)) with open(self.filepath, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() self.log.info('Version {v} successfully downloaded to {fn}'.format(v=self.version, fn=self.filepath))
[ "def", "download", "(", "self", ")", ":", "# Submit a download request and test the response", "self", ".", "log", ".", "debug", "(", "'Submitting request: %s'", ",", "self", ".", "request", ")", "response", "=", "self", ".", "session", ".", "request", "(", "*", "self", ".", "request", ",", "stream", "=", "True", ")", "if", "response", ".", "status_code", "!=", "200", ":", "self", ".", "log", ".", "error", "(", "'Download request failed: %d'", ",", "response", ".", "status_code", ")", "raise", "HtmlParserError", "# If we're re-downloading this version, delete the old file", "if", "self", ".", "filepath", "and", "os", ".", "path", ".", "isfile", "(", "self", ".", "filepath", ")", ":", "self", ".", "log", ".", "info", "(", "'Removing old version download'", ")", "os", ".", "remove", "(", "self", ".", "filepath", ")", "# Make sure our versions data directory exists", "if", "not", "os", ".", "path", ".", "isdir", "(", "self", ".", "basedir", ")", ":", "self", ".", "log", ".", "debug", "(", "'Creating versions data directory'", ")", "os", ".", "makedirs", "(", "self", ".", "basedir", ",", "0o755", ")", "# Process our file download", "vslug", "=", "self", ".", "version", ".", "vstring", ".", "replace", "(", "' '", ",", "'-'", ")", "self", ".", "filepath", "=", "self", ".", "filepath", "or", "os", ".", "path", ".", "join", "(", "self", ".", "basedir", ",", "'{v}.zip'", ".", "format", "(", "v", "=", "vslug", ")", ")", "with", "open", "(", "self", ".", "filepath", ",", "'wb'", ")", "as", "f", ":", "for", "chunk", "in", "response", ".", "iter_content", "(", "chunk_size", "=", "1024", ")", ":", "if", "chunk", ":", "# filter out keep-alive new chunks", "f", ".", "write", "(", "chunk", ")", "f", ".", "flush", "(", ")", "self", ".", "log", ".", "info", "(", "'Version {v} successfully downloaded to {fn}'", ".", "format", "(", "v", "=", "self", ".", "version", ",", "fn", "=", "self", ".", "filepath", ")", ")" ]
Download the latest IPS release @return: Download file path @rtype: str
[ "Download", "the", "latest", "IPS", "release" ]
7b1d6d095034dd8befb026d9315ecc6494d52269
https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/downloaders/downloader.py#L147-L179
246,365
akatrevorjay/uninhibited
uninhibited/events.py
Event.remove_handlers_bound_to_instance
def remove_handlers_bound_to_instance(self, obj): """ Remove all handlers bound to given object instance. This is useful to remove all handler methods that are part of an instance. :param object obj: Remove handlers that are methods of this instance """ for handler in self.handlers: if handler.im_self == obj: self -= handler
python
def remove_handlers_bound_to_instance(self, obj): """ Remove all handlers bound to given object instance. This is useful to remove all handler methods that are part of an instance. :param object obj: Remove handlers that are methods of this instance """ for handler in self.handlers: if handler.im_self == obj: self -= handler
[ "def", "remove_handlers_bound_to_instance", "(", "self", ",", "obj", ")", ":", "for", "handler", "in", "self", ".", "handlers", ":", "if", "handler", ".", "im_self", "==", "obj", ":", "self", "-=", "handler" ]
Remove all handlers bound to given object instance. This is useful to remove all handler methods that are part of an instance. :param object obj: Remove handlers that are methods of this instance
[ "Remove", "all", "handlers", "bound", "to", "given", "object", "instance", ".", "This", "is", "useful", "to", "remove", "all", "handler", "methods", "that", "are", "part", "of", "an", "instance", "." ]
f23079fe61cf831fa274d3c60bda8076c571d3f1
https://github.com/akatrevorjay/uninhibited/blob/f23079fe61cf831fa274d3c60bda8076c571d3f1/uninhibited/events.py#L100-L109
246,366
akatrevorjay/uninhibited
uninhibited/events.py
PriorityEvent.add
def add(self, handler, priority=10): """ Add handler. :param callable handler: callable handler :return callable: The handler you added is given back so this can be used as a decorator. """ self.container.add_handler(handler, priority=priority) return handler
python
def add(self, handler, priority=10): """ Add handler. :param callable handler: callable handler :return callable: The handler you added is given back so this can be used as a decorator. """ self.container.add_handler(handler, priority=priority) return handler
[ "def", "add", "(", "self", ",", "handler", ",", "priority", "=", "10", ")", ":", "self", ".", "container", ".", "add_handler", "(", "handler", ",", "priority", "=", "priority", ")", "return", "handler" ]
Add handler. :param callable handler: callable handler :return callable: The handler you added is given back so this can be used as a decorator.
[ "Add", "handler", "." ]
f23079fe61cf831fa274d3c60bda8076c571d3f1
https://github.com/akatrevorjay/uninhibited/blob/f23079fe61cf831fa274d3c60bda8076c571d3f1/uninhibited/events.py#L165-L173
246,367
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.usage
def usage(self): """Print usage description for this program. Output is to standard out.""" print self.programName + " [options]", if self.maxArgs == -1 or self.maxArgs - self.minArgs > 1: print "[files..]" elif self.maxArgs - self.minArgs == 1: print "[file]" print print self.shortDescription print "Options:" for o in self.options: print "\t", ("-" + o.short + ", --" + o.long).ljust(15), ":", print o.description.replace("\t", "\\t").ljust(80)
python
def usage(self): """Print usage description for this program. Output is to standard out.""" print self.programName + " [options]", if self.maxArgs == -1 or self.maxArgs - self.minArgs > 1: print "[files..]" elif self.maxArgs - self.minArgs == 1: print "[file]" print print self.shortDescription print "Options:" for o in self.options: print "\t", ("-" + o.short + ", --" + o.long).ljust(15), ":", print o.description.replace("\t", "\\t").ljust(80)
[ "def", "usage", "(", "self", ")", ":", "print", "self", ".", "programName", "+", "\" [options]\"", ",", "if", "self", ".", "maxArgs", "==", "-", "1", "or", "self", ".", "maxArgs", "-", "self", ".", "minArgs", ">", "1", ":", "print", "\"[files..]\"", "elif", "self", ".", "maxArgs", "-", "self", ".", "minArgs", "==", "1", ":", "print", "\"[file]\"", "print", "print", "self", ".", "shortDescription", "print", "\"Options:\"", "for", "o", "in", "self", ".", "options", ":", "print", "\"\\t\"", ",", "(", "\"-\"", "+", "o", ".", "short", "+", "\", --\"", "+", "o", ".", "long", ")", ".", "ljust", "(", "15", ")", ",", "\":\"", ",", "print", "o", ".", "description", ".", "replace", "(", "\"\\t\"", ",", "\"\\\\t\"", ")", ".", "ljust", "(", "80", ")" ]
Print usage description for this program. Output is to standard out.
[ "Print", "usage", "description", "for", "this", "program", ".", "Output", "is", "to", "standard", "out", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L155-L169
246,368
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.parseCommandLine
def parseCommandLine(self, line): """ Parse the given command line and populate self with the values found. If the command line doesn't conform to the specification defined by this CLI object, this function prints a message to stdout indicating what was wrong, prints the program usage instructions and then exists the program :param line: list of tokens from the command line. Should have had program name removed - generally one would do this: sys.argv[1:] """ # separate arguments and options try: optlist, args = getopt.getopt(line, self._optlist(), self._longoptl()) except getopt.GetoptError, err: print str(err) self.usage() sys.exit(2) # parse options for opt, arg in optlist: opt = opt.lstrip("-") found = False for option in self.options: if option.short == opt or option.long == opt: option.value = option.type(arg) option.set = True found = True if not found: sys.stderr.write("unknown option: " + opt) self.usage() sys.exit(2) # check for special options specialOptions = False for opt in self.options: if opt.special and opt.isSet(): specialOptions = True # parse arguments if len(args) < self.minArgs and not specialOptions: err = (str(len(args)) + " input arguments found, but required at " + "least " + str(self.minArgs) + " arguments") sys.stderr.write(err) sys.stderr.write("\n\n") self.usage() sys.exit(2) else: self.args = args # check for required options for option in self.options: if option.isRequired() and not option.isSet() and not specialOptions: err = "required option \'" + str(option) + "\' is missing" sys.stderr.write(err) print "\n" self.usage() sys.exit(2)
python
def parseCommandLine(self, line): """ Parse the given command line and populate self with the values found. If the command line doesn't conform to the specification defined by this CLI object, this function prints a message to stdout indicating what was wrong, prints the program usage instructions and then exists the program :param line: list of tokens from the command line. Should have had program name removed - generally one would do this: sys.argv[1:] """ # separate arguments and options try: optlist, args = getopt.getopt(line, self._optlist(), self._longoptl()) except getopt.GetoptError, err: print str(err) self.usage() sys.exit(2) # parse options for opt, arg in optlist: opt = opt.lstrip("-") found = False for option in self.options: if option.short == opt or option.long == opt: option.value = option.type(arg) option.set = True found = True if not found: sys.stderr.write("unknown option: " + opt) self.usage() sys.exit(2) # check for special options specialOptions = False for opt in self.options: if opt.special and opt.isSet(): specialOptions = True # parse arguments if len(args) < self.minArgs and not specialOptions: err = (str(len(args)) + " input arguments found, but required at " + "least " + str(self.minArgs) + " arguments") sys.stderr.write(err) sys.stderr.write("\n\n") self.usage() sys.exit(2) else: self.args = args # check for required options for option in self.options: if option.isRequired() and not option.isSet() and not specialOptions: err = "required option \'" + str(option) + "\' is missing" sys.stderr.write(err) print "\n" self.usage() sys.exit(2)
[ "def", "parseCommandLine", "(", "self", ",", "line", ")", ":", "# separate arguments and options", "try", ":", "optlist", ",", "args", "=", "getopt", ".", "getopt", "(", "line", ",", "self", ".", "_optlist", "(", ")", ",", "self", ".", "_longoptl", "(", ")", ")", "except", "getopt", ".", "GetoptError", ",", "err", ":", "print", "str", "(", "err", ")", "self", ".", "usage", "(", ")", "sys", ".", "exit", "(", "2", ")", "# parse options", "for", "opt", ",", "arg", "in", "optlist", ":", "opt", "=", "opt", ".", "lstrip", "(", "\"-\"", ")", "found", "=", "False", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "short", "==", "opt", "or", "option", ".", "long", "==", "opt", ":", "option", ".", "value", "=", "option", ".", "type", "(", "arg", ")", "option", ".", "set", "=", "True", "found", "=", "True", "if", "not", "found", ":", "sys", ".", "stderr", ".", "write", "(", "\"unknown option: \"", "+", "opt", ")", "self", ".", "usage", "(", ")", "sys", ".", "exit", "(", "2", ")", "# check for special options", "specialOptions", "=", "False", "for", "opt", "in", "self", ".", "options", ":", "if", "opt", ".", "special", "and", "opt", ".", "isSet", "(", ")", ":", "specialOptions", "=", "True", "# parse arguments", "if", "len", "(", "args", ")", "<", "self", ".", "minArgs", "and", "not", "specialOptions", ":", "err", "=", "(", "str", "(", "len", "(", "args", ")", ")", "+", "\" input arguments found, but required at \"", "+", "\"least \"", "+", "str", "(", "self", ".", "minArgs", ")", "+", "\" arguments\"", ")", "sys", ".", "stderr", ".", "write", "(", "err", ")", "sys", ".", "stderr", ".", "write", "(", "\"\\n\\n\"", ")", "self", ".", "usage", "(", ")", "sys", ".", "exit", "(", "2", ")", "else", ":", "self", ".", "args", "=", "args", "# check for required options", "for", "option", "in", "self", ".", "options", ":", "if", "option", ".", "isRequired", "(", ")", "and", "not", "option", ".", "isSet", "(", ")", "and", "not", "specialOptions", ":", "err", "=", "\"required option \\'\"", "+", "str", "(", "option", ")", "+", "\"\\' is missing\"", "sys", ".", "stderr", ".", "write", "(", "err", ")", "print", "\"\\n\"", "self", ".", "usage", "(", ")", "sys", ".", "exit", "(", "2", ")" ]
Parse the given command line and populate self with the values found. If the command line doesn't conform to the specification defined by this CLI object, this function prints a message to stdout indicating what was wrong, prints the program usage instructions and then exists the program :param line: list of tokens from the command line. Should have had program name removed - generally one would do this: sys.argv[1:]
[ "Parse", "the", "given", "command", "line", "and", "populate", "self", "with", "the", "values", "found", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L171-L229
246,369
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.getOption
def getOption(self, name): """ Get the the Option object associated with the given name. :param name: the name of the option to retrieve; can be short or long name. :raise InterfaceException: if the named option doesn't exist. """ name = name.strip() for o in self.options: if o.short == name or o.long == name: return o raise InterfaceException("No such option: " + name)
python
def getOption(self, name): """ Get the the Option object associated with the given name. :param name: the name of the option to retrieve; can be short or long name. :raise InterfaceException: if the named option doesn't exist. """ name = name.strip() for o in self.options: if o.short == name or o.long == name: return o raise InterfaceException("No such option: " + name)
[ "def", "getOption", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "for", "o", "in", "self", ".", "options", ":", "if", "o", ".", "short", "==", "name", "or", "o", ".", "long", "==", "name", ":", "return", "o", "raise", "InterfaceException", "(", "\"No such option: \"", "+", "name", ")" ]
Get the the Option object associated with the given name. :param name: the name of the option to retrieve; can be short or long name. :raise InterfaceException: if the named option doesn't exist.
[ "Get", "the", "the", "Option", "object", "associated", "with", "the", "given", "name", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L231-L242
246,370
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.hasOption
def hasOption(self, name): """ Check whether this CLI has an option with a given name. :param name: the name of the option to check; can be short or long name. :return: true if an option exists in the UI for the given name """ name = name.strip() for o in self.options: if o.short == name or o.long == name: return True return False
python
def hasOption(self, name): """ Check whether this CLI has an option with a given name. :param name: the name of the option to check; can be short or long name. :return: true if an option exists in the UI for the given name """ name = name.strip() for o in self.options: if o.short == name or o.long == name: return True return False
[ "def", "hasOption", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "for", "o", "in", "self", ".", "options", ":", "if", "o", ".", "short", "==", "name", "or", "o", ".", "long", "==", "name", ":", "return", "True", "return", "False" ]
Check whether this CLI has an option with a given name. :param name: the name of the option to check; can be short or long name. :return: true if an option exists in the UI for the given name
[ "Check", "whether", "this", "CLI", "has", "an", "option", "with", "a", "given", "name", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L253-L264
246,371
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.addOption
def addOption(self, o): """ Add a new Option to this CLI. :param o: the option to add :raise InterfaceException: if an option with that name already exists. """ if self.hasOption(o.short): raise InterfaceException("Failed adding option - already have " + str(o)) self.options.append(o)
python
def addOption(self, o): """ Add a new Option to this CLI. :param o: the option to add :raise InterfaceException: if an option with that name already exists. """ if self.hasOption(o.short): raise InterfaceException("Failed adding option - already have " + str(o)) self.options.append(o)
[ "def", "addOption", "(", "self", ",", "o", ")", ":", "if", "self", ".", "hasOption", "(", "o", ".", "short", ")", ":", "raise", "InterfaceException", "(", "\"Failed adding option - already have \"", "+", "str", "(", "o", ")", ")", "self", ".", "options", ".", "append", "(", "o", ")" ]
Add a new Option to this CLI. :param o: the option to add :raise InterfaceException: if an option with that name already exists.
[ "Add", "a", "new", "Option", "to", "this", "CLI", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L266-L275
246,372
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.optionIsSet
def optionIsSet(self, name): """ Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user """ name = name.strip() if not self.hasOption(name): return False return self.getOption(name).isSet()
python
def optionIsSet(self, name): """ Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user """ name = name.strip() if not self.hasOption(name): return False return self.getOption(name).isSet()
[ "def", "optionIsSet", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "if", "not", "self", ".", "hasOption", "(", "name", ")", ":", "return", "False", "return", "self", ".", "getOption", "(", "name", ")", ".", "isSet", "(", ")" ]
Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user
[ "Check", "whether", "an", "option", "with", "a", "given", "name", "exists", "and", "has", "been", "set", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L277-L288
246,373
pjuren/pyokit
src/pyokit/interface/cli.py
CLI.getArgument
def getArgument(self, num): """ Get the num^th argument. :param num: Which argument to get; indexing here is from 0. :return: The num^th agument; arguments are always parsed as strings, so this will be a string. :raise InterfaceException: if there are fewer than num + 1 arguments. """ if not self.hasArgument(num): raise InterfaceException("Failed to retrieve argument " + str(num) + " -- not enough arguments provided") return self.args[num]
python
def getArgument(self, num): """ Get the num^th argument. :param num: Which argument to get; indexing here is from 0. :return: The num^th agument; arguments are always parsed as strings, so this will be a string. :raise InterfaceException: if there are fewer than num + 1 arguments. """ if not self.hasArgument(num): raise InterfaceException("Failed to retrieve argument " + str(num) + " -- not enough arguments provided") return self.args[num]
[ "def", "getArgument", "(", "self", ",", "num", ")", ":", "if", "not", "self", ".", "hasArgument", "(", "num", ")", ":", "raise", "InterfaceException", "(", "\"Failed to retrieve argument \"", "+", "str", "(", "num", ")", "+", "\" -- not enough arguments provided\"", ")", "return", "self", ".", "args", "[", "num", "]" ]
Get the num^th argument. :param num: Which argument to get; indexing here is from 0. :return: The num^th agument; arguments are always parsed as strings, so this will be a string. :raise InterfaceException: if there are fewer than num + 1 arguments.
[ "Get", "the", "num^th", "argument", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L301-L313
246,374
pjuren/pyokit
src/pyokit/interface/cli.py
CLI._optlist
def _optlist(self): """Get a string representation of the options in short format.""" res = "" for o in self.options: res += o.short if o.argName is not None: res += ":" return res
python
def _optlist(self): """Get a string representation of the options in short format.""" res = "" for o in self.options: res += o.short if o.argName is not None: res += ":" return res
[ "def", "_optlist", "(", "self", ")", ":", "res", "=", "\"\"", "for", "o", "in", "self", ".", "options", ":", "res", "+=", "o", ".", "short", "if", "o", ".", "argName", "is", "not", "None", ":", "res", "+=", "\":\"", "return", "res" ]
Get a string representation of the options in short format.
[ "Get", "a", "string", "representation", "of", "the", "options", "in", "short", "format", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L324-L331
246,375
pjuren/pyokit
src/pyokit/interface/cli.py
CLI._longoptl
def _longoptl(self): """Get a list of string representations of the options in long format.""" res = [] for o in self.options: nm = o.long if o.argName is not None: nm += "=" res.append(nm) return res
python
def _longoptl(self): """Get a list of string representations of the options in long format.""" res = [] for o in self.options: nm = o.long if o.argName is not None: nm += "=" res.append(nm) return res
[ "def", "_longoptl", "(", "self", ")", ":", "res", "=", "[", "]", "for", "o", "in", "self", ".", "options", ":", "nm", "=", "o", ".", "long", "if", "o", ".", "argName", "is", "not", "None", ":", "nm", "+=", "\"=\"", "res", ".", "append", "(", "nm", ")", "return", "res" ]
Get a list of string representations of the options in long format.
[ "Get", "a", "list", "of", "string", "representations", "of", "the", "options", "in", "long", "format", "." ]
fddae123b5d817daa39496183f19c000d9c3791f
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/interface/cli.py#L333-L341
246,376
Tinche/django-bower-cache
registry/models.py
ClonedRepo.pull
def pull(self): """Pull from the origin.""" repo_root = settings.REPO_ROOT pull_from_origin(join(repo_root, self.name))
python
def pull(self): """Pull from the origin.""" repo_root = settings.REPO_ROOT pull_from_origin(join(repo_root, self.name))
[ "def", "pull", "(", "self", ")", ":", "repo_root", "=", "settings", ".", "REPO_ROOT", "pull_from_origin", "(", "join", "(", "repo_root", ",", "self", ".", "name", ")", ")" ]
Pull from the origin.
[ "Pull", "from", "the", "origin", "." ]
5245b2ee80c33c09d85ce0bf8f047825d9df2118
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/models.py#L40-L43
246,377
Tinche/django-bower-cache
registry/models.py
ClonedRepo.to_package
def to_package(self, repo_url): """Return the package representation of this repo.""" return Package(name=self.name, url=repo_url + self.name)
python
def to_package(self, repo_url): """Return the package representation of this repo.""" return Package(name=self.name, url=repo_url + self.name)
[ "def", "to_package", "(", "self", ",", "repo_url", ")", ":", "return", "Package", "(", "name", "=", "self", ".", "name", ",", "url", "=", "repo_url", "+", "self", ".", "name", ")" ]
Return the package representation of this repo.
[ "Return", "the", "package", "representation", "of", "this", "repo", "." ]
5245b2ee80c33c09d85ce0bf8f047825d9df2118
https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/models.py#L45-L47
246,378
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/utils.py
get_storage
def get_storage(clear=False): """helper function to get annotation storage on the portal :param clear: If true is passed in, annotations will be cleared :returns: portal annotations :rtype: IAnnotations """ portal = getUtility(ISiteRoot) annotations = IAnnotations(portal) if ANNOTATION_KEY not in annotations or clear: annotations[ANNOTATION_KEY] = OOBTree() return annotations[ANNOTATION_KEY]
python
def get_storage(clear=False): """helper function to get annotation storage on the portal :param clear: If true is passed in, annotations will be cleared :returns: portal annotations :rtype: IAnnotations """ portal = getUtility(ISiteRoot) annotations = IAnnotations(portal) if ANNOTATION_KEY not in annotations or clear: annotations[ANNOTATION_KEY] = OOBTree() return annotations[ANNOTATION_KEY]
[ "def", "get_storage", "(", "clear", "=", "False", ")", ":", "portal", "=", "getUtility", "(", "ISiteRoot", ")", "annotations", "=", "IAnnotations", "(", "portal", ")", "if", "ANNOTATION_KEY", "not", "in", "annotations", "or", "clear", ":", "annotations", "[", "ANNOTATION_KEY", "]", "=", "OOBTree", "(", ")", "return", "annotations", "[", "ANNOTATION_KEY", "]" ]
helper function to get annotation storage on the portal :param clear: If true is passed in, annotations will be cleared :returns: portal annotations :rtype: IAnnotations
[ "helper", "function", "to", "get", "annotation", "storage", "on", "the", "portal" ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/utils.py#L33-L45
246,379
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/utils.py
send_email
def send_email(recipient, subject, message, sender="[email protected]"): """helper function to send an email with the sender preset """ try: api.portal.send_email( recipient=recipient, sender=sender, subject=subject, body=message) except ValueError, e: log.error("MailHost error: {0}".format(e))
python
def send_email(recipient, subject, message, sender="[email protected]"): """helper function to send an email with the sender preset """ try: api.portal.send_email( recipient=recipient, sender=sender, subject=subject, body=message) except ValueError, e: log.error("MailHost error: {0}".format(e))
[ "def", "send_email", "(", "recipient", ",", "subject", ",", "message", ",", "sender", "=", "\"[email protected]\"", ")", ":", "try", ":", "api", ".", "portal", ".", "send_email", "(", "recipient", "=", "recipient", ",", "sender", "=", "sender", ",", "subject", "=", "subject", ",", "body", "=", "message", ")", "except", "ValueError", ",", "e", ":", "log", ".", "error", "(", "\"MailHost error: {0}\"", ".", "format", "(", "e", ")", ")" ]
helper function to send an email with the sender preset
[ "helper", "function", "to", "send", "an", "email", "with", "the", "sender", "preset" ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/utils.py#L48-L62
246,380
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/utils.py
parent_workspace
def parent_workspace(context): """ Return containing workspace Returns None if not found. """ if IWorkspaceFolder.providedBy(context): return context for parent in aq_chain(context): if IWorkspaceFolder.providedBy(parent): return parent
python
def parent_workspace(context): """ Return containing workspace Returns None if not found. """ if IWorkspaceFolder.providedBy(context): return context for parent in aq_chain(context): if IWorkspaceFolder.providedBy(parent): return parent
[ "def", "parent_workspace", "(", "context", ")", ":", "if", "IWorkspaceFolder", ".", "providedBy", "(", "context", ")", ":", "return", "context", "for", "parent", "in", "aq_chain", "(", "context", ")", ":", "if", "IWorkspaceFolder", ".", "providedBy", "(", "parent", ")", ":", "return", "parent" ]
Return containing workspace Returns None if not found.
[ "Return", "containing", "workspace", "Returns", "None", "if", "not", "found", "." ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/utils.py#L65-L73
246,381
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/utils.py
get_workspace_activities
def get_workspace_activities(brain, limit=1): """ Return the workspace activities sorted by reverse chronological order Regarding the time value: - the datetime value contains the time in international format (machine readable) - the title value contains the absolute date and time of the post """ mb = queryUtility(IMicroblogTool) items = mb.context_values(brain.getObject(), limit=limit) return [ { 'subject': item.creator, 'verb': 'published', 'object': item.text, 'time': { 'datetime': item.date.strftime('%Y-%m-%d'), 'title': item.date.strftime('%d %B %Y, %H:%M'), } } for item in items ]
python
def get_workspace_activities(brain, limit=1): """ Return the workspace activities sorted by reverse chronological order Regarding the time value: - the datetime value contains the time in international format (machine readable) - the title value contains the absolute date and time of the post """ mb = queryUtility(IMicroblogTool) items = mb.context_values(brain.getObject(), limit=limit) return [ { 'subject': item.creator, 'verb': 'published', 'object': item.text, 'time': { 'datetime': item.date.strftime('%Y-%m-%d'), 'title': item.date.strftime('%d %B %Y, %H:%M'), } } for item in items ]
[ "def", "get_workspace_activities", "(", "brain", ",", "limit", "=", "1", ")", ":", "mb", "=", "queryUtility", "(", "IMicroblogTool", ")", "items", "=", "mb", ".", "context_values", "(", "brain", ".", "getObject", "(", ")", ",", "limit", "=", "limit", ")", "return", "[", "{", "'subject'", ":", "item", ".", "creator", ",", "'verb'", ":", "'published'", ",", "'object'", ":", "item", ".", "text", ",", "'time'", ":", "{", "'datetime'", ":", "item", ".", "date", ".", "strftime", "(", "'%Y-%m-%d'", ")", ",", "'title'", ":", "item", ".", "date", ".", "strftime", "(", "'%d %B %Y, %H:%M'", ")", ",", "}", "}", "for", "item", "in", "items", "]" ]
Return the workspace activities sorted by reverse chronological order Regarding the time value: - the datetime value contains the time in international format (machine readable) - the title value contains the absolute date and time of the post
[ "Return", "the", "workspace", "activities", "sorted", "by", "reverse", "chronological", "order" ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/utils.py#L89-L110
246,382
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/utils.py
my_workspaces
def my_workspaces(context): """ The list of my workspaces """ pc = api.portal.get_tool('portal_catalog') brains = pc( portal_type="ploneintranet.workspace.workspacefolder", sort_on="modified", sort_order="reversed", ) workspaces = [ { 'id': brain.getId, 'title': brain.Title, 'description': brain.Description, 'url': brain.getURL(), 'activities': get_workspace_activities(brain), 'class': escape_id_to_class(brain.getId), } for brain in brains ] return workspaces
python
def my_workspaces(context): """ The list of my workspaces """ pc = api.portal.get_tool('portal_catalog') brains = pc( portal_type="ploneintranet.workspace.workspacefolder", sort_on="modified", sort_order="reversed", ) workspaces = [ { 'id': brain.getId, 'title': brain.Title, 'description': brain.Description, 'url': brain.getURL(), 'activities': get_workspace_activities(brain), 'class': escape_id_to_class(brain.getId), } for brain in brains ] return workspaces
[ "def", "my_workspaces", "(", "context", ")", ":", "pc", "=", "api", ".", "portal", ".", "get_tool", "(", "'portal_catalog'", ")", "brains", "=", "pc", "(", "portal_type", "=", "\"ploneintranet.workspace.workspacefolder\"", ",", "sort_on", "=", "\"modified\"", ",", "sort_order", "=", "\"reversed\"", ",", ")", "workspaces", "=", "[", "{", "'id'", ":", "brain", ".", "getId", ",", "'title'", ":", "brain", ".", "Title", ",", "'description'", ":", "brain", ".", "Description", ",", "'url'", ":", "brain", ".", "getURL", "(", ")", ",", "'activities'", ":", "get_workspace_activities", "(", "brain", ")", ",", "'class'", ":", "escape_id_to_class", "(", "brain", ".", "getId", ")", ",", "}", "for", "brain", "in", "brains", "]", "return", "workspaces" ]
The list of my workspaces
[ "The", "list", "of", "my", "workspaces" ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/utils.py#L113-L132
246,383
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/utils.py
existing_users
def existing_users(context): """ Look up the full user details for current workspace members """ members = IWorkspace(context).members info = [] for userid, details in members.items(): user = api.user.get(userid) if user is None: continue user = user.getUser() title = user.getProperty('fullname') or user.getId() or userid # XXX tbd, we don't know what a persons description is, yet description = _(u'Here we could have a nice status of this person') classes = description and 'has-description' or 'has-no-description' portal = api.portal.get() portrait = '%s/portal_memberdata/portraits/%s' % \ (portal.absolute_url(), userid) info.append( dict( id=userid, title=title, description=description, portrait=portrait, cls=classes, member=True, admin='Admins' in details['groups'], ) ) return info
python
def existing_users(context): """ Look up the full user details for current workspace members """ members = IWorkspace(context).members info = [] for userid, details in members.items(): user = api.user.get(userid) if user is None: continue user = user.getUser() title = user.getProperty('fullname') or user.getId() or userid # XXX tbd, we don't know what a persons description is, yet description = _(u'Here we could have a nice status of this person') classes = description and 'has-description' or 'has-no-description' portal = api.portal.get() portrait = '%s/portal_memberdata/portraits/%s' % \ (portal.absolute_url(), userid) info.append( dict( id=userid, title=title, description=description, portrait=portrait, cls=classes, member=True, admin='Admins' in details['groups'], ) ) return info
[ "def", "existing_users", "(", "context", ")", ":", "members", "=", "IWorkspace", "(", "context", ")", ".", "members", "info", "=", "[", "]", "for", "userid", ",", "details", "in", "members", ".", "items", "(", ")", ":", "user", "=", "api", ".", "user", ".", "get", "(", "userid", ")", "if", "user", "is", "None", ":", "continue", "user", "=", "user", ".", "getUser", "(", ")", "title", "=", "user", ".", "getProperty", "(", "'fullname'", ")", "or", "user", ".", "getId", "(", ")", "or", "userid", "# XXX tbd, we don't know what a persons description is, yet", "description", "=", "_", "(", "u'Here we could have a nice status of this person'", ")", "classes", "=", "description", "and", "'has-description'", "or", "'has-no-description'", "portal", "=", "api", ".", "portal", ".", "get", "(", ")", "portrait", "=", "'%s/portal_memberdata/portraits/%s'", "%", "(", "portal", ".", "absolute_url", "(", ")", ",", "userid", ")", "info", ".", "append", "(", "dict", "(", "id", "=", "userid", ",", "title", "=", "title", ",", "description", "=", "description", ",", "portrait", "=", "portrait", ",", "cls", "=", "classes", ",", "member", "=", "True", ",", "admin", "=", "'Admins'", "in", "details", "[", "'groups'", "]", ",", ")", ")", "return", "info" ]
Look up the full user details for current workspace members
[ "Look", "up", "the", "full", "user", "details", "for", "current", "workspace", "members" ]
a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/utils.py#L135-L165
246,384
sbusard/wagoner
wagoner/utils.py
random_weighted_choice
def random_weighted_choice(choices): """ Return a random key of choices, weighted by their value. :param choices: a dictionary of keys and positive integer pairs; :return: a random key of choices. """ choices, weights = zip(*choices.items()) cumdist = list(accumulate(weights)) x = random.random() * cumdist[-1] element = bisect.bisect(cumdist, x) return choices[element]
python
def random_weighted_choice(choices): """ Return a random key of choices, weighted by their value. :param choices: a dictionary of keys and positive integer pairs; :return: a random key of choices. """ choices, weights = zip(*choices.items()) cumdist = list(accumulate(weights)) x = random.random() * cumdist[-1] element = bisect.bisect(cumdist, x) return choices[element]
[ "def", "random_weighted_choice", "(", "choices", ")", ":", "choices", ",", "weights", "=", "zip", "(", "*", "choices", ".", "items", "(", ")", ")", "cumdist", "=", "list", "(", "accumulate", "(", "weights", ")", ")", "x", "=", "random", ".", "random", "(", ")", "*", "cumdist", "[", "-", "1", "]", "element", "=", "bisect", ".", "bisect", "(", "cumdist", ",", "x", ")", "return", "choices", "[", "element", "]" ]
Return a random key of choices, weighted by their value. :param choices: a dictionary of keys and positive integer pairs; :return: a random key of choices.
[ "Return", "a", "random", "key", "of", "choices", "weighted", "by", "their", "value", "." ]
7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b
https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/utils.py#L62-L73
246,385
sbusard/wagoner
wagoner/utils.py
extract_words
def extract_words(lines): """ Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of lines. """ for line in lines: for word in re.findall(r"\w+", line): yield word
python
def extract_words(lines): """ Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of lines. """ for line in lines: for word in re.findall(r"\w+", line): yield word
[ "def", "extract_words", "(", "lines", ")", ":", "for", "line", "in", "lines", ":", "for", "word", "in", "re", ".", "findall", "(", "r\"\\w+\"", ",", "line", ")", ":", "yield", "word" ]
Extract from the given iterable of lines the list of words. :param lines: an iterable of lines; :return: a generator of words of lines.
[ "Extract", "from", "the", "given", "iterable", "of", "lines", "the", "list", "of", "words", "." ]
7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b
https://github.com/sbusard/wagoner/blob/7f83d66bbd0e009e4d4232ffdf319bd5a2a5683b/wagoner/utils.py#L76-L85
246,386
minhhoit/yacms
yacms/utils/html.py
absolute_urls
def absolute_urls(html): """ Converts relative URLs into absolute URLs. Used for RSS feeds to provide more complete HTML for item descriptions, but could also be used as a general richtext filter. """ from bs4 import BeautifulSoup from yacms.core.request import current_request request = current_request() if request is not None: dom = BeautifulSoup(html, "html.parser") for tag, attr in ABSOLUTE_URL_TAGS.items(): for node in dom.findAll(tag): url = node.get(attr, "") if url: node[attr] = request.build_absolute_uri(url) html = str(dom) return html
python
def absolute_urls(html): """ Converts relative URLs into absolute URLs. Used for RSS feeds to provide more complete HTML for item descriptions, but could also be used as a general richtext filter. """ from bs4 import BeautifulSoup from yacms.core.request import current_request request = current_request() if request is not None: dom = BeautifulSoup(html, "html.parser") for tag, attr in ABSOLUTE_URL_TAGS.items(): for node in dom.findAll(tag): url = node.get(attr, "") if url: node[attr] = request.build_absolute_uri(url) html = str(dom) return html
[ "def", "absolute_urls", "(", "html", ")", ":", "from", "bs4", "import", "BeautifulSoup", "from", "yacms", ".", "core", ".", "request", "import", "current_request", "request", "=", "current_request", "(", ")", "if", "request", "is", "not", "None", ":", "dom", "=", "BeautifulSoup", "(", "html", ",", "\"html.parser\"", ")", "for", "tag", ",", "attr", "in", "ABSOLUTE_URL_TAGS", ".", "items", "(", ")", ":", "for", "node", "in", "dom", ".", "findAll", "(", "tag", ")", ":", "url", "=", "node", ".", "get", "(", "attr", ",", "\"\"", ")", "if", "url", ":", "node", "[", "attr", "]", "=", "request", ".", "build_absolute_uri", "(", "url", ")", "html", "=", "str", "(", "dom", ")", "return", "html" ]
Converts relative URLs into absolute URLs. Used for RSS feeds to provide more complete HTML for item descriptions, but could also be used as a general richtext filter.
[ "Converts", "relative", "URLs", "into", "absolute", "URLs", ".", "Used", "for", "RSS", "feeds", "to", "provide", "more", "complete", "HTML", "for", "item", "descriptions", "but", "could", "also", "be", "used", "as", "a", "general", "richtext", "filter", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/html.py#L40-L59
246,387
minhhoit/yacms
yacms/utils/html.py
escape
def escape(html): """ Escapes HTML according to the rules defined by the settings ``RICHTEXT_FILTER_LEVEL``, ``RICHTEXT_ALLOWED_TAGS``, ``RICHTEXT_ALLOWED_ATTRIBUTES``, ``RICHTEXT_ALLOWED_STYLES``. """ from yacms.conf import settings from yacms.core import defaults if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_NONE: return html tags = settings.RICHTEXT_ALLOWED_TAGS attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES styles = settings.RICHTEXT_ALLOWED_STYLES if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_LOW: tags += LOW_FILTER_TAGS attrs += LOW_FILTER_ATTRS return clean(html, tags=tags, attributes=attrs, strip=True, strip_comments=False, styles=styles)
python
def escape(html): """ Escapes HTML according to the rules defined by the settings ``RICHTEXT_FILTER_LEVEL``, ``RICHTEXT_ALLOWED_TAGS``, ``RICHTEXT_ALLOWED_ATTRIBUTES``, ``RICHTEXT_ALLOWED_STYLES``. """ from yacms.conf import settings from yacms.core import defaults if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_NONE: return html tags = settings.RICHTEXT_ALLOWED_TAGS attrs = settings.RICHTEXT_ALLOWED_ATTRIBUTES styles = settings.RICHTEXT_ALLOWED_STYLES if settings.RICHTEXT_FILTER_LEVEL == defaults.RICHTEXT_FILTER_LEVEL_LOW: tags += LOW_FILTER_TAGS attrs += LOW_FILTER_ATTRS return clean(html, tags=tags, attributes=attrs, strip=True, strip_comments=False, styles=styles)
[ "def", "escape", "(", "html", ")", ":", "from", "yacms", ".", "conf", "import", "settings", "from", "yacms", ".", "core", "import", "defaults", "if", "settings", ".", "RICHTEXT_FILTER_LEVEL", "==", "defaults", ".", "RICHTEXT_FILTER_LEVEL_NONE", ":", "return", "html", "tags", "=", "settings", ".", "RICHTEXT_ALLOWED_TAGS", "attrs", "=", "settings", ".", "RICHTEXT_ALLOWED_ATTRIBUTES", "styles", "=", "settings", ".", "RICHTEXT_ALLOWED_STYLES", "if", "settings", ".", "RICHTEXT_FILTER_LEVEL", "==", "defaults", ".", "RICHTEXT_FILTER_LEVEL_LOW", ":", "tags", "+=", "LOW_FILTER_TAGS", "attrs", "+=", "LOW_FILTER_ATTRS", "return", "clean", "(", "html", ",", "tags", "=", "tags", ",", "attributes", "=", "attrs", ",", "strip", "=", "True", ",", "strip_comments", "=", "False", ",", "styles", "=", "styles", ")" ]
Escapes HTML according to the rules defined by the settings ``RICHTEXT_FILTER_LEVEL``, ``RICHTEXT_ALLOWED_TAGS``, ``RICHTEXT_ALLOWED_ATTRIBUTES``, ``RICHTEXT_ALLOWED_STYLES``.
[ "Escapes", "HTML", "according", "to", "the", "rules", "defined", "by", "the", "settings", "RICHTEXT_FILTER_LEVEL", "RICHTEXT_ALLOWED_TAGS", "RICHTEXT_ALLOWED_ATTRIBUTES", "RICHTEXT_ALLOWED_STYLES", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/html.py#L86-L103
246,388
minhhoit/yacms
yacms/utils/html.py
thumbnails
def thumbnails(html): """ Given a HTML string, converts paths in img tags to thumbnail paths, using yacms's ``thumbnail`` template tag. Used as one of the default values in the ``RICHTEXT_FILTERS`` setting. """ from django.conf import settings from bs4 import BeautifulSoup from yacms.core.templatetags.yacms_tags import thumbnail # If MEDIA_URL isn't in the HTML string, there aren't any # images to replace, so bail early. if settings.MEDIA_URL.lower() not in html.lower(): return html dom = BeautifulSoup(html, "html.parser") for img in dom.findAll("img"): src = img.get("src", "") src_in_media = src.lower().startswith(settings.MEDIA_URL.lower()) width = img.get("width") height = img.get("height") if src_in_media and width and height: img["src"] = settings.MEDIA_URL + thumbnail(src, width, height) # BS adds closing br tags, which the browser interprets as br tags. return str(dom).replace("</br>", "")
python
def thumbnails(html): """ Given a HTML string, converts paths in img tags to thumbnail paths, using yacms's ``thumbnail`` template tag. Used as one of the default values in the ``RICHTEXT_FILTERS`` setting. """ from django.conf import settings from bs4 import BeautifulSoup from yacms.core.templatetags.yacms_tags import thumbnail # If MEDIA_URL isn't in the HTML string, there aren't any # images to replace, so bail early. if settings.MEDIA_URL.lower() not in html.lower(): return html dom = BeautifulSoup(html, "html.parser") for img in dom.findAll("img"): src = img.get("src", "") src_in_media = src.lower().startswith(settings.MEDIA_URL.lower()) width = img.get("width") height = img.get("height") if src_in_media and width and height: img["src"] = settings.MEDIA_URL + thumbnail(src, width, height) # BS adds closing br tags, which the browser interprets as br tags. return str(dom).replace("</br>", "")
[ "def", "thumbnails", "(", "html", ")", ":", "from", "django", ".", "conf", "import", "settings", "from", "bs4", "import", "BeautifulSoup", "from", "yacms", ".", "core", ".", "templatetags", ".", "yacms_tags", "import", "thumbnail", "# If MEDIA_URL isn't in the HTML string, there aren't any", "# images to replace, so bail early.", "if", "settings", ".", "MEDIA_URL", ".", "lower", "(", ")", "not", "in", "html", ".", "lower", "(", ")", ":", "return", "html", "dom", "=", "BeautifulSoup", "(", "html", ",", "\"html.parser\"", ")", "for", "img", "in", "dom", ".", "findAll", "(", "\"img\"", ")", ":", "src", "=", "img", ".", "get", "(", "\"src\"", ",", "\"\"", ")", "src_in_media", "=", "src", ".", "lower", "(", ")", ".", "startswith", "(", "settings", ".", "MEDIA_URL", ".", "lower", "(", ")", ")", "width", "=", "img", ".", "get", "(", "\"width\"", ")", "height", "=", "img", ".", "get", "(", "\"height\"", ")", "if", "src_in_media", "and", "width", "and", "height", ":", "img", "[", "\"src\"", "]", "=", "settings", ".", "MEDIA_URL", "+", "thumbnail", "(", "src", ",", "width", ",", "height", ")", "# BS adds closing br tags, which the browser interprets as br tags.", "return", "str", "(", "dom", ")", ".", "replace", "(", "\"</br>\"", ",", "\"\"", ")" ]
Given a HTML string, converts paths in img tags to thumbnail paths, using yacms's ``thumbnail`` template tag. Used as one of the default values in the ``RICHTEXT_FILTERS`` setting.
[ "Given", "a", "HTML", "string", "converts", "paths", "in", "img", "tags", "to", "thumbnail", "paths", "using", "yacms", "s", "thumbnail", "template", "tag", ".", "Used", "as", "one", "of", "the", "default", "values", "in", "the", "RICHTEXT_FILTERS", "setting", "." ]
2921b706b7107c6e8c5f2bbf790ff11f85a2167f
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/utils/html.py#L106-L130
246,389
rackerlabs/rackspace-python-neutronclient
neutronclient/client.py
HTTPClient.request
def request(self, url, method, body=None, headers=None, **kwargs): """Request without authentication.""" content_type = kwargs.pop('content_type', None) or 'application/json' headers = headers or {} headers.setdefault('Accept', content_type) if body: headers.setdefault('Content-Type', content_type) headers['User-Agent'] = self.USER_AGENT resp = requests.request( method, url, data=body, headers=headers, verify=self.verify_cert, timeout=self.timeout, **kwargs) return resp, resp.text
python
def request(self, url, method, body=None, headers=None, **kwargs): """Request without authentication.""" content_type = kwargs.pop('content_type', None) or 'application/json' headers = headers or {} headers.setdefault('Accept', content_type) if body: headers.setdefault('Content-Type', content_type) headers['User-Agent'] = self.USER_AGENT resp = requests.request( method, url, data=body, headers=headers, verify=self.verify_cert, timeout=self.timeout, **kwargs) return resp, resp.text
[ "def", "request", "(", "self", ",", "url", ",", "method", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "content_type", "=", "kwargs", ".", "pop", "(", "'content_type'", ",", "None", ")", "or", "'application/json'", "headers", "=", "headers", "or", "{", "}", "headers", ".", "setdefault", "(", "'Accept'", ",", "content_type", ")", "if", "body", ":", "headers", ".", "setdefault", "(", "'Content-Type'", ",", "content_type", ")", "headers", "[", "'User-Agent'", "]", "=", "self", ".", "USER_AGENT", "resp", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "data", "=", "body", ",", "headers", "=", "headers", ",", "verify", "=", "self", ".", "verify_cert", ",", "timeout", "=", "self", ".", "timeout", ",", "*", "*", "kwargs", ")", "return", "resp", ",", "resp", ".", "text" ]
Request without authentication.
[ "Request", "without", "authentication", "." ]
5a5009a8fe078e3aa1d582176669f1b28ab26bef
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/client.py#L133-L154
246,390
rackerlabs/rackspace-python-neutronclient
neutronclient/client.py
HTTPClient._extract_service_catalog
def _extract_service_catalog(self, body): """Set the client's service catalog from the response data.""" self.auth_ref = access.create(body=body) self.service_catalog = self.auth_ref.service_catalog self.auth_token = self.auth_ref.auth_token self.auth_tenant_id = self.auth_ref.tenant_id self.auth_user_id = self.auth_ref.user_id if not self.endpoint_url: self.endpoint_url = self.service_catalog.url_for( region_name=self.region_name, service_type=self.service_type, interface=self.endpoint_type)
python
def _extract_service_catalog(self, body): """Set the client's service catalog from the response data.""" self.auth_ref = access.create(body=body) self.service_catalog = self.auth_ref.service_catalog self.auth_token = self.auth_ref.auth_token self.auth_tenant_id = self.auth_ref.tenant_id self.auth_user_id = self.auth_ref.user_id if not self.endpoint_url: self.endpoint_url = self.service_catalog.url_for( region_name=self.region_name, service_type=self.service_type, interface=self.endpoint_type)
[ "def", "_extract_service_catalog", "(", "self", ",", "body", ")", ":", "self", ".", "auth_ref", "=", "access", ".", "create", "(", "body", "=", "body", ")", "self", ".", "service_catalog", "=", "self", ".", "auth_ref", ".", "service_catalog", "self", ".", "auth_token", "=", "self", ".", "auth_ref", ".", "auth_token", "self", ".", "auth_tenant_id", "=", "self", ".", "auth_ref", ".", "tenant_id", "self", ".", "auth_user_id", "=", "self", ".", "auth_ref", ".", "user_id", "if", "not", "self", ".", "endpoint_url", ":", "self", ".", "endpoint_url", "=", "self", ".", "service_catalog", ".", "url_for", "(", "region_name", "=", "self", ".", "region_name", ",", "service_type", "=", "self", ".", "service_type", ",", "interface", "=", "self", ".", "endpoint_type", ")" ]
Set the client's service catalog from the response data.
[ "Set", "the", "client", "s", "service", "catalog", "from", "the", "response", "data", "." ]
5a5009a8fe078e3aa1d582176669f1b28ab26bef
https://github.com/rackerlabs/rackspace-python-neutronclient/blob/5a5009a8fe078e3aa1d582176669f1b28ab26bef/neutronclient/client.py#L190-L202
246,391
usc-isi-i2/dig-sparkutil
digSparkUtil/rddUtil.py
show_partitioning
def show_partitioning(rdd, show=True): """Seems to be significantly more expensive on cluster than locally""" if show: partitionCount = rdd.getNumPartitions() try: valueCount = rdd.countApprox(1000, confidence=0.50) except: valueCount = -1 try: name = rdd.name() or None except: pass name = name or "anonymous" logging.info("For RDD %s, there are %d partitions with on average %s values" % (name, partitionCount, int(valueCount/float(partitionCount))))
python
def show_partitioning(rdd, show=True): """Seems to be significantly more expensive on cluster than locally""" if show: partitionCount = rdd.getNumPartitions() try: valueCount = rdd.countApprox(1000, confidence=0.50) except: valueCount = -1 try: name = rdd.name() or None except: pass name = name or "anonymous" logging.info("For RDD %s, there are %d partitions with on average %s values" % (name, partitionCount, int(valueCount/float(partitionCount))))
[ "def", "show_partitioning", "(", "rdd", ",", "show", "=", "True", ")", ":", "if", "show", ":", "partitionCount", "=", "rdd", ".", "getNumPartitions", "(", ")", "try", ":", "valueCount", "=", "rdd", ".", "countApprox", "(", "1000", ",", "confidence", "=", "0.50", ")", "except", ":", "valueCount", "=", "-", "1", "try", ":", "name", "=", "rdd", ".", "name", "(", ")", "or", "None", "except", ":", "pass", "name", "=", "name", "or", "\"anonymous\"", "logging", ".", "info", "(", "\"For RDD %s, there are %d partitions with on average %s values\"", "%", "(", "name", ",", "partitionCount", ",", "int", "(", "valueCount", "/", "float", "(", "partitionCount", ")", ")", ")", ")" ]
Seems to be significantly more expensive on cluster than locally
[ "Seems", "to", "be", "significantly", "more", "expensive", "on", "cluster", "than", "locally" ]
d39c6cf957025c170753b0e02e477fea20ee3f2a
https://github.com/usc-isi-i2/dig-sparkutil/blob/d39c6cf957025c170753b0e02e477fea20ee3f2a/digSparkUtil/rddUtil.py#L26-L40
246,392
tehmaze-labs/wright
wright/util.py
normal_case
def normal_case(name): """Converts "CamelCaseHere" to "camel case here".""" s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
python
def normal_case(name): """Converts "CamelCaseHere" to "camel case here".""" s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
[ "def", "normal_case", "(", "name", ")", ":", "s1", "=", "re", ".", "sub", "(", "r'(.)([A-Z][a-z]+)'", ",", "r'\\1 \\2'", ",", "name", ")", "return", "re", ".", "sub", "(", "r'([a-z0-9])([A-Z])'", ",", "r'\\1 \\2'", ",", "s1", ")", ".", "lower", "(", ")" ]
Converts "CamelCaseHere" to "camel case here".
[ "Converts", "CamelCaseHere", "to", "camel", "case", "here", "." ]
79b2d816f541e69d5fb7f36a3c39fa0d432157a6
https://github.com/tehmaze-labs/wright/blob/79b2d816f541e69d5fb7f36a3c39fa0d432157a6/wright/util.py#L123-L126
246,393
bird-house/birdhousebuilder.recipe.supervisor
birdhousebuilder/recipe/supervisor/__init__.py
Recipe.install_config
def install_config(self): """ install supervisor main config file """ text = templ_config.render(**self.options) config = Configuration(self.buildout, 'supervisord.conf', { 'deployment': self.deployment_name, 'text': text}) return [config.install()]
python
def install_config(self): """ install supervisor main config file """ text = templ_config.render(**self.options) config = Configuration(self.buildout, 'supervisord.conf', { 'deployment': self.deployment_name, 'text': text}) return [config.install()]
[ "def", "install_config", "(", "self", ")", ":", "text", "=", "templ_config", ".", "render", "(", "*", "*", "self", ".", "options", ")", "config", "=", "Configuration", "(", "self", ".", "buildout", ",", "'supervisord.conf'", ",", "{", "'deployment'", ":", "self", ".", "deployment_name", ",", "'text'", ":", "text", "}", ")", "return", "[", "config", ".", "install", "(", ")", "]" ]
install supervisor main config file
[ "install", "supervisor", "main", "config", "file" ]
bbd5531466f5f84b2ab7757f674dcdb5ae751d7f
https://github.com/bird-house/birdhousebuilder.recipe.supervisor/blob/bbd5531466f5f84b2ab7757f674dcdb5ae751d7f/birdhousebuilder/recipe/supervisor/__init__.py#L127-L135
246,394
bird-house/birdhousebuilder.recipe.supervisor
birdhousebuilder/recipe/supervisor/__init__.py
Recipe.install_program
def install_program(self): """ install supervisor program config file """ text = templ_program.render(**self.options) config = Configuration(self.buildout, self.program + '.conf', { 'deployment': self.deployment_name, 'directory': os.path.join(self.options['etc-directory'], 'conf.d'), 'text': text}) return [config.install()]
python
def install_program(self): """ install supervisor program config file """ text = templ_program.render(**self.options) config = Configuration(self.buildout, self.program + '.conf', { 'deployment': self.deployment_name, 'directory': os.path.join(self.options['etc-directory'], 'conf.d'), 'text': text}) return [config.install()]
[ "def", "install_program", "(", "self", ")", ":", "text", "=", "templ_program", ".", "render", "(", "*", "*", "self", ".", "options", ")", "config", "=", "Configuration", "(", "self", ".", "buildout", ",", "self", ".", "program", "+", "'.conf'", ",", "{", "'deployment'", ":", "self", ".", "deployment_name", ",", "'directory'", ":", "os", ".", "path", ".", "join", "(", "self", ".", "options", "[", "'etc-directory'", "]", ",", "'conf.d'", ")", ",", "'text'", ":", "text", "}", ")", "return", "[", "config", ".", "install", "(", ")", "]" ]
install supervisor program config file
[ "install", "supervisor", "program", "config", "file" ]
bbd5531466f5f84b2ab7757f674dcdb5ae751d7f
https://github.com/bird-house/birdhousebuilder.recipe.supervisor/blob/bbd5531466f5f84b2ab7757f674dcdb5ae751d7f/birdhousebuilder/recipe/supervisor/__init__.py#L137-L146
246,395
ulf1/oxyba
oxyba/linreg_ols_lu.py
linreg_ols_lu
def linreg_ols_lu(y, X): """Linear Regression, OLS, by solving linear equations and LU decomposition Properties ---------- * based on LAPACK's _gesv what applies LU decomposition * avoids using python's inverse functions * should be stable * no overhead or other computations Example: -------- beta = linreg_ols_lu(y,X) Links: ------ * http://oxyba.de/docs/linreg_ols_lu """ import numpy as np try: # solve OLS formula return np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y)) except np.linalg.LinAlgError: print("LinAlgError: X*X' is singular or not square.") return None
python
def linreg_ols_lu(y, X): """Linear Regression, OLS, by solving linear equations and LU decomposition Properties ---------- * based on LAPACK's _gesv what applies LU decomposition * avoids using python's inverse functions * should be stable * no overhead or other computations Example: -------- beta = linreg_ols_lu(y,X) Links: ------ * http://oxyba.de/docs/linreg_ols_lu """ import numpy as np try: # solve OLS formula return np.linalg.solve(np.dot(X.T, X), np.dot(X.T, y)) except np.linalg.LinAlgError: print("LinAlgError: X*X' is singular or not square.") return None
[ "def", "linreg_ols_lu", "(", "y", ",", "X", ")", ":", "import", "numpy", "as", "np", "try", ":", "# solve OLS formula", "return", "np", ".", "linalg", ".", "solve", "(", "np", ".", "dot", "(", "X", ".", "T", ",", "X", ")", ",", "np", ".", "dot", "(", "X", ".", "T", ",", "y", ")", ")", "except", "np", ".", "linalg", ".", "LinAlgError", ":", "print", "(", "\"LinAlgError: X*X' is singular or not square.\"", ")", "return", "None" ]
Linear Regression, OLS, by solving linear equations and LU decomposition Properties ---------- * based on LAPACK's _gesv what applies LU decomposition * avoids using python's inverse functions * should be stable * no overhead or other computations Example: -------- beta = linreg_ols_lu(y,X) Links: ------ * http://oxyba.de/docs/linreg_ols_lu
[ "Linear", "Regression", "OLS", "by", "solving", "linear", "equations", "and", "LU", "decomposition" ]
b3043116050de275124365cb11e7df91fb40169d
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_ols_lu.py#L2-L26
246,396
natemara/jumprunpro-python
jumprun/__init__.py
JumprunProApi._time_to_minutes
def _time_to_minutes(self, time_str): """ Convert a time string to the equivalent number in minutes as an int. Return 0 if the time_str is not a valid amount of time. >>> jump = JumprunProApi('skydive-warren-county') >>> jump._time_to_minutes('34 minutes') 34 >>> jump._time_to_minutes('1 hour, 30 minutes') 90 >>> jump._time_to_minutes('jfksadjfkas') 0 """ minutes = 0 try: call_time_obj = parser.parse(time_str) minutes = call_time_obj.minute minutes += call_time_obj.hour * 60 except ValueError: minutes = 0 return minutes
python
def _time_to_minutes(self, time_str): """ Convert a time string to the equivalent number in minutes as an int. Return 0 if the time_str is not a valid amount of time. >>> jump = JumprunProApi('skydive-warren-county') >>> jump._time_to_minutes('34 minutes') 34 >>> jump._time_to_minutes('1 hour, 30 minutes') 90 >>> jump._time_to_minutes('jfksadjfkas') 0 """ minutes = 0 try: call_time_obj = parser.parse(time_str) minutes = call_time_obj.minute minutes += call_time_obj.hour * 60 except ValueError: minutes = 0 return minutes
[ "def", "_time_to_minutes", "(", "self", ",", "time_str", ")", ":", "minutes", "=", "0", "try", ":", "call_time_obj", "=", "parser", ".", "parse", "(", "time_str", ")", "minutes", "=", "call_time_obj", ".", "minute", "minutes", "+=", "call_time_obj", ".", "hour", "*", "60", "except", "ValueError", ":", "minutes", "=", "0", "return", "minutes" ]
Convert a time string to the equivalent number in minutes as an int. Return 0 if the time_str is not a valid amount of time. >>> jump = JumprunProApi('skydive-warren-county') >>> jump._time_to_minutes('34 minutes') 34 >>> jump._time_to_minutes('1 hour, 30 minutes') 90 >>> jump._time_to_minutes('jfksadjfkas') 0
[ "Convert", "a", "time", "string", "to", "the", "equivalent", "number", "in", "minutes", "as", "an", "int", ".", "Return", "0", "if", "the", "time_str", "is", "not", "a", "valid", "amount", "of", "time", "." ]
016fb86955a87d2c6a4c776959031a44180b37f3
https://github.com/natemara/jumprunpro-python/blob/016fb86955a87d2c6a4c776959031a44180b37f3/jumprun/__init__.py#L31-L53
246,397
natemara/jumprunpro-python
jumprun/__init__.py
JumprunProApi.jumping
def jumping(self, _loads=None): """ Return True if this dropzone is still making new loads, False otherwise. :param _loads: The output of the `departing_loads` function. This should be left alone except for debugging purposes. """ if _loads is None: _loads = self.departing_loads() if len(_loads) < 1: return False last_load = _loads[-1:][0] if last_load['state'].lower() in ('departed', 'closed', 'on hold'): return False return True
python
def jumping(self, _loads=None): """ Return True if this dropzone is still making new loads, False otherwise. :param _loads: The output of the `departing_loads` function. This should be left alone except for debugging purposes. """ if _loads is None: _loads = self.departing_loads() if len(_loads) < 1: return False last_load = _loads[-1:][0] if last_load['state'].lower() in ('departed', 'closed', 'on hold'): return False return True
[ "def", "jumping", "(", "self", ",", "_loads", "=", "None", ")", ":", "if", "_loads", "is", "None", ":", "_loads", "=", "self", ".", "departing_loads", "(", ")", "if", "len", "(", "_loads", ")", "<", "1", ":", "return", "False", "last_load", "=", "_loads", "[", "-", "1", ":", "]", "[", "0", "]", "if", "last_load", "[", "'state'", "]", ".", "lower", "(", ")", "in", "(", "'departed'", ",", "'closed'", ",", "'on hold'", ")", ":", "return", "False", "return", "True" ]
Return True if this dropzone is still making new loads, False otherwise. :param _loads: The output of the `departing_loads` function. This should be left alone except for debugging purposes.
[ "Return", "True", "if", "this", "dropzone", "is", "still", "making", "new", "loads", "False", "otherwise", "." ]
016fb86955a87d2c6a4c776959031a44180b37f3
https://github.com/natemara/jumprunpro-python/blob/016fb86955a87d2c6a4c776959031a44180b37f3/jumprun/__init__.py#L90-L107
246,398
Othernet-Project/hwd
hwd/udev.py
devices_by_subsystem
def devices_by_subsystem(subsys, only=lambda x: True): """ Iterator that yields devices that belong to specified subsystem. Returned values are ``pydev.Device`` instances. The ``only`` argument can be used to further filter devices. It should be a function that takes a ``pyudev.Device`` object, and returns ``True`` or ``False`` to indicate whether device should be returned. Example:: >>> devices_by_subsystem('net') [Device('/sys/devices/pci0000:00/0000:00:1c.3/0000:02:00.0/net/wlp2s0'), Device('/sys/devices/virtual/net/lo')] """ ctx = pyudev.Context() for d in ctx.list_devices(): if d.subsystem != subsys: continue if not only(d): continue yield d
python
def devices_by_subsystem(subsys, only=lambda x: True): """ Iterator that yields devices that belong to specified subsystem. Returned values are ``pydev.Device`` instances. The ``only`` argument can be used to further filter devices. It should be a function that takes a ``pyudev.Device`` object, and returns ``True`` or ``False`` to indicate whether device should be returned. Example:: >>> devices_by_subsystem('net') [Device('/sys/devices/pci0000:00/0000:00:1c.3/0000:02:00.0/net/wlp2s0'), Device('/sys/devices/virtual/net/lo')] """ ctx = pyudev.Context() for d in ctx.list_devices(): if d.subsystem != subsys: continue if not only(d): continue yield d
[ "def", "devices_by_subsystem", "(", "subsys", ",", "only", "=", "lambda", "x", ":", "True", ")", ":", "ctx", "=", "pyudev", ".", "Context", "(", ")", "for", "d", "in", "ctx", ".", "list_devices", "(", ")", ":", "if", "d", ".", "subsystem", "!=", "subsys", ":", "continue", "if", "not", "only", "(", "d", ")", ":", "continue", "yield", "d" ]
Iterator that yields devices that belong to specified subsystem. Returned values are ``pydev.Device`` instances. The ``only`` argument can be used to further filter devices. It should be a function that takes a ``pyudev.Device`` object, and returns ``True`` or ``False`` to indicate whether device should be returned. Example:: >>> devices_by_subsystem('net') [Device('/sys/devices/pci0000:00/0000:00:1c.3/0000:02:00.0/net/wlp2s0'), Device('/sys/devices/virtual/net/lo')]
[ "Iterator", "that", "yields", "devices", "that", "belong", "to", "specified", "subsystem", ".", "Returned", "values", "are", "pydev", ".", "Device", "instances", "." ]
7f4445bac61aa2305806aa80338e2ce5baa1093c
https://github.com/Othernet-Project/hwd/blob/7f4445bac61aa2305806aa80338e2ce5baa1093c/hwd/udev.py#L4-L25
246,399
mkouhei/tonicdnscli
src/tonicdnscli/command.py
check_infile
def check_infile(filename): """Check text file exisitense. Argument: filename: text file of bulk updating """ if os.path.isfile(filename): domain = os.path.basename(filename).split('.txt')[0] return domain else: sys.stderr.write("ERROR: %s : No such file\n" % filename) sys.exit(1)
python
def check_infile(filename): """Check text file exisitense. Argument: filename: text file of bulk updating """ if os.path.isfile(filename): domain = os.path.basename(filename).split('.txt')[0] return domain else: sys.stderr.write("ERROR: %s : No such file\n" % filename) sys.exit(1)
[ "def", "check_infile", "(", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "domain", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", ".", "split", "(", "'.txt'", ")", "[", "0", "]", "return", "domain", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: %s : No such file\\n\"", "%", "filename", ")", "sys", ".", "exit", "(", "1", ")" ]
Check text file exisitense. Argument: filename: text file of bulk updating
[ "Check", "text", "file", "exisitense", "." ]
df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c
https://github.com/mkouhei/tonicdnscli/blob/df2d6fb2104ae4d49fa89d1bba2f3ccd2fed388c/src/tonicdnscli/command.py#L35-L47