repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
timgabets/bpc8583
bpc8583/terminal.py
Terminal.set_terminal_key
def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key """ if encrypted_key: try: new_key = bytes.fromhex(encrypted_key) if l...
python
def set_terminal_key(self, encrypted_key): """ Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key """ if encrypted_key: try: new_key = bytes.fromhex(encrypted_key) if l...
[ "def", "set_terminal_key", "(", "self", ",", "encrypted_key", ")", ":", "if", "encrypted_key", ":", "try", ":", "new_key", "=", "bytes", ".", "fromhex", "(", "encrypted_key", ")", "if", "len", "(", "self", ".", "terminal_key", ")", "!=", "len", "(", "new...
Change the terminal key. The encrypted_key is a hex string. encrypted_key is expected to be encrypted under master key
[ "Change", "the", "terminal", "key", ".", "The", "encrypted_key", "is", "a", "hex", "string", ".", "encrypted_key", "is", "expected", "to", "be", "encrypted", "under", "master", "key" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/terminal.py#L144-L166
timgabets/bpc8583
bpc8583/terminal.py
Terminal.get_encrypted_pin
def get_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """ if not self.terminal_key: print('Terminal key is not set') return '' if self.pinblock_format == '01': try: ...
python
def get_encrypted_pin(self, clear_pin, card_number): """ Get PIN block in ISO 0 format, encrypted with the terminal key """ if not self.terminal_key: print('Terminal key is not set') return '' if self.pinblock_format == '01': try: ...
[ "def", "get_encrypted_pin", "(", "self", ",", "clear_pin", ",", "card_number", ")", ":", "if", "not", "self", ".", "terminal_key", ":", "print", "(", "'Terminal key is not set'", ")", "return", "''", "if", "self", ".", "pinblock_format", "==", "'01'", ":", "...
Get PIN block in ISO 0 format, encrypted with the terminal key
[ "Get", "PIN", "block", "in", "ISO", "0", "format", "encrypted", "with", "the", "terminal", "key" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/terminal.py#L176-L196
daveoncode/python-string-utils
string_utils.py
is_url
def is_url(string, allowed_schemes=None): """ Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool """ if not...
python
def is_url(string, allowed_schemes=None): """ Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool """ if not...
[ "def", "is_url", "(", "string", ",", "allowed_schemes", "=", "None", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "valid", "=", "bool", "(", "URL_RE", ".", "search", "(", "string", ")", ")", "if", "allowed_schemes"...
Check if a string is a valid url. :param string: String to check. :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :return: True if url, false otherwise :rtype: bool
[ "Check", "if", "a", "string", "is", "a", "valid", "url", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L184-L198
daveoncode/python-string-utils
string_utils.py
is_credit_card
def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card typ...
python
def is_credit_card(string, card_type=None): """ Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card typ...
[ "def", "is_credit_card", "(", "string", ",", "card_type", "=", "None", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "if", "card_type", ":", "if", "card_type", "not", "in", "CREDIT_CARDS", ":", "raise", "KeyError", "(...
Checks if a string is a valid credit card number. If card type is provided then it checks that specific type, otherwise any known credit card number will be accepted. :param string: String to check. :type string: str :param card_type: Card type. :type card_type: str Can be one of these: ...
[ "Checks", "if", "a", "string", "is", "a", "valid", "credit", "card", "number", ".", "If", "card", "type", "is", "provided", "then", "it", "checks", "that", "specific", "type", "otherwise", "any", "known", "credit", "card", "number", "will", "be", "accepted...
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L223-L259
daveoncode/python-string-utils
string_utils.py
is_snake_case
def is_snake_case(string, separator='_'): """ Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore...
python
def is_snake_case(string, separator='_'): """ Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore...
[ "def", "is_snake_case", "(", "string", ",", "separator", "=", "'_'", ")", ":", "if", "is_full_string", "(", "string", ")", ":", "re_map", "=", "{", "'_'", ":", "SNAKE_CASE_TEST_RE", ",", "'-'", ":", "SNAKE_CASE_TEST_DASH_RE", "}", "re_template", "=", "'^[a-z...
Checks if a string is formatted as snake case. A string is considered snake case when: * it's composed only by lowercase letters ([a-z]), underscores (or provided separator) \ and optionally numbers ([0-9]) * it does not start/end with an underscore (or provided separator) * it does not start with ...
[ "Checks", "if", "a", "string", "is", "formatted", "as", "snake", "case", ".", "A", "string", "is", "considered", "snake", "case", "when", ":" ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L280-L306
daveoncode/python-string-utils
string_utils.py
is_json
def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool """ if not is_full_string(string): return False if bool(JSON_WRAPPER_RE.search(string)): try: ...
python
def is_json(string): """ Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool """ if not is_full_string(string): return False if bool(JSON_WRAPPER_RE.search(string)): try: ...
[ "def", "is_json", "(", "string", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "if", "bool", "(", "JSON_WRAPPER_RE", ".", "search", "(", "string", ")", ")", ":", "try", ":", "return", "isinstance", "(", "json", "....
Check if a string is a valid json. :param string: String to check. :type string: str :return: True if json, false otherwise :rtype: bool
[ "Check", "if", "a", "string", "is", "a", "valid", "json", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L309-L325
daveoncode/python-string-utils
string_utils.py
is_palindrome
def is_palindrome(string, strict=True): """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the strin...
python
def is_palindrome(string, strict=True): """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the strin...
[ "def", "is_palindrome", "(", "string", ",", "strict", "=", "True", ")", ":", "if", "is_full_string", "(", "string", ")", ":", "if", "strict", ":", "return", "reverse", "(", "string", ")", "==", "string", "return", "is_palindrome", "(", "SPACES_RE", ".", ...
Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). :param string: String to check. :type string: str :param strict: True if white spaces matter (default), false otherwise. :type strict: bool :return: True if the string is a palindrome (like "otto", or "i topi non aveva...
[ "Checks", "if", "the", "string", "is", "a", "palindrome", "(", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Palindrome", ")", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L352-L367
daveoncode/python-string-utils
string_utils.py
is_pangram
def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. """ return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset...
python
def is_pangram(string): """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise. """ return is_full_string(string) and set(SPACES_RE.sub('', string)).issuperset...
[ "def", "is_pangram", "(", "string", ")", ":", "return", "is_full_string", "(", "string", ")", "and", "set", "(", "SPACES_RE", ".", "sub", "(", "''", ",", "string", ")", ")", ".", "issuperset", "(", "letters_set", ")" ]
Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). :param string: String to check. :type string: str :return: True if the string is a pangram, False otherwise.
[ "Checks", "if", "the", "string", "is", "a", "pangram", "(", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Pangram", ")", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L370-L378
daveoncode/python-string-utils
string_utils.py
is_slug
def is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise. """ if not is_full_string(string): return False rex =...
python
def is_slug(string, sign='-'): """ Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise. """ if not is_full_string(string): return False rex =...
[ "def", "is_slug", "(", "string", ",", "sign", "=", "'-'", ")", ":", "if", "not", "is_full_string", "(", "string", ")", ":", "return", "False", "rex", "=", "r'^([a-z\\d]+'", "+", "re", ".", "escape", "(", "sign", ")", "+", "r'?)*[a-z\\d]$'", "return", "...
Checks if a given string is a slug. :param string: String to check. :type string: str :param sign: Join sign used by the slug. :type sign: str :return: True if slug, false otherwise.
[ "Checks", "if", "a", "given", "string", "is", "a", "slug", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L392-L405
daveoncode/python-string-utils
string_utils.py
camel_case_to_snake
def camel_case_to_snake(string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str ...
python
def camel_case_to_snake(string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str ...
[ "def", "camel_case_to_snake", "(", "string", ",", "separator", "=", "'_'", ")", ":", "if", "not", "is_string", "(", "string", ")", ":", "raise", "TypeError", "(", "'Expected string'", ")", "if", "not", "is_camel_case", "(", "string", ")", ":", "return", "s...
Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) :param string: String to convert. :type string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. :rtype: str
[ "Convert", "a", "camel", "case", "string", "into", "a", "snake", "case", "one", ".", "(", "The", "original", "string", "is", "returned", "if", "is", "not", "a", "valid", "camel", "case", "string", ")" ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L453-L469
daveoncode/python-string-utils
string_utils.py
snake_case_to_camel
def snake_case_to_camel(string, upper_case_first=True, separator='_'): """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first...
python
def snake_case_to_camel(string, upper_case_first=True, separator='_'): """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first...
[ "def", "snake_case_to_camel", "(", "string", ",", "upper_case_first", "=", "True", ",", "separator", "=", "'_'", ")", ":", "if", "not", "is_string", "(", "string", ")", ":", "raise", "TypeError", "(", "'Expected string'", ")", "if", "not", "is_snake_case", "...
Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) :param string: String to convert. :type string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separ...
[ "Convert", "a", "snake", "case", "string", "into", "a", "camel", "case", "one", ".", "(", "The", "original", "string", "is", "returned", "if", "is", "not", "a", "valid", "snake", "case", "string", ")" ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L472-L498
daveoncode/python-string-utils
string_utils.py
shuffle
def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str """ s = sorted(string) # turn the string into a list of chars random.shuffle(s) # shuffle the list return ''.join(s)
python
def shuffle(string): """ Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str """ s = sorted(string) # turn the string into a list of chars random.shuffle(s) # shuffle the list return ''.join(s)
[ "def", "shuffle", "(", "string", ")", ":", "s", "=", "sorted", "(", "string", ")", "# turn the string into a list of chars", "random", ".", "shuffle", "(", "s", ")", "# shuffle the list", "return", "''", ".", "join", "(", "s", ")" ]
Return a new string containing shuffled items. :param string: String to shuffle :type string: str :return: Shuffled string :rtype: str
[ "Return", "a", "new", "string", "containing", "shuffled", "items", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L511-L522
daveoncode/python-string-utils
string_utils.py
strip_html
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool ...
python
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool ...
[ "def", "strip_html", "(", "string", ",", "keep_tag_content", "=", "False", ")", ":", "r", "=", "HTML_TAG_ONLY_RE", "if", "keep_tag_content", "else", "HTML_RE", "return", "r", ".", "sub", "(", "''", ",", "string", ")" ]
Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. :rtype: str
[ "Remove", "html", "code", "contained", "into", "the", "given", "string", "." ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L525-L537
daveoncode/python-string-utils
string_utils.py
prettify
def prettify(string): """ Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operator...
python
def prettify(string): """ Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operator...
[ "def", "prettify", "(", "string", ")", ":", "def", "remove_duplicates", "(", "regex_match", ")", ":", "return", "regex_match", ".", "group", "(", "1", ")", "[", "0", "]", "def", "uppercase_first_letter_after_sign", "(", "regex_match", ")", ":", "match", "=",...
Turns an ugly text string into a beautiful one by applying a regex pipeline which ensures the following: - String cannot start or end with spaces - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \*, =) must have one, ...
[ "Turns", "an", "ugly", "text", "string", "into", "a", "beautiful", "one", "by", "applying", "a", "regex", "pipeline", "which", "ensures", "the", "following", ":" ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L540-L595
daveoncode/python-string-utils
string_utils.py
slugify
def slugify(string, sign='-'): """ Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugifie...
python
def slugify(string, sign='-'): """ Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugifie...
[ "def", "slugify", "(", "string", ",", "sign", "=", "'-'", ")", ":", "if", "not", "is_string", "(", "string", ")", ":", "raise", "TypeError", "(", "'Expected string'", ")", "# unicode casting for python 2 (unicode is default for python 3)", "try", ":", "string", "=...
Converts a string into a slug using provided join sign. (**(This Is A "Test"!)** -> **this-is-a-test**) :param string: String to convert. :type string: str :param sign: Sign used to join string tokens (default to "-"). :type sign: str :return: Slugified string
[ "Converts", "a", "string", "into", "a", "slug", "using", "provided", "join", "sign", ".", "(", "**", "(", "This", "Is", "A", "Test", "!", ")", "**", "-", ">", "**", "this", "-", "is", "-", "a", "-", "test", "**", ")" ]
train
https://github.com/daveoncode/python-string-utils/blob/5dfe43c26aeecd01941c598316eb4eb7005a1492/string_utils.py#L598-L630
vidartf/nbsphinx-link
nbsphinx_link/__init__.py
setup
def setup(app): """Initialize Sphinx extension.""" app.setup_extension('nbsphinx') app.add_source_suffix('.nblink', 'linked_jupyter_notebook') app.add_source_parser(LinkedNotebookParser) app.add_config_value('nbsphinx_link_target_root', None, rebuild='env') return {'version': __version__, 'para...
python
def setup(app): """Initialize Sphinx extension.""" app.setup_extension('nbsphinx') app.add_source_suffix('.nblink', 'linked_jupyter_notebook') app.add_source_parser(LinkedNotebookParser) app.add_config_value('nbsphinx_link_target_root', None, rebuild='env') return {'version': __version__, 'para...
[ "def", "setup", "(", "app", ")", ":", "app", ".", "setup_extension", "(", "'nbsphinx'", ")", "app", ".", "add_source_suffix", "(", "'.nblink'", ",", "'linked_jupyter_notebook'", ")", "app", ".", "add_source_parser", "(", "LinkedNotebookParser", ")", "app", ".", ...
Initialize Sphinx extension.
[ "Initialize", "Sphinx", "extension", "." ]
train
https://github.com/vidartf/nbsphinx-link/blob/d64288606a8cc50461792dd3033f5ff081602afc/nbsphinx_link/__init__.py#L100-L107
vidartf/nbsphinx-link
nbsphinx_link/__init__.py
LinkedNotebookParser.parse
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
python
def parse(self, inputstring, document): """Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser. """ link = json.loads(inputstring) env = document.settings.env source_dir = os.path.dirname...
[ "def", "parse", "(", "self", ",", "inputstring", ",", "document", ")", ":", "link", "=", "json", ".", "loads", "(", "inputstring", ")", "env", "=", "document", ".", "settings", ".", "env", "source_dir", "=", "os", ".", "path", ".", "dirname", "(", "e...
Parse the nblink file. Adds the linked file as a dependency, read the file, and pass the content to the nbshpinx.NotebookParser.
[ "Parse", "the", "nblink", "file", "." ]
train
https://github.com/vidartf/nbsphinx-link/blob/d64288606a8cc50461792dd3033f5ff081602afc/nbsphinx_link/__init__.py#L48-L96
ucsb-cs-education/hairball
hairball/plugins/duplicate.py
DuplicateScripts.finalize
def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
python
def finalize(self): """Output the duplicate scripts detected.""" if self.total_duplicate > 0: print('{} duplicate scripts found'.format(self.total_duplicate)) for duplicate in self.list_duplicate: print(duplicate)
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "total_duplicate", ">", "0", ":", "print", "(", "'{} duplicate scripts found'", ".", "format", "(", "self", ".", "total_duplicate", ")", ")", "for", "duplicate", "in", "self", ".", "list_duplicate"...
Output the duplicate scripts detected.
[ "Output", "the", "duplicate", "scripts", "detected", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/duplicate.py#L17-L22
ucsb-cs-education/hairball
hairball/plugins/duplicate.py
DuplicateScripts.analyze
def analyze(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. """ scripts_set = set() for script in self.iter_scripts(scratch): if script[0].type.text == 'define %s': ...
python
def analyze(self, scratch, **kwargs): """Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks. """ scripts_set = set() for script in self.iter_scripts(scratch): if script[0].type.text == 'define %s': ...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "scripts_set", "=", "set", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "if", "script", "[", "0", "]", ".", "type", ".", ...
Run and return the results from the DuplicateScripts plugin. Only takes into account scripts with more than 3 blocks.
[ "Run", "and", "return", "the", "results", "from", "the", "DuplicateScripts", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/duplicate.py#L24-L43
ramses-tech/nefertari
nefertari/renderers.py
JsonRendererFactory._set_content_type
def _set_content_type(self, system): """ Set response content type """ request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'applicati...
python
def _set_content_type(self, system): """ Set response content type """ request = system.get('request') if request: response = request.response ct = response.content_type if ct == response.default_content_type: response.content_type = 'applicati...
[ "def", "_set_content_type", "(", "self", ",", "system", ")", ":", "request", "=", "system", ".", "get", "(", "'request'", ")", "if", "request", ":", "response", "=", "request", ".", "response", "ct", "=", "response", ".", "content_type", "if", "ct", "=="...
Set response content type
[ "Set", "response", "content", "type" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L35-L42
ramses-tech/nefertari
nefertari/renderers.py
JsonRendererFactory._render_response
def _render_response(self, value, system): """ Render a response """ view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
python
def _render_response(self, value, system): """ Render a response """ view = system['view'] enc_class = getattr(view, '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return json.dumps(value, cls=enc_class)
[ "def", "_render_response", "(", "self", ",", "value", ",", "system", ")", ":", "view", "=", "system", "[", "'view'", "]", "enc_class", "=", "getattr", "(", "view", ",", "'_json_encoder'", ",", "None", ")", "if", "enc_class", "is", "None", ":", "enc_class...
Render a response
[ "Render", "a", "response" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L44-L50
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin._get_common_kwargs
def _get_common_kwargs(self, system): """ Get kwargs common for all methods. """ enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request'], 'encoder': enc_class...
python
def _get_common_kwargs(self, system): """ Get kwargs common for all methods. """ enc_class = getattr(system['view'], '_json_encoder', None) if enc_class is None: enc_class = get_json_encoder() return { 'request': system['request'], 'encoder': enc_class...
[ "def", "_get_common_kwargs", "(", "self", ",", "system", ")", ":", "enc_class", "=", "getattr", "(", "system", "[", "'view'", "]", ",", "'_json_encoder'", ",", "None", ")", "if", "enc_class", "is", "None", ":", "enc_class", "=", "get_json_encoder", "(", ")...
Get kwargs common for all methods.
[ "Get", "kwargs", "common", "for", "all", "methods", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L86-L94
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin._get_create_update_kwargs
def _get_create_update_kwargs(self, value, common_kw): """ Get kwargs common to create, update, replace. """ kw = common_kw.copy() kw['body'] = value if '_self' in value: kw['headers'] = [('Location', value['_self'])] return kw
python
def _get_create_update_kwargs(self, value, common_kw): """ Get kwargs common to create, update, replace. """ kw = common_kw.copy() kw['body'] = value if '_self' in value: kw['headers'] = [('Location', value['_self'])] return kw
[ "def", "_get_create_update_kwargs", "(", "self", ",", "value", ",", "common_kw", ")", ":", "kw", "=", "common_kw", ".", "copy", "(", ")", "kw", "[", "'body'", "]", "=", "value", "if", "'_self'", "in", "value", ":", "kw", "[", "'headers'", "]", "=", "...
Get kwargs common to create, update, replace.
[ "Get", "kwargs", "common", "to", "create", "update", "replace", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L96-L102
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin.render_create
def render_create(self, value, system, common_kw): """ Render response for view `create` method (collection POST) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPCreated(**kw)
python
def render_create(self, value, system, common_kw): """ Render response for view `create` method (collection POST) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPCreated(**kw)
[ "def", "render_create", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "kw", "=", "self", ".", "_get_create_update_kwargs", "(", "value", ",", "common_kw", ")", "return", "JHTTPCreated", "(", "*", "*", "kw", ")" ]
Render response for view `create` method (collection POST)
[ "Render", "response", "for", "view", "create", "method", "(", "collection", "POST", ")" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L104-L107
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin.render_update
def render_update(self, value, system, common_kw): """ Render response for view `update` method (item PATCH) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPOk('Updated', **kw)
python
def render_update(self, value, system, common_kw): """ Render response for view `update` method (item PATCH) """ kw = self._get_create_update_kwargs(value, common_kw) return JHTTPOk('Updated', **kw)
[ "def", "render_update", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "kw", "=", "self", ".", "_get_create_update_kwargs", "(", "value", ",", "common_kw", ")", "return", "JHTTPOk", "(", "'Updated'", ",", "*", "*", "kw", ")" ]
Render response for view `update` method (item PATCH)
[ "Render", "response", "for", "view", "update", "method", "(", "item", "PATCH", ")" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L109-L112
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin.render_delete_many
def render_delete_many(self, value, system, common_kw): """ Render response for view `delete_many` method (collection DELETE) """ if isinstance(value, dict): return JHTTPOk(extra=value) msg = 'Deleted {} {}(s) objects'.format( value, system['view'].Model.__name__)...
python
def render_delete_many(self, value, system, common_kw): """ Render response for view `delete_many` method (collection DELETE) """ if isinstance(value, dict): return JHTTPOk(extra=value) msg = 'Deleted {} {}(s) objects'.format( value, system['view'].Model.__name__)...
[ "def", "render_delete_many", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "JHTTPOk", "(", "extra", "=", "value", ")", "msg", "=", "'Deleted {} {}(s) objects'", ".",...
Render response for view `delete_many` method (collection DELETE)
[ "Render", "response", "for", "view", "delete_many", "method", "(", "collection", "DELETE", ")" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L122-L129
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin.render_update_many
def render_update_many(self, value, system, common_kw): """ Render response for view `update_many` method (collection PUT/PATCH) """ msg = 'Updated {} {}(s) objects'.format( value, system['view'].Model.__name__) return JHTTPOk(msg, **common_kw.copy())
python
def render_update_many(self, value, system, common_kw): """ Render response for view `update_many` method (collection PUT/PATCH) """ msg = 'Updated {} {}(s) objects'.format( value, system['view'].Model.__name__) return JHTTPOk(msg, **common_kw.copy())
[ "def", "render_update_many", "(", "self", ",", "value", ",", "system", ",", "common_kw", ")", ":", "msg", "=", "'Updated {} {}(s) objects'", ".", "format", "(", "value", ",", "system", "[", "'view'", "]", ".", "Model", ".", "__name__", ")", "return", "JHTT...
Render response for view `update_many` method (collection PUT/PATCH)
[ "Render", "response", "for", "view", "update_many", "method", "(", "collection", "PUT", "/", "PATCH", ")" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L131-L137
ramses-tech/nefertari
nefertari/renderers.py
DefaultResponseRendererMixin._render_response
def _render_response(self, value, system): """ Handle response rendering. Calls mixin methods according to request.action value. """ super_call = super(DefaultResponseRendererMixin, self)._render_response try: method_name = 'render_{}'.format(system['request'].action...
python
def _render_response(self, value, system): """ Handle response rendering. Calls mixin methods according to request.action value. """ super_call = super(DefaultResponseRendererMixin, self)._render_response try: method_name = 'render_{}'.format(system['request'].action...
[ "def", "_render_response", "(", "self", ",", "value", ",", "system", ")", ":", "super_call", "=", "super", "(", "DefaultResponseRendererMixin", ",", "self", ")", ".", "_render_response", "try", ":", "method_name", "=", "'render_{}'", ".", "format", "(", "syste...
Handle response rendering. Calls mixin methods according to request.action value.
[ "Handle", "response", "rendering", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/renderers.py#L139-L155
ramses-tech/nefertari
nefertari/authentication/policies.py
ApiKeyAuthenticationPolicy.remember
def remember(self, request, username, **kw): """ Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header. """ if self.credentials_callback: token = self.credentials_callback(username, request) api_key = 'ApiKey {}:{}'.format(us...
python
def remember(self, request, username, **kw): """ Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header. """ if self.credentials_callback: token = self.credentials_callback(username, request) api_key = 'ApiKey {}:{}'.format(us...
[ "def", "remember", "(", "self", ",", "request", ",", "username", ",", "*", "*", "kw", ")", ":", "if", "self", ".", "credentials_callback", ":", "token", "=", "self", ".", "credentials_callback", "(", "username", ",", "request", ")", "api_key", "=", "'Api...
Returns 'WWW-Authenticate' header with a value that should be used in 'Authorization' header.
[ "Returns", "WWW", "-", "Authenticate", "header", "with", "a", "value", "that", "should", "be", "used", "in", "Authorization", "header", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L49-L56
ramses-tech/nefertari
nefertari/authentication/policies.py
ApiKeyAuthenticationPolicy.callback
def callback(self, username, request): """ Having :username: return user's identifiers or None. """ credentials = self._get_credentials(request) if credentials: username, api_key = credentials if self.check: return self.check(username, api_key, request)
python
def callback(self, username, request): """ Having :username: return user's identifiers or None. """ credentials = self._get_credentials(request) if credentials: username, api_key = credentials if self.check: return self.check(username, api_key, request)
[ "def", "callback", "(", "self", ",", "username", ",", "request", ")", ":", "credentials", "=", "self", ".", "_get_credentials", "(", "request", ")", "if", "credentials", ":", "username", ",", "api_key", "=", "credentials", "if", "self", ".", "check", ":", ...
Having :username: return user's identifiers or None.
[ "Having", ":", "username", ":", "return", "user", "s", "identifiers", "or", "None", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L69-L75
ramses-tech/nefertari
nefertari/authentication/policies.py
ApiKeyAuthenticationPolicy._get_credentials
def _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """ authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except...
python
def _get_credentials(self, request): """ Extract username and api key token from 'Authorization' header """ authorization = request.headers.get('Authorization') if not authorization: return None try: authmeth, authbytes = authorization.split(' ', 1) except...
[ "def", "_get_credentials", "(", "self", ",", "request", ")", ":", "authorization", "=", "request", ".", "headers", ".", "get", "(", "'Authorization'", ")", "if", "not", "authorization", ":", "return", "None", "try", ":", "authmeth", ",", "authbytes", "=", ...
Extract username and api key token from 'Authorization' header
[ "Extract", "username", "and", "api", "key", "token", "from", "Authorization", "header" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/authentication/policies.py#L77-L101
ramses-tech/nefertari
nefertari/events.py
_get_event_kwargs
def _get_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired. """ request = view_obj.request view_method = getattr(view_obj, request.ac...
python
def _get_event_kwargs(view_obj): """ Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired. """ request = view_obj.request view_method = getattr(view_obj, request.ac...
[ "def", "_get_event_kwargs", "(", "view_obj", ")", ":", "request", "=", "view_obj", ".", "request", "view_method", "=", "getattr", "(", "view_obj", ",", "request", ".", "action", ")", "do_trigger", "=", "not", "(", "getattr", "(", "view_method", ",", "'_silen...
Helper function to get event kwargs. :param view_obj: Instance of View that processes the request. :returns dict: Containing event kwargs or None if events shouldn't be fired.
[ "Helper", "function", "to", "get", "event", "kwargs", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L305-L330
ramses-tech/nefertari
nefertari/events.py
_get_event_cls
def _get_event_cls(view_obj, events_map): """ Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class. """ request = view_obj.request view_...
python
def _get_event_cls(view_obj, events_map): """ Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class. """ request = view_obj.request view_...
[ "def", "_get_event_cls", "(", "view_obj", ",", "events_map", ")", ":", "request", "=", "view_obj", ".", "request", "view_method", "=", "getattr", "(", "view_obj", ",", "request", ".", "action", ")", "event_action", "=", "(", "getattr", "(", "view_method", ",...
Helper function to get event class. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Found event class.
[ "Helper", "function", "to", "get", "event", "class", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L333-L346
ramses-tech/nefertari
nefertari/events.py
_trigger_events
def _trigger_events(view_obj, events_map, additional_kw=None): """ Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. """ ...
python
def _trigger_events(view_obj, events_map, additional_kw=None): """ Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event. """ ...
[ "def", "_trigger_events", "(", "view_obj", ",", "events_map", ",", "additional_kw", "=", "None", ")", ":", "if", "additional_kw", "is", "None", ":", "additional_kw", "=", "{", "}", "event_kwargs", "=", "_get_event_kwargs", "(", "view_obj", ")", "if", "event_kw...
Common logic to trigger before/after events. :param view_obj: Instance of View that processes the request. :param events_map: Map of events from which event class should be picked. :returns: Instance if triggered event.
[ "Common", "logic", "to", "trigger", "before", "/", "after", "events", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L349-L368
ramses-tech/nefertari
nefertari/events.py
subscribe_to_events
def subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value. """...
python
def subscribe_to_events(config, subscriber, events, model=None): """ Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value. """...
[ "def", "subscribe_to_events", "(", "config", ",", "subscriber", ",", "events", ",", "model", "=", "None", ")", ":", "kwargs", "=", "{", "}", "if", "model", "is", "not", "None", ":", "kwargs", "[", "'model'", "]", "=", "model", "for", "evt", "in", "ev...
Helper function to subscribe to group of events. :param config: Pyramid contig instance. :param subscriber: Event subscriber function. :param events: Sequence of events to subscribe to. :param model: Model predicate value.
[ "Helper", "function", "to", "subscribe", "to", "group", "of", "events", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L393-L406
ramses-tech/nefertari
nefertari/events.py
add_field_processors
def add_field_processors(config, processors, model, field): """ Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of fie...
python
def add_field_processors(config, processors, model, field): """ Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of fie...
[ "def", "add_field_processors", "(", "config", ",", "processors", ",", "model", ",", "field", ")", ":", "before_change_events", "=", "(", "BeforeCreate", ",", "BeforeUpdate", ",", "BeforeReplace", ",", "BeforeUpdateMany", ",", "BeforeRegister", ",", ")", "def", "...
Add processors for model field. Under the hood, regular nefertari event subscribed is created which calls field processors in order passed to this function. Processors are passed following params: * **new_value**: New value of of field. * **instance**: Instance affected by request. Is None when s...
[ "Add", "processors", "for", "model", "field", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L409-L459
ramses-tech/nefertari
nefertari/events.py
BeforeEvent.set_field_value
def set_field_value(self, field_name, value): """ Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self...
python
def set_field_value(self, field_name, value): """ Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self...
[ "def", "set_field_value", "(", "self", ",", "field_name", ",", "value", ")", ":", "self", ".", "view", ".", "_json_params", "[", "field_name", "]", "=", "value", "if", "field_name", "in", "self", ".", "fields", ":", "self", ".", "fields", "[", "field_nam...
Set value of request field named `field_name`. Use this method to apply changes to object which is affected by request. Values are set on `view._json_params` dict. If `field_name` is not affected by request, it is added to `self.fields` which makes field processors which are connected ...
[ "Set", "value", "of", "request", "field", "named", "field_name", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L46-L68
ramses-tech/nefertari
nefertari/events.py
AfterEvent.set_field_value
def set_field_value(self, field_name, value): """ Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response dire...
python
def set_field_value(self, field_name, value): """ Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response dire...
[ "def", "set_field_value", "(", "self", ",", "field_name", ",", "value", ")", ":", "if", "self", ".", "response", "is", "None", ":", "return", "if", "'data'", "in", "self", ".", "response", ":", "items", "=", "self", ".", "response", "[", "'data'", "]",...
Set value of response field named `field_name`. If response contains single item, its field is set. If response contains multiple items, all the items in response are edited. To edit response meta(e.g. 'count') edit response directly at `event.response`. :param field_na...
[ "Set", "value", "of", "response", "field", "named", "field_name", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/events.py#L76-L98
ramses-tech/nefertari
nefertari/elasticsearch.py
process_fields_param
def process_fields_param(fields): """ Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None' """ if not fields: return fields if isinstance(fields, six.string_types): fields =...
python
def process_fields_param(fields): """ Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None' """ if not fields: return fields if isinstance(fields, six.string_types): fields =...
[ "def", "process_fields_param", "(", "fields", ")", ":", "if", "not", "fields", ":", "return", "fields", "if", "isinstance", "(", "fields", ",", "six", ".", "string_types", ")", ":", "fields", "=", "split_strip", "(", "fields", ")", "if", "'_type'", "not", ...
Process 'fields' ES param. * Fields list is split if needed * '_type' field is added, if not present, so the actual value is displayed instead of 'None'
[ "Process", "fields", "ES", "param", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L98-L114
ramses-tech/nefertari
nefertari/elasticsearch.py
ESHttpConnection._catch_index_error
def _catch_index_error(self, response): """ Catch and raise index errors which are not critical and thus not raised by elasticsearch-py. """ code, headers, raw_data = response if not raw_data: return data = json.loads(raw_data) if not data or not data....
python
def _catch_index_error(self, response): """ Catch and raise index errors which are not critical and thus not raised by elasticsearch-py. """ code, headers, raw_data = response if not raw_data: return data = json.loads(raw_data) if not data or not data....
[ "def", "_catch_index_error", "(", "self", ",", "response", ")", ":", "code", ",", "headers", ",", "raw_data", "=", "response", "if", "not", "raw_data", ":", "return", "data", "=", "json", ".", "loads", "(", "raw_data", ")", "if", "not", "data", "or", "...
Catch and raise index errors which are not critical and thus not raised by elasticsearch-py.
[ "Catch", "and", "raise", "index", "errors", "which", "are", "not", "critical", "and", "thus", "not", "raised", "by", "elasticsearch", "-", "py", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L25-L40
ramses-tech/nefertari
nefertari/elasticsearch.py
ES.setup_mappings
def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls per...
python
def setup_mappings(cls, force=False): """ Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls per...
[ "def", "setup_mappings", "(", "cls", ",", "force", "=", "False", ")", ":", "if", "getattr", "(", "cls", ",", "'_mappings_setup'", ",", "False", ")", "and", "not", "force", ":", "log", ".", "debug", "(", "'ES mappings have been already set up for currently '", ...
Setup ES mappings for all existing models. This method is meant to be run once at application lauch. ES._mappings_setup flag is set to not run make mapping creation calls on subsequent runs. Use `force=True` to make subsequent calls perform mapping creation calls to ES.
[ "Setup", "ES", "mappings", "for", "all", "existing", "models", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L226-L250
ramses-tech/nefertari
nefertari/elasticsearch.py
ES.process_chunks
def process_chunks(self, documents, operation): """ Apply `operation` to chunks of `documents` of size `self.chunk_size`. """ chunk_size = self.chunk_size start = end = 0 count = len(documents) while count: if count < chunk_size: chun...
python
def process_chunks(self, documents, operation): """ Apply `operation` to chunks of `documents` of size `self.chunk_size`. """ chunk_size = self.chunk_size start = end = 0 count = len(documents) while count: if count < chunk_size: chun...
[ "def", "process_chunks", "(", "self", ",", "documents", ",", "operation", ")", ":", "chunk_size", "=", "self", ".", "chunk_size", "start", "=", "end", "=", "0", "count", "=", "len", "(", "documents", ")", "while", "count", ":", "if", "count", "<", "chu...
Apply `operation` to chunks of `documents` of size `self.chunk_size`.
[ "Apply", "operation", "to", "chunks", "of", "documents", "of", "size", "self", ".", "chunk_size", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L259-L277
ramses-tech/nefertari
nefertari/elasticsearch.py
ES.index_missing_documents
def index_missing_documents(self, documents, request=None): """ Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed. "...
python
def index_missing_documents(self, documents, request=None): """ Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed. "...
[ "def", "index_missing_documents", "(", "self", ",", "documents", ",", "request", "=", "None", ")", ":", "log", ".", "info", "(", "'Trying to index documents of type `{}` missing from '", "'`{}` index'", ".", "format", "(", "self", ".", "doc_type", ",", "self", "."...
Index documents that are missing from ES index. Determines which documents are missing using ES `mget` call which returns a list of document IDs as `documents`. Then missing `documents` from that list are indexed.
[ "Index", "documents", "that", "are", "missing", "from", "ES", "index", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L326-L358
ramses-tech/nefertari
nefertari/elasticsearch.py
ES.aggregate
def aggregate(self, **params): """ Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundExcep...
python
def aggregate(self, **params): """ Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundExcep...
[ "def", "aggregate", "(", "self", ",", "*", "*", "params", ")", ":", "_aggregations_params", "=", "params", ".", "pop", "(", "'_aggregations_params'", ",", "None", ")", "_raise_on_empty", "=", "params", ".", "pop", "(", "'_raise_on_empty'", ",", "False", ")",...
Perform aggreration Arguments: :_aggregations_params: Dict of aggregation params. Root key is an aggregation name. Required. :_raise_on_empty: Boolean indicating whether to raise exception when IndexNotFoundException exception happens. Optional, ...
[ "Perform", "aggreration" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L493-L530
ramses-tech/nefertari
nefertari/elasticsearch.py
ES.bulk_index_relations
def bulk_index_relations(cls, items, request=None, **kwargs): """ Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be ind...
python
def bulk_index_relations(cls, items, request=None, **kwargs): """ Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be ind...
[ "def", "bulk_index_relations", "(", "cls", ",", "items", ",", "request", "=", "None", ",", "*", "*", "kwargs", ")", ":", "index_map", "=", "defaultdict", "(", "set", ")", "for", "item", "in", "items", ":", "relations", "=", "item", ".", "get_related_docu...
Index objects related to :items: in bulk. Related items are first grouped in map {model_name: {item1, item2, ...}} and then indexed. :param items: Sequence of DB objects related objects if which should be indexed. :param request: Pyramid Request instance.
[ "Index", "objects", "related", "to", ":", "items", ":", "in", "bulk", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/elasticsearch.py#L620-L639
sametmax/devpy
setup.py
get_version
def get_version(path="src/devpy/__init__.py"): """ Return the version of by with regex intead of importing it""" init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(1)
python
def get_version(path="src/devpy/__init__.py"): """ Return the version of by with regex intead of importing it""" init_content = open(path, "rt").read() pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" return re.search(pattern, init_content, re.M).group(1)
[ "def", "get_version", "(", "path", "=", "\"src/devpy/__init__.py\"", ")", ":", "init_content", "=", "open", "(", "path", ",", "\"rt\"", ")", ".", "read", "(", ")", "pattern", "=", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", "return", "re", ".", "search", "(...
Return the version of by with regex intead of importing it
[ "Return", "the", "version", "of", "by", "with", "regex", "intead", "of", "importing", "it" ]
train
https://github.com/sametmax/devpy/blob/66a150817644edf825d19b80f644e7d05b2a3e86/setup.py#L7-L11
scalative/haas
haas/plugin_manager.py
PluginManager.add_plugin_arguments
def add_plugin_arguments(self, parser): """Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser. """ for manager in self.hook_managers.values(): if len(list(manager)) == 0: ...
python
def add_plugin_arguments(self, parser): """Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser. """ for manager in self.hook_managers.values(): if len(list(manager)) == 0: ...
[ "def", "add_plugin_arguments", "(", "self", ",", "parser", ")", ":", "for", "manager", "in", "self", ".", "hook_managers", ".", "values", "(", ")", ":", "if", "len", "(", "list", "(", "manager", ")", ")", "==", "0", ":", "continue", "manager", ".", "...
Add plugin arguments to argument parser. Parameters ---------- parser : argparse.ArgumentParser The main haas ArgumentParser.
[ "Add", "plugin", "arguments", "to", "argument", "parser", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L105-L129
scalative/haas
haas/plugin_manager.py
PluginManager.get_enabled_hook_plugins
def get_enabled_hook_plugins(self, hook, args, **kwargs): """Get enabled plugins for specified hook name. """ manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_...
python
def get_enabled_hook_plugins(self, hook, args, **kwargs): """Get enabled plugins for specified hook name. """ manager = self.hook_managers[hook] if len(list(manager)) == 0: return [] return [ plugin for plugin in manager.map( self._create_...
[ "def", "get_enabled_hook_plugins", "(", "self", ",", "hook", ",", "args", ",", "*", "*", "kwargs", ")", ":", "manager", "=", "self", ".", "hook_managers", "[", "hook", "]", "if", "len", "(", "list", "(", "manager", ")", ")", "==", "0", ":", "return",...
Get enabled plugins for specified hook name.
[ "Get", "enabled", "plugins", "for", "specified", "hook", "name", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L131-L142
scalative/haas
haas/plugin_manager.py
PluginManager.get_driver
def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """ option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = ...
python
def get_driver(self, namespace, parsed_args, **kwargs): """Get mutually-exlusive plugin for plugin namespace. """ option, dest = self._namespace_to_option(namespace) dest_prefix = '{0}_'.format(dest) driver_name = getattr(parsed_args, dest, 'default') driver_extension = ...
[ "def", "get_driver", "(", "self", ",", "namespace", ",", "parsed_args", ",", "*", "*", "kwargs", ")", ":", "option", ",", "dest", "=", "self", ".", "_namespace_to_option", "(", "namespace", ")", "dest_prefix", "=", "'{0}_'", ".", "format", "(", "dest", "...
Get mutually-exlusive plugin for plugin namespace.
[ "Get", "mutually", "-", "exlusive", "plugin", "for", "plugin", "namespace", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugin_manager.py#L144-L153
timgabets/bpc8583
bpc8583/transaction.py
Transaction.get_description
def get_description(self): """ Get transaction description (for logging purposes) """ if self.card: card_description = self.card.get_description() else: card_description = 'Cardless' if card_description: card_description += ' | ' ...
python
def get_description(self): """ Get transaction description (for logging purposes) """ if self.card: card_description = self.card.get_description() else: card_description = 'Cardless' if card_description: card_description += ' | ' ...
[ "def", "get_description", "(", "self", ")", ":", "if", "self", ".", "card", ":", "card_description", "=", "self", ".", "card", ".", "get_description", "(", ")", "else", ":", "card_description", "=", "'Cardless'", "if", "card_description", ":", "card_descriptio...
Get transaction description (for logging purposes)
[ "Get", "transaction", "description", "(", "for", "logging", "purposes", ")" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L196-L208
timgabets/bpc8583
bpc8583/transaction.py
Transaction.set_amount
def set_amount(self, amount): """ Set transaction amount """ if amount: try: self.IsoMessage.FieldData(4, int(amount)) except ValueError: self.IsoMessage.FieldData(4, 0) self.rebuild()
python
def set_amount(self, amount): """ Set transaction amount """ if amount: try: self.IsoMessage.FieldData(4, int(amount)) except ValueError: self.IsoMessage.FieldData(4, 0) self.rebuild()
[ "def", "set_amount", "(", "self", ",", "amount", ")", ":", "if", "amount", ":", "try", ":", "self", ".", "IsoMessage", ".", "FieldData", "(", "4", ",", "int", "(", "amount", ")", ")", "except", "ValueError", ":", "self", ".", "IsoMessage", ".", "Fiel...
Set transaction amount
[ "Set", "transaction", "amount" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L244-L253
timgabets/bpc8583
bpc8583/transaction.py
Transaction.set_expected_action
def set_expected_action(self, expected_response_action): """ Expected outcome of the transaction ('APPROVED' or 'DECLINED') """ if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']: return False self.expected_response_action = exp...
python
def set_expected_action(self, expected_response_action): """ Expected outcome of the transaction ('APPROVED' or 'DECLINED') """ if expected_response_action.upper() not in ['APPROVED', 'APPROVE', 'DECLINED', 'DECLINE']: return False self.expected_response_action = exp...
[ "def", "set_expected_action", "(", "self", ",", "expected_response_action", ")", ":", "if", "expected_response_action", ".", "upper", "(", ")", "not", "in", "[", "'APPROVED'", ",", "'APPROVE'", ",", "'DECLINED'", ",", "'DECLINE'", "]", ":", "return", "False", ...
Expected outcome of the transaction ('APPROVED' or 'DECLINED')
[ "Expected", "outcome", "of", "the", "transaction", "(", "APPROVED", "or", "DECLINED", ")" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L263-L271
timgabets/bpc8583
bpc8583/transaction.py
Transaction.build_emv_data
def build_emv_data(self): """ TODO: 95 TVR 82 app_int_prof """ emv_data = '' emv_data += self.TLV.build({'82': self._get_app_interchange_profile()}) emv_data += self.TLV.build({'9A': get_date()}) emv_data += self.TLV.build({'95': self.term.g...
python
def build_emv_data(self): """ TODO: 95 TVR 82 app_int_prof """ emv_data = '' emv_data += self.TLV.build({'82': self._get_app_interchange_profile()}) emv_data += self.TLV.build({'9A': get_date()}) emv_data += self.TLV.build({'95': self.term.g...
[ "def", "build_emv_data", "(", "self", ")", ":", "emv_data", "=", "''", "emv_data", "+=", "self", ".", "TLV", ".", "build", "(", "{", "'82'", ":", "self", ".", "_get_app_interchange_profile", "(", ")", "}", ")", "emv_data", "+=", "self", ".", "TLV", "."...
TODO: 95 TVR 82 app_int_prof
[ "TODO", ":", "95", "TVR", "82", "app_int_prof" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L302-L317
timgabets/bpc8583
bpc8583/transaction.py
Transaction.set_currency
def set_currency(self, currency_id): """ Set transaction currency code from given currency id, e.g. set 840 from 'USD' """ try: self.currency = currency_codes[currency_id] self.IsoMessage.FieldData(49, self.currency) self.rebuild() except KeyEr...
python
def set_currency(self, currency_id): """ Set transaction currency code from given currency id, e.g. set 840 from 'USD' """ try: self.currency = currency_codes[currency_id] self.IsoMessage.FieldData(49, self.currency) self.rebuild() except KeyEr...
[ "def", "set_currency", "(", "self", ",", "currency_id", ")", ":", "try", ":", "self", ".", "currency", "=", "currency_codes", "[", "currency_id", "]", "self", ".", "IsoMessage", ".", "FieldData", "(", "49", ",", "self", ".", "currency", ")", "self", ".",...
Set transaction currency code from given currency id, e.g. set 840 from 'USD'
[ "Set", "transaction", "currency", "code", "from", "given", "currency", "id", "e", ".", "g", ".", "set", "840", "from", "USD" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/transaction.py#L337-L346
ucsb-cs-education/hairball
hairball/plugins/blocks.py
BlockCounts.finalize
def finalize(self): """Output the aggregate block count results.""" for name, count in sorted(self.blocks.items(), key=lambda x: x[1]): print('{:3} {}'.format(count, name)) print('{:3} total'.format(sum(self.blocks.values())))
python
def finalize(self): """Output the aggregate block count results.""" for name, count in sorted(self.blocks.items(), key=lambda x: x[1]): print('{:3} {}'.format(count, name)) print('{:3} total'.format(sum(self.blocks.values())))
[ "def", "finalize", "(", "self", ")", ":", "for", "name", ",", "count", "in", "sorted", "(", "self", ".", "blocks", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", ":", "print", "(", "'{:3} {}'", ".", "forma...
Output the aggregate block count results.
[ "Output", "the", "aggregate", "block", "count", "results", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L17-L21
ucsb-cs-education/hairball
hairball/plugins/blocks.py
BlockCounts.analyze
def analyze(self, scratch, **kwargs): """Run and return the results from the BlockCounts plugin.""" file_blocks = Counter() for script in self.iter_scripts(scratch): for name, _, _ in self.iter_blocks(script.blocks): file_blocks[name] += 1 self.blocks.update(f...
python
def analyze(self, scratch, **kwargs): """Run and return the results from the BlockCounts plugin.""" file_blocks = Counter() for script in self.iter_scripts(scratch): for name, _, _ in self.iter_blocks(script.blocks): file_blocks[name] += 1 self.blocks.update(f...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "file_blocks", "=", "Counter", "(", ")", "for", "script", "in", "self", ".", "iter_scripts", "(", "scratch", ")", ":", "for", "name", ",", "_", ",", "_", "in", "self"...
Run and return the results from the BlockCounts plugin.
[ "Run", "and", "return", "the", "results", "from", "the", "BlockCounts", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L23-L30
ucsb-cs-education/hairball
hairball/plugins/blocks.py
DeadCode.analyze
def analyze(self, scratch, **kwargs): """Run and return the results form the DeadCode plugin. The variable_event indicates that the Scratch file contains at least one instance of a broadcast event based on a variable. When variable_event is True, dead code scripts reported by this plugi...
python
def analyze(self, scratch, **kwargs): """Run and return the results form the DeadCode plugin. The variable_event indicates that the Scratch file contains at least one instance of a broadcast event based on a variable. When variable_event is True, dead code scripts reported by this plugi...
[ "def", "analyze", "(", "self", ",", "scratch", ",", "*", "*", "kwargs", ")", ":", "self", ".", "total_instances", "+=", "1", "sprites", "=", "{", "}", "for", "sprite", ",", "script", "in", "self", ".", "iter_sprite_scripts", "(", "scratch", ")", ":", ...
Run and return the results form the DeadCode plugin. The variable_event indicates that the Scratch file contains at least one instance of a broadcast event based on a variable. When variable_event is True, dead code scripts reported by this plugin that begin with a "when I receive" bloc...
[ "Run", "and", "return", "the", "results", "form", "the", "DeadCode", "plugin", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L43-L65
ucsb-cs-education/hairball
hairball/plugins/blocks.py
DeadCode.finalize
def finalize(self): """Output the number of instances that contained dead code.""" if self.total_instances > 1: print('{} of {} instances contained dead code.' .format(self.dead_code_instances, self.total_instances))
python
def finalize(self): """Output the number of instances that contained dead code.""" if self.total_instances > 1: print('{} of {} instances contained dead code.' .format(self.dead_code_instances, self.total_instances))
[ "def", "finalize", "(", "self", ")", ":", "if", "self", ".", "total_instances", ">", "1", ":", "print", "(", "'{} of {} instances contained dead code.'", ".", "format", "(", "self", ".", "dead_code_instances", ",", "self", ".", "total_instances", ")", ")" ]
Output the number of instances that contained dead code.
[ "Output", "the", "number", "of", "instances", "that", "contained", "dead", "code", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/blocks.py#L67-L71
timgabets/bpc8583
examples/isoClient.py
show_help
def show_help(name): """ Show help and basic usage """ print('Usage: python3 {} [OPTIONS]... '.format(name)) print('ISO8583 message client') print(' -v, --verbose\t\tRun transactions verbosely') print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default') print(' -s, --serve...
python
def show_help(name): """ Show help and basic usage """ print('Usage: python3 {} [OPTIONS]... '.format(name)) print('ISO8583 message client') print(' -v, --verbose\t\tRun transactions verbosely') print(' -p, --port=[PORT]\t\tTCP port to connect to, 1337 by default') print(' -s, --serve...
[ "def", "show_help", "(", "name", ")", ":", "print", "(", "'Usage: python3 {} [OPTIONS]... '", ".", "format", "(", "name", ")", ")", "print", "(", "'ISO8583 message client'", ")", "print", "(", "' -v, --verbose\\t\\tRun transactions verbosely'", ")", "print", "(", "...
Show help and basic usage
[ "Show", "help", "and", "basic", "usage" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/examples/isoClient.py#L301-L314
timgabets/bpc8583
examples/isoClient.py
isoClient._run_interactive
def _run_interactive(self): """ Run transactions interactively (by asking user which transaction to run) """ self.term.connect() self._show_available_transactions() while True: trxn_type = self._user_input('\nEnter transaction to send: ') ...
python
def _run_interactive(self): """ Run transactions interactively (by asking user which transaction to run) """ self.term.connect() self._show_available_transactions() while True: trxn_type = self._user_input('\nEnter transaction to send: ') ...
[ "def", "_run_interactive", "(", "self", ")", ":", "self", ".", "term", ".", "connect", "(", ")", "self", ".", "_show_available_transactions", "(", ")", "while", "True", ":", "trxn_type", "=", "self", ".", "_user_input", "(", "'\\nEnter transaction to send: '", ...
Run transactions interactively (by asking user which transaction to run)
[ "Run", "transactions", "interactively", "(", "by", "asking", "user", "which", "transaction", "to", "run", ")" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/examples/isoClient.py#L92-L138
scalative/haas
haas/plugins/discoverer.py
find_top_level_directory
def find_top_level_directory(start_directory): """Finds the top-level directory of a project given a start directory inside the project. Parameters ---------- start_directory : str The directory in which test discovery will start. """ top_level = start_directory while os.path.i...
python
def find_top_level_directory(start_directory): """Finds the top-level directory of a project given a start directory inside the project. Parameters ---------- start_directory : str The directory in which test discovery will start. """ top_level = start_directory while os.path.i...
[ "def", "find_top_level_directory", "(", "start_directory", ")", ":", "top_level", "=", "start_directory", "while", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "top_level", ",", "'__init__.py'", ")", ")", ":", "top_level", "=",...
Finds the top-level directory of a project given a start directory inside the project. Parameters ---------- start_directory : str The directory in which test discovery will start.
[ "Finds", "the", "top", "-", "level", "directory", "of", "a", "project", "given", "a", "start", "directory", "inside", "the", "project", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L92-L107
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover
def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. ...
python
def discover(self, start, top_level_directory=None, pattern='test*.py'): """Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. ...
[ "def", "discover", "(", "self", ",", "start", ",", "top_level_directory", "=", "None", ",", "pattern", "=", "'test*.py'", ")", ":", "logger", ".", "debug", "(", "'Starting test discovery'", ")", "if", "os", ".", "path", ".", "isdir", "(", "start", ")", "...
Do test case discovery. This is the top-level entry-point for test discovery. If the ``start`` argument is a drectory, then ``haas`` will discover all tests in the package contained in that directory. If the ``start`` argument is not a directory, it is assumed to be a package ...
[ "Do", "test", "case", "discovery", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L178-L219
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_by_module
def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str ...
python
def discover_by_module(self, module_name, top_level_directory=None, pattern='test*.py'): """Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str ...
[ "def", "discover_by_module", "(", "self", ",", "module_name", ",", "top_level_directory", "=", "None", ",", "pattern", "=", "'test*.py'", ")", ":", "# If the top level directory is given, the module may only be", "# importable with that in the path.", "if", "top_level_directory...
Find all tests in a package or module, or load a single test case if a class or test inside a module was specified. Parameters ---------- module_name : str The dotted package name, module name or TestCase class and test method. top_level_directory : str ...
[ "Find", "all", "tests", "in", "a", "package", "or", "module", "or", "load", "a", "single", "test", "case", "if", "a", "class", "or", "test", "inside", "a", "module", "was", "specified", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L221-L266
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_single_case
def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list ...
python
def discover_single_case(self, module, case_attributes): """Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list ...
[ "def", "discover_single_case", "(", "self", ",", "module", ",", "case_attributes", ")", ":", "# Find single case", "case", "=", "module", "loader", "=", "self", ".", "_loader", "for", "index", ",", "component", "in", "enumerate", "(", "case_attributes", ")", "...
Find and load a single TestCase or TestCase method from a module. Parameters ---------- module : module The imported Python module containing the TestCase to be loaded. case_attributes : list A list (length 1 or 2) of str. The first component must be...
[ "Find", "and", "load", "a", "single", "TestCase", "or", "TestCase", "method", "from", "a", "module", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L268-L299
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_by_directory
def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top...
python
def discover_by_directory(self, start_directory, top_level_directory=None, pattern='test*.py'): """Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top...
[ "def", "discover_by_directory", "(", "self", ",", "start_directory", ",", "top_level_directory", "=", "None", ",", "pattern", "=", "'test*.py'", ")", ":", "start_directory", "=", "os", ".", "path", ".", "abspath", "(", "start_directory", ")", "if", "top_level_di...
Run test discovery in a directory. Parameters ---------- start_directory : str The package directory in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the pr...
[ "Run", "test", "discovery", "in", "a", "directory", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L301-L332
scalative/haas
haas/plugins/discoverer.py
Discoverer.discover_by_file
def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level ...
python
def discover_by_file(self, start_filepath, top_level_directory=None): """Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level ...
[ "def", "discover_by_file", "(", "self", ",", "start_filepath", ",", "top_level_directory", "=", "None", ")", ":", "start_filepath", "=", "os", ".", "path", ".", "abspath", "(", "start_filepath", ")", "start_directory", "=", "os", ".", "path", ".", "dirname", ...
Run test discovery on a single file. Parameters ---------- start_filepath : str The module file in which to start test discovery. top_level_directory : str The path to the top-level directoy of the project. This is the parent directory of the project...
[ "Run", "test", "discovery", "on", "a", "single", "file", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/plugins/discoverer.py#L334-L362
ramses-tech/nefertari
nefertari/view_helpers.py
OptionsViewMixin._set_options_headers
def _set_options_headers(self, methods): """ Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for request...
python
def _set_options_headers(self, methods): """ Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for request...
[ "def", "_set_options_headers", "(", "self", ",", "methods", ")", ":", "request", "=", "self", ".", "request", "response", "=", "request", ".", "response", "response", ".", "headers", "[", "'Allow'", "]", "=", "', '", ".", "join", "(", "sorted", "(", "met...
Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for requested URI
[ "Set", "proper", "headers", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L33-L58
ramses-tech/nefertari
nefertari/view_helpers.py
OptionsViewMixin._get_handled_methods
def _get_handled_methods(self, actions_map): """ Get names of HTTP methods that can be used at requested URI. Arguments: :actions_map: Map of actions. Must have the same structure as self._item_actions and self._collection_actions """ methods = ('OPTIONS',) ...
python
def _get_handled_methods(self, actions_map): """ Get names of HTTP methods that can be used at requested URI. Arguments: :actions_map: Map of actions. Must have the same structure as self._item_actions and self._collection_actions """ methods = ('OPTIONS',) ...
[ "def", "_get_handled_methods", "(", "self", ",", "actions_map", ")", ":", "methods", "=", "(", "'OPTIONS'", ",", ")", "defined_actions", "=", "[", "]", "for", "action_name", "in", "actions_map", ".", "keys", "(", ")", ":", "view_method", "=", "getattr", "(...
Get names of HTTP methods that can be used at requested URI. Arguments: :actions_map: Map of actions. Must have the same structure as self._item_actions and self._collection_actions
[ "Get", "names", "of", "HTTP", "methods", "that", "can", "be", "used", "at", "requested", "URI", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L60-L80
ramses-tech/nefertari
nefertari/view_helpers.py
OptionsViewMixin.item_options
def item_options(self, **kwargs): """ Handle collection OPTIONS request. Singular route requests are handled a bit differently because singular views may handle POST requests despite being registered as item routes. """ actions = self._item_actions.copy() if self...
python
def item_options(self, **kwargs): """ Handle collection OPTIONS request. Singular route requests are handled a bit differently because singular views may handle POST requests despite being registered as item routes. """ actions = self._item_actions.copy() if self...
[ "def", "item_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "actions", "=", "self", ".", "_item_actions", ".", "copy", "(", ")", "if", "self", ".", "_resource", ".", "is_singular", ":", "actions", "[", "'create'", "]", "=", "(", "'POST'", ...
Handle collection OPTIONS request. Singular route requests are handled a bit differently because singular views may handle POST requests despite being registered as item routes.
[ "Handle", "collection", "OPTIONS", "request", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L82-L93
ramses-tech/nefertari
nefertari/view_helpers.py
OptionsViewMixin.collection_options
def collection_options(self, **kwargs): """ Handle collection item OPTIONS request. """ methods = self._get_handled_methods(self._collection_actions) return self._set_options_headers(methods)
python
def collection_options(self, **kwargs): """ Handle collection item OPTIONS request. """ methods = self._get_handled_methods(self._collection_actions) return self._set_options_headers(methods)
[ "def", "collection_options", "(", "self", ",", "*", "*", "kwargs", ")", ":", "methods", "=", "self", ".", "_get_handled_methods", "(", "self", ".", "_collection_actions", ")", "return", "self", ".", "_set_options_headers", "(", "methods", ")" ]
Handle collection item OPTIONS request.
[ "Handle", "collection", "item", "OPTIONS", "request", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L95-L98
ramses-tech/nefertari
nefertari/view_helpers.py
ESAggregator.wrap
def wrap(self, func): """ Wrap :func: to perform aggregation on :func: call. Should be called with view instance methods. """ @six.wraps(func) def wrapper(*args, **kwargs): try: return self.aggregate() except KeyError: retu...
python
def wrap(self, func): """ Wrap :func: to perform aggregation on :func: call. Should be called with view instance methods. """ @six.wraps(func) def wrapper(*args, **kwargs): try: return self.aggregate() except KeyError: retu...
[ "def", "wrap", "(", "self", ",", "func", ")", ":", "@", "six", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "aggregate", "(", ")", "except", "KeyError", ...
Wrap :func: to perform aggregation on :func: call. Should be called with view instance methods.
[ "Wrap", ":", "func", ":", "to", "perform", "aggregation", "on", ":", "func", ":", "call", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L129-L140
ramses-tech/nefertari
nefertari/view_helpers.py
ESAggregator.pop_aggregations_params
def pop_aggregations_params(self): """ Pop and return aggregation params from query string params. Aggregation params are expected to be prefixed(nested under) by any of `self._aggregations_keys`. """ from nefertari.view import BaseView self._query_params = BaseView.conv...
python
def pop_aggregations_params(self): """ Pop and return aggregation params from query string params. Aggregation params are expected to be prefixed(nested under) by any of `self._aggregations_keys`. """ from nefertari.view import BaseView self._query_params = BaseView.conv...
[ "def", "pop_aggregations_params", "(", "self", ")", ":", "from", "nefertari", ".", "view", "import", "BaseView", "self", ".", "_query_params", "=", "BaseView", ".", "convert_dotted", "(", "self", ".", "view", ".", "_query_params", ")", "for", "key", "in", "s...
Pop and return aggregation params from query string params. Aggregation params are expected to be prefixed(nested under) by any of `self._aggregations_keys`.
[ "Pop", "and", "return", "aggregation", "params", "from", "query", "string", "params", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L142-L155
ramses-tech/nefertari
nefertari/view_helpers.py
ESAggregator.get_aggregations_fields
def get_aggregations_fields(cls, params): """ Recursively get values under the 'field' key. Is used to get names of fields on which aggregations should be performed. """ fields = [] for key, val in params.items(): if isinstance(val, dict): fie...
python
def get_aggregations_fields(cls, params): """ Recursively get values under the 'field' key. Is used to get names of fields on which aggregations should be performed. """ fields = [] for key, val in params.items(): if isinstance(val, dict): fie...
[ "def", "get_aggregations_fields", "(", "cls", ",", "params", ")", ":", "fields", "=", "[", "]", "for", "key", ",", "val", "in", "params", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "fields", "+=", "cls", "."...
Recursively get values under the 'field' key. Is used to get names of fields on which aggregations should be performed.
[ "Recursively", "get", "values", "under", "the", "field", "key", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L164-L176
ramses-tech/nefertari
nefertari/view_helpers.py
ESAggregator.check_aggregations_privacy
def check_aggregations_privacy(self, aggregations_params): """ Check per-field privacy rules in aggregations. Privacy is checked by making sure user has access to the fields used in aggregations. """ fields = self.get_aggregations_fields(aggregations_params) fields_dict ...
python
def check_aggregations_privacy(self, aggregations_params): """ Check per-field privacy rules in aggregations. Privacy is checked by making sure user has access to the fields used in aggregations. """ fields = self.get_aggregations_fields(aggregations_params) fields_dict ...
[ "def", "check_aggregations_privacy", "(", "self", ",", "aggregations_params", ")", ":", "fields", "=", "self", ".", "get_aggregations_fields", "(", "aggregations_params", ")", "fields_dict", "=", "dictset", ".", "fromkeys", "(", "fields", ")", "fields_dict", "[", ...
Check per-field privacy rules in aggregations. Privacy is checked by making sure user has access to the fields used in aggregations.
[ "Check", "per", "-", "field", "privacy", "rules", "in", "aggregations", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L178-L193
ramses-tech/nefertari
nefertari/view_helpers.py
ESAggregator.aggregate
def aggregate(self): """ Perform aggregation and return response. """ from nefertari.elasticsearch import ES aggregations_params = self.pop_aggregations_params() if self.view._auth_enabled: self.check_aggregations_privacy(aggregations_params) self.stub_wrappers() ...
python
def aggregate(self): """ Perform aggregation and return response. """ from nefertari.elasticsearch import ES aggregations_params = self.pop_aggregations_params() if self.view._auth_enabled: self.check_aggregations_privacy(aggregations_params) self.stub_wrappers() ...
[ "def", "aggregate", "(", "self", ")", ":", "from", "nefertari", ".", "elasticsearch", "import", "ES", "aggregations_params", "=", "self", ".", "pop_aggregations_params", "(", ")", "if", "self", ".", "view", ".", "_auth_enabled", ":", "self", ".", "check_aggreg...
Perform aggregation and return response.
[ "Perform", "aggregation", "and", "return", "response", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/view_helpers.py#L195-L205
ramses-tech/nefertari
nefertari/utils/dictset.py
dictset.asdict
def asdict(self, name, _type=None, _set=False): """ Turn this 'a:2,b:blabla,c:True,a:'d' to {a:[2, 'd'], b:'blabla', c:True} """ if _type is None: _type = lambda t: t dict_str = self.pop(name, None) if not dict_str: return {} _d...
python
def asdict(self, name, _type=None, _set=False): """ Turn this 'a:2,b:blabla,c:True,a:'d' to {a:[2, 'd'], b:'blabla', c:True} """ if _type is None: _type = lambda t: t dict_str = self.pop(name, None) if not dict_str: return {} _d...
[ "def", "asdict", "(", "self", ",", "name", ",", "_type", "=", "None", ",", "_set", "=", "False", ")", ":", "if", "_type", "is", "None", ":", "_type", "=", "lambda", "t", ":", "t", "dict_str", "=", "self", ".", "pop", "(", "name", ",", "None", "...
Turn this 'a:2,b:blabla,c:True,a:'d' to {a:[2, 'd'], b:'blabla', c:True}
[ "Turn", "this", "a", ":", "2", "b", ":", "blabla", "c", ":", "True", "a", ":", "d", "to", "{", "a", ":", "[", "2", "d", "]", "b", ":", "blabla", "c", ":", "True", "}" ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/utils/dictset.py#L66-L95
timgabets/bpc8583
bpc8583/tools.py
get_random_hex
def get_random_hex(length): """ Return random hex string of a given length """ if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
python
def get_random_hex(length): """ Return random hex string of a given length """ if length <= 0: return '' return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
[ "def", "get_random_hex", "(", "length", ")", ":", "if", "length", "<=", "0", ":", "return", "''", "return", "hexify", "(", "random", ".", "randint", "(", "pow", "(", "2", ",", "length", "*", "2", ")", ",", "pow", "(", "2", ",", "length", "*", "4"...
Return random hex string of a given length
[ "Return", "random", "hex", "string", "of", "a", "given", "length" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/tools.py#L59-L65
timgabets/bpc8583
bpc8583/tools.py
get_response
def get_response(_code): """ Return xx1x response for xx0x codes (e.g. 0810 for 0800) """ if _code: code = str(_code) return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1] else: return None
python
def get_response(_code): """ Return xx1x response for xx0x codes (e.g. 0810 for 0800) """ if _code: code = str(_code) return code[:-2] + str(int(code[-2:-1]) + 1) + code[-1] else: return None
[ "def", "get_response", "(", "_code", ")", ":", "if", "_code", ":", "code", "=", "str", "(", "_code", ")", "return", "code", "[", ":", "-", "2", "]", "+", "str", "(", "int", "(", "code", "[", "-", "2", ":", "-", "1", "]", ")", "+", "1", ")",...
Return xx1x response for xx0x codes (e.g. 0810 for 0800)
[ "Return", "xx1x", "response", "for", "xx0x", "codes", "(", "e", ".", "g", ".", "0810", "for", "0800", ")" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/tools.py#L68-L76
scalative/haas
haas/loader.py
Loader.load_case
def load_case(self, testcase): """Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters ---------- testcase : type A subclass of :class:`unittest.TestCase` """ tests = [self.load_test(testcase, name) ...
python
def load_case(self, testcase): """Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters ---------- testcase : type A subclass of :class:`unittest.TestCase` """ tests = [self.load_test(testcase, name) ...
[ "def", "load_case", "(", "self", ",", "testcase", ")", ":", "tests", "=", "[", "self", ".", "load_test", "(", "testcase", ",", "name", ")", "for", "name", "in", "self", ".", "find_test_method_names", "(", "testcase", ")", "]", "return", "self", ".", "c...
Load a TestSuite containing all TestCase instances for all tests in a TestCase subclass. Parameters ---------- testcase : type A subclass of :class:`unittest.TestCase`
[ "Load", "a", "TestSuite", "containing", "all", "TestCase", "instances", "for", "all", "tests", "in", "a", "TestCase", "subclass", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/loader.py#L83-L95
scalative/haas
haas/loader.py
Loader.load_module
def load_module(self, module): """Create and return a test suite containing all cases loaded from the provided module. Parameters ---------- module : module A module object containing ``TestCases`` """ cases = self.get_test_cases_from_module(module) ...
python
def load_module(self, module): """Create and return a test suite containing all cases loaded from the provided module. Parameters ---------- module : module A module object containing ``TestCases`` """ cases = self.get_test_cases_from_module(module) ...
[ "def", "load_module", "(", "self", ",", "module", ")", ":", "cases", "=", "self", ".", "get_test_cases_from_module", "(", "module", ")", "suites", "=", "[", "self", ".", "load_case", "(", "case", ")", "for", "case", "in", "cases", "]", "return", "self", ...
Create and return a test suite containing all cases loaded from the provided module. Parameters ---------- module : module A module object containing ``TestCases``
[ "Create", "and", "return", "a", "test", "suite", "containing", "all", "cases", "loaded", "from", "the", "provided", "module", "." ]
train
https://github.com/scalative/haas/blob/72c05216a2a80e5ee94d9cd8d05ed2b188725027/haas/loader.py#L112-L124
timgabets/bpc8583
bpc8583/ISO8583.py
ISO8583.Field
def Field(self, field, Value = None): ''' Add field to bitmap ''' if Value == None: try: return self.__Bitmap[field] except KeyError: return None elif Value == 1 or Value == 0: self.__Bitmap[field] = Value ...
python
def Field(self, field, Value = None): ''' Add field to bitmap ''' if Value == None: try: return self.__Bitmap[field] except KeyError: return None elif Value == 1 or Value == 0: self.__Bitmap[field] = Value ...
[ "def", "Field", "(", "self", ",", "field", ",", "Value", "=", "None", ")", ":", "if", "Value", "==", "None", ":", "try", ":", "return", "self", ".", "__Bitmap", "[", "field", "]", "except", "KeyError", ":", "return", "None", "elif", "Value", "==", ...
Add field to bitmap
[ "Add", "field", "to", "bitmap" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/ISO8583.py#L396-L408
timgabets/bpc8583
bpc8583/ISO8583.py
ISO8583.FieldData
def FieldData(self, field, Value = None): ''' Add field data ''' if Value == None: try: return self.__FieldData[field] except KeyError: return None else: if len(str(Value)) > self.__IsoSpec.MaxLength(field): ...
python
def FieldData(self, field, Value = None): ''' Add field data ''' if Value == None: try: return self.__FieldData[field] except KeyError: return None else: if len(str(Value)) > self.__IsoSpec.MaxLength(field): ...
[ "def", "FieldData", "(", "self", ",", "field", ",", "Value", "=", "None", ")", ":", "if", "Value", "==", "None", ":", "try", ":", "return", "self", ".", "__FieldData", "[", "field", "]", "except", "KeyError", ":", "return", "None", "else", ":", "if",...
Add field data
[ "Add", "field", "data" ]
train
https://github.com/timgabets/bpc8583/blob/1b8e95d73ad273ad9d11bff40d1af3f06f0f3503/bpc8583/ISO8583.py#L419-L433
ramses-tech/nefertari
nefertari/acl.py
authenticated_userid
def authenticated_userid(request): """Helper function that can be used in ``db_key`` to support `self` as a collection key. """ user = getattr(request, 'user', None) key = user.pk_field() return getattr(user, key)
python
def authenticated_userid(request): """Helper function that can be used in ``db_key`` to support `self` as a collection key. """ user = getattr(request, 'user', None) key = user.pk_field() return getattr(user, key)
[ "def", "authenticated_userid", "(", "request", ")", ":", "user", "=", "getattr", "(", "request", ",", "'user'", ",", "None", ")", "key", "=", "user", ".", "pk_field", "(", ")", "return", "getattr", "(", "user", ",", "key", ")" ]
Helper function that can be used in ``db_key`` to support `self` as a collection key.
[ "Helper", "function", "that", "can", "be", "used", "in", "db_key", "to", "support", "self", "as", "a", "collection", "key", "." ]
train
https://github.com/ramses-tech/nefertari/blob/c7caffe11576c11aa111adbdbadeff70ce66b1dd/nefertari/acl.py#L68-L74
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.iter_blocks
def iter_blocks(block_list): """A generator for blocks contained in a block list. Yields tuples containing the block name, the depth that the block was found at, and finally a handle to the block itself. """ # queue the block and the depth of the block queue = [(block, ...
python
def iter_blocks(block_list): """A generator for blocks contained in a block list. Yields tuples containing the block name, the depth that the block was found at, and finally a handle to the block itself. """ # queue the block and the depth of the block queue = [(block, ...
[ "def", "iter_blocks", "(", "block_list", ")", ":", "# queue the block and the depth of the block", "queue", "=", "[", "(", "block", ",", "0", ")", "for", "block", "in", "block_list", "if", "isinstance", "(", "block", ",", "kurt", ".", "Block", ")", "]", "whi...
A generator for blocks contained in a block list. Yields tuples containing the block name, the depth that the block was found at, and finally a handle to the block itself.
[ "A", "generator", "for", "blocks", "contained", "in", "a", "block", "list", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L48-L67
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.iter_scripts
def iter_scripts(scratch): """A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite """ for script in scratch.stage.scripts: if not isinstance(script, kurt.Comment): yield script for sprite ...
python
def iter_scripts(scratch): """A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite """ for script in scratch.stage.scripts: if not isinstance(script, kurt.Comment): yield script for sprite ...
[ "def", "iter_scripts", "(", "scratch", ")", ":", "for", "script", "in", "scratch", ".", "stage", ".", "scripts", ":", "if", "not", "isinstance", "(", "script", ",", "kurt", ".", "Comment", ")", ":", "yield", "script", "for", "sprite", "in", "scratch", ...
A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite
[ "A", "generator", "for", "all", "scripts", "contained", "in", "a", "scratch", "file", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L70-L82
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.iter_sprite_scripts
def iter_sprite_scripts(scratch): """A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite """ for script in scratch.stage.scripts: if not isinstance(script, kurt.Comment): yield ('Stage', script) ...
python
def iter_sprite_scripts(scratch): """A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite """ for script in scratch.stage.scripts: if not isinstance(script, kurt.Comment): yield ('Stage', script) ...
[ "def", "iter_sprite_scripts", "(", "scratch", ")", ":", "for", "script", "in", "scratch", ".", "stage", ".", "scripts", ":", "if", "not", "isinstance", "(", "script", ",", "kurt", ".", "Comment", ")", ":", "yield", "(", "'Stage'", ",", "script", ")", "...
A generator for all scripts contained in a scratch file. yields stage scripts first, then scripts for each sprite
[ "A", "generator", "for", "all", "scripts", "contained", "in", "a", "scratch", "file", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L91-L103
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.script_start_type
def script_start_type(script): """Return the type of block the script begins with.""" if script[0].type.text == 'when @greenFlag clicked': return HairballPlugin.HAT_GREEN_FLAG elif script[0].type.text == 'when I receive %s': return HairballPlugin.HAT_WHEN_I_RECEIVE ...
python
def script_start_type(script): """Return the type of block the script begins with.""" if script[0].type.text == 'when @greenFlag clicked': return HairballPlugin.HAT_GREEN_FLAG elif script[0].type.text == 'when I receive %s': return HairballPlugin.HAT_WHEN_I_RECEIVE ...
[ "def", "script_start_type", "(", "script", ")", ":", "if", "script", "[", "0", "]", ".", "type", ".", "text", "==", "'when @greenFlag clicked'", ":", "return", "HairballPlugin", ".", "HAT_GREEN_FLAG", "elif", "script", "[", "0", "]", ".", "type", ".", "tex...
Return the type of block the script begins with.
[ "Return", "the", "type", "of", "block", "the", "script", "begins", "with", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L106-L117
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.get_broadcast_events
def get_broadcast_events(cls, script): """Return a Counter of event-names that were broadcast. The Count will contain the key True if any of the broadcast blocks contain a parameter that is a variable. """ events = Counter() for name, _, block in cls.iter_blocks(script)...
python
def get_broadcast_events(cls, script): """Return a Counter of event-names that were broadcast. The Count will contain the key True if any of the broadcast blocks contain a parameter that is a variable. """ events = Counter() for name, _, block in cls.iter_blocks(script)...
[ "def", "get_broadcast_events", "(", "cls", ",", "script", ")", ":", "events", "=", "Counter", "(", ")", "for", "name", ",", "_", ",", "block", "in", "cls", ".", "iter_blocks", "(", "script", ")", ":", "if", "'broadcast %s'", "in", "name", ":", "if", ...
Return a Counter of event-names that were broadcast. The Count will contain the key True if any of the broadcast blocks contain a parameter that is a variable.
[ "Return", "a", "Counter", "of", "event", "-", "names", "that", "were", "broadcast", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L120-L134
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.tag_reachable_scripts
def tag_reachable_scripts(cls, scratch): """Tag each script with attribute reachable. The reachable attribute will be set false for any script that does not begin with a hat block. Additionally, any script that begins with a 'when I receive' block whose event-name doesn't appear in a ...
python
def tag_reachable_scripts(cls, scratch): """Tag each script with attribute reachable. The reachable attribute will be set false for any script that does not begin with a hat block. Additionally, any script that begins with a 'when I receive' block whose event-name doesn't appear in a ...
[ "def", "tag_reachable_scripts", "(", "cls", ",", "scratch", ")", ":", "if", "getattr", "(", "scratch", ",", "'hairball_prepared'", ",", "False", ")", ":", "# Only process once", "return", "reachable", "=", "set", "(", ")", "untriggered_events", "=", "{", "}", ...
Tag each script with attribute reachable. The reachable attribute will be set false for any script that does not begin with a hat block. Additionally, any script that begins with a 'when I receive' block whose event-name doesn't appear in a corresponding broadcast block is marked as unr...
[ "Tag", "each", "script", "with", "attribute", "reachable", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L137-L172
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin.description
def description(self): """Attribute that returns the plugin description from its docstring.""" lines = [] for line in self.__doc__.split('\n')[2:]: line = line.strip() if line: lines.append(line) return ' '.join(lines)
python
def description(self): """Attribute that returns the plugin description from its docstring.""" lines = [] for line in self.__doc__.split('\n')[2:]: line = line.strip() if line: lines.append(line) return ' '.join(lines)
[ "def", "description", "(", "self", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "self", ".", "__doc__", ".", "split", "(", "'\\n'", ")", "[", "2", ":", "]", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ":", "lines",...
Attribute that returns the plugin description from its docstring.
[ "Attribute", "that", "returns", "the", "plugin", "description", "from", "its", "docstring", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L175-L182
ucsb-cs-education/hairball
hairball/plugins/__init__.py
HairballPlugin._process
def _process(self, scratch, filename, **kwargs): """Internal hook that marks reachable scripts before calling analyze. Returns data exactly as returned by the analyze method. """ self.tag_reachable_scripts(scratch) return self.analyze(scratch, filename=filename, **kwargs)
python
def _process(self, scratch, filename, **kwargs): """Internal hook that marks reachable scripts before calling analyze. Returns data exactly as returned by the analyze method. """ self.tag_reachable_scripts(scratch) return self.analyze(scratch, filename=filename, **kwargs)
[ "def", "_process", "(", "self", ",", "scratch", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "self", ".", "tag_reachable_scripts", "(", "scratch", ")", "return", "self", ".", "analyze", "(", "scratch", ",", "filename", "=", "filename", ",", "*", ...
Internal hook that marks reachable scripts before calling analyze. Returns data exactly as returned by the analyze method.
[ "Internal", "hook", "that", "marks", "reachable", "scripts", "before", "calling", "analyze", "." ]
train
https://github.com/ucsb-cs-education/hairball/blob/c6da8971f8a34e88ce401d36b51431715e1dff5b/hairball/plugins/__init__.py#L189-L196
mmulqueen/odswriter
odswriter/__init__.py
ODSWriter.close
def close(self): """ Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement, you must call this manually, it is not triggered automatically like on a file object. :return: Nothing. """ self.zipf.writestr("content.xml...
python
def close(self): """ Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement, you must call this manually, it is not triggered automatically like on a file object. :return: Nothing. """ self.zipf.writestr("content.xml...
[ "def", "close", "(", "self", ")", ":", "self", ".", "zipf", ".", "writestr", "(", "\"content.xml\"", ",", "self", ".", "dom", ".", "toxml", "(", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", "self", ".", "zipf", ".", "close", "(", ")" ]
Finalises the compressed version of the spreadsheet. If you aren't using the context manager ('with' statement, you must call this manually, it is not triggered automatically like on a file object. :return: Nothing.
[ "Finalises", "the", "compressed", "version", "of", "the", "spreadsheet", ".", "If", "you", "aren", "t", "using", "the", "context", "manager", "(", "with", "statement", "you", "must", "call", "this", "manually", "it", "is", "not", "triggered", "automatically", ...
train
https://github.com/mmulqueen/odswriter/blob/0bb038a60dd27bacd76d6b1ff3a200e2a7729651/odswriter/__init__.py#L49-L56
mmulqueen/odswriter
odswriter/__init__.py
ODSWriter.writerow
def writerow(self, cells): """ Write a row of cells into the default sheet of the spreadsheet. :param cells: A list of cells (most basic Python types supported). :return: Nothing. """ if self.default_sheet is None: self.default_sheet = self.new_sheet() ...
python
def writerow(self, cells): """ Write a row of cells into the default sheet of the spreadsheet. :param cells: A list of cells (most basic Python types supported). :return: Nothing. """ if self.default_sheet is None: self.default_sheet = self.new_sheet() ...
[ "def", "writerow", "(", "self", ",", "cells", ")", ":", "if", "self", ".", "default_sheet", "is", "None", ":", "self", ".", "default_sheet", "=", "self", ".", "new_sheet", "(", ")", "self", ".", "default_sheet", ".", "writerow", "(", "cells", ")" ]
Write a row of cells into the default sheet of the spreadsheet. :param cells: A list of cells (most basic Python types supported). :return: Nothing.
[ "Write", "a", "row", "of", "cells", "into", "the", "default", "sheet", "of", "the", "spreadsheet", ".", ":", "param", "cells", ":", "A", "list", "of", "cells", "(", "most", "basic", "Python", "types", "supported", ")", ".", ":", "return", ":", "Nothing...
train
https://github.com/mmulqueen/odswriter/blob/0bb038a60dd27bacd76d6b1ff3a200e2a7729651/odswriter/__init__.py#L58-L66
mmulqueen/odswriter
odswriter/__init__.py
ODSWriter.new_sheet
def new_sheet(self, name=None, cols=None): """ Create a new sheet in the spreadsheet and return it so content can be added. :param name: Optional name for the sheet. :param cols: Specify the number of columns, needed for compatibility in some cases :return: Sheet object "...
python
def new_sheet(self, name=None, cols=None): """ Create a new sheet in the spreadsheet and return it so content can be added. :param name: Optional name for the sheet. :param cols: Specify the number of columns, needed for compatibility in some cases :return: Sheet object "...
[ "def", "new_sheet", "(", "self", ",", "name", "=", "None", ",", "cols", "=", "None", ")", ":", "sheet", "=", "Sheet", "(", "self", ".", "dom", ",", "name", ",", "cols", ")", "self", ".", "sheets", ".", "append", "(", "sheet", ")", "return", "shee...
Create a new sheet in the spreadsheet and return it so content can be added. :param name: Optional name for the sheet. :param cols: Specify the number of columns, needed for compatibility in some cases :return: Sheet object
[ "Create", "a", "new", "sheet", "in", "the", "spreadsheet", "and", "return", "it", "so", "content", "can", "be", "added", ".", ":", "param", "name", ":", "Optional", "name", "for", "the", "sheet", ".", ":", "param", "cols", ":", "Specify", "the", "numbe...
train
https://github.com/mmulqueen/odswriter/blob/0bb038a60dd27bacd76d6b1ff3a200e2a7729651/odswriter/__init__.py#L77-L86
jeffrimko/Qprompt
lib/qprompt.py
_format_kwargs
def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} form...
python
def _format_kwargs(func): """Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.""" formats = {} form...
[ "def", "_format_kwargs", "(", "func", ")", ":", "formats", "=", "{", "}", "formats", "[", "'blk'", "]", "=", "[", "\"blank\"", "]", "formats", "[", "'dft'", "]", "=", "[", "\"default\"", "]", "formats", "[", "'hdr'", "]", "=", "[", "\"header\"", "]",...
Decorator to handle formatting kwargs to the proper names expected by the associated function. The formats dictionary string keys will be used as expected function kwargs and the value list of strings will be renamed to the associated key string.
[ "Decorator", "to", "handle", "formatting", "kwargs", "to", "the", "proper", "names", "expected", "by", "the", "associated", "function", ".", "The", "formats", "dictionary", "string", "keys", "will", "be", "used", "as", "expected", "function", "kwargs", "and", ...
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L34-L55
jeffrimko/Qprompt
lib/qprompt.py
show_limit
def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start...
python
def show_limit(entries, **kwargs): """Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.""" limit = kwargs.pop('limit', 5) if limit <= 0: return show_menu(entries, **kwargs) istart = 0 # Index of group start...
[ "def", "show_limit", "(", "entries", ",", "*", "*", "kwargs", ")", ":", "limit", "=", "kwargs", ".", "pop", "(", "'limit'", ",", "5", ")", "if", "limit", "<=", "0", ":", "return", "show_menu", "(", "entries", ",", "*", "*", "kwargs", ")", "istart",...
Shows a menu but limits the number of entries shown at a time. Functionally equivalent to `show_menu()` with the `limit` parameter set.
[ "Shows", "a", "menu", "but", "limits", "the", "number", "of", "entries", "shown", "at", "a", "time", ".", "Functionally", "equivalent", "to", "show_menu", "()", "with", "the", "limit", "parameter", "set", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L258-L315
jeffrimko/Qprompt
lib/qprompt.py
show_menu
def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left b...
python
def show_menu(entries, **kwargs): """Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left b...
[ "def", "show_menu", "(", "entries", ",", "*", "*", "kwargs", ")", ":", "global", "_AUTO", "hdr", "=", "kwargs", ".", "get", "(", "'hdr'", ",", "\"\"", ")", "note", "=", "kwargs", ".", "get", "(", "'note'", ",", "\"\"", ")", "dft", "=", "kwargs", ...
Shows a menu with the given list of `MenuEntry` items. **Params**: - header (str) - String to show above menu. - note (str) - String to show as a note below menu. - msg (str) - String to show below menu. - dft (str) - Default value if input is left blank. - compact (bool) - If true, t...
[ "Shows", "a", "menu", "with", "the", "given", "list", "of", "MenuEntry", "items", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L318-L388
jeffrimko/Qprompt
lib/qprompt.py
run_func
def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(*...
python
def run_func(entry): """Runs the function associated with the given MenuEntry.""" if entry.func: if entry.args and entry.krgs: return entry.func(*entry.args, **entry.krgs) if entry.args: return entry.func(*entry.args) if entry.krgs: return entry.func(*...
[ "def", "run_func", "(", "entry", ")", ":", "if", "entry", ".", "func", ":", "if", "entry", ".", "args", "and", "entry", ".", "krgs", ":", "return", "entry", ".", "func", "(", "*", "entry", ".", "args", ",", "*", "*", "entry", ".", "krgs", ")", ...
Runs the function associated with the given MenuEntry.
[ "Runs", "the", "function", "associated", "with", "the", "given", "MenuEntry", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L390-L399
jeffrimko/Qprompt
lib/qprompt.py
enum_menu
def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: m...
python
def enum_menu(strs, menu=None, *args, **kwargs): """Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created. """ if not menu: menu = Menu(*args, **kwargs) for s in strs: m...
[ "def", "enum_menu", "(", "strs", ",", "menu", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "menu", ":", "menu", "=", "Menu", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "s", "in", "strs", ":", "men...
Enumerates the given list of strings into returned menu. **Params**: - menu (Menu) - Existing menu to append. If not provided, a new menu will be created.
[ "Enumerates", "the", "given", "list", "of", "strings", "into", "returned", "menu", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L401-L412
jeffrimko/Qprompt
lib/qprompt.py
ask
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format...
python
def ask(msg="Enter input", fmt=None, dft=None, vld=None, shw=True, blk=False, hlp=None, qstr=True): """Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format...
[ "def", "ask", "(", "msg", "=", "\"Enter input\"", ",", "fmt", "=", "None", ",", "dft", "=", "None", ",", "vld", "=", "None", ",", "shw", "=", "True", ",", "blk", "=", "False", ",", "hlp", "=", "None", ",", "qstr", "=", "True", ")", ":", "global...
Prompts the user for input and returns the given answer. Optionally checks if answer is valid. **Params**: - msg (str) - Message to prompt the user with. - fmt (func) - Function used to format user input. - dft (int|float|str) - Default value if input is left blank. - vld ([int|float|st...
[ "Prompts", "the", "user", "for", "input", "and", "returns", "the", "given", "answer", ".", "Optionally", "checks", "if", "answer", "is", "valid", "." ]
train
https://github.com/jeffrimko/Qprompt/blob/1887c53656dfecac49e0650e0f912328801cbb83/lib/qprompt.py#L424-L516