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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Xion/taipan
taipan/objective/modifiers.py
abstract
def abstract(class_): """Mark the class as _abstract_ base class, forbidding its instantiation. .. note:: Unlike other modifiers, ``@abstract`` can be applied to all Python classes, not just subclasses of :class:`Object`. .. versionadded:: 0.0.3 """ if not inspect.isclass(class_): raise TypeError("@abstract can only be applied to classes") abc_meta = None # if the class is not already using a metaclass specific to ABC, # we need to change that class_meta = type(class_) if class_meta not in (_ABCMetaclass, _ABCObjectMetaclass): # decide what metaclass to use, depending on whether it's a subclass # of our universal :class:`Object` or not if class_meta is type: abc_meta = _ABCMetaclass # like ABCMeta, but can never instantiate elif class_meta is ObjectMetaclass: abc_meta = _ABCObjectMetaclass # ABCMeta mixed with ObjectMetaclass else: raise ValueError( "@abstract cannot be applied to classes with custom metaclass") class_.__abstract__ = True return metaclass(abc_meta)(class_) if abc_meta else class_
python
def abstract(class_): """Mark the class as _abstract_ base class, forbidding its instantiation. .. note:: Unlike other modifiers, ``@abstract`` can be applied to all Python classes, not just subclasses of :class:`Object`. .. versionadded:: 0.0.3 """ if not inspect.isclass(class_): raise TypeError("@abstract can only be applied to classes") abc_meta = None # if the class is not already using a metaclass specific to ABC, # we need to change that class_meta = type(class_) if class_meta not in (_ABCMetaclass, _ABCObjectMetaclass): # decide what metaclass to use, depending on whether it's a subclass # of our universal :class:`Object` or not if class_meta is type: abc_meta = _ABCMetaclass # like ABCMeta, but can never instantiate elif class_meta is ObjectMetaclass: abc_meta = _ABCObjectMetaclass # ABCMeta mixed with ObjectMetaclass else: raise ValueError( "@abstract cannot be applied to classes with custom metaclass") class_.__abstract__ = True return metaclass(abc_meta)(class_) if abc_meta else class_
[ "def", "abstract", "(", "class_", ")", ":", "if", "not", "inspect", ".", "isclass", "(", "class_", ")", ":", "raise", "TypeError", "(", "\"@abstract can only be applied to classes\"", ")", "abc_meta", "=", "None", "# if the class is not already using a metaclass specific to ABC,", "# we need to change that", "class_meta", "=", "type", "(", "class_", ")", "if", "class_meta", "not", "in", "(", "_ABCMetaclass", ",", "_ABCObjectMetaclass", ")", ":", "# decide what metaclass to use, depending on whether it's a subclass", "# of our universal :class:`Object` or not", "if", "class_meta", "is", "type", ":", "abc_meta", "=", "_ABCMetaclass", "# like ABCMeta, but can never instantiate", "elif", "class_meta", "is", "ObjectMetaclass", ":", "abc_meta", "=", "_ABCObjectMetaclass", "# ABCMeta mixed with ObjectMetaclass", "else", ":", "raise", "ValueError", "(", "\"@abstract cannot be applied to classes with custom metaclass\"", ")", "class_", ".", "__abstract__", "=", "True", "return", "metaclass", "(", "abc_meta", ")", "(", "class_", ")", "if", "abc_meta", "else", "class_" ]
Mark the class as _abstract_ base class, forbidding its instantiation. .. note:: Unlike other modifiers, ``@abstract`` can be applied to all Python classes, not just subclasses of :class:`Object`. .. versionadded:: 0.0.3
[ "Mark", "the", "class", "as", "_abstract_", "base", "class", "forbidding", "its", "instantiation", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/modifiers.py#L50-L80
train
Xion/taipan
taipan/objective/modifiers.py
final
def final(arg): """Mark a class or method as _final_. Final classes are those that end the inheritance chain, i.e. forbid further subclassing. A final class can thus be only instantiated, not inherited from. Similarly, methods marked as final in a superclass cannot be overridden in any of the subclasses. .. note:: Final method itself can also be (in fact, it usually is) an overridden method from a superclass. In those cases, it's recommended to place @\ :func:`final` modifier before @\ :func:`override` for clarity:: class Foo(Base): @final @override def florb(self): super(Foo, self).florb() # ... .. versionadded:: 0.0.3 Now applicable to methods in addition to classes """ if inspect.isclass(arg): if not isinstance(arg, ObjectMetaclass): raise ValueError("@final can only be applied to a class " "that is a subclass of Object") elif not is_method(arg): raise TypeError("@final can only be applied to classes or methods") method = arg.method if isinstance(arg, _WrappedMethod) else arg method.__final__ = True return arg
python
def final(arg): """Mark a class or method as _final_. Final classes are those that end the inheritance chain, i.e. forbid further subclassing. A final class can thus be only instantiated, not inherited from. Similarly, methods marked as final in a superclass cannot be overridden in any of the subclasses. .. note:: Final method itself can also be (in fact, it usually is) an overridden method from a superclass. In those cases, it's recommended to place @\ :func:`final` modifier before @\ :func:`override` for clarity:: class Foo(Base): @final @override def florb(self): super(Foo, self).florb() # ... .. versionadded:: 0.0.3 Now applicable to methods in addition to classes """ if inspect.isclass(arg): if not isinstance(arg, ObjectMetaclass): raise ValueError("@final can only be applied to a class " "that is a subclass of Object") elif not is_method(arg): raise TypeError("@final can only be applied to classes or methods") method = arg.method if isinstance(arg, _WrappedMethod) else arg method.__final__ = True return arg
[ "def", "final", "(", "arg", ")", ":", "if", "inspect", ".", "isclass", "(", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "ObjectMetaclass", ")", ":", "raise", "ValueError", "(", "\"@final can only be applied to a class \"", "\"that is a subclass of Object\"", ")", "elif", "not", "is_method", "(", "arg", ")", ":", "raise", "TypeError", "(", "\"@final can only be applied to classes or methods\"", ")", "method", "=", "arg", ".", "method", "if", "isinstance", "(", "arg", ",", "_WrappedMethod", ")", "else", "arg", "method", ".", "__final__", "=", "True", "return", "arg" ]
Mark a class or method as _final_. Final classes are those that end the inheritance chain, i.e. forbid further subclassing. A final class can thus be only instantiated, not inherited from. Similarly, methods marked as final in a superclass cannot be overridden in any of the subclasses. .. note:: Final method itself can also be (in fact, it usually is) an overridden method from a superclass. In those cases, it's recommended to place @\ :func:`final` modifier before @\ :func:`override` for clarity:: class Foo(Base): @final @override def florb(self): super(Foo, self).florb() # ... .. versionadded:: 0.0.3 Now applicable to methods in addition to classes
[ "Mark", "a", "class", "or", "method", "as", "_final_", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/modifiers.py#L93-L129
train
Xion/taipan
taipan/objective/modifiers.py
override
def override(base=ABSENT): """Mark a method as overriding a corresponding method from superclass. :param base: Optional base class from which this method is being overridden. If provided, it can be a class itself, or its (qualified) name. .. note:: When overriding a :class:`classmethod`, remember to place ``@override`` above the ``@classmethod`` decorator:: class Foo(Bar): @override @classmethod def florb(cls): pass """ arg = base # ``base`` is just for clean, user-facing argument name # direct application of the modifier through ``@override`` if inspect.isfunction(arg) or isinstance(arg, NonInstanceMethod): _OverrideDecorator.maybe_signal_classmethod(arg) decorator = _OverrideDecorator(None) return decorator(arg) # indirect (but simple) application of the modifier through ``@override()`` if arg is ABSENT: return _OverrideDecorator(None) # full-blown application, with base class specified if is_class(arg) or is_string(arg): return _OverrideDecorator(arg) raise TypeError("explicit base class for @override " "must be either a string or a class object")
python
def override(base=ABSENT): """Mark a method as overriding a corresponding method from superclass. :param base: Optional base class from which this method is being overridden. If provided, it can be a class itself, or its (qualified) name. .. note:: When overriding a :class:`classmethod`, remember to place ``@override`` above the ``@classmethod`` decorator:: class Foo(Bar): @override @classmethod def florb(cls): pass """ arg = base # ``base`` is just for clean, user-facing argument name # direct application of the modifier through ``@override`` if inspect.isfunction(arg) or isinstance(arg, NonInstanceMethod): _OverrideDecorator.maybe_signal_classmethod(arg) decorator = _OverrideDecorator(None) return decorator(arg) # indirect (but simple) application of the modifier through ``@override()`` if arg is ABSENT: return _OverrideDecorator(None) # full-blown application, with base class specified if is_class(arg) or is_string(arg): return _OverrideDecorator(arg) raise TypeError("explicit base class for @override " "must be either a string or a class object")
[ "def", "override", "(", "base", "=", "ABSENT", ")", ":", "arg", "=", "base", "# ``base`` is just for clean, user-facing argument name", "# direct application of the modifier through ``@override``", "if", "inspect", ".", "isfunction", "(", "arg", ")", "or", "isinstance", "(", "arg", ",", "NonInstanceMethod", ")", ":", "_OverrideDecorator", ".", "maybe_signal_classmethod", "(", "arg", ")", "decorator", "=", "_OverrideDecorator", "(", "None", ")", "return", "decorator", "(", "arg", ")", "# indirect (but simple) application of the modifier through ``@override()``", "if", "arg", "is", "ABSENT", ":", "return", "_OverrideDecorator", "(", "None", ")", "# full-blown application, with base class specified", "if", "is_class", "(", "arg", ")", "or", "is_string", "(", "arg", ")", ":", "return", "_OverrideDecorator", "(", "arg", ")", "raise", "TypeError", "(", "\"explicit base class for @override \"", "\"must be either a string or a class object\"", ")" ]
Mark a method as overriding a corresponding method from superclass. :param base: Optional base class from which this method is being overridden. If provided, it can be a class itself, or its (qualified) name. .. note:: When overriding a :class:`classmethod`, remember to place ``@override`` above the ``@classmethod`` decorator:: class Foo(Bar): @override @classmethod def florb(cls): pass
[ "Mark", "a", "method", "as", "overriding", "a", "corresponding", "method", "from", "superclass", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/modifiers.py#L134-L170
train
Xion/taipan
taipan/collections/lists.py
find
def find(*args, **kwargs): """Find the first matching element in a list and return it. Usage:: find(element, list_) find(of=element, in_=list_) find(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Last matching element :raise IndexError: If no matching elements were found .. versionadded:: 0.0.4 """ list_, idx = _index(*args, start=0, step=1, **kwargs) if idx < 0: raise IndexError("element not found") return list_[idx]
python
def find(*args, **kwargs): """Find the first matching element in a list and return it. Usage:: find(element, list_) find(of=element, in_=list_) find(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Last matching element :raise IndexError: If no matching elements were found .. versionadded:: 0.0.4 """ list_, idx = _index(*args, start=0, step=1, **kwargs) if idx < 0: raise IndexError("element not found") return list_[idx]
[ "def", "find", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "list_", ",", "idx", "=", "_index", "(", "*", "args", ",", "start", "=", "0", ",", "step", "=", "1", ",", "*", "*", "kwargs", ")", "if", "idx", "<", "0", ":", "raise", "IndexError", "(", "\"element not found\"", ")", "return", "list_", "[", "idx", "]" ]
Find the first matching element in a list and return it. Usage:: find(element, list_) find(of=element, in_=list_) find(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Last matching element :raise IndexError: If no matching elements were found .. versionadded:: 0.0.4
[ "Find", "the", "first", "matching", "element", "in", "a", "list", "and", "return", "it", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L50-L73
train
Xion/taipan
taipan/collections/lists.py
findlast
def findlast(*args, **kwargs): """Find the last matching element in a list and return it. Usage:: findlast(element, list_) findlast(of=element, in_=list_) findlast(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Last matching element :raise IndexError: If no matching elements were found .. versionadded:: 0.0.4 """ list_, idx = _index(*args, start=sys.maxsize, step=-1, **kwargs) if idx < 0: raise IndexError("element not found") return list_[idx]
python
def findlast(*args, **kwargs): """Find the last matching element in a list and return it. Usage:: findlast(element, list_) findlast(of=element, in_=list_) findlast(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Last matching element :raise IndexError: If no matching elements were found .. versionadded:: 0.0.4 """ list_, idx = _index(*args, start=sys.maxsize, step=-1, **kwargs) if idx < 0: raise IndexError("element not found") return list_[idx]
[ "def", "findlast", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "list_", ",", "idx", "=", "_index", "(", "*", "args", ",", "start", "=", "sys", ".", "maxsize", ",", "step", "=", "-", "1", ",", "*", "*", "kwargs", ")", "if", "idx", "<", "0", ":", "raise", "IndexError", "(", "\"element not found\"", ")", "return", "list_", "[", "idx", "]" ]
Find the last matching element in a list and return it. Usage:: findlast(element, list_) findlast(of=element, in_=list_) findlast(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Last matching element :raise IndexError: If no matching elements were found .. versionadded:: 0.0.4
[ "Find", "the", "last", "matching", "element", "in", "a", "list", "and", "return", "it", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L76-L99
train
Xion/taipan
taipan/collections/lists.py
index
def index(*args, **kwargs): """Search a list for an exact element, or element satisfying a predicate. Usage:: index(element, list_) index(of=element, in_=list_) index(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Index of first matching element, or -1 if none was found .. versionadded:: 0.0.3 """ _, idx = _index(*args, start=0, step=1, **kwargs) return idx
python
def index(*args, **kwargs): """Search a list for an exact element, or element satisfying a predicate. Usage:: index(element, list_) index(of=element, in_=list_) index(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Index of first matching element, or -1 if none was found .. versionadded:: 0.0.3 """ _, idx = _index(*args, start=0, step=1, **kwargs) return idx
[ "def", "index", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", ",", "idx", "=", "_index", "(", "*", "args", ",", "start", "=", "0", ",", "step", "=", "1", ",", "*", "*", "kwargs", ")", "return", "idx" ]
Search a list for an exact element, or element satisfying a predicate. Usage:: index(element, list_) index(of=element, in_=list_) index(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Index of first matching element, or -1 if none was found .. versionadded:: 0.0.3
[ "Search", "a", "list", "for", "an", "exact", "element", "or", "element", "satisfying", "a", "predicate", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L102-L122
train
Xion/taipan
taipan/collections/lists.py
lastindex
def lastindex(*args, **kwargs): """Search a list backwards for an exact element, or element satisfying a predicate. Usage:: lastindex(element, list_) lastindex(of=element, in_=list_) lastindex(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Index of the last matching element, or -1 if none was found .. versionadded:: 0.0.3 """ _, idx = _index(*args, start=sys.maxsize, step=-1, **kwargs) return idx
python
def lastindex(*args, **kwargs): """Search a list backwards for an exact element, or element satisfying a predicate. Usage:: lastindex(element, list_) lastindex(of=element, in_=list_) lastindex(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Index of the last matching element, or -1 if none was found .. versionadded:: 0.0.3 """ _, idx = _index(*args, start=sys.maxsize, step=-1, **kwargs) return idx
[ "def", "lastindex", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_", ",", "idx", "=", "_index", "(", "*", "args", ",", "start", "=", "sys", ".", "maxsize", ",", "step", "=", "-", "1", ",", "*", "*", "kwargs", ")", "return", "idx" ]
Search a list backwards for an exact element, or element satisfying a predicate. Usage:: lastindex(element, list_) lastindex(of=element, in_=list_) lastindex(where=predicate, in_=list_) :param element, of: Element to search for (by equality comparison) :param where: Predicate defining an element to search for. This should be a callable taking a single argument and returning a boolean result. :param list_, in_: List to search in :return: Index of the last matching element, or -1 if none was found .. versionadded:: 0.0.3
[ "Search", "a", "list", "backwards", "for", "an", "exact", "element", "or", "element", "satisfying", "a", "predicate", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L125-L146
train
Xion/taipan
taipan/collections/lists.py
_index
def _index(*args, **kwargs): """Implementation of list searching. :param of: Element to search for :param where: Predicate to search for :param in_: List to search in :param start: Start index for the lookup :param step: Counter step (i.e. in/decrement) for each iteration :return: Pair of ``(list, index)``, where ``list`` is the list we searched in and ``index`` is the index of the first element found, or -1 """ start = kwargs.pop('start', 0) step = kwargs.pop('step', 1) if len(args) == 2: elem, list_ = args ensure_sequence(list_) predicate = lambda item: item == elem else: ensure_keyword_args(kwargs, mandatory=('in_',), optional=('of', 'where')) if 'of' in kwargs and 'where' in kwargs: raise TypeError( "either an item or predicate must be supplied, not both") if not ('of' in kwargs or 'where' in kwargs): raise TypeError("an item or predicate must be supplied") list_ = ensure_sequence(kwargs['in_']) if 'where' in kwargs: predicate = ensure_callable(kwargs['where']) else: elem = kwargs['of'] predicate = lambda item: item == elem len_ = len(list_) start = max(0, min(len_ - 1, start)) i = start while 0 <= i < len_: if predicate(list_[i]): return list_, i i += step else: return list_, -1
python
def _index(*args, **kwargs): """Implementation of list searching. :param of: Element to search for :param where: Predicate to search for :param in_: List to search in :param start: Start index for the lookup :param step: Counter step (i.e. in/decrement) for each iteration :return: Pair of ``(list, index)``, where ``list`` is the list we searched in and ``index`` is the index of the first element found, or -1 """ start = kwargs.pop('start', 0) step = kwargs.pop('step', 1) if len(args) == 2: elem, list_ = args ensure_sequence(list_) predicate = lambda item: item == elem else: ensure_keyword_args(kwargs, mandatory=('in_',), optional=('of', 'where')) if 'of' in kwargs and 'where' in kwargs: raise TypeError( "either an item or predicate must be supplied, not both") if not ('of' in kwargs or 'where' in kwargs): raise TypeError("an item or predicate must be supplied") list_ = ensure_sequence(kwargs['in_']) if 'where' in kwargs: predicate = ensure_callable(kwargs['where']) else: elem = kwargs['of'] predicate = lambda item: item == elem len_ = len(list_) start = max(0, min(len_ - 1, start)) i = start while 0 <= i < len_: if predicate(list_[i]): return list_, i i += step else: return list_, -1
[ "def", "_index", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "start", "=", "kwargs", ".", "pop", "(", "'start'", ",", "0", ")", "step", "=", "kwargs", ".", "pop", "(", "'step'", ",", "1", ")", "if", "len", "(", "args", ")", "==", "2", ":", "elem", ",", "list_", "=", "args", "ensure_sequence", "(", "list_", ")", "predicate", "=", "lambda", "item", ":", "item", "==", "elem", "else", ":", "ensure_keyword_args", "(", "kwargs", ",", "mandatory", "=", "(", "'in_'", ",", ")", ",", "optional", "=", "(", "'of'", ",", "'where'", ")", ")", "if", "'of'", "in", "kwargs", "and", "'where'", "in", "kwargs", ":", "raise", "TypeError", "(", "\"either an item or predicate must be supplied, not both\"", ")", "if", "not", "(", "'of'", "in", "kwargs", "or", "'where'", "in", "kwargs", ")", ":", "raise", "TypeError", "(", "\"an item or predicate must be supplied\"", ")", "list_", "=", "ensure_sequence", "(", "kwargs", "[", "'in_'", "]", ")", "if", "'where'", "in", "kwargs", ":", "predicate", "=", "ensure_callable", "(", "kwargs", "[", "'where'", "]", ")", "else", ":", "elem", "=", "kwargs", "[", "'of'", "]", "predicate", "=", "lambda", "item", ":", "item", "==", "elem", "len_", "=", "len", "(", "list_", ")", "start", "=", "max", "(", "0", ",", "min", "(", "len_", "-", "1", ",", "start", ")", ")", "i", "=", "start", "while", "0", "<=", "i", "<", "len_", ":", "if", "predicate", "(", "list_", "[", "i", "]", ")", ":", "return", "list_", ",", "i", "i", "+=", "step", "else", ":", "return", "list_", ",", "-", "1" ]
Implementation of list searching. :param of: Element to search for :param where: Predicate to search for :param in_: List to search in :param start: Start index for the lookup :param step: Counter step (i.e. in/decrement) for each iteration :return: Pair of ``(list, index)``, where ``list`` is the list we searched in and ``index`` is the index of the first element found, or -1
[ "Implementation", "of", "list", "searching", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L149-L194
train
Xion/taipan
taipan/collections/lists.py
intercalate
def intercalate(elems, list_): """Insert given elements between existing elements of a list. :param elems: List of elements to insert between elements of ``list_` :param list_: List to insert the elements to :return: A new list where items from ``elems`` are inserted between every two elements of ``list_`` """ ensure_sequence(elems) ensure_sequence(list_) if len(list_) <= 1: return list_ return sum( (elems + list_[i:i+1] for i in xrange(1, len(list_))), list_[:1])
python
def intercalate(elems, list_): """Insert given elements between existing elements of a list. :param elems: List of elements to insert between elements of ``list_` :param list_: List to insert the elements to :return: A new list where items from ``elems`` are inserted between every two elements of ``list_`` """ ensure_sequence(elems) ensure_sequence(list_) if len(list_) <= 1: return list_ return sum( (elems + list_[i:i+1] for i in xrange(1, len(list_))), list_[:1])
[ "def", "intercalate", "(", "elems", ",", "list_", ")", ":", "ensure_sequence", "(", "elems", ")", "ensure_sequence", "(", "list_", ")", "if", "len", "(", "list_", ")", "<=", "1", ":", "return", "list_", "return", "sum", "(", "(", "elems", "+", "list_", "[", "i", ":", "i", "+", "1", "]", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "list_", ")", ")", ")", ",", "list_", "[", ":", "1", "]", ")" ]
Insert given elements between existing elements of a list. :param elems: List of elements to insert between elements of ``list_` :param list_: List to insert the elements to :return: A new list where items from ``elems`` are inserted between every two elements of ``list_``
[ "Insert", "given", "elements", "between", "existing", "elements", "of", "a", "list", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/lists.py#L208-L225
train
tjcsl/cslbot
cslbot/hooks/caps.py
handle
def handle(_, msg, args): """Check for capslock abuse. Check if a line is more than THRESHOLD percent uppercase. If this is the second line in a row, kick the user. """ # SHUT CAPS LOCK OFF, MORON if args['config']['feature'].getboolean('capskick'): nick = args['nick'] threshold = 0.65 text = "shutting caps lock off" upper = [i for i in msg if i in string.ascii_uppercase] if len(msg) == 0: return upper_ratio = len(upper) / len(msg.replace(' ', '')) if args['target'] != 'private': with _caps_lock: if upper_ratio > threshold and len(msg) > 10: if nick in _caps: args['do_kick'](args['target'], nick, text) _caps.remove(nick) else: _caps.append(nick) elif nick in _caps: _caps.remove(nick)
python
def handle(_, msg, args): """Check for capslock abuse. Check if a line is more than THRESHOLD percent uppercase. If this is the second line in a row, kick the user. """ # SHUT CAPS LOCK OFF, MORON if args['config']['feature'].getboolean('capskick'): nick = args['nick'] threshold = 0.65 text = "shutting caps lock off" upper = [i for i in msg if i in string.ascii_uppercase] if len(msg) == 0: return upper_ratio = len(upper) / len(msg.replace(' ', '')) if args['target'] != 'private': with _caps_lock: if upper_ratio > threshold and len(msg) > 10: if nick in _caps: args['do_kick'](args['target'], nick, text) _caps.remove(nick) else: _caps.append(nick) elif nick in _caps: _caps.remove(nick)
[ "def", "handle", "(", "_", ",", "msg", ",", "args", ")", ":", "# SHUT CAPS LOCK OFF, MORON", "if", "args", "[", "'config'", "]", "[", "'feature'", "]", ".", "getboolean", "(", "'capskick'", ")", ":", "nick", "=", "args", "[", "'nick'", "]", "threshold", "=", "0.65", "text", "=", "\"shutting caps lock off\"", "upper", "=", "[", "i", "for", "i", "in", "msg", "if", "i", "in", "string", ".", "ascii_uppercase", "]", "if", "len", "(", "msg", ")", "==", "0", ":", "return", "upper_ratio", "=", "len", "(", "upper", ")", "/", "len", "(", "msg", ".", "replace", "(", "' '", ",", "''", ")", ")", "if", "args", "[", "'target'", "]", "!=", "'private'", ":", "with", "_caps_lock", ":", "if", "upper_ratio", ">", "threshold", "and", "len", "(", "msg", ")", ">", "10", ":", "if", "nick", "in", "_caps", ":", "args", "[", "'do_kick'", "]", "(", "args", "[", "'target'", "]", ",", "nick", ",", "text", ")", "_caps", ".", "remove", "(", "nick", ")", "else", ":", "_caps", ".", "append", "(", "nick", ")", "elif", "nick", "in", "_caps", ":", "_caps", ".", "remove", "(", "nick", ")" ]
Check for capslock abuse. Check if a line is more than THRESHOLD percent uppercase. If this is the second line in a row, kick the user.
[ "Check", "for", "capslock", "abuse", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/hooks/caps.py#L29-L55
train
tjcsl/cslbot
cslbot/commands/fullwidth.py
cmd
def cmd(send, msg, args): """Converts text to fullwidth characters. Syntax: {command} [text] """ if not msg: msg = gen_word() send(gen_fullwidth(msg.upper()))
python
def cmd(send, msg, args): """Converts text to fullwidth characters. Syntax: {command} [text] """ if not msg: msg = gen_word() send(gen_fullwidth(msg.upper()))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "msg", "=", "gen_word", "(", ")", "send", "(", "gen_fullwidth", "(", "msg", ".", "upper", "(", ")", ")", ")" ]
Converts text to fullwidth characters. Syntax: {command} [text]
[ "Converts", "text", "to", "fullwidth", "characters", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/fullwidth.py#L23-L31
train
ktdreyer/txkoji
examples/estimate-container.py
task_estimates
def task_estimates(channel, states): """ Estimate remaining time for all tasks in this channel. :param channel: txkoji.channel.Channel :param list states: list of task_states ints, eg [task_states.OPEN] :returns: deferred that when fired returns a list of (task, est_remaining) tuples """ for state in states: if state != task_states.OPEN: raise NotImplementedError('only estimate OPEN tasks') tasks = yield channel.tasks(state=states) # Estimate all the unique packages. packages = set([task.package for task in tasks]) print('checking avg build duration for %i packages:' % len(packages)) packages = list(packages) durations = yield average_build_durations(channel.connection, packages) avg_package_durations = dict(zip(packages, durations)) # pprint(avg_package_durations) # Determine estimates for all our tasks. results = [] utcnow = datetime.utcnow() for task in tasks: avg_duration = avg_package_durations[task.package] est_complete = task.started + avg_duration est_remaining = est_complete - utcnow result = (task, est_remaining) results.append(result) defer.returnValue(results)
python
def task_estimates(channel, states): """ Estimate remaining time for all tasks in this channel. :param channel: txkoji.channel.Channel :param list states: list of task_states ints, eg [task_states.OPEN] :returns: deferred that when fired returns a list of (task, est_remaining) tuples """ for state in states: if state != task_states.OPEN: raise NotImplementedError('only estimate OPEN tasks') tasks = yield channel.tasks(state=states) # Estimate all the unique packages. packages = set([task.package for task in tasks]) print('checking avg build duration for %i packages:' % len(packages)) packages = list(packages) durations = yield average_build_durations(channel.connection, packages) avg_package_durations = dict(zip(packages, durations)) # pprint(avg_package_durations) # Determine estimates for all our tasks. results = [] utcnow = datetime.utcnow() for task in tasks: avg_duration = avg_package_durations[task.package] est_complete = task.started + avg_duration est_remaining = est_complete - utcnow result = (task, est_remaining) results.append(result) defer.returnValue(results)
[ "def", "task_estimates", "(", "channel", ",", "states", ")", ":", "for", "state", "in", "states", ":", "if", "state", "!=", "task_states", ".", "OPEN", ":", "raise", "NotImplementedError", "(", "'only estimate OPEN tasks'", ")", "tasks", "=", "yield", "channel", ".", "tasks", "(", "state", "=", "states", ")", "# Estimate all the unique packages.", "packages", "=", "set", "(", "[", "task", ".", "package", "for", "task", "in", "tasks", "]", ")", "print", "(", "'checking avg build duration for %i packages:'", "%", "len", "(", "packages", ")", ")", "packages", "=", "list", "(", "packages", ")", "durations", "=", "yield", "average_build_durations", "(", "channel", ".", "connection", ",", "packages", ")", "avg_package_durations", "=", "dict", "(", "zip", "(", "packages", ",", "durations", ")", ")", "# pprint(avg_package_durations)", "# Determine estimates for all our tasks.", "results", "=", "[", "]", "utcnow", "=", "datetime", ".", "utcnow", "(", ")", "for", "task", "in", "tasks", ":", "avg_duration", "=", "avg_package_durations", "[", "task", ".", "package", "]", "est_complete", "=", "task", ".", "started", "+", "avg_duration", "est_remaining", "=", "est_complete", "-", "utcnow", "result", "=", "(", "task", ",", "est_remaining", ")", "results", ".", "append", "(", "result", ")", "defer", ".", "returnValue", "(", "results", ")" ]
Estimate remaining time for all tasks in this channel. :param channel: txkoji.channel.Channel :param list states: list of task_states ints, eg [task_states.OPEN] :returns: deferred that when fired returns a list of (task, est_remaining) tuples
[ "Estimate", "remaining", "time", "for", "all", "tasks", "in", "this", "channel", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/examples/estimate-container.py#L80-L109
train
ktdreyer/txkoji
examples/estimate-container.py
describe_delta
def describe_delta(delta): """ Describe this timedelta in human-readable terms. :param delta: datetime.timedelta object :returns: str, describing this delta """ s = delta.total_seconds() s = abs(s) hours, remainder = divmod(s, 3600) minutes, seconds = divmod(remainder, 60) if hours: return '%d hr %d min' % (hours, minutes) if minutes: return '%d min %d secs' % (minutes, seconds) return '%d secs' % seconds
python
def describe_delta(delta): """ Describe this timedelta in human-readable terms. :param delta: datetime.timedelta object :returns: str, describing this delta """ s = delta.total_seconds() s = abs(s) hours, remainder = divmod(s, 3600) minutes, seconds = divmod(remainder, 60) if hours: return '%d hr %d min' % (hours, minutes) if minutes: return '%d min %d secs' % (minutes, seconds) return '%d secs' % seconds
[ "def", "describe_delta", "(", "delta", ")", ":", "s", "=", "delta", ".", "total_seconds", "(", ")", "s", "=", "abs", "(", "s", ")", "hours", ",", "remainder", "=", "divmod", "(", "s", ",", "3600", ")", "minutes", ",", "seconds", "=", "divmod", "(", "remainder", ",", "60", ")", "if", "hours", ":", "return", "'%d hr %d min'", "%", "(", "hours", ",", "minutes", ")", "if", "minutes", ":", "return", "'%d min %d secs'", "%", "(", "minutes", ",", "seconds", ")", "return", "'%d secs'", "%", "seconds" ]
Describe this timedelta in human-readable terms. :param delta: datetime.timedelta object :returns: str, describing this delta
[ "Describe", "this", "timedelta", "in", "human", "-", "readable", "terms", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/examples/estimate-container.py#L112-L127
train
ktdreyer/txkoji
examples/estimate-container.py
log_est_complete
def log_est_complete(est_complete): """ Log the relative time remaining for this est_complete datetime object. """ if not est_complete: print('could not determine an estimated completion time') return remaining = est_complete - datetime.utcnow() message = 'this task should be complete in %s' if remaining.total_seconds() < 0: message = 'this task exceeds estimate by %s' log_delta(message, remaining)
python
def log_est_complete(est_complete): """ Log the relative time remaining for this est_complete datetime object. """ if not est_complete: print('could not determine an estimated completion time') return remaining = est_complete - datetime.utcnow() message = 'this task should be complete in %s' if remaining.total_seconds() < 0: message = 'this task exceeds estimate by %s' log_delta(message, remaining)
[ "def", "log_est_complete", "(", "est_complete", ")", ":", "if", "not", "est_complete", ":", "print", "(", "'could not determine an estimated completion time'", ")", "return", "remaining", "=", "est_complete", "-", "datetime", ".", "utcnow", "(", ")", "message", "=", "'this task should be complete in %s'", "if", "remaining", ".", "total_seconds", "(", ")", "<", "0", ":", "message", "=", "'this task exceeds estimate by %s'", "log_delta", "(", "message", ",", "remaining", ")" ]
Log the relative time remaining for this est_complete datetime object.
[ "Log", "the", "relative", "time", "remaining", "for", "this", "est_complete", "datetime", "object", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/examples/estimate-container.py#L130-L141
train
davisagli/eye
eye/patch.py
patched_normalizeargs
def patched_normalizeargs(sequence, output = None): """Normalize declaration arguments Normalization arguments might contain Declarions, tuples, or single interfaces. Anything but individial interfaces or implements specs will be expanded. """ if output is None: output = [] if Broken in getattr(sequence, '__bases__', ()): return [sequence] cls = sequence.__class__ if InterfaceClass in cls.__mro__ or zope.interface.declarations.Implements in cls.__mro__: output.append(sequence) else: for v in sequence: patched_normalizeargs(v, output) return output
python
def patched_normalizeargs(sequence, output = None): """Normalize declaration arguments Normalization arguments might contain Declarions, tuples, or single interfaces. Anything but individial interfaces or implements specs will be expanded. """ if output is None: output = [] if Broken in getattr(sequence, '__bases__', ()): return [sequence] cls = sequence.__class__ if InterfaceClass in cls.__mro__ or zope.interface.declarations.Implements in cls.__mro__: output.append(sequence) else: for v in sequence: patched_normalizeargs(v, output) return output
[ "def", "patched_normalizeargs", "(", "sequence", ",", "output", "=", "None", ")", ":", "if", "output", "is", "None", ":", "output", "=", "[", "]", "if", "Broken", "in", "getattr", "(", "sequence", ",", "'__bases__'", ",", "(", ")", ")", ":", "return", "[", "sequence", "]", "cls", "=", "sequence", ".", "__class__", "if", "InterfaceClass", "in", "cls", ".", "__mro__", "or", "zope", ".", "interface", ".", "declarations", ".", "Implements", "in", "cls", ".", "__mro__", ":", "output", ".", "append", "(", "sequence", ")", "else", ":", "for", "v", "in", "sequence", ":", "patched_normalizeargs", "(", "v", ",", "output", ")", "return", "output" ]
Normalize declaration arguments Normalization arguments might contain Declarions, tuples, or single interfaces. Anything but individial interfaces or implements specs will be expanded.
[ "Normalize", "declaration", "arguments" ]
4007b6b490ac667c8423c6cc789b303e93f9d03d
https://github.com/davisagli/eye/blob/4007b6b490ac667c8423c6cc789b303e93f9d03d/eye/patch.py#L12-L33
train
ktdreyer/txkoji
txkoji/connection.py
profiles
def profiles(): """ List of all the connection profile files, ordered by preference. :returns: list of all Koji client config files. Example: ['/home/kdreyer/.koji/config.d/kojidev.conf', '/etc/koji.conf.d/stg.conf', '/etc/koji.conf.d/fedora.conf'] """ paths = [] for pattern in PROFILES: pattern = os.path.expanduser(pattern) paths += glob(pattern) return paths
python
def profiles(): """ List of all the connection profile files, ordered by preference. :returns: list of all Koji client config files. Example: ['/home/kdreyer/.koji/config.d/kojidev.conf', '/etc/koji.conf.d/stg.conf', '/etc/koji.conf.d/fedora.conf'] """ paths = [] for pattern in PROFILES: pattern = os.path.expanduser(pattern) paths += glob(pattern) return paths
[ "def", "profiles", "(", ")", ":", "paths", "=", "[", "]", "for", "pattern", "in", "PROFILES", ":", "pattern", "=", "os", ".", "path", ".", "expanduser", "(", "pattern", ")", "paths", "+=", "glob", "(", "pattern", ")", "return", "paths" ]
List of all the connection profile files, ordered by preference. :returns: list of all Koji client config files. Example: ['/home/kdreyer/.koji/config.d/kojidev.conf', '/etc/koji.conf.d/stg.conf', '/etc/koji.conf.d/fedora.conf']
[ "List", "of", "all", "the", "connection", "profile", "files", "ordered", "by", "preference", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L38-L51
train
ktdreyer/txkoji
txkoji/connection.py
Connection.lookup
def lookup(self, profile, setting): """ Check koji.conf.d files for this profile's setting. :param setting: ``str`` like "server" (for kojihub) or "weburl" :returns: ``str``, value for this setting """ for path in profiles(): cfg = SafeConfigParser() cfg.read(path) if profile not in cfg.sections(): continue if not cfg.has_option(profile, setting): continue return cfg.get(profile, setting)
python
def lookup(self, profile, setting): """ Check koji.conf.d files for this profile's setting. :param setting: ``str`` like "server" (for kojihub) or "weburl" :returns: ``str``, value for this setting """ for path in profiles(): cfg = SafeConfigParser() cfg.read(path) if profile not in cfg.sections(): continue if not cfg.has_option(profile, setting): continue return cfg.get(profile, setting)
[ "def", "lookup", "(", "self", ",", "profile", ",", "setting", ")", ":", "for", "path", "in", "profiles", "(", ")", ":", "cfg", "=", "SafeConfigParser", "(", ")", "cfg", ".", "read", "(", "path", ")", "if", "profile", "not", "in", "cfg", ".", "sections", "(", ")", ":", "continue", "if", "not", "cfg", ".", "has_option", "(", "profile", ",", "setting", ")", ":", "continue", "return", "cfg", ".", "get", "(", "profile", ",", "setting", ")" ]
Check koji.conf.d files for this profile's setting. :param setting: ``str`` like "server" (for kojihub) or "weburl" :returns: ``str``, value for this setting
[ "Check", "koji", ".", "conf", ".", "d", "files", "for", "this", "profile", "s", "setting", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L71-L84
train
ktdreyer/txkoji
txkoji/connection.py
Connection.connect_from_web
def connect_from_web(klass, url): """ Find a connection that matches this kojiweb URL. Check all koji.conf.d files' kojiweb URLs and load the profile that matches the url we pass in here. For example, if a user pastes a kojiweb URL into chat, we want to discover the corresponding Koji instance hub automatically. See also from_web(). :param url: ``str``, for example "http://cbs.centos.org/koji/buildinfo?buildID=21155" :returns: A "Connection" instance """ # Treat any input with whitespace as invalid: if re.search(r'\s', url): return url = url.split(' ', 1)[0] for path in profiles(): cfg = SafeConfigParser() cfg.read(path) for profile in cfg.sections(): if not cfg.has_option(profile, 'weburl'): continue weburl = cfg.get(profile, 'weburl') if url.startswith(weburl): return klass(profile)
python
def connect_from_web(klass, url): """ Find a connection that matches this kojiweb URL. Check all koji.conf.d files' kojiweb URLs and load the profile that matches the url we pass in here. For example, if a user pastes a kojiweb URL into chat, we want to discover the corresponding Koji instance hub automatically. See also from_web(). :param url: ``str``, for example "http://cbs.centos.org/koji/buildinfo?buildID=21155" :returns: A "Connection" instance """ # Treat any input with whitespace as invalid: if re.search(r'\s', url): return url = url.split(' ', 1)[0] for path in profiles(): cfg = SafeConfigParser() cfg.read(path) for profile in cfg.sections(): if not cfg.has_option(profile, 'weburl'): continue weburl = cfg.get(profile, 'weburl') if url.startswith(weburl): return klass(profile)
[ "def", "connect_from_web", "(", "klass", ",", "url", ")", ":", "# Treat any input with whitespace as invalid:", "if", "re", ".", "search", "(", "r'\\s'", ",", "url", ")", ":", "return", "url", "=", "url", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", "for", "path", "in", "profiles", "(", ")", ":", "cfg", "=", "SafeConfigParser", "(", ")", "cfg", ".", "read", "(", "path", ")", "for", "profile", "in", "cfg", ".", "sections", "(", ")", ":", "if", "not", "cfg", ".", "has_option", "(", "profile", ",", "'weburl'", ")", ":", "continue", "weburl", "=", "cfg", ".", "get", "(", "profile", ",", "'weburl'", ")", "if", "url", ".", "startswith", "(", "weburl", ")", ":", "return", "klass", "(", "profile", ")" ]
Find a connection that matches this kojiweb URL. Check all koji.conf.d files' kojiweb URLs and load the profile that matches the url we pass in here. For example, if a user pastes a kojiweb URL into chat, we want to discover the corresponding Koji instance hub automatically. See also from_web(). :param url: ``str``, for example "http://cbs.centos.org/koji/buildinfo?buildID=21155" :returns: A "Connection" instance
[ "Find", "a", "connection", "that", "matches", "this", "kojiweb", "URL", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L87-L115
train
ktdreyer/txkoji
txkoji/connection.py
Connection.from_web
def from_web(self, url): """ Reverse-engineer a kojiweb URL into an equivalent API response. Only a few kojiweb URL endpoints work here. See also connect_from_web(). :param url: ``str``, for example "http://cbs.centos.org/koji/buildinfo?buildID=21155" :returns: deferred that when fired returns a Munch (dict-like) object with data about this resource, or None if we could not parse the url. """ # Treat any input with whitespace as invalid: if re.search(r'\s', url): return defer.succeed(None) o = urlparse(url) endpoint = os.path.basename(o.path) if o.query: query = parse_qs(o.query) # Known Kojiweb endpoints: endpoints = { 'buildinfo': ('buildID', self.getBuild), 'channelinfo': ('channelID', self.getChannel), 'hostinfo': ('hostID', self.getHost), 'packageinfo': ('packageID', self.getPackage), 'taskinfo': ('taskID', self.getTaskInfo), 'taginfo': ('tagID', self.getTag), 'targetinfo': ('targetID', self.getTarget), 'userinfo': ('userID', self.getUser), } try: (param, method) = endpoints[endpoint] except KeyError: return defer.succeed(None) try: id_str = query[param][0] id_ = int(id_str) except (KeyError, ValueError): return defer.succeed(None) return method(id_)
python
def from_web(self, url): """ Reverse-engineer a kojiweb URL into an equivalent API response. Only a few kojiweb URL endpoints work here. See also connect_from_web(). :param url: ``str``, for example "http://cbs.centos.org/koji/buildinfo?buildID=21155" :returns: deferred that when fired returns a Munch (dict-like) object with data about this resource, or None if we could not parse the url. """ # Treat any input with whitespace as invalid: if re.search(r'\s', url): return defer.succeed(None) o = urlparse(url) endpoint = os.path.basename(o.path) if o.query: query = parse_qs(o.query) # Known Kojiweb endpoints: endpoints = { 'buildinfo': ('buildID', self.getBuild), 'channelinfo': ('channelID', self.getChannel), 'hostinfo': ('hostID', self.getHost), 'packageinfo': ('packageID', self.getPackage), 'taskinfo': ('taskID', self.getTaskInfo), 'taginfo': ('tagID', self.getTag), 'targetinfo': ('targetID', self.getTarget), 'userinfo': ('userID', self.getUser), } try: (param, method) = endpoints[endpoint] except KeyError: return defer.succeed(None) try: id_str = query[param][0] id_ = int(id_str) except (KeyError, ValueError): return defer.succeed(None) return method(id_)
[ "def", "from_web", "(", "self", ",", "url", ")", ":", "# Treat any input with whitespace as invalid:", "if", "re", ".", "search", "(", "r'\\s'", ",", "url", ")", ":", "return", "defer", ".", "succeed", "(", "None", ")", "o", "=", "urlparse", "(", "url", ")", "endpoint", "=", "os", ".", "path", ".", "basename", "(", "o", ".", "path", ")", "if", "o", ".", "query", ":", "query", "=", "parse_qs", "(", "o", ".", "query", ")", "# Known Kojiweb endpoints:", "endpoints", "=", "{", "'buildinfo'", ":", "(", "'buildID'", ",", "self", ".", "getBuild", ")", ",", "'channelinfo'", ":", "(", "'channelID'", ",", "self", ".", "getChannel", ")", ",", "'hostinfo'", ":", "(", "'hostID'", ",", "self", ".", "getHost", ")", ",", "'packageinfo'", ":", "(", "'packageID'", ",", "self", ".", "getPackage", ")", ",", "'taskinfo'", ":", "(", "'taskID'", ",", "self", ".", "getTaskInfo", ")", ",", "'taginfo'", ":", "(", "'tagID'", ",", "self", ".", "getTag", ")", ",", "'targetinfo'", ":", "(", "'targetID'", ",", "self", ".", "getTarget", ")", ",", "'userinfo'", ":", "(", "'userID'", ",", "self", ".", "getUser", ")", ",", "}", "try", ":", "(", "param", ",", "method", ")", "=", "endpoints", "[", "endpoint", "]", "except", "KeyError", ":", "return", "defer", ".", "succeed", "(", "None", ")", "try", ":", "id_str", "=", "query", "[", "param", "]", "[", "0", "]", "id_", "=", "int", "(", "id_str", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "return", "defer", ".", "succeed", "(", "None", ")", "return", "method", "(", "id_", ")" ]
Reverse-engineer a kojiweb URL into an equivalent API response. Only a few kojiweb URL endpoints work here. See also connect_from_web(). :param url: ``str``, for example "http://cbs.centos.org/koji/buildinfo?buildID=21155" :returns: deferred that when fired returns a Munch (dict-like) object with data about this resource, or None if we could not parse the url.
[ "Reverse", "-", "engineer", "a", "kojiweb", "URL", "into", "an", "equivalent", "API", "response", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L117-L158
train
ktdreyer/txkoji
txkoji/connection.py
Connection.call
def call(self, method, *args, **kwargs): """ Make an XML-RPC call to the server. If this client is logged in (with login()), this call will be authenticated. Koji has its own custom implementation of XML-RPC that supports named args (kwargs). For example, to use the "queryOpts" kwarg: d = client.call('listBuilds', package_id, queryOpts={'order': 'creation_ts'}) In this example, the server will order the list of builds according to the "creation_ts" database column. Many of Koji's XML-RPC methods have optional kwargs that you can set as needed. :returns: deferred that when fired returns a dict with data from this XML-RPC call. """ if kwargs: kwargs['__starstar'] = True args = args + (kwargs,) if self.session_id: self.proxy.path = self._authenticated_path() d = self.proxy.callRemote(method, *args) d.addCallback(self._munchify_callback) d.addErrback(self._parse_errback) if self.callnum is not None: self.callnum += 1 return d
python
def call(self, method, *args, **kwargs): """ Make an XML-RPC call to the server. If this client is logged in (with login()), this call will be authenticated. Koji has its own custom implementation of XML-RPC that supports named args (kwargs). For example, to use the "queryOpts" kwarg: d = client.call('listBuilds', package_id, queryOpts={'order': 'creation_ts'}) In this example, the server will order the list of builds according to the "creation_ts" database column. Many of Koji's XML-RPC methods have optional kwargs that you can set as needed. :returns: deferred that when fired returns a dict with data from this XML-RPC call. """ if kwargs: kwargs['__starstar'] = True args = args + (kwargs,) if self.session_id: self.proxy.path = self._authenticated_path() d = self.proxy.callRemote(method, *args) d.addCallback(self._munchify_callback) d.addErrback(self._parse_errback) if self.callnum is not None: self.callnum += 1 return d
[ "def", "call", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "kwargs", "[", "'__starstar'", "]", "=", "True", "args", "=", "args", "+", "(", "kwargs", ",", ")", "if", "self", ".", "session_id", ":", "self", ".", "proxy", ".", "path", "=", "self", ".", "_authenticated_path", "(", ")", "d", "=", "self", ".", "proxy", ".", "callRemote", "(", "method", ",", "*", "args", ")", "d", ".", "addCallback", "(", "self", ".", "_munchify_callback", ")", "d", ".", "addErrback", "(", "self", ".", "_parse_errback", ")", "if", "self", ".", "callnum", "is", "not", "None", ":", "self", ".", "callnum", "+=", "1", "return", "d" ]
Make an XML-RPC call to the server. If this client is logged in (with login()), this call will be authenticated. Koji has its own custom implementation of XML-RPC that supports named args (kwargs). For example, to use the "queryOpts" kwarg: d = client.call('listBuilds', package_id, queryOpts={'order': 'creation_ts'}) In this example, the server will order the list of builds according to the "creation_ts" database column. Many of Koji's XML-RPC methods have optional kwargs that you can set as needed. :returns: deferred that when fired returns a dict with data from this XML-RPC call.
[ "Make", "an", "XML", "-", "RPC", "call", "to", "the", "server", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L160-L190
train
ktdreyer/txkoji
txkoji/connection.py
Connection._authenticated_path
def _authenticated_path(self): """ Get the path of our XML-RPC endpoint with session auth params added. For example: /kojihub?session-id=123456&session-key=1234-asdf&callnum=0 If we're making an authenticated request, we must add these session parameters to the hub's XML-RPC endpoint. :return: a path suitable for twisted.web.xmlrpc.Proxy """ basepath = self.proxy.path.decode().split('?')[0] params = urlencode({'session-id': self.session_id, 'session-key': self.session_key, 'callnum': self.callnum}) result = '%s?%s' % (basepath, params) return result.encode('utf-8')
python
def _authenticated_path(self): """ Get the path of our XML-RPC endpoint with session auth params added. For example: /kojihub?session-id=123456&session-key=1234-asdf&callnum=0 If we're making an authenticated request, we must add these session parameters to the hub's XML-RPC endpoint. :return: a path suitable for twisted.web.xmlrpc.Proxy """ basepath = self.proxy.path.decode().split('?')[0] params = urlencode({'session-id': self.session_id, 'session-key': self.session_key, 'callnum': self.callnum}) result = '%s?%s' % (basepath, params) return result.encode('utf-8')
[ "def", "_authenticated_path", "(", "self", ")", ":", "basepath", "=", "self", ".", "proxy", ".", "path", ".", "decode", "(", ")", ".", "split", "(", "'?'", ")", "[", "0", "]", "params", "=", "urlencode", "(", "{", "'session-id'", ":", "self", ".", "session_id", ",", "'session-key'", ":", "self", ".", "session_key", ",", "'callnum'", ":", "self", ".", "callnum", "}", ")", "result", "=", "'%s?%s'", "%", "(", "basepath", ",", "params", ")", "return", "result", ".", "encode", "(", "'utf-8'", ")" ]
Get the path of our XML-RPC endpoint with session auth params added. For example: /kojihub?session-id=123456&session-key=1234-asdf&callnum=0 If we're making an authenticated request, we must add these session parameters to the hub's XML-RPC endpoint. :return: a path suitable for twisted.web.xmlrpc.Proxy
[ "Get", "the", "path", "of", "our", "XML", "-", "RPC", "endpoint", "with", "session", "auth", "params", "added", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L192-L209
train
ktdreyer/txkoji
txkoji/connection.py
Connection.getAverageBuildDuration
def getAverageBuildDuration(self, package, **kwargs): """ Return a timedelta that Koji considers to be average for this package. Calls "getAverageBuildDuration" XML-RPC. :param package: ``str``, for example "ceph" :returns: deferred that when fired returns a datetime object for the estimated duration, or None if we could find no estimate for this package. """ seconds = yield self.call('getAverageBuildDuration', package, **kwargs) if seconds is None: defer.returnValue(None) defer.returnValue(timedelta(seconds=seconds))
python
def getAverageBuildDuration(self, package, **kwargs): """ Return a timedelta that Koji considers to be average for this package. Calls "getAverageBuildDuration" XML-RPC. :param package: ``str``, for example "ceph" :returns: deferred that when fired returns a datetime object for the estimated duration, or None if we could find no estimate for this package. """ seconds = yield self.call('getAverageBuildDuration', package, **kwargs) if seconds is None: defer.returnValue(None) defer.returnValue(timedelta(seconds=seconds))
[ "def", "getAverageBuildDuration", "(", "self", ",", "package", ",", "*", "*", "kwargs", ")", ":", "seconds", "=", "yield", "self", ".", "call", "(", "'getAverageBuildDuration'", ",", "package", ",", "*", "*", "kwargs", ")", "if", "seconds", "is", "None", ":", "defer", ".", "returnValue", "(", "None", ")", "defer", ".", "returnValue", "(", "timedelta", "(", "seconds", "=", "seconds", ")", ")" ]
Return a timedelta that Koji considers to be average for this package. Calls "getAverageBuildDuration" XML-RPC. :param package: ``str``, for example "ceph" :returns: deferred that when fired returns a datetime object for the estimated duration, or None if we could find no estimate for this package.
[ "Return", "a", "timedelta", "that", "Koji", "considers", "to", "be", "average", "for", "this", "package", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L215-L229
train
ktdreyer/txkoji
txkoji/connection.py
Connection.getBuild
def getBuild(self, build_id, **kwargs): """ Load all information about a build and return a custom Build class. Calls "getBuild" XML-RPC. :param build_id: ``int``, for example 12345 :returns: deferred that when fired returns a Build (Munch, dict-like) object representing this Koji build, or None if no build was found. """ buildinfo = yield self.call('getBuild', build_id, **kwargs) build = Build.fromDict(buildinfo) if build: build.connection = self defer.returnValue(build)
python
def getBuild(self, build_id, **kwargs): """ Load all information about a build and return a custom Build class. Calls "getBuild" XML-RPC. :param build_id: ``int``, for example 12345 :returns: deferred that when fired returns a Build (Munch, dict-like) object representing this Koji build, or None if no build was found. """ buildinfo = yield self.call('getBuild', build_id, **kwargs) build = Build.fromDict(buildinfo) if build: build.connection = self defer.returnValue(build)
[ "def", "getBuild", "(", "self", ",", "build_id", ",", "*", "*", "kwargs", ")", ":", "buildinfo", "=", "yield", "self", ".", "call", "(", "'getBuild'", ",", "build_id", ",", "*", "*", "kwargs", ")", "build", "=", "Build", ".", "fromDict", "(", "buildinfo", ")", "if", "build", ":", "build", ".", "connection", "=", "self", "defer", ".", "returnValue", "(", "build", ")" ]
Load all information about a build and return a custom Build class. Calls "getBuild" XML-RPC. :param build_id: ``int``, for example 12345 :returns: deferred that when fired returns a Build (Munch, dict-like) object representing this Koji build, or None if no build was found.
[ "Load", "all", "information", "about", "a", "build", "and", "return", "a", "custom", "Build", "class", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L232-L247
train
ktdreyer/txkoji
txkoji/connection.py
Connection.getChannel
def getChannel(self, channel_id, **kwargs): """ Load all information about a channel and return a custom Channel class. Calls "getChannel" XML-RPC. :param channel_id: ``int``, for example 12345, or ``str`` for name. :returns: deferred that when fired returns a Channel (Munch, dict-like) object representing this Koji channel, or None if no channel was found. """ channelinfo = yield self.call('getChannel', channel_id, **kwargs) channel = Channel.fromDict(channelinfo) if channel: channel.connection = self defer.returnValue(channel)
python
def getChannel(self, channel_id, **kwargs): """ Load all information about a channel and return a custom Channel class. Calls "getChannel" XML-RPC. :param channel_id: ``int``, for example 12345, or ``str`` for name. :returns: deferred that when fired returns a Channel (Munch, dict-like) object representing this Koji channel, or None if no channel was found. """ channelinfo = yield self.call('getChannel', channel_id, **kwargs) channel = Channel.fromDict(channelinfo) if channel: channel.connection = self defer.returnValue(channel)
[ "def", "getChannel", "(", "self", ",", "channel_id", ",", "*", "*", "kwargs", ")", ":", "channelinfo", "=", "yield", "self", ".", "call", "(", "'getChannel'", ",", "channel_id", ",", "*", "*", "kwargs", ")", "channel", "=", "Channel", ".", "fromDict", "(", "channelinfo", ")", "if", "channel", ":", "channel", ".", "connection", "=", "self", "defer", ".", "returnValue", "(", "channel", ")" ]
Load all information about a channel and return a custom Channel class. Calls "getChannel" XML-RPC. :param channel_id: ``int``, for example 12345, or ``str`` for name. :returns: deferred that when fired returns a Channel (Munch, dict-like) object representing this Koji channel, or None if no channel was found.
[ "Load", "all", "information", "about", "a", "channel", "and", "return", "a", "custom", "Channel", "class", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L250-L265
train
ktdreyer/txkoji
txkoji/connection.py
Connection.getPackage
def getPackage(self, name, **kwargs): """ Load information about a package and return a custom Package class. Calls "getPackage" XML-RPC. :param package_id: ``int``, for example 12345 :returns: deferred that when fired returns a Package (Munch, dict-like) object representing this Koji package, or None if no build was found. """ packageinfo = yield self.call('getPackage', name, **kwargs) package = Package.fromDict(packageinfo) if package: package.connection = self defer.returnValue(package)
python
def getPackage(self, name, **kwargs): """ Load information about a package and return a custom Package class. Calls "getPackage" XML-RPC. :param package_id: ``int``, for example 12345 :returns: deferred that when fired returns a Package (Munch, dict-like) object representing this Koji package, or None if no build was found. """ packageinfo = yield self.call('getPackage', name, **kwargs) package = Package.fromDict(packageinfo) if package: package.connection = self defer.returnValue(package)
[ "def", "getPackage", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "packageinfo", "=", "yield", "self", ".", "call", "(", "'getPackage'", ",", "name", ",", "*", "*", "kwargs", ")", "package", "=", "Package", ".", "fromDict", "(", "packageinfo", ")", "if", "package", ":", "package", ".", "connection", "=", "self", "defer", ".", "returnValue", "(", "package", ")" ]
Load information about a package and return a custom Package class. Calls "getPackage" XML-RPC. :param package_id: ``int``, for example 12345 :returns: deferred that when fired returns a Package (Munch, dict-like) object representing this Koji package, or None if no build was found.
[ "Load", "information", "about", "a", "package", "and", "return", "a", "custom", "Package", "class", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L268-L283
train
ktdreyer/txkoji
txkoji/connection.py
Connection.getTaskDescendents
def getTaskDescendents(self, task_id, **kwargs): """ Load all information about a task's descendents into Task classes. Calls "getTaskDescendents" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345, parent task ID :returns: deferred that when fired returns a list of Task (Munch, dict-like) objects representing Koji tasks. """ kwargs['request'] = True data = yield self.call('getTaskDescendents', task_id, **kwargs) tasks = [] for tdata in data[str(task_id)]: task = Task.fromDict(tdata) task.connection = self tasks.append(task) defer.returnValue(tasks)
python
def getTaskDescendents(self, task_id, **kwargs): """ Load all information about a task's descendents into Task classes. Calls "getTaskDescendents" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345, parent task ID :returns: deferred that when fired returns a list of Task (Munch, dict-like) objects representing Koji tasks. """ kwargs['request'] = True data = yield self.call('getTaskDescendents', task_id, **kwargs) tasks = [] for tdata in data[str(task_id)]: task = Task.fromDict(tdata) task.connection = self tasks.append(task) defer.returnValue(tasks)
[ "def", "getTaskDescendents", "(", "self", ",", "task_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'request'", "]", "=", "True", "data", "=", "yield", "self", ".", "call", "(", "'getTaskDescendents'", ",", "task_id", ",", "*", "*", "kwargs", ")", "tasks", "=", "[", "]", "for", "tdata", "in", "data", "[", "str", "(", "task_id", ")", "]", ":", "task", "=", "Task", ".", "fromDict", "(", "tdata", ")", "task", ".", "connection", "=", "self", "tasks", ".", "append", "(", "task", ")", "defer", ".", "returnValue", "(", "tasks", ")" ]
Load all information about a task's descendents into Task classes. Calls "getTaskDescendents" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345, parent task ID :returns: deferred that when fired returns a list of Task (Munch, dict-like) objects representing Koji tasks.
[ "Load", "all", "information", "about", "a", "task", "s", "descendents", "into", "Task", "classes", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L286-L304
train
ktdreyer/txkoji
txkoji/connection.py
Connection.getTaskInfo
def getTaskInfo(self, task_id, **kwargs): """ Load all information about a task and return a custom Task class. Calls "getTaskInfo" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345 :returns: deferred that when fired returns a Task (Munch, dict-like) object representing this Koji task, or none if no task was found. """ kwargs['request'] = True taskinfo = yield self.call('getTaskInfo', task_id, **kwargs) task = Task.fromDict(taskinfo) if task: task.connection = self defer.returnValue(task)
python
def getTaskInfo(self, task_id, **kwargs): """ Load all information about a task and return a custom Task class. Calls "getTaskInfo" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345 :returns: deferred that when fired returns a Task (Munch, dict-like) object representing this Koji task, or none if no task was found. """ kwargs['request'] = True taskinfo = yield self.call('getTaskInfo', task_id, **kwargs) task = Task.fromDict(taskinfo) if task: task.connection = self defer.returnValue(task)
[ "def", "getTaskInfo", "(", "self", ",", "task_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'request'", "]", "=", "True", "taskinfo", "=", "yield", "self", ".", "call", "(", "'getTaskInfo'", ",", "task_id", ",", "*", "*", "kwargs", ")", "task", "=", "Task", ".", "fromDict", "(", "taskinfo", ")", "if", "task", ":", "task", ".", "connection", "=", "self", "defer", ".", "returnValue", "(", "task", ")" ]
Load all information about a task and return a custom Task class. Calls "getTaskInfo" XML-RPC (with request=True to get the full information.) :param task_id: ``int``, for example 12345 :returns: deferred that when fired returns a Task (Munch, dict-like) object representing this Koji task, or none if no task was found.
[ "Load", "all", "information", "about", "a", "task", "and", "return", "a", "custom", "Task", "class", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L307-L324
train
ktdreyer/txkoji
txkoji/connection.py
Connection.listBuilds
def listBuilds(self, package, **kwargs): """ Get information about all builds of a package. Calls "listBuilds" XML-RPC, with an enhancement: you can also pass a string here for the package name instead of the package ID number. See https://pagure.io/koji/issue/1209 for implementing this server-side. :param package: ``int`` (packageID) or ``str`` (package name). :returns: deferred that when fired returns a list of Build objects for this package. """ if isinstance(package, int): package_id = package else: package_data = yield self.getPackage(package) if package_data is None: defer.returnValue([]) package_id = package_data.id data = yield self.call('listBuilds', package_id, **kwargs) builds = [] for bdata in data: build = Build.fromDict(bdata) build.connection = self builds.append(build) defer.returnValue(builds)
python
def listBuilds(self, package, **kwargs): """ Get information about all builds of a package. Calls "listBuilds" XML-RPC, with an enhancement: you can also pass a string here for the package name instead of the package ID number. See https://pagure.io/koji/issue/1209 for implementing this server-side. :param package: ``int`` (packageID) or ``str`` (package name). :returns: deferred that when fired returns a list of Build objects for this package. """ if isinstance(package, int): package_id = package else: package_data = yield self.getPackage(package) if package_data is None: defer.returnValue([]) package_id = package_data.id data = yield self.call('listBuilds', package_id, **kwargs) builds = [] for bdata in data: build = Build.fromDict(bdata) build.connection = self builds.append(build) defer.returnValue(builds)
[ "def", "listBuilds", "(", "self", ",", "package", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "package", ",", "int", ")", ":", "package_id", "=", "package", "else", ":", "package_data", "=", "yield", "self", ".", "getPackage", "(", "package", ")", "if", "package_data", "is", "None", ":", "defer", ".", "returnValue", "(", "[", "]", ")", "package_id", "=", "package_data", ".", "id", "data", "=", "yield", "self", ".", "call", "(", "'listBuilds'", ",", "package_id", ",", "*", "*", "kwargs", ")", "builds", "=", "[", "]", "for", "bdata", "in", "data", ":", "build", "=", "Build", ".", "fromDict", "(", "bdata", ")", "build", ".", "connection", "=", "self", "builds", ".", "append", "(", "build", ")", "defer", ".", "returnValue", "(", "builds", ")" ]
Get information about all builds of a package. Calls "listBuilds" XML-RPC, with an enhancement: you can also pass a string here for the package name instead of the package ID number. See https://pagure.io/koji/issue/1209 for implementing this server-side. :param package: ``int`` (packageID) or ``str`` (package name). :returns: deferred that when fired returns a list of Build objects for this package.
[ "Get", "information", "about", "all", "builds", "of", "a", "package", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L327-L353
train
ktdreyer/txkoji
txkoji/connection.py
Connection.listTagged
def listTagged(self, *args, **kwargs): """ List builds tagged with a tag. Calls "listTagged" XML-RPC. :returns: deferred that when fired returns a list of Build objects. """ data = yield self.call('listTagged', *args, **kwargs) builds = [] for bdata in data: build = Build.fromDict(bdata) build.connection = self builds.append(build) defer.returnValue(builds)
python
def listTagged(self, *args, **kwargs): """ List builds tagged with a tag. Calls "listTagged" XML-RPC. :returns: deferred that when fired returns a list of Build objects. """ data = yield self.call('listTagged', *args, **kwargs) builds = [] for bdata in data: build = Build.fromDict(bdata) build.connection = self builds.append(build) defer.returnValue(builds)
[ "def", "listTagged", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "yield", "self", ".", "call", "(", "'listTagged'", ",", "*", "args", ",", "*", "*", "kwargs", ")", "builds", "=", "[", "]", "for", "bdata", "in", "data", ":", "build", "=", "Build", ".", "fromDict", "(", "bdata", ")", "build", ".", "connection", "=", "self", "builds", ".", "append", "(", "build", ")", "defer", ".", "returnValue", "(", "builds", ")" ]
List builds tagged with a tag. Calls "listTagged" XML-RPC. :returns: deferred that when fired returns a list of Build objects.
[ "List", "builds", "tagged", "with", "a", "tag", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L356-L370
train
ktdreyer/txkoji
txkoji/connection.py
Connection.listTasks
def listTasks(self, opts={}, queryOpts={}): """ Get information about all Koji tasks. Calls "listTasks" XML-RPC. :param dict opts: Eg. {'state': [task_states.OPEN]} :param dict queryOpts: Eg. {'order' : 'priority,create_time'} :returns: deferred that when fired returns a list of Task objects. """ opts['decode'] = True # decode xmlrpc data in "request" data = yield self.call('listTasks', opts, queryOpts) tasks = [] for tdata in data: task = Task.fromDict(tdata) task.connection = self tasks.append(task) defer.returnValue(tasks)
python
def listTasks(self, opts={}, queryOpts={}): """ Get information about all Koji tasks. Calls "listTasks" XML-RPC. :param dict opts: Eg. {'state': [task_states.OPEN]} :param dict queryOpts: Eg. {'order' : 'priority,create_time'} :returns: deferred that when fired returns a list of Task objects. """ opts['decode'] = True # decode xmlrpc data in "request" data = yield self.call('listTasks', opts, queryOpts) tasks = [] for tdata in data: task = Task.fromDict(tdata) task.connection = self tasks.append(task) defer.returnValue(tasks)
[ "def", "listTasks", "(", "self", ",", "opts", "=", "{", "}", ",", "queryOpts", "=", "{", "}", ")", ":", "opts", "[", "'decode'", "]", "=", "True", "# decode xmlrpc data in \"request\"", "data", "=", "yield", "self", ".", "call", "(", "'listTasks'", ",", "opts", ",", "queryOpts", ")", "tasks", "=", "[", "]", "for", "tdata", "in", "data", ":", "task", "=", "Task", ".", "fromDict", "(", "tdata", ")", "task", ".", "connection", "=", "self", "tasks", ".", "append", "(", "task", ")", "defer", ".", "returnValue", "(", "tasks", ")" ]
Get information about all Koji tasks. Calls "listTasks" XML-RPC. :param dict opts: Eg. {'state': [task_states.OPEN]} :param dict queryOpts: Eg. {'order' : 'priority,create_time'} :returns: deferred that when fired returns a list of Task objects.
[ "Get", "information", "about", "all", "Koji", "tasks", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L373-L390
train
ktdreyer/txkoji
txkoji/connection.py
Connection.listChannels
def listChannels(self, **kwargs): """ Get information about all Koji channels. :param **kwargs: keyword args to pass through to listChannels RPC. :returns: deferred that when fired returns a list of Channel objects. """ data = yield self.call('listChannels', **kwargs) channels = [] for cdata in data: channel = Channel.fromDict(cdata) channel.connection = self channels.append(channel) defer.returnValue(channels)
python
def listChannels(self, **kwargs): """ Get information about all Koji channels. :param **kwargs: keyword args to pass through to listChannels RPC. :returns: deferred that when fired returns a list of Channel objects. """ data = yield self.call('listChannels', **kwargs) channels = [] for cdata in data: channel = Channel.fromDict(cdata) channel.connection = self channels.append(channel) defer.returnValue(channels)
[ "def", "listChannels", "(", "self", ",", "*", "*", "kwargs", ")", ":", "data", "=", "yield", "self", ".", "call", "(", "'listChannels'", ",", "*", "*", "kwargs", ")", "channels", "=", "[", "]", "for", "cdata", "in", "data", ":", "channel", "=", "Channel", ".", "fromDict", "(", "cdata", ")", "channel", ".", "connection", "=", "self", "channels", ".", "append", "(", "channel", ")", "defer", ".", "returnValue", "(", "channels", ")" ]
Get information about all Koji channels. :param **kwargs: keyword args to pass through to listChannels RPC. :returns: deferred that when fired returns a list of Channel objects.
[ "Get", "information", "about", "all", "Koji", "channels", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L393-L406
train
ktdreyer/txkoji
txkoji/connection.py
Connection.login
def login(self): """ Return True if we successfully logged into this Koji hub. We support GSSAPI and SSL Client authentication (not the old-style krb-over-xmlrpc krbLogin method). :returns: deferred that when fired returns True """ authtype = self.lookup(self.profile, 'authtype') if authtype is None: cert = self.lookup(self.profile, 'cert') if cert and os.path.isfile(os.path.expanduser(cert)): authtype = 'ssl' # Note: official koji cli is a little more lax here. If authtype is # None and we have a valid kerberos ccache, we still try kerberos # auth. if authtype == 'kerberos': # Note: we don't try the old-style kerberos login here. result = yield self._gssapi_login() elif authtype == 'ssl': result = yield self._ssl_login() else: raise NotImplementedError('unsupported auth: %s' % authtype) self.session_id = result['session-id'] self.session_key = result['session-key'] self.callnum = 0 # increment this on every call for this session. defer.returnValue(True)
python
def login(self): """ Return True if we successfully logged into this Koji hub. We support GSSAPI and SSL Client authentication (not the old-style krb-over-xmlrpc krbLogin method). :returns: deferred that when fired returns True """ authtype = self.lookup(self.profile, 'authtype') if authtype is None: cert = self.lookup(self.profile, 'cert') if cert and os.path.isfile(os.path.expanduser(cert)): authtype = 'ssl' # Note: official koji cli is a little more lax here. If authtype is # None and we have a valid kerberos ccache, we still try kerberos # auth. if authtype == 'kerberos': # Note: we don't try the old-style kerberos login here. result = yield self._gssapi_login() elif authtype == 'ssl': result = yield self._ssl_login() else: raise NotImplementedError('unsupported auth: %s' % authtype) self.session_id = result['session-id'] self.session_key = result['session-key'] self.callnum = 0 # increment this on every call for this session. defer.returnValue(True)
[ "def", "login", "(", "self", ")", ":", "authtype", "=", "self", ".", "lookup", "(", "self", ".", "profile", ",", "'authtype'", ")", "if", "authtype", "is", "None", ":", "cert", "=", "self", ".", "lookup", "(", "self", ".", "profile", ",", "'cert'", ")", "if", "cert", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "expanduser", "(", "cert", ")", ")", ":", "authtype", "=", "'ssl'", "# Note: official koji cli is a little more lax here. If authtype is", "# None and we have a valid kerberos ccache, we still try kerberos", "# auth.", "if", "authtype", "==", "'kerberos'", ":", "# Note: we don't try the old-style kerberos login here.", "result", "=", "yield", "self", ".", "_gssapi_login", "(", ")", "elif", "authtype", "==", "'ssl'", ":", "result", "=", "yield", "self", ".", "_ssl_login", "(", ")", "else", ":", "raise", "NotImplementedError", "(", "'unsupported auth: %s'", "%", "authtype", ")", "self", ".", "session_id", "=", "result", "[", "'session-id'", "]", "self", ".", "session_key", "=", "result", "[", "'session-key'", "]", "self", ".", "callnum", "=", "0", "# increment this on every call for this session.", "defer", ".", "returnValue", "(", "True", ")" ]
Return True if we successfully logged into this Koji hub. We support GSSAPI and SSL Client authentication (not the old-style krb-over-xmlrpc krbLogin method). :returns: deferred that when fired returns True
[ "Return", "True", "if", "we", "successfully", "logged", "into", "this", "Koji", "hub", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L412-L439
train
ktdreyer/txkoji
txkoji/connection.py
Connection._ssl_agent
def _ssl_agent(self): """ Get a Twisted Agent that performs Client SSL authentication for Koji. """ # Load "cert" into a PrivateCertificate. certfile = self.lookup(self.profile, 'cert') certfile = os.path.expanduser(certfile) with open(certfile) as certfp: pemdata = certfp.read() client_cert = PrivateCertificate.loadPEM(pemdata) trustRoot = None # Use Twisted's platformTrust(). # Optionally load "serverca" into a Certificate. servercafile = self.lookup(self.profile, 'serverca') if servercafile: servercafile = os.path.expanduser(servercafile) trustRoot = RootCATrustRoot(servercafile) policy = ClientCertPolicy(trustRoot=trustRoot, client_cert=client_cert) return Agent(reactor, policy)
python
def _ssl_agent(self): """ Get a Twisted Agent that performs Client SSL authentication for Koji. """ # Load "cert" into a PrivateCertificate. certfile = self.lookup(self.profile, 'cert') certfile = os.path.expanduser(certfile) with open(certfile) as certfp: pemdata = certfp.read() client_cert = PrivateCertificate.loadPEM(pemdata) trustRoot = None # Use Twisted's platformTrust(). # Optionally load "serverca" into a Certificate. servercafile = self.lookup(self.profile, 'serverca') if servercafile: servercafile = os.path.expanduser(servercafile) trustRoot = RootCATrustRoot(servercafile) policy = ClientCertPolicy(trustRoot=trustRoot, client_cert=client_cert) return Agent(reactor, policy)
[ "def", "_ssl_agent", "(", "self", ")", ":", "# Load \"cert\" into a PrivateCertificate.", "certfile", "=", "self", ".", "lookup", "(", "self", ".", "profile", ",", "'cert'", ")", "certfile", "=", "os", ".", "path", ".", "expanduser", "(", "certfile", ")", "with", "open", "(", "certfile", ")", "as", "certfp", ":", "pemdata", "=", "certfp", ".", "read", "(", ")", "client_cert", "=", "PrivateCertificate", ".", "loadPEM", "(", "pemdata", ")", "trustRoot", "=", "None", "# Use Twisted's platformTrust().", "# Optionally load \"serverca\" into a Certificate.", "servercafile", "=", "self", ".", "lookup", "(", "self", ".", "profile", ",", "'serverca'", ")", "if", "servercafile", ":", "servercafile", "=", "os", ".", "path", ".", "expanduser", "(", "servercafile", ")", "trustRoot", "=", "RootCATrustRoot", "(", "servercafile", ")", "policy", "=", "ClientCertPolicy", "(", "trustRoot", "=", "trustRoot", ",", "client_cert", "=", "client_cert", ")", "return", "Agent", "(", "reactor", ",", "policy", ")" ]
Get a Twisted Agent that performs Client SSL authentication for Koji.
[ "Get", "a", "Twisted", "Agent", "that", "performs", "Client", "SSL", "authentication", "for", "Koji", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/connection.py#L451-L470
train
shapiromatron/bmds
bmds/logic/recommender.py
Recommender._get_bmdl_ratio
def _get_bmdl_ratio(self, models): """Return BMDL ratio in list of models.""" bmdls = [model.output["BMDL"] for model in models if model.output["BMDL"] > 0] return max(bmdls) / min(bmdls) if len(bmdls) > 0 else 0
python
def _get_bmdl_ratio(self, models): """Return BMDL ratio in list of models.""" bmdls = [model.output["BMDL"] for model in models if model.output["BMDL"] > 0] return max(bmdls) / min(bmdls) if len(bmdls) > 0 else 0
[ "def", "_get_bmdl_ratio", "(", "self", ",", "models", ")", ":", "bmdls", "=", "[", "model", ".", "output", "[", "\"BMDL\"", "]", "for", "model", "in", "models", "if", "model", ".", "output", "[", "\"BMDL\"", "]", ">", "0", "]", "return", "max", "(", "bmdls", ")", "/", "min", "(", "bmdls", ")", "if", "len", "(", "bmdls", ")", ">", "0", "else", "0" ]
Return BMDL ratio in list of models.
[ "Return", "BMDL", "ratio", "in", "list", "of", "models", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/logic/recommender.py#L129-L133
train
shapiromatron/bmds
bmds/logic/recommender.py
Recommender._get_parsimonious_model
def _get_parsimonious_model(models): """ Return the most parsimonious model of all available models. The most parsimonious model is defined as the model with the fewest number of parameters. """ params = [len(model.output["parameters"]) for model in models] idx = params.index(min(params)) return models[idx]
python
def _get_parsimonious_model(models): """ Return the most parsimonious model of all available models. The most parsimonious model is defined as the model with the fewest number of parameters. """ params = [len(model.output["parameters"]) for model in models] idx = params.index(min(params)) return models[idx]
[ "def", "_get_parsimonious_model", "(", "models", ")", ":", "params", "=", "[", "len", "(", "model", ".", "output", "[", "\"parameters\"", "]", ")", "for", "model", "in", "models", "]", "idx", "=", "params", ".", "index", "(", "min", "(", "params", ")", ")", "return", "models", "[", "idx", "]" ]
Return the most parsimonious model of all available models. The most parsimonious model is defined as the model with the fewest number of parameters.
[ "Return", "the", "most", "parsimonious", "model", "of", "all", "available", "models", ".", "The", "most", "parsimonious", "model", "is", "defined", "as", "the", "model", "with", "the", "fewest", "number", "of", "parameters", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/logic/recommender.py#L145-L153
train
rraadd88/rohan
rohan/dandage/io_strs.py
make_pathable_string
def make_pathable_string(s,replacewith='_'): """ Removes symbols from a string to be compatible with directory structure. :param s: string """ import re return re.sub(r'[^\w+/.]',replacewith, s.lower())
python
def make_pathable_string(s,replacewith='_'): """ Removes symbols from a string to be compatible with directory structure. :param s: string """ import re return re.sub(r'[^\w+/.]',replacewith, s.lower())
[ "def", "make_pathable_string", "(", "s", ",", "replacewith", "=", "'_'", ")", ":", "import", "re", "return", "re", ".", "sub", "(", "r'[^\\w+/.]'", ",", "replacewith", ",", "s", ".", "lower", "(", ")", ")" ]
Removes symbols from a string to be compatible with directory structure. :param s: string
[ "Removes", "symbols", "from", "a", "string", "to", "be", "compatible", "with", "directory", "structure", "." ]
b0643a3582a2fffc0165ace69fb80880d92bfb10
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_strs.py#L120-L127
train
rraadd88/rohan
rohan/dandage/io_strs.py
get_time
def get_time(): """ Gets current time in a form of a formated string. Used in logger function. """ import datetime time=make_pathable_string('%s' % datetime.datetime.now()) return time.replace('-','_').replace(':','_').replace('.','_')
python
def get_time(): """ Gets current time in a form of a formated string. Used in logger function. """ import datetime time=make_pathable_string('%s' % datetime.datetime.now()) return time.replace('-','_').replace(':','_').replace('.','_')
[ "def", "get_time", "(", ")", ":", "import", "datetime", "time", "=", "make_pathable_string", "(", "'%s'", "%", "datetime", ".", "datetime", ".", "now", "(", ")", ")", "return", "time", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "replace", "(", "':'", ",", "'_'", ")", ".", "replace", "(", "'.'", ",", "'_'", ")" ]
Gets current time in a form of a formated string. Used in logger function.
[ "Gets", "current", "time", "in", "a", "form", "of", "a", "formated", "string", ".", "Used", "in", "logger", "function", "." ]
b0643a3582a2fffc0165ace69fb80880d92bfb10
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_strs.py#L174-L181
train
The-Politico/politico-civic-election-night
electionnight/management/commands/methods/bootstrap/general_election.py
GeneralElection.bootstrap_general_election
def bootstrap_general_election(self, election): """ Create a general election page type """ election_day = election.election_day page_type, created = PageType.objects.get_or_create( model_type=ContentType.objects.get( app_label="election", model="electionday" ), election_day=election_day, ) PageContent.objects.get_or_create( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, )
python
def bootstrap_general_election(self, election): """ Create a general election page type """ election_day = election.election_day page_type, created = PageType.objects.get_or_create( model_type=ContentType.objects.get( app_label="election", model="electionday" ), election_day=election_day, ) PageContent.objects.get_or_create( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, )
[ "def", "bootstrap_general_election", "(", "self", ",", "election", ")", ":", "election_day", "=", "election", ".", "election_day", "page_type", ",", "created", "=", "PageType", ".", "objects", ".", "get_or_create", "(", "model_type", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "\"election\"", ",", "model", "=", "\"electionday\"", ")", ",", "election_day", "=", "election_day", ",", ")", "PageContent", ".", "objects", ".", "get_or_create", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "page_type", ")", ",", "object_id", "=", "page_type", ".", "pk", ",", "election_day", "=", "election_day", ",", ")" ]
Create a general election page type
[ "Create", "a", "general", "election", "page", "type" ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/methods/bootstrap/general_election.py#L6-L21
train
tjcsl/cslbot
cslbot/commands/wtf.py
cmd
def cmd(send, msg, _): """Tells you what acronyms mean. Syntax: {command} <term> """ try: answer = subprocess.check_output(['wtf', msg], stderr=subprocess.STDOUT) send(answer.decode().strip().replace('\n', ' or ').replace('fuck', 'fsck')) except subprocess.CalledProcessError as ex: send(ex.output.decode().rstrip().splitlines()[0])
python
def cmd(send, msg, _): """Tells you what acronyms mean. Syntax: {command} <term> """ try: answer = subprocess.check_output(['wtf', msg], stderr=subprocess.STDOUT) send(answer.decode().strip().replace('\n', ' or ').replace('fuck', 'fsck')) except subprocess.CalledProcessError as ex: send(ex.output.decode().rstrip().splitlines()[0])
[ "def", "cmd", "(", "send", ",", "msg", ",", "_", ")", ":", "try", ":", "answer", "=", "subprocess", ".", "check_output", "(", "[", "'wtf'", ",", "msg", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "send", "(", "answer", ".", "decode", "(", ")", ".", "strip", "(", ")", ".", "replace", "(", "'\\n'", ",", "' or '", ")", ".", "replace", "(", "'fuck'", ",", "'fsck'", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "ex", ":", "send", "(", "ex", ".", "output", ".", "decode", "(", ")", ".", "rstrip", "(", ")", ".", "splitlines", "(", ")", "[", "0", "]", ")" ]
Tells you what acronyms mean. Syntax: {command} <term>
[ "Tells", "you", "what", "acronyms", "mean", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wtf.py#L24-L34
train
kodethon/KoDrive
kodrive/cli.py
sys
def sys(**kwargs): ''' Manage system configuration. ''' output, err = cli_syncthing_adapter.sys(**kwargs) if output: click.echo("%s" % output, err=err) else: if not kwargs['init']: click.echo(click.get_current_context().get_help())
python
def sys(**kwargs): ''' Manage system configuration. ''' output, err = cli_syncthing_adapter.sys(**kwargs) if output: click.echo("%s" % output, err=err) else: if not kwargs['init']: click.echo(click.get_current_context().get_help())
[ "def", "sys", "(", "*", "*", "kwargs", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "sys", "(", "*", "*", "kwargs", ")", "if", "output", ":", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")", "else", ":", "if", "not", "kwargs", "[", "'init'", "]", ":", "click", ".", "echo", "(", "click", ".", "get_current_context", "(", ")", ".", "get_help", "(", ")", ")" ]
Manage system configuration.
[ "Manage", "system", "configuration", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L32-L41
train
kodethon/KoDrive
kodrive/cli.py
ls
def ls(): ''' List all synchronized directories. ''' heading, body = cli_syncthing_adapter.ls() if heading: click.echo(heading) if body: click.echo(body.strip())
python
def ls(): ''' List all synchronized directories. ''' heading, body = cli_syncthing_adapter.ls() if heading: click.echo(heading) if body: click.echo(body.strip())
[ "def", "ls", "(", ")", ":", "heading", ",", "body", "=", "cli_syncthing_adapter", ".", "ls", "(", ")", "if", "heading", ":", "click", ".", "echo", "(", "heading", ")", "if", "body", ":", "click", ".", "echo", "(", "body", ".", "strip", "(", ")", ")" ]
List all synchronized directories.
[ "List", "all", "synchronized", "directories", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L45-L54
train
kodethon/KoDrive
kodrive/cli.py
auth
def auth(**kwargs): ''' Authorize device synchronization. ''' """ kodrive auth <path> <device_id (client)> 1. make sure path has been added to config.xml, server 2. make sure path is not shared by someone 3. add device_id to folder in config.xml, server 4. add device to devices in config.xml, server """ option = 'add' path = kwargs['path'] key = kwargs['key'] if kwargs['remove']: option = 'remove' if kwargs['yes']: output, err = cli_syncthing_adapter.auth(option, key, path) click.echo("%s" % output, err=err) else: verb = 'authorize' if not kwargs['remove'] else 'de-authorize' if click.confirm("Are you sure you want to %s this device to access %s?" % (verb, path)): output, err = cli_syncthing_adapter.auth(option, key, path) if output: click.echo("%s" % output, err=err)
python
def auth(**kwargs): ''' Authorize device synchronization. ''' """ kodrive auth <path> <device_id (client)> 1. make sure path has been added to config.xml, server 2. make sure path is not shared by someone 3. add device_id to folder in config.xml, server 4. add device to devices in config.xml, server """ option = 'add' path = kwargs['path'] key = kwargs['key'] if kwargs['remove']: option = 'remove' if kwargs['yes']: output, err = cli_syncthing_adapter.auth(option, key, path) click.echo("%s" % output, err=err) else: verb = 'authorize' if not kwargs['remove'] else 'de-authorize' if click.confirm("Are you sure you want to %s this device to access %s?" % (verb, path)): output, err = cli_syncthing_adapter.auth(option, key, path) if output: click.echo("%s" % output, err=err)
[ "def", "auth", "(", "*", "*", "kwargs", ")", ":", "\"\"\"\n kodrive auth <path> <device_id (client)>\n\n 1. make sure path has been added to config.xml, server\n 2. make sure path is not shared by someone\n 3. add device_id to folder in config.xml, server\n 4. add device to devices in config.xml, server\n\n \"\"\"", "option", "=", "'add'", "path", "=", "kwargs", "[", "'path'", "]", "key", "=", "kwargs", "[", "'key'", "]", "if", "kwargs", "[", "'remove'", "]", ":", "option", "=", "'remove'", "if", "kwargs", "[", "'yes'", "]", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "auth", "(", "option", ",", "key", ",", "path", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")", "else", ":", "verb", "=", "'authorize'", "if", "not", "kwargs", "[", "'remove'", "]", "else", "'de-authorize'", "if", "click", ".", "confirm", "(", "\"Are you sure you want to %s this device to access %s?\"", "%", "(", "verb", ",", "path", ")", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "auth", "(", "option", ",", "key", ",", "path", ")", "if", "output", ":", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Authorize device synchronization.
[ "Authorize", "device", "synchronization", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L132-L161
train
kodethon/KoDrive
kodrive/cli.py
mv
def mv(source, target): ''' Move synchronized directory. ''' if os.path.isfile(target) and len(source) == 1: if click.confirm("Are you sure you want to overwrite %s?" % target): err_msg = cli_syncthing_adapter.mv_edge_case(source, target) # Edge case: to match Bash 'mv' behavior and overwrite file if err_msg: click.echo(err_msg) return if len(source) > 1 and not os.path.isdir(target): click.echo(click.get_current_context().get_help()) return else: err_msg, err = cli_syncthing_adapter.mv(source, target) if err_msg: click.echo(err_msg, err)
python
def mv(source, target): ''' Move synchronized directory. ''' if os.path.isfile(target) and len(source) == 1: if click.confirm("Are you sure you want to overwrite %s?" % target): err_msg = cli_syncthing_adapter.mv_edge_case(source, target) # Edge case: to match Bash 'mv' behavior and overwrite file if err_msg: click.echo(err_msg) return if len(source) > 1 and not os.path.isdir(target): click.echo(click.get_current_context().get_help()) return else: err_msg, err = cli_syncthing_adapter.mv(source, target) if err_msg: click.echo(err_msg, err)
[ "def", "mv", "(", "source", ",", "target", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "target", ")", "and", "len", "(", "source", ")", "==", "1", ":", "if", "click", ".", "confirm", "(", "\"Are you sure you want to overwrite %s?\"", "%", "target", ")", ":", "err_msg", "=", "cli_syncthing_adapter", ".", "mv_edge_case", "(", "source", ",", "target", ")", "# Edge case: to match Bash 'mv' behavior and overwrite file", "if", "err_msg", ":", "click", ".", "echo", "(", "err_msg", ")", "return", "if", "len", "(", "source", ")", ">", "1", "and", "not", "os", ".", "path", ".", "isdir", "(", "target", ")", ":", "click", ".", "echo", "(", "click", ".", "get_current_context", "(", ")", ".", "get_help", "(", ")", ")", "return", "else", ":", "err_msg", ",", "err", "=", "cli_syncthing_adapter", ".", "mv", "(", "source", ",", "target", ")", "if", "err_msg", ":", "click", ".", "echo", "(", "err_msg", ",", "err", ")" ]
Move synchronized directory.
[ "Move", "synchronized", "directory", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L178-L200
train
kodethon/KoDrive
kodrive/cli.py
push
def push(**kwargs): ''' Force synchronization of directory. ''' output, err = cli_syncthing_adapter.refresh(**kwargs) if output: click.echo("%s" % output, err=err) if kwargs['verbose'] and not err: with click.progressbar( iterable=None, length=100, label='Synchronizing') as bar: device_num = 0 max_devices = 1 prev_percent = 0 while True: kwargs['progress'] = True kwargs['device_num'] = device_num data, err = cli_syncthing_adapter.refresh(**kwargs) device_num = data['device_num'] max_devices = data['max_devices'] cur_percent = math.floor(data['percent']) - prev_percent if cur_percent > 0: bar.update(cur_percent) prev_percent = math.floor(data['percent']) if device_num < max_devices: time.sleep(0.5) else: break
python
def push(**kwargs): ''' Force synchronization of directory. ''' output, err = cli_syncthing_adapter.refresh(**kwargs) if output: click.echo("%s" % output, err=err) if kwargs['verbose'] and not err: with click.progressbar( iterable=None, length=100, label='Synchronizing') as bar: device_num = 0 max_devices = 1 prev_percent = 0 while True: kwargs['progress'] = True kwargs['device_num'] = device_num data, err = cli_syncthing_adapter.refresh(**kwargs) device_num = data['device_num'] max_devices = data['max_devices'] cur_percent = math.floor(data['percent']) - prev_percent if cur_percent > 0: bar.update(cur_percent) prev_percent = math.floor(data['percent']) if device_num < max_devices: time.sleep(0.5) else: break
[ "def", "push", "(", "*", "*", "kwargs", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "refresh", "(", "*", "*", "kwargs", ")", "if", "output", ":", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")", "if", "kwargs", "[", "'verbose'", "]", "and", "not", "err", ":", "with", "click", ".", "progressbar", "(", "iterable", "=", "None", ",", "length", "=", "100", ",", "label", "=", "'Synchronizing'", ")", "as", "bar", ":", "device_num", "=", "0", "max_devices", "=", "1", "prev_percent", "=", "0", "while", "True", ":", "kwargs", "[", "'progress'", "]", "=", "True", "kwargs", "[", "'device_num'", "]", "=", "device_num", "data", ",", "err", "=", "cli_syncthing_adapter", ".", "refresh", "(", "*", "*", "kwargs", ")", "device_num", "=", "data", "[", "'device_num'", "]", "max_devices", "=", "data", "[", "'max_devices'", "]", "cur_percent", "=", "math", ".", "floor", "(", "data", "[", "'percent'", "]", ")", "-", "prev_percent", "if", "cur_percent", ">", "0", ":", "bar", ".", "update", "(", "cur_percent", ")", "prev_percent", "=", "math", ".", "floor", "(", "data", "[", "'percent'", "]", ")", "if", "device_num", "<", "max_devices", ":", "time", ".", "sleep", "(", "0.5", ")", "else", ":", "break" ]
Force synchronization of directory.
[ "Force", "synchronization", "of", "directory", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L212-L246
train
kodethon/KoDrive
kodrive/cli.py
tag
def tag(path, name): ''' Change tag associated with directory. ''' output, err = cli_syncthing_adapter.tag(path, name) click.echo("%s" % output, err=err)
python
def tag(path, name): ''' Change tag associated with directory. ''' output, err = cli_syncthing_adapter.tag(path, name) click.echo("%s" % output, err=err)
[ "def", "tag", "(", "path", ",", "name", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "tag", "(", "path", ",", "name", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Change tag associated with directory.
[ "Change", "tag", "associated", "with", "directory", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L256-L260
train
kodethon/KoDrive
kodrive/cli.py
free
def free(**kwargs): ''' Stop synchronization of directory. ''' output, err = cli_syncthing_adapter.free(kwargs['path']) click.echo("%s" % output, err=err)
python
def free(**kwargs): ''' Stop synchronization of directory. ''' output, err = cli_syncthing_adapter.free(kwargs['path']) click.echo("%s" % output, err=err)
[ "def", "free", "(", "*", "*", "kwargs", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "free", "(", "kwargs", "[", "'path'", "]", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Stop synchronization of directory.
[ "Stop", "synchronization", "of", "directory", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L269-L273
train
kodethon/KoDrive
kodrive/cli.py
add
def add(**kwargs): ''' Make a directory shareable. ''' output, err = cli_syncthing_adapter.add(**kwargs) click.echo("%s" % output, err=err)
python
def add(**kwargs): ''' Make a directory shareable. ''' output, err = cli_syncthing_adapter.add(**kwargs) click.echo("%s" % output, err=err)
[ "def", "add", "(", "*", "*", "kwargs", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "add", "(", "*", "*", "kwargs", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Make a directory shareable.
[ "Make", "a", "directory", "shareable", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L292-L296
train
kodethon/KoDrive
kodrive/cli.py
info
def info(path): ''' Display synchronization information. ''' output, err = cli_syncthing_adapter.info(folder=path) if err: click.echo(output, err=err) else: stat = output['status'] click.echo("State: %s" % stat['state']) click.echo("\nTotal Files: %s" % stat['localFiles']) click.echo("Files Needed: %s" % stat['needFiles']) click.echo("\nTotal Bytes: %s" % stat['localBytes']) click.echo("Bytes Needed: %s" % stat['needBytes']) progress = output['files_needed']['progress'] queued = output['files_needed']['queued'] rest = output['files_needed']['rest'] if len(progress) or len(queued) or len(rest): click.echo("\nFiles Needed:") for f in progress: click.echo(" " + f['name']) for f in queued: click.echo(" " + f['name']) for f in rest: click.echo(" " + f['name']) click.echo("\nDevices Authorized:\n%s" % output['auth_ls'])
python
def info(path): ''' Display synchronization information. ''' output, err = cli_syncthing_adapter.info(folder=path) if err: click.echo(output, err=err) else: stat = output['status'] click.echo("State: %s" % stat['state']) click.echo("\nTotal Files: %s" % stat['localFiles']) click.echo("Files Needed: %s" % stat['needFiles']) click.echo("\nTotal Bytes: %s" % stat['localBytes']) click.echo("Bytes Needed: %s" % stat['needBytes']) progress = output['files_needed']['progress'] queued = output['files_needed']['queued'] rest = output['files_needed']['rest'] if len(progress) or len(queued) or len(rest): click.echo("\nFiles Needed:") for f in progress: click.echo(" " + f['name']) for f in queued: click.echo(" " + f['name']) for f in rest: click.echo(" " + f['name']) click.echo("\nDevices Authorized:\n%s" % output['auth_ls'])
[ "def", "info", "(", "path", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "info", "(", "folder", "=", "path", ")", "if", "err", ":", "click", ".", "echo", "(", "output", ",", "err", "=", "err", ")", "else", ":", "stat", "=", "output", "[", "'status'", "]", "click", ".", "echo", "(", "\"State: %s\"", "%", "stat", "[", "'state'", "]", ")", "click", ".", "echo", "(", "\"\\nTotal Files: %s\"", "%", "stat", "[", "'localFiles'", "]", ")", "click", ".", "echo", "(", "\"Files Needed: %s\"", "%", "stat", "[", "'needFiles'", "]", ")", "click", ".", "echo", "(", "\"\\nTotal Bytes: %s\"", "%", "stat", "[", "'localBytes'", "]", ")", "click", ".", "echo", "(", "\"Bytes Needed: %s\"", "%", "stat", "[", "'needBytes'", "]", ")", "progress", "=", "output", "[", "'files_needed'", "]", "[", "'progress'", "]", "queued", "=", "output", "[", "'files_needed'", "]", "[", "'queued'", "]", "rest", "=", "output", "[", "'files_needed'", "]", "[", "'rest'", "]", "if", "len", "(", "progress", ")", "or", "len", "(", "queued", ")", "or", "len", "(", "rest", ")", ":", "click", ".", "echo", "(", "\"\\nFiles Needed:\"", ")", "for", "f", "in", "progress", ":", "click", ".", "echo", "(", "\" \"", "+", "f", "[", "'name'", "]", ")", "for", "f", "in", "queued", ":", "click", ".", "echo", "(", "\" \"", "+", "f", "[", "'name'", "]", ")", "for", "f", "in", "rest", ":", "click", ".", "echo", "(", "\" \"", "+", "f", "[", "'name'", "]", ")", "click", ".", "echo", "(", "\"\\nDevices Authorized:\\n%s\"", "%", "output", "[", "'auth_ls'", "]", ")" ]
Display synchronization information.
[ "Display", "synchronization", "information", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L304-L335
train
kodethon/KoDrive
kodrive/cli.py
key
def key(**kwargs): ''' Display system key. ''' output, err = cli_syncthing_adapter.key(device=True) click.echo("%s" % output, err=err)
python
def key(**kwargs): ''' Display system key. ''' output, err = cli_syncthing_adapter.key(device=True) click.echo("%s" % output, err=err)
[ "def", "key", "(", "*", "*", "kwargs", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "key", "(", "device", "=", "True", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Display system key.
[ "Display", "system", "key", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L381-L385
train
kodethon/KoDrive
kodrive/cli.py
start
def start(**kwargs): ''' Start KodeDrive daemon. ''' output, err = cli_syncthing_adapter.start(**kwargs) click.echo("%s" % output, err=err)
python
def start(**kwargs): ''' Start KodeDrive daemon. ''' output, err = cli_syncthing_adapter.start(**kwargs) click.echo("%s" % output, err=err)
[ "def", "start", "(", "*", "*", "kwargs", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "start", "(", "*", "*", "kwargs", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Start KodeDrive daemon.
[ "Start", "KodeDrive", "daemon", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L406-L410
train
kodethon/KoDrive
kodrive/cli.py
stop
def stop(): ''' Stop KodeDrive daemon. ''' output, err = cli_syncthing_adapter.sys(exit=True) click.echo("%s" % output, err=err)
python
def stop(): ''' Stop KodeDrive daemon. ''' output, err = cli_syncthing_adapter.sys(exit=True) click.echo("%s" % output, err=err)
[ "def", "stop", "(", ")", ":", "output", ",", "err", "=", "cli_syncthing_adapter", ".", "sys", "(", "exit", "=", "True", ")", "click", ".", "echo", "(", "\"%s\"", "%", "output", ",", "err", "=", "err", ")" ]
Stop KodeDrive daemon.
[ "Stop", "KodeDrive", "daemon", "." ]
325fe5e5870b7d4eb121dcc7e93be64aa16e7988
https://github.com/kodethon/KoDrive/blob/325fe5e5870b7d4eb121dcc7e93be64aa16e7988/kodrive/cli.py#L414-L418
train
tjcsl/cslbot
cslbot/commands/vote.py
start_poll
def start_poll(args): """Starts a poll.""" if args.type == 'privmsg': return "We don't have secret ballots in this benevolent dictatorship!" if not args.msg: return "Polls need a question." ctrlchan = args.config['core']['ctrlchan'] poll = Polls(question=args.msg, submitter=args.nick) args.session.add(poll) args.session.flush() if args.isadmin or not args.config.getboolean('adminrestrict', 'poll'): poll.accepted = 1 return "Poll #%d created!" % poll.id else: args.send("Poll submitted for approval.", target=args.nick) args.send("New Poll: #%d -- %s, Submitted by %s" % (poll.id, args.msg, args.nick), target=ctrlchan) return ""
python
def start_poll(args): """Starts a poll.""" if args.type == 'privmsg': return "We don't have secret ballots in this benevolent dictatorship!" if not args.msg: return "Polls need a question." ctrlchan = args.config['core']['ctrlchan'] poll = Polls(question=args.msg, submitter=args.nick) args.session.add(poll) args.session.flush() if args.isadmin or not args.config.getboolean('adminrestrict', 'poll'): poll.accepted = 1 return "Poll #%d created!" % poll.id else: args.send("Poll submitted for approval.", target=args.nick) args.send("New Poll: #%d -- %s, Submitted by %s" % (poll.id, args.msg, args.nick), target=ctrlchan) return ""
[ "def", "start_poll", "(", "args", ")", ":", "if", "args", ".", "type", "==", "'privmsg'", ":", "return", "\"We don't have secret ballots in this benevolent dictatorship!\"", "if", "not", "args", ".", "msg", ":", "return", "\"Polls need a question.\"", "ctrlchan", "=", "args", ".", "config", "[", "'core'", "]", "[", "'ctrlchan'", "]", "poll", "=", "Polls", "(", "question", "=", "args", ".", "msg", ",", "submitter", "=", "args", ".", "nick", ")", "args", ".", "session", ".", "add", "(", "poll", ")", "args", ".", "session", ".", "flush", "(", ")", "if", "args", ".", "isadmin", "or", "not", "args", ".", "config", ".", "getboolean", "(", "'adminrestrict'", ",", "'poll'", ")", ":", "poll", ".", "accepted", "=", "1", "return", "\"Poll #%d created!\"", "%", "poll", ".", "id", "else", ":", "args", ".", "send", "(", "\"Poll submitted for approval.\"", ",", "target", "=", "args", ".", "nick", ")", "args", ".", "send", "(", "\"New Poll: #%d -- %s, Submitted by %s\"", "%", "(", "poll", ".", "id", ",", "args", ".", "msg", ",", "args", ".", "nick", ")", ",", "target", "=", "ctrlchan", ")", "return", "\"\"" ]
Starts a poll.
[ "Starts", "a", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L25-L41
train
tjcsl/cslbot
cslbot/commands/vote.py
delete_poll
def delete_poll(args): """Deletes a poll.""" if not args.isadmin: return "Nope, not gonna do it." if not args.msg: return "Syntax: !poll delete <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." poll = args.session.query(Polls).filter(Polls.accepted == 1, Polls.id == int(args.msg)).first() if poll is None: return "Poll does not exist." if poll.active == 1: return "You can't delete an active poll!" elif poll.deleted == 1: return "Poll already deleted." poll.deleted = 1 return "Poll deleted."
python
def delete_poll(args): """Deletes a poll.""" if not args.isadmin: return "Nope, not gonna do it." if not args.msg: return "Syntax: !poll delete <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." poll = args.session.query(Polls).filter(Polls.accepted == 1, Polls.id == int(args.msg)).first() if poll is None: return "Poll does not exist." if poll.active == 1: return "You can't delete an active poll!" elif poll.deleted == 1: return "Poll already deleted." poll.deleted = 1 return "Poll deleted."
[ "def", "delete_poll", "(", "args", ")", ":", "if", "not", "args", ".", "isadmin", ":", "return", "\"Nope, not gonna do it.\"", "if", "not", "args", ".", "msg", ":", "return", "\"Syntax: !poll delete <pollnum>\"", "if", "not", "args", ".", "msg", ".", "isdigit", "(", ")", ":", "return", "\"Not A Valid Positive Integer.\"", "poll", "=", "args", ".", "session", ".", "query", "(", "Polls", ")", ".", "filter", "(", "Polls", ".", "accepted", "==", "1", ",", "Polls", ".", "id", "==", "int", "(", "args", ".", "msg", ")", ")", ".", "first", "(", ")", "if", "poll", "is", "None", ":", "return", "\"Poll does not exist.\"", "if", "poll", ".", "active", "==", "1", ":", "return", "\"You can't delete an active poll!\"", "elif", "poll", ".", "deleted", "==", "1", ":", "return", "\"Poll already deleted.\"", "poll", ".", "deleted", "=", "1", "return", "\"Poll deleted.\"" ]
Deletes a poll.
[ "Deletes", "a", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L44-L60
train
tjcsl/cslbot
cslbot/commands/vote.py
edit_poll
def edit_poll(args): """Edits a poll.""" if not args.isadmin: return "Nope, not gonna do it." msg = args.msg.split(maxsplit=1) if len(msg) < 2: return "Syntax: !vote edit <pollnum> <question>" if not msg[0].isdigit(): return "Not A Valid Positive Integer." pid = int(msg[0]) poll = get_open_poll(args.session, pid) if poll is None: return "That poll was deleted or does not exist!" poll.question = msg[1] return "Poll updated!"
python
def edit_poll(args): """Edits a poll.""" if not args.isadmin: return "Nope, not gonna do it." msg = args.msg.split(maxsplit=1) if len(msg) < 2: return "Syntax: !vote edit <pollnum> <question>" if not msg[0].isdigit(): return "Not A Valid Positive Integer." pid = int(msg[0]) poll = get_open_poll(args.session, pid) if poll is None: return "That poll was deleted or does not exist!" poll.question = msg[1] return "Poll updated!"
[ "def", "edit_poll", "(", "args", ")", ":", "if", "not", "args", ".", "isadmin", ":", "return", "\"Nope, not gonna do it.\"", "msg", "=", "args", ".", "msg", ".", "split", "(", "maxsplit", "=", "1", ")", "if", "len", "(", "msg", ")", "<", "2", ":", "return", "\"Syntax: !vote edit <pollnum> <question>\"", "if", "not", "msg", "[", "0", "]", ".", "isdigit", "(", ")", ":", "return", "\"Not A Valid Positive Integer.\"", "pid", "=", "int", "(", "msg", "[", "0", "]", ")", "poll", "=", "get_open_poll", "(", "args", ".", "session", ",", "pid", ")", "if", "poll", "is", "None", ":", "return", "\"That poll was deleted or does not exist!\"", "poll", ".", "question", "=", "msg", "[", "1", "]", "return", "\"Poll updated!\"" ]
Edits a poll.
[ "Edits", "a", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L67-L81
train
tjcsl/cslbot
cslbot/commands/vote.py
reopen
def reopen(args): """reopens a closed poll.""" if not args.isadmin: return "Nope, not gonna do it." msg = args.msg.split() if not msg: return "Syntax: !poll reopen <pollnum>" if not msg[0].isdigit(): return "Not a valid positve integer." pid = int(msg[0]) poll = get_open_poll(args.session, pid) if poll is None: return "That poll doesn't exist or has been deleted!" poll.active = 1 return "Poll %d reopened!" % pid
python
def reopen(args): """reopens a closed poll.""" if not args.isadmin: return "Nope, not gonna do it." msg = args.msg.split() if not msg: return "Syntax: !poll reopen <pollnum>" if not msg[0].isdigit(): return "Not a valid positve integer." pid = int(msg[0]) poll = get_open_poll(args.session, pid) if poll is None: return "That poll doesn't exist or has been deleted!" poll.active = 1 return "Poll %d reopened!" % pid
[ "def", "reopen", "(", "args", ")", ":", "if", "not", "args", ".", "isadmin", ":", "return", "\"Nope, not gonna do it.\"", "msg", "=", "args", ".", "msg", ".", "split", "(", ")", "if", "not", "msg", ":", "return", "\"Syntax: !poll reopen <pollnum>\"", "if", "not", "msg", "[", "0", "]", ".", "isdigit", "(", ")", ":", "return", "\"Not a valid positve integer.\"", "pid", "=", "int", "(", "msg", "[", "0", "]", ")", "poll", "=", "get_open_poll", "(", "args", ".", "session", ",", "pid", ")", "if", "poll", "is", "None", ":", "return", "\"That poll doesn't exist or has been deleted!\"", "poll", ".", "active", "=", "1", "return", "\"Poll %d reopened!\"", "%", "pid" ]
reopens a closed poll.
[ "reopens", "a", "closed", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L84-L98
train
tjcsl/cslbot
cslbot/commands/vote.py
end_poll
def end_poll(args): """Ends a poll.""" if not args.isadmin: return "Nope, not gonna do it." if not args.msg: return "Syntax: !vote end <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." poll = get_open_poll(args.session, int(args.msg)) if poll is None: return "That poll doesn't exist or has already been deleted!" if poll.active == 0: return "Poll already ended!" poll.active = 0 return "Poll ended!"
python
def end_poll(args): """Ends a poll.""" if not args.isadmin: return "Nope, not gonna do it." if not args.msg: return "Syntax: !vote end <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." poll = get_open_poll(args.session, int(args.msg)) if poll is None: return "That poll doesn't exist or has already been deleted!" if poll.active == 0: return "Poll already ended!" poll.active = 0 return "Poll ended!"
[ "def", "end_poll", "(", "args", ")", ":", "if", "not", "args", ".", "isadmin", ":", "return", "\"Nope, not gonna do it.\"", "if", "not", "args", ".", "msg", ":", "return", "\"Syntax: !vote end <pollnum>\"", "if", "not", "args", ".", "msg", ".", "isdigit", "(", ")", ":", "return", "\"Not A Valid Positive Integer.\"", "poll", "=", "get_open_poll", "(", "args", ".", "session", ",", "int", "(", "args", ".", "msg", ")", ")", "if", "poll", "is", "None", ":", "return", "\"That poll doesn't exist or has already been deleted!\"", "if", "poll", ".", "active", "==", "0", ":", "return", "\"Poll already ended!\"", "poll", ".", "active", "=", "0", "return", "\"Poll ended!\"" ]
Ends a poll.
[ "Ends", "a", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L101-L115
train
tjcsl/cslbot
cslbot/commands/vote.py
tally_poll
def tally_poll(args): """Shows the results of poll.""" if not args.msg: return "Syntax: !vote tally <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." pid = int(args.msg) poll = get_open_poll(args.session, pid) if poll is None: return "That poll doesn't exist or was deleted. Use !poll list to see valid polls" state = "Active" if poll.active == 1 else "Closed" votes = args.session.query(Poll_responses).filter(Poll_responses.pid == pid).all() args.send("%s poll: %s, %d total votes" % (state, poll.question, len(votes))) votemap = collections.defaultdict(list) for v in votes: votemap[v.response].append(v.voter) for x in sorted(votemap.keys()): args.send("%s: %d -- %s" % (x, len(votemap[x]), ", ".join(votemap[x])), target=args.nick) if not votemap: return "" ranking = collections.defaultdict(list) for x in votemap.keys(): num = len(votemap[x]) ranking[num].append(x) high = max(ranking) winners = (ranking[high], high) if len(winners[0]) == 1: winners = (winners[0][0], high) return "The winner is %s with %d votes." % winners else: winners = (", ".join(winners[0]), high) return "Tie between %s with %d votes." % winners
python
def tally_poll(args): """Shows the results of poll.""" if not args.msg: return "Syntax: !vote tally <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." pid = int(args.msg) poll = get_open_poll(args.session, pid) if poll is None: return "That poll doesn't exist or was deleted. Use !poll list to see valid polls" state = "Active" if poll.active == 1 else "Closed" votes = args.session.query(Poll_responses).filter(Poll_responses.pid == pid).all() args.send("%s poll: %s, %d total votes" % (state, poll.question, len(votes))) votemap = collections.defaultdict(list) for v in votes: votemap[v.response].append(v.voter) for x in sorted(votemap.keys()): args.send("%s: %d -- %s" % (x, len(votemap[x]), ", ".join(votemap[x])), target=args.nick) if not votemap: return "" ranking = collections.defaultdict(list) for x in votemap.keys(): num = len(votemap[x]) ranking[num].append(x) high = max(ranking) winners = (ranking[high], high) if len(winners[0]) == 1: winners = (winners[0][0], high) return "The winner is %s with %d votes." % winners else: winners = (", ".join(winners[0]), high) return "Tie between %s with %d votes." % winners
[ "def", "tally_poll", "(", "args", ")", ":", "if", "not", "args", ".", "msg", ":", "return", "\"Syntax: !vote tally <pollnum>\"", "if", "not", "args", ".", "msg", ".", "isdigit", "(", ")", ":", "return", "\"Not A Valid Positive Integer.\"", "pid", "=", "int", "(", "args", ".", "msg", ")", "poll", "=", "get_open_poll", "(", "args", ".", "session", ",", "pid", ")", "if", "poll", "is", "None", ":", "return", "\"That poll doesn't exist or was deleted. Use !poll list to see valid polls\"", "state", "=", "\"Active\"", "if", "poll", ".", "active", "==", "1", "else", "\"Closed\"", "votes", "=", "args", ".", "session", ".", "query", "(", "Poll_responses", ")", ".", "filter", "(", "Poll_responses", ".", "pid", "==", "pid", ")", ".", "all", "(", ")", "args", ".", "send", "(", "\"%s poll: %s, %d total votes\"", "%", "(", "state", ",", "poll", ".", "question", ",", "len", "(", "votes", ")", ")", ")", "votemap", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "v", "in", "votes", ":", "votemap", "[", "v", ".", "response", "]", ".", "append", "(", "v", ".", "voter", ")", "for", "x", "in", "sorted", "(", "votemap", ".", "keys", "(", ")", ")", ":", "args", ".", "send", "(", "\"%s: %d -- %s\"", "%", "(", "x", ",", "len", "(", "votemap", "[", "x", "]", ")", ",", "\", \"", ".", "join", "(", "votemap", "[", "x", "]", ")", ")", ",", "target", "=", "args", ".", "nick", ")", "if", "not", "votemap", ":", "return", "\"\"", "ranking", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "x", "in", "votemap", ".", "keys", "(", ")", ":", "num", "=", "len", "(", "votemap", "[", "x", "]", ")", "ranking", "[", "num", "]", ".", "append", "(", "x", ")", "high", "=", "max", "(", "ranking", ")", "winners", "=", "(", "ranking", "[", "high", "]", ",", "high", ")", "if", "len", "(", "winners", "[", "0", "]", ")", "==", "1", ":", "winners", "=", "(", "winners", "[", "0", "]", "[", "0", "]", ",", "high", ")", "return", "\"The winner is %s with %d votes.\"", "%", "winners", "else", ":", "winners", "=", "(", "\", \"", ".", "join", "(", "winners", "[", "0", "]", ")", ",", "high", ")", "return", "\"Tie between %s with %d votes.\"", "%", "winners" ]
Shows the results of poll.
[ "Shows", "the", "results", "of", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L118-L149
train
tjcsl/cslbot
cslbot/commands/vote.py
vote
def vote(session, nick, pid, response): """Votes on a poll.""" if not response: return "You have to vote something!" if response == "n" or response == "nay": response = "no" elif response == "y" or response == "aye": response = "yes" poll = get_open_poll(session, pid) if poll is None: return "That poll doesn't exist or isn't active. Use !poll list to see valid polls" old_vote = get_response(session, pid, nick) if old_vote is None: session.add(Poll_responses(pid=pid, response=response, voter=nick)) return "%s voted %s." % (nick, response) else: if response == old_vote.response: return "You've already voted %s." % response else: msg = "%s changed their vote from %s to %s." % (nick, old_vote.response, response) old_vote.response = response return msg
python
def vote(session, nick, pid, response): """Votes on a poll.""" if not response: return "You have to vote something!" if response == "n" or response == "nay": response = "no" elif response == "y" or response == "aye": response = "yes" poll = get_open_poll(session, pid) if poll is None: return "That poll doesn't exist or isn't active. Use !poll list to see valid polls" old_vote = get_response(session, pid, nick) if old_vote is None: session.add(Poll_responses(pid=pid, response=response, voter=nick)) return "%s voted %s." % (nick, response) else: if response == old_vote.response: return "You've already voted %s." % response else: msg = "%s changed their vote from %s to %s." % (nick, old_vote.response, response) old_vote.response = response return msg
[ "def", "vote", "(", "session", ",", "nick", ",", "pid", ",", "response", ")", ":", "if", "not", "response", ":", "return", "\"You have to vote something!\"", "if", "response", "==", "\"n\"", "or", "response", "==", "\"nay\"", ":", "response", "=", "\"no\"", "elif", "response", "==", "\"y\"", "or", "response", "==", "\"aye\"", ":", "response", "=", "\"yes\"", "poll", "=", "get_open_poll", "(", "session", ",", "pid", ")", "if", "poll", "is", "None", ":", "return", "\"That poll doesn't exist or isn't active. Use !poll list to see valid polls\"", "old_vote", "=", "get_response", "(", "session", ",", "pid", ",", "nick", ")", "if", "old_vote", "is", "None", ":", "session", ".", "add", "(", "Poll_responses", "(", "pid", "=", "pid", ",", "response", "=", "response", ",", "voter", "=", "nick", ")", ")", "return", "\"%s voted %s.\"", "%", "(", "nick", ",", "response", ")", "else", ":", "if", "response", "==", "old_vote", ".", "response", ":", "return", "\"You've already voted %s.\"", "%", "response", "else", ":", "msg", "=", "\"%s changed their vote from %s to %s.\"", "%", "(", "nick", ",", "old_vote", ".", "response", ",", "response", ")", "old_vote", ".", "response", "=", "response", "return", "msg" ]
Votes on a poll.
[ "Votes", "on", "a", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L156-L177
train
tjcsl/cslbot
cslbot/commands/vote.py
retract
def retract(args): """Deletes a vote for a poll.""" if not args.msg: return "Syntax: !vote retract <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." response = get_response(args.session, args.msg, args.nick) if response is None: return "You haven't voted on that poll yet!" args.session.delete(response) return "Vote retracted"
python
def retract(args): """Deletes a vote for a poll.""" if not args.msg: return "Syntax: !vote retract <pollnum>" if not args.msg.isdigit(): return "Not A Valid Positive Integer." response = get_response(args.session, args.msg, args.nick) if response is None: return "You haven't voted on that poll yet!" args.session.delete(response) return "Vote retracted"
[ "def", "retract", "(", "args", ")", ":", "if", "not", "args", ".", "msg", ":", "return", "\"Syntax: !vote retract <pollnum>\"", "if", "not", "args", ".", "msg", ".", "isdigit", "(", ")", ":", "return", "\"Not A Valid Positive Integer.\"", "response", "=", "get_response", "(", "args", ".", "session", ",", "args", ".", "msg", ",", "args", ".", "nick", ")", "if", "response", "is", "None", ":", "return", "\"You haven't voted on that poll yet!\"", "args", ".", "session", ".", "delete", "(", "response", ")", "return", "\"Vote retracted\"" ]
Deletes a vote for a poll.
[ "Deletes", "a", "vote", "for", "a", "poll", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L180-L190
train
tjcsl/cslbot
cslbot/commands/vote.py
cmd
def cmd(send, msg, args): """Handles voting. Syntax: {command} <start|end|list|tally|edit|delete|retract|reopen|(num) vote> """ command = msg.split() msg = " ".join(command[1:]) if not command: send("Which poll?") return else: command = command[0] # FIXME: integrate this with ArgParser if command.isdigit(): if args['type'] == 'privmsg': send("We don't have secret ballots in this benevolent dictatorship!") else: send(vote(args['db'], args['nick'], int(command), msg)) return isadmin = args['is_admin'](args['nick']) parser = arguments.ArgParser(args['config']) parser.set_defaults(session=args['db'], msg=msg, nick=args['nick']) subparser = parser.add_subparsers() start_parser = subparser.add_parser('start', config=args['config'], aliases=['open', 'add', 'create']) start_parser.set_defaults(func=start_poll, send=send, isadmin=isadmin, type=args['type']) tally_parser = subparser.add_parser('tally') tally_parser.set_defaults(func=tally_poll, send=send) list_parser = subparser.add_parser('list', config=args['config']) list_parser.set_defaults(func=list_polls) retract_parser = subparser.add_parser('retract') retract_parser.set_defaults(func=retract) end_parser = subparser.add_parser('end', aliases=['close']) end_parser.set_defaults(func=end_poll, isadmin=isadmin) delete_parser = subparser.add_parser('delete') delete_parser.set_defaults(func=delete_poll, isadmin=isadmin) edit_parser = subparser.add_parser('edit') edit_parser.set_defaults(func=edit_poll, isadmin=isadmin) reopen_parser = subparser.add_parser('reopen') reopen_parser.set_defaults(func=reopen, isadmin=isadmin) try: cmdargs = parser.parse_args(command) except arguments.ArgumentException as e: send(str(e)) return send(cmdargs.func(cmdargs))
python
def cmd(send, msg, args): """Handles voting. Syntax: {command} <start|end|list|tally|edit|delete|retract|reopen|(num) vote> """ command = msg.split() msg = " ".join(command[1:]) if not command: send("Which poll?") return else: command = command[0] # FIXME: integrate this with ArgParser if command.isdigit(): if args['type'] == 'privmsg': send("We don't have secret ballots in this benevolent dictatorship!") else: send(vote(args['db'], args['nick'], int(command), msg)) return isadmin = args['is_admin'](args['nick']) parser = arguments.ArgParser(args['config']) parser.set_defaults(session=args['db'], msg=msg, nick=args['nick']) subparser = parser.add_subparsers() start_parser = subparser.add_parser('start', config=args['config'], aliases=['open', 'add', 'create']) start_parser.set_defaults(func=start_poll, send=send, isadmin=isadmin, type=args['type']) tally_parser = subparser.add_parser('tally') tally_parser.set_defaults(func=tally_poll, send=send) list_parser = subparser.add_parser('list', config=args['config']) list_parser.set_defaults(func=list_polls) retract_parser = subparser.add_parser('retract') retract_parser.set_defaults(func=retract) end_parser = subparser.add_parser('end', aliases=['close']) end_parser.set_defaults(func=end_poll, isadmin=isadmin) delete_parser = subparser.add_parser('delete') delete_parser.set_defaults(func=delete_poll, isadmin=isadmin) edit_parser = subparser.add_parser('edit') edit_parser.set_defaults(func=edit_poll, isadmin=isadmin) reopen_parser = subparser.add_parser('reopen') reopen_parser.set_defaults(func=reopen, isadmin=isadmin) try: cmdargs = parser.parse_args(command) except arguments.ArgumentException as e: send(str(e)) return send(cmdargs.func(cmdargs))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "command", "=", "msg", ".", "split", "(", ")", "msg", "=", "\" \"", ".", "join", "(", "command", "[", "1", ":", "]", ")", "if", "not", "command", ":", "send", "(", "\"Which poll?\"", ")", "return", "else", ":", "command", "=", "command", "[", "0", "]", "# FIXME: integrate this with ArgParser", "if", "command", ".", "isdigit", "(", ")", ":", "if", "args", "[", "'type'", "]", "==", "'privmsg'", ":", "send", "(", "\"We don't have secret ballots in this benevolent dictatorship!\"", ")", "else", ":", "send", "(", "vote", "(", "args", "[", "'db'", "]", ",", "args", "[", "'nick'", "]", ",", "int", "(", "command", ")", ",", "msg", ")", ")", "return", "isadmin", "=", "args", "[", "'is_admin'", "]", "(", "args", "[", "'nick'", "]", ")", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "set_defaults", "(", "session", "=", "args", "[", "'db'", "]", ",", "msg", "=", "msg", ",", "nick", "=", "args", "[", "'nick'", "]", ")", "subparser", "=", "parser", ".", "add_subparsers", "(", ")", "start_parser", "=", "subparser", ".", "add_parser", "(", "'start'", ",", "config", "=", "args", "[", "'config'", "]", ",", "aliases", "=", "[", "'open'", ",", "'add'", ",", "'create'", "]", ")", "start_parser", ".", "set_defaults", "(", "func", "=", "start_poll", ",", "send", "=", "send", ",", "isadmin", "=", "isadmin", ",", "type", "=", "args", "[", "'type'", "]", ")", "tally_parser", "=", "subparser", ".", "add_parser", "(", "'tally'", ")", "tally_parser", ".", "set_defaults", "(", "func", "=", "tally_poll", ",", "send", "=", "send", ")", "list_parser", "=", "subparser", ".", "add_parser", "(", "'list'", ",", "config", "=", "args", "[", "'config'", "]", ")", "list_parser", ".", "set_defaults", "(", "func", "=", "list_polls", ")", "retract_parser", "=", "subparser", ".", "add_parser", "(", "'retract'", ")", "retract_parser", ".", "set_defaults", "(", "func", "=", "retract", ")", "end_parser", "=", "subparser", ".", "add_parser", "(", "'end'", ",", "aliases", "=", "[", "'close'", "]", ")", "end_parser", ".", "set_defaults", "(", "func", "=", "end_poll", ",", "isadmin", "=", "isadmin", ")", "delete_parser", "=", "subparser", ".", "add_parser", "(", "'delete'", ")", "delete_parser", ".", "set_defaults", "(", "func", "=", "delete_poll", ",", "isadmin", "=", "isadmin", ")", "edit_parser", "=", "subparser", ".", "add_parser", "(", "'edit'", ")", "edit_parser", ".", "set_defaults", "(", "func", "=", "edit_poll", ",", "isadmin", "=", "isadmin", ")", "reopen_parser", "=", "subparser", ".", "add_parser", "(", "'reopen'", ")", "reopen_parser", ".", "set_defaults", "(", "func", "=", "reopen", ",", "isadmin", "=", "isadmin", ")", "try", ":", "cmdargs", "=", "parser", ".", "parse_args", "(", "command", ")", "except", "arguments", ".", "ArgumentException", "as", "e", ":", "send", "(", "str", "(", "e", ")", ")", "return", "send", "(", "cmdargs", ".", "func", "(", "cmdargs", ")", ")" ]
Handles voting. Syntax: {command} <start|end|list|tally|edit|delete|retract|reopen|(num) vote>
[ "Handles", "voting", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L199-L244
train
tjcsl/cslbot
cslbot/commands/stats.py
cmd
def cmd(send, msg, args): """Gets stats. Syntax: {command} <--high|--low|--userhigh|--nick <nick>|command> """ parser = arguments.ArgParser(args['config']) group = parser.add_mutually_exclusive_group() group.add_argument('--high', action='store_true') group.add_argument('--low', action='store_true') group.add_argument('--userhigh', action='store_true') group.add_argument('--nick', action=arguments.NickParser) group.add_argument('command', nargs='?') try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return session = args['db'] totals = get_command_totals(session) sortedtotals = sorted(totals, key=totals.get) if command_registry.is_registered(cmdargs.command): send(get_command(session, cmdargs.command, totals)) elif cmdargs.command and not command_registry.is_registered(cmdargs.command): send("Command %s not found." % cmdargs.command) elif cmdargs.high: send('Most Used Commands:') high = list(reversed(sortedtotals)) for x in range(3): if x < len(high): send("%s: %s" % (high[x], totals[high[x]])) elif cmdargs.low: send('Least Used Commands:') low = sortedtotals for x in range(3): if x < len(low): send("%s: %s" % (low[x], totals[low[x]])) elif cmdargs.userhigh: totals = get_nick_totals(session) sortedtotals = sorted(totals, key=totals.get) high = list(reversed(sortedtotals)) send('Most active bot users:') for x in range(3): if x < len(high): send("%s: %s" % (high[x], totals[high[x]])) elif cmdargs.nick: send(get_nick(session, cmdargs.nick)) else: command = choice(list(totals.keys())) send("%s has been used %s times." % (command, totals[command]))
python
def cmd(send, msg, args): """Gets stats. Syntax: {command} <--high|--low|--userhigh|--nick <nick>|command> """ parser = arguments.ArgParser(args['config']) group = parser.add_mutually_exclusive_group() group.add_argument('--high', action='store_true') group.add_argument('--low', action='store_true') group.add_argument('--userhigh', action='store_true') group.add_argument('--nick', action=arguments.NickParser) group.add_argument('command', nargs='?') try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return session = args['db'] totals = get_command_totals(session) sortedtotals = sorted(totals, key=totals.get) if command_registry.is_registered(cmdargs.command): send(get_command(session, cmdargs.command, totals)) elif cmdargs.command and not command_registry.is_registered(cmdargs.command): send("Command %s not found." % cmdargs.command) elif cmdargs.high: send('Most Used Commands:') high = list(reversed(sortedtotals)) for x in range(3): if x < len(high): send("%s: %s" % (high[x], totals[high[x]])) elif cmdargs.low: send('Least Used Commands:') low = sortedtotals for x in range(3): if x < len(low): send("%s: %s" % (low[x], totals[low[x]])) elif cmdargs.userhigh: totals = get_nick_totals(session) sortedtotals = sorted(totals, key=totals.get) high = list(reversed(sortedtotals)) send('Most active bot users:') for x in range(3): if x < len(high): send("%s: %s" % (high[x], totals[high[x]])) elif cmdargs.nick: send(get_nick(session, cmdargs.nick)) else: command = choice(list(totals.keys())) send("%s has been used %s times." % (command, totals[command]))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "group", ".", "add_argument", "(", "'--high'", ",", "action", "=", "'store_true'", ")", "group", ".", "add_argument", "(", "'--low'", ",", "action", "=", "'store_true'", ")", "group", ".", "add_argument", "(", "'--userhigh'", ",", "action", "=", "'store_true'", ")", "group", ".", "add_argument", "(", "'--nick'", ",", "action", "=", "arguments", ".", "NickParser", ")", "group", ".", "add_argument", "(", "'command'", ",", "nargs", "=", "'?'", ")", "try", ":", "cmdargs", "=", "parser", ".", "parse_args", "(", "msg", ")", "except", "arguments", ".", "ArgumentException", "as", "e", ":", "send", "(", "str", "(", "e", ")", ")", "return", "session", "=", "args", "[", "'db'", "]", "totals", "=", "get_command_totals", "(", "session", ")", "sortedtotals", "=", "sorted", "(", "totals", ",", "key", "=", "totals", ".", "get", ")", "if", "command_registry", ".", "is_registered", "(", "cmdargs", ".", "command", ")", ":", "send", "(", "get_command", "(", "session", ",", "cmdargs", ".", "command", ",", "totals", ")", ")", "elif", "cmdargs", ".", "command", "and", "not", "command_registry", ".", "is_registered", "(", "cmdargs", ".", "command", ")", ":", "send", "(", "\"Command %s not found.\"", "%", "cmdargs", ".", "command", ")", "elif", "cmdargs", ".", "high", ":", "send", "(", "'Most Used Commands:'", ")", "high", "=", "list", "(", "reversed", "(", "sortedtotals", ")", ")", "for", "x", "in", "range", "(", "3", ")", ":", "if", "x", "<", "len", "(", "high", ")", ":", "send", "(", "\"%s: %s\"", "%", "(", "high", "[", "x", "]", ",", "totals", "[", "high", "[", "x", "]", "]", ")", ")", "elif", "cmdargs", ".", "low", ":", "send", "(", "'Least Used Commands:'", ")", "low", "=", "sortedtotals", "for", "x", "in", "range", "(", "3", ")", ":", "if", "x", "<", "len", "(", "low", ")", ":", "send", "(", "\"%s: %s\"", "%", "(", "low", "[", "x", "]", ",", "totals", "[", "low", "[", "x", "]", "]", ")", ")", "elif", "cmdargs", ".", "userhigh", ":", "totals", "=", "get_nick_totals", "(", "session", ")", "sortedtotals", "=", "sorted", "(", "totals", ",", "key", "=", "totals", ".", "get", ")", "high", "=", "list", "(", "reversed", "(", "sortedtotals", ")", ")", "send", "(", "'Most active bot users:'", ")", "for", "x", "in", "range", "(", "3", ")", ":", "if", "x", "<", "len", "(", "high", ")", ":", "send", "(", "\"%s: %s\"", "%", "(", "high", "[", "x", "]", ",", "totals", "[", "high", "[", "x", "]", "]", ")", ")", "elif", "cmdargs", ".", "nick", ":", "send", "(", "get_nick", "(", "session", ",", "cmdargs", ".", "nick", ")", ")", "else", ":", "command", "=", "choice", "(", "list", "(", "totals", ".", "keys", "(", ")", ")", ")", "send", "(", "\"%s has been used %s times.\"", "%", "(", "command", ",", "totals", "[", "command", "]", ")", ")" ]
Gets stats. Syntax: {command} <--high|--low|--userhigh|--nick <nick>|command>
[ "Gets", "stats", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/stats.py#L59-L108
train
nephila/djangocms-apphook-setup
djangocms_apphook_setup/base.py
AutoCMSAppMixin._create_page
def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None, site=None, set_home=False): """ Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param parent: parent page (None when creating the home page) :param namespace: application instance name (as provided to the ApphookConfig) :param set_home: mark as home page (on django CMS 3.5 only) :return: draft copy of the created page """ from cms.api import create_page, create_title from cms.utils.conf import get_templates default_template = get_templates()[0][0] if page is None: page = create_page( auto_title, language=lang, parent=parent, site=site, template=default_template, in_navigation=True, published=True ) page.application_urls = cms_app page.application_namespace = namespace page.save() page.publish(lang) elif lang not in page.get_languages(): create_title( language=lang, title=auto_title, page=page ) page.publish(lang) if set_home: page.set_as_homepage() return page.get_draft_object()
python
def _create_page(cls, page, lang, auto_title, cms_app=None, parent=None, namespace=None, site=None, set_home=False): """ Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param parent: parent page (None when creating the home page) :param namespace: application instance name (as provided to the ApphookConfig) :param set_home: mark as home page (on django CMS 3.5 only) :return: draft copy of the created page """ from cms.api import create_page, create_title from cms.utils.conf import get_templates default_template = get_templates()[0][0] if page is None: page = create_page( auto_title, language=lang, parent=parent, site=site, template=default_template, in_navigation=True, published=True ) page.application_urls = cms_app page.application_namespace = namespace page.save() page.publish(lang) elif lang not in page.get_languages(): create_title( language=lang, title=auto_title, page=page ) page.publish(lang) if set_home: page.set_as_homepage() return page.get_draft_object()
[ "def", "_create_page", "(", "cls", ",", "page", ",", "lang", ",", "auto_title", ",", "cms_app", "=", "None", ",", "parent", "=", "None", ",", "namespace", "=", "None", ",", "site", "=", "None", ",", "set_home", "=", "False", ")", ":", "from", "cms", ".", "api", "import", "create_page", ",", "create_title", "from", "cms", ".", "utils", ".", "conf", "import", "get_templates", "default_template", "=", "get_templates", "(", ")", "[", "0", "]", "[", "0", "]", "if", "page", "is", "None", ":", "page", "=", "create_page", "(", "auto_title", ",", "language", "=", "lang", ",", "parent", "=", "parent", ",", "site", "=", "site", ",", "template", "=", "default_template", ",", "in_navigation", "=", "True", ",", "published", "=", "True", ")", "page", ".", "application_urls", "=", "cms_app", "page", ".", "application_namespace", "=", "namespace", "page", ".", "save", "(", ")", "page", ".", "publish", "(", "lang", ")", "elif", "lang", "not", "in", "page", ".", "get_languages", "(", ")", ":", "create_title", "(", "language", "=", "lang", ",", "title", "=", "auto_title", ",", "page", "=", "page", ")", "page", ".", "publish", "(", "lang", ")", "if", "set_home", ":", "page", ".", "set_as_homepage", "(", ")", "return", "page", ".", "get_draft_object", "(", ")" ]
Create a single page or titles :param page: Page instance :param lang: language code :param auto_title: title text for the newly created title :param cms_app: Apphook Class to be attached to the page :param parent: parent page (None when creating the home page) :param namespace: application instance name (as provided to the ApphookConfig) :param set_home: mark as home page (on django CMS 3.5 only) :return: draft copy of the created page
[ "Create", "a", "single", "page", "or", "titles" ]
e82c0afdf966f859fe13dc80fcd417b44080f460
https://github.com/nephila/djangocms-apphook-setup/blob/e82c0afdf966f859fe13dc80fcd417b44080f460/djangocms_apphook_setup/base.py#L22-L57
train
nephila/djangocms-apphook-setup
djangocms_apphook_setup/base.py
AutoCMSAppMixin._create_config
def _create_config(cls): """ Creates an ApphookConfig instance ``AutoCMSAppMixin.auto_setup['config_fields']`` is used to fill in the data of the instance. :return: ApphookConfig instance """ return cls.app_config.objects.create( namespace=cls.auto_setup['namespace'], **cls.auto_setup['config_fields'] )
python
def _create_config(cls): """ Creates an ApphookConfig instance ``AutoCMSAppMixin.auto_setup['config_fields']`` is used to fill in the data of the instance. :return: ApphookConfig instance """ return cls.app_config.objects.create( namespace=cls.auto_setup['namespace'], **cls.auto_setup['config_fields'] )
[ "def", "_create_config", "(", "cls", ")", ":", "return", "cls", ".", "app_config", ".", "objects", ".", "create", "(", "namespace", "=", "cls", ".", "auto_setup", "[", "'namespace'", "]", ",", "*", "*", "cls", ".", "auto_setup", "[", "'config_fields'", "]", ")" ]
Creates an ApphookConfig instance ``AutoCMSAppMixin.auto_setup['config_fields']`` is used to fill in the data of the instance. :return: ApphookConfig instance
[ "Creates", "an", "ApphookConfig", "instance" ]
e82c0afdf966f859fe13dc80fcd417b44080f460
https://github.com/nephila/djangocms-apphook-setup/blob/e82c0afdf966f859fe13dc80fcd417b44080f460/djangocms_apphook_setup/base.py#L60-L71
train
nephila/djangocms-apphook-setup
djangocms_apphook_setup/base.py
AutoCMSAppMixin._create_config_translation
def _create_config_translation(cls, config, lang): """ Creates a translation for the given ApphookConfig Only django-parler kind of models are currently supported. ``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data of the instance for all the languages. :param config: ApphookConfig instance :param lang: language code for the language to create """ config.set_current_language(lang, initialize=True) for field, data in cls.auto_setup['config_translated_fields'].items(): setattr(config, field, data) config.save_translations()
python
def _create_config_translation(cls, config, lang): """ Creates a translation for the given ApphookConfig Only django-parler kind of models are currently supported. ``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data of the instance for all the languages. :param config: ApphookConfig instance :param lang: language code for the language to create """ config.set_current_language(lang, initialize=True) for field, data in cls.auto_setup['config_translated_fields'].items(): setattr(config, field, data) config.save_translations()
[ "def", "_create_config_translation", "(", "cls", ",", "config", ",", "lang", ")", ":", "config", ".", "set_current_language", "(", "lang", ",", "initialize", "=", "True", ")", "for", "field", ",", "data", "in", "cls", ".", "auto_setup", "[", "'config_translated_fields'", "]", ".", "items", "(", ")", ":", "setattr", "(", "config", ",", "field", ",", "data", ")", "config", ".", "save_translations", "(", ")" ]
Creates a translation for the given ApphookConfig Only django-parler kind of models are currently supported. ``AutoCMSAppMixin.auto_setup['config_translated_fields']`` is used to fill in the data of the instance for all the languages. :param config: ApphookConfig instance :param lang: language code for the language to create
[ "Creates", "a", "translation", "for", "the", "given", "ApphookConfig" ]
e82c0afdf966f859fe13dc80fcd417b44080f460
https://github.com/nephila/djangocms-apphook-setup/blob/e82c0afdf966f859fe13dc80fcd417b44080f460/djangocms_apphook_setup/base.py#L74-L89
train
nephila/djangocms-apphook-setup
djangocms_apphook_setup/base.py
AutoCMSAppMixin._setup_pages
def _setup_pages(cls, config): """ Create the page structure. It created a home page (if not exists) and a sub-page, and attach the Apphook to the sub-page. Pages titles are provided by ``AutoCMSAppMixin.auto_setup`` :param setup_config: boolean to control whether creating the ApphookConfig instance """ from cms.exceptions import NoHomeFound from cms.models import Page from cms.utils import get_language_list from django.conf import settings from django.utils.translation import override app_page = None get_url = False if getattr(settings, 'ALDRYN_SEARCH_CMS_PAGE', False): from aldryn_search.search_indexes import TitleIndex def fake_url(self, obj): return '' get_url = TitleIndex.get_url TitleIndex.get_url = fake_url site = Site.objects.get_current() auto_sites = cls.auto_setup.get('sites', True) if auto_sites is True or site.pk in auto_sites: if getattr(cls, 'app_config', False): configs = cls.app_config.objects.all() if not configs.exists(): config = cls._create_config() else: config = configs.first() langs = get_language_list(site.pk) if not Page.objects.on_site(site.pk).filter(application_urls=cls.__name__).exists(): for lang in langs: with override(lang): if config: if cls.auto_setup['config_translated_fields']: cls._create_config_translation(config, lang) namespace = config.namespace elif cls.app_name: namespace = cls.app_name else: namespace = None try: home = Page.objects.get_home(site.pk).get_draft_object() except NoHomeFound: home = None set_home = hasattr(Page, 'set_as_homepage') home = cls._create_page( home, lang, cls.auto_setup['home title'], site=site, set_home=set_home ) app_page = cls._create_page( app_page, lang, cls.auto_setup['page title'], cls.__name__, home, namespace, site=site ) if get_url: TitleIndex.get_url = get_url
python
def _setup_pages(cls, config): """ Create the page structure. It created a home page (if not exists) and a sub-page, and attach the Apphook to the sub-page. Pages titles are provided by ``AutoCMSAppMixin.auto_setup`` :param setup_config: boolean to control whether creating the ApphookConfig instance """ from cms.exceptions import NoHomeFound from cms.models import Page from cms.utils import get_language_list from django.conf import settings from django.utils.translation import override app_page = None get_url = False if getattr(settings, 'ALDRYN_SEARCH_CMS_PAGE', False): from aldryn_search.search_indexes import TitleIndex def fake_url(self, obj): return '' get_url = TitleIndex.get_url TitleIndex.get_url = fake_url site = Site.objects.get_current() auto_sites = cls.auto_setup.get('sites', True) if auto_sites is True or site.pk in auto_sites: if getattr(cls, 'app_config', False): configs = cls.app_config.objects.all() if not configs.exists(): config = cls._create_config() else: config = configs.first() langs = get_language_list(site.pk) if not Page.objects.on_site(site.pk).filter(application_urls=cls.__name__).exists(): for lang in langs: with override(lang): if config: if cls.auto_setup['config_translated_fields']: cls._create_config_translation(config, lang) namespace = config.namespace elif cls.app_name: namespace = cls.app_name else: namespace = None try: home = Page.objects.get_home(site.pk).get_draft_object() except NoHomeFound: home = None set_home = hasattr(Page, 'set_as_homepage') home = cls._create_page( home, lang, cls.auto_setup['home title'], site=site, set_home=set_home ) app_page = cls._create_page( app_page, lang, cls.auto_setup['page title'], cls.__name__, home, namespace, site=site ) if get_url: TitleIndex.get_url = get_url
[ "def", "_setup_pages", "(", "cls", ",", "config", ")", ":", "from", "cms", ".", "exceptions", "import", "NoHomeFound", "from", "cms", ".", "models", "import", "Page", "from", "cms", ".", "utils", "import", "get_language_list", "from", "django", ".", "conf", "import", "settings", "from", "django", ".", "utils", ".", "translation", "import", "override", "app_page", "=", "None", "get_url", "=", "False", "if", "getattr", "(", "settings", ",", "'ALDRYN_SEARCH_CMS_PAGE'", ",", "False", ")", ":", "from", "aldryn_search", ".", "search_indexes", "import", "TitleIndex", "def", "fake_url", "(", "self", ",", "obj", ")", ":", "return", "''", "get_url", "=", "TitleIndex", ".", "get_url", "TitleIndex", ".", "get_url", "=", "fake_url", "site", "=", "Site", ".", "objects", ".", "get_current", "(", ")", "auto_sites", "=", "cls", ".", "auto_setup", ".", "get", "(", "'sites'", ",", "True", ")", "if", "auto_sites", "is", "True", "or", "site", ".", "pk", "in", "auto_sites", ":", "if", "getattr", "(", "cls", ",", "'app_config'", ",", "False", ")", ":", "configs", "=", "cls", ".", "app_config", ".", "objects", ".", "all", "(", ")", "if", "not", "configs", ".", "exists", "(", ")", ":", "config", "=", "cls", ".", "_create_config", "(", ")", "else", ":", "config", "=", "configs", ".", "first", "(", ")", "langs", "=", "get_language_list", "(", "site", ".", "pk", ")", "if", "not", "Page", ".", "objects", ".", "on_site", "(", "site", ".", "pk", ")", ".", "filter", "(", "application_urls", "=", "cls", ".", "__name__", ")", ".", "exists", "(", ")", ":", "for", "lang", "in", "langs", ":", "with", "override", "(", "lang", ")", ":", "if", "config", ":", "if", "cls", ".", "auto_setup", "[", "'config_translated_fields'", "]", ":", "cls", ".", "_create_config_translation", "(", "config", ",", "lang", ")", "namespace", "=", "config", ".", "namespace", "elif", "cls", ".", "app_name", ":", "namespace", "=", "cls", ".", "app_name", "else", ":", "namespace", "=", "None", "try", ":", "home", "=", "Page", ".", "objects", ".", "get_home", "(", "site", ".", "pk", ")", ".", "get_draft_object", "(", ")", "except", "NoHomeFound", ":", "home", "=", "None", "set_home", "=", "hasattr", "(", "Page", ",", "'set_as_homepage'", ")", "home", "=", "cls", ".", "_create_page", "(", "home", ",", "lang", ",", "cls", ".", "auto_setup", "[", "'home title'", "]", ",", "site", "=", "site", ",", "set_home", "=", "set_home", ")", "app_page", "=", "cls", ".", "_create_page", "(", "app_page", ",", "lang", ",", "cls", ".", "auto_setup", "[", "'page title'", "]", ",", "cls", ".", "__name__", ",", "home", ",", "namespace", ",", "site", "=", "site", ")", "if", "get_url", ":", "TitleIndex", ".", "get_url", "=", "get_url" ]
Create the page structure. It created a home page (if not exists) and a sub-page, and attach the Apphook to the sub-page. Pages titles are provided by ``AutoCMSAppMixin.auto_setup`` :param setup_config: boolean to control whether creating the ApphookConfig instance
[ "Create", "the", "page", "structure", "." ]
e82c0afdf966f859fe13dc80fcd417b44080f460
https://github.com/nephila/djangocms-apphook-setup/blob/e82c0afdf966f859fe13dc80fcd417b44080f460/djangocms_apphook_setup/base.py#L92-L153
train
nephila/djangocms-apphook-setup
djangocms_apphook_setup/base.py
AutoCMSAppMixin.setup
def setup(cls): """ Main method to auto setup Apphook It must be called after the Apphook registration:: apphook_pool.register(MyApp) MyApp.setup() """ try: if cls.auto_setup and cls.auto_setup.get('enabled', False): if not cls.auto_setup.get('home title', False): warnings.warn( '"home title" is not set in {0}.auto_setup attribute'.format(cls) ) return if not cls.auto_setup.get('page title', False): warnings.warn( '"page title" is not set in {0}.auto_setup attribute'.format(cls) ) return if cls.app_name and not cls.auto_setup.get('namespace', False): warnings.warn( '"page title" is not set in {0}.auto_setup attribute'.format(cls) ) return config = None cls._setup_pages(config) except Exception: # Ignore any error during setup. Worst case: pages are not created, but the instance # won't break pass
python
def setup(cls): """ Main method to auto setup Apphook It must be called after the Apphook registration:: apphook_pool.register(MyApp) MyApp.setup() """ try: if cls.auto_setup and cls.auto_setup.get('enabled', False): if not cls.auto_setup.get('home title', False): warnings.warn( '"home title" is not set in {0}.auto_setup attribute'.format(cls) ) return if not cls.auto_setup.get('page title', False): warnings.warn( '"page title" is not set in {0}.auto_setup attribute'.format(cls) ) return if cls.app_name and not cls.auto_setup.get('namespace', False): warnings.warn( '"page title" is not set in {0}.auto_setup attribute'.format(cls) ) return config = None cls._setup_pages(config) except Exception: # Ignore any error during setup. Worst case: pages are not created, but the instance # won't break pass
[ "def", "setup", "(", "cls", ")", ":", "try", ":", "if", "cls", ".", "auto_setup", "and", "cls", ".", "auto_setup", ".", "get", "(", "'enabled'", ",", "False", ")", ":", "if", "not", "cls", ".", "auto_setup", ".", "get", "(", "'home title'", ",", "False", ")", ":", "warnings", ".", "warn", "(", "'\"home title\" is not set in {0}.auto_setup attribute'", ".", "format", "(", "cls", ")", ")", "return", "if", "not", "cls", ".", "auto_setup", ".", "get", "(", "'page title'", ",", "False", ")", ":", "warnings", ".", "warn", "(", "'\"page title\" is not set in {0}.auto_setup attribute'", ".", "format", "(", "cls", ")", ")", "return", "if", "cls", ".", "app_name", "and", "not", "cls", ".", "auto_setup", ".", "get", "(", "'namespace'", ",", "False", ")", ":", "warnings", ".", "warn", "(", "'\"page title\" is not set in {0}.auto_setup attribute'", ".", "format", "(", "cls", ")", ")", "return", "config", "=", "None", "cls", ".", "_setup_pages", "(", "config", ")", "except", "Exception", ":", "# Ignore any error during setup. Worst case: pages are not created, but the instance", "# won't break", "pass" ]
Main method to auto setup Apphook It must be called after the Apphook registration:: apphook_pool.register(MyApp) MyApp.setup()
[ "Main", "method", "to", "auto", "setup", "Apphook" ]
e82c0afdf966f859fe13dc80fcd417b44080f460
https://github.com/nephila/djangocms-apphook-setup/blob/e82c0afdf966f859fe13dc80fcd417b44080f460/djangocms_apphook_setup/base.py#L156-L187
train
Genida/archan
src/archan/analysis.py
Analysis.run
def run(self, verbose=True): """ Run the analysis. Generate data from each provider, then check these data with every checker, and store the analysis results. Args: verbose (bool): whether to immediately print the results or not. """ self.results.clear() for analysis_group in self.config.analysis_groups: if analysis_group.providers: for provider in analysis_group.providers: logger.info('Run provider %s', provider.identifier) provider.run() for checker in analysis_group.checkers: result = self._get_checker_result( analysis_group, checker, provider) self.results.append(result) analysis_group.results.append(result) if verbose: result.print() else: for checker in analysis_group.checkers: result = self._get_checker_result( analysis_group, checker, nd='no-data-') self.results.append(result) analysis_group.results.append(result) if verbose: result.print()
python
def run(self, verbose=True): """ Run the analysis. Generate data from each provider, then check these data with every checker, and store the analysis results. Args: verbose (bool): whether to immediately print the results or not. """ self.results.clear() for analysis_group in self.config.analysis_groups: if analysis_group.providers: for provider in analysis_group.providers: logger.info('Run provider %s', provider.identifier) provider.run() for checker in analysis_group.checkers: result = self._get_checker_result( analysis_group, checker, provider) self.results.append(result) analysis_group.results.append(result) if verbose: result.print() else: for checker in analysis_group.checkers: result = self._get_checker_result( analysis_group, checker, nd='no-data-') self.results.append(result) analysis_group.results.append(result) if verbose: result.print()
[ "def", "run", "(", "self", ",", "verbose", "=", "True", ")", ":", "self", ".", "results", ".", "clear", "(", ")", "for", "analysis_group", "in", "self", ".", "config", ".", "analysis_groups", ":", "if", "analysis_group", ".", "providers", ":", "for", "provider", "in", "analysis_group", ".", "providers", ":", "logger", ".", "info", "(", "'Run provider %s'", ",", "provider", ".", "identifier", ")", "provider", ".", "run", "(", ")", "for", "checker", "in", "analysis_group", ".", "checkers", ":", "result", "=", "self", ".", "_get_checker_result", "(", "analysis_group", ",", "checker", ",", "provider", ")", "self", ".", "results", ".", "append", "(", "result", ")", "analysis_group", ".", "results", ".", "append", "(", "result", ")", "if", "verbose", ":", "result", ".", "print", "(", ")", "else", ":", "for", "checker", "in", "analysis_group", ".", "checkers", ":", "result", "=", "self", ".", "_get_checker_result", "(", "analysis_group", ",", "checker", ",", "nd", "=", "'no-data-'", ")", "self", ".", "results", ".", "append", "(", "result", ")", "analysis_group", ".", "results", ".", "append", "(", "result", ")", "if", "verbose", ":", "result", ".", "print", "(", ")" ]
Run the analysis. Generate data from each provider, then check these data with every checker, and store the analysis results. Args: verbose (bool): whether to immediately print the results or not.
[ "Run", "the", "analysis", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/analysis.py#L41-L72
train
Genida/archan
src/archan/analysis.py
Analysis.output_tap
def output_tap(self): """Output analysis results in TAP format.""" tracker = Tracker(streaming=True, stream=sys.stdout) for group in self.config.analysis_groups: n_providers = len(group.providers) n_checkers = len(group.checkers) if not group.providers and group.checkers: test_suite = group.name description_lambda = lambda r: r.checker.name elif not group.checkers: logger.warning( 'Invalid analysis group (no checkers), skipping') continue elif n_providers > n_checkers: test_suite = group.checkers[0].name description_lambda = lambda r: r.provider.name else: test_suite = group.providers[0].name description_lambda = lambda r: r.checker.name for result in group.results: description = description_lambda(result) if result.code == ResultCode.PASSED: tracker.add_ok(test_suite, description) elif result.code == ResultCode.IGNORED: tracker.add_ok( test_suite, description + ' (ALLOWED FAILURE)') elif result.code == ResultCode.NOT_IMPLEMENTED: tracker.add_not_ok( test_suite, description, 'TODO implement the test') elif result.code == ResultCode.FAILED: tracker.add_not_ok( test_suite, description, diagnostics=' ---\n message: %s\n hint: %s\n ...' % ( '\n message: '.join(result.messages.split('\n')), result.checker.hint))
python
def output_tap(self): """Output analysis results in TAP format.""" tracker = Tracker(streaming=True, stream=sys.stdout) for group in self.config.analysis_groups: n_providers = len(group.providers) n_checkers = len(group.checkers) if not group.providers and group.checkers: test_suite = group.name description_lambda = lambda r: r.checker.name elif not group.checkers: logger.warning( 'Invalid analysis group (no checkers), skipping') continue elif n_providers > n_checkers: test_suite = group.checkers[0].name description_lambda = lambda r: r.provider.name else: test_suite = group.providers[0].name description_lambda = lambda r: r.checker.name for result in group.results: description = description_lambda(result) if result.code == ResultCode.PASSED: tracker.add_ok(test_suite, description) elif result.code == ResultCode.IGNORED: tracker.add_ok( test_suite, description + ' (ALLOWED FAILURE)') elif result.code == ResultCode.NOT_IMPLEMENTED: tracker.add_not_ok( test_suite, description, 'TODO implement the test') elif result.code == ResultCode.FAILED: tracker.add_not_ok( test_suite, description, diagnostics=' ---\n message: %s\n hint: %s\n ...' % ( '\n message: '.join(result.messages.split('\n')), result.checker.hint))
[ "def", "output_tap", "(", "self", ")", ":", "tracker", "=", "Tracker", "(", "streaming", "=", "True", ",", "stream", "=", "sys", ".", "stdout", ")", "for", "group", "in", "self", ".", "config", ".", "analysis_groups", ":", "n_providers", "=", "len", "(", "group", ".", "providers", ")", "n_checkers", "=", "len", "(", "group", ".", "checkers", ")", "if", "not", "group", ".", "providers", "and", "group", ".", "checkers", ":", "test_suite", "=", "group", ".", "name", "description_lambda", "=", "lambda", "r", ":", "r", ".", "checker", ".", "name", "elif", "not", "group", ".", "checkers", ":", "logger", ".", "warning", "(", "'Invalid analysis group (no checkers), skipping'", ")", "continue", "elif", "n_providers", ">", "n_checkers", ":", "test_suite", "=", "group", ".", "checkers", "[", "0", "]", ".", "name", "description_lambda", "=", "lambda", "r", ":", "r", ".", "provider", ".", "name", "else", ":", "test_suite", "=", "group", ".", "providers", "[", "0", "]", ".", "name", "description_lambda", "=", "lambda", "r", ":", "r", ".", "checker", ".", "name", "for", "result", "in", "group", ".", "results", ":", "description", "=", "description_lambda", "(", "result", ")", "if", "result", ".", "code", "==", "ResultCode", ".", "PASSED", ":", "tracker", ".", "add_ok", "(", "test_suite", ",", "description", ")", "elif", "result", ".", "code", "==", "ResultCode", ".", "IGNORED", ":", "tracker", ".", "add_ok", "(", "test_suite", ",", "description", "+", "' (ALLOWED FAILURE)'", ")", "elif", "result", ".", "code", "==", "ResultCode", ".", "NOT_IMPLEMENTED", ":", "tracker", ".", "add_not_ok", "(", "test_suite", ",", "description", ",", "'TODO implement the test'", ")", "elif", "result", ".", "code", "==", "ResultCode", ".", "FAILED", ":", "tracker", ".", "add_not_ok", "(", "test_suite", ",", "description", ",", "diagnostics", "=", "' ---\\n message: %s\\n hint: %s\\n ...'", "%", "(", "'\\n message: '", ".", "join", "(", "result", ".", "messages", ".", "split", "(", "'\\n'", ")", ")", ",", "result", ".", "checker", ".", "hint", ")", ")" ]
Output analysis results in TAP format.
[ "Output", "analysis", "results", "in", "TAP", "format", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/analysis.py#L79-L114
train
tdegeus/GooseMPL
GooseMPL/__init__.py
find_latex_font_serif
def find_latex_font_serif(): r''' Find an available font to mimic LaTeX, and return its name. ''' import os, re import matplotlib.font_manager name = lambda font: os.path.splitext(os.path.split(font)[-1])[0].split(' - ')[0] fonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf') matches = [ r'.*Computer\ Modern\ Roman.*', r'.*CMU\ Serif.*', r'.*CMU.*', r'.*Times.*', r'.*DejaVu.*', r'.*Serif.*', ] for match in matches: for font in fonts: if re.match(match,font): return name(font) return None
python
def find_latex_font_serif(): r''' Find an available font to mimic LaTeX, and return its name. ''' import os, re import matplotlib.font_manager name = lambda font: os.path.splitext(os.path.split(font)[-1])[0].split(' - ')[0] fonts = matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf') matches = [ r'.*Computer\ Modern\ Roman.*', r'.*CMU\ Serif.*', r'.*CMU.*', r'.*Times.*', r'.*DejaVu.*', r'.*Serif.*', ] for match in matches: for font in fonts: if re.match(match,font): return name(font) return None
[ "def", "find_latex_font_serif", "(", ")", ":", "import", "os", ",", "re", "import", "matplotlib", ".", "font_manager", "name", "=", "lambda", "font", ":", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "split", "(", "font", ")", "[", "-", "1", "]", ")", "[", "0", "]", ".", "split", "(", "' - '", ")", "[", "0", "]", "fonts", "=", "matplotlib", ".", "font_manager", ".", "findSystemFonts", "(", "fontpaths", "=", "None", ",", "fontext", "=", "'ttf'", ")", "matches", "=", "[", "r'.*Computer\\ Modern\\ Roman.*'", ",", "r'.*CMU\\ Serif.*'", ",", "r'.*CMU.*'", ",", "r'.*Times.*'", ",", "r'.*DejaVu.*'", ",", "r'.*Serif.*'", ",", "]", "for", "match", "in", "matches", ":", "for", "font", "in", "fonts", ":", "if", "re", ".", "match", "(", "match", ",", "font", ")", ":", "return", "name", "(", "font", ")", "return", "None" ]
r''' Find an available font to mimic LaTeX, and return its name.
[ "r", "Find", "an", "available", "font", "to", "mimic", "LaTeX", "and", "return", "its", "name", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L25-L51
train
tdegeus/GooseMPL
GooseMPL/__init__.py
copy_style
def copy_style(): r''' Write all goose-styles to the relevant matplotlib configuration directory. ''' import os import matplotlib # style definitions # ----------------- styles = {} styles['goose.mplstyle'] = ''' figure.figsize : 8,6 font.weight : normal font.size : 16 axes.labelsize : medium axes.titlesize : medium xtick.labelsize : small ytick.labelsize : small xtick.top : True ytick.right : True axes.facecolor : none axes.prop_cycle : cycler('color',['k', 'r', 'g', 'b', 'y', 'c', 'm']) legend.fontsize : medium legend.fancybox : true legend.columnspacing : 1.0 legend.handletextpad : 0.2 lines.linewidth : 2 image.cmap : afmhot image.interpolation : nearest image.origin : lower savefig.facecolor : none figure.autolayout : True errorbar.capsize : 2 ''' styles['goose-tick-in.mplstyle'] = ''' xtick.direction : in ytick.direction : in ''' styles['goose-tick-lower.mplstyle'] = ''' xtick.top : False ytick.right : False axes.spines.top : False axes.spines.right : False ''' if find_latex_font_serif() is not None: styles['goose-latex.mplstyle'] = r''' font.family : serif font.serif : {serif:s} font.weight : bold font.size : 18 text.usetex : true text.latex.preamble : \usepackage{{amsmath}},\usepackage{{amsfonts}},\usepackage{{amssymb}},\usepackage{{bm}} '''.format(serif=find_latex_font_serif()) else: styles['goose-latex.mplstyle'] = r''' font.family : serif font.weight : bold font.size : 18 text.usetex : true text.latex.preamble : \usepackage{{amsmath}},\usepackage{{amsfonts}},\usepackage{{amssymb}},\usepackage{{bm}} ''' # write style definitions # ----------------------- # directory name where the styles are stored dirname = os.path.abspath(os.path.join(matplotlib.get_configdir(), 'stylelib')) # make directory if it does not yet exist if not os.path.isdir(dirname): os.makedirs(dirname) # write all styles for fname, style in styles.items(): open(os.path.join(dirname, fname),'w').write(style)
python
def copy_style(): r''' Write all goose-styles to the relevant matplotlib configuration directory. ''' import os import matplotlib # style definitions # ----------------- styles = {} styles['goose.mplstyle'] = ''' figure.figsize : 8,6 font.weight : normal font.size : 16 axes.labelsize : medium axes.titlesize : medium xtick.labelsize : small ytick.labelsize : small xtick.top : True ytick.right : True axes.facecolor : none axes.prop_cycle : cycler('color',['k', 'r', 'g', 'b', 'y', 'c', 'm']) legend.fontsize : medium legend.fancybox : true legend.columnspacing : 1.0 legend.handletextpad : 0.2 lines.linewidth : 2 image.cmap : afmhot image.interpolation : nearest image.origin : lower savefig.facecolor : none figure.autolayout : True errorbar.capsize : 2 ''' styles['goose-tick-in.mplstyle'] = ''' xtick.direction : in ytick.direction : in ''' styles['goose-tick-lower.mplstyle'] = ''' xtick.top : False ytick.right : False axes.spines.top : False axes.spines.right : False ''' if find_latex_font_serif() is not None: styles['goose-latex.mplstyle'] = r''' font.family : serif font.serif : {serif:s} font.weight : bold font.size : 18 text.usetex : true text.latex.preamble : \usepackage{{amsmath}},\usepackage{{amsfonts}},\usepackage{{amssymb}},\usepackage{{bm}} '''.format(serif=find_latex_font_serif()) else: styles['goose-latex.mplstyle'] = r''' font.family : serif font.weight : bold font.size : 18 text.usetex : true text.latex.preamble : \usepackage{{amsmath}},\usepackage{{amsfonts}},\usepackage{{amssymb}},\usepackage{{bm}} ''' # write style definitions # ----------------------- # directory name where the styles are stored dirname = os.path.abspath(os.path.join(matplotlib.get_configdir(), 'stylelib')) # make directory if it does not yet exist if not os.path.isdir(dirname): os.makedirs(dirname) # write all styles for fname, style in styles.items(): open(os.path.join(dirname, fname),'w').write(style)
[ "def", "copy_style", "(", ")", ":", "import", "os", "import", "matplotlib", "# style definitions", "# -----------------", "styles", "=", "{", "}", "styles", "[", "'goose.mplstyle'", "]", "=", "'''\nfigure.figsize : 8,6\nfont.weight : normal\nfont.size : 16\naxes.labelsize : medium\naxes.titlesize : medium\nxtick.labelsize : small\nytick.labelsize : small\nxtick.top : True\nytick.right : True\naxes.facecolor : none\naxes.prop_cycle : cycler('color',['k', 'r', 'g', 'b', 'y', 'c', 'm'])\nlegend.fontsize : medium\nlegend.fancybox : true\nlegend.columnspacing : 1.0\nlegend.handletextpad : 0.2\nlines.linewidth : 2\nimage.cmap : afmhot\nimage.interpolation : nearest\nimage.origin : lower\nsavefig.facecolor : none\nfigure.autolayout : True\nerrorbar.capsize : 2\n'''", "styles", "[", "'goose-tick-in.mplstyle'", "]", "=", "'''\nxtick.direction : in\nytick.direction : in\n'''", "styles", "[", "'goose-tick-lower.mplstyle'", "]", "=", "'''\nxtick.top : False\nytick.right : False\naxes.spines.top : False\naxes.spines.right : False\n'''", "if", "find_latex_font_serif", "(", ")", "is", "not", "None", ":", "styles", "[", "'goose-latex.mplstyle'", "]", "=", "r'''\nfont.family : serif\nfont.serif : {serif:s}\nfont.weight : bold\nfont.size : 18\ntext.usetex : true\ntext.latex.preamble : \\usepackage{{amsmath}},\\usepackage{{amsfonts}},\\usepackage{{amssymb}},\\usepackage{{bm}}\n'''", ".", "format", "(", "serif", "=", "find_latex_font_serif", "(", ")", ")", "else", ":", "styles", "[", "'goose-latex.mplstyle'", "]", "=", "r'''\nfont.family : serif\nfont.weight : bold\nfont.size : 18\ntext.usetex : true\ntext.latex.preamble : \\usepackage{{amsmath}},\\usepackage{{amsfonts}},\\usepackage{{amssymb}},\\usepackage{{bm}}\n'''", "# write style definitions", "# -----------------------", "# directory name where the styles are stored", "dirname", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "matplotlib", ".", "get_configdir", "(", ")", ",", "'stylelib'", ")", ")", "# make directory if it does not yet exist", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")", "# write all styles", "for", "fname", ",", "style", "in", "styles", ".", "items", "(", ")", ":", "open", "(", "os", ".", "path", ".", "join", "(", "dirname", ",", "fname", ")", ",", "'w'", ")", ".", "write", "(", "style", ")" ]
r''' Write all goose-styles to the relevant matplotlib configuration directory.
[ "r", "Write", "all", "goose", "-", "styles", "to", "the", "relevant", "matplotlib", "configuration", "directory", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L55-L137
train
tdegeus/GooseMPL
GooseMPL/__init__.py
scale_lim
def scale_lim(lim,factor=1.05): r''' Scale limits to be 5% wider, to have a nice plot. :arguments: **lim** (``<list>`` | ``<str>``) The limits. May be a string "[...,...]", which is converted to a list. :options: **factor** ([``1.05``] | ``<float>``) Scale factor. ''' # convert string "[...,...]" if type(lim) == str: lim = eval(lim) # scale limits D = lim[1] - lim[0] lim[0] -= (factor-1.)/2. * D lim[1] += (factor-1.)/2. * D return lim
python
def scale_lim(lim,factor=1.05): r''' Scale limits to be 5% wider, to have a nice plot. :arguments: **lim** (``<list>`` | ``<str>``) The limits. May be a string "[...,...]", which is converted to a list. :options: **factor** ([``1.05``] | ``<float>``) Scale factor. ''' # convert string "[...,...]" if type(lim) == str: lim = eval(lim) # scale limits D = lim[1] - lim[0] lim[0] -= (factor-1.)/2. * D lim[1] += (factor-1.)/2. * D return lim
[ "def", "scale_lim", "(", "lim", ",", "factor", "=", "1.05", ")", ":", "# convert string \"[...,...]\"", "if", "type", "(", "lim", ")", "==", "str", ":", "lim", "=", "eval", "(", "lim", ")", "# scale limits", "D", "=", "lim", "[", "1", "]", "-", "lim", "[", "0", "]", "lim", "[", "0", "]", "-=", "(", "factor", "-", "1.", ")", "/", "2.", "*", "D", "lim", "[", "1", "]", "+=", "(", "factor", "-", "1.", ")", "/", "2.", "*", "D", "return", "lim" ]
r''' Scale limits to be 5% wider, to have a nice plot. :arguments: **lim** (``<list>`` | ``<str>``) The limits. May be a string "[...,...]", which is converted to a list. :options: **factor** ([``1.05``] | ``<float>``) Scale factor.
[ "r", "Scale", "limits", "to", "be", "5%", "wider", "to", "have", "a", "nice", "plot", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L180-L203
train
tdegeus/GooseMPL
GooseMPL/__init__.py
abs2rel_y
def abs2rel_y(y, axis=None): r''' Transform absolute y-coordinates to relative y-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **y** (``float``, ``list``) Absolute coordinates. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. :returns: **y** (``float``, ``list``) Relative coordinates. ''' # get current axis if axis is None: axis = plt.gca() # get current limits ymin, ymax = axis.get_ylim() # transform # - log scale if axis.get_xscale() == 'log': try : return [(np.log10(i)-np.log10(ymin))/(np.log10(ymax)-np.log10(ymin)) if i is not None else i for i in y] except: return (np.log10(y)-np.log10(ymin))/(np.log10(ymax)-np.log10(ymin)) # - normal scale else: try : return [(i-ymin)/(ymax-ymin) if i is not None else i for i in y] except: return (y-ymin)/(ymax-ymin)
python
def abs2rel_y(y, axis=None): r''' Transform absolute y-coordinates to relative y-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **y** (``float``, ``list``) Absolute coordinates. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. :returns: **y** (``float``, ``list``) Relative coordinates. ''' # get current axis if axis is None: axis = plt.gca() # get current limits ymin, ymax = axis.get_ylim() # transform # - log scale if axis.get_xscale() == 'log': try : return [(np.log10(i)-np.log10(ymin))/(np.log10(ymax)-np.log10(ymin)) if i is not None else i for i in y] except: return (np.log10(y)-np.log10(ymin))/(np.log10(ymax)-np.log10(ymin)) # - normal scale else: try : return [(i-ymin)/(ymax-ymin) if i is not None else i for i in y] except: return (y-ymin)/(ymax-ymin)
[ "def", "abs2rel_y", "(", "y", ",", "axis", "=", "None", ")", ":", "# get current axis", "if", "axis", "is", "None", ":", "axis", "=", "plt", ".", "gca", "(", ")", "# get current limits", "ymin", ",", "ymax", "=", "axis", ".", "get_ylim", "(", ")", "# transform", "# - log scale", "if", "axis", ".", "get_xscale", "(", ")", "==", "'log'", ":", "try", ":", "return", "[", "(", "np", ".", "log10", "(", "i", ")", "-", "np", ".", "log10", "(", "ymin", ")", ")", "/", "(", "np", ".", "log10", "(", "ymax", ")", "-", "np", ".", "log10", "(", "ymin", ")", ")", "if", "i", "is", "not", "None", "else", "i", "for", "i", "in", "y", "]", "except", ":", "return", "(", "np", ".", "log10", "(", "y", ")", "-", "np", ".", "log10", "(", "ymin", ")", ")", "/", "(", "np", ".", "log10", "(", "ymax", ")", "-", "np", ".", "log10", "(", "ymin", ")", ")", "# - normal scale", "else", ":", "try", ":", "return", "[", "(", "i", "-", "ymin", ")", "/", "(", "ymax", "-", "ymin", ")", "if", "i", "is", "not", "None", "else", "i", "for", "i", "in", "y", "]", "except", ":", "return", "(", "y", "-", "ymin", ")", "/", "(", "ymax", "-", "ymin", ")" ]
r''' Transform absolute y-coordinates to relative y-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **y** (``float``, ``list``) Absolute coordinates. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. :returns: **y** (``float``, ``list``) Relative coordinates.
[ "r", "Transform", "absolute", "y", "-", "coordinates", "to", "relative", "y", "-", "coordinates", ".", "Relative", "coordinates", "correspond", "to", "a", "fraction", "of", "the", "relevant", "axis", ".", "Be", "sure", "to", "set", "the", "limits", "and", "scale", "before", "calling", "this", "function!" ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L247-L283
train
tdegeus/GooseMPL
GooseMPL/__init__.py
rel2abs_x
def rel2abs_x(x, axis=None): r''' Transform relative x-coordinates to absolute x-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **x** (``float``, ``list``) Relative coordinates. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. :returns: **x** (``float``, ``list``) Absolute coordinates. ''' # get current axis if axis is None: axis = plt.gca() # get current limits xmin, xmax = axis.get_xlim() # transform # - log scale if axis.get_xscale() == 'log': try : return [10.**(np.log10(xmin)+i*(np.log10(xmax)-np.log10(xmin))) if i is not None else i for i in x] except: return 10.**(np.log10(xmin)+x*(np.log10(xmax)-np.log10(xmin))) # - normal scale else: try : return [xmin+i*(xmax-xmin) if i is not None else i for i in x] except: return xmin+x*(xmax-xmin)
python
def rel2abs_x(x, axis=None): r''' Transform relative x-coordinates to absolute x-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **x** (``float``, ``list``) Relative coordinates. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. :returns: **x** (``float``, ``list``) Absolute coordinates. ''' # get current axis if axis is None: axis = plt.gca() # get current limits xmin, xmax = axis.get_xlim() # transform # - log scale if axis.get_xscale() == 'log': try : return [10.**(np.log10(xmin)+i*(np.log10(xmax)-np.log10(xmin))) if i is not None else i for i in x] except: return 10.**(np.log10(xmin)+x*(np.log10(xmax)-np.log10(xmin))) # - normal scale else: try : return [xmin+i*(xmax-xmin) if i is not None else i for i in x] except: return xmin+x*(xmax-xmin)
[ "def", "rel2abs_x", "(", "x", ",", "axis", "=", "None", ")", ":", "# get current axis", "if", "axis", "is", "None", ":", "axis", "=", "plt", ".", "gca", "(", ")", "# get current limits", "xmin", ",", "xmax", "=", "axis", ".", "get_xlim", "(", ")", "# transform", "# - log scale", "if", "axis", ".", "get_xscale", "(", ")", "==", "'log'", ":", "try", ":", "return", "[", "10.", "**", "(", "np", ".", "log10", "(", "xmin", ")", "+", "i", "*", "(", "np", ".", "log10", "(", "xmax", ")", "-", "np", ".", "log10", "(", "xmin", ")", ")", ")", "if", "i", "is", "not", "None", "else", "i", "for", "i", "in", "x", "]", "except", ":", "return", "10.", "**", "(", "np", ".", "log10", "(", "xmin", ")", "+", "x", "*", "(", "np", ".", "log10", "(", "xmax", ")", "-", "np", ".", "log10", "(", "xmin", ")", ")", ")", "# - normal scale", "else", ":", "try", ":", "return", "[", "xmin", "+", "i", "*", "(", "xmax", "-", "xmin", ")", "if", "i", "is", "not", "None", "else", "i", "for", "i", "in", "x", "]", "except", ":", "return", "xmin", "+", "x", "*", "(", "xmax", "-", "xmin", ")" ]
r''' Transform relative x-coordinates to absolute x-coordinates. Relative coordinates correspond to a fraction of the relevant axis. Be sure to set the limits and scale before calling this function! :arguments: **x** (``float``, ``list``) Relative coordinates. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. :returns: **x** (``float``, ``list``) Absolute coordinates.
[ "r", "Transform", "relative", "x", "-", "coordinates", "to", "absolute", "x", "-", "coordinates", ".", "Relative", "coordinates", "correspond", "to", "a", "fraction", "of", "the", "relevant", "axis", ".", "Be", "sure", "to", "set", "the", "limits", "and", "scale", "before", "calling", "this", "function!" ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L287-L323
train
tdegeus/GooseMPL
GooseMPL/__init__.py
subplots
def subplots(scale_x=None, scale_y=None, scale=None, **kwargs): r''' Run ``matplotlib.pyplot.subplots`` with ``figsize`` set to the correct multiple of the default. :additional options: **scale, scale_x, scale_y** (``<float>``) Scale the figure-size (along one of the dimensions). ''' if 'figsize' in kwargs: return plt.subplots(**kwargs) width, height = mpl.rcParams['figure.figsize'] if scale is not None: width *= scale height *= scale if scale_x is not None: width *= scale_x if scale_y is not None: height *= scale_y nrows = kwargs.pop('nrows', 1) ncols = kwargs.pop('ncols', 1) width = ncols * width height = nrows * height return plt.subplots(nrows=nrows, ncols=ncols, figsize=(width,height), **kwargs)
python
def subplots(scale_x=None, scale_y=None, scale=None, **kwargs): r''' Run ``matplotlib.pyplot.subplots`` with ``figsize`` set to the correct multiple of the default. :additional options: **scale, scale_x, scale_y** (``<float>``) Scale the figure-size (along one of the dimensions). ''' if 'figsize' in kwargs: return plt.subplots(**kwargs) width, height = mpl.rcParams['figure.figsize'] if scale is not None: width *= scale height *= scale if scale_x is not None: width *= scale_x if scale_y is not None: height *= scale_y nrows = kwargs.pop('nrows', 1) ncols = kwargs.pop('ncols', 1) width = ncols * width height = nrows * height return plt.subplots(nrows=nrows, ncols=ncols, figsize=(width,height), **kwargs)
[ "def", "subplots", "(", "scale_x", "=", "None", ",", "scale_y", "=", "None", ",", "scale", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'figsize'", "in", "kwargs", ":", "return", "plt", ".", "subplots", "(", "*", "*", "kwargs", ")", "width", ",", "height", "=", "mpl", ".", "rcParams", "[", "'figure.figsize'", "]", "if", "scale", "is", "not", "None", ":", "width", "*=", "scale", "height", "*=", "scale", "if", "scale_x", "is", "not", "None", ":", "width", "*=", "scale_x", "if", "scale_y", "is", "not", "None", ":", "height", "*=", "scale_y", "nrows", "=", "kwargs", ".", "pop", "(", "'nrows'", ",", "1", ")", "ncols", "=", "kwargs", ".", "pop", "(", "'ncols'", ",", "1", ")", "width", "=", "ncols", "*", "width", "height", "=", "nrows", "*", "height", "return", "plt", ".", "subplots", "(", "nrows", "=", "nrows", ",", "ncols", "=", "ncols", ",", "figsize", "=", "(", "width", ",", "height", ")", ",", "*", "*", "kwargs", ")" ]
r''' Run ``matplotlib.pyplot.subplots`` with ``figsize`` set to the correct multiple of the default. :additional options: **scale, scale_x, scale_y** (``<float>``) Scale the figure-size (along one of the dimensions).
[ "r", "Run", "matplotlib", ".", "pyplot", ".", "subplots", "with", "figsize", "set", "to", "the", "correct", "multiple", "of", "the", "default", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L367-L397
train
tdegeus/GooseMPL
GooseMPL/__init__.py
plot
def plot(x, y, units='absolute', axis=None, **kwargs): r''' Plot. :arguments: **x, y** (``list``) Coordinates. :options: **units** ([``'absolute'``] | ``'relative'``) The type of units in which the coordinates are specified. Relative coordinates correspond to a fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and scale before calling this function! ... Any ``plt.plot(...)`` option. :returns: The handle of the ``plt.plot(...)`` command. ''' # get current axis if axis is None: axis = plt.gca() # transform if units.lower() == 'relative': x = rel2abs_x(x, axis) y = rel2abs_y(y, axis) # plot return axis.plot(x, y, **kwargs)
python
def plot(x, y, units='absolute', axis=None, **kwargs): r''' Plot. :arguments: **x, y** (``list``) Coordinates. :options: **units** ([``'absolute'``] | ``'relative'``) The type of units in which the coordinates are specified. Relative coordinates correspond to a fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and scale before calling this function! ... Any ``plt.plot(...)`` option. :returns: The handle of the ``plt.plot(...)`` command. ''' # get current axis if axis is None: axis = plt.gca() # transform if units.lower() == 'relative': x = rel2abs_x(x, axis) y = rel2abs_y(y, axis) # plot return axis.plot(x, y, **kwargs)
[ "def", "plot", "(", "x", ",", "y", ",", "units", "=", "'absolute'", ",", "axis", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# get current axis", "if", "axis", "is", "None", ":", "axis", "=", "plt", ".", "gca", "(", ")", "# transform", "if", "units", ".", "lower", "(", ")", "==", "'relative'", ":", "x", "=", "rel2abs_x", "(", "x", ",", "axis", ")", "y", "=", "rel2abs_y", "(", "y", ",", "axis", ")", "# plot", "return", "axis", ".", "plot", "(", "x", ",", "y", ",", "*", "*", "kwargs", ")" ]
r''' Plot. :arguments: **x, y** (``list``) Coordinates. :options: **units** ([``'absolute'``] | ``'relative'``) The type of units in which the coordinates are specified. Relative coordinates correspond to a fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and scale before calling this function! ... Any ``plt.plot(...)`` option. :returns: The handle of the ``plt.plot(...)`` command.
[ "r", "Plot", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L401-L435
train
tdegeus/GooseMPL
GooseMPL/__init__.py
plot_powerlaw
def plot_powerlaw(exp, startx, starty, width=None, **kwargs): r''' Plot a power-law. :arguments: **exp** (``float``) The power-law exponent. **startx, starty** (``float``) Start coordinates. :options: **width, height, endx, endy** (``float``) Definition of the end coordinate (only on of these options is needed). **units** ([``'relative'``] | ``'absolute'``) The type of units in which the coordinates are specified. Relative coordinates correspond to a fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and scale before calling this function! **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. ... Any ``plt.plot(...)`` option. :returns: The handle of the ``plt.plot(...)`` command. ''' # get options/defaults endx = kwargs.pop('endx' , None ) endy = kwargs.pop('endy' , None ) height = kwargs.pop('height', None ) units = kwargs.pop('units' , 'relative') axis = kwargs.pop('axis' , plt.gca() ) # check if axis.get_xscale() != 'log' or axis.get_yscale() != 'log': raise IOError('This function only works on a log-log scale, where the power-law is a straight line') # apply width/height if width is not None: endx = startx + width endy = None elif height is not None: if exp > 0: endy = starty + height elif exp == 0: endy = starty else : endy = starty - height endx = None # transform if units.lower() == 'relative': [startx, endx] = rel2abs_x([startx, endx], axis) [starty, endy] = rel2abs_y([starty, endy], axis) # determine multiplication constant const = starty / ( startx**exp ) # get end x/y-coordinate if endx is not None: endy = const * endx**exp else : endx = ( endy / const )**( 1/exp ) # plot return axis.plot([startx, endx], [starty, endy], **kwargs)
python
def plot_powerlaw(exp, startx, starty, width=None, **kwargs): r''' Plot a power-law. :arguments: **exp** (``float``) The power-law exponent. **startx, starty** (``float``) Start coordinates. :options: **width, height, endx, endy** (``float``) Definition of the end coordinate (only on of these options is needed). **units** ([``'relative'``] | ``'absolute'``) The type of units in which the coordinates are specified. Relative coordinates correspond to a fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and scale before calling this function! **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. ... Any ``plt.plot(...)`` option. :returns: The handle of the ``plt.plot(...)`` command. ''' # get options/defaults endx = kwargs.pop('endx' , None ) endy = kwargs.pop('endy' , None ) height = kwargs.pop('height', None ) units = kwargs.pop('units' , 'relative') axis = kwargs.pop('axis' , plt.gca() ) # check if axis.get_xscale() != 'log' or axis.get_yscale() != 'log': raise IOError('This function only works on a log-log scale, where the power-law is a straight line') # apply width/height if width is not None: endx = startx + width endy = None elif height is not None: if exp > 0: endy = starty + height elif exp == 0: endy = starty else : endy = starty - height endx = None # transform if units.lower() == 'relative': [startx, endx] = rel2abs_x([startx, endx], axis) [starty, endy] = rel2abs_y([starty, endy], axis) # determine multiplication constant const = starty / ( startx**exp ) # get end x/y-coordinate if endx is not None: endy = const * endx**exp else : endx = ( endy / const )**( 1/exp ) # plot return axis.plot([startx, endx], [starty, endy], **kwargs)
[ "def", "plot_powerlaw", "(", "exp", ",", "startx", ",", "starty", ",", "width", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# get options/defaults", "endx", "=", "kwargs", ".", "pop", "(", "'endx'", ",", "None", ")", "endy", "=", "kwargs", ".", "pop", "(", "'endy'", ",", "None", ")", "height", "=", "kwargs", ".", "pop", "(", "'height'", ",", "None", ")", "units", "=", "kwargs", ".", "pop", "(", "'units'", ",", "'relative'", ")", "axis", "=", "kwargs", ".", "pop", "(", "'axis'", ",", "plt", ".", "gca", "(", ")", ")", "# check", "if", "axis", ".", "get_xscale", "(", ")", "!=", "'log'", "or", "axis", ".", "get_yscale", "(", ")", "!=", "'log'", ":", "raise", "IOError", "(", "'This function only works on a log-log scale, where the power-law is a straight line'", ")", "# apply width/height", "if", "width", "is", "not", "None", ":", "endx", "=", "startx", "+", "width", "endy", "=", "None", "elif", "height", "is", "not", "None", ":", "if", "exp", ">", "0", ":", "endy", "=", "starty", "+", "height", "elif", "exp", "==", "0", ":", "endy", "=", "starty", "else", ":", "endy", "=", "starty", "-", "height", "endx", "=", "None", "# transform", "if", "units", ".", "lower", "(", ")", "==", "'relative'", ":", "[", "startx", ",", "endx", "]", "=", "rel2abs_x", "(", "[", "startx", ",", "endx", "]", ",", "axis", ")", "[", "starty", ",", "endy", "]", "=", "rel2abs_y", "(", "[", "starty", ",", "endy", "]", ",", "axis", ")", "# determine multiplication constant", "const", "=", "starty", "/", "(", "startx", "**", "exp", ")", "# get end x/y-coordinate", "if", "endx", "is", "not", "None", ":", "endy", "=", "const", "*", "endx", "**", "exp", "else", ":", "endx", "=", "(", "endy", "/", "const", ")", "**", "(", "1", "/", "exp", ")", "# plot", "return", "axis", ".", "plot", "(", "[", "startx", ",", "endx", "]", ",", "[", "starty", ",", "endy", "]", ",", "*", "*", "kwargs", ")" ]
r''' Plot a power-law. :arguments: **exp** (``float``) The power-law exponent. **startx, starty** (``float``) Start coordinates. :options: **width, height, endx, endy** (``float``) Definition of the end coordinate (only on of these options is needed). **units** ([``'relative'``] | ``'absolute'``) The type of units in which the coordinates are specified. Relative coordinates correspond to a fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and scale before calling this function! **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. ... Any ``plt.plot(...)`` option. :returns: The handle of the ``plt.plot(...)`` command.
[ "r", "Plot", "a", "power", "-", "law", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L630-L701
train
tdegeus/GooseMPL
GooseMPL/__init__.py
histogram_bin_edges_minwidth
def histogram_bin_edges_minwidth(min_width, bins): r''' Merge bins with right-neighbour until each bin has a minimum width. :arguments: **bins** (``<array_like>``) The bin-edges. **min_width** (``<float>``) The minimum bin width. ''' # escape if min_width is None : return bins if min_width is False: return bins # keep removing where needed while True: idx = np.where(np.diff(bins) < min_width)[0] if len(idx) == 0: return bins idx = idx[0] if idx+1 == len(bins)-1: bins = np.hstack(( bins[:(idx) ], bins[-1] )) else : bins = np.hstack(( bins[:(idx+1)], bins[(idx+2):] ))
python
def histogram_bin_edges_minwidth(min_width, bins): r''' Merge bins with right-neighbour until each bin has a minimum width. :arguments: **bins** (``<array_like>``) The bin-edges. **min_width** (``<float>``) The minimum bin width. ''' # escape if min_width is None : return bins if min_width is False: return bins # keep removing where needed while True: idx = np.where(np.diff(bins) < min_width)[0] if len(idx) == 0: return bins idx = idx[0] if idx+1 == len(bins)-1: bins = np.hstack(( bins[:(idx) ], bins[-1] )) else : bins = np.hstack(( bins[:(idx+1)], bins[(idx+2):] ))
[ "def", "histogram_bin_edges_minwidth", "(", "min_width", ",", "bins", ")", ":", "# escape", "if", "min_width", "is", "None", ":", "return", "bins", "if", "min_width", "is", "False", ":", "return", "bins", "# keep removing where needed", "while", "True", ":", "idx", "=", "np", ".", "where", "(", "np", ".", "diff", "(", "bins", ")", "<", "min_width", ")", "[", "0", "]", "if", "len", "(", "idx", ")", "==", "0", ":", "return", "bins", "idx", "=", "idx", "[", "0", "]", "if", "idx", "+", "1", "==", "len", "(", "bins", ")", "-", "1", ":", "bins", "=", "np", ".", "hstack", "(", "(", "bins", "[", ":", "(", "idx", ")", "]", ",", "bins", "[", "-", "1", "]", ")", ")", "else", ":", "bins", "=", "np", ".", "hstack", "(", "(", "bins", "[", ":", "(", "idx", "+", "1", ")", "]", ",", "bins", "[", "(", "idx", "+", "2", ")", ":", "]", ")", ")" ]
r''' Merge bins with right-neighbour until each bin has a minimum width. :arguments: **bins** (``<array_like>``) The bin-edges. **min_width** (``<float>``) The minimum bin width.
[ "r", "Merge", "bins", "with", "right", "-", "neighbour", "until", "each", "bin", "has", "a", "minimum", "width", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L840-L867
train
tdegeus/GooseMPL
GooseMPL/__init__.py
histogram_bin_edges_mincount
def histogram_bin_edges_mincount(data, min_count, bins): r''' Merge bins with right-neighbour until each bin has a minimum number of data-points. :arguments: **data** (``<array_like>``) Input data. The histogram is computed over the flattened array. **bins** (``<array_like>`` | ``<int>``) The bin-edges (or the number of bins, automatically converted to equal-sized bins). **min_count** (``<int>``) The minimum number of data-points per bin. ''' # escape if min_count is None : return bins if min_count is False: return bins # check if type(min_count) != int: raise IOError('"min_count" must be an integer number') # keep removing where needed while True: P, _ = np.histogram(data, bins=bins, density=False) idx = np.where(P < min_count)[0] if len(idx) == 0: return bins idx = idx[0] if idx+1 == len(P): bins = np.hstack(( bins[:(idx) ], bins[-1] )) else : bins = np.hstack(( bins[:(idx+1)], bins[(idx+2):] ))
python
def histogram_bin_edges_mincount(data, min_count, bins): r''' Merge bins with right-neighbour until each bin has a minimum number of data-points. :arguments: **data** (``<array_like>``) Input data. The histogram is computed over the flattened array. **bins** (``<array_like>`` | ``<int>``) The bin-edges (or the number of bins, automatically converted to equal-sized bins). **min_count** (``<int>``) The minimum number of data-points per bin. ''' # escape if min_count is None : return bins if min_count is False: return bins # check if type(min_count) != int: raise IOError('"min_count" must be an integer number') # keep removing where needed while True: P, _ = np.histogram(data, bins=bins, density=False) idx = np.where(P < min_count)[0] if len(idx) == 0: return bins idx = idx[0] if idx+1 == len(P): bins = np.hstack(( bins[:(idx) ], bins[-1] )) else : bins = np.hstack(( bins[:(idx+1)], bins[(idx+2):] ))
[ "def", "histogram_bin_edges_mincount", "(", "data", ",", "min_count", ",", "bins", ")", ":", "# escape", "if", "min_count", "is", "None", ":", "return", "bins", "if", "min_count", "is", "False", ":", "return", "bins", "# check", "if", "type", "(", "min_count", ")", "!=", "int", ":", "raise", "IOError", "(", "'\"min_count\" must be an integer number'", ")", "# keep removing where needed", "while", "True", ":", "P", ",", "_", "=", "np", ".", "histogram", "(", "data", ",", "bins", "=", "bins", ",", "density", "=", "False", ")", "idx", "=", "np", ".", "where", "(", "P", "<", "min_count", ")", "[", "0", "]", "if", "len", "(", "idx", ")", "==", "0", ":", "return", "bins", "idx", "=", "idx", "[", "0", "]", "if", "idx", "+", "1", "==", "len", "(", "P", ")", ":", "bins", "=", "np", ".", "hstack", "(", "(", "bins", "[", ":", "(", "idx", ")", "]", ",", "bins", "[", "-", "1", "]", ")", ")", "else", ":", "bins", "=", "np", ".", "hstack", "(", "(", "bins", "[", ":", "(", "idx", "+", "1", ")", "]", ",", "bins", "[", "(", "idx", "+", "2", ")", ":", "]", ")", ")" ]
r''' Merge bins with right-neighbour until each bin has a minimum number of data-points. :arguments: **data** (``<array_like>``) Input data. The histogram is computed over the flattened array. **bins** (``<array_like>`` | ``<int>``) The bin-edges (or the number of bins, automatically converted to equal-sized bins). **min_count** (``<int>``) The minimum number of data-points per bin.
[ "r", "Merge", "bins", "with", "right", "-", "neighbour", "until", "each", "bin", "has", "a", "minimum", "number", "of", "data", "-", "points", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L871-L906
train
tdegeus/GooseMPL
GooseMPL/__init__.py
histogram_bin_edges
def histogram_bin_edges(data, bins=10, mode='equal', min_count=None, integer=False, remove_empty_edges=True, min_width=None): r''' Determine bin-edges. :arguments: **data** (``<array_like>``) Input data. The histogram is computed over the flattened array. :options: **bins** ([``10``] | ``<int>``) The number of bins. **mode** ([``'equal'`` | ``<str>``) Mode with which to compute the bin-edges: * ``'equal'``: each bin has equal width. * ``'log'``: logarithmic spacing. * ``'uniform'``: uniform number of data-points per bin. **min_count** (``<int>``) The minimum number of data-points per bin. **min_width** (``<float>``) The minimum width of each bin. **integer** ([``False``] | [``True``]) If ``True``, bins not encompassing an integer are removed (e.g. a bin with edges ``[1.1, 1.9]`` is removed, but ``[0.9, 1.1]`` is not removed). **remove_empty_edges** ([``True``] | [``False``]) Remove empty bins at the beginning or the end. :returns: **bin_edges** (``<array of dtype float>``) The edges to pass into histogram. ''' # determine the bin-edges if mode == 'equal': bin_edges = np.linspace(np.min(data),np.max(data),bins+1) elif mode == 'log': bin_edges = np.logspace(np.log10(np.min(data)),np.log10(np.max(data)),bins+1) elif mode == 'uniform': # - check if hasattr(bins, "__len__"): raise IOError('Only the number of bins can be specified') # - use the minimum count to estimate the number of bins if min_count is not None and min_count is not False: if type(min_count) != int: raise IOError('"min_count" must be an integer number') bins = int(np.floor(float(len(data))/float(min_count))) # - number of data-points in each bin (equal for each) count = int(np.floor(float(len(data))/float(bins))) * np.ones(bins, dtype='int') # - increase the number of data-points by one is an many bins as needed, # such that the total fits the total number of data-points count[np.linspace(0, bins-1, len(data)-np.sum(count)).astype(np.int)] += 1 # - split the data idx = np.empty((bins+1), dtype='int') idx[0 ] = 0 idx[1:] = np.cumsum(count) idx[-1] = len(data) - 1 # - determine the bin-edges bin_edges = np.unique(np.sort(data)[idx]) else: raise IOError('Unknown option') # remove empty starting and ending bin (related to an unfortunate choice of bin-edges) if remove_empty_edges: N, _ = np.histogram(data, bins=bin_edges, density=False) idx = np.min(np.where(N>0)[0]) jdx = np.max(np.where(N>0)[0]) bin_edges = bin_edges[(idx):(jdx+2)] # merge bins with too few data-points (if needed) bin_edges = histogram_bin_edges_mincount(data, min_count=min_count, bins=bin_edges) # merge bins that have too small of a width bin_edges = histogram_bin_edges_minwidth(min_width=min_width, bins=bin_edges) # select only bins that encompass an integer (and retain the original bounds) if integer: idx = np.where(np.diff(np.floor(bin_edges))>=1)[0] idx = np.unique(np.hstack((0, idx, len(bin_edges)-1))) bin_edges = bin_edges[idx] # return return bin_edges
python
def histogram_bin_edges(data, bins=10, mode='equal', min_count=None, integer=False, remove_empty_edges=True, min_width=None): r''' Determine bin-edges. :arguments: **data** (``<array_like>``) Input data. The histogram is computed over the flattened array. :options: **bins** ([``10``] | ``<int>``) The number of bins. **mode** ([``'equal'`` | ``<str>``) Mode with which to compute the bin-edges: * ``'equal'``: each bin has equal width. * ``'log'``: logarithmic spacing. * ``'uniform'``: uniform number of data-points per bin. **min_count** (``<int>``) The minimum number of data-points per bin. **min_width** (``<float>``) The minimum width of each bin. **integer** ([``False``] | [``True``]) If ``True``, bins not encompassing an integer are removed (e.g. a bin with edges ``[1.1, 1.9]`` is removed, but ``[0.9, 1.1]`` is not removed). **remove_empty_edges** ([``True``] | [``False``]) Remove empty bins at the beginning or the end. :returns: **bin_edges** (``<array of dtype float>``) The edges to pass into histogram. ''' # determine the bin-edges if mode == 'equal': bin_edges = np.linspace(np.min(data),np.max(data),bins+1) elif mode == 'log': bin_edges = np.logspace(np.log10(np.min(data)),np.log10(np.max(data)),bins+1) elif mode == 'uniform': # - check if hasattr(bins, "__len__"): raise IOError('Only the number of bins can be specified') # - use the minimum count to estimate the number of bins if min_count is not None and min_count is not False: if type(min_count) != int: raise IOError('"min_count" must be an integer number') bins = int(np.floor(float(len(data))/float(min_count))) # - number of data-points in each bin (equal for each) count = int(np.floor(float(len(data))/float(bins))) * np.ones(bins, dtype='int') # - increase the number of data-points by one is an many bins as needed, # such that the total fits the total number of data-points count[np.linspace(0, bins-1, len(data)-np.sum(count)).astype(np.int)] += 1 # - split the data idx = np.empty((bins+1), dtype='int') idx[0 ] = 0 idx[1:] = np.cumsum(count) idx[-1] = len(data) - 1 # - determine the bin-edges bin_edges = np.unique(np.sort(data)[idx]) else: raise IOError('Unknown option') # remove empty starting and ending bin (related to an unfortunate choice of bin-edges) if remove_empty_edges: N, _ = np.histogram(data, bins=bin_edges, density=False) idx = np.min(np.where(N>0)[0]) jdx = np.max(np.where(N>0)[0]) bin_edges = bin_edges[(idx):(jdx+2)] # merge bins with too few data-points (if needed) bin_edges = histogram_bin_edges_mincount(data, min_count=min_count, bins=bin_edges) # merge bins that have too small of a width bin_edges = histogram_bin_edges_minwidth(min_width=min_width, bins=bin_edges) # select only bins that encompass an integer (and retain the original bounds) if integer: idx = np.where(np.diff(np.floor(bin_edges))>=1)[0] idx = np.unique(np.hstack((0, idx, len(bin_edges)-1))) bin_edges = bin_edges[idx] # return return bin_edges
[ "def", "histogram_bin_edges", "(", "data", ",", "bins", "=", "10", ",", "mode", "=", "'equal'", ",", "min_count", "=", "None", ",", "integer", "=", "False", ",", "remove_empty_edges", "=", "True", ",", "min_width", "=", "None", ")", ":", "# determine the bin-edges", "if", "mode", "==", "'equal'", ":", "bin_edges", "=", "np", ".", "linspace", "(", "np", ".", "min", "(", "data", ")", ",", "np", ".", "max", "(", "data", ")", ",", "bins", "+", "1", ")", "elif", "mode", "==", "'log'", ":", "bin_edges", "=", "np", ".", "logspace", "(", "np", ".", "log10", "(", "np", ".", "min", "(", "data", ")", ")", ",", "np", ".", "log10", "(", "np", ".", "max", "(", "data", ")", ")", ",", "bins", "+", "1", ")", "elif", "mode", "==", "'uniform'", ":", "# - check", "if", "hasattr", "(", "bins", ",", "\"__len__\"", ")", ":", "raise", "IOError", "(", "'Only the number of bins can be specified'", ")", "# - use the minimum count to estimate the number of bins", "if", "min_count", "is", "not", "None", "and", "min_count", "is", "not", "False", ":", "if", "type", "(", "min_count", ")", "!=", "int", ":", "raise", "IOError", "(", "'\"min_count\" must be an integer number'", ")", "bins", "=", "int", "(", "np", ".", "floor", "(", "float", "(", "len", "(", "data", ")", ")", "/", "float", "(", "min_count", ")", ")", ")", "# - number of data-points in each bin (equal for each)", "count", "=", "int", "(", "np", ".", "floor", "(", "float", "(", "len", "(", "data", ")", ")", "/", "float", "(", "bins", ")", ")", ")", "*", "np", ".", "ones", "(", "bins", ",", "dtype", "=", "'int'", ")", "# - increase the number of data-points by one is an many bins as needed,", "# such that the total fits the total number of data-points", "count", "[", "np", ".", "linspace", "(", "0", ",", "bins", "-", "1", ",", "len", "(", "data", ")", "-", "np", ".", "sum", "(", "count", ")", ")", ".", "astype", "(", "np", ".", "int", ")", "]", "+=", "1", "# - split the data", "idx", "=", "np", ".", "empty", "(", "(", "bins", "+", "1", ")", ",", "dtype", "=", "'int'", ")", "idx", "[", "0", "]", "=", "0", "idx", "[", "1", ":", "]", "=", "np", ".", "cumsum", "(", "count", ")", "idx", "[", "-", "1", "]", "=", "len", "(", "data", ")", "-", "1", "# - determine the bin-edges", "bin_edges", "=", "np", ".", "unique", "(", "np", ".", "sort", "(", "data", ")", "[", "idx", "]", ")", "else", ":", "raise", "IOError", "(", "'Unknown option'", ")", "# remove empty starting and ending bin (related to an unfortunate choice of bin-edges)", "if", "remove_empty_edges", ":", "N", ",", "_", "=", "np", ".", "histogram", "(", "data", ",", "bins", "=", "bin_edges", ",", "density", "=", "False", ")", "idx", "=", "np", ".", "min", "(", "np", ".", "where", "(", "N", ">", "0", ")", "[", "0", "]", ")", "jdx", "=", "np", ".", "max", "(", "np", ".", "where", "(", "N", ">", "0", ")", "[", "0", "]", ")", "bin_edges", "=", "bin_edges", "[", "(", "idx", ")", ":", "(", "jdx", "+", "2", ")", "]", "# merge bins with too few data-points (if needed)", "bin_edges", "=", "histogram_bin_edges_mincount", "(", "data", ",", "min_count", "=", "min_count", ",", "bins", "=", "bin_edges", ")", "# merge bins that have too small of a width", "bin_edges", "=", "histogram_bin_edges_minwidth", "(", "min_width", "=", "min_width", ",", "bins", "=", "bin_edges", ")", "# select only bins that encompass an integer (and retain the original bounds)", "if", "integer", ":", "idx", "=", "np", ".", "where", "(", "np", ".", "diff", "(", "np", ".", "floor", "(", "bin_edges", ")", ")", ">=", "1", ")", "[", "0", "]", "idx", "=", "np", ".", "unique", "(", "np", ".", "hstack", "(", "(", "0", ",", "idx", ",", "len", "(", "bin_edges", ")", "-", "1", ")", ")", ")", "bin_edges", "=", "bin_edges", "[", "idx", "]", "# return", "return", "bin_edges" ]
r''' Determine bin-edges. :arguments: **data** (``<array_like>``) Input data. The histogram is computed over the flattened array. :options: **bins** ([``10``] | ``<int>``) The number of bins. **mode** ([``'equal'`` | ``<str>``) Mode with which to compute the bin-edges: * ``'equal'``: each bin has equal width. * ``'log'``: logarithmic spacing. * ``'uniform'``: uniform number of data-points per bin. **min_count** (``<int>``) The minimum number of data-points per bin. **min_width** (``<float>``) The minimum width of each bin. **integer** ([``False``] | [``True``]) If ``True``, bins not encompassing an integer are removed (e.g. a bin with edges ``[1.1, 1.9]`` is removed, but ``[0.9, 1.1]`` is not removed). **remove_empty_edges** ([``True``] | [``False``]) Remove empty bins at the beginning or the end. :returns: **bin_edges** (``<array of dtype float>``) The edges to pass into histogram.
[ "r", "Determine", "bin", "-", "edges", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L910-L1020
train
tdegeus/GooseMPL
GooseMPL/__init__.py
hist
def hist(P, edges, **kwargs): r''' Plot histogram. ''' from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # extract local options axis = kwargs.pop( 'axis' , plt.gca() ) cindex = kwargs.pop( 'cindex' , None ) autoscale = kwargs.pop( 'autoscale' , True ) # set defaults kwargs.setdefault('edgecolor','k') # no color-index -> set transparent if cindex is None: kwargs.setdefault('facecolor',(0.,0.,0.,0.)) # convert -> list of Polygons poly = [] for p, xl, xu in zip(P, edges[:-1], edges[1:]): coor = np.array([ [xl, 0.], [xu, 0.], [xu, p ], [xl, p ], ]) poly.append(Polygon(coor)) args = (poly) # convert patches -> matplotlib-objects p = PatchCollection(args,**kwargs) # add colors to patches if cindex is not None: p.set_array(cindex) # add patches to axis axis.add_collection(p) # rescale the axes manually if autoscale: # - get limits xlim = [ edges[0], edges[-1] ] ylim = [ 0 , np.max(P) ] # - set limits +/- 10% extra margin axis.set_xlim([xlim[0]-.1*(xlim[1]-xlim[0]),xlim[1]+.1*(xlim[1]-xlim[0])]) axis.set_ylim([ylim[0]-.1*(ylim[1]-ylim[0]),ylim[1]+.1*(ylim[1]-ylim[0])]) return p
python
def hist(P, edges, **kwargs): r''' Plot histogram. ''' from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # extract local options axis = kwargs.pop( 'axis' , plt.gca() ) cindex = kwargs.pop( 'cindex' , None ) autoscale = kwargs.pop( 'autoscale' , True ) # set defaults kwargs.setdefault('edgecolor','k') # no color-index -> set transparent if cindex is None: kwargs.setdefault('facecolor',(0.,0.,0.,0.)) # convert -> list of Polygons poly = [] for p, xl, xu in zip(P, edges[:-1], edges[1:]): coor = np.array([ [xl, 0.], [xu, 0.], [xu, p ], [xl, p ], ]) poly.append(Polygon(coor)) args = (poly) # convert patches -> matplotlib-objects p = PatchCollection(args,**kwargs) # add colors to patches if cindex is not None: p.set_array(cindex) # add patches to axis axis.add_collection(p) # rescale the axes manually if autoscale: # - get limits xlim = [ edges[0], edges[-1] ] ylim = [ 0 , np.max(P) ] # - set limits +/- 10% extra margin axis.set_xlim([xlim[0]-.1*(xlim[1]-xlim[0]),xlim[1]+.1*(xlim[1]-xlim[0])]) axis.set_ylim([ylim[0]-.1*(ylim[1]-ylim[0]),ylim[1]+.1*(ylim[1]-ylim[0])]) return p
[ "def", "hist", "(", "P", ",", "edges", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", ".", "collections", "import", "PatchCollection", "from", "matplotlib", ".", "patches", "import", "Polygon", "# extract local options", "axis", "=", "kwargs", ".", "pop", "(", "'axis'", ",", "plt", ".", "gca", "(", ")", ")", "cindex", "=", "kwargs", ".", "pop", "(", "'cindex'", ",", "None", ")", "autoscale", "=", "kwargs", ".", "pop", "(", "'autoscale'", ",", "True", ")", "# set defaults", "kwargs", ".", "setdefault", "(", "'edgecolor'", ",", "'k'", ")", "# no color-index -> set transparent", "if", "cindex", "is", "None", ":", "kwargs", ".", "setdefault", "(", "'facecolor'", ",", "(", "0.", ",", "0.", ",", "0.", ",", "0.", ")", ")", "# convert -> list of Polygons", "poly", "=", "[", "]", "for", "p", ",", "xl", ",", "xu", "in", "zip", "(", "P", ",", "edges", "[", ":", "-", "1", "]", ",", "edges", "[", "1", ":", "]", ")", ":", "coor", "=", "np", ".", "array", "(", "[", "[", "xl", ",", "0.", "]", ",", "[", "xu", ",", "0.", "]", ",", "[", "xu", ",", "p", "]", ",", "[", "xl", ",", "p", "]", ",", "]", ")", "poly", ".", "append", "(", "Polygon", "(", "coor", ")", ")", "args", "=", "(", "poly", ")", "# convert patches -> matplotlib-objects", "p", "=", "PatchCollection", "(", "args", ",", "*", "*", "kwargs", ")", "# add colors to patches", "if", "cindex", "is", "not", "None", ":", "p", ".", "set_array", "(", "cindex", ")", "# add patches to axis", "axis", ".", "add_collection", "(", "p", ")", "# rescale the axes manually", "if", "autoscale", ":", "# - get limits", "xlim", "=", "[", "edges", "[", "0", "]", ",", "edges", "[", "-", "1", "]", "]", "ylim", "=", "[", "0", ",", "np", ".", "max", "(", "P", ")", "]", "# - set limits +/- 10% extra margin", "axis", ".", "set_xlim", "(", "[", "xlim", "[", "0", "]", "-", ".1", "*", "(", "xlim", "[", "1", "]", "-", "xlim", "[", "0", "]", ")", ",", "xlim", "[", "1", "]", "+", ".1", "*", "(", "xlim", "[", "1", "]", "-", "xlim", "[", "0", "]", ")", "]", ")", "axis", ".", "set_ylim", "(", "[", "ylim", "[", "0", "]", "-", ".1", "*", "(", "ylim", "[", "1", "]", "-", "ylim", "[", "0", "]", ")", ",", "ylim", "[", "1", "]", "+", ".1", "*", "(", "ylim", "[", "1", "]", "-", "ylim", "[", "0", "]", ")", "]", ")", "return", "p" ]
r''' Plot histogram.
[ "r", "Plot", "histogram", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L1080-L1129
train
tdegeus/GooseMPL
GooseMPL/__init__.py
cdf
def cdf(data,mode='continuous',**kwargs): ''' Return cumulative density. :arguments: **data** (``<numpy.ndarray>``) Input data, to plot the distribution for. :returns: **P** (``<numpy.ndarray>``) Cumulative probability. **x** (``<numpy.ndarray>``) Data points. ''' return ( np.linspace(0.0,1.0,len(data)), np.sort(data) )
python
def cdf(data,mode='continuous',**kwargs): ''' Return cumulative density. :arguments: **data** (``<numpy.ndarray>``) Input data, to plot the distribution for. :returns: **P** (``<numpy.ndarray>``) Cumulative probability. **x** (``<numpy.ndarray>``) Data points. ''' return ( np.linspace(0.0,1.0,len(data)), np.sort(data) )
[ "def", "cdf", "(", "data", ",", "mode", "=", "'continuous'", ",", "*", "*", "kwargs", ")", ":", "return", "(", "np", ".", "linspace", "(", "0.0", ",", "1.0", ",", "len", "(", "data", ")", ")", ",", "np", ".", "sort", "(", "data", ")", ")" ]
Return cumulative density. :arguments: **data** (``<numpy.ndarray>``) Input data, to plot the distribution for. :returns: **P** (``<numpy.ndarray>``) Cumulative probability. **x** (``<numpy.ndarray>``) Data points.
[ "Return", "cumulative", "density", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L1133-L1151
train
tdegeus/GooseMPL
GooseMPL/__init__.py
patch
def patch(*args,**kwargs): ''' Add patches to plot. The color of the patches is indexed according to a specified color-index. :example: Plot a finite element mesh: the outline of the undeformed configuration, and the deformed configuration for which the elements get a color e.g. based on stress:: import matplotlib.pyplot as plt import goosempl as gplt fig,ax = plt.subplots() p = gplt.patch(coor=coor+disp,conn=conn,axis=ax,cindex=stress,cmap='YlOrRd',edgecolor=None) _ = gplt.patch(coor=coor ,conn=conn,axis=ax) cbar = fig.colorbar(p,axis=ax,aspect=10) plt.show() :arguments - option 1/2: **patches** (``<list>``) List with patch objects. Can be replaced by specifying ``coor`` and ``conn``. :arguments - option 2/2: **coor** (``<numpy.ndarray>`` | ``<list>`` (nested)) Matrix with on each row the coordinates (positions) of each node. **conn** (``<numpy.ndarray>`` | ``<list>`` (nested)) Matrix with on each row the number numbers (rows in ``coor``) which form an element (patch). :options: **cindex** (``<numpy.ndarray>``) Array with, for each patch, the value that should be indexed to a color. **axis** (``<matplotlib>``) Specify an axis to include to plot in. By default the current axis is used. **autoscale** ([``True``] | ``False``) Automatically update the limits of the plot (currently automatic limits of Collections are not supported by matplotlib). :recommended options: **cmap** (``<str>`` | ...) Specify a colormap. **linewidth** (``<float>``) Width of the edges. **edgecolor** (``<str>`` | ...) Color of the edges. **clim** (``(<float>,<float>)``) Lower and upper limit of the color-axis. :returns: **handle** (``<matplotlib>``) Handle of the patch objects. .. seealso:: * `matplotlib example <http://matplotlib.org/examples/api/patch_collection.html>`_. ''' from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # check dependent options if ( 'coor' not in kwargs or 'conn' not in kwargs ): raise IOError('Specify both "coor" and "conn"') # extract local options axis = kwargs.pop( 'axis' , plt.gca() ) cindex = kwargs.pop( 'cindex' , None ) coor = kwargs.pop( 'coor' , None ) conn = kwargs.pop( 'conn' , None ) autoscale = kwargs.pop( 'autoscale' , True ) # set defaults kwargs.setdefault('edgecolor','k') # no color-index -> set transparent if cindex is None: kwargs.setdefault('facecolor',(0.,0.,0.,0.)) # convert mesh -> list of Polygons if coor is not None and conn is not None: poly = [] for iconn in conn: poly.append(Polygon(coor[iconn,:])) args = tuple(poly, *args) # convert patches -> matplotlib-objects p = PatchCollection(args,**kwargs) # add colors to patches if cindex is not None: p.set_array(cindex) # add patches to axis axis.add_collection(p) # rescale the axes manually if autoscale: # - get limits xlim = [ np.min(coor[:,0]) , np.max(coor[:,0]) ] ylim = [ np.min(coor[:,1]) , np.max(coor[:,1]) ] # - set limits +/- 10% extra margin axis.set_xlim([xlim[0]-.1*(xlim[1]-xlim[0]),xlim[1]+.1*(xlim[1]-xlim[0])]) axis.set_ylim([ylim[0]-.1*(ylim[1]-ylim[0]),ylim[1]+.1*(ylim[1]-ylim[0])]) return p
python
def patch(*args,**kwargs): ''' Add patches to plot. The color of the patches is indexed according to a specified color-index. :example: Plot a finite element mesh: the outline of the undeformed configuration, and the deformed configuration for which the elements get a color e.g. based on stress:: import matplotlib.pyplot as plt import goosempl as gplt fig,ax = plt.subplots() p = gplt.patch(coor=coor+disp,conn=conn,axis=ax,cindex=stress,cmap='YlOrRd',edgecolor=None) _ = gplt.patch(coor=coor ,conn=conn,axis=ax) cbar = fig.colorbar(p,axis=ax,aspect=10) plt.show() :arguments - option 1/2: **patches** (``<list>``) List with patch objects. Can be replaced by specifying ``coor`` and ``conn``. :arguments - option 2/2: **coor** (``<numpy.ndarray>`` | ``<list>`` (nested)) Matrix with on each row the coordinates (positions) of each node. **conn** (``<numpy.ndarray>`` | ``<list>`` (nested)) Matrix with on each row the number numbers (rows in ``coor``) which form an element (patch). :options: **cindex** (``<numpy.ndarray>``) Array with, for each patch, the value that should be indexed to a color. **axis** (``<matplotlib>``) Specify an axis to include to plot in. By default the current axis is used. **autoscale** ([``True``] | ``False``) Automatically update the limits of the plot (currently automatic limits of Collections are not supported by matplotlib). :recommended options: **cmap** (``<str>`` | ...) Specify a colormap. **linewidth** (``<float>``) Width of the edges. **edgecolor** (``<str>`` | ...) Color of the edges. **clim** (``(<float>,<float>)``) Lower and upper limit of the color-axis. :returns: **handle** (``<matplotlib>``) Handle of the patch objects. .. seealso:: * `matplotlib example <http://matplotlib.org/examples/api/patch_collection.html>`_. ''' from matplotlib.collections import PatchCollection from matplotlib.patches import Polygon # check dependent options if ( 'coor' not in kwargs or 'conn' not in kwargs ): raise IOError('Specify both "coor" and "conn"') # extract local options axis = kwargs.pop( 'axis' , plt.gca() ) cindex = kwargs.pop( 'cindex' , None ) coor = kwargs.pop( 'coor' , None ) conn = kwargs.pop( 'conn' , None ) autoscale = kwargs.pop( 'autoscale' , True ) # set defaults kwargs.setdefault('edgecolor','k') # no color-index -> set transparent if cindex is None: kwargs.setdefault('facecolor',(0.,0.,0.,0.)) # convert mesh -> list of Polygons if coor is not None and conn is not None: poly = [] for iconn in conn: poly.append(Polygon(coor[iconn,:])) args = tuple(poly, *args) # convert patches -> matplotlib-objects p = PatchCollection(args,**kwargs) # add colors to patches if cindex is not None: p.set_array(cindex) # add patches to axis axis.add_collection(p) # rescale the axes manually if autoscale: # - get limits xlim = [ np.min(coor[:,0]) , np.max(coor[:,0]) ] ylim = [ np.min(coor[:,1]) , np.max(coor[:,1]) ] # - set limits +/- 10% extra margin axis.set_xlim([xlim[0]-.1*(xlim[1]-xlim[0]),xlim[1]+.1*(xlim[1]-xlim[0])]) axis.set_ylim([ylim[0]-.1*(ylim[1]-ylim[0]),ylim[1]+.1*(ylim[1]-ylim[0])]) return p
[ "def", "patch", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", ".", "collections", "import", "PatchCollection", "from", "matplotlib", ".", "patches", "import", "Polygon", "# check dependent options", "if", "(", "'coor'", "not", "in", "kwargs", "or", "'conn'", "not", "in", "kwargs", ")", ":", "raise", "IOError", "(", "'Specify both \"coor\" and \"conn\"'", ")", "# extract local options", "axis", "=", "kwargs", ".", "pop", "(", "'axis'", ",", "plt", ".", "gca", "(", ")", ")", "cindex", "=", "kwargs", ".", "pop", "(", "'cindex'", ",", "None", ")", "coor", "=", "kwargs", ".", "pop", "(", "'coor'", ",", "None", ")", "conn", "=", "kwargs", ".", "pop", "(", "'conn'", ",", "None", ")", "autoscale", "=", "kwargs", ".", "pop", "(", "'autoscale'", ",", "True", ")", "# set defaults", "kwargs", ".", "setdefault", "(", "'edgecolor'", ",", "'k'", ")", "# no color-index -> set transparent", "if", "cindex", "is", "None", ":", "kwargs", ".", "setdefault", "(", "'facecolor'", ",", "(", "0.", ",", "0.", ",", "0.", ",", "0.", ")", ")", "# convert mesh -> list of Polygons", "if", "coor", "is", "not", "None", "and", "conn", "is", "not", "None", ":", "poly", "=", "[", "]", "for", "iconn", "in", "conn", ":", "poly", ".", "append", "(", "Polygon", "(", "coor", "[", "iconn", ",", ":", "]", ")", ")", "args", "=", "tuple", "(", "poly", ",", "*", "args", ")", "# convert patches -> matplotlib-objects", "p", "=", "PatchCollection", "(", "args", ",", "*", "*", "kwargs", ")", "# add colors to patches", "if", "cindex", "is", "not", "None", ":", "p", ".", "set_array", "(", "cindex", ")", "# add patches to axis", "axis", ".", "add_collection", "(", "p", ")", "# rescale the axes manually", "if", "autoscale", ":", "# - get limits", "xlim", "=", "[", "np", ".", "min", "(", "coor", "[", ":", ",", "0", "]", ")", ",", "np", ".", "max", "(", "coor", "[", ":", ",", "0", "]", ")", "]", "ylim", "=", "[", "np", ".", "min", "(", "coor", "[", ":", ",", "1", "]", ")", ",", "np", ".", "max", "(", "coor", "[", ":", ",", "1", "]", ")", "]", "# - set limits +/- 10% extra margin", "axis", ".", "set_xlim", "(", "[", "xlim", "[", "0", "]", "-", ".1", "*", "(", "xlim", "[", "1", "]", "-", "xlim", "[", "0", "]", ")", ",", "xlim", "[", "1", "]", "+", ".1", "*", "(", "xlim", "[", "1", "]", "-", "xlim", "[", "0", "]", ")", "]", ")", "axis", ".", "set_ylim", "(", "[", "ylim", "[", "0", "]", "-", ".1", "*", "(", "ylim", "[", "1", "]", "-", "ylim", "[", "0", "]", ")", ",", "ylim", "[", "1", "]", "+", ".1", "*", "(", "ylim", "[", "1", "]", "-", "ylim", "[", "0", "]", ")", "]", ")", "return", "p" ]
Add patches to plot. The color of the patches is indexed according to a specified color-index. :example: Plot a finite element mesh: the outline of the undeformed configuration, and the deformed configuration for which the elements get a color e.g. based on stress:: import matplotlib.pyplot as plt import goosempl as gplt fig,ax = plt.subplots() p = gplt.patch(coor=coor+disp,conn=conn,axis=ax,cindex=stress,cmap='YlOrRd',edgecolor=None) _ = gplt.patch(coor=coor ,conn=conn,axis=ax) cbar = fig.colorbar(p,axis=ax,aspect=10) plt.show() :arguments - option 1/2: **patches** (``<list>``) List with patch objects. Can be replaced by specifying ``coor`` and ``conn``. :arguments - option 2/2: **coor** (``<numpy.ndarray>`` | ``<list>`` (nested)) Matrix with on each row the coordinates (positions) of each node. **conn** (``<numpy.ndarray>`` | ``<list>`` (nested)) Matrix with on each row the number numbers (rows in ``coor``) which form an element (patch). :options: **cindex** (``<numpy.ndarray>``) Array with, for each patch, the value that should be indexed to a color. **axis** (``<matplotlib>``) Specify an axis to include to plot in. By default the current axis is used. **autoscale** ([``True``] | ``False``) Automatically update the limits of the plot (currently automatic limits of Collections are not supported by matplotlib). :recommended options: **cmap** (``<str>`` | ...) Specify a colormap. **linewidth** (``<float>``) Width of the edges. **edgecolor** (``<str>`` | ...) Color of the edges. **clim** (``(<float>,<float>)``) Lower and upper limit of the color-axis. :returns: **handle** (``<matplotlib>``) Handle of the patch objects. .. seealso:: * `matplotlib example <http://matplotlib.org/examples/api/patch_collection.html>`_.
[ "Add", "patches", "to", "plot", ".", "The", "color", "of", "the", "patches", "is", "indexed", "according", "to", "a", "specified", "color", "-", "index", "." ]
16e1e06cbcf7131ac98c03ca7251ce83734ef905
https://github.com/tdegeus/GooseMPL/blob/16e1e06cbcf7131ac98c03ca7251ce83734ef905/GooseMPL/__init__.py#L1155-L1271
train
tjcsl/cslbot
cslbot/commands/filter.py
cmd
def cmd(send, msg, args): """Changes the output filter. Syntax: {command} [--channel channel] <filter|--show|--list|--reset|--chain filter,[filter2,...]> """ if args['type'] == 'privmsg': send('Filters must be set in channels, not via private message.') return isadmin = args['is_admin'](args['nick']) parser = arguments.ArgParser(args['config']) parser.add_argument('--channel', nargs='?', default=args['target']) group = parser.add_mutually_exclusive_group() group.add_argument('filter', nargs='?') group.add_argument('--show', action='store_true') group.add_argument('--list', action='store_true') group.add_argument('--reset', '--clear', action='store_true') group.add_argument('--chain') if not msg: send(get_filters(args['handler'], args['target'])) return try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return if cmdargs.list: send("Available filters are %s" % ", ".join(textutils.output_filters.keys())) elif cmdargs.reset and isadmin: args['handler'].outputfilter[cmdargs.channel].clear() send("Okay!") elif cmdargs.chain and isadmin: if not args['handler'].outputfilter[cmdargs.channel]: send("Must have a filter set in order to chain.") return filter_list, output = textutils.append_filters(cmdargs.chain) if filter_list is not None: args['handler'].outputfilter[cmdargs.channel].extend(filter_list) send(output) elif cmdargs.show: send(get_filters(args['handler'], cmdargs.channel)) elif isadmin: # If we're just adding a filter without chain, blow away any existing filters. filter_list, output = textutils.append_filters(cmdargs.filter) if filter_list is not None: args['handler'].outputfilter[cmdargs.channel].clear() args['handler'].outputfilter[cmdargs.channel].extend(filter_list) send(output) else: send('This command requires admin privileges.')
python
def cmd(send, msg, args): """Changes the output filter. Syntax: {command} [--channel channel] <filter|--show|--list|--reset|--chain filter,[filter2,...]> """ if args['type'] == 'privmsg': send('Filters must be set in channels, not via private message.') return isadmin = args['is_admin'](args['nick']) parser = arguments.ArgParser(args['config']) parser.add_argument('--channel', nargs='?', default=args['target']) group = parser.add_mutually_exclusive_group() group.add_argument('filter', nargs='?') group.add_argument('--show', action='store_true') group.add_argument('--list', action='store_true') group.add_argument('--reset', '--clear', action='store_true') group.add_argument('--chain') if not msg: send(get_filters(args['handler'], args['target'])) return try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: send(str(e)) return if cmdargs.list: send("Available filters are %s" % ", ".join(textutils.output_filters.keys())) elif cmdargs.reset and isadmin: args['handler'].outputfilter[cmdargs.channel].clear() send("Okay!") elif cmdargs.chain and isadmin: if not args['handler'].outputfilter[cmdargs.channel]: send("Must have a filter set in order to chain.") return filter_list, output = textutils.append_filters(cmdargs.chain) if filter_list is not None: args['handler'].outputfilter[cmdargs.channel].extend(filter_list) send(output) elif cmdargs.show: send(get_filters(args['handler'], cmdargs.channel)) elif isadmin: # If we're just adding a filter without chain, blow away any existing filters. filter_list, output = textutils.append_filters(cmdargs.filter) if filter_list is not None: args['handler'].outputfilter[cmdargs.channel].clear() args['handler'].outputfilter[cmdargs.channel].extend(filter_list) send(output) else: send('This command requires admin privileges.')
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "args", "[", "'type'", "]", "==", "'privmsg'", ":", "send", "(", "'Filters must be set in channels, not via private message.'", ")", "return", "isadmin", "=", "args", "[", "'is_admin'", "]", "(", "args", "[", "'nick'", "]", ")", "parser", "=", "arguments", ".", "ArgParser", "(", "args", "[", "'config'", "]", ")", "parser", ".", "add_argument", "(", "'--channel'", ",", "nargs", "=", "'?'", ",", "default", "=", "args", "[", "'target'", "]", ")", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", ")", "group", ".", "add_argument", "(", "'filter'", ",", "nargs", "=", "'?'", ")", "group", ".", "add_argument", "(", "'--show'", ",", "action", "=", "'store_true'", ")", "group", ".", "add_argument", "(", "'--list'", ",", "action", "=", "'store_true'", ")", "group", ".", "add_argument", "(", "'--reset'", ",", "'--clear'", ",", "action", "=", "'store_true'", ")", "group", ".", "add_argument", "(", "'--chain'", ")", "if", "not", "msg", ":", "send", "(", "get_filters", "(", "args", "[", "'handler'", "]", ",", "args", "[", "'target'", "]", ")", ")", "return", "try", ":", "cmdargs", "=", "parser", ".", "parse_args", "(", "msg", ")", "except", "arguments", ".", "ArgumentException", "as", "e", ":", "send", "(", "str", "(", "e", ")", ")", "return", "if", "cmdargs", ".", "list", ":", "send", "(", "\"Available filters are %s\"", "%", "\", \"", ".", "join", "(", "textutils", ".", "output_filters", ".", "keys", "(", ")", ")", ")", "elif", "cmdargs", ".", "reset", "and", "isadmin", ":", "args", "[", "'handler'", "]", ".", "outputfilter", "[", "cmdargs", ".", "channel", "]", ".", "clear", "(", ")", "send", "(", "\"Okay!\"", ")", "elif", "cmdargs", ".", "chain", "and", "isadmin", ":", "if", "not", "args", "[", "'handler'", "]", ".", "outputfilter", "[", "cmdargs", ".", "channel", "]", ":", "send", "(", "\"Must have a filter set in order to chain.\"", ")", "return", "filter_list", ",", "output", "=", "textutils", ".", "append_filters", "(", "cmdargs", ".", "chain", ")", "if", "filter_list", "is", "not", "None", ":", "args", "[", "'handler'", "]", ".", "outputfilter", "[", "cmdargs", ".", "channel", "]", ".", "extend", "(", "filter_list", ")", "send", "(", "output", ")", "elif", "cmdargs", ".", "show", ":", "send", "(", "get_filters", "(", "args", "[", "'handler'", "]", ",", "cmdargs", ".", "channel", ")", ")", "elif", "isadmin", ":", "# If we're just adding a filter without chain, blow away any existing filters.", "filter_list", ",", "output", "=", "textutils", ".", "append_filters", "(", "cmdargs", ".", "filter", ")", "if", "filter_list", "is", "not", "None", ":", "args", "[", "'handler'", "]", ".", "outputfilter", "[", "cmdargs", ".", "channel", "]", ".", "clear", "(", ")", "args", "[", "'handler'", "]", ".", "outputfilter", "[", "cmdargs", ".", "channel", "]", ".", "extend", "(", "filter_list", ")", "send", "(", "output", ")", "else", ":", "send", "(", "'This command requires admin privileges.'", ")" ]
Changes the output filter. Syntax: {command} [--channel channel] <filter|--show|--list|--reset|--chain filter,[filter2,...]>
[ "Changes", "the", "output", "filter", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/filter.py#L31-L80
train
JIC-CSB/jicimagelib
jicimagelib/region.py
Region.inner
def inner(self): """Region formed by taking non-border elements. :returns: :class:`jicimagelib.region.Region` """ inner_array = nd.morphology.binary_erosion(self.bitmap) return Region(inner_array)
python
def inner(self): """Region formed by taking non-border elements. :returns: :class:`jicimagelib.region.Region` """ inner_array = nd.morphology.binary_erosion(self.bitmap) return Region(inner_array)
[ "def", "inner", "(", "self", ")", ":", "inner_array", "=", "nd", ".", "morphology", ".", "binary_erosion", "(", "self", ".", "bitmap", ")", "return", "Region", "(", "inner_array", ")" ]
Region formed by taking non-border elements. :returns: :class:`jicimagelib.region.Region`
[ "Region", "formed", "by", "taking", "non", "-", "border", "elements", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/region.py#L107-L114
train
JIC-CSB/jicimagelib
jicimagelib/region.py
Region.border
def border(self): """Region formed by taking border elements. :returns: :class:`jicimagelib.region.Region` """ border_array = self.bitmap - self.inner.bitmap return Region(border_array)
python
def border(self): """Region formed by taking border elements. :returns: :class:`jicimagelib.region.Region` """ border_array = self.bitmap - self.inner.bitmap return Region(border_array)
[ "def", "border", "(", "self", ")", ":", "border_array", "=", "self", ".", "bitmap", "-", "self", ".", "inner", ".", "bitmap", "return", "Region", "(", "border_array", ")" ]
Region formed by taking border elements. :returns: :class:`jicimagelib.region.Region`
[ "Region", "formed", "by", "taking", "border", "elements", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/region.py#L117-L124
train
JIC-CSB/jicimagelib
jicimagelib/region.py
Region.convex_hull
def convex_hull(self): """Region representing the convex hull. :returns: :class:`jicimagelib.region.Region` """ hull_array = skimage.morphology.convex_hull_image(self.bitmap) return Region(hull_array)
python
def convex_hull(self): """Region representing the convex hull. :returns: :class:`jicimagelib.region.Region` """ hull_array = skimage.morphology.convex_hull_image(self.bitmap) return Region(hull_array)
[ "def", "convex_hull", "(", "self", ")", ":", "hull_array", "=", "skimage", ".", "morphology", ".", "convex_hull_image", "(", "self", ".", "bitmap", ")", "return", "Region", "(", "hull_array", ")" ]
Region representing the convex hull. :returns: :class:`jicimagelib.region.Region`
[ "Region", "representing", "the", "convex", "hull", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/region.py#L127-L133
train
JIC-CSB/jicimagelib
jicimagelib/region.py
Region.dilate
def dilate(self, iterations=1): """Return a dilated region. :param iterations: number of iterations to use in dilation :returns: :class:`jicimagelib.region.Region` """ dilated_array = nd.morphology.binary_dilation(self.bitmap, iterations=iterations) return Region(dilated_array)
python
def dilate(self, iterations=1): """Return a dilated region. :param iterations: number of iterations to use in dilation :returns: :class:`jicimagelib.region.Region` """ dilated_array = nd.morphology.binary_dilation(self.bitmap, iterations=iterations) return Region(dilated_array)
[ "def", "dilate", "(", "self", ",", "iterations", "=", "1", ")", ":", "dilated_array", "=", "nd", ".", "morphology", ".", "binary_dilation", "(", "self", ".", "bitmap", ",", "iterations", "=", "iterations", ")", "return", "Region", "(", "dilated_array", ")" ]
Return a dilated region. :param iterations: number of iterations to use in dilation :returns: :class:`jicimagelib.region.Region`
[ "Return", "a", "dilated", "region", "." ]
fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44
https://github.com/JIC-CSB/jicimagelib/blob/fbd67accb2e6d55969c6d4ed7e8b4bb4ab65cd44/jicimagelib/region.py#L162-L170
train
tjcsl/cslbot
cslbot/commands/guarded.py
cmd
def cmd(send, _, args): """Shows the currently guarded nicks. Syntax: {command} """ guarded = args['handler'].guarded if not guarded: send("Nobody is guarded.") else: send(", ".join(guarded))
python
def cmd(send, _, args): """Shows the currently guarded nicks. Syntax: {command} """ guarded = args['handler'].guarded if not guarded: send("Nobody is guarded.") else: send(", ".join(guarded))
[ "def", "cmd", "(", "send", ",", "_", ",", "args", ")", ":", "guarded", "=", "args", "[", "'handler'", "]", ".", "guarded", "if", "not", "guarded", ":", "send", "(", "\"Nobody is guarded.\"", ")", "else", ":", "send", "(", "\", \"", ".", "join", "(", "guarded", ")", ")" ]
Shows the currently guarded nicks. Syntax: {command}
[ "Shows", "the", "currently", "guarded", "nicks", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/guarded.py#L22-L32
train
CI-WATER/mapkit
mapkit/ColorRampGenerator.py
ColorRampGenerator.mapColorRampToValues
def mapColorRampToValues(cls, colorRamp, minValue, maxValue, alpha=1.0): """ Creates color ramp based on min and max values of all the raster pixels from all rasters. If pixel value is one of the no data values it will be excluded in the color ramp interpolation. Returns colorRamp, slope, intercept :param colorRamp: A list of RGB tuples representing a color ramp (e.g.: results of either generate color ramp method) :param minValue: Minimum value of range of values to map to color ramp :param maxValue: Maximum value of range of values to map to color ramp :param alpha: Decimal representing transparency (e.g.: 0.8) :rtype : MappedColorRamp """ minRampIndex = 0 # Always zero maxRampIndex = float(len(colorRamp) - 1) # Map color ramp indices to values using equation of a line # Resulting equation will be: # rampIndex = slope * value + intercept if minValue != maxValue: slope = (maxRampIndex - minRampIndex) / (maxValue - minValue) intercept = maxRampIndex - (slope * maxValue) else: slope = 0 intercept = minRampIndex # Return color ramp, slope, and intercept to interpolate by value mappedColorRamp = MappedColorRamp(colorRamp=colorRamp, slope=slope, intercept=intercept, min=minValue, max=maxValue, alpha=alpha) return mappedColorRamp
python
def mapColorRampToValues(cls, colorRamp, minValue, maxValue, alpha=1.0): """ Creates color ramp based on min and max values of all the raster pixels from all rasters. If pixel value is one of the no data values it will be excluded in the color ramp interpolation. Returns colorRamp, slope, intercept :param colorRamp: A list of RGB tuples representing a color ramp (e.g.: results of either generate color ramp method) :param minValue: Minimum value of range of values to map to color ramp :param maxValue: Maximum value of range of values to map to color ramp :param alpha: Decimal representing transparency (e.g.: 0.8) :rtype : MappedColorRamp """ minRampIndex = 0 # Always zero maxRampIndex = float(len(colorRamp) - 1) # Map color ramp indices to values using equation of a line # Resulting equation will be: # rampIndex = slope * value + intercept if minValue != maxValue: slope = (maxRampIndex - minRampIndex) / (maxValue - minValue) intercept = maxRampIndex - (slope * maxValue) else: slope = 0 intercept = minRampIndex # Return color ramp, slope, and intercept to interpolate by value mappedColorRamp = MappedColorRamp(colorRamp=colorRamp, slope=slope, intercept=intercept, min=minValue, max=maxValue, alpha=alpha) return mappedColorRamp
[ "def", "mapColorRampToValues", "(", "cls", ",", "colorRamp", ",", "minValue", ",", "maxValue", ",", "alpha", "=", "1.0", ")", ":", "minRampIndex", "=", "0", "# Always zero", "maxRampIndex", "=", "float", "(", "len", "(", "colorRamp", ")", "-", "1", ")", "# Map color ramp indices to values using equation of a line", "# Resulting equation will be:", "# rampIndex = slope * value + intercept", "if", "minValue", "!=", "maxValue", ":", "slope", "=", "(", "maxRampIndex", "-", "minRampIndex", ")", "/", "(", "maxValue", "-", "minValue", ")", "intercept", "=", "maxRampIndex", "-", "(", "slope", "*", "maxValue", ")", "else", ":", "slope", "=", "0", "intercept", "=", "minRampIndex", "# Return color ramp, slope, and intercept to interpolate by value", "mappedColorRamp", "=", "MappedColorRamp", "(", "colorRamp", "=", "colorRamp", ",", "slope", "=", "slope", ",", "intercept", "=", "intercept", ",", "min", "=", "minValue", ",", "max", "=", "maxValue", ",", "alpha", "=", "alpha", ")", "return", "mappedColorRamp" ]
Creates color ramp based on min and max values of all the raster pixels from all rasters. If pixel value is one of the no data values it will be excluded in the color ramp interpolation. Returns colorRamp, slope, intercept :param colorRamp: A list of RGB tuples representing a color ramp (e.g.: results of either generate color ramp method) :param minValue: Minimum value of range of values to map to color ramp :param maxValue: Maximum value of range of values to map to color ramp :param alpha: Decimal representing transparency (e.g.: 0.8) :rtype : MappedColorRamp
[ "Creates", "color", "ramp", "based", "on", "min", "and", "max", "values", "of", "all", "the", "raster", "pixels", "from", "all", "rasters", ".", "If", "pixel", "value", "is", "one", "of", "the", "no", "data", "values", "it", "will", "be", "excluded", "in", "the", "color", "ramp", "interpolation", ".", "Returns", "colorRamp", "slope", "intercept" ]
ce5fbded6af7adabdf1eec85631c6811ef8ecc34
https://github.com/CI-WATER/mapkit/blob/ce5fbded6af7adabdf1eec85631c6811ef8ecc34/mapkit/ColorRampGenerator.py#L273-L305
train
tjcsl/cslbot
cslbot/commands/blame.py
cmd
def cmd(send, msg, args): """Blames a random user for something. Syntax: {command} [reason] """ user = choice(get_users(args)) if msg: msg = " for " + msg msg = "blames " + user + msg send(msg, 'action')
python
def cmd(send, msg, args): """Blames a random user for something. Syntax: {command} [reason] """ user = choice(get_users(args)) if msg: msg = " for " + msg msg = "blames " + user + msg send(msg, 'action')
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "user", "=", "choice", "(", "get_users", "(", "args", ")", ")", "if", "msg", ":", "msg", "=", "\" for \"", "+", "msg", "msg", "=", "\"blames \"", "+", "user", "+", "msg", "send", "(", "msg", ",", "'action'", ")" ]
Blames a random user for something. Syntax: {command} [reason]
[ "Blames", "a", "random", "user", "for", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/blame.py#L25-L35
train
tjcsl/cslbot
cslbot/commands/weather.py
set_default
def set_default(nick, location, session, send, apikey): """Sets nick's default location to location.""" if valid_location(location, apikey): send("Setting default location") default = session.query(Weather_prefs).filter(Weather_prefs.nick == nick).first() if default is None: default = Weather_prefs(nick=nick, location=location) session.add(default) else: default.location = location else: send("Invalid or Ambiguous Location")
python
def set_default(nick, location, session, send, apikey): """Sets nick's default location to location.""" if valid_location(location, apikey): send("Setting default location") default = session.query(Weather_prefs).filter(Weather_prefs.nick == nick).first() if default is None: default = Weather_prefs(nick=nick, location=location) session.add(default) else: default.location = location else: send("Invalid or Ambiguous Location")
[ "def", "set_default", "(", "nick", ",", "location", ",", "session", ",", "send", ",", "apikey", ")", ":", "if", "valid_location", "(", "location", ",", "apikey", ")", ":", "send", "(", "\"Setting default location\"", ")", "default", "=", "session", ".", "query", "(", "Weather_prefs", ")", ".", "filter", "(", "Weather_prefs", ".", "nick", "==", "nick", ")", ".", "first", "(", ")", "if", "default", "is", "None", ":", "default", "=", "Weather_prefs", "(", "nick", "=", "nick", ",", "location", "=", "location", ")", "session", ".", "add", "(", "default", ")", "else", ":", "default", ".", "location", "=", "location", "else", ":", "send", "(", "\"Invalid or Ambiguous Location\"", ")" ]
Sets nick's default location to location.
[ "Sets", "nick", "s", "default", "location", "to", "location", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/weather.py#L73-L84
train
tjcsl/cslbot
cslbot/commands/slogan.py
cmd
def cmd(send, msg, _): """Gets a slogan. Syntax: {command} [text] """ if not msg: msg = textutils.gen_word() send(textutils.gen_slogan(msg))
python
def cmd(send, msg, _): """Gets a slogan. Syntax: {command} [text] """ if not msg: msg = textutils.gen_word() send(textutils.gen_slogan(msg))
[ "def", "cmd", "(", "send", ",", "msg", ",", "_", ")", ":", "if", "not", "msg", ":", "msg", "=", "textutils", ".", "gen_word", "(", ")", "send", "(", "textutils", ".", "gen_slogan", "(", "msg", ")", ")" ]
Gets a slogan. Syntax: {command} [text]
[ "Gets", "a", "slogan", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/slogan.py#L23-L31
train
acutesoftware/virtual-AI-simulator
vais/planet.py
Planet.evolve
def evolve(self, years): """ run the evolution of the planet to see how it looks after 'years' """ world_file = fldr + os.sep + self.name + '.txt' self.build_base() self.world.add_mountains() self.add_life() self.world.grd.save(world_file) print('TODO - run ' + str(years) + ' years')
python
def evolve(self, years): """ run the evolution of the planet to see how it looks after 'years' """ world_file = fldr + os.sep + self.name + '.txt' self.build_base() self.world.add_mountains() self.add_life() self.world.grd.save(world_file) print('TODO - run ' + str(years) + ' years')
[ "def", "evolve", "(", "self", ",", "years", ")", ":", "world_file", "=", "fldr", "+", "os", ".", "sep", "+", "self", ".", "name", "+", "'.txt'", "self", ".", "build_base", "(", ")", "self", ".", "world", ".", "add_mountains", "(", ")", "self", ".", "add_life", "(", ")", "self", ".", "world", ".", "grd", ".", "save", "(", "world_file", ")", "print", "(", "'TODO - run '", "+", "str", "(", "years", ")", "+", "' years'", ")" ]
run the evolution of the planet to see how it looks after 'years'
[ "run", "the", "evolution", "of", "the", "planet", "to", "see", "how", "it", "looks", "after", "years" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/planet.py#L53-L64
train
acutesoftware/virtual-AI-simulator
vais/planet.py
Planet.build_base
def build_base(self): """ create a base random land structure using the AIKIF world model """ #print('Planet ' + self.name + ' has formed!') self.world = my_world.World( self.grid_height, self.grid_width, [' ','x','#']) perc_land = (self.lava + (self.wind/10) + (self.rain/20) + (self.sun/10))*100 perc_sea = (100 - perc_land) perc_blocked = (self.lava/10)*100 #print('Calculating world : sea=', perc_sea, ' land=', perc_land, ' mountain=', perc_blocked, ) self.world.build_random( self.num_seeds, perc_land, perc_sea, perc_blocked)
python
def build_base(self): """ create a base random land structure using the AIKIF world model """ #print('Planet ' + self.name + ' has formed!') self.world = my_world.World( self.grid_height, self.grid_width, [' ','x','#']) perc_land = (self.lava + (self.wind/10) + (self.rain/20) + (self.sun/10))*100 perc_sea = (100 - perc_land) perc_blocked = (self.lava/10)*100 #print('Calculating world : sea=', perc_sea, ' land=', perc_land, ' mountain=', perc_blocked, ) self.world.build_random( self.num_seeds, perc_land, perc_sea, perc_blocked)
[ "def", "build_base", "(", "self", ")", ":", "#print('Planet ' + self.name + ' has formed!')", "self", ".", "world", "=", "my_world", ".", "World", "(", "self", ".", "grid_height", ",", "self", ".", "grid_width", ",", "[", "' '", ",", "'x'", ",", "'#'", "]", ")", "perc_land", "=", "(", "self", ".", "lava", "+", "(", "self", ".", "wind", "/", "10", ")", "+", "(", "self", ".", "rain", "/", "20", ")", "+", "(", "self", ".", "sun", "/", "10", ")", ")", "*", "100", "perc_sea", "=", "(", "100", "-", "perc_land", ")", "perc_blocked", "=", "(", "self", ".", "lava", "/", "10", ")", "*", "100", "#print('Calculating world : sea=', perc_sea, ' land=', perc_land, ' mountain=', perc_blocked, )", "self", ".", "world", ".", "build_random", "(", "self", ".", "num_seeds", ",", "perc_land", ",", "perc_sea", ",", "perc_blocked", ")" ]
create a base random land structure using the AIKIF world model
[ "create", "a", "base", "random", "land", "structure", "using", "the", "AIKIF", "world", "model" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/planet.py#L68-L80
train
tylerbutler/engineer
engineer/models.py
Post.url
def url(self): """The site-relative URL to the post.""" url = u'{home_url}{permalink}'.format(home_url=settings.HOME_URL, permalink=self._permalink) url = re.sub(r'/{2,}', r'/', url) return url
python
def url(self): """The site-relative URL to the post.""" url = u'{home_url}{permalink}'.format(home_url=settings.HOME_URL, permalink=self._permalink) url = re.sub(r'/{2,}', r'/', url) return url
[ "def", "url", "(", "self", ")", ":", "url", "=", "u'{home_url}{permalink}'", ".", "format", "(", "home_url", "=", "settings", ".", "HOME_URL", ",", "permalink", "=", "self", ".", "_permalink", ")", "url", "=", "re", ".", "sub", "(", "r'/{2,}'", ",", "r'/'", ",", "url", ")", "return", "url" ]
The site-relative URL to the post.
[ "The", "site", "-", "relative", "URL", "to", "the", "post", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/models.py#L157-L162
train
tylerbutler/engineer
engineer/models.py
Post.content
def content(self): """The post's content in HTML format.""" content_list = wrap_list(self._content_preprocessed) content_list.extend(self._content_stash) content_to_render = '\n'.join(content_list) return typogrify(self.content_renderer.render(content_to_render, self.format))
python
def content(self): """The post's content in HTML format.""" content_list = wrap_list(self._content_preprocessed) content_list.extend(self._content_stash) content_to_render = '\n'.join(content_list) return typogrify(self.content_renderer.render(content_to_render, self.format))
[ "def", "content", "(", "self", ")", ":", "content_list", "=", "wrap_list", "(", "self", ".", "_content_preprocessed", ")", "content_list", ".", "extend", "(", "self", ".", "_content_stash", ")", "content_to_render", "=", "'\\n'", ".", "join", "(", "content_list", ")", "return", "typogrify", "(", "self", ".", "content_renderer", ".", "render", "(", "content_to_render", ",", "self", ".", "format", ")", ")" ]
The post's content in HTML format.
[ "The", "post", "s", "content", "in", "HTML", "format", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/models.py#L188-L193
train
tylerbutler/engineer
engineer/models.py
Post.is_published
def is_published(self): """``True`` if the post is published, ``False`` otherwise.""" return self.status == Status.published and self.timestamp <= arrow.now()
python
def is_published(self): """``True`` if the post is published, ``False`` otherwise.""" return self.status == Status.published and self.timestamp <= arrow.now()
[ "def", "is_published", "(", "self", ")", ":", "return", "self", ".", "status", "==", "Status", ".", "published", "and", "self", ".", "timestamp", "<=", "arrow", ".", "now", "(", ")" ]
``True`` if the post is published, ``False`` otherwise.
[ "True", "if", "the", "post", "is", "published", "False", "otherwise", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/models.py#L243-L245
train
tylerbutler/engineer
engineer/models.py
Post.is_pending
def is_pending(self): """``True`` if the post is marked as published but has a timestamp set in the future.""" return self.status == Status.published and self.timestamp >= arrow.now()
python
def is_pending(self): """``True`` if the post is marked as published but has a timestamp set in the future.""" return self.status == Status.published and self.timestamp >= arrow.now()
[ "def", "is_pending", "(", "self", ")", ":", "return", "self", ".", "status", "==", "Status", ".", "published", "and", "self", ".", "timestamp", ">=", "arrow", ".", "now", "(", ")" ]
``True`` if the post is marked as published but has a timestamp set in the future.
[ "True", "if", "the", "post", "is", "marked", "as", "published", "but", "has", "a", "timestamp", "set", "in", "the", "future", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/models.py#L248-L250
train
tylerbutler/engineer
engineer/models.py
Post.set_finalized_content
def set_finalized_content(self, content, caller_class): """ Plugins can call this method to modify post content that is written back to source post files. This method can be called at any time by anyone, but it has no effect if the caller is not granted the ``MODIFY_RAW_POST`` permission in the Engineer configuration. The :attr:`~engineer.conf.EngineerConfiguration.FINALIZE_METADATA` setting must also be enabled in order for calls to this method to have any effect. :param content: The modified post content that should be written back to the post source file. :param caller_class: The class of the plugin that's calling this method. :return: ``True`` if the content was successfully modified; otherwise ``False``. """ caller = caller_class.get_name() if hasattr(caller_class, 'get_name') else unicode(caller_class) if not FinalizationPlugin.is_enabled(): logger.warning("A plugin is trying to modify the post content but the FINALIZE_METADATA setting is " "disabled. This setting must be enabled for plugins to modify post content. " "Plugin: %s" % caller) return False perms = settings.PLUGIN_PERMISSIONS['MODIFY_RAW_POST'] if caller not in perms and '*' not in perms: logger.warning("A plugin is trying to modify the post content but does not have the " "MODIFY_RAW_POST permission. Plugin: %s" % caller) return False else: logger.debug("%s is setting post source content." % caller) self._content_finalized = self._remove_all_stashed_content() return True
python
def set_finalized_content(self, content, caller_class): """ Plugins can call this method to modify post content that is written back to source post files. This method can be called at any time by anyone, but it has no effect if the caller is not granted the ``MODIFY_RAW_POST`` permission in the Engineer configuration. The :attr:`~engineer.conf.EngineerConfiguration.FINALIZE_METADATA` setting must also be enabled in order for calls to this method to have any effect. :param content: The modified post content that should be written back to the post source file. :param caller_class: The class of the plugin that's calling this method. :return: ``True`` if the content was successfully modified; otherwise ``False``. """ caller = caller_class.get_name() if hasattr(caller_class, 'get_name') else unicode(caller_class) if not FinalizationPlugin.is_enabled(): logger.warning("A plugin is trying to modify the post content but the FINALIZE_METADATA setting is " "disabled. This setting must be enabled for plugins to modify post content. " "Plugin: %s" % caller) return False perms = settings.PLUGIN_PERMISSIONS['MODIFY_RAW_POST'] if caller not in perms and '*' not in perms: logger.warning("A plugin is trying to modify the post content but does not have the " "MODIFY_RAW_POST permission. Plugin: %s" % caller) return False else: logger.debug("%s is setting post source content." % caller) self._content_finalized = self._remove_all_stashed_content() return True
[ "def", "set_finalized_content", "(", "self", ",", "content", ",", "caller_class", ")", ":", "caller", "=", "caller_class", ".", "get_name", "(", ")", "if", "hasattr", "(", "caller_class", ",", "'get_name'", ")", "else", "unicode", "(", "caller_class", ")", "if", "not", "FinalizationPlugin", ".", "is_enabled", "(", ")", ":", "logger", ".", "warning", "(", "\"A plugin is trying to modify the post content but the FINALIZE_METADATA setting is \"", "\"disabled. This setting must be enabled for plugins to modify post content. \"", "\"Plugin: %s\"", "%", "caller", ")", "return", "False", "perms", "=", "settings", ".", "PLUGIN_PERMISSIONS", "[", "'MODIFY_RAW_POST'", "]", "if", "caller", "not", "in", "perms", "and", "'*'", "not", "in", "perms", ":", "logger", ".", "warning", "(", "\"A plugin is trying to modify the post content but does not have the \"", "\"MODIFY_RAW_POST permission. Plugin: %s\"", "%", "caller", ")", "return", "False", "else", ":", "logger", ".", "debug", "(", "\"%s is setting post source content.\"", "%", "caller", ")", "self", ".", "_content_finalized", "=", "self", ".", "_remove_all_stashed_content", "(", ")", "return", "True" ]
Plugins can call this method to modify post content that is written back to source post files. This method can be called at any time by anyone, but it has no effect if the caller is not granted the ``MODIFY_RAW_POST`` permission in the Engineer configuration. The :attr:`~engineer.conf.EngineerConfiguration.FINALIZE_METADATA` setting must also be enabled in order for calls to this method to have any effect. :param content: The modified post content that should be written back to the post source file. :param caller_class: The class of the plugin that's calling this method. :return: ``True`` if the content was successfully modified; otherwise ``False``.
[ "Plugins", "can", "call", "this", "method", "to", "modify", "post", "content", "that", "is", "written", "back", "to", "source", "post", "files", ".", "This", "method", "can", "be", "called", "at", "any", "time", "by", "anyone", "but", "it", "has", "no", "effect", "if", "the", "caller", "is", "not", "granted", "the", "MODIFY_RAW_POST", "permission", "in", "the", "Engineer", "configuration", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/models.py#L344-L371
train
tylerbutler/engineer
engineer/models.py
PostCollection.all_tags
def all_tags(self): """Returns a list of all the unique tags, as strings, that posts in the collection have.""" tags = set() for post in self: tags.update(post.tags) return list(tags)
python
def all_tags(self): """Returns a list of all the unique tags, as strings, that posts in the collection have.""" tags = set() for post in self: tags.update(post.tags) return list(tags)
[ "def", "all_tags", "(", "self", ")", ":", "tags", "=", "set", "(", ")", "for", "post", "in", "self", ":", "tags", ".", "update", "(", "post", ".", "tags", ")", "return", "list", "(", "tags", ")" ]
Returns a list of all the unique tags, as strings, that posts in the collection have.
[ "Returns", "a", "list", "of", "all", "the", "unique", "tags", "as", "strings", "that", "posts", "in", "the", "collection", "have", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/models.py#L428-L433
train