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 |
---|---|---|---|---|---|---|---|---|---|---|---|
maximkulkin/hypothesis-regex | hypothesis_regex.py | CharactersBuilder.strategy | def strategy(self):
'Returns resulting strategy that generates configured char set'
max_codepoint = None if self._unicode else 127
strategies = []
if self._negate:
if self._categories or self._whitelist_chars:
strategies.append(
hs.characters(
blacklist_categories=self._categories | set(['Cc', 'Cs']),
blacklist_characters=self._whitelist_chars,
max_codepoint=max_codepoint,
)
)
if self._blacklist_chars:
strategies.append(
hs.sampled_from(
list(self._blacklist_chars - self._whitelist_chars)
)
)
else:
if self._categories or self._blacklist_chars:
strategies.append(
hs.characters(
whitelist_categories=self._categories,
blacklist_characters=self._blacklist_chars,
max_codepoint=max_codepoint,
)
)
if self._whitelist_chars:
strategies.append(
hs.sampled_from(
list(self._whitelist_chars - self._blacklist_chars)
)
)
return hs.one_of(*strategies) if strategies else hs.just(u'') | python | def strategy(self):
'Returns resulting strategy that generates configured char set'
max_codepoint = None if self._unicode else 127
strategies = []
if self._negate:
if self._categories or self._whitelist_chars:
strategies.append(
hs.characters(
blacklist_categories=self._categories | set(['Cc', 'Cs']),
blacklist_characters=self._whitelist_chars,
max_codepoint=max_codepoint,
)
)
if self._blacklist_chars:
strategies.append(
hs.sampled_from(
list(self._blacklist_chars - self._whitelist_chars)
)
)
else:
if self._categories or self._blacklist_chars:
strategies.append(
hs.characters(
whitelist_categories=self._categories,
blacklist_characters=self._blacklist_chars,
max_codepoint=max_codepoint,
)
)
if self._whitelist_chars:
strategies.append(
hs.sampled_from(
list(self._whitelist_chars - self._blacklist_chars)
)
)
return hs.one_of(*strategies) if strategies else hs.just(u'') | [
"def",
"strategy",
"(",
"self",
")",
":",
"max_codepoint",
"=",
"None",
"if",
"self",
".",
"_unicode",
"else",
"127",
"strategies",
"=",
"[",
"]",
"if",
"self",
".",
"_negate",
":",
"if",
"self",
".",
"_categories",
"or",
"self",
".",
"_whitelist_chars",
":",
"strategies",
".",
"append",
"(",
"hs",
".",
"characters",
"(",
"blacklist_categories",
"=",
"self",
".",
"_categories",
"|",
"set",
"(",
"[",
"'Cc'",
",",
"'Cs'",
"]",
")",
",",
"blacklist_characters",
"=",
"self",
".",
"_whitelist_chars",
",",
"max_codepoint",
"=",
"max_codepoint",
",",
")",
")",
"if",
"self",
".",
"_blacklist_chars",
":",
"strategies",
".",
"append",
"(",
"hs",
".",
"sampled_from",
"(",
"list",
"(",
"self",
".",
"_blacklist_chars",
"-",
"self",
".",
"_whitelist_chars",
")",
")",
")",
"else",
":",
"if",
"self",
".",
"_categories",
"or",
"self",
".",
"_blacklist_chars",
":",
"strategies",
".",
"append",
"(",
"hs",
".",
"characters",
"(",
"whitelist_categories",
"=",
"self",
".",
"_categories",
",",
"blacklist_characters",
"=",
"self",
".",
"_blacklist_chars",
",",
"max_codepoint",
"=",
"max_codepoint",
",",
")",
")",
"if",
"self",
".",
"_whitelist_chars",
":",
"strategies",
".",
"append",
"(",
"hs",
".",
"sampled_from",
"(",
"list",
"(",
"self",
".",
"_whitelist_chars",
"-",
"self",
".",
"_blacklist_chars",
")",
")",
")",
"return",
"hs",
".",
"one_of",
"(",
"*",
"strategies",
")",
"if",
"strategies",
"else",
"hs",
".",
"just",
"(",
"u''",
")"
]
| Returns resulting strategy that generates configured char set | [
"Returns",
"resulting",
"strategy",
"that",
"generates",
"configured",
"char",
"set"
]
| dd139e97f5ef555dc61e9636bbe96558a5c7801f | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L63-L99 | train |
maximkulkin/hypothesis-regex | hypothesis_regex.py | CharactersBuilder.add_category | def add_category(self, category):
'''
Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()`
'''
if category == sre.CATEGORY_DIGIT:
self._categories |= UNICODE_DIGIT_CATEGORIES
elif category == sre.CATEGORY_NOT_DIGIT:
self._categories |= UNICODE_CATEGORIES - UNICODE_DIGIT_CATEGORIES
elif category == sre.CATEGORY_SPACE:
self._categories |= UNICODE_SPACE_CATEGORIES
for c in (UNICODE_SPACE_CHARS if self._unicode else SPACE_CHARS):
self._whitelist_chars.add(c)
elif category == sre.CATEGORY_NOT_SPACE:
self._categories |= UNICODE_CATEGORIES - UNICODE_SPACE_CATEGORIES
for c in (UNICODE_SPACE_CHARS if self._unicode else SPACE_CHARS):
self._blacklist_chars.add(c)
elif category == sre.CATEGORY_WORD:
self._categories |= UNICODE_WORD_CATEGORIES
self._whitelist_chars.add(u'_')
if HAS_WEIRD_WORD_CHARS and self._unicode:
for c in UNICODE_WEIRD_NONWORD_CHARS:
self._blacklist_chars.add(c)
elif category == sre.CATEGORY_NOT_WORD:
self._categories |= UNICODE_CATEGORIES - UNICODE_WORD_CATEGORIES
self._blacklist_chars.add(u'_')
if HAS_WEIRD_WORD_CHARS and self._unicode:
for c in UNICODE_WEIRD_NONWORD_CHARS:
self._whitelist_chars.add(c) | python | def add_category(self, category):
'''
Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()`
'''
if category == sre.CATEGORY_DIGIT:
self._categories |= UNICODE_DIGIT_CATEGORIES
elif category == sre.CATEGORY_NOT_DIGIT:
self._categories |= UNICODE_CATEGORIES - UNICODE_DIGIT_CATEGORIES
elif category == sre.CATEGORY_SPACE:
self._categories |= UNICODE_SPACE_CATEGORIES
for c in (UNICODE_SPACE_CHARS if self._unicode else SPACE_CHARS):
self._whitelist_chars.add(c)
elif category == sre.CATEGORY_NOT_SPACE:
self._categories |= UNICODE_CATEGORIES - UNICODE_SPACE_CATEGORIES
for c in (UNICODE_SPACE_CHARS if self._unicode else SPACE_CHARS):
self._blacklist_chars.add(c)
elif category == sre.CATEGORY_WORD:
self._categories |= UNICODE_WORD_CATEGORIES
self._whitelist_chars.add(u'_')
if HAS_WEIRD_WORD_CHARS and self._unicode:
for c in UNICODE_WEIRD_NONWORD_CHARS:
self._blacklist_chars.add(c)
elif category == sre.CATEGORY_NOT_WORD:
self._categories |= UNICODE_CATEGORIES - UNICODE_WORD_CATEGORIES
self._blacklist_chars.add(u'_')
if HAS_WEIRD_WORD_CHARS and self._unicode:
for c in UNICODE_WEIRD_NONWORD_CHARS:
self._whitelist_chars.add(c) | [
"def",
"add_category",
"(",
"self",
",",
"category",
")",
":",
"if",
"category",
"==",
"sre",
".",
"CATEGORY_DIGIT",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_DIGIT_CATEGORIES",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_NOT_DIGIT",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_CATEGORIES",
"-",
"UNICODE_DIGIT_CATEGORIES",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_SPACE",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_SPACE_CATEGORIES",
"for",
"c",
"in",
"(",
"UNICODE_SPACE_CHARS",
"if",
"self",
".",
"_unicode",
"else",
"SPACE_CHARS",
")",
":",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"c",
")",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_NOT_SPACE",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_CATEGORIES",
"-",
"UNICODE_SPACE_CATEGORIES",
"for",
"c",
"in",
"(",
"UNICODE_SPACE_CHARS",
"if",
"self",
".",
"_unicode",
"else",
"SPACE_CHARS",
")",
":",
"self",
".",
"_blacklist_chars",
".",
"add",
"(",
"c",
")",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_WORD",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_WORD_CATEGORIES",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"u'_'",
")",
"if",
"HAS_WEIRD_WORD_CHARS",
"and",
"self",
".",
"_unicode",
":",
"for",
"c",
"in",
"UNICODE_WEIRD_NONWORD_CHARS",
":",
"self",
".",
"_blacklist_chars",
".",
"add",
"(",
"c",
")",
"elif",
"category",
"==",
"sre",
".",
"CATEGORY_NOT_WORD",
":",
"self",
".",
"_categories",
"|=",
"UNICODE_CATEGORIES",
"-",
"UNICODE_WORD_CATEGORIES",
"self",
".",
"_blacklist_chars",
".",
"add",
"(",
"u'_'",
")",
"if",
"HAS_WEIRD_WORD_CHARS",
"and",
"self",
".",
"_unicode",
":",
"for",
"c",
"in",
"UNICODE_WEIRD_NONWORD_CHARS",
":",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"c",
")"
]
| Add unicode category to set
Unicode categories are strings like 'Ll', 'Lu', 'Nd', etc.
See `unicodedata.category()` | [
"Add",
"unicode",
"category",
"to",
"set"
]
| dd139e97f5ef555dc61e9636bbe96558a5c7801f | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L101-L131 | train |
maximkulkin/hypothesis-regex | hypothesis_regex.py | CharactersBuilder.add_chars | def add_chars(self, chars):
'Add given chars to char set'
for c in chars:
if self._ignorecase:
self._whitelist_chars.add(c.lower())
self._whitelist_chars.add(c.upper())
else:
self._whitelist_chars.add(c) | python | def add_chars(self, chars):
'Add given chars to char set'
for c in chars:
if self._ignorecase:
self._whitelist_chars.add(c.lower())
self._whitelist_chars.add(c.upper())
else:
self._whitelist_chars.add(c) | [
"def",
"add_chars",
"(",
"self",
",",
"chars",
")",
":",
"for",
"c",
"in",
"chars",
":",
"if",
"self",
".",
"_ignorecase",
":",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"c",
".",
"lower",
"(",
")",
")",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"c",
".",
"upper",
"(",
")",
")",
"else",
":",
"self",
".",
"_whitelist_chars",
".",
"add",
"(",
"c",
")"
]
| Add given chars to char set | [
"Add",
"given",
"chars",
"to",
"char",
"set"
]
| dd139e97f5ef555dc61e9636bbe96558a5c7801f | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L133-L140 | train |
jeffh/describe | describe/spec/utils.py | str_traceback | def str_traceback(error, tb):
"""Returns a string representation of the traceback.
"""
if not isinstance(tb, types.TracebackType):
return tb
return ''.join(traceback.format_exception(error.__class__, error, tb)) | python | def str_traceback(error, tb):
"""Returns a string representation of the traceback.
"""
if not isinstance(tb, types.TracebackType):
return tb
return ''.join(traceback.format_exception(error.__class__, error, tb)) | [
"def",
"str_traceback",
"(",
"error",
",",
"tb",
")",
":",
"if",
"not",
"isinstance",
"(",
"tb",
",",
"types",
".",
"TracebackType",
")",
":",
"return",
"tb",
"return",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"error",
".",
"__class__",
",",
"error",
",",
"tb",
")",
")"
]
| Returns a string representation of the traceback. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"traceback",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L9-L15 | train |
jeffh/describe | describe/spec/utils.py | filter_traceback | def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE):
"""Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals.
"""
if not isinstance(tb, types.TracebackType):
return tb
def in_namespace(n):
return n and (n.startswith(ignore_pkg + '.') or n == ignore_pkg)
# Skip test runner traceback levels
while tb and in_namespace(tb.tb_frame.f_globals['__package__']):
tb = tb.tb_next
starting_tb = tb
limit = 0
while tb and not in_namespace(tb.tb_frame.f_globals['__package__']):
tb = tb.tb_next
limit += 1
return ''.join(traceback.format_exception(error.__class__, error, starting_tb, limit)) | python | def filter_traceback(error, tb, ignore_pkg=CURRENT_PACKAGE):
"""Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals.
"""
if not isinstance(tb, types.TracebackType):
return tb
def in_namespace(n):
return n and (n.startswith(ignore_pkg + '.') or n == ignore_pkg)
# Skip test runner traceback levels
while tb and in_namespace(tb.tb_frame.f_globals['__package__']):
tb = tb.tb_next
starting_tb = tb
limit = 0
while tb and not in_namespace(tb.tb_frame.f_globals['__package__']):
tb = tb.tb_next
limit += 1
return ''.join(traceback.format_exception(error.__class__, error, starting_tb, limit)) | [
"def",
"filter_traceback",
"(",
"error",
",",
"tb",
",",
"ignore_pkg",
"=",
"CURRENT_PACKAGE",
")",
":",
"if",
"not",
"isinstance",
"(",
"tb",
",",
"types",
".",
"TracebackType",
")",
":",
"return",
"tb",
"def",
"in_namespace",
"(",
"n",
")",
":",
"return",
"n",
"and",
"(",
"n",
".",
"startswith",
"(",
"ignore_pkg",
"+",
"'.'",
")",
"or",
"n",
"==",
"ignore_pkg",
")",
"# Skip test runner traceback levels",
"while",
"tb",
"and",
"in_namespace",
"(",
"tb",
".",
"tb_frame",
".",
"f_globals",
"[",
"'__package__'",
"]",
")",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"starting_tb",
"=",
"tb",
"limit",
"=",
"0",
"while",
"tb",
"and",
"not",
"in_namespace",
"(",
"tb",
".",
"tb_frame",
".",
"f_globals",
"[",
"'__package__'",
"]",
")",
":",
"tb",
"=",
"tb",
".",
"tb_next",
"limit",
"+=",
"1",
"return",
"''",
".",
"join",
"(",
"traceback",
".",
"format_exception",
"(",
"error",
".",
"__class__",
",",
"error",
",",
"starting_tb",
",",
"limit",
")",
")"
]
| Filtered out all parent stacktraces starting with the given stacktrace that has
a given variable name in its globals. | [
"Filtered",
"out",
"all",
"parent",
"stacktraces",
"starting",
"with",
"the",
"given",
"stacktrace",
"that",
"has",
"a",
"given",
"variable",
"name",
"in",
"its",
"globals",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L17-L35 | train |
jeffh/describe | describe/spec/utils.py | get_true_function | def get_true_function(obj):
"Returns the actual function and a boolean indicated if this is a method or not."
if not callable(obj):
raise TypeError("%r is not callable." % (obj,))
ismethod = inspect.ismethod(obj)
if inspect.isfunction(obj) or ismethod:
return obj, ismethod
if hasattr(obj, 'im_func'):
return obj.im_func, True
if inspect.isclass(obj):
return getattr(obj, '__init__', None), True
if isinstance(obj, object):
if hasattr(obj, 'func'):
return get_true_function(obj.func)
return obj.__call__, True
raise TypeError("Unknown type of object: %r" % obj) | python | def get_true_function(obj):
"Returns the actual function and a boolean indicated if this is a method or not."
if not callable(obj):
raise TypeError("%r is not callable." % (obj,))
ismethod = inspect.ismethod(obj)
if inspect.isfunction(obj) or ismethod:
return obj, ismethod
if hasattr(obj, 'im_func'):
return obj.im_func, True
if inspect.isclass(obj):
return getattr(obj, '__init__', None), True
if isinstance(obj, object):
if hasattr(obj, 'func'):
return get_true_function(obj.func)
return obj.__call__, True
raise TypeError("Unknown type of object: %r" % obj) | [
"def",
"get_true_function",
"(",
"obj",
")",
":",
"if",
"not",
"callable",
"(",
"obj",
")",
":",
"raise",
"TypeError",
"(",
"\"%r is not callable.\"",
"%",
"(",
"obj",
",",
")",
")",
"ismethod",
"=",
"inspect",
".",
"ismethod",
"(",
"obj",
")",
"if",
"inspect",
".",
"isfunction",
"(",
"obj",
")",
"or",
"ismethod",
":",
"return",
"obj",
",",
"ismethod",
"if",
"hasattr",
"(",
"obj",
",",
"'im_func'",
")",
":",
"return",
"obj",
".",
"im_func",
",",
"True",
"if",
"inspect",
".",
"isclass",
"(",
"obj",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"'__init__'",
",",
"None",
")",
",",
"True",
"if",
"isinstance",
"(",
"obj",
",",
"object",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'func'",
")",
":",
"return",
"get_true_function",
"(",
"obj",
".",
"func",
")",
"return",
"obj",
".",
"__call__",
",",
"True",
"raise",
"TypeError",
"(",
"\"Unknown type of object: %r\"",
"%",
"obj",
")"
]
| Returns the actual function and a boolean indicated if this is a method or not. | [
"Returns",
"the",
"actual",
"function",
"and",
"a",
"boolean",
"indicated",
"if",
"this",
"is",
"a",
"method",
"or",
"not",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/spec/utils.py#L151-L166 | train |
adamziel/python_translate | python_translate/loaders.py | FileMixin.assert_valid_path | def assert_valid_path(self, path):
"""
Ensures that the path represents an existing file
@type path: str
@param path: path to check
"""
if not isinstance(path, str):
raise NotFoundResourceException(
"Resource passed to load() method must be a file path")
if not os.path.isfile(path):
raise NotFoundResourceException(
'File "{0}" does not exist'.format(path)) | python | def assert_valid_path(self, path):
"""
Ensures that the path represents an existing file
@type path: str
@param path: path to check
"""
if not isinstance(path, str):
raise NotFoundResourceException(
"Resource passed to load() method must be a file path")
if not os.path.isfile(path):
raise NotFoundResourceException(
'File "{0}" does not exist'.format(path)) | [
"def",
"assert_valid_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"raise",
"NotFoundResourceException",
"(",
"\"Resource passed to load() method must be a file path\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"raise",
"NotFoundResourceException",
"(",
"'File \"{0}\" does not exist'",
".",
"format",
"(",
"path",
")",
")"
]
| Ensures that the path represents an existing file
@type path: str
@param path: path to check | [
"Ensures",
"that",
"the",
"path",
"represents",
"an",
"existing",
"file"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L63-L77 | train |
adamziel/python_translate | python_translate/loaders.py | FileMixin.read_file | def read_file(self, path):
"""
Reads a file into memory and returns it's contents
@type path: str
@param path: path to load
"""
self.assert_valid_path(path)
with open(path, 'rb') as file:
contents = file.read().decode('UTF-8')
return contents | python | def read_file(self, path):
"""
Reads a file into memory and returns it's contents
@type path: str
@param path: path to load
"""
self.assert_valid_path(path)
with open(path, 'rb') as file:
contents = file.read().decode('UTF-8')
return contents | [
"def",
"read_file",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"assert_valid_path",
"(",
"path",
")",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file",
":",
"contents",
"=",
"file",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
"return",
"contents"
]
| Reads a file into memory and returns it's contents
@type path: str
@param path: path to load | [
"Reads",
"a",
"file",
"into",
"memory",
"and",
"returns",
"it",
"s",
"contents"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L79-L92 | train |
adamziel/python_translate | python_translate/loaders.py | DictLoader.flatten | def flatten(self, messages, parent_key=''):
"""
Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
@type messages: dict
@param messages: The dict that will be flattened
@type parent_key: str
@param parent_key: Current path being parsed, used internally for recursive calls
"""
items = []
sep = '.'
for k, v in list(messages.items()):
new_key = "{0}{1}{2}".format(parent_key, sep, k) if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(list(self.flatten(v, new_key).items()))
else:
items.append((new_key, v))
return dict(items) | python | def flatten(self, messages, parent_key=''):
"""
Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
@type messages: dict
@param messages: The dict that will be flattened
@type parent_key: str
@param parent_key: Current path being parsed, used internally for recursive calls
"""
items = []
sep = '.'
for k, v in list(messages.items()):
new_key = "{0}{1}{2}".format(parent_key, sep, k) if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(list(self.flatten(v, new_key).items()))
else:
items.append((new_key, v))
return dict(items) | [
"def",
"flatten",
"(",
"self",
",",
"messages",
",",
"parent_key",
"=",
"''",
")",
":",
"items",
"=",
"[",
"]",
"sep",
"=",
"'.'",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"messages",
".",
"items",
"(",
")",
")",
":",
"new_key",
"=",
"\"{0}{1}{2}\"",
".",
"format",
"(",
"parent_key",
",",
"sep",
",",
"k",
")",
"if",
"parent_key",
"else",
"k",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"MutableMapping",
")",
":",
"items",
".",
"extend",
"(",
"list",
"(",
"self",
".",
"flatten",
"(",
"v",
",",
"new_key",
")",
".",
"items",
"(",
")",
")",
")",
"else",
":",
"items",
".",
"append",
"(",
"(",
"new_key",
",",
"v",
")",
")",
"return",
"dict",
"(",
"items",
")"
]
| Flattens an nested array of translations.
The scheme used is:
'key' => array('key2' => array('key3' => 'value'))
Becomes:
'key.key2.key3' => 'value'
This function takes an array by reference and will modify it
@type messages: dict
@param messages: The dict that will be flattened
@type parent_key: str
@param parent_key: Current path being parsed, used internally for recursive calls | [
"Flattens",
"an",
"nested",
"array",
"of",
"translations",
"."
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L127-L152 | train |
adamziel/python_translate | python_translate/loaders.py | PoFileLoader.parse | def parse(self, resource):
"""
Loads given resource into a dict using polib
@type resource: str
@param resource: resource
@rtype: list
"""
try:
import polib
except ImportError as e:
self.rethrow(
"You need to install polib to use PoFileLoader or MoFileLoader",
ImportError)
self.assert_valid_path(resource)
messages = {}
parsed = self._load_contents(polib, resource)
for item in parsed:
if item.msgid_plural:
plurals = sorted(item.msgstr_plural.items())
if item.msgid and len(plurals) > 1:
messages[item.msgid] = plurals[0][1]
plurals = [msgstr for idx, msgstr in plurals]
messages[item.msgid_plural] = "|".join(plurals)
elif item.msgid:
messages[item.msgid] = item.msgstr
return messages | python | def parse(self, resource):
"""
Loads given resource into a dict using polib
@type resource: str
@param resource: resource
@rtype: list
"""
try:
import polib
except ImportError as e:
self.rethrow(
"You need to install polib to use PoFileLoader or MoFileLoader",
ImportError)
self.assert_valid_path(resource)
messages = {}
parsed = self._load_contents(polib, resource)
for item in parsed:
if item.msgid_plural:
plurals = sorted(item.msgstr_plural.items())
if item.msgid and len(plurals) > 1:
messages[item.msgid] = plurals[0][1]
plurals = [msgstr for idx, msgstr in plurals]
messages[item.msgid_plural] = "|".join(plurals)
elif item.msgid:
messages[item.msgid] = item.msgstr
return messages | [
"def",
"parse",
"(",
"self",
",",
"resource",
")",
":",
"try",
":",
"import",
"polib",
"except",
"ImportError",
"as",
"e",
":",
"self",
".",
"rethrow",
"(",
"\"You need to install polib to use PoFileLoader or MoFileLoader\"",
",",
"ImportError",
")",
"self",
".",
"assert_valid_path",
"(",
"resource",
")",
"messages",
"=",
"{",
"}",
"parsed",
"=",
"self",
".",
"_load_contents",
"(",
"polib",
",",
"resource",
")",
"for",
"item",
"in",
"parsed",
":",
"if",
"item",
".",
"msgid_plural",
":",
"plurals",
"=",
"sorted",
"(",
"item",
".",
"msgstr_plural",
".",
"items",
"(",
")",
")",
"if",
"item",
".",
"msgid",
"and",
"len",
"(",
"plurals",
")",
">",
"1",
":",
"messages",
"[",
"item",
".",
"msgid",
"]",
"=",
"plurals",
"[",
"0",
"]",
"[",
"1",
"]",
"plurals",
"=",
"[",
"msgstr",
"for",
"idx",
",",
"msgstr",
"in",
"plurals",
"]",
"messages",
"[",
"item",
".",
"msgid_plural",
"]",
"=",
"\"|\"",
".",
"join",
"(",
"plurals",
")",
"elif",
"item",
".",
"msgid",
":",
"messages",
"[",
"item",
".",
"msgid",
"]",
"=",
"item",
".",
"msgstr",
"return",
"messages"
]
| Loads given resource into a dict using polib
@type resource: str
@param resource: resource
@rtype: list | [
"Loads",
"given",
"resource",
"into",
"a",
"dict",
"using",
"polib"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/loaders.py#L219-L250 | train |
ktdreyer/txkoji | txkoji/task.py | Task.arch | def arch(self):
"""
Return an architecture for this task.
:returns: an arch string (eg "noarch", or "ppc64le"), or None this task
has no architecture associated with it.
"""
if self.method in ('buildArch', 'createdistrepo', 'livecd'):
return self.params[2]
if self.method in ('createrepo', 'runroot'):
return self.params[1]
if self.method == 'createImage':
return self.params[3]
if self.method == 'indirectionimage':
return self.params[0]['arch'] | python | def arch(self):
"""
Return an architecture for this task.
:returns: an arch string (eg "noarch", or "ppc64le"), or None this task
has no architecture associated with it.
"""
if self.method in ('buildArch', 'createdistrepo', 'livecd'):
return self.params[2]
if self.method in ('createrepo', 'runroot'):
return self.params[1]
if self.method == 'createImage':
return self.params[3]
if self.method == 'indirectionimage':
return self.params[0]['arch'] | [
"def",
"arch",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"in",
"(",
"'buildArch'",
",",
"'createdistrepo'",
",",
"'livecd'",
")",
":",
"return",
"self",
".",
"params",
"[",
"2",
"]",
"if",
"self",
".",
"method",
"in",
"(",
"'createrepo'",
",",
"'runroot'",
")",
":",
"return",
"self",
".",
"params",
"[",
"1",
"]",
"if",
"self",
".",
"method",
"==",
"'createImage'",
":",
"return",
"self",
".",
"params",
"[",
"3",
"]",
"if",
"self",
".",
"method",
"==",
"'indirectionimage'",
":",
"return",
"self",
".",
"params",
"[",
"0",
"]",
"[",
"'arch'",
"]"
]
| Return an architecture for this task.
:returns: an arch string (eg "noarch", or "ppc64le"), or None this task
has no architecture associated with it. | [
"Return",
"an",
"architecture",
"for",
"this",
"task",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L28-L42 | train |
ktdreyer/txkoji | txkoji/task.py | Task.arches | def arches(self):
"""
Return a list of architectures for this task.
:returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list
is empty if this task has no arches associated with it.
"""
if self.method == 'image':
return self.params[2]
if self.arch:
return [self.arch]
return [] | python | def arches(self):
"""
Return a list of architectures for this task.
:returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list
is empty if this task has no arches associated with it.
"""
if self.method == 'image':
return self.params[2]
if self.arch:
return [self.arch]
return [] | [
"def",
"arches",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"'image'",
":",
"return",
"self",
".",
"params",
"[",
"2",
"]",
"if",
"self",
".",
"arch",
":",
"return",
"[",
"self",
".",
"arch",
"]",
"return",
"[",
"]"
]
| Return a list of architectures for this task.
:returns: a list of arch strings (eg ["ppc64le", "x86_64"]). The list
is empty if this task has no arches associated with it. | [
"Return",
"a",
"list",
"of",
"architectures",
"for",
"this",
"task",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L45-L56 | train |
ktdreyer/txkoji | txkoji/task.py | Task.duration | def duration(self):
"""
Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started.
"""
if not self.started:
return None
start = self.started
end = self.completed
if not end:
end = datetime.utcnow()
return end - start | python | def duration(self):
"""
Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started.
"""
if not self.started:
return None
start = self.started
end = self.completed
if not end:
end = datetime.utcnow()
return end - start | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"return",
"None",
"start",
"=",
"self",
".",
"started",
"end",
"=",
"self",
".",
"completed",
"if",
"not",
"end",
":",
"end",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"end",
"-",
"start"
]
| Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started. | [
"Return",
"a",
"timedelta",
"for",
"this",
"task",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L127-L142 | train |
ktdreyer/txkoji | txkoji/task.py | Task.estimate_completion | def estimate_completion(self):
"""
Estimate completion time for a task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
if self.completion_ts:
# Task is already complete. Return the exact completion time:
defer.returnValue(self.completed)
# Get the timestamps from the descendent task that's doing the work:
if self.method == 'build' or self.method == 'image':
subtask_completion = yield self.estimate_descendents()
defer.returnValue(subtask_completion)
if self.state == task_states.FREE:
est_completion = yield self._estimate_free()
defer.returnValue(est_completion)
avg_delta = yield self.estimate_duration()
if avg_delta is None:
defer.returnValue(None)
est_completion = self.started + avg_delta
defer.returnValue(est_completion) | python | def estimate_completion(self):
"""
Estimate completion time for a task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
if self.completion_ts:
# Task is already complete. Return the exact completion time:
defer.returnValue(self.completed)
# Get the timestamps from the descendent task that's doing the work:
if self.method == 'build' or self.method == 'image':
subtask_completion = yield self.estimate_descendents()
defer.returnValue(subtask_completion)
if self.state == task_states.FREE:
est_completion = yield self._estimate_free()
defer.returnValue(est_completion)
avg_delta = yield self.estimate_duration()
if avg_delta is None:
defer.returnValue(None)
est_completion = self.started + avg_delta
defer.returnValue(est_completion) | [
"def",
"estimate_completion",
"(",
"self",
")",
":",
"if",
"self",
".",
"completion_ts",
":",
"# Task is already complete. Return the exact completion time:",
"defer",
".",
"returnValue",
"(",
"self",
".",
"completed",
")",
"# Get the timestamps from the descendent task that's doing the work:",
"if",
"self",
".",
"method",
"==",
"'build'",
"or",
"self",
".",
"method",
"==",
"'image'",
":",
"subtask_completion",
"=",
"yield",
"self",
".",
"estimate_descendents",
"(",
")",
"defer",
".",
"returnValue",
"(",
"subtask_completion",
")",
"if",
"self",
".",
"state",
"==",
"task_states",
".",
"FREE",
":",
"est_completion",
"=",
"yield",
"self",
".",
"_estimate_free",
"(",
")",
"defer",
".",
"returnValue",
"(",
"est_completion",
")",
"avg_delta",
"=",
"yield",
"self",
".",
"estimate_duration",
"(",
")",
"if",
"avg_delta",
"is",
"None",
":",
"defer",
".",
"returnValue",
"(",
"None",
")",
"est_completion",
"=",
"self",
".",
"started",
"+",
"avg_delta",
"defer",
".",
"returnValue",
"(",
"est_completion",
")"
]
| Estimate completion time for a task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method. | [
"Estimate",
"completion",
"time",
"for",
"a",
"task",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L145-L167 | train |
ktdreyer/txkoji | txkoji/task.py | Task._estimate_free | def _estimate_free(self):
"""
Estimate completion time for a free task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
# Query the information we need for this task's channel and package.
capacity_deferred = self.channel.total_capacity()
open_tasks_deferred = self.channel.tasks(state=[task_states.OPEN])
avg_delta_deferred = self.estimate_duration()
deferreds = [capacity_deferred,
open_tasks_deferred,
avg_delta_deferred]
results = yield defer.gatherResults(deferreds, consumeErrors=True)
capacity, open_tasks, avg_delta = results
# Ensure this task's channel has spare capacity for this task.
open_weight = sum([task.weight for task in open_tasks])
if open_weight >= capacity:
# TODO: Evaluate all tasks in the channel and
# determine when enough OPEN tasks will complete so that we can
# get to OPEN.
raise NotImplementedError('channel %d is at capacity' %
self.channel_id)
# A builder will pick up this task and start it within SLEEPTIME.
# start_time is the maximum amount of time we expect to wait here.
start_time = self.created + SLEEPTIME
if avg_delta is None:
defer.returnValue(None)
est_completion = start_time + avg_delta
defer.returnValue(est_completion) | python | def _estimate_free(self):
"""
Estimate completion time for a free task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method.
"""
# Query the information we need for this task's channel and package.
capacity_deferred = self.channel.total_capacity()
open_tasks_deferred = self.channel.tasks(state=[task_states.OPEN])
avg_delta_deferred = self.estimate_duration()
deferreds = [capacity_deferred,
open_tasks_deferred,
avg_delta_deferred]
results = yield defer.gatherResults(deferreds, consumeErrors=True)
capacity, open_tasks, avg_delta = results
# Ensure this task's channel has spare capacity for this task.
open_weight = sum([task.weight for task in open_tasks])
if open_weight >= capacity:
# TODO: Evaluate all tasks in the channel and
# determine when enough OPEN tasks will complete so that we can
# get to OPEN.
raise NotImplementedError('channel %d is at capacity' %
self.channel_id)
# A builder will pick up this task and start it within SLEEPTIME.
# start_time is the maximum amount of time we expect to wait here.
start_time = self.created + SLEEPTIME
if avg_delta is None:
defer.returnValue(None)
est_completion = start_time + avg_delta
defer.returnValue(est_completion) | [
"def",
"_estimate_free",
"(",
"self",
")",
":",
"# Query the information we need for this task's channel and package.",
"capacity_deferred",
"=",
"self",
".",
"channel",
".",
"total_capacity",
"(",
")",
"open_tasks_deferred",
"=",
"self",
".",
"channel",
".",
"tasks",
"(",
"state",
"=",
"[",
"task_states",
".",
"OPEN",
"]",
")",
"avg_delta_deferred",
"=",
"self",
".",
"estimate_duration",
"(",
")",
"deferreds",
"=",
"[",
"capacity_deferred",
",",
"open_tasks_deferred",
",",
"avg_delta_deferred",
"]",
"results",
"=",
"yield",
"defer",
".",
"gatherResults",
"(",
"deferreds",
",",
"consumeErrors",
"=",
"True",
")",
"capacity",
",",
"open_tasks",
",",
"avg_delta",
"=",
"results",
"# Ensure this task's channel has spare capacity for this task.",
"open_weight",
"=",
"sum",
"(",
"[",
"task",
".",
"weight",
"for",
"task",
"in",
"open_tasks",
"]",
")",
"if",
"open_weight",
">=",
"capacity",
":",
"# TODO: Evaluate all tasks in the channel and",
"# determine when enough OPEN tasks will complete so that we can",
"# get to OPEN.",
"raise",
"NotImplementedError",
"(",
"'channel %d is at capacity'",
"%",
"self",
".",
"channel_id",
")",
"# A builder will pick up this task and start it within SLEEPTIME.",
"# start_time is the maximum amount of time we expect to wait here.",
"start_time",
"=",
"self",
".",
"created",
"+",
"SLEEPTIME",
"if",
"avg_delta",
"is",
"None",
":",
"defer",
".",
"returnValue",
"(",
"None",
")",
"est_completion",
"=",
"start_time",
"+",
"avg_delta",
"defer",
".",
"returnValue",
"(",
"est_completion",
")"
]
| Estimate completion time for a free task.
:returns: deferred that when fired returns a datetime object for the
estimated, or the actual datetime, or None if we could not
estimate a time for this task method. | [
"Estimate",
"completion",
"time",
"for",
"a",
"free",
"task",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L197-L228 | train |
ktdreyer/txkoji | txkoji/task.py | Task.package | def package(self):
"""
Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params.
"""
if self.method == 'buildNotification':
return self.params[1]['name']
if self.method in ('createImage', 'image', 'livecd'):
return self.params[0]
if self.method == 'indirectionimage':
return self.params[0]['name']
# params[0] is the source URL for these tasks:
if self.method not in ('build', 'buildArch', 'buildContainer',
'buildMaven', 'buildSRPMFromSCM', 'maven'):
return None
# (I wish there was a better way to do this.)
source = self.params[0]
o = urlparse(source)
# build tasks can load an SRPM from a "cli-build" tmpdir:
if source.endswith('.src.rpm'):
srpm = os.path.basename(source)
(name, version, release) = srpm.rsplit('-', 2)
# Note we're throwing away version and release here. They could be
# useful eventually, maybe in a "Package" class.
return name
# or an allowed SCM:
elif o.scheme:
package = os.path.basename(o.path)
if package.endswith('.git'):
package = package[:-4]
if self.method == 'buildContainer':
package += '-container'
return package
raise ValueError('could not parse source "%s"' % source) | python | def package(self):
"""
Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params.
"""
if self.method == 'buildNotification':
return self.params[1]['name']
if self.method in ('createImage', 'image', 'livecd'):
return self.params[0]
if self.method == 'indirectionimage':
return self.params[0]['name']
# params[0] is the source URL for these tasks:
if self.method not in ('build', 'buildArch', 'buildContainer',
'buildMaven', 'buildSRPMFromSCM', 'maven'):
return None
# (I wish there was a better way to do this.)
source = self.params[0]
o = urlparse(source)
# build tasks can load an SRPM from a "cli-build" tmpdir:
if source.endswith('.src.rpm'):
srpm = os.path.basename(source)
(name, version, release) = srpm.rsplit('-', 2)
# Note we're throwing away version and release here. They could be
# useful eventually, maybe in a "Package" class.
return name
# or an allowed SCM:
elif o.scheme:
package = os.path.basename(o.path)
if package.endswith('.git'):
package = package[:-4]
if self.method == 'buildContainer':
package += '-container'
return package
raise ValueError('could not parse source "%s"' % source) | [
"def",
"package",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"'buildNotification'",
":",
"return",
"self",
".",
"params",
"[",
"1",
"]",
"[",
"'name'",
"]",
"if",
"self",
".",
"method",
"in",
"(",
"'createImage'",
",",
"'image'",
",",
"'livecd'",
")",
":",
"return",
"self",
".",
"params",
"[",
"0",
"]",
"if",
"self",
".",
"method",
"==",
"'indirectionimage'",
":",
"return",
"self",
".",
"params",
"[",
"0",
"]",
"[",
"'name'",
"]",
"# params[0] is the source URL for these tasks:",
"if",
"self",
".",
"method",
"not",
"in",
"(",
"'build'",
",",
"'buildArch'",
",",
"'buildContainer'",
",",
"'buildMaven'",
",",
"'buildSRPMFromSCM'",
",",
"'maven'",
")",
":",
"return",
"None",
"# (I wish there was a better way to do this.)",
"source",
"=",
"self",
".",
"params",
"[",
"0",
"]",
"o",
"=",
"urlparse",
"(",
"source",
")",
"# build tasks can load an SRPM from a \"cli-build\" tmpdir:",
"if",
"source",
".",
"endswith",
"(",
"'.src.rpm'",
")",
":",
"srpm",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"source",
")",
"(",
"name",
",",
"version",
",",
"release",
")",
"=",
"srpm",
".",
"rsplit",
"(",
"'-'",
",",
"2",
")",
"# Note we're throwing away version and release here. They could be",
"# useful eventually, maybe in a \"Package\" class.",
"return",
"name",
"# or an allowed SCM:",
"elif",
"o",
".",
"scheme",
":",
"package",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"o",
".",
"path",
")",
"if",
"package",
".",
"endswith",
"(",
"'.git'",
")",
":",
"package",
"=",
"package",
"[",
":",
"-",
"4",
"]",
"if",
"self",
".",
"method",
"==",
"'buildContainer'",
":",
"package",
"+=",
"'-container'",
"return",
"package",
"raise",
"ValueError",
"(",
"'could not parse source \"%s\"'",
"%",
"source",
")"
]
| Find a package name from a build task's parameters.
:returns: name of the package this build task is building.
:raises: ValueError if we could not parse this tasks's request params. | [
"Find",
"a",
"package",
"name",
"from",
"a",
"build",
"task",
"s",
"parameters",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L290-L325 | train |
ktdreyer/txkoji | txkoji/task.py | Task.params | def params(self):
"""
Return a list of parameters in this task's request.
If self.request is already a list, simply return it.
If self.request is a raw XML-RPC string, parse it and return the
params.
"""
if isinstance(self.request, list):
return unmunchify(self.request)
(params, _) = xmlrpc.loads(self.request)
return params | python | def params(self):
"""
Return a list of parameters in this task's request.
If self.request is already a list, simply return it.
If self.request is a raw XML-RPC string, parse it and return the
params.
"""
if isinstance(self.request, list):
return unmunchify(self.request)
(params, _) = xmlrpc.loads(self.request)
return params | [
"def",
"params",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"request",
",",
"list",
")",
":",
"return",
"unmunchify",
"(",
"self",
".",
"request",
")",
"(",
"params",
",",
"_",
")",
"=",
"xmlrpc",
".",
"loads",
"(",
"self",
".",
"request",
")",
"return",
"params"
]
| Return a list of parameters in this task's request.
If self.request is already a list, simply return it.
If self.request is a raw XML-RPC string, parse it and return the
params. | [
"Return",
"a",
"list",
"of",
"parameters",
"in",
"this",
"task",
"s",
"request",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task.py#L328-L340 | train |
tjcsl/cslbot | cslbot/commands/pull.py | cmd | def cmd(send, _, args):
"""Pull changes.
Syntax: {command} <branch>
"""
try:
if exists(join(args['handler'].confdir, '.git')):
send(do_pull(srcdir=args['handler'].confdir))
else:
send(do_pull(repo=args['config']['api']['githubrepo']))
except subprocess.CalledProcessError as ex:
for line in ex.output.strip().splitlines():
logging.error(line)
raise ex | python | def cmd(send, _, args):
"""Pull changes.
Syntax: {command} <branch>
"""
try:
if exists(join(args['handler'].confdir, '.git')):
send(do_pull(srcdir=args['handler'].confdir))
else:
send(do_pull(repo=args['config']['api']['githubrepo']))
except subprocess.CalledProcessError as ex:
for line in ex.output.strip().splitlines():
logging.error(line)
raise ex | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"try",
":",
"if",
"exists",
"(",
"join",
"(",
"args",
"[",
"'handler'",
"]",
".",
"confdir",
",",
"'.git'",
")",
")",
":",
"send",
"(",
"do_pull",
"(",
"srcdir",
"=",
"args",
"[",
"'handler'",
"]",
".",
"confdir",
")",
")",
"else",
":",
"send",
"(",
"do_pull",
"(",
"repo",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'githubrepo'",
"]",
")",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"ex",
":",
"for",
"line",
"in",
"ex",
".",
"output",
".",
"strip",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"logging",
".",
"error",
"(",
"line",
")",
"raise",
"ex"
]
| Pull changes.
Syntax: {command} <branch> | [
"Pull",
"changes",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/pull.py#L27-L41 | train |
reichlab/pymmwr | pymmwr.py | _start_date_of_year | def _start_date_of_year(year: int) -> datetime.date:
"""
Return start date of the year using MMWR week rules
"""
jan_one = datetime.date(year, 1, 1)
diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday()
return jan_one + datetime.timedelta(days=diff) | python | def _start_date_of_year(year: int) -> datetime.date:
"""
Return start date of the year using MMWR week rules
"""
jan_one = datetime.date(year, 1, 1)
diff = 7 * (jan_one.isoweekday() > 3) - jan_one.isoweekday()
return jan_one + datetime.timedelta(days=diff) | [
"def",
"_start_date_of_year",
"(",
"year",
":",
"int",
")",
"->",
"datetime",
".",
"date",
":",
"jan_one",
"=",
"datetime",
".",
"date",
"(",
"year",
",",
"1",
",",
"1",
")",
"diff",
"=",
"7",
"*",
"(",
"jan_one",
".",
"isoweekday",
"(",
")",
">",
"3",
")",
"-",
"jan_one",
".",
"isoweekday",
"(",
")",
"return",
"jan_one",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"diff",
")"
]
| Return start date of the year using MMWR week rules | [
"Return",
"start",
"date",
"of",
"the",
"year",
"using",
"MMWR",
"week",
"rules"
]
| 98216bd5081998ca63db89003c4ef397fe905755 | https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L40-L48 | train |
reichlab/pymmwr | pymmwr.py | date_to_epiweek | def date_to_epiweek(date=datetime.date.today()) -> Epiweek:
"""
Convert python date to Epiweek
"""
year = date.year
start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1]))
start_date = start_dates[1]
if start_dates[1] > date:
start_date = start_dates[0]
elif date >= start_dates[2]:
start_date = start_dates[2]
return Epiweek(
year=(start_date + datetime.timedelta(days=7)).year,
week=((date - start_date).days // 7) + 1,
day=(date.isoweekday() % 7) + 1
) | python | def date_to_epiweek(date=datetime.date.today()) -> Epiweek:
"""
Convert python date to Epiweek
"""
year = date.year
start_dates = list(map(_start_date_of_year, [year - 1, year, year + 1]))
start_date = start_dates[1]
if start_dates[1] > date:
start_date = start_dates[0]
elif date >= start_dates[2]:
start_date = start_dates[2]
return Epiweek(
year=(start_date + datetime.timedelta(days=7)).year,
week=((date - start_date).days // 7) + 1,
day=(date.isoweekday() % 7) + 1
) | [
"def",
"date_to_epiweek",
"(",
"date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"->",
"Epiweek",
":",
"year",
"=",
"date",
".",
"year",
"start_dates",
"=",
"list",
"(",
"map",
"(",
"_start_date_of_year",
",",
"[",
"year",
"-",
"1",
",",
"year",
",",
"year",
"+",
"1",
"]",
")",
")",
"start_date",
"=",
"start_dates",
"[",
"1",
"]",
"if",
"start_dates",
"[",
"1",
"]",
">",
"date",
":",
"start_date",
"=",
"start_dates",
"[",
"0",
"]",
"elif",
"date",
">=",
"start_dates",
"[",
"2",
"]",
":",
"start_date",
"=",
"start_dates",
"[",
"2",
"]",
"return",
"Epiweek",
"(",
"year",
"=",
"(",
"start_date",
"+",
"datetime",
".",
"timedelta",
"(",
"days",
"=",
"7",
")",
")",
".",
"year",
",",
"week",
"=",
"(",
"(",
"date",
"-",
"start_date",
")",
".",
"days",
"//",
"7",
")",
"+",
"1",
",",
"day",
"=",
"(",
"date",
".",
"isoweekday",
"(",
")",
"%",
"7",
")",
"+",
"1",
")"
]
| Convert python date to Epiweek | [
"Convert",
"python",
"date",
"to",
"Epiweek"
]
| 98216bd5081998ca63db89003c4ef397fe905755 | https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L62-L80 | train |
reichlab/pymmwr | pymmwr.py | epiweeks_in_year | def epiweeks_in_year(year: int) -> int:
"""
Return number of epiweeks in a year
"""
if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year:
return 53
else:
return 52 | python | def epiweeks_in_year(year: int) -> int:
"""
Return number of epiweeks in a year
"""
if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year:
return 53
else:
return 52 | [
"def",
"epiweeks_in_year",
"(",
"year",
":",
"int",
")",
"->",
"int",
":",
"if",
"date_to_epiweek",
"(",
"epiweek_to_date",
"(",
"Epiweek",
"(",
"year",
",",
"53",
")",
")",
")",
".",
"year",
"==",
"year",
":",
"return",
"53",
"else",
":",
"return",
"52"
]
| Return number of epiweeks in a year | [
"Return",
"number",
"of",
"epiweeks",
"in",
"a",
"year"
]
| 98216bd5081998ca63db89003c4ef397fe905755 | https://github.com/reichlab/pymmwr/blob/98216bd5081998ca63db89003c4ef397fe905755/pymmwr.py#L83-L91 | train |
tylerbutler/engineer | engineer/commands/core.py | _ArgparseMixin.parser | def parser(self):
"""Returns the appropriate parser to use for adding arguments to your command."""
if self._command_parser is None:
parents = []
if self.need_verbose:
parents.append(_verbose_parser)
if self.need_settings:
parents.append(_settings_parser)
self._command_parser = self._main_parser.add_parser(self.name,
help=self.help,
parents=parents,
formatter_class=argparse.RawDescriptionHelpFormatter)
return self._command_parser | python | def parser(self):
"""Returns the appropriate parser to use for adding arguments to your command."""
if self._command_parser is None:
parents = []
if self.need_verbose:
parents.append(_verbose_parser)
if self.need_settings:
parents.append(_settings_parser)
self._command_parser = self._main_parser.add_parser(self.name,
help=self.help,
parents=parents,
formatter_class=argparse.RawDescriptionHelpFormatter)
return self._command_parser | [
"def",
"parser",
"(",
"self",
")",
":",
"if",
"self",
".",
"_command_parser",
"is",
"None",
":",
"parents",
"=",
"[",
"]",
"if",
"self",
".",
"need_verbose",
":",
"parents",
".",
"append",
"(",
"_verbose_parser",
")",
"if",
"self",
".",
"need_settings",
":",
"parents",
".",
"append",
"(",
"_settings_parser",
")",
"self",
".",
"_command_parser",
"=",
"self",
".",
"_main_parser",
".",
"add_parser",
"(",
"self",
".",
"name",
",",
"help",
"=",
"self",
".",
"help",
",",
"parents",
"=",
"parents",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
")",
"return",
"self",
".",
"_command_parser"
]
| Returns the appropriate parser to use for adding arguments to your command. | [
"Returns",
"the",
"appropriate",
"parser",
"to",
"use",
"for",
"adding",
"arguments",
"to",
"your",
"command",
"."
]
| 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/commands/core.py#L165-L178 | train |
tjcsl/cslbot | cslbot/commands/admins.py | cmd | def cmd(send, _, args):
"""Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command}
"""
adminlist = []
for admin in args['db'].query(Permissions).order_by(Permissions.nick).all():
if admin.registered:
adminlist.append("%s (V)" % admin.nick)
else:
adminlist.append("%s (U)" % admin.nick)
send(", ".join(adminlist), target=args['nick']) | python | def cmd(send, _, args):
"""Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command}
"""
adminlist = []
for admin in args['db'].query(Permissions).order_by(Permissions.nick).all():
if admin.registered:
adminlist.append("%s (V)" % admin.nick)
else:
adminlist.append("%s (U)" % admin.nick)
send(", ".join(adminlist), target=args['nick']) | [
"def",
"cmd",
"(",
"send",
",",
"_",
",",
"args",
")",
":",
"adminlist",
"=",
"[",
"]",
"for",
"admin",
"in",
"args",
"[",
"'db'",
"]",
".",
"query",
"(",
"Permissions",
")",
".",
"order_by",
"(",
"Permissions",
".",
"nick",
")",
".",
"all",
"(",
")",
":",
"if",
"admin",
".",
"registered",
":",
"adminlist",
".",
"append",
"(",
"\"%s (V)\"",
"%",
"admin",
".",
"nick",
")",
"else",
":",
"adminlist",
".",
"append",
"(",
"\"%s (U)\"",
"%",
"admin",
".",
"nick",
")",
"send",
"(",
"\", \"",
".",
"join",
"(",
"adminlist",
")",
",",
"target",
"=",
"args",
"[",
"'nick'",
"]",
")"
]
| Returns a list of admins.
V = Verified (authed to NickServ), U = Unverified.
Syntax: {command} | [
"Returns",
"a",
"list",
"of",
"admins",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/admins.py#L23-L36 | train |
acutesoftware/virtual-AI-simulator | vais/AI_sample_game.py | ReallySimpleGameAI.run | def run(self):
"""
This AI simple moves the characters towards the opposite
edges of the grid for 3 steps or until event halts the
simulation
"""
x, y = 1,0 # set the direction
num_steps = 0
while self.s.get_state() != 'Halted':
self.s.command({'name':'walk', 'type':'move', 'direction':[x, y]}, self.a1)
self.s.command({'name':'walk', 'type':'run', 'direction':[x, y+1]}, self.a2)
num_steps += 1
if num_steps >= 3:
break
for a in self.s.agents:
print(a.name, 'finished at position ', a.coords['x'], a.coords['y']) | python | def run(self):
"""
This AI simple moves the characters towards the opposite
edges of the grid for 3 steps or until event halts the
simulation
"""
x, y = 1,0 # set the direction
num_steps = 0
while self.s.get_state() != 'Halted':
self.s.command({'name':'walk', 'type':'move', 'direction':[x, y]}, self.a1)
self.s.command({'name':'walk', 'type':'run', 'direction':[x, y+1]}, self.a2)
num_steps += 1
if num_steps >= 3:
break
for a in self.s.agents:
print(a.name, 'finished at position ', a.coords['x'], a.coords['y']) | [
"def",
"run",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"1",
",",
"0",
"# set the direction",
"num_steps",
"=",
"0",
"while",
"self",
".",
"s",
".",
"get_state",
"(",
")",
"!=",
"'Halted'",
":",
"self",
".",
"s",
".",
"command",
"(",
"{",
"'name'",
":",
"'walk'",
",",
"'type'",
":",
"'move'",
",",
"'direction'",
":",
"[",
"x",
",",
"y",
"]",
"}",
",",
"self",
".",
"a1",
")",
"self",
".",
"s",
".",
"command",
"(",
"{",
"'name'",
":",
"'walk'",
",",
"'type'",
":",
"'run'",
",",
"'direction'",
":",
"[",
"x",
",",
"y",
"+",
"1",
"]",
"}",
",",
"self",
".",
"a2",
")",
"num_steps",
"+=",
"1",
"if",
"num_steps",
">=",
"3",
":",
"break",
"for",
"a",
"in",
"self",
".",
"s",
".",
"agents",
":",
"print",
"(",
"a",
".",
"name",
",",
"'finished at position '",
",",
"a",
".",
"coords",
"[",
"'x'",
"]",
",",
"a",
".",
"coords",
"[",
"'y'",
"]",
")"
]
| This AI simple moves the characters towards the opposite
edges of the grid for 3 steps or until event halts the
simulation | [
"This",
"AI",
"simple",
"moves",
"the",
"characters",
"towards",
"the",
"opposite",
"edges",
"of",
"the",
"grid",
"for",
"3",
"steps",
"or",
"until",
"event",
"halts",
"the",
"simulation"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/AI_sample_game.py#L28-L43 | train |
louib/confirm | confirm/main.py | validate | def validate(schema_file, config_file, deprecation):
'''Validate a configuration file against a confirm schema.'''
result = validator_from_config_file(config_file, schema_file)
result.validate(error_on_deprecated=deprecation)
for error in result.errors():
click.secho('Error : %s' % error, err=True, fg='red')
for warning in result.warnings():
click.secho('Warning : %s' % warning, err=True, fg='yellow') | python | def validate(schema_file, config_file, deprecation):
'''Validate a configuration file against a confirm schema.'''
result = validator_from_config_file(config_file, schema_file)
result.validate(error_on_deprecated=deprecation)
for error in result.errors():
click.secho('Error : %s' % error, err=True, fg='red')
for warning in result.warnings():
click.secho('Warning : %s' % warning, err=True, fg='yellow') | [
"def",
"validate",
"(",
"schema_file",
",",
"config_file",
",",
"deprecation",
")",
":",
"result",
"=",
"validator_from_config_file",
"(",
"config_file",
",",
"schema_file",
")",
"result",
".",
"validate",
"(",
"error_on_deprecated",
"=",
"deprecation",
")",
"for",
"error",
"in",
"result",
".",
"errors",
"(",
")",
":",
"click",
".",
"secho",
"(",
"'Error : %s'",
"%",
"error",
",",
"err",
"=",
"True",
",",
"fg",
"=",
"'red'",
")",
"for",
"warning",
"in",
"result",
".",
"warnings",
"(",
")",
":",
"click",
".",
"secho",
"(",
"'Warning : %s'",
"%",
"warning",
",",
"err",
"=",
"True",
",",
"fg",
"=",
"'yellow'",
")"
]
| Validate a configuration file against a confirm schema. | [
"Validate",
"a",
"configuration",
"file",
"against",
"a",
"confirm",
"schema",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L25-L35 | train |
louib/confirm | confirm/main.py | migrate | def migrate(schema_file, config_file):
'''Migrates a configuration file using a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config = load_config_file(config_file, open(config_file, 'r').read())
config = append_existing_values(schema, config)
migrated_config = generate_config_parser(config)
migrated_config.write(sys.stdout) | python | def migrate(schema_file, config_file):
'''Migrates a configuration file using a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config = load_config_file(config_file, open(config_file, 'r').read())
config = append_existing_values(schema, config)
migrated_config = generate_config_parser(config)
migrated_config.write(sys.stdout) | [
"def",
"migrate",
"(",
"schema_file",
",",
"config_file",
")",
":",
"schema",
"=",
"load_schema_file",
"(",
"open",
"(",
"schema_file",
",",
"'r'",
")",
")",
"config",
"=",
"load_config_file",
"(",
"config_file",
",",
"open",
"(",
"config_file",
",",
"'r'",
")",
".",
"read",
"(",
")",
")",
"config",
"=",
"append_existing_values",
"(",
"schema",
",",
"config",
")",
"migrated_config",
"=",
"generate_config_parser",
"(",
"config",
")",
"migrated_config",
".",
"write",
"(",
"sys",
".",
"stdout",
")"
]
| Migrates a configuration file using a confirm schema. | [
"Migrates",
"a",
"configuration",
"file",
"using",
"a",
"confirm",
"schema",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L41-L50 | train |
louib/confirm | confirm/main.py | document | def document(schema_file):
'''Generate reStructuredText documentation from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
documentation = generate_documentation(schema)
sys.stdout.write(documentation) | python | def document(schema_file):
'''Generate reStructuredText documentation from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
documentation = generate_documentation(schema)
sys.stdout.write(documentation) | [
"def",
"document",
"(",
"schema_file",
")",
":",
"schema",
"=",
"load_schema_file",
"(",
"open",
"(",
"schema_file",
",",
"'r'",
")",
")",
"documentation",
"=",
"generate_documentation",
"(",
"schema",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"documentation",
")"
]
| Generate reStructuredText documentation from a confirm schema. | [
"Generate",
"reStructuredText",
"documentation",
"from",
"a",
"confirm",
"schema",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L55-L59 | train |
louib/confirm | confirm/main.py | generate | def generate(schema_file, all_options):
'''Generates a template configuration file from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config_parser = generate_config_parser(schema, include_all=all_options)
config_parser.write(sys.stdout) | python | def generate(schema_file, all_options):
'''Generates a template configuration file from a confirm schema.'''
schema = load_schema_file(open(schema_file, 'r'))
config_parser = generate_config_parser(schema, include_all=all_options)
config_parser.write(sys.stdout) | [
"def",
"generate",
"(",
"schema_file",
",",
"all_options",
")",
":",
"schema",
"=",
"load_schema_file",
"(",
"open",
"(",
"schema_file",
",",
"'r'",
")",
")",
"config_parser",
"=",
"generate_config_parser",
"(",
"schema",
",",
"include_all",
"=",
"all_options",
")",
"config_parser",
".",
"write",
"(",
"sys",
".",
"stdout",
")"
]
| Generates a template configuration file from a confirm schema. | [
"Generates",
"a",
"template",
"configuration",
"file",
"from",
"a",
"confirm",
"schema",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L65-L69 | train |
louib/confirm | confirm/main.py | init | def init(config_file):
'''Initialize a confirm schema from an existing configuration file.'''
schema = generate_schema_file(open(config_file, 'r').read())
sys.stdout.write(schema) | python | def init(config_file):
'''Initialize a confirm schema from an existing configuration file.'''
schema = generate_schema_file(open(config_file, 'r').read())
sys.stdout.write(schema) | [
"def",
"init",
"(",
"config_file",
")",
":",
"schema",
"=",
"generate_schema_file",
"(",
"open",
"(",
"config_file",
",",
"'r'",
")",
".",
"read",
"(",
")",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"schema",
")"
]
| Initialize a confirm schema from an existing configuration file. | [
"Initialize",
"a",
"confirm",
"schema",
"from",
"an",
"existing",
"configuration",
"file",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/main.py#L74-L77 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._init_random_gaussians | def _init_random_gaussians(self, X):
"""Initialize gaussian randomly"""
n_samples = np.shape(X)[0]
self.priors = (1 / self.k) * np.ones(self.k)
for _ in range(self.k):
params = {}
params["mean"] = X[np.random.choice(range(n_samples))]
params["cov"] = calculate_covariance_matrix(X)
self.parameters.append(params) | python | def _init_random_gaussians(self, X):
"""Initialize gaussian randomly"""
n_samples = np.shape(X)[0]
self.priors = (1 / self.k) * np.ones(self.k)
for _ in range(self.k):
params = {}
params["mean"] = X[np.random.choice(range(n_samples))]
params["cov"] = calculate_covariance_matrix(X)
self.parameters.append(params) | [
"def",
"_init_random_gaussians",
"(",
"self",
",",
"X",
")",
":",
"n_samples",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"self",
".",
"priors",
"=",
"(",
"1",
"/",
"self",
".",
"k",
")",
"*",
"np",
".",
"ones",
"(",
"self",
".",
"k",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"k",
")",
":",
"params",
"=",
"{",
"}",
"params",
"[",
"\"mean\"",
"]",
"=",
"X",
"[",
"np",
".",
"random",
".",
"choice",
"(",
"range",
"(",
"n_samples",
")",
")",
"]",
"params",
"[",
"\"cov\"",
"]",
"=",
"calculate_covariance_matrix",
"(",
"X",
")",
"self",
".",
"parameters",
".",
"append",
"(",
"params",
")"
]
| Initialize gaussian randomly | [
"Initialize",
"gaussian",
"randomly"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L36-L45 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._get_likelihoods | def _get_likelihoods(self, X):
"""Calculate the likelihood over all samples"""
n_samples = np.shape(X)[0]
likelihoods = np.zeros((n_samples, self.k))
for i in range(self.k):
likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i])
return likelihoods | python | def _get_likelihoods(self, X):
"""Calculate the likelihood over all samples"""
n_samples = np.shape(X)[0]
likelihoods = np.zeros((n_samples, self.k))
for i in range(self.k):
likelihoods[:, i] = self.multivariate_gaussian(X, self.parameters[i])
return likelihoods | [
"def",
"_get_likelihoods",
"(",
"self",
",",
"X",
")",
":",
"n_samples",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"likelihoods",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_samples",
",",
"self",
".",
"k",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"k",
")",
":",
"likelihoods",
"[",
":",
",",
"i",
"]",
"=",
"self",
".",
"multivariate_gaussian",
"(",
"X",
",",
"self",
".",
"parameters",
"[",
"i",
"]",
")",
"return",
"likelihoods"
]
| Calculate the likelihood over all samples | [
"Calculate",
"the",
"likelihood",
"over",
"all",
"samples"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L63-L71 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._expectation | def _expectation(self, X):
"""Calculate the responsibility"""
# Calculate probabilities of X belonging to the different clusters
weighted_likelihoods = self._get_likelihoods(X) * self.priors
sum_likelihoods = np.expand_dims(np.sum(weighted_likelihoods, axis=1), axis=1)
# Determine responsibility as P(X|y)*P(y)/P(X)
self.responsibility = weighted_likelihoods / sum_likelihoods
# Assign samples to cluster that has largest probability
self.sample_assignments = self.responsibility.argmax(axis=1)
# Save value for convergence check
self.responsibilities.append(np.max(self.responsibility, axis=1)) | python | def _expectation(self, X):
"""Calculate the responsibility"""
# Calculate probabilities of X belonging to the different clusters
weighted_likelihoods = self._get_likelihoods(X) * self.priors
sum_likelihoods = np.expand_dims(np.sum(weighted_likelihoods, axis=1), axis=1)
# Determine responsibility as P(X|y)*P(y)/P(X)
self.responsibility = weighted_likelihoods / sum_likelihoods
# Assign samples to cluster that has largest probability
self.sample_assignments = self.responsibility.argmax(axis=1)
# Save value for convergence check
self.responsibilities.append(np.max(self.responsibility, axis=1)) | [
"def",
"_expectation",
"(",
"self",
",",
"X",
")",
":",
"# Calculate probabilities of X belonging to the different clusters",
"weighted_likelihoods",
"=",
"self",
".",
"_get_likelihoods",
"(",
"X",
")",
"*",
"self",
".",
"priors",
"sum_likelihoods",
"=",
"np",
".",
"expand_dims",
"(",
"np",
".",
"sum",
"(",
"weighted_likelihoods",
",",
"axis",
"=",
"1",
")",
",",
"axis",
"=",
"1",
")",
"# Determine responsibility as P(X|y)*P(y)/P(X)",
"self",
".",
"responsibility",
"=",
"weighted_likelihoods",
"/",
"sum_likelihoods",
"# Assign samples to cluster that has largest probability",
"self",
".",
"sample_assignments",
"=",
"self",
".",
"responsibility",
".",
"argmax",
"(",
"axis",
"=",
"1",
")",
"# Save value for convergence check",
"self",
".",
"responsibilities",
".",
"append",
"(",
"np",
".",
"max",
"(",
"self",
".",
"responsibility",
",",
"axis",
"=",
"1",
")",
")"
]
| Calculate the responsibility | [
"Calculate",
"the",
"responsibility"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L73-L84 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._maximization | def _maximization(self, X):
"""Update the parameters and priors"""
# Iterate through clusters and recalculate mean and covariance
for i in range(self.k):
resp = np.expand_dims(self.responsibility[:, i], axis=1)
mean = (resp * X).sum(axis=0) / resp.sum()
covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum()
self.parameters[i]["mean"], self.parameters[i]["cov"] = mean, covariance
# Update weights
n_samples = np.shape(X)[0]
self.priors = self.responsibility.sum(axis=0) / n_samples | python | def _maximization(self, X):
"""Update the parameters and priors"""
# Iterate through clusters and recalculate mean and covariance
for i in range(self.k):
resp = np.expand_dims(self.responsibility[:, i], axis=1)
mean = (resp * X).sum(axis=0) / resp.sum()
covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum()
self.parameters[i]["mean"], self.parameters[i]["cov"] = mean, covariance
# Update weights
n_samples = np.shape(X)[0]
self.priors = self.responsibility.sum(axis=0) / n_samples | [
"def",
"_maximization",
"(",
"self",
",",
"X",
")",
":",
"# Iterate through clusters and recalculate mean and covariance",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"k",
")",
":",
"resp",
"=",
"np",
".",
"expand_dims",
"(",
"self",
".",
"responsibility",
"[",
":",
",",
"i",
"]",
",",
"axis",
"=",
"1",
")",
"mean",
"=",
"(",
"resp",
"*",
"X",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"/",
"resp",
".",
"sum",
"(",
")",
"covariance",
"=",
"(",
"X",
"-",
"mean",
")",
".",
"T",
".",
"dot",
"(",
"(",
"X",
"-",
"mean",
")",
"*",
"resp",
")",
"/",
"resp",
".",
"sum",
"(",
")",
"self",
".",
"parameters",
"[",
"i",
"]",
"[",
"\"mean\"",
"]",
",",
"self",
".",
"parameters",
"[",
"i",
"]",
"[",
"\"cov\"",
"]",
"=",
"mean",
",",
"covariance",
"# Update weights",
"n_samples",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"self",
".",
"priors",
"=",
"self",
".",
"responsibility",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
"/",
"n_samples"
]
| Update the parameters and priors | [
"Update",
"the",
"parameters",
"and",
"priors"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L86-L98 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel._converged | def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2])
return diff <= self.tolerance | python | def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2])
return diff <= self.tolerance | [
"def",
"_converged",
"(",
"self",
",",
"X",
")",
":",
"if",
"len",
"(",
"self",
".",
"responsibilities",
")",
"<",
"2",
":",
"return",
"False",
"diff",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"responsibilities",
"[",
"-",
"1",
"]",
"-",
"self",
".",
"responsibilities",
"[",
"-",
"2",
"]",
")",
"return",
"diff",
"<=",
"self",
".",
"tolerance"
]
| Covergence if || likehood - last_likelihood || < tolerance | [
"Covergence",
"if",
"||",
"likehood",
"-",
"last_likelihood",
"||",
"<",
"tolerance"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L100-L107 | train |
VIVelev/PyDojoML | dojo/cluster/mixture/gaussian_mixture_model.py | GaussianMixtureModel.cluster | def cluster(self, X):
"""Run GMM and return the cluster indices"""
# Initialize the gaussians randomly
self._init_random_gaussians(X)
# Run EM until convergence or for max iterations
for _ in range(self.max_iterations):
self._expectation(X) # E-step
self._maximization(X) # M-step
# Check convergence
if self._converged(X):
break
# Make new assignments and return them
self._expectation(X)
return self.sample_assignments | python | def cluster(self, X):
"""Run GMM and return the cluster indices"""
# Initialize the gaussians randomly
self._init_random_gaussians(X)
# Run EM until convergence or for max iterations
for _ in range(self.max_iterations):
self._expectation(X) # E-step
self._maximization(X) # M-step
# Check convergence
if self._converged(X):
break
# Make new assignments and return them
self._expectation(X)
return self.sample_assignments | [
"def",
"cluster",
"(",
"self",
",",
"X",
")",
":",
"# Initialize the gaussians randomly",
"self",
".",
"_init_random_gaussians",
"(",
"X",
")",
"# Run EM until convergence or for max iterations",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"max_iterations",
")",
":",
"self",
".",
"_expectation",
"(",
"X",
")",
"# E-step",
"self",
".",
"_maximization",
"(",
"X",
")",
"# M-step",
"# Check convergence",
"if",
"self",
".",
"_converged",
"(",
"X",
")",
":",
"break",
"# Make new assignments and return them",
"self",
".",
"_expectation",
"(",
"X",
")",
"return",
"self",
".",
"sample_assignments"
]
| Run GMM and return the cluster indices | [
"Run",
"GMM",
"and",
"return",
"the",
"cluster",
"indices"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/cluster/mixture/gaussian_mixture_model.py#L109-L126 | train |
tjcsl/cslbot | cslbot/commands/translate.py | cmd | def cmd(send, msg, args):
"""Translate something.
Syntax: {command} [--from <language code>] [--to <language code>] <text>
See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--lang', '--from', default=None)
parser.add_argument('--to', default='en')
parser.add_argument('msg', nargs='+')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
send(gen_translate(' '.join(cmdargs.msg), cmdargs.lang, cmdargs.to)) | python | def cmd(send, msg, args):
"""Translate something.
Syntax: {command} [--from <language code>] [--to <language code>] <text>
See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--lang', '--from', default=None)
parser.add_argument('--to', default='en')
parser.add_argument('msg', nargs='+')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
send(gen_translate(' '.join(cmdargs.msg), cmdargs.lang, cmdargs.to)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--lang'",
",",
"'--from'",
",",
"default",
"=",
"None",
")",
"parser",
".",
"add_argument",
"(",
"'--to'",
",",
"default",
"=",
"'en'",
")",
"parser",
".",
"add_argument",
"(",
"'msg'",
",",
"nargs",
"=",
"'+'",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"send",
"(",
"gen_translate",
"(",
"' '",
".",
"join",
"(",
"cmdargs",
".",
"msg",
")",
",",
"cmdargs",
".",
"lang",
",",
"cmdargs",
".",
"to",
")",
")"
]
| Translate something.
Syntax: {command} [--from <language code>] [--to <language code>] <text>
See https://cloud.google.com/translate/v2/translate-reference#supported_languages for a list of valid language codes | [
"Translate",
"something",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/translate.py#L24-L40 | train |
tjcsl/cslbot | cslbot/commands/coin.py | cmd | def cmd(send, msg, _):
"""Flips a coin a number of times.
Syntax: {command} [number]
"""
coin = ['heads', 'tails']
if not msg:
send('The coin lands on... %s' % choice(coin))
elif not msg.lstrip('-').isdigit():
send("Not A Valid Positive Integer.")
else:
msg = int(msg)
if msg < 0:
send("Negative Flipping requires the (optional) quantum coprocessor.")
return
headflips = randint(0, msg)
tailflips = msg - headflips
send('The coins land on heads %g times and on tails %g times.' % (headflips, tailflips)) | python | def cmd(send, msg, _):
"""Flips a coin a number of times.
Syntax: {command} [number]
"""
coin = ['heads', 'tails']
if not msg:
send('The coin lands on... %s' % choice(coin))
elif not msg.lstrip('-').isdigit():
send("Not A Valid Positive Integer.")
else:
msg = int(msg)
if msg < 0:
send("Negative Flipping requires the (optional) quantum coprocessor.")
return
headflips = randint(0, msg)
tailflips = msg - headflips
send('The coins land on heads %g times and on tails %g times.' % (headflips, tailflips)) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"_",
")",
":",
"coin",
"=",
"[",
"'heads'",
",",
"'tails'",
"]",
"if",
"not",
"msg",
":",
"send",
"(",
"'The coin lands on... %s'",
"%",
"choice",
"(",
"coin",
")",
")",
"elif",
"not",
"msg",
".",
"lstrip",
"(",
"'-'",
")",
".",
"isdigit",
"(",
")",
":",
"send",
"(",
"\"Not A Valid Positive Integer.\"",
")",
"else",
":",
"msg",
"=",
"int",
"(",
"msg",
")",
"if",
"msg",
"<",
"0",
":",
"send",
"(",
"\"Negative Flipping requires the (optional) quantum coprocessor.\"",
")",
"return",
"headflips",
"=",
"randint",
"(",
"0",
",",
"msg",
")",
"tailflips",
"=",
"msg",
"-",
"headflips",
"send",
"(",
"'The coins land on heads %g times and on tails %g times.'",
"%",
"(",
"headflips",
",",
"tailflips",
")",
")"
]
| Flips a coin a number of times.
Syntax: {command} [number] | [
"Flips",
"a",
"coin",
"a",
"number",
"of",
"times",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/coin.py#L24-L42 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.is_admin | def is_admin(self, send, nick, required_role='admin'):
"""Checks if a nick is a admin.
If NickServ hasn't responded yet, then the admin is unverified,
so assume they aren't a admin.
"""
# If the required role is None, bypass checks.
if not required_role:
return True
# Current roles are admin and owner, which is a superset of admin.
with self.db.session_scope() as session:
admin = session.query(orm.Permissions).filter(orm.Permissions.nick == nick).first()
if admin is None:
return False
# owner implies admin, but not the other way around.
if required_role == "owner" and admin.role != "owner":
return False
# no nickserv support, assume people are who they say they are.
if not self.config['feature'].getboolean('nickserv'):
return True
if not admin.registered:
self.update_authstatus(nick)
# We don't necessarily want to complain in all cases.
if send is not None:
send("Unverified admin: %s" % nick, target=self.config['core']['channel'])
return False
else:
if not self.features['account-notify']:
# reverify every 5min if we don't have the notification feature.
if datetime.now() - admin.time > timedelta(minutes=5):
self.update_authstatus(nick)
return True | python | def is_admin(self, send, nick, required_role='admin'):
"""Checks if a nick is a admin.
If NickServ hasn't responded yet, then the admin is unverified,
so assume they aren't a admin.
"""
# If the required role is None, bypass checks.
if not required_role:
return True
# Current roles are admin and owner, which is a superset of admin.
with self.db.session_scope() as session:
admin = session.query(orm.Permissions).filter(orm.Permissions.nick == nick).first()
if admin is None:
return False
# owner implies admin, but not the other way around.
if required_role == "owner" and admin.role != "owner":
return False
# no nickserv support, assume people are who they say they are.
if not self.config['feature'].getboolean('nickserv'):
return True
if not admin.registered:
self.update_authstatus(nick)
# We don't necessarily want to complain in all cases.
if send is not None:
send("Unverified admin: %s" % nick, target=self.config['core']['channel'])
return False
else:
if not self.features['account-notify']:
# reverify every 5min if we don't have the notification feature.
if datetime.now() - admin.time > timedelta(minutes=5):
self.update_authstatus(nick)
return True | [
"def",
"is_admin",
"(",
"self",
",",
"send",
",",
"nick",
",",
"required_role",
"=",
"'admin'",
")",
":",
"# If the required role is None, bypass checks.",
"if",
"not",
"required_role",
":",
"return",
"True",
"# Current roles are admin and owner, which is a superset of admin.",
"with",
"self",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"admin",
"=",
"session",
".",
"query",
"(",
"orm",
".",
"Permissions",
")",
".",
"filter",
"(",
"orm",
".",
"Permissions",
".",
"nick",
"==",
"nick",
")",
".",
"first",
"(",
")",
"if",
"admin",
"is",
"None",
":",
"return",
"False",
"# owner implies admin, but not the other way around.",
"if",
"required_role",
"==",
"\"owner\"",
"and",
"admin",
".",
"role",
"!=",
"\"owner\"",
":",
"return",
"False",
"# no nickserv support, assume people are who they say they are.",
"if",
"not",
"self",
".",
"config",
"[",
"'feature'",
"]",
".",
"getboolean",
"(",
"'nickserv'",
")",
":",
"return",
"True",
"if",
"not",
"admin",
".",
"registered",
":",
"self",
".",
"update_authstatus",
"(",
"nick",
")",
"# We don't necessarily want to complain in all cases.",
"if",
"send",
"is",
"not",
"None",
":",
"send",
"(",
"\"Unverified admin: %s\"",
"%",
"nick",
",",
"target",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
")",
"return",
"False",
"else",
":",
"if",
"not",
"self",
".",
"features",
"[",
"'account-notify'",
"]",
":",
"# reverify every 5min if we don't have the notification feature.",
"if",
"datetime",
".",
"now",
"(",
")",
"-",
"admin",
".",
"time",
">",
"timedelta",
"(",
"minutes",
"=",
"5",
")",
":",
"self",
".",
"update_authstatus",
"(",
"nick",
")",
"return",
"True"
]
| Checks if a nick is a admin.
If NickServ hasn't responded yet, then the admin is unverified,
so assume they aren't a admin. | [
"Checks",
"if",
"a",
"nick",
"is",
"a",
"admin",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L106-L138 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.get_admins | def get_admins(self):
"""Check verification for all admins."""
# no nickserv support, assume people are who they say they are.
if not self.config['feature'].getboolean('nickserv'):
return
with self.db.session_scope() as session:
for a in session.query(orm.Permissions).all():
if not a.registered:
self.update_authstatus(a.nick) | python | def get_admins(self):
"""Check verification for all admins."""
# no nickserv support, assume people are who they say they are.
if not self.config['feature'].getboolean('nickserv'):
return
with self.db.session_scope() as session:
for a in session.query(orm.Permissions).all():
if not a.registered:
self.update_authstatus(a.nick) | [
"def",
"get_admins",
"(",
"self",
")",
":",
"# no nickserv support, assume people are who they say they are.",
"if",
"not",
"self",
".",
"config",
"[",
"'feature'",
"]",
".",
"getboolean",
"(",
"'nickserv'",
")",
":",
"return",
"with",
"self",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"for",
"a",
"in",
"session",
".",
"query",
"(",
"orm",
".",
"Permissions",
")",
".",
"all",
"(",
")",
":",
"if",
"not",
"a",
".",
"registered",
":",
"self",
".",
"update_authstatus",
"(",
"a",
".",
"nick",
")"
]
| Check verification for all admins. | [
"Check",
"verification",
"for",
"all",
"admins",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L140-L148 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.abusecheck | def abusecheck(self, send, nick, target, limit, cmd):
""" Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick.
"""
if nick not in self.abuselist:
self.abuselist[nick] = {}
if cmd not in self.abuselist[nick]:
self.abuselist[nick][cmd] = [datetime.now()]
else:
self.abuselist[nick][cmd].append(datetime.now())
count = 0
for x in self.abuselist[nick][cmd]:
# 60 seconds - arbitrary cuttoff
if datetime.now() - x < timedelta(seconds=60):
count = count + 1
if count > limit:
msg = "%s: don't abuse scores!" if cmd == 'scores' else "%s: stop abusing the bot!"
send(msg % nick, target=target)
with self.db.session_scope() as session:
send(misc.ignore(session, nick))
return True | python | def abusecheck(self, send, nick, target, limit, cmd):
""" Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick.
"""
if nick not in self.abuselist:
self.abuselist[nick] = {}
if cmd not in self.abuselist[nick]:
self.abuselist[nick][cmd] = [datetime.now()]
else:
self.abuselist[nick][cmd].append(datetime.now())
count = 0
for x in self.abuselist[nick][cmd]:
# 60 seconds - arbitrary cuttoff
if datetime.now() - x < timedelta(seconds=60):
count = count + 1
if count > limit:
msg = "%s: don't abuse scores!" if cmd == 'scores' else "%s: stop abusing the bot!"
send(msg % nick, target=target)
with self.db.session_scope() as session:
send(misc.ignore(session, nick))
return True | [
"def",
"abusecheck",
"(",
"self",
",",
"send",
",",
"nick",
",",
"target",
",",
"limit",
",",
"cmd",
")",
":",
"if",
"nick",
"not",
"in",
"self",
".",
"abuselist",
":",
"self",
".",
"abuselist",
"[",
"nick",
"]",
"=",
"{",
"}",
"if",
"cmd",
"not",
"in",
"self",
".",
"abuselist",
"[",
"nick",
"]",
":",
"self",
".",
"abuselist",
"[",
"nick",
"]",
"[",
"cmd",
"]",
"=",
"[",
"datetime",
".",
"now",
"(",
")",
"]",
"else",
":",
"self",
".",
"abuselist",
"[",
"nick",
"]",
"[",
"cmd",
"]",
".",
"append",
"(",
"datetime",
".",
"now",
"(",
")",
")",
"count",
"=",
"0",
"for",
"x",
"in",
"self",
".",
"abuselist",
"[",
"nick",
"]",
"[",
"cmd",
"]",
":",
"# 60 seconds - arbitrary cuttoff",
"if",
"datetime",
".",
"now",
"(",
")",
"-",
"x",
"<",
"timedelta",
"(",
"seconds",
"=",
"60",
")",
":",
"count",
"=",
"count",
"+",
"1",
"if",
"count",
">",
"limit",
":",
"msg",
"=",
"\"%s: don't abuse scores!\"",
"if",
"cmd",
"==",
"'scores'",
"else",
"\"%s: stop abusing the bot!\"",
"send",
"(",
"msg",
"%",
"nick",
",",
"target",
"=",
"target",
")",
"with",
"self",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"send",
"(",
"misc",
".",
"ignore",
"(",
"session",
",",
"nick",
")",
")",
"return",
"True"
]
| Rate-limits commands.
| If a nick uses commands with the limit attr set, record the time
| at which they were used.
| If the command is used more than `limit` times in a
| minute, ignore the nick. | [
"Rate",
"-",
"limits",
"commands",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L150-L174 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_log | def do_log(self, target, nick, msg, msgtype):
"""Handles logging.
| Logs to a sql db.
"""
if not isinstance(msg, str):
raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__)
target = target.lower()
flags = 0
# Properly handle /msg +#channel
if target.startswith(('+', '@')):
target = target[1:]
with self.data_lock:
if target in self.channels:
if self.opers[target].get(nick, False):
flags |= 1
if self.voiced[target].get(nick, False):
flags |= 2
else:
target = 'private'
# FIXME: should we special-case this?
# strip ctrl chars from !creffett
msg = msg.replace('\x02\x038,4', '<rage>')
self.db.log(nick, target, flags, msg, msgtype)
if self.log_to_ctrlchan:
ctrlchan = self.config['core']['ctrlchan']
if target != ctrlchan:
ctrlmsg = "%s:%s:%s:%s" % (target, msgtype, nick, msg)
# If we call self.send, we'll get a infinite loop.
self.connection.privmsg(ctrlchan, ctrlmsg.strip()) | python | def do_log(self, target, nick, msg, msgtype):
"""Handles logging.
| Logs to a sql db.
"""
if not isinstance(msg, str):
raise Exception("IRC doesn't like it when you send it a %s" % type(msg).__name__)
target = target.lower()
flags = 0
# Properly handle /msg +#channel
if target.startswith(('+', '@')):
target = target[1:]
with self.data_lock:
if target in self.channels:
if self.opers[target].get(nick, False):
flags |= 1
if self.voiced[target].get(nick, False):
flags |= 2
else:
target = 'private'
# FIXME: should we special-case this?
# strip ctrl chars from !creffett
msg = msg.replace('\x02\x038,4', '<rage>')
self.db.log(nick, target, flags, msg, msgtype)
if self.log_to_ctrlchan:
ctrlchan = self.config['core']['ctrlchan']
if target != ctrlchan:
ctrlmsg = "%s:%s:%s:%s" % (target, msgtype, nick, msg)
# If we call self.send, we'll get a infinite loop.
self.connection.privmsg(ctrlchan, ctrlmsg.strip()) | [
"def",
"do_log",
"(",
"self",
",",
"target",
",",
"nick",
",",
"msg",
",",
"msgtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
"raise",
"Exception",
"(",
"\"IRC doesn't like it when you send it a %s\"",
"%",
"type",
"(",
"msg",
")",
".",
"__name__",
")",
"target",
"=",
"target",
".",
"lower",
"(",
")",
"flags",
"=",
"0",
"# Properly handle /msg +#channel",
"if",
"target",
".",
"startswith",
"(",
"(",
"'+'",
",",
"'@'",
")",
")",
":",
"target",
"=",
"target",
"[",
"1",
":",
"]",
"with",
"self",
".",
"data_lock",
":",
"if",
"target",
"in",
"self",
".",
"channels",
":",
"if",
"self",
".",
"opers",
"[",
"target",
"]",
".",
"get",
"(",
"nick",
",",
"False",
")",
":",
"flags",
"|=",
"1",
"if",
"self",
".",
"voiced",
"[",
"target",
"]",
".",
"get",
"(",
"nick",
",",
"False",
")",
":",
"flags",
"|=",
"2",
"else",
":",
"target",
"=",
"'private'",
"# FIXME: should we special-case this?",
"# strip ctrl chars from !creffett",
"msg",
"=",
"msg",
".",
"replace",
"(",
"'\\x02\\x038,4'",
",",
"'<rage>'",
")",
"self",
".",
"db",
".",
"log",
"(",
"nick",
",",
"target",
",",
"flags",
",",
"msg",
",",
"msgtype",
")",
"if",
"self",
".",
"log_to_ctrlchan",
":",
"ctrlchan",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
"if",
"target",
"!=",
"ctrlchan",
":",
"ctrlmsg",
"=",
"\"%s:%s:%s:%s\"",
"%",
"(",
"target",
",",
"msgtype",
",",
"nick",
",",
"msg",
")",
"# If we call self.send, we'll get a infinite loop.",
"self",
".",
"connection",
".",
"privmsg",
"(",
"ctrlchan",
",",
"ctrlmsg",
".",
"strip",
"(",
")",
")"
]
| Handles logging.
| Logs to a sql db. | [
"Handles",
"logging",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L226-L257 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_part | def do_part(self, cmdargs, nick, target, msgtype, send, c):
"""Leaves a channel.
Prevent user from leaving the primary channel.
"""
channel = self.config['core']['channel']
botnick = self.config['core']['nick']
if not cmdargs:
# don't leave the primary channel
if target == channel:
send("%s must have a home." % botnick)
return
else:
cmdargs = target
if not cmdargs.startswith(('#', '+', '@')):
cmdargs = '#' + cmdargs
# don't leave the primary channel
if cmdargs == channel:
send("%s must have a home." % botnick)
return
# don't leave the control channel
if cmdargs == self.config['core']['ctrlchan']:
send("%s must remain under control, or bad things will happen." % botnick)
return
self.send(cmdargs, nick, "Leaving at the request of %s" % nick, msgtype)
c.part(cmdargs) | python | def do_part(self, cmdargs, nick, target, msgtype, send, c):
"""Leaves a channel.
Prevent user from leaving the primary channel.
"""
channel = self.config['core']['channel']
botnick = self.config['core']['nick']
if not cmdargs:
# don't leave the primary channel
if target == channel:
send("%s must have a home." % botnick)
return
else:
cmdargs = target
if not cmdargs.startswith(('#', '+', '@')):
cmdargs = '#' + cmdargs
# don't leave the primary channel
if cmdargs == channel:
send("%s must have a home." % botnick)
return
# don't leave the control channel
if cmdargs == self.config['core']['ctrlchan']:
send("%s must remain under control, or bad things will happen." % botnick)
return
self.send(cmdargs, nick, "Leaving at the request of %s" % nick, msgtype)
c.part(cmdargs) | [
"def",
"do_part",
"(",
"self",
",",
"cmdargs",
",",
"nick",
",",
"target",
",",
"msgtype",
",",
"send",
",",
"c",
")",
":",
"channel",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
"botnick",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'nick'",
"]",
"if",
"not",
"cmdargs",
":",
"# don't leave the primary channel",
"if",
"target",
"==",
"channel",
":",
"send",
"(",
"\"%s must have a home.\"",
"%",
"botnick",
")",
"return",
"else",
":",
"cmdargs",
"=",
"target",
"if",
"not",
"cmdargs",
".",
"startswith",
"(",
"(",
"'#'",
",",
"'+'",
",",
"'@'",
")",
")",
":",
"cmdargs",
"=",
"'#'",
"+",
"cmdargs",
"# don't leave the primary channel",
"if",
"cmdargs",
"==",
"channel",
":",
"send",
"(",
"\"%s must have a home.\"",
"%",
"botnick",
")",
"return",
"# don't leave the control channel",
"if",
"cmdargs",
"==",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
":",
"send",
"(",
"\"%s must remain under control, or bad things will happen.\"",
"%",
"botnick",
")",
"return",
"self",
".",
"send",
"(",
"cmdargs",
",",
"nick",
",",
"\"Leaving at the request of %s\"",
"%",
"nick",
",",
"msgtype",
")",
"c",
".",
"part",
"(",
"cmdargs",
")"
]
| Leaves a channel.
Prevent user from leaving the primary channel. | [
"Leaves",
"a",
"channel",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L259-L285 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_join | def do_join(self, cmdargs, nick, msgtype, send, c):
"""Join a channel.
| Checks if bot is already joined to channel.
"""
if not cmdargs:
send("Join what?")
return
if cmdargs == '0':
send("I'm sorry, Dave. I'm afraid I can't do that.")
return
if not cmdargs.startswith(('#', '+', '@')):
cmdargs = '#' + cmdargs
cmd = cmdargs.split()
# FIXME: use argparse
if cmd[0] in self.channels and not (len(cmd) > 1 and cmd[1] == "force"):
send("%s is already a member of %s" % (self.config['core']['nick'], cmd[0]))
return
c.join(cmd[0])
self.send(cmd[0], nick, "Joined at the request of " + nick, msgtype) | python | def do_join(self, cmdargs, nick, msgtype, send, c):
"""Join a channel.
| Checks if bot is already joined to channel.
"""
if not cmdargs:
send("Join what?")
return
if cmdargs == '0':
send("I'm sorry, Dave. I'm afraid I can't do that.")
return
if not cmdargs.startswith(('#', '+', '@')):
cmdargs = '#' + cmdargs
cmd = cmdargs.split()
# FIXME: use argparse
if cmd[0] in self.channels and not (len(cmd) > 1 and cmd[1] == "force"):
send("%s is already a member of %s" % (self.config['core']['nick'], cmd[0]))
return
c.join(cmd[0])
self.send(cmd[0], nick, "Joined at the request of " + nick, msgtype) | [
"def",
"do_join",
"(",
"self",
",",
"cmdargs",
",",
"nick",
",",
"msgtype",
",",
"send",
",",
"c",
")",
":",
"if",
"not",
"cmdargs",
":",
"send",
"(",
"\"Join what?\"",
")",
"return",
"if",
"cmdargs",
"==",
"'0'",
":",
"send",
"(",
"\"I'm sorry, Dave. I'm afraid I can't do that.\"",
")",
"return",
"if",
"not",
"cmdargs",
".",
"startswith",
"(",
"(",
"'#'",
",",
"'+'",
",",
"'@'",
")",
")",
":",
"cmdargs",
"=",
"'#'",
"+",
"cmdargs",
"cmd",
"=",
"cmdargs",
".",
"split",
"(",
")",
"# FIXME: use argparse",
"if",
"cmd",
"[",
"0",
"]",
"in",
"self",
".",
"channels",
"and",
"not",
"(",
"len",
"(",
"cmd",
")",
">",
"1",
"and",
"cmd",
"[",
"1",
"]",
"==",
"\"force\"",
")",
":",
"send",
"(",
"\"%s is already a member of %s\"",
"%",
"(",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'nick'",
"]",
",",
"cmd",
"[",
"0",
"]",
")",
")",
"return",
"c",
".",
"join",
"(",
"cmd",
"[",
"0",
"]",
")",
"self",
".",
"send",
"(",
"cmd",
"[",
"0",
"]",
",",
"nick",
",",
"\"Joined at the request of \"",
"+",
"nick",
",",
"msgtype",
")"
]
| Join a channel.
| Checks if bot is already joined to channel. | [
"Join",
"a",
"channel",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L287-L307 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_mode | def do_mode(self, target, msg, nick, send):
"""reop and handle guard violations."""
mode_changes = irc.modes.parse_channel_modes(msg)
with self.data_lock:
for change in mode_changes:
if change[1] == 'v':
self.voiced[target][change[2]] = True if change[0] == '+' else False
if change[1] == 'o':
self.opers[target][change[2]] = True if change[0] == '+' else False
# reop
# FIXME: handle -o+o msbobBot msbobBot
if [x for x in mode_changes if self.check_mode(x)]:
send("%s: :(" % nick, target=target)
# Assume bot admins know what they're doing.
if not self.is_admin(None, nick):
send("OP %s" % target, target='ChanServ')
send("UNBAN %s" % target, target='ChanServ')
if len(self.guarded) > 0:
# if user is guarded and quieted, devoiced, or deopped, fix that
regex = r"(.*(-v|-o|\+q|\+b)[^ ]*) (%s)" % "|".join(self.guarded)
match = re.search(regex, msg)
if match and nick not in [match.group(3), self.connection.real_nickname]:
modestring = "+voe-qb %s" % (" ".join([match.group(3)] * 5))
self.connection.mode(target, modestring)
send('Mode %s on %s by the guard system' % (modestring, target), target=self.config['core']['ctrlchan']) | python | def do_mode(self, target, msg, nick, send):
"""reop and handle guard violations."""
mode_changes = irc.modes.parse_channel_modes(msg)
with self.data_lock:
for change in mode_changes:
if change[1] == 'v':
self.voiced[target][change[2]] = True if change[0] == '+' else False
if change[1] == 'o':
self.opers[target][change[2]] = True if change[0] == '+' else False
# reop
# FIXME: handle -o+o msbobBot msbobBot
if [x for x in mode_changes if self.check_mode(x)]:
send("%s: :(" % nick, target=target)
# Assume bot admins know what they're doing.
if not self.is_admin(None, nick):
send("OP %s" % target, target='ChanServ')
send("UNBAN %s" % target, target='ChanServ')
if len(self.guarded) > 0:
# if user is guarded and quieted, devoiced, or deopped, fix that
regex = r"(.*(-v|-o|\+q|\+b)[^ ]*) (%s)" % "|".join(self.guarded)
match = re.search(regex, msg)
if match and nick not in [match.group(3), self.connection.real_nickname]:
modestring = "+voe-qb %s" % (" ".join([match.group(3)] * 5))
self.connection.mode(target, modestring)
send('Mode %s on %s by the guard system' % (modestring, target), target=self.config['core']['ctrlchan']) | [
"def",
"do_mode",
"(",
"self",
",",
"target",
",",
"msg",
",",
"nick",
",",
"send",
")",
":",
"mode_changes",
"=",
"irc",
".",
"modes",
".",
"parse_channel_modes",
"(",
"msg",
")",
"with",
"self",
".",
"data_lock",
":",
"for",
"change",
"in",
"mode_changes",
":",
"if",
"change",
"[",
"1",
"]",
"==",
"'v'",
":",
"self",
".",
"voiced",
"[",
"target",
"]",
"[",
"change",
"[",
"2",
"]",
"]",
"=",
"True",
"if",
"change",
"[",
"0",
"]",
"==",
"'+'",
"else",
"False",
"if",
"change",
"[",
"1",
"]",
"==",
"'o'",
":",
"self",
".",
"opers",
"[",
"target",
"]",
"[",
"change",
"[",
"2",
"]",
"]",
"=",
"True",
"if",
"change",
"[",
"0",
"]",
"==",
"'+'",
"else",
"False",
"# reop",
"# FIXME: handle -o+o msbobBot msbobBot",
"if",
"[",
"x",
"for",
"x",
"in",
"mode_changes",
"if",
"self",
".",
"check_mode",
"(",
"x",
")",
"]",
":",
"send",
"(",
"\"%s: :(\"",
"%",
"nick",
",",
"target",
"=",
"target",
")",
"# Assume bot admins know what they're doing.",
"if",
"not",
"self",
".",
"is_admin",
"(",
"None",
",",
"nick",
")",
":",
"send",
"(",
"\"OP %s\"",
"%",
"target",
",",
"target",
"=",
"'ChanServ'",
")",
"send",
"(",
"\"UNBAN %s\"",
"%",
"target",
",",
"target",
"=",
"'ChanServ'",
")",
"if",
"len",
"(",
"self",
".",
"guarded",
")",
">",
"0",
":",
"# if user is guarded and quieted, devoiced, or deopped, fix that",
"regex",
"=",
"r\"(.*(-v|-o|\\+q|\\+b)[^ ]*) (%s)\"",
"%",
"\"|\"",
".",
"join",
"(",
"self",
".",
"guarded",
")",
"match",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"msg",
")",
"if",
"match",
"and",
"nick",
"not",
"in",
"[",
"match",
".",
"group",
"(",
"3",
")",
",",
"self",
".",
"connection",
".",
"real_nickname",
"]",
":",
"modestring",
"=",
"\"+voe-qb %s\"",
"%",
"(",
"\" \"",
".",
"join",
"(",
"[",
"match",
".",
"group",
"(",
"3",
")",
"]",
"*",
"5",
")",
")",
"self",
".",
"connection",
".",
"mode",
"(",
"target",
",",
"modestring",
")",
"send",
"(",
"'Mode %s on %s by the guard system'",
"%",
"(",
"modestring",
",",
"target",
")",
",",
"target",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
")"
]
| reop and handle guard violations. | [
"reop",
"and",
"handle",
"guard",
"violations",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L318-L343 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_kick | def do_kick(self, send, target, nick, msg, slogan=True):
"""Kick users.
- If kick is disabled, don't do anything.
- If the bot is not a op, rage at a op.
- Kick the user.
"""
if not self.kick_enabled:
return
if target not in self.channels:
send("%s: you're lucky, private message kicking hasn't been implemented yet." % nick)
return
with self.data_lock:
ops = [k for k, v in self.opers[target].items() if v]
botnick = self.config['core']['nick']
if botnick not in ops:
ops = ['someone'] if not ops else ops
send(textutils.gen_creffett("%s: /op the bot" % random.choice(ops)), target=target)
elif random.random() < 0.01 and msg == "shutting caps lock off":
if nick in ops:
send("%s: HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U" % nick, target=target)
else:
self.connection.kick(target, nick, "HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U")
else:
msg = textutils.gen_slogan(msg).upper() if slogan else msg
if nick in ops:
send("%s: %s" % (nick, msg), target=target)
else:
self.connection.kick(target, nick, msg) | python | def do_kick(self, send, target, nick, msg, slogan=True):
"""Kick users.
- If kick is disabled, don't do anything.
- If the bot is not a op, rage at a op.
- Kick the user.
"""
if not self.kick_enabled:
return
if target not in self.channels:
send("%s: you're lucky, private message kicking hasn't been implemented yet." % nick)
return
with self.data_lock:
ops = [k for k, v in self.opers[target].items() if v]
botnick = self.config['core']['nick']
if botnick not in ops:
ops = ['someone'] if not ops else ops
send(textutils.gen_creffett("%s: /op the bot" % random.choice(ops)), target=target)
elif random.random() < 0.01 and msg == "shutting caps lock off":
if nick in ops:
send("%s: HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U" % nick, target=target)
else:
self.connection.kick(target, nick, "HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U")
else:
msg = textutils.gen_slogan(msg).upper() if slogan else msg
if nick in ops:
send("%s: %s" % (nick, msg), target=target)
else:
self.connection.kick(target, nick, msg) | [
"def",
"do_kick",
"(",
"self",
",",
"send",
",",
"target",
",",
"nick",
",",
"msg",
",",
"slogan",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"kick_enabled",
":",
"return",
"if",
"target",
"not",
"in",
"self",
".",
"channels",
":",
"send",
"(",
"\"%s: you're lucky, private message kicking hasn't been implemented yet.\"",
"%",
"nick",
")",
"return",
"with",
"self",
".",
"data_lock",
":",
"ops",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"opers",
"[",
"target",
"]",
".",
"items",
"(",
")",
"if",
"v",
"]",
"botnick",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'nick'",
"]",
"if",
"botnick",
"not",
"in",
"ops",
":",
"ops",
"=",
"[",
"'someone'",
"]",
"if",
"not",
"ops",
"else",
"ops",
"send",
"(",
"textutils",
".",
"gen_creffett",
"(",
"\"%s: /op the bot\"",
"%",
"random",
".",
"choice",
"(",
"ops",
")",
")",
",",
"target",
"=",
"target",
")",
"elif",
"random",
".",
"random",
"(",
")",
"<",
"0.01",
"and",
"msg",
"==",
"\"shutting caps lock off\"",
":",
"if",
"nick",
"in",
"ops",
":",
"send",
"(",
"\"%s: HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U\"",
"%",
"nick",
",",
"target",
"=",
"target",
")",
"else",
":",
"self",
".",
"connection",
".",
"kick",
"(",
"target",
",",
"nick",
",",
"\"HUEHUEHUE GIBE CAPSLOCK PLS I REPORT U\"",
")",
"else",
":",
"msg",
"=",
"textutils",
".",
"gen_slogan",
"(",
"msg",
")",
".",
"upper",
"(",
")",
"if",
"slogan",
"else",
"msg",
"if",
"nick",
"in",
"ops",
":",
"send",
"(",
"\"%s: %s\"",
"%",
"(",
"nick",
",",
"msg",
")",
",",
"target",
"=",
"target",
")",
"else",
":",
"self",
".",
"connection",
".",
"kick",
"(",
"target",
",",
"nick",
",",
"msg",
")"
]
| Kick users.
- If kick is disabled, don't do anything.
- If the bot is not a op, rage at a op.
- Kick the user. | [
"Kick",
"users",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L345-L374 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_args | def do_args(self, modargs, send, nick, target, source, name, msgtype):
"""Handle the various args that modules need."""
realargs = {}
args = {
'nick': nick,
'handler': self,
'db': None,
'config': self.config,
'source': source,
'name': name,
'type': msgtype,
'botnick': self.connection.real_nickname,
'target': target if target[0] == "#" else "private",
'do_kick': lambda target, nick, msg: self.do_kick(send, target, nick, msg),
'is_admin': lambda nick: self.is_admin(send, nick),
'abuse': lambda nick, limit, cmd: self.abusecheck(send, nick, target, limit, cmd)
}
for arg in modargs:
if arg in args:
realargs[arg] = args[arg]
else:
raise Exception("Invalid Argument: %s" % arg)
return realargs | python | def do_args(self, modargs, send, nick, target, source, name, msgtype):
"""Handle the various args that modules need."""
realargs = {}
args = {
'nick': nick,
'handler': self,
'db': None,
'config': self.config,
'source': source,
'name': name,
'type': msgtype,
'botnick': self.connection.real_nickname,
'target': target if target[0] == "#" else "private",
'do_kick': lambda target, nick, msg: self.do_kick(send, target, nick, msg),
'is_admin': lambda nick: self.is_admin(send, nick),
'abuse': lambda nick, limit, cmd: self.abusecheck(send, nick, target, limit, cmd)
}
for arg in modargs:
if arg in args:
realargs[arg] = args[arg]
else:
raise Exception("Invalid Argument: %s" % arg)
return realargs | [
"def",
"do_args",
"(",
"self",
",",
"modargs",
",",
"send",
",",
"nick",
",",
"target",
",",
"source",
",",
"name",
",",
"msgtype",
")",
":",
"realargs",
"=",
"{",
"}",
"args",
"=",
"{",
"'nick'",
":",
"nick",
",",
"'handler'",
":",
"self",
",",
"'db'",
":",
"None",
",",
"'config'",
":",
"self",
".",
"config",
",",
"'source'",
":",
"source",
",",
"'name'",
":",
"name",
",",
"'type'",
":",
"msgtype",
",",
"'botnick'",
":",
"self",
".",
"connection",
".",
"real_nickname",
",",
"'target'",
":",
"target",
"if",
"target",
"[",
"0",
"]",
"==",
"\"#\"",
"else",
"\"private\"",
",",
"'do_kick'",
":",
"lambda",
"target",
",",
"nick",
",",
"msg",
":",
"self",
".",
"do_kick",
"(",
"send",
",",
"target",
",",
"nick",
",",
"msg",
")",
",",
"'is_admin'",
":",
"lambda",
"nick",
":",
"self",
".",
"is_admin",
"(",
"send",
",",
"nick",
")",
",",
"'abuse'",
":",
"lambda",
"nick",
",",
"limit",
",",
"cmd",
":",
"self",
".",
"abusecheck",
"(",
"send",
",",
"nick",
",",
"target",
",",
"limit",
",",
"cmd",
")",
"}",
"for",
"arg",
"in",
"modargs",
":",
"if",
"arg",
"in",
"args",
":",
"realargs",
"[",
"arg",
"]",
"=",
"args",
"[",
"arg",
"]",
"else",
":",
"raise",
"Exception",
"(",
"\"Invalid Argument: %s\"",
"%",
"arg",
")",
"return",
"realargs"
]
| Handle the various args that modules need. | [
"Handle",
"the",
"various",
"args",
"that",
"modules",
"need",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L376-L398 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.do_welcome | def do_welcome(self):
"""Do setup when connected to server.
- Join the primary channel.
- Join the control channel.
"""
self.rate_limited_send('join', self.config['core']['channel'])
self.rate_limited_send('join', self.config['core']['ctrlchan'], self.config['auth']['ctrlkey'])
# We use this to pick up info on admins who aren't currently in a channel.
self.workers.defer(5, False, self.get_admins)
extrachans = self.config['core']['extrachans']
if extrachans:
for chan in [x.strip() for x in extrachans.split(',')]:
self.rate_limited_send('join', chan) | python | def do_welcome(self):
"""Do setup when connected to server.
- Join the primary channel.
- Join the control channel.
"""
self.rate_limited_send('join', self.config['core']['channel'])
self.rate_limited_send('join', self.config['core']['ctrlchan'], self.config['auth']['ctrlkey'])
# We use this to pick up info on admins who aren't currently in a channel.
self.workers.defer(5, False, self.get_admins)
extrachans = self.config['core']['extrachans']
if extrachans:
for chan in [x.strip() for x in extrachans.split(',')]:
self.rate_limited_send('join', chan) | [
"def",
"do_welcome",
"(",
"self",
")",
":",
"self",
".",
"rate_limited_send",
"(",
"'join'",
",",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
")",
"self",
".",
"rate_limited_send",
"(",
"'join'",
",",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
",",
"self",
".",
"config",
"[",
"'auth'",
"]",
"[",
"'ctrlkey'",
"]",
")",
"# We use this to pick up info on admins who aren't currently in a channel.",
"self",
".",
"workers",
".",
"defer",
"(",
"5",
",",
"False",
",",
"self",
".",
"get_admins",
")",
"extrachans",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'extrachans'",
"]",
"if",
"extrachans",
":",
"for",
"chan",
"in",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"extrachans",
".",
"split",
"(",
"','",
")",
"]",
":",
"self",
".",
"rate_limited_send",
"(",
"'join'",
",",
"chan",
")"
]
| Do setup when connected to server.
- Join the primary channel.
- Join the control channel. | [
"Do",
"setup",
"when",
"connected",
"to",
"server",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L400-L414 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.get_filtered_send | def get_filtered_send(self, cmdargs, send, target):
"""Parse out any filters."""
parser = arguments.ArgParser(self.config)
parser.add_argument('--filter')
try:
filterargs, remainder = parser.parse_known_args(cmdargs)
except arguments.ArgumentException as ex:
return str(ex), None
cmdargs = ' '.join(remainder)
if filterargs.filter is None:
return cmdargs, send
filter_list, output = textutils.append_filters(filterargs.filter)
if filter_list is None:
return output, None
# define a new send to handle filter chaining
def filtersend(msg, mtype='privmsg', target=target, ignore_length=False):
self.send(target, self.connection.real_nickname, msg, mtype, ignore_length, filters=filter_list)
return cmdargs, filtersend | python | def get_filtered_send(self, cmdargs, send, target):
"""Parse out any filters."""
parser = arguments.ArgParser(self.config)
parser.add_argument('--filter')
try:
filterargs, remainder = parser.parse_known_args(cmdargs)
except arguments.ArgumentException as ex:
return str(ex), None
cmdargs = ' '.join(remainder)
if filterargs.filter is None:
return cmdargs, send
filter_list, output = textutils.append_filters(filterargs.filter)
if filter_list is None:
return output, None
# define a new send to handle filter chaining
def filtersend(msg, mtype='privmsg', target=target, ignore_length=False):
self.send(target, self.connection.real_nickname, msg, mtype, ignore_length, filters=filter_list)
return cmdargs, filtersend | [
"def",
"get_filtered_send",
"(",
"self",
",",
"cmdargs",
",",
"send",
",",
"target",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"self",
".",
"config",
")",
"parser",
".",
"add_argument",
"(",
"'--filter'",
")",
"try",
":",
"filterargs",
",",
"remainder",
"=",
"parser",
".",
"parse_known_args",
"(",
"cmdargs",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"ex",
":",
"return",
"str",
"(",
"ex",
")",
",",
"None",
"cmdargs",
"=",
"' '",
".",
"join",
"(",
"remainder",
")",
"if",
"filterargs",
".",
"filter",
"is",
"None",
":",
"return",
"cmdargs",
",",
"send",
"filter_list",
",",
"output",
"=",
"textutils",
".",
"append_filters",
"(",
"filterargs",
".",
"filter",
")",
"if",
"filter_list",
"is",
"None",
":",
"return",
"output",
",",
"None",
"# define a new send to handle filter chaining",
"def",
"filtersend",
"(",
"msg",
",",
"mtype",
"=",
"'privmsg'",
",",
"target",
"=",
"target",
",",
"ignore_length",
"=",
"False",
")",
":",
"self",
".",
"send",
"(",
"target",
",",
"self",
".",
"connection",
".",
"real_nickname",
",",
"msg",
",",
"mtype",
",",
"ignore_length",
",",
"filters",
"=",
"filter_list",
")",
"return",
"cmdargs",
",",
"filtersend"
]
| Parse out any filters. | [
"Parse",
"out",
"any",
"filters",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L420-L439 | train |
tjcsl/cslbot | cslbot/helpers/handler.py | BotHandler.handle_msg | def handle_msg(self, c, e):
"""The Heart and Soul of IrcBot."""
if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']:
nick = e.source.nick
else:
nick = e.source
if e.arguments is None:
msg = ""
else:
msg = " ".join(e.arguments).strip()
# Send the response to private messages to the sending nick.
target = nick if e.type == 'privmsg' else e.target
def send(msg, mtype='privmsg', target=target, ignore_length=False):
self.send(target, self.connection.real_nickname, msg, mtype, ignore_length)
if e.type in [
'account', 'authenticate', 'bannedfromchan', 'cap', 'ctcpreply', 'error', 'featurelist', 'nosuchnick', 'nick', 'nicknameinuse',
'privnotice', 'welcome', 'whospcrpl'
]:
self.handle_event(msg, send, c, e)
return
# ignore empty messages
if not msg and e.type != 'join':
return
self.do_log(target, nick, msg, e.type)
if e.type == 'mode':
self.do_mode(target, msg, nick, send)
return
if e.type == 'join':
self.handle_join(c, e, target, send)
return
if e.type == 'part':
if nick == c.real_nickname:
send("Parted channel %s" % target, target=self.config['core']['ctrlchan'])
return
if e.type == 'kick':
self.handle_kick(c, e, target, send)
return
if e.target == self.config['core']['ctrlchan'] and self.is_admin(None, nick):
control.handle_ctrlchan(self, msg, nick, send)
if self.is_ignored(nick) and not self.is_admin(None, nick):
return
self.handle_hooks(send, nick, target, e, msg)
# We only process hooks for notices, not commands.
if e.type == 'pubnotice':
return
msg = misc.get_cmdchar(self.config, c, msg, e.type)
cmd_name, cmdargs = self.get_cmd(msg)
if registry.command_registry.is_registered(cmd_name):
self.run_cmd(send, nick, target, cmd_name, cmdargs, e)
# special commands
elif cmd_name == 'reload':
with self.db.session_scope() as session:
if session.query(orm.Permissions).filter(orm.Permissions.nick == nick).count():
send("Aye Aye Capt'n") | python | def handle_msg(self, c, e):
"""The Heart and Soul of IrcBot."""
if e.type not in ['authenticate', 'error', 'join', 'part', 'quit']:
nick = e.source.nick
else:
nick = e.source
if e.arguments is None:
msg = ""
else:
msg = " ".join(e.arguments).strip()
# Send the response to private messages to the sending nick.
target = nick if e.type == 'privmsg' else e.target
def send(msg, mtype='privmsg', target=target, ignore_length=False):
self.send(target, self.connection.real_nickname, msg, mtype, ignore_length)
if e.type in [
'account', 'authenticate', 'bannedfromchan', 'cap', 'ctcpreply', 'error', 'featurelist', 'nosuchnick', 'nick', 'nicknameinuse',
'privnotice', 'welcome', 'whospcrpl'
]:
self.handle_event(msg, send, c, e)
return
# ignore empty messages
if not msg and e.type != 'join':
return
self.do_log(target, nick, msg, e.type)
if e.type == 'mode':
self.do_mode(target, msg, nick, send)
return
if e.type == 'join':
self.handle_join(c, e, target, send)
return
if e.type == 'part':
if nick == c.real_nickname:
send("Parted channel %s" % target, target=self.config['core']['ctrlchan'])
return
if e.type == 'kick':
self.handle_kick(c, e, target, send)
return
if e.target == self.config['core']['ctrlchan'] and self.is_admin(None, nick):
control.handle_ctrlchan(self, msg, nick, send)
if self.is_ignored(nick) and not self.is_admin(None, nick):
return
self.handle_hooks(send, nick, target, e, msg)
# We only process hooks for notices, not commands.
if e.type == 'pubnotice':
return
msg = misc.get_cmdchar(self.config, c, msg, e.type)
cmd_name, cmdargs = self.get_cmd(msg)
if registry.command_registry.is_registered(cmd_name):
self.run_cmd(send, nick, target, cmd_name, cmdargs, e)
# special commands
elif cmd_name == 'reload':
with self.db.session_scope() as session:
if session.query(orm.Permissions).filter(orm.Permissions.nick == nick).count():
send("Aye Aye Capt'n") | [
"def",
"handle_msg",
"(",
"self",
",",
"c",
",",
"e",
")",
":",
"if",
"e",
".",
"type",
"not",
"in",
"[",
"'authenticate'",
",",
"'error'",
",",
"'join'",
",",
"'part'",
",",
"'quit'",
"]",
":",
"nick",
"=",
"e",
".",
"source",
".",
"nick",
"else",
":",
"nick",
"=",
"e",
".",
"source",
"if",
"e",
".",
"arguments",
"is",
"None",
":",
"msg",
"=",
"\"\"",
"else",
":",
"msg",
"=",
"\" \"",
".",
"join",
"(",
"e",
".",
"arguments",
")",
".",
"strip",
"(",
")",
"# Send the response to private messages to the sending nick.",
"target",
"=",
"nick",
"if",
"e",
".",
"type",
"==",
"'privmsg'",
"else",
"e",
".",
"target",
"def",
"send",
"(",
"msg",
",",
"mtype",
"=",
"'privmsg'",
",",
"target",
"=",
"target",
",",
"ignore_length",
"=",
"False",
")",
":",
"self",
".",
"send",
"(",
"target",
",",
"self",
".",
"connection",
".",
"real_nickname",
",",
"msg",
",",
"mtype",
",",
"ignore_length",
")",
"if",
"e",
".",
"type",
"in",
"[",
"'account'",
",",
"'authenticate'",
",",
"'bannedfromchan'",
",",
"'cap'",
",",
"'ctcpreply'",
",",
"'error'",
",",
"'featurelist'",
",",
"'nosuchnick'",
",",
"'nick'",
",",
"'nicknameinuse'",
",",
"'privnotice'",
",",
"'welcome'",
",",
"'whospcrpl'",
"]",
":",
"self",
".",
"handle_event",
"(",
"msg",
",",
"send",
",",
"c",
",",
"e",
")",
"return",
"# ignore empty messages",
"if",
"not",
"msg",
"and",
"e",
".",
"type",
"!=",
"'join'",
":",
"return",
"self",
".",
"do_log",
"(",
"target",
",",
"nick",
",",
"msg",
",",
"e",
".",
"type",
")",
"if",
"e",
".",
"type",
"==",
"'mode'",
":",
"self",
".",
"do_mode",
"(",
"target",
",",
"msg",
",",
"nick",
",",
"send",
")",
"return",
"if",
"e",
".",
"type",
"==",
"'join'",
":",
"self",
".",
"handle_join",
"(",
"c",
",",
"e",
",",
"target",
",",
"send",
")",
"return",
"if",
"e",
".",
"type",
"==",
"'part'",
":",
"if",
"nick",
"==",
"c",
".",
"real_nickname",
":",
"send",
"(",
"\"Parted channel %s\"",
"%",
"target",
",",
"target",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
")",
"return",
"if",
"e",
".",
"type",
"==",
"'kick'",
":",
"self",
".",
"handle_kick",
"(",
"c",
",",
"e",
",",
"target",
",",
"send",
")",
"return",
"if",
"e",
".",
"target",
"==",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'ctrlchan'",
"]",
"and",
"self",
".",
"is_admin",
"(",
"None",
",",
"nick",
")",
":",
"control",
".",
"handle_ctrlchan",
"(",
"self",
",",
"msg",
",",
"nick",
",",
"send",
")",
"if",
"self",
".",
"is_ignored",
"(",
"nick",
")",
"and",
"not",
"self",
".",
"is_admin",
"(",
"None",
",",
"nick",
")",
":",
"return",
"self",
".",
"handle_hooks",
"(",
"send",
",",
"nick",
",",
"target",
",",
"e",
",",
"msg",
")",
"# We only process hooks for notices, not commands.",
"if",
"e",
".",
"type",
"==",
"'pubnotice'",
":",
"return",
"msg",
"=",
"misc",
".",
"get_cmdchar",
"(",
"self",
".",
"config",
",",
"c",
",",
"msg",
",",
"e",
".",
"type",
")",
"cmd_name",
",",
"cmdargs",
"=",
"self",
".",
"get_cmd",
"(",
"msg",
")",
"if",
"registry",
".",
"command_registry",
".",
"is_registered",
"(",
"cmd_name",
")",
":",
"self",
".",
"run_cmd",
"(",
"send",
",",
"nick",
",",
"target",
",",
"cmd_name",
",",
"cmdargs",
",",
"e",
")",
"# special commands",
"elif",
"cmd_name",
"==",
"'reload'",
":",
"with",
"self",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"if",
"session",
".",
"query",
"(",
"orm",
".",
"Permissions",
")",
".",
"filter",
"(",
"orm",
".",
"Permissions",
".",
"nick",
"==",
"nick",
")",
".",
"count",
"(",
")",
":",
"send",
"(",
"\"Aye Aye Capt'n\"",
")"
]
| The Heart and Soul of IrcBot. | [
"The",
"Heart",
"and",
"Soul",
"of",
"IrcBot",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/handler.py#L605-L675 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_tag | def process_tag(self, tag):
"""Processes tag and detects which function to use"""
try:
if not self._is_function(tag):
self._tag_type_processor[tag.data_type](tag)
except KeyError as ex:
raise Exception('Tag type {0} not recognized for tag {1}'
.format(
tag.data_type,
tag.name),
ex) | python | def process_tag(self, tag):
"""Processes tag and detects which function to use"""
try:
if not self._is_function(tag):
self._tag_type_processor[tag.data_type](tag)
except KeyError as ex:
raise Exception('Tag type {0} not recognized for tag {1}'
.format(
tag.data_type,
tag.name),
ex) | [
"def",
"process_tag",
"(",
"self",
",",
"tag",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_is_function",
"(",
"tag",
")",
":",
"self",
".",
"_tag_type_processor",
"[",
"tag",
".",
"data_type",
"]",
"(",
"tag",
")",
"except",
"KeyError",
"as",
"ex",
":",
"raise",
"Exception",
"(",
"'Tag type {0} not recognized for tag {1}'",
".",
"format",
"(",
"tag",
".",
"data_type",
",",
"tag",
".",
"name",
")",
",",
"ex",
")"
]
| Processes tag and detects which function to use | [
"Processes",
"tag",
"and",
"detects",
"which",
"function",
"to",
"use"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L48-L58 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_boolean | def process_boolean(self, tag):
"""Process Boolean type tags"""
tag.set_address(self.normal_register.current_bit_address)
self.normal_register.move_to_next_bit_address() | python | def process_boolean(self, tag):
"""Process Boolean type tags"""
tag.set_address(self.normal_register.current_bit_address)
self.normal_register.move_to_next_bit_address() | [
"def",
"process_boolean",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"normal_register",
".",
"current_bit_address",
")",
"self",
".",
"normal_register",
".",
"move_to_next_bit_address",
"(",
")"
]
| Process Boolean type tags | [
"Process",
"Boolean",
"type",
"tags"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L61-L64 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_boolean_array | def process_boolean_array(self, tag):
"""Process Boolean array type tags"""
array_size = tag.get_array_size()
tag.set_address(self.normal_register.get_array(array_size))
if self.is_sixteen_bit:
# each boolean address needs 1/16 byte
self.normal_register.move_to_next_address((array_size / 16) + 1)
return
# each boolean address needs 1/8 byte
self.normal_register.move_to_next_address((array_size / 8) + 1) | python | def process_boolean_array(self, tag):
"""Process Boolean array type tags"""
array_size = tag.get_array_size()
tag.set_address(self.normal_register.get_array(array_size))
if self.is_sixteen_bit:
# each boolean address needs 1/16 byte
self.normal_register.move_to_next_address((array_size / 16) + 1)
return
# each boolean address needs 1/8 byte
self.normal_register.move_to_next_address((array_size / 8) + 1) | [
"def",
"process_boolean_array",
"(",
"self",
",",
"tag",
")",
":",
"array_size",
"=",
"tag",
".",
"get_array_size",
"(",
")",
"tag",
".",
"set_address",
"(",
"self",
".",
"normal_register",
".",
"get_array",
"(",
"array_size",
")",
")",
"if",
"self",
".",
"is_sixteen_bit",
":",
"# each boolean address needs 1/16 byte",
"self",
".",
"normal_register",
".",
"move_to_next_address",
"(",
"(",
"array_size",
"/",
"16",
")",
"+",
"1",
")",
"return",
"# each boolean address needs 1/8 byte",
"self",
".",
"normal_register",
".",
"move_to_next_address",
"(",
"(",
"array_size",
"/",
"8",
")",
"+",
"1",
")"
]
| Process Boolean array type tags | [
"Process",
"Boolean",
"array",
"type",
"tags"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L66-L75 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_byte | def process_byte(self, tag):
"""Process byte type tags"""
tag.set_address(self.normal_register.current_address)
# each address needs 1 byte
self.normal_register.move_to_next_address(1) | python | def process_byte(self, tag):
"""Process byte type tags"""
tag.set_address(self.normal_register.current_address)
# each address needs 1 byte
self.normal_register.move_to_next_address(1) | [
"def",
"process_byte",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"normal_register",
".",
"current_address",
")",
"# each address needs 1 byte",
"self",
".",
"normal_register",
".",
"move_to_next_address",
"(",
"1",
")"
]
| Process byte type tags | [
"Process",
"byte",
"type",
"tags"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L77-L81 | train |
jmbeach/KEP.py | src/keppy/simulator_device.py | SimulatorDevice.process_string | def process_string(self, tag):
"""Process string type tags"""
tag.set_address(self.string_register.current_address)
if self.is_sixteen_bit:
# each string address needs 1 byte = 1/2 an address
self.string_register.move_to_next_address(1)
return
# each string address needs 1 byte = 1 address
self.string_register.move_to_next_address(1) | python | def process_string(self, tag):
"""Process string type tags"""
tag.set_address(self.string_register.current_address)
if self.is_sixteen_bit:
# each string address needs 1 byte = 1/2 an address
self.string_register.move_to_next_address(1)
return
# each string address needs 1 byte = 1 address
self.string_register.move_to_next_address(1) | [
"def",
"process_string",
"(",
"self",
",",
"tag",
")",
":",
"tag",
".",
"set_address",
"(",
"self",
".",
"string_register",
".",
"current_address",
")",
"if",
"self",
".",
"is_sixteen_bit",
":",
"# each string address needs 1 byte = 1/2 an address",
"self",
".",
"string_register",
".",
"move_to_next_address",
"(",
"1",
")",
"return",
"# each string address needs 1 byte = 1 address",
"self",
".",
"string_register",
".",
"move_to_next_address",
"(",
"1",
")"
]
| Process string type tags | [
"Process",
"string",
"type",
"tags"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/simulator_device.py#L166-L174 | train |
tjcsl/cslbot | cslbot/commands/microwave.py | cmd | def cmd(send, msg, args):
"""Microwaves something.
Syntax: {command} <level> <target>
"""
nick = args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
levels = {
1: 'Whirr...',
2: 'Vrrm...',
3: 'Zzzzhhhh...',
4: 'SHFRRRRM...',
5: 'GEEEEZZSH...',
6: 'PLAAAAIIID...',
7: 'KKKRRRAAKKKAAKRAKKGGARGHGIZZZZ...',
8: 'Nuke',
9: 'nneeeaaaooowwwwww..... BOOOOOSH BLAM KABOOM',
10: 'ssh [email protected] rm -rf ~%s'
}
if not msg:
send('What to microwave?')
return
match = re.match('(-?[0-9]*) (.*)', msg)
if not match:
send('Power level?')
else:
level = int(match.group(1))
target = match.group(2)
if level > 10:
send('Aborting to prevent extinction of human race.')
return
if level < 1:
send('Anti-matter not yet implemented.')
return
if level > 7:
if not args['is_admin'](nick):
send("I'm sorry. Nukes are a admin-only feature")
return
elif msg == args['botnick']:
send("Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.")
else:
with args['handler'].data_lock:
if target not in args['handler'].channels[channel].users():
send("I'm sorry. Anonymous Nuking is not allowed")
return
msg = levels[1]
for i in range(2, level + 1):
if i < 8:
msg += ' ' + levels[i]
send(msg)
if level >= 8:
do_nuke(args['handler'].connection, nick, target, channel)
if level >= 9:
send(levels[9])
if level == 10:
send(levels[10] % target)
send('Ding, your %s is ready.' % target) | python | def cmd(send, msg, args):
"""Microwaves something.
Syntax: {command} <level> <target>
"""
nick = args['nick']
channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel']
levels = {
1: 'Whirr...',
2: 'Vrrm...',
3: 'Zzzzhhhh...',
4: 'SHFRRRRM...',
5: 'GEEEEZZSH...',
6: 'PLAAAAIIID...',
7: 'KKKRRRAAKKKAAKRAKKGGARGHGIZZZZ...',
8: 'Nuke',
9: 'nneeeaaaooowwwwww..... BOOOOOSH BLAM KABOOM',
10: 'ssh [email protected] rm -rf ~%s'
}
if not msg:
send('What to microwave?')
return
match = re.match('(-?[0-9]*) (.*)', msg)
if not match:
send('Power level?')
else:
level = int(match.group(1))
target = match.group(2)
if level > 10:
send('Aborting to prevent extinction of human race.')
return
if level < 1:
send('Anti-matter not yet implemented.')
return
if level > 7:
if not args['is_admin'](nick):
send("I'm sorry. Nukes are a admin-only feature")
return
elif msg == args['botnick']:
send("Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.")
else:
with args['handler'].data_lock:
if target not in args['handler'].channels[channel].users():
send("I'm sorry. Anonymous Nuking is not allowed")
return
msg = levels[1]
for i in range(2, level + 1):
if i < 8:
msg += ' ' + levels[i]
send(msg)
if level >= 8:
do_nuke(args['handler'].connection, nick, target, channel)
if level >= 9:
send(levels[9])
if level == 10:
send(levels[10] % target)
send('Ding, your %s is ready.' % target) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"nick",
"=",
"args",
"[",
"'nick'",
"]",
"channel",
"=",
"args",
"[",
"'target'",
"]",
"if",
"args",
"[",
"'target'",
"]",
"!=",
"'private'",
"else",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'channel'",
"]",
"levels",
"=",
"{",
"1",
":",
"'Whirr...'",
",",
"2",
":",
"'Vrrm...'",
",",
"3",
":",
"'Zzzzhhhh...'",
",",
"4",
":",
"'SHFRRRRM...'",
",",
"5",
":",
"'GEEEEZZSH...'",
",",
"6",
":",
"'PLAAAAIIID...'",
",",
"7",
":",
"'KKKRRRAAKKKAAKRAKKGGARGHGIZZZZ...'",
",",
"8",
":",
"'Nuke'",
",",
"9",
":",
"'nneeeaaaooowwwwww..... BOOOOOSH BLAM KABOOM'",
",",
"10",
":",
"'ssh [email protected] rm -rf ~%s'",
"}",
"if",
"not",
"msg",
":",
"send",
"(",
"'What to microwave?'",
")",
"return",
"match",
"=",
"re",
".",
"match",
"(",
"'(-?[0-9]*) (.*)'",
",",
"msg",
")",
"if",
"not",
"match",
":",
"send",
"(",
"'Power level?'",
")",
"else",
":",
"level",
"=",
"int",
"(",
"match",
".",
"group",
"(",
"1",
")",
")",
"target",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"level",
">",
"10",
":",
"send",
"(",
"'Aborting to prevent extinction of human race.'",
")",
"return",
"if",
"level",
"<",
"1",
":",
"send",
"(",
"'Anti-matter not yet implemented.'",
")",
"return",
"if",
"level",
">",
"7",
":",
"if",
"not",
"args",
"[",
"'is_admin'",
"]",
"(",
"nick",
")",
":",
"send",
"(",
"\"I'm sorry. Nukes are a admin-only feature\"",
")",
"return",
"elif",
"msg",
"==",
"args",
"[",
"'botnick'",
"]",
":",
"send",
"(",
"\"Sorry, Self-Nuking is disabled pending aquisition of a Lead-Lined Fridge.\"",
")",
"else",
":",
"with",
"args",
"[",
"'handler'",
"]",
".",
"data_lock",
":",
"if",
"target",
"not",
"in",
"args",
"[",
"'handler'",
"]",
".",
"channels",
"[",
"channel",
"]",
".",
"users",
"(",
")",
":",
"send",
"(",
"\"I'm sorry. Anonymous Nuking is not allowed\"",
")",
"return",
"msg",
"=",
"levels",
"[",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"level",
"+",
"1",
")",
":",
"if",
"i",
"<",
"8",
":",
"msg",
"+=",
"' '",
"+",
"levels",
"[",
"i",
"]",
"send",
"(",
"msg",
")",
"if",
"level",
">=",
"8",
":",
"do_nuke",
"(",
"args",
"[",
"'handler'",
"]",
".",
"connection",
",",
"nick",
",",
"target",
",",
"channel",
")",
"if",
"level",
">=",
"9",
":",
"send",
"(",
"levels",
"[",
"9",
"]",
")",
"if",
"level",
"==",
"10",
":",
"send",
"(",
"levels",
"[",
"10",
"]",
"%",
"target",
")",
"send",
"(",
"'Ding, your %s is ready.'",
"%",
"target",
")"
]
| Microwaves something.
Syntax: {command} <level> <target> | [
"Microwaves",
"something",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/microwave.py#L25-L83 | train |
fabaff/python-opensensemap-api | example.py | main | async def main():
"""Sample code to retrieve the data from an OpenSenseMap station."""
async with aiohttp.ClientSession() as session:
station = OpenSenseMap(SENSOR_ID, loop, session)
# Print details about the given station
await station.get_data()
print("Name:", station.name)
print("Description:", station.description)
print("Coordinates:", station.coordinates)
print("PM 2.5:", station.pm2_5)
print("PM 10:", station.pm10)
print("Temperature:", station.temperature) | python | async def main():
"""Sample code to retrieve the data from an OpenSenseMap station."""
async with aiohttp.ClientSession() as session:
station = OpenSenseMap(SENSOR_ID, loop, session)
# Print details about the given station
await station.get_data()
print("Name:", station.name)
print("Description:", station.description)
print("Coordinates:", station.coordinates)
print("PM 2.5:", station.pm2_5)
print("PM 10:", station.pm10)
print("Temperature:", station.temperature) | [
"async",
"def",
"main",
"(",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"station",
"=",
"OpenSenseMap",
"(",
"SENSOR_ID",
",",
"loop",
",",
"session",
")",
"# Print details about the given station",
"await",
"station",
".",
"get_data",
"(",
")",
"print",
"(",
"\"Name:\"",
",",
"station",
".",
"name",
")",
"print",
"(",
"\"Description:\"",
",",
"station",
".",
"description",
")",
"print",
"(",
"\"Coordinates:\"",
",",
"station",
".",
"coordinates",
")",
"print",
"(",
"\"PM 2.5:\"",
",",
"station",
".",
"pm2_5",
")",
"print",
"(",
"\"PM 10:\"",
",",
"station",
".",
"pm10",
")",
"print",
"(",
"\"Temperature:\"",
",",
"station",
".",
"temperature",
")"
]
| Sample code to retrieve the data from an OpenSenseMap station. | [
"Sample",
"code",
"to",
"retrieve",
"the",
"data",
"from",
"an",
"OpenSenseMap",
"station",
"."
]
| 3c4f5473c514185087aae5d766ab4d5736ec1f30 | https://github.com/fabaff/python-opensensemap-api/blob/3c4f5473c514185087aae5d766ab4d5736ec1f30/example.py#L11-L26 | train |
adamheins/r12 | r12/shell.py | ShellStyle.theme | def theme(self, text):
''' Theme style. '''
return self.theme_color + self.BRIGHT + text + self.RESET | python | def theme(self, text):
''' Theme style. '''
return self.theme_color + self.BRIGHT + text + self.RESET | [
"def",
"theme",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"theme_color",
"+",
"self",
".",
"BRIGHT",
"+",
"text",
"+",
"self",
".",
"RESET"
]
| Theme style. | [
"Theme",
"style",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L33-L35 | train |
adamheins/r12 | r12/shell.py | ShellStyle._label_desc | def _label_desc(self, label, desc, label_color=''):
''' Generic styler for a line consisting of a label and description. '''
return self.BRIGHT + label_color + label + self.RESET + desc | python | def _label_desc(self, label, desc, label_color=''):
''' Generic styler for a line consisting of a label and description. '''
return self.BRIGHT + label_color + label + self.RESET + desc | [
"def",
"_label_desc",
"(",
"self",
",",
"label",
",",
"desc",
",",
"label_color",
"=",
"''",
")",
":",
"return",
"self",
".",
"BRIGHT",
"+",
"label_color",
"+",
"label",
"+",
"self",
".",
"RESET",
"+",
"desc"
]
| Generic styler for a line consisting of a label and description. | [
"Generic",
"styler",
"for",
"a",
"line",
"consisting",
"of",
"a",
"label",
"and",
"description",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L38-L40 | train |
adamheins/r12 | r12/shell.py | ShellStyle.error | def error(self, cmd, desc=''):
''' Style for an error message. '''
return self._label_desc(cmd, desc, self.error_color) | python | def error(self, cmd, desc=''):
''' Style for an error message. '''
return self._label_desc(cmd, desc, self.error_color) | [
"def",
"error",
"(",
"self",
",",
"cmd",
",",
"desc",
"=",
"''",
")",
":",
"return",
"self",
".",
"_label_desc",
"(",
"cmd",
",",
"desc",
",",
"self",
".",
"error_color",
")"
]
| Style for an error message. | [
"Style",
"for",
"an",
"error",
"message",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L48-L50 | train |
adamheins/r12 | r12/shell.py | ShellStyle.warn | def warn(self, cmd, desc=''):
''' Style for warning message. '''
return self._label_desc(cmd, desc, self.warn_color) | python | def warn(self, cmd, desc=''):
''' Style for warning message. '''
return self._label_desc(cmd, desc, self.warn_color) | [
"def",
"warn",
"(",
"self",
",",
"cmd",
",",
"desc",
"=",
"''",
")",
":",
"return",
"self",
".",
"_label_desc",
"(",
"cmd",
",",
"desc",
",",
"self",
".",
"warn_color",
")"
]
| Style for warning message. | [
"Style",
"for",
"warning",
"message",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L53-L55 | train |
adamheins/r12 | r12/shell.py | ShellStyle.success | def success(self, cmd, desc=''):
''' Style for a success message. '''
return self._label_desc(cmd, desc, self.success_color) | python | def success(self, cmd, desc=''):
''' Style for a success message. '''
return self._label_desc(cmd, desc, self.success_color) | [
"def",
"success",
"(",
"self",
",",
"cmd",
",",
"desc",
"=",
"''",
")",
":",
"return",
"self",
".",
"_label_desc",
"(",
"cmd",
",",
"desc",
",",
"self",
".",
"success_color",
")"
]
| Style for a success message. | [
"Style",
"for",
"a",
"success",
"message",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L58-L60 | train |
adamheins/r12 | r12/shell.py | ArmShell.cmdloop | def cmdloop(self, intro=None):
''' Override the command loop to handle Ctrl-C. '''
self.preloop()
# Set up completion with readline.
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey + ': complete')
except ImportError:
pass
try:
if intro is not None:
self.intro = intro
if self.intro:
self.stdout.write(str(self.intro)+"\n")
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
if self.use_rawinput:
try:
if sys.version_info[0] == 2:
line = raw_input(self.prompt)
else:
line = input(self.prompt)
except EOFError:
line = 'EOF'
except KeyboardInterrupt:
line = 'ctrlc'
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = 'EOF'
else:
line = line.rstrip('\r\n')
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
finally:
if self.use_rawinput and self.completekey:
try:
import readline
readline.set_completer(self.old_completer)
except ImportError:
pass | python | def cmdloop(self, intro=None):
''' Override the command loop to handle Ctrl-C. '''
self.preloop()
# Set up completion with readline.
if self.use_rawinput and self.completekey:
try:
import readline
self.old_completer = readline.get_completer()
readline.set_completer(self.complete)
readline.parse_and_bind(self.completekey + ': complete')
except ImportError:
pass
try:
if intro is not None:
self.intro = intro
if self.intro:
self.stdout.write(str(self.intro)+"\n")
stop = None
while not stop:
if self.cmdqueue:
line = self.cmdqueue.pop(0)
else:
if self.use_rawinput:
try:
if sys.version_info[0] == 2:
line = raw_input(self.prompt)
else:
line = input(self.prompt)
except EOFError:
line = 'EOF'
except KeyboardInterrupt:
line = 'ctrlc'
else:
self.stdout.write(self.prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = 'EOF'
else:
line = line.rstrip('\r\n')
line = self.precmd(line)
stop = self.onecmd(line)
stop = self.postcmd(stop, line)
self.postloop()
finally:
if self.use_rawinput and self.completekey:
try:
import readline
readline.set_completer(self.old_completer)
except ImportError:
pass | [
"def",
"cmdloop",
"(",
"self",
",",
"intro",
"=",
"None",
")",
":",
"self",
".",
"preloop",
"(",
")",
"# Set up completion with readline.",
"if",
"self",
".",
"use_rawinput",
"and",
"self",
".",
"completekey",
":",
"try",
":",
"import",
"readline",
"self",
".",
"old_completer",
"=",
"readline",
".",
"get_completer",
"(",
")",
"readline",
".",
"set_completer",
"(",
"self",
".",
"complete",
")",
"readline",
".",
"parse_and_bind",
"(",
"self",
".",
"completekey",
"+",
"': complete'",
")",
"except",
"ImportError",
":",
"pass",
"try",
":",
"if",
"intro",
"is",
"not",
"None",
":",
"self",
".",
"intro",
"=",
"intro",
"if",
"self",
".",
"intro",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"self",
".",
"intro",
")",
"+",
"\"\\n\"",
")",
"stop",
"=",
"None",
"while",
"not",
"stop",
":",
"if",
"self",
".",
"cmdqueue",
":",
"line",
"=",
"self",
".",
"cmdqueue",
".",
"pop",
"(",
"0",
")",
"else",
":",
"if",
"self",
".",
"use_rawinput",
":",
"try",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"line",
"=",
"raw_input",
"(",
"self",
".",
"prompt",
")",
"else",
":",
"line",
"=",
"input",
"(",
"self",
".",
"prompt",
")",
"except",
"EOFError",
":",
"line",
"=",
"'EOF'",
"except",
"KeyboardInterrupt",
":",
"line",
"=",
"'ctrlc'",
"else",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"prompt",
")",
"self",
".",
"stdout",
".",
"flush",
"(",
")",
"line",
"=",
"self",
".",
"stdin",
".",
"readline",
"(",
")",
"if",
"not",
"len",
"(",
"line",
")",
":",
"line",
"=",
"'EOF'",
"else",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"line",
"=",
"self",
".",
"precmd",
"(",
"line",
")",
"stop",
"=",
"self",
".",
"onecmd",
"(",
"line",
")",
"stop",
"=",
"self",
".",
"postcmd",
"(",
"stop",
",",
"line",
")",
"self",
".",
"postloop",
"(",
")",
"finally",
":",
"if",
"self",
".",
"use_rawinput",
"and",
"self",
".",
"completekey",
":",
"try",
":",
"import",
"readline",
"readline",
".",
"set_completer",
"(",
"self",
".",
"old_completer",
")",
"except",
"ImportError",
":",
"pass"
]
| Override the command loop to handle Ctrl-C. | [
"Override",
"the",
"command",
"loop",
"to",
"handle",
"Ctrl",
"-",
"C",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L95-L147 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_exit | def do_exit(self, arg):
''' Exit the shell. '''
if self.arm.is_connected():
self.arm.disconnect()
print('Bye!')
return True | python | def do_exit(self, arg):
''' Exit the shell. '''
if self.arm.is_connected():
self.arm.disconnect()
print('Bye!')
return True | [
"def",
"do_exit",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"arm",
".",
"disconnect",
"(",
")",
"print",
"(",
"'Bye!'",
")",
"return",
"True"
]
| Exit the shell. | [
"Exit",
"the",
"shell",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L150-L155 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_ctrlc | def do_ctrlc(self, arg):
''' Ctrl-C sends a STOP command to the arm. '''
print('STOP')
if self.arm.is_connected():
self.arm.write('STOP') | python | def do_ctrlc(self, arg):
''' Ctrl-C sends a STOP command to the arm. '''
print('STOP')
if self.arm.is_connected():
self.arm.write('STOP') | [
"def",
"do_ctrlc",
"(",
"self",
",",
"arg",
")",
":",
"print",
"(",
"'STOP'",
")",
"if",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"self",
".",
"arm",
".",
"write",
"(",
"'STOP'",
")"
]
| Ctrl-C sends a STOP command to the arm. | [
"Ctrl",
"-",
"C",
"sends",
"a",
"STOP",
"command",
"to",
"the",
"arm",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L158-L162 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_status | def do_status(self, arg):
''' Print information about the arm. '''
info = self.arm.get_info()
max_len = len(max(info.keys(), key=len))
print(self.style.theme('\nArm Status'))
for key, value in info.items():
print(self.style.help(key.ljust(max_len + 2), str(value)))
print() | python | def do_status(self, arg):
''' Print information about the arm. '''
info = self.arm.get_info()
max_len = len(max(info.keys(), key=len))
print(self.style.theme('\nArm Status'))
for key, value in info.items():
print(self.style.help(key.ljust(max_len + 2), str(value)))
print() | [
"def",
"do_status",
"(",
"self",
",",
"arg",
")",
":",
"info",
"=",
"self",
".",
"arm",
".",
"get_info",
"(",
")",
"max_len",
"=",
"len",
"(",
"max",
"(",
"info",
".",
"keys",
"(",
")",
",",
"key",
"=",
"len",
")",
")",
"print",
"(",
"self",
".",
"style",
".",
"theme",
"(",
"'\\nArm Status'",
")",
")",
"for",
"key",
",",
"value",
"in",
"info",
".",
"items",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"help",
"(",
"key",
".",
"ljust",
"(",
"max_len",
"+",
"2",
")",
",",
"str",
"(",
"value",
")",
")",
")",
"print",
"(",
")"
]
| Print information about the arm. | [
"Print",
"information",
"about",
"the",
"arm",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L180-L188 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_connect | def do_connect(self, arg):
''' Connect to the arm. '''
if self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already connected.'))
else:
try:
port = self.arm.connect()
print(self.style.success('Success: ',
'Connected to \'{}\'.'.format(port)))
except r12.ArmException as e:
print(self.style.error('Error: ', str(e))) | python | def do_connect(self, arg):
''' Connect to the arm. '''
if self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already connected.'))
else:
try:
port = self.arm.connect()
print(self.style.success('Success: ',
'Connected to \'{}\'.'.format(port)))
except r12.ArmException as e:
print(self.style.error('Error: ', str(e))) | [
"def",
"do_connect",
"(",
"self",
",",
"arg",
")",
":",
"if",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is already connected.'",
")",
")",
"else",
":",
"try",
":",
"port",
"=",
"self",
".",
"arm",
".",
"connect",
"(",
")",
"print",
"(",
"self",
".",
"style",
".",
"success",
"(",
"'Success: '",
",",
"'Connected to \\'{}\\'.'",
".",
"format",
"(",
"port",
")",
")",
")",
"except",
"r12",
".",
"ArmException",
"as",
"e",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"str",
"(",
"e",
")",
")",
")"
]
| Connect to the arm. | [
"Connect",
"to",
"the",
"arm",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L191-L201 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_disconnect | def do_disconnect(self, arg):
''' Disconnect from the arm. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already disconnected.'))
else:
self.arm.disconnect()
print(self.style.success('Success: ', 'Disconnected.')) | python | def do_disconnect(self, arg):
''' Disconnect from the arm. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is already disconnected.'))
else:
self.arm.disconnect()
print(self.style.success('Success: ', 'Disconnected.')) | [
"def",
"do_disconnect",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is already disconnected.'",
")",
")",
"else",
":",
"self",
".",
"arm",
".",
"disconnect",
"(",
")",
"print",
"(",
"self",
".",
"style",
".",
"success",
"(",
"'Success: '",
",",
"'Disconnected.'",
")",
")"
]
| Disconnect from the arm. | [
"Disconnect",
"from",
"the",
"arm",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L204-L210 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_run | def do_run(self, arg):
''' Load and run an external FORTH script. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
# Load the script.
try:
with open(arg) as f:
lines = [line.strip() for line in f.readlines()]
except IOError:
print(self.style.error('Error: ',
'Could not load file \'{}\'.'.format(arg)))
return
for line in lines:
if self.wrapper:
line = self.wrapper.wrap_input(line)
self.arm.write(line)
res = self.arm.read()
if self.wrapper:
res = self.wrapper.wrap_output(res)
print(res) | python | def do_run(self, arg):
''' Load and run an external FORTH script. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
# Load the script.
try:
with open(arg) as f:
lines = [line.strip() for line in f.readlines()]
except IOError:
print(self.style.error('Error: ',
'Could not load file \'{}\'.'.format(arg)))
return
for line in lines:
if self.wrapper:
line = self.wrapper.wrap_input(line)
self.arm.write(line)
res = self.arm.read()
if self.wrapper:
res = self.wrapper.wrap_output(res)
print(res) | [
"def",
"do_run",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is not connected.'",
")",
")",
"return",
"# Load the script.",
"try",
":",
"with",
"open",
"(",
"arg",
")",
"as",
"f",
":",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"f",
".",
"readlines",
"(",
")",
"]",
"except",
"IOError",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Could not load file \\'{}\\'.'",
".",
"format",
"(",
"arg",
")",
")",
")",
"return",
"for",
"line",
"in",
"lines",
":",
"if",
"self",
".",
"wrapper",
":",
"line",
"=",
"self",
".",
"wrapper",
".",
"wrap_input",
"(",
"line",
")",
"self",
".",
"arm",
".",
"write",
"(",
"line",
")",
"res",
"=",
"self",
".",
"arm",
".",
"read",
"(",
")",
"if",
"self",
".",
"wrapper",
":",
"res",
"=",
"self",
".",
"wrapper",
".",
"wrap_output",
"(",
"res",
")",
"print",
"(",
"res",
")"
]
| Load and run an external FORTH script. | [
"Load",
"and",
"run",
"an",
"external",
"FORTH",
"script",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L213-L235 | train |
adamheins/r12 | r12/shell.py | ArmShell.do_dump | def do_dump(self, arg):
''' Output all bytes waiting in output queue. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
print(self.arm.dump()) | python | def do_dump(self, arg):
''' Output all bytes waiting in output queue. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
print(self.arm.dump()) | [
"def",
"do_dump",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is not connected.'",
")",
")",
"return",
"print",
"(",
"self",
".",
"arm",
".",
"dump",
"(",
")",
")"
]
| Output all bytes waiting in output queue. | [
"Output",
"all",
"bytes",
"waiting",
"in",
"output",
"queue",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L238-L243 | train |
adamheins/r12 | r12/shell.py | ArmShell.complete_run | def complete_run(self, text, line, b, e):
''' Autocomplete file names with .forth ending. '''
# Don't break on path separators.
text = line.split()[-1]
# Try to find files with a forth file ending, .fs.
forth_files = glob.glob(text + '*.fs')
# Failing that, just try and complete something.
if len(forth_files) == 0:
return [f.split(os.path.sep)[-1] for f in glob.glob(text + '*')]
forth_files = [f.split(os.path.sep)[-1] for f in forth_files]
return forth_files | python | def complete_run(self, text, line, b, e):
''' Autocomplete file names with .forth ending. '''
# Don't break on path separators.
text = line.split()[-1]
# Try to find files with a forth file ending, .fs.
forth_files = glob.glob(text + '*.fs')
# Failing that, just try and complete something.
if len(forth_files) == 0:
return [f.split(os.path.sep)[-1] for f in glob.glob(text + '*')]
forth_files = [f.split(os.path.sep)[-1] for f in forth_files]
return forth_files | [
"def",
"complete_run",
"(",
"self",
",",
"text",
",",
"line",
",",
"b",
",",
"e",
")",
":",
"# Don't break on path separators.",
"text",
"=",
"line",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
"# Try to find files with a forth file ending, .fs.",
"forth_files",
"=",
"glob",
".",
"glob",
"(",
"text",
"+",
"'*.fs'",
")",
"# Failing that, just try and complete something.",
"if",
"len",
"(",
"forth_files",
")",
"==",
"0",
":",
"return",
"[",
"f",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"[",
"-",
"1",
"]",
"for",
"f",
"in",
"glob",
".",
"glob",
"(",
"text",
"+",
"'*'",
")",
"]",
"forth_files",
"=",
"[",
"f",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
"[",
"-",
"1",
"]",
"for",
"f",
"in",
"forth_files",
"]",
"return",
"forth_files"
]
| Autocomplete file names with .forth ending. | [
"Autocomplete",
"file",
"names",
"with",
".",
"forth",
"ending",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L251-L264 | train |
adamheins/r12 | r12/shell.py | ArmShell.get_names | def get_names(self):
''' Get names for autocompletion. '''
# Overridden to support autocompletion for the ROBOFORTH commands.
return (['do_' + x for x in self.commands['shell']]
+ ['do_' + x for x in self.commands['forth']]) | python | def get_names(self):
''' Get names for autocompletion. '''
# Overridden to support autocompletion for the ROBOFORTH commands.
return (['do_' + x for x in self.commands['shell']]
+ ['do_' + x for x in self.commands['forth']]) | [
"def",
"get_names",
"(",
"self",
")",
":",
"# Overridden to support autocompletion for the ROBOFORTH commands.",
"return",
"(",
"[",
"'do_'",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"commands",
"[",
"'shell'",
"]",
"]",
"+",
"[",
"'do_'",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"commands",
"[",
"'forth'",
"]",
"]",
")"
]
| Get names for autocompletion. | [
"Get",
"names",
"for",
"autocompletion",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L297-L301 | train |
adamheins/r12 | r12/shell.py | ArmShell.parse_help_text | def parse_help_text(self, file_path):
''' Load of list of commands and descriptions from a file. '''
with open(file_path) as f:
lines = f.readlines()
# Parse commands and descriptions, which are separated by a multi-space
# (any sequence of two or more space characters in a row.
cmds = []
descs = []
for line in lines:
line = line.strip()
if len(line) == 0:
cmds.append('')
descs.append('')
else:
tokens = line.split(' ')
cmds.append(tokens[0])
descs.append(''.join(tokens[1:]).strip())
max_len = len(max(cmds, key=len))
# Convert commands and descriptions into help text.
text = ''
for cmd, desc in zip(cmds, descs):
if len(cmd) == 0:
text += '\n'
else:
text += self.style.help(cmd.ljust(max_len + 2), desc + '\n')
return cmds, text | python | def parse_help_text(self, file_path):
''' Load of list of commands and descriptions from a file. '''
with open(file_path) as f:
lines = f.readlines()
# Parse commands and descriptions, which are separated by a multi-space
# (any sequence of two or more space characters in a row.
cmds = []
descs = []
for line in lines:
line = line.strip()
if len(line) == 0:
cmds.append('')
descs.append('')
else:
tokens = line.split(' ')
cmds.append(tokens[0])
descs.append(''.join(tokens[1:]).strip())
max_len = len(max(cmds, key=len))
# Convert commands and descriptions into help text.
text = ''
for cmd, desc in zip(cmds, descs):
if len(cmd) == 0:
text += '\n'
else:
text += self.style.help(cmd.ljust(max_len + 2), desc + '\n')
return cmds, text | [
"def",
"parse_help_text",
"(",
"self",
",",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"# Parse commands and descriptions, which are separated by a multi-space",
"# (any sequence of two or more space characters in a row.",
"cmds",
"=",
"[",
"]",
"descs",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"cmds",
".",
"append",
"(",
"''",
")",
"descs",
".",
"append",
"(",
"''",
")",
"else",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"cmds",
".",
"append",
"(",
"tokens",
"[",
"0",
"]",
")",
"descs",
".",
"append",
"(",
"''",
".",
"join",
"(",
"tokens",
"[",
"1",
":",
"]",
")",
".",
"strip",
"(",
")",
")",
"max_len",
"=",
"len",
"(",
"max",
"(",
"cmds",
",",
"key",
"=",
"len",
")",
")",
"# Convert commands and descriptions into help text.",
"text",
"=",
"''",
"for",
"cmd",
",",
"desc",
"in",
"zip",
"(",
"cmds",
",",
"descs",
")",
":",
"if",
"len",
"(",
"cmd",
")",
"==",
"0",
":",
"text",
"+=",
"'\\n'",
"else",
":",
"text",
"+=",
"self",
".",
"style",
".",
"help",
"(",
"cmd",
".",
"ljust",
"(",
"max_len",
"+",
"2",
")",
",",
"desc",
"+",
"'\\n'",
")",
"return",
"cmds",
",",
"text"
]
| Load of list of commands and descriptions from a file. | [
"Load",
"of",
"list",
"of",
"commands",
"and",
"descriptions",
"from",
"a",
"file",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L304-L333 | train |
adamheins/r12 | r12/shell.py | ArmShell.load_forth_commands | def load_forth_commands(self, help_dir):
''' Load completion list for ROBOFORTH commands. '''
try:
help_file_path = os.path.join(help_dir, 'roboforth.txt')
commands, help_text = self.parse_help_text(help_file_path)
except IOError:
print(self.style.warn('Warning: ',
'Failed to load ROBOFORTH help.'))
return
self.commands['forth'] = commands
self.help['forth'] = '\n'.join([self.style.theme('Forth Commands'),
help_text]) | python | def load_forth_commands(self, help_dir):
''' Load completion list for ROBOFORTH commands. '''
try:
help_file_path = os.path.join(help_dir, 'roboforth.txt')
commands, help_text = self.parse_help_text(help_file_path)
except IOError:
print(self.style.warn('Warning: ',
'Failed to load ROBOFORTH help.'))
return
self.commands['forth'] = commands
self.help['forth'] = '\n'.join([self.style.theme('Forth Commands'),
help_text]) | [
"def",
"load_forth_commands",
"(",
"self",
",",
"help_dir",
")",
":",
"try",
":",
"help_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"help_dir",
",",
"'roboforth.txt'",
")",
"commands",
",",
"help_text",
"=",
"self",
".",
"parse_help_text",
"(",
"help_file_path",
")",
"except",
"IOError",
":",
"print",
"(",
"self",
".",
"style",
".",
"warn",
"(",
"'Warning: '",
",",
"'Failed to load ROBOFORTH help.'",
")",
")",
"return",
"self",
".",
"commands",
"[",
"'forth'",
"]",
"=",
"commands",
"self",
".",
"help",
"[",
"'forth'",
"]",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"self",
".",
"style",
".",
"theme",
"(",
"'Forth Commands'",
")",
",",
"help_text",
"]",
")"
]
| Load completion list for ROBOFORTH commands. | [
"Load",
"completion",
"list",
"for",
"ROBOFORTH",
"commands",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L336-L347 | train |
adamheins/r12 | r12/shell.py | ArmShell.preloop | def preloop(self):
''' Executed before the command loop starts. '''
script_dir = os.path.dirname(os.path.realpath(__file__))
help_dir = os.path.join(script_dir, HELP_DIR_NAME)
self.load_forth_commands(help_dir)
self.load_shell_commands(help_dir) | python | def preloop(self):
''' Executed before the command loop starts. '''
script_dir = os.path.dirname(os.path.realpath(__file__))
help_dir = os.path.join(script_dir, HELP_DIR_NAME)
self.load_forth_commands(help_dir)
self.load_shell_commands(help_dir) | [
"def",
"preloop",
"(",
"self",
")",
":",
"script_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"help_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"script_dir",
",",
"HELP_DIR_NAME",
")",
"self",
".",
"load_forth_commands",
"(",
"help_dir",
")",
"self",
".",
"load_shell_commands",
"(",
"help_dir",
")"
]
| Executed before the command loop starts. | [
"Executed",
"before",
"the",
"command",
"loop",
"starts",
"."
]
| ff78178332140930bf46a94a0b15ee082bb92491 | https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/shell.py#L363-L368 | train |
The-Politico/politico-civic-election-night | electionnight/management/commands/methods/bootstrap/legislative_office.py | LegislativeOffice.bootstrap_legislative_office | def bootstrap_legislative_office(self, election):
"""
For legislative offices, create page content for the legislative
Body the Office belongs to AND the state-level Division.
E.g., for a Texas U.S. Senate seat, create page content for:
- U.S. Senate page
- Texas state page
"""
body = election.race.office.body
body_division = election.race.office.body.jurisdiction.division
office_division = election.race.office.division
self.bootstrap_federal_body_type_page(election)
self.bootstrap_state_body_type_page(election)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(body),
object_id=body.pk,
election_day=election.election_day,
division=body_division,
)
# Senate seats
if office_division.level.name == DivisionLevel.STATE:
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(
office_division
),
object_id=office_division.pk,
election_day=election.election_day,
special_election=False,
)
# House seats
elif office_division.level.name == DivisionLevel.DISTRICT:
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(
office_division.parent
),
object_id=office_division.parent.pk,
election_day=election.election_day,
special_election=False,
)
# Generic state pages, type and content
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label="geography", model="division"
),
election_day=election.election_day,
division_level=DivisionLevel.objects.get(name=DivisionLevel.STATE),
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
) | python | def bootstrap_legislative_office(self, election):
"""
For legislative offices, create page content for the legislative
Body the Office belongs to AND the state-level Division.
E.g., for a Texas U.S. Senate seat, create page content for:
- U.S. Senate page
- Texas state page
"""
body = election.race.office.body
body_division = election.race.office.body.jurisdiction.division
office_division = election.race.office.division
self.bootstrap_federal_body_type_page(election)
self.bootstrap_state_body_type_page(election)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(body),
object_id=body.pk,
election_day=election.election_day,
division=body_division,
)
# Senate seats
if office_division.level.name == DivisionLevel.STATE:
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(
office_division
),
object_id=office_division.pk,
election_day=election.election_day,
special_election=False,
)
# House seats
elif office_division.level.name == DivisionLevel.DISTRICT:
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(
office_division.parent
),
object_id=office_division.parent.pk,
election_day=election.election_day,
special_election=False,
)
# Generic state pages, type and content
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label="geography", model="division"
),
election_day=election.election_day,
division_level=DivisionLevel.objects.get(name=DivisionLevel.STATE),
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
) | [
"def",
"bootstrap_legislative_office",
"(",
"self",
",",
"election",
")",
":",
"body",
"=",
"election",
".",
"race",
".",
"office",
".",
"body",
"body_division",
"=",
"election",
".",
"race",
".",
"office",
".",
"body",
".",
"jurisdiction",
".",
"division",
"office_division",
"=",
"election",
".",
"race",
".",
"office",
".",
"division",
"self",
".",
"bootstrap_federal_body_type_page",
"(",
"election",
")",
"self",
".",
"bootstrap_state_body_type_page",
"(",
"election",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"body",
")",
",",
"object_id",
"=",
"body",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division",
"=",
"body_division",
",",
")",
"# Senate seats",
"if",
"office_division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"STATE",
":",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"office_division",
")",
",",
"object_id",
"=",
"office_division",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"special_election",
"=",
"False",
",",
")",
"# House seats",
"elif",
"office_division",
".",
"level",
".",
"name",
"==",
"DivisionLevel",
".",
"DISTRICT",
":",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"office_division",
".",
"parent",
")",
",",
"object_id",
"=",
"office_division",
".",
"parent",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"special_election",
"=",
"False",
",",
")",
"# Generic state pages, type and content",
"page_type",
",",
"created",
"=",
"PageType",
".",
"objects",
".",
"get_or_create",
"(",
"model_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"\"geography\"",
",",
"model",
"=",
"\"division\"",
")",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division_level",
"=",
"DivisionLevel",
".",
"objects",
".",
"get",
"(",
"name",
"=",
"DivisionLevel",
".",
"STATE",
")",
",",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"page_type",
")",
",",
"object_id",
"=",
"page_type",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
")"
]
| For legislative offices, create page content for the legislative
Body the Office belongs to AND the state-level Division.
E.g., for a Texas U.S. Senate seat, create page content for:
- U.S. Senate page
- Texas state page | [
"For",
"legislative",
"offices",
"create",
"page",
"content",
"for",
"the",
"legislative",
"Body",
"the",
"Office",
"belongs",
"to",
"AND",
"the",
"state",
"-",
"level",
"Division",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/methods/bootstrap/legislative_office.py#L40-L94 | train |
tjcsl/cslbot | cslbot/commands/xkcd.py | cmd | def cmd(send, msg, args):
"""Gets a xkcd comic.
Syntax: {command} [num|latest|term]
"""
latest = get_latest()
if not msg:
msg = randrange(1, latest)
elif msg == 'latest':
msg = latest
elif msg.isdigit():
msg = int(msg)
if msg > latest or msg < 1:
send("Number out of range")
return
else:
send(do_search(msg, args['config']['api']['googleapikey'], args['config']['api']['xkcdsearchid']))
return
url = 'http://xkcd.com/%d/info.0.json' % msg if msg != 'latest' else 'http://xkcd.com/info.0.json'
data = get(url).json()
output = "%s -- http://xkcd.com/%d" % (data['safe_title'], data['num'])
send(output) | python | def cmd(send, msg, args):
"""Gets a xkcd comic.
Syntax: {command} [num|latest|term]
"""
latest = get_latest()
if not msg:
msg = randrange(1, latest)
elif msg == 'latest':
msg = latest
elif msg.isdigit():
msg = int(msg)
if msg > latest or msg < 1:
send("Number out of range")
return
else:
send(do_search(msg, args['config']['api']['googleapikey'], args['config']['api']['xkcdsearchid']))
return
url = 'http://xkcd.com/%d/info.0.json' % msg if msg != 'latest' else 'http://xkcd.com/info.0.json'
data = get(url).json()
output = "%s -- http://xkcd.com/%d" % (data['safe_title'], data['num'])
send(output) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"latest",
"=",
"get_latest",
"(",
")",
"if",
"not",
"msg",
":",
"msg",
"=",
"randrange",
"(",
"1",
",",
"latest",
")",
"elif",
"msg",
"==",
"'latest'",
":",
"msg",
"=",
"latest",
"elif",
"msg",
".",
"isdigit",
"(",
")",
":",
"msg",
"=",
"int",
"(",
"msg",
")",
"if",
"msg",
">",
"latest",
"or",
"msg",
"<",
"1",
":",
"send",
"(",
"\"Number out of range\"",
")",
"return",
"else",
":",
"send",
"(",
"do_search",
"(",
"msg",
",",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'googleapikey'",
"]",
",",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'xkcdsearchid'",
"]",
")",
")",
"return",
"url",
"=",
"'http://xkcd.com/%d/info.0.json'",
"%",
"msg",
"if",
"msg",
"!=",
"'latest'",
"else",
"'http://xkcd.com/info.0.json'",
"data",
"=",
"get",
"(",
"url",
")",
".",
"json",
"(",
")",
"output",
"=",
"\"%s -- http://xkcd.com/%d\"",
"%",
"(",
"data",
"[",
"'safe_title'",
"]",
",",
"data",
"[",
"'num'",
"]",
")",
"send",
"(",
"output",
")"
]
| Gets a xkcd comic.
Syntax: {command} [num|latest|term] | [
"Gets",
"a",
"xkcd",
"comic",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/xkcd.py#L41-L63 | train |
louib/confirm | confirm/generator.py | generate_config_parser | def generate_config_parser(config, include_all=False):
"""
Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* field of an option.
"""
# The allow_no_value allows us to output commented lines.
config_parser = SafeConfigParser(allow_no_value=True)
for section_name, option_name in _get_included_schema_sections_options(config, include_all):
if not config_parser.has_section(section_name):
config_parser.add_section(section_name)
option = config[section_name][option_name]
if option.get('required'):
config_parser.set(section_name, '# REQUIRED')
config_parser.set(section_name, '# ' + option.get('description', 'No description provided.'))
if option.get('deprecated'):
config_parser.set(section_name, '# DEPRECATED')
option_value = _get_value(option)
config_parser.set(section_name, option_name, option_value)
config_parser.set(section_name, '')
return config_parser | python | def generate_config_parser(config, include_all=False):
"""
Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* field of an option.
"""
# The allow_no_value allows us to output commented lines.
config_parser = SafeConfigParser(allow_no_value=True)
for section_name, option_name in _get_included_schema_sections_options(config, include_all):
if not config_parser.has_section(section_name):
config_parser.add_section(section_name)
option = config[section_name][option_name]
if option.get('required'):
config_parser.set(section_name, '# REQUIRED')
config_parser.set(section_name, '# ' + option.get('description', 'No description provided.'))
if option.get('deprecated'):
config_parser.set(section_name, '# DEPRECATED')
option_value = _get_value(option)
config_parser.set(section_name, option_name, option_value)
config_parser.set(section_name, '')
return config_parser | [
"def",
"generate_config_parser",
"(",
"config",
",",
"include_all",
"=",
"False",
")",
":",
"# The allow_no_value allows us to output commented lines.",
"config_parser",
"=",
"SafeConfigParser",
"(",
"allow_no_value",
"=",
"True",
")",
"for",
"section_name",
",",
"option_name",
"in",
"_get_included_schema_sections_options",
"(",
"config",
",",
"include_all",
")",
":",
"if",
"not",
"config_parser",
".",
"has_section",
"(",
"section_name",
")",
":",
"config_parser",
".",
"add_section",
"(",
"section_name",
")",
"option",
"=",
"config",
"[",
"section_name",
"]",
"[",
"option_name",
"]",
"if",
"option",
".",
"get",
"(",
"'required'",
")",
":",
"config_parser",
".",
"set",
"(",
"section_name",
",",
"'# REQUIRED'",
")",
"config_parser",
".",
"set",
"(",
"section_name",
",",
"'# '",
"+",
"option",
".",
"get",
"(",
"'description'",
",",
"'No description provided.'",
")",
")",
"if",
"option",
".",
"get",
"(",
"'deprecated'",
")",
":",
"config_parser",
".",
"set",
"(",
"section_name",
",",
"'# DEPRECATED'",
")",
"option_value",
"=",
"_get_value",
"(",
"option",
")",
"config_parser",
".",
"set",
"(",
"section_name",
",",
"option_name",
",",
"option_value",
")",
"config_parser",
".",
"set",
"(",
"section_name",
",",
"''",
")",
"return",
"config_parser"
]
| Generates a config parser from a configuration dictionary.
The dictionary contains the merged informations of the schema and,
optionally, of a source configuration file. Values of the source
configuration file will be stored in the *value* field of an option. | [
"Generates",
"a",
"config",
"parser",
"from",
"a",
"configuration",
"dictionary",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L24-L55 | train |
louib/confirm | confirm/generator.py | generate_documentation | def generate_documentation(schema):
"""
Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation.
"""
documentation_title = "Configuration documentation"
documentation = documentation_title + "\n"
documentation += "=" * len(documentation_title) + '\n'
for section_name in schema:
section_created = False
for option_name in schema[section_name]:
option = schema[section_name][option_name]
if not section_created:
documentation += '\n'
documentation += section_name + '\n'
documentation += '-' * len(section_name) + '\n'
section_created = True
documentation += '\n'
documentation += option_name + '\n'
documentation += '~' * len(option_name) + '\n'
if option.get('required'):
documentation += "** This option is required! **\n"
if option.get('type'):
documentation += '*Type : %s.*\n' % option.get('type')
if option.get('description'):
documentation += option.get('description') + '\n'
if option.get('default'):
documentation += 'The default value is %s.\n' % option.get('default')
if option.get('deprecated'):
documentation += "** This option is deprecated! **\n"
return documentation | python | def generate_documentation(schema):
"""
Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation.
"""
documentation_title = "Configuration documentation"
documentation = documentation_title + "\n"
documentation += "=" * len(documentation_title) + '\n'
for section_name in schema:
section_created = False
for option_name in schema[section_name]:
option = schema[section_name][option_name]
if not section_created:
documentation += '\n'
documentation += section_name + '\n'
documentation += '-' * len(section_name) + '\n'
section_created = True
documentation += '\n'
documentation += option_name + '\n'
documentation += '~' * len(option_name) + '\n'
if option.get('required'):
documentation += "** This option is required! **\n"
if option.get('type'):
documentation += '*Type : %s.*\n' % option.get('type')
if option.get('description'):
documentation += option.get('description') + '\n'
if option.get('default'):
documentation += 'The default value is %s.\n' % option.get('default')
if option.get('deprecated'):
documentation += "** This option is deprecated! **\n"
return documentation | [
"def",
"generate_documentation",
"(",
"schema",
")",
":",
"documentation_title",
"=",
"\"Configuration documentation\"",
"documentation",
"=",
"documentation_title",
"+",
"\"\\n\"",
"documentation",
"+=",
"\"=\"",
"*",
"len",
"(",
"documentation_title",
")",
"+",
"'\\n'",
"for",
"section_name",
"in",
"schema",
":",
"section_created",
"=",
"False",
"for",
"option_name",
"in",
"schema",
"[",
"section_name",
"]",
":",
"option",
"=",
"schema",
"[",
"section_name",
"]",
"[",
"option_name",
"]",
"if",
"not",
"section_created",
":",
"documentation",
"+=",
"'\\n'",
"documentation",
"+=",
"section_name",
"+",
"'\\n'",
"documentation",
"+=",
"'-'",
"*",
"len",
"(",
"section_name",
")",
"+",
"'\\n'",
"section_created",
"=",
"True",
"documentation",
"+=",
"'\\n'",
"documentation",
"+=",
"option_name",
"+",
"'\\n'",
"documentation",
"+=",
"'~'",
"*",
"len",
"(",
"option_name",
")",
"+",
"'\\n'",
"if",
"option",
".",
"get",
"(",
"'required'",
")",
":",
"documentation",
"+=",
"\"** This option is required! **\\n\"",
"if",
"option",
".",
"get",
"(",
"'type'",
")",
":",
"documentation",
"+=",
"'*Type : %s.*\\n'",
"%",
"option",
".",
"get",
"(",
"'type'",
")",
"if",
"option",
".",
"get",
"(",
"'description'",
")",
":",
"documentation",
"+=",
"option",
".",
"get",
"(",
"'description'",
")",
"+",
"'\\n'",
"if",
"option",
".",
"get",
"(",
"'default'",
")",
":",
"documentation",
"+=",
"'The default value is %s.\\n'",
"%",
"option",
".",
"get",
"(",
"'default'",
")",
"if",
"option",
".",
"get",
"(",
"'deprecated'",
")",
":",
"documentation",
"+=",
"\"** This option is deprecated! **\\n\"",
"return",
"documentation"
]
| Generates reStructuredText documentation from a Confirm file.
:param schema: Dictionary representing the Confirm schema.
:returns: String representing the reStructuredText documentation. | [
"Generates",
"reStructuredText",
"documentation",
"from",
"a",
"Confirm",
"file",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L73-L123 | train |
louib/confirm | confirm/generator.py | append_existing_values | def append_existing_values(schema, config):
"""
Adds the values of the existing config to the config dictionary.
"""
for section_name in config:
for option_name in config[section_name]:
option_value = config[section_name][option_name]
# Note that we must preserve existing values, wether or not they
# exist in the schema file!
schema.setdefault(section_name, {}).setdefault(option_name, {})['value'] = option_value
return schema | python | def append_existing_values(schema, config):
"""
Adds the values of the existing config to the config dictionary.
"""
for section_name in config:
for option_name in config[section_name]:
option_value = config[section_name][option_name]
# Note that we must preserve existing values, wether or not they
# exist in the schema file!
schema.setdefault(section_name, {}).setdefault(option_name, {})['value'] = option_value
return schema | [
"def",
"append_existing_values",
"(",
"schema",
",",
"config",
")",
":",
"for",
"section_name",
"in",
"config",
":",
"for",
"option_name",
"in",
"config",
"[",
"section_name",
"]",
":",
"option_value",
"=",
"config",
"[",
"section_name",
"]",
"[",
"option_name",
"]",
"# Note that we must preserve existing values, wether or not they",
"# exist in the schema file!",
"schema",
".",
"setdefault",
"(",
"section_name",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"option_name",
",",
"{",
"}",
")",
"[",
"'value'",
"]",
"=",
"option_value",
"return",
"schema"
]
| Adds the values of the existing config to the config dictionary. | [
"Adds",
"the",
"values",
"of",
"the",
"existing",
"config",
"to",
"the",
"config",
"dictionary",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L126-L139 | train |
louib/confirm | confirm/generator.py | generate_schema_file | def generate_schema_file(config_file):
"""
Generates a basic confirm schema file from a configuration file.
"""
config = utils.load_config_from_ini_file(config_file)
schema = {}
for section_name in config:
for option_name in config[section_name]:
schema.setdefault(section_name, {}).setdefault(option_name, {})
schema[section_name][option_name]['description'] = 'No description provided.'
return utils.dump_schema_file(schema) | python | def generate_schema_file(config_file):
"""
Generates a basic confirm schema file from a configuration file.
"""
config = utils.load_config_from_ini_file(config_file)
schema = {}
for section_name in config:
for option_name in config[section_name]:
schema.setdefault(section_name, {}).setdefault(option_name, {})
schema[section_name][option_name]['description'] = 'No description provided.'
return utils.dump_schema_file(schema) | [
"def",
"generate_schema_file",
"(",
"config_file",
")",
":",
"config",
"=",
"utils",
".",
"load_config_from_ini_file",
"(",
"config_file",
")",
"schema",
"=",
"{",
"}",
"for",
"section_name",
"in",
"config",
":",
"for",
"option_name",
"in",
"config",
"[",
"section_name",
"]",
":",
"schema",
".",
"setdefault",
"(",
"section_name",
",",
"{",
"}",
")",
".",
"setdefault",
"(",
"option_name",
",",
"{",
"}",
")",
"schema",
"[",
"section_name",
"]",
"[",
"option_name",
"]",
"[",
"'description'",
"]",
"=",
"'No description provided.'",
"return",
"utils",
".",
"dump_schema_file",
"(",
"schema",
")"
]
| Generates a basic confirm schema file from a configuration file. | [
"Generates",
"a",
"basic",
"confirm",
"schema",
"file",
"from",
"a",
"configuration",
"file",
"."
]
| 0acd1eccda6cd71c69d2ae33166a16a257685811 | https://github.com/louib/confirm/blob/0acd1eccda6cd71c69d2ae33166a16a257685811/confirm/generator.py#L142-L155 | train |
rraadd88/rohan | rohan/dandage/io_sets.py | rankwithlist | def rankwithlist(l,lwith,test=False):
"""
rank l wrt lwith
"""
if not (isinstance(l,list) and isinstance(lwith,list)):
l,lwith=list(l),list(lwith)
from scipy.stats import rankdata
if test:
print(l,lwith)
print(rankdata(l),rankdata(lwith))
print(rankdata(l+lwith))
return rankdata(l+lwith)[:len(l)] | python | def rankwithlist(l,lwith,test=False):
"""
rank l wrt lwith
"""
if not (isinstance(l,list) and isinstance(lwith,list)):
l,lwith=list(l),list(lwith)
from scipy.stats import rankdata
if test:
print(l,lwith)
print(rankdata(l),rankdata(lwith))
print(rankdata(l+lwith))
return rankdata(l+lwith)[:len(l)] | [
"def",
"rankwithlist",
"(",
"l",
",",
"lwith",
",",
"test",
"=",
"False",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"l",
",",
"list",
")",
"and",
"isinstance",
"(",
"lwith",
",",
"list",
")",
")",
":",
"l",
",",
"lwith",
"=",
"list",
"(",
"l",
")",
",",
"list",
"(",
"lwith",
")",
"from",
"scipy",
".",
"stats",
"import",
"rankdata",
"if",
"test",
":",
"print",
"(",
"l",
",",
"lwith",
")",
"print",
"(",
"rankdata",
"(",
"l",
")",
",",
"rankdata",
"(",
"lwith",
")",
")",
"print",
"(",
"rankdata",
"(",
"l",
"+",
"lwith",
")",
")",
"return",
"rankdata",
"(",
"l",
"+",
"lwith",
")",
"[",
":",
"len",
"(",
"l",
")",
"]"
]
| rank l wrt lwith | [
"rank",
"l",
"wrt",
"lwith"
]
| b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_sets.py#L38-L49 | train |
rraadd88/rohan | rohan/dandage/io_sets.py | dfbool2intervals | def dfbool2intervals(df,colbool):
"""
ds contains bool values
"""
df.index=range(len(df))
intervals=bools2intervals(df[colbool])
for intervali,interval in enumerate(intervals):
df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali
df.loc[interval[0]:interval[1],f'{colbool} interval start']=interval[0]
df.loc[interval[0]:interval[1],f'{colbool} interval stop']=interval[1]
df.loc[interval[0]:interval[1],f'{colbool} interval length']=interval[1]-interval[0]+1
df.loc[interval[0]:interval[1],f'{colbool} interval within index']=range(interval[1]-interval[0]+1)
df[f'{colbool} interval index']=df.index
return df | python | def dfbool2intervals(df,colbool):
"""
ds contains bool values
"""
df.index=range(len(df))
intervals=bools2intervals(df[colbool])
for intervali,interval in enumerate(intervals):
df.loc[interval[0]:interval[1],f'{colbool} interval id']=intervali
df.loc[interval[0]:interval[1],f'{colbool} interval start']=interval[0]
df.loc[interval[0]:interval[1],f'{colbool} interval stop']=interval[1]
df.loc[interval[0]:interval[1],f'{colbool} interval length']=interval[1]-interval[0]+1
df.loc[interval[0]:interval[1],f'{colbool} interval within index']=range(interval[1]-interval[0]+1)
df[f'{colbool} interval index']=df.index
return df | [
"def",
"dfbool2intervals",
"(",
"df",
",",
"colbool",
")",
":",
"df",
".",
"index",
"=",
"range",
"(",
"len",
"(",
"df",
")",
")",
"intervals",
"=",
"bools2intervals",
"(",
"df",
"[",
"colbool",
"]",
")",
"for",
"intervali",
",",
"interval",
"in",
"enumerate",
"(",
"intervals",
")",
":",
"df",
".",
"loc",
"[",
"interval",
"[",
"0",
"]",
":",
"interval",
"[",
"1",
"]",
",",
"f'{colbool} interval id'",
"]",
"=",
"intervali",
"df",
".",
"loc",
"[",
"interval",
"[",
"0",
"]",
":",
"interval",
"[",
"1",
"]",
",",
"f'{colbool} interval start'",
"]",
"=",
"interval",
"[",
"0",
"]",
"df",
".",
"loc",
"[",
"interval",
"[",
"0",
"]",
":",
"interval",
"[",
"1",
"]",
",",
"f'{colbool} interval stop'",
"]",
"=",
"interval",
"[",
"1",
"]",
"df",
".",
"loc",
"[",
"interval",
"[",
"0",
"]",
":",
"interval",
"[",
"1",
"]",
",",
"f'{colbool} interval length'",
"]",
"=",
"interval",
"[",
"1",
"]",
"-",
"interval",
"[",
"0",
"]",
"+",
"1",
"df",
".",
"loc",
"[",
"interval",
"[",
"0",
"]",
":",
"interval",
"[",
"1",
"]",
",",
"f'{colbool} interval within index'",
"]",
"=",
"range",
"(",
"interval",
"[",
"1",
"]",
"-",
"interval",
"[",
"0",
"]",
"+",
"1",
")",
"df",
"[",
"f'{colbool} interval index'",
"]",
"=",
"df",
".",
"index",
"return",
"df"
]
| ds contains bool values | [
"ds",
"contains",
"bool",
"values"
]
| b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_sets.py#L54-L67 | train |
brandjon/simplestruct | simplestruct/type.py | TypeChecker.normalize_kind | def normalize_kind(self, kindlike):
"""Make a kind out of a possible shorthand. If the given
argument is a sequence of types or a singular type, it becomes
a kind that accepts exactly those types. If the given argument
is None, it becomes a type that accepts anything.
"""
if kindlike is None:
return (object,)
elif isinstance(kindlike, type):
return (kindlike,)
else:
return tuple(kindlike) | python | def normalize_kind(self, kindlike):
"""Make a kind out of a possible shorthand. If the given
argument is a sequence of types or a singular type, it becomes
a kind that accepts exactly those types. If the given argument
is None, it becomes a type that accepts anything.
"""
if kindlike is None:
return (object,)
elif isinstance(kindlike, type):
return (kindlike,)
else:
return tuple(kindlike) | [
"def",
"normalize_kind",
"(",
"self",
",",
"kindlike",
")",
":",
"if",
"kindlike",
"is",
"None",
":",
"return",
"(",
"object",
",",
")",
"elif",
"isinstance",
"(",
"kindlike",
",",
"type",
")",
":",
"return",
"(",
"kindlike",
",",
")",
"else",
":",
"return",
"tuple",
"(",
"kindlike",
")"
]
| Make a kind out of a possible shorthand. If the given
argument is a sequence of types or a singular type, it becomes
a kind that accepts exactly those types. If the given argument
is None, it becomes a type that accepts anything. | [
"Make",
"a",
"kind",
"out",
"of",
"a",
"possible",
"shorthand",
".",
"If",
"the",
"given",
"argument",
"is",
"a",
"sequence",
"of",
"types",
"or",
"a",
"singular",
"type",
"it",
"becomes",
"a",
"kind",
"that",
"accepts",
"exactly",
"those",
"types",
".",
"If",
"the",
"given",
"argument",
"is",
"None",
"it",
"becomes",
"a",
"type",
"that",
"accepts",
"anything",
"."
]
| f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L31-L42 | train |
brandjon/simplestruct | simplestruct/type.py | TypeChecker.str_kind | def str_kind(self, kind):
"""Get a string describing a kind."""
if len(kind) == 0:
return 'Nothing'
elif len(kind) == 1:
return kind[0].__name__
elif len(kind) == 2:
return kind[0].__name__ + ' or ' + kind[1].__name__
else:
return 'one of {' + ', '.join(t.__name__ for t in kind) + '}' | python | def str_kind(self, kind):
"""Get a string describing a kind."""
if len(kind) == 0:
return 'Nothing'
elif len(kind) == 1:
return kind[0].__name__
elif len(kind) == 2:
return kind[0].__name__ + ' or ' + kind[1].__name__
else:
return 'one of {' + ', '.join(t.__name__ for t in kind) + '}' | [
"def",
"str_kind",
"(",
"self",
",",
"kind",
")",
":",
"if",
"len",
"(",
"kind",
")",
"==",
"0",
":",
"return",
"'Nothing'",
"elif",
"len",
"(",
"kind",
")",
"==",
"1",
":",
"return",
"kind",
"[",
"0",
"]",
".",
"__name__",
"elif",
"len",
"(",
"kind",
")",
"==",
"2",
":",
"return",
"kind",
"[",
"0",
"]",
".",
"__name__",
"+",
"' or '",
"+",
"kind",
"[",
"1",
"]",
".",
"__name__",
"else",
":",
"return",
"'one of {'",
"+",
"', '",
".",
"join",
"(",
"t",
".",
"__name__",
"for",
"t",
"in",
"kind",
")",
"+",
"'}'"
]
| Get a string describing a kind. | [
"Get",
"a",
"string",
"describing",
"a",
"kind",
"."
]
| f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L44-L53 | train |
brandjon/simplestruct | simplestruct/type.py | TypeChecker.checktype | def checktype(self, val, kind, **kargs):
"""Raise TypeError if val does not satisfy kind."""
if not isinstance(val, kind):
raise TypeError('Expected {}; got {}'.format(
self.str_kind(kind), self.str_valtype(val))) | python | def checktype(self, val, kind, **kargs):
"""Raise TypeError if val does not satisfy kind."""
if not isinstance(val, kind):
raise TypeError('Expected {}; got {}'.format(
self.str_kind(kind), self.str_valtype(val))) | [
"def",
"checktype",
"(",
"self",
",",
"val",
",",
"kind",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"kind",
")",
":",
"raise",
"TypeError",
"(",
"'Expected {}; got {}'",
".",
"format",
"(",
"self",
".",
"str_kind",
"(",
"kind",
")",
",",
"self",
".",
"str_valtype",
"(",
"val",
")",
")",
")"
]
| Raise TypeError if val does not satisfy kind. | [
"Raise",
"TypeError",
"if",
"val",
"does",
"not",
"satisfy",
"kind",
"."
]
| f2bba77278838b5904fd72b35741da162f337c37 | https://github.com/brandjon/simplestruct/blob/f2bba77278838b5904fd72b35741da162f337c37/simplestruct/type.py#L55-L59 | train |
jeffh/describe | describe/mock/expectations.py | Expectation.raises | def raises(cls, sender, attrname, error, args=ANYTHING, kwargs=ANYTHING):
"An alternative constructor which raises the given error"
def raise_error():
raise error
return cls(sender, attrname, returns=Invoke(raise_error), args=ANYTHING, kwargs=ANYTHING) | python | def raises(cls, sender, attrname, error, args=ANYTHING, kwargs=ANYTHING):
"An alternative constructor which raises the given error"
def raise_error():
raise error
return cls(sender, attrname, returns=Invoke(raise_error), args=ANYTHING, kwargs=ANYTHING) | [
"def",
"raises",
"(",
"cls",
",",
"sender",
",",
"attrname",
",",
"error",
",",
"args",
"=",
"ANYTHING",
",",
"kwargs",
"=",
"ANYTHING",
")",
":",
"def",
"raise_error",
"(",
")",
":",
"raise",
"error",
"return",
"cls",
"(",
"sender",
",",
"attrname",
",",
"returns",
"=",
"Invoke",
"(",
"raise_error",
")",
",",
"args",
"=",
"ANYTHING",
",",
"kwargs",
"=",
"ANYTHING",
")"
]
| An alternative constructor which raises the given error | [
"An",
"alternative",
"constructor",
"which",
"raises",
"the",
"given",
"error"
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L24-L28 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilder.and_raises | def and_raises(self, *errors):
"Expects an error or more to be raised from the given expectation."
for error in errors:
self.__expect(Expectation.raises, error) | python | def and_raises(self, *errors):
"Expects an error or more to be raised from the given expectation."
for error in errors:
self.__expect(Expectation.raises, error) | [
"def",
"and_raises",
"(",
"self",
",",
"*",
"errors",
")",
":",
"for",
"error",
"in",
"errors",
":",
"self",
".",
"__expect",
"(",
"Expectation",
".",
"raises",
",",
"error",
")"
]
| Expects an error or more to be raised from the given expectation. | [
"Expects",
"an",
"error",
"or",
"more",
"to",
"be",
"raised",
"from",
"the",
"given",
"expectation",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L204-L207 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilder.and_calls | def and_calls(self, *funcs):
"""Expects the return value from one or more functions to be raised
from the given expectation.
"""
for fn in funcs:
self.__expect(Expectation, Invoke(fn)) | python | def and_calls(self, *funcs):
"""Expects the return value from one or more functions to be raised
from the given expectation.
"""
for fn in funcs:
self.__expect(Expectation, Invoke(fn)) | [
"def",
"and_calls",
"(",
"self",
",",
"*",
"funcs",
")",
":",
"for",
"fn",
"in",
"funcs",
":",
"self",
".",
"__expect",
"(",
"Expectation",
",",
"Invoke",
"(",
"fn",
")",
")"
]
| Expects the return value from one or more functions to be raised
from the given expectation. | [
"Expects",
"the",
"return",
"value",
"from",
"one",
"or",
"more",
"functions",
"to",
"be",
"raised",
"from",
"the",
"given",
"expectation",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L214-L219 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilder.and_yields | def and_yields(self, *values):
"""Expects the return value of the expectation to be a generator of the
given values
"""
def generator():
for value in values:
yield value
self.__expect(Expectation, Invoke(generator)) | python | def and_yields(self, *values):
"""Expects the return value of the expectation to be a generator of the
given values
"""
def generator():
for value in values:
yield value
self.__expect(Expectation, Invoke(generator)) | [
"def",
"and_yields",
"(",
"self",
",",
"*",
"values",
")",
":",
"def",
"generator",
"(",
")",
":",
"for",
"value",
"in",
"values",
":",
"yield",
"value",
"self",
".",
"__expect",
"(",
"Expectation",
",",
"Invoke",
"(",
"generator",
")",
")"
]
| Expects the return value of the expectation to be a generator of the
given values | [
"Expects",
"the",
"return",
"value",
"of",
"the",
"expectation",
"to",
"be",
"a",
"generator",
"of",
"the",
"given",
"values"
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L221-L228 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilderFactory.attribute_invoked | def attribute_invoked(self, sender, name, args, kwargs):
"Handles the creation of ExpectationBuilder when an attribute is invoked."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__call__')(*args, **kwargs) | python | def attribute_invoked(self, sender, name, args, kwargs):
"Handles the creation of ExpectationBuilder when an attribute is invoked."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__call__')(*args, **kwargs) | [
"def",
"attribute_invoked",
"(",
"self",
",",
"sender",
",",
"name",
",",
"args",
",",
"kwargs",
")",
":",
"return",
"ExpectationBuilder",
"(",
"self",
".",
"sender",
",",
"self",
".",
"delegate",
",",
"self",
".",
"add_invocation",
",",
"self",
".",
"add_expectations",
",",
"'__call__'",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Handles the creation of ExpectationBuilder when an attribute is invoked. | [
"Handles",
"the",
"creation",
"of",
"ExpectationBuilder",
"when",
"an",
"attribute",
"is",
"invoked",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L257-L259 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilderFactory.attribute_read | def attribute_read(self, sender, name):
"Handles the creation of ExpectationBuilder when an attribute is read."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, name) | python | def attribute_read(self, sender, name):
"Handles the creation of ExpectationBuilder when an attribute is read."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, name) | [
"def",
"attribute_read",
"(",
"self",
",",
"sender",
",",
"name",
")",
":",
"return",
"ExpectationBuilder",
"(",
"self",
".",
"sender",
",",
"self",
".",
"delegate",
",",
"self",
".",
"add_invocation",
",",
"self",
".",
"add_expectations",
",",
"name",
")"
]
| Handles the creation of ExpectationBuilder when an attribute is read. | [
"Handles",
"the",
"creation",
"of",
"ExpectationBuilder",
"when",
"an",
"attribute",
"is",
"read",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L261-L263 | train |
jeffh/describe | describe/mock/expectations.py | ExpectationBuilderFactory.key_read | def key_read(self, sender, name):
"Handles the creation of ExpectationBuilder when a dictionary item access."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__getitem__')(name) | python | def key_read(self, sender, name):
"Handles the creation of ExpectationBuilder when a dictionary item access."
return ExpectationBuilder(self.sender, self.delegate, self.add_invocation, self.add_expectations, '__getitem__')(name) | [
"def",
"key_read",
"(",
"self",
",",
"sender",
",",
"name",
")",
":",
"return",
"ExpectationBuilder",
"(",
"self",
".",
"sender",
",",
"self",
".",
"delegate",
",",
"self",
".",
"add_invocation",
",",
"self",
".",
"add_expectations",
",",
"'__getitem__'",
")",
"(",
"name",
")"
]
| Handles the creation of ExpectationBuilder when a dictionary item access. | [
"Handles",
"the",
"creation",
"of",
"ExpectationBuilder",
"when",
"a",
"dictionary",
"item",
"access",
"."
]
| 6a33ffecc3340b57e60bc8a7095521882ff9a156 | https://github.com/jeffh/describe/blob/6a33ffecc3340b57e60bc8a7095521882ff9a156/describe/mock/expectations.py#L265-L267 | train |
ataylor32/django-friendly-tag-loader | src/friendlytagloader/templatetags/friendly_loader.py | friendly_load | def friendly_load(parser, token):
"""
Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not installed.
For example::
{% load friendly_loader %}
{% friendly_load comments webdesign %}
{% if_has_tag render_comment_list %}
{% render_comment_list for obj %}
{% else %}
{% if_has_tag lorem %}
{% lorem %}
{% endif_has_tag %}
{% endif_has_tag %}
"""
bits = token.contents.split()
if len(bits) >= 4 and bits[-2] == "from":
# from syntax is used; load individual tags from the library
name = bits[-1]
try:
lib = find_library(parser, name)
subset = load_from_library(lib, name, bits[1:-2])
parser.add_library(subset)
except TemplateSyntaxError:
pass
else:
# one or more libraries are specified; load and add them to the parser
for name in bits[1:]:
try:
lib = find_library(parser, name)
parser.add_library(lib)
except TemplateSyntaxError:
pass
return LoadNode() | python | def friendly_load(parser, token):
"""
Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not installed.
For example::
{% load friendly_loader %}
{% friendly_load comments webdesign %}
{% if_has_tag render_comment_list %}
{% render_comment_list for obj %}
{% else %}
{% if_has_tag lorem %}
{% lorem %}
{% endif_has_tag %}
{% endif_has_tag %}
"""
bits = token.contents.split()
if len(bits) >= 4 and bits[-2] == "from":
# from syntax is used; load individual tags from the library
name = bits[-1]
try:
lib = find_library(parser, name)
subset = load_from_library(lib, name, bits[1:-2])
parser.add_library(subset)
except TemplateSyntaxError:
pass
else:
# one or more libraries are specified; load and add them to the parser
for name in bits[1:]:
try:
lib = find_library(parser, name)
parser.add_library(lib)
except TemplateSyntaxError:
pass
return LoadNode() | [
"def",
"friendly_load",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
">=",
"4",
"and",
"bits",
"[",
"-",
"2",
"]",
"==",
"\"from\"",
":",
"# from syntax is used; load individual tags from the library",
"name",
"=",
"bits",
"[",
"-",
"1",
"]",
"try",
":",
"lib",
"=",
"find_library",
"(",
"parser",
",",
"name",
")",
"subset",
"=",
"load_from_library",
"(",
"lib",
",",
"name",
",",
"bits",
"[",
"1",
":",
"-",
"2",
"]",
")",
"parser",
".",
"add_library",
"(",
"subset",
")",
"except",
"TemplateSyntaxError",
":",
"pass",
"else",
":",
"# one or more libraries are specified; load and add them to the parser",
"for",
"name",
"in",
"bits",
"[",
"1",
":",
"]",
":",
"try",
":",
"lib",
"=",
"find_library",
"(",
"parser",
",",
"name",
")",
"parser",
".",
"add_library",
"(",
"lib",
")",
"except",
"TemplateSyntaxError",
":",
"pass",
"return",
"LoadNode",
"(",
")"
]
| Tries to load a custom template tag set. Non existing tag libraries
are ignored.
This means that, if used in conjunction with ``if_has_tag``, you can try to
load the comments template tag library to enable comments even if the
comments framework is not installed.
For example::
{% load friendly_loader %}
{% friendly_load comments webdesign %}
{% if_has_tag render_comment_list %}
{% render_comment_list for obj %}
{% else %}
{% if_has_tag lorem %}
{% lorem %}
{% endif_has_tag %}
{% endif_has_tag %} | [
"Tries",
"to",
"load",
"a",
"custom",
"template",
"tag",
"set",
".",
"Non",
"existing",
"tag",
"libraries",
"are",
"ignored",
"."
]
| fe6037dbb1a4a97a64b57d0f2212ad77b832057a | https://github.com/ataylor32/django-friendly-tag-loader/blob/fe6037dbb1a4a97a64b57d0f2212ad77b832057a/src/friendlytagloader/templatetags/friendly_loader.py#L19-L59 | train |
jlesquembre/autopilot | src/autopilot/ui.py | CursesManager.off | def off(self):
"""Turn off curses"""
self.win.keypad(0)
curses.nocbreak()
curses.echo()
try:
curses.curs_set(1)
except:
pass
curses.endwin() | python | def off(self):
"""Turn off curses"""
self.win.keypad(0)
curses.nocbreak()
curses.echo()
try:
curses.curs_set(1)
except:
pass
curses.endwin() | [
"def",
"off",
"(",
"self",
")",
":",
"self",
".",
"win",
".",
"keypad",
"(",
"0",
")",
"curses",
".",
"nocbreak",
"(",
")",
"curses",
".",
"echo",
"(",
")",
"try",
":",
"curses",
".",
"curs_set",
"(",
"1",
")",
"except",
":",
"pass",
"curses",
".",
"endwin",
"(",
")"
]
| Turn off curses | [
"Turn",
"off",
"curses"
]
| ca5f36269ba0173bd29c39db6971dac57a58513d | https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/ui.py#L36-L45 | train |
acutesoftware/virtual-AI-simulator | vais/simulator.py | Simulator._move_agent | def _move_agent(self, agent, direction, wrap_allowed=True):
"""
moves agent 'agent' in 'direction'
"""
x,y = agent.coords['x'], agent.coords['y']
print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed)
agent.coords['x'] = x + direction[0]
agent.coords['y'] = y + direction[1] | python | def _move_agent(self, agent, direction, wrap_allowed=True):
"""
moves agent 'agent' in 'direction'
"""
x,y = agent.coords['x'], agent.coords['y']
print('moving agent ', agent.name, 'to x,y=', direction, 'wrap_allowed = ', wrap_allowed)
agent.coords['x'] = x + direction[0]
agent.coords['y'] = y + direction[1] | [
"def",
"_move_agent",
"(",
"self",
",",
"agent",
",",
"direction",
",",
"wrap_allowed",
"=",
"True",
")",
":",
"x",
",",
"y",
"=",
"agent",
".",
"coords",
"[",
"'x'",
"]",
",",
"agent",
".",
"coords",
"[",
"'y'",
"]",
"print",
"(",
"'moving agent '",
",",
"agent",
".",
"name",
",",
"'to x,y='",
",",
"direction",
",",
"'wrap_allowed = '",
",",
"wrap_allowed",
")",
"agent",
".",
"coords",
"[",
"'x'",
"]",
"=",
"x",
"+",
"direction",
"[",
"0",
"]",
"agent",
".",
"coords",
"[",
"'y'",
"]",
"=",
"y",
"+",
"direction",
"[",
"1",
"]"
]
| moves agent 'agent' in 'direction' | [
"moves",
"agent",
"agent",
"in",
"direction"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/simulator.py#L107-L114 | train |
Xion/taipan | taipan/functional/functions.py | key_func | def key_func(*keys, **kwargs):
"""Creates a "key function" based on given keys.
Resulting function will perform lookup using specified keys, in order,
on the object passed to it as an argument.
For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.
:param keys: Lookup keys
:param default: Optional keyword argument specifying default value
that will be returned when some lookup key is not present
:return: Unary key function
"""
ensure_argcount(keys, min_=1)
ensure_keyword_args(kwargs, optional=('default',))
keys = list(map(ensure_string, keys))
if 'default' in kwargs:
default = kwargs['default']
def getitems(obj):
for key in keys:
try:
obj = obj[key]
except KeyError:
return default
return obj
else:
if len(keys) == 1:
getitems = operator.itemgetter(keys[0])
else:
def getitems(obj):
for key in keys:
obj = obj[key]
return obj
return getitems | python | def key_func(*keys, **kwargs):
"""Creates a "key function" based on given keys.
Resulting function will perform lookup using specified keys, in order,
on the object passed to it as an argument.
For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.
:param keys: Lookup keys
:param default: Optional keyword argument specifying default value
that will be returned when some lookup key is not present
:return: Unary key function
"""
ensure_argcount(keys, min_=1)
ensure_keyword_args(kwargs, optional=('default',))
keys = list(map(ensure_string, keys))
if 'default' in kwargs:
default = kwargs['default']
def getitems(obj):
for key in keys:
try:
obj = obj[key]
except KeyError:
return default
return obj
else:
if len(keys) == 1:
getitems = operator.itemgetter(keys[0])
else:
def getitems(obj):
for key in keys:
obj = obj[key]
return obj
return getitems | [
"def",
"key_func",
"(",
"*",
"keys",
",",
"*",
"*",
"kwargs",
")",
":",
"ensure_argcount",
"(",
"keys",
",",
"min_",
"=",
"1",
")",
"ensure_keyword_args",
"(",
"kwargs",
",",
"optional",
"=",
"(",
"'default'",
",",
")",
")",
"keys",
"=",
"list",
"(",
"map",
"(",
"ensure_string",
",",
"keys",
")",
")",
"if",
"'default'",
"in",
"kwargs",
":",
"default",
"=",
"kwargs",
"[",
"'default'",
"]",
"def",
"getitems",
"(",
"obj",
")",
":",
"for",
"key",
"in",
"keys",
":",
"try",
":",
"obj",
"=",
"obj",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default",
"return",
"obj",
"else",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"1",
":",
"getitems",
"=",
"operator",
".",
"itemgetter",
"(",
"keys",
"[",
"0",
"]",
")",
"else",
":",
"def",
"getitems",
"(",
"obj",
")",
":",
"for",
"key",
"in",
"keys",
":",
"obj",
"=",
"obj",
"[",
"key",
"]",
"return",
"obj",
"return",
"getitems"
]
| Creates a "key function" based on given keys.
Resulting function will perform lookup using specified keys, in order,
on the object passed to it as an argument.
For example, ``key_func('a', 'b')(foo)`` is equivalent to ``foo['a']['b']``.
:param keys: Lookup keys
:param default: Optional keyword argument specifying default value
that will be returned when some lookup key is not present
:return: Unary key function | [
"Creates",
"a",
"key",
"function",
"based",
"on",
"given",
"keys",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/functions.py#L134-L170 | train |
adamziel/python_translate | python_translate/utils.py | find_files | def find_files(path, patterns):
"""
Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list of matched files
"""
if not isinstance(patterns, (list, tuple)):
patterns = [patterns]
matches = []
for root, dirnames, filenames in os.walk(path):
for pattern in patterns:
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches | python | def find_files(path, patterns):
"""
Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list of matched files
"""
if not isinstance(patterns, (list, tuple)):
patterns = [patterns]
matches = []
for root, dirnames, filenames in os.walk(path):
for pattern in patterns:
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches | [
"def",
"find_files",
"(",
"path",
",",
"patterns",
")",
":",
"if",
"not",
"isinstance",
"(",
"patterns",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"patterns",
"=",
"[",
"patterns",
"]",
"matches",
"=",
"[",
"]",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"for",
"pattern",
"in",
"patterns",
":",
"for",
"filename",
"in",
"fnmatch",
".",
"filter",
"(",
"filenames",
",",
"pattern",
")",
":",
"matches",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"filename",
")",
")",
"return",
"matches"
]
| Returns all files from a given path that matches the pattern or list
of patterns
@type path: str
@param path: A path to traverse
@typ patterns: str|list
@param patterns: A pattern or a list of patterns to match
@rtype: list[str]:
@return: A list of matched files | [
"Returns",
"all",
"files",
"from",
"a",
"given",
"path",
"that",
"matches",
"the",
"pattern",
"or",
"list",
"of",
"patterns"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/utils.py#L18-L40 | train |
adamziel/python_translate | python_translate/utils.py | recursive_update | def recursive_update(_dict, _update):
"""
Same as dict.update, but updates also nested dicts instead of
overriding then
@type _dict: A
@param _dict: dict to apply update to
@type _update: A
@param _update: dict to pick update data from
@return:
"""
for k, v in _update.items():
if isinstance(v, collections.Mapping):
r = recursive_update(_dict.get(k, {}), v)
_dict[k] = r
else:
_dict[k] = _update[k]
return _dict | python | def recursive_update(_dict, _update):
"""
Same as dict.update, but updates also nested dicts instead of
overriding then
@type _dict: A
@param _dict: dict to apply update to
@type _update: A
@param _update: dict to pick update data from
@return:
"""
for k, v in _update.items():
if isinstance(v, collections.Mapping):
r = recursive_update(_dict.get(k, {}), v)
_dict[k] = r
else:
_dict[k] = _update[k]
return _dict | [
"def",
"recursive_update",
"(",
"_dict",
",",
"_update",
")",
":",
"for",
"k",
",",
"v",
"in",
"_update",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"Mapping",
")",
":",
"r",
"=",
"recursive_update",
"(",
"_dict",
".",
"get",
"(",
"k",
",",
"{",
"}",
")",
",",
"v",
")",
"_dict",
"[",
"k",
"]",
"=",
"r",
"else",
":",
"_dict",
"[",
"k",
"]",
"=",
"_update",
"[",
"k",
"]",
"return",
"_dict"
]
| Same as dict.update, but updates also nested dicts instead of
overriding then
@type _dict: A
@param _dict: dict to apply update to
@type _update: A
@param _update: dict to pick update data from
@return: | [
"Same",
"as",
"dict",
".",
"update",
"but",
"updates",
"also",
"nested",
"dicts",
"instead",
"of",
"overriding",
"then"
]
| 0aee83f434bd2d1b95767bcd63adb7ac7036c7df | https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/utils.py#L43-L62 | train |
UMIACS/qav | qav/validators.py | Validator.validate | def validate(self, value):
'''The most basic validation'''
if not self.blank and value == '':
self.error_message = 'Can not be empty. Please provide a value.'
return False
self._choice = value
return True | python | def validate(self, value):
'''The most basic validation'''
if not self.blank and value == '':
self.error_message = 'Can not be empty. Please provide a value.'
return False
self._choice = value
return True | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"blank",
"and",
"value",
"==",
"''",
":",
"self",
".",
"error_message",
"=",
"'Can not be empty. Please provide a value.'",
"return",
"False",
"self",
".",
"_choice",
"=",
"value",
"return",
"True"
]
| The most basic validation | [
"The",
"most",
"basic",
"validation"
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L42-L48 | train |
UMIACS/qav | qav/validators.py | DomainNameValidator.validate | def validate(self, value):
"""Attempts a forward lookup via the socket library and if
successful will try to do a reverse lookup to verify DNS
is returning both lookups.
"""
if '.' not in value:
self.error_message = '%s is not a fully qualified domain name.' % \
value
return False
try:
ipaddress = socket.gethostbyname(value)
except socket.gaierror:
self.error_message = '%s does not resolve.' % value
return False
try:
socket.gethostbyaddr(ipaddress)
except socket.herror:
self.error_message = \
'%s reverse address (%s) does not resolve.' % \
(value, ipaddress)
return False
self._choice = value
return True | python | def validate(self, value):
"""Attempts a forward lookup via the socket library and if
successful will try to do a reverse lookup to verify DNS
is returning both lookups.
"""
if '.' not in value:
self.error_message = '%s is not a fully qualified domain name.' % \
value
return False
try:
ipaddress = socket.gethostbyname(value)
except socket.gaierror:
self.error_message = '%s does not resolve.' % value
return False
try:
socket.gethostbyaddr(ipaddress)
except socket.herror:
self.error_message = \
'%s reverse address (%s) does not resolve.' % \
(value, ipaddress)
return False
self._choice = value
return True | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"'.'",
"not",
"in",
"value",
":",
"self",
".",
"error_message",
"=",
"'%s is not a fully qualified domain name.'",
"%",
"value",
"return",
"False",
"try",
":",
"ipaddress",
"=",
"socket",
".",
"gethostbyname",
"(",
"value",
")",
"except",
"socket",
".",
"gaierror",
":",
"self",
".",
"error_message",
"=",
"'%s does not resolve.'",
"%",
"value",
"return",
"False",
"try",
":",
"socket",
".",
"gethostbyaddr",
"(",
"ipaddress",
")",
"except",
"socket",
".",
"herror",
":",
"self",
".",
"error_message",
"=",
"'%s reverse address (%s) does not resolve.'",
"%",
"(",
"value",
",",
"ipaddress",
")",
"return",
"False",
"self",
".",
"_choice",
"=",
"value",
"return",
"True"
]
| Attempts a forward lookup via the socket library and if
successful will try to do a reverse lookup to verify DNS
is returning both lookups. | [
"Attempts",
"a",
"forward",
"lookup",
"via",
"the",
"socket",
"library",
"and",
"if",
"successful",
"will",
"try",
"to",
"do",
"a",
"reverse",
"lookup",
"to",
"verify",
"DNS",
"is",
"returning",
"both",
"lookups",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/validators.py#L125-L147 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.