repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
luqasz/librouteros
librouteros/connections.py
Decoder.decodeLength
def decodeLength(length): """ Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length. """ bytes_length = len(length) if bytes_length < 2: offset = b'\x00\x00\x00' XOR = 0 elif bytes_length < 3: offset = b'\x00\x00' XOR = 0x8000 elif bytes_length < 4: offset = b'\x00' XOR = 0xC00000 elif bytes_length < 5: offset = b'' XOR = 0xE0000000 else: raise ConnectionError('Unable to decode length of {}'.format(length)) decoded = unpack('!I', (offset + length))[0] decoded ^= XOR return decoded
python
def decodeLength(length): """ Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length. """ bytes_length = len(length) if bytes_length < 2: offset = b'\x00\x00\x00' XOR = 0 elif bytes_length < 3: offset = b'\x00\x00' XOR = 0x8000 elif bytes_length < 4: offset = b'\x00' XOR = 0xC00000 elif bytes_length < 5: offset = b'' XOR = 0xE0000000 else: raise ConnectionError('Unable to decode length of {}'.format(length)) decoded = unpack('!I', (offset + length))[0] decoded ^= XOR return decoded
[ "def", "decodeLength", "(", "length", ")", ":", "bytes_length", "=", "len", "(", "length", ")", "if", "bytes_length", "<", "2", ":", "offset", "=", "b'\\x00\\x00\\x00'", "XOR", "=", "0", "elif", "bytes_length", "<", "3", ":", "offset", "=", "b'\\x00\\x00'", "XOR", "=", "0x8000", "elif", "bytes_length", "<", "4", ":", "offset", "=", "b'\\x00'", "XOR", "=", "0xC00000", "elif", "bytes_length", "<", "5", ":", "offset", "=", "b''", "XOR", "=", "0xE0000000", "else", ":", "raise", "ConnectionError", "(", "'Unable to decode length of {}'", ".", "format", "(", "length", ")", ")", "decoded", "=", "unpack", "(", "'!I'", ",", "(", "offset", "+", "length", ")", ")", "[", "0", "]", "decoded", "^=", "XOR", "return", "decoded" ]
Decode length based on given bytes. :param length: Bytes string to decode. :return: Decoded length.
[ "Decode", "length", "based", "on", "given", "bytes", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L88-L114
train
luqasz/librouteros
librouteros/connections.py
ApiProtocol.writeSentence
def writeSentence(self, cmd, *words): """ Write encoded sentence. :param cmd: Command word. :param words: Aditional words. """ encoded = self.encodeSentence(cmd, *words) self.log('<---', cmd, *words) self.transport.write(encoded)
python
def writeSentence(self, cmd, *words): """ Write encoded sentence. :param cmd: Command word. :param words: Aditional words. """ encoded = self.encodeSentence(cmd, *words) self.log('<---', cmd, *words) self.transport.write(encoded)
[ "def", "writeSentence", "(", "self", ",", "cmd", ",", "*", "words", ")", ":", "encoded", "=", "self", ".", "encodeSentence", "(", "cmd", ",", "*", "words", ")", "self", ".", "log", "(", "'<---'", ",", "cmd", ",", "*", "words", ")", "self", ".", "transport", ".", "write", "(", "encoded", ")" ]
Write encoded sentence. :param cmd: Command word. :param words: Aditional words.
[ "Write", "encoded", "sentence", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L129-L138
train
luqasz/librouteros
librouteros/connections.py
SocketTransport.read
def read(self, length): """ Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised. """ data = bytearray() while len(data) != length: data += self.sock.recv((length - len(data))) if not data: raise ConnectionError('Connection unexpectedly closed.') return data
python
def read(self, length): """ Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised. """ data = bytearray() while len(data) != length: data += self.sock.recv((length - len(data))) if not data: raise ConnectionError('Connection unexpectedly closed.') return data
[ "def", "read", "(", "self", ",", "length", ")", ":", "data", "=", "bytearray", "(", ")", "while", "len", "(", "data", ")", "!=", "length", ":", "data", "+=", "self", ".", "sock", ".", "recv", "(", "(", "length", "-", "len", "(", "data", ")", ")", ")", "if", "not", "data", ":", "raise", "ConnectionError", "(", "'Connection unexpectedly closed.'", ")", "return", "data" ]
Read as many bytes from socket as specified in length. Loop as long as every byte is read unless exception is raised.
[ "Read", "as", "many", "bytes", "from", "socket", "as", "specified", "in", "length", ".", "Loop", "as", "long", "as", "every", "byte", "is", "read", "unless", "exception", "is", "raised", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L178-L188
train
luqasz/librouteros
librouteros/protocol.py
parseWord
def parseWord(word): """ Split given attribute word to key, value pair. Values are casted to python equivalents. :param word: API word. :returns: Key, value pair. """ mapping = {'yes': True, 'true': True, 'no': False, 'false': False} _, key, value = word.split('=', 2) try: value = int(value) except ValueError: value = mapping.get(value, value) return (key, value)
python
def parseWord(word): """ Split given attribute word to key, value pair. Values are casted to python equivalents. :param word: API word. :returns: Key, value pair. """ mapping = {'yes': True, 'true': True, 'no': False, 'false': False} _, key, value = word.split('=', 2) try: value = int(value) except ValueError: value = mapping.get(value, value) return (key, value)
[ "def", "parseWord", "(", "word", ")", ":", "mapping", "=", "{", "'yes'", ":", "True", ",", "'true'", ":", "True", ",", "'no'", ":", "False", ",", "'false'", ":", "False", "}", "_", ",", "key", ",", "value", "=", "word", ".", "split", "(", "'='", ",", "2", ")", "try", ":", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "value", "=", "mapping", ".", "get", "(", "value", ",", "value", ")", "return", "(", "key", ",", "value", ")" ]
Split given attribute word to key, value pair. Values are casted to python equivalents. :param word: API word. :returns: Key, value pair.
[ "Split", "given", "attribute", "word", "to", "key", "value", "pair", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L1-L16
train
luqasz/librouteros
librouteros/protocol.py
composeWord
def composeWord(key, value): """ Create a attribute word from key, value pair. Values are casted to api equivalents. """ mapping = {True: 'yes', False: 'no'} # this is necesary because 1 == True, 0 == False if type(value) == int: value = str(value) else: value = mapping.get(value, str(value)) return '={}={}'.format(key, value)
python
def composeWord(key, value): """ Create a attribute word from key, value pair. Values are casted to api equivalents. """ mapping = {True: 'yes', False: 'no'} # this is necesary because 1 == True, 0 == False if type(value) == int: value = str(value) else: value = mapping.get(value, str(value)) return '={}={}'.format(key, value)
[ "def", "composeWord", "(", "key", ",", "value", ")", ":", "mapping", "=", "{", "True", ":", "'yes'", ",", "False", ":", "'no'", "}", "# this is necesary because 1 == True, 0 == False", "if", "type", "(", "value", ")", "==", "int", ":", "value", "=", "str", "(", "value", ")", "else", ":", "value", "=", "mapping", ".", "get", "(", "value", ",", "str", "(", "value", ")", ")", "return", "'={}={}'", ".", "format", "(", "key", ",", "value", ")" ]
Create a attribute word from key, value pair. Values are casted to api equivalents.
[ "Create", "a", "attribute", "word", "from", "key", "value", "pair", ".", "Values", "are", "casted", "to", "api", "equivalents", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L19-L30
train
luqasz/librouteros
librouteros/login.py
login_token
def login_token(api, username, password): """Login using pre routeros 6.43 authorization method.""" sentence = api('/login') token = tuple(sentence)[0]['ret'] encoded = encode_password(token, password) tuple(api('/login', **{'name': username, 'response': encoded}))
python
def login_token(api, username, password): """Login using pre routeros 6.43 authorization method.""" sentence = api('/login') token = tuple(sentence)[0]['ret'] encoded = encode_password(token, password) tuple(api('/login', **{'name': username, 'response': encoded}))
[ "def", "login_token", "(", "api", ",", "username", ",", "password", ")", ":", "sentence", "=", "api", "(", "'/login'", ")", "token", "=", "tuple", "(", "sentence", ")", "[", "0", "]", "[", "'ret'", "]", "encoded", "=", "encode_password", "(", "token", ",", "password", ")", "tuple", "(", "api", "(", "'/login'", ",", "*", "*", "{", "'name'", ":", "username", ",", "'response'", ":", "encoded", "}", ")", ")" ]
Login using pre routeros 6.43 authorization method.
[ "Login", "using", "pre", "routeros", "6", ".", "43", "authorization", "method", "." ]
59293eb49c07a339af87b0416e4619e78ca5176d
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/login.py#L15-L20
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.check_relations
def check_relations(self, relations): """Recursive function which checks if a relation is valid.""" for rel in relations: if not rel: continue fields = rel.split('.', 1) local_field = fields[0] if local_field not in self.fields: raise ValueError('Unknown field "{}"'.format(local_field)) field = self.fields[local_field] if not isinstance(field, BaseRelationship): raise ValueError('Can only include relationships. "{}" is a "{}"' .format(field.name, field.__class__.__name__)) field.include_data = True if len(fields) > 1: field.schema.check_relations(fields[1:])
python
def check_relations(self, relations): """Recursive function which checks if a relation is valid.""" for rel in relations: if not rel: continue fields = rel.split('.', 1) local_field = fields[0] if local_field not in self.fields: raise ValueError('Unknown field "{}"'.format(local_field)) field = self.fields[local_field] if not isinstance(field, BaseRelationship): raise ValueError('Can only include relationships. "{}" is a "{}"' .format(field.name, field.__class__.__name__)) field.include_data = True if len(fields) > 1: field.schema.check_relations(fields[1:])
[ "def", "check_relations", "(", "self", ",", "relations", ")", ":", "for", "rel", "in", "relations", ":", "if", "not", "rel", ":", "continue", "fields", "=", "rel", ".", "split", "(", "'.'", ",", "1", ")", "local_field", "=", "fields", "[", "0", "]", "if", "local_field", "not", "in", "self", ".", "fields", ":", "raise", "ValueError", "(", "'Unknown field \"{}\"'", ".", "format", "(", "local_field", ")", ")", "field", "=", "self", ".", "fields", "[", "local_field", "]", "if", "not", "isinstance", "(", "field", ",", "BaseRelationship", ")", ":", "raise", "ValueError", "(", "'Can only include relationships. \"{}\" is a \"{}\"'", ".", "format", "(", "field", ".", "name", ",", "field", ".", "__class__", ".", "__name__", ")", ")", "field", ".", "include_data", "=", "True", "if", "len", "(", "fields", ")", ">", "1", ":", "field", ".", "schema", ".", "check_relations", "(", "fields", "[", "1", ":", "]", ")" ]
Recursive function which checks if a relation is valid.
[ "Recursive", "function", "which", "checks", "if", "a", "relation", "is", "valid", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L102-L120
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_json_api_response
def format_json_api_response(self, data, many): """Post-dump hook that formats serialized data as a top-level JSON API object. See: http://jsonapi.org/format/#document-top-level """ ret = self.format_items(data, many) ret = self.wrap_response(ret, many) ret = self.render_included_data(ret) ret = self.render_meta_document(ret) return ret
python
def format_json_api_response(self, data, many): """Post-dump hook that formats serialized data as a top-level JSON API object. See: http://jsonapi.org/format/#document-top-level """ ret = self.format_items(data, many) ret = self.wrap_response(ret, many) ret = self.render_included_data(ret) ret = self.render_meta_document(ret) return ret
[ "def", "format_json_api_response", "(", "self", ",", "data", ",", "many", ")", ":", "ret", "=", "self", ".", "format_items", "(", "data", ",", "many", ")", "ret", "=", "self", ".", "wrap_response", "(", "ret", ",", "many", ")", "ret", "=", "self", ".", "render_included_data", "(", "ret", ")", "ret", "=", "self", ".", "render_meta_document", "(", "ret", ")", "return", "ret" ]
Post-dump hook that formats serialized data as a top-level JSON API object. See: http://jsonapi.org/format/#document-top-level
[ "Post", "-", "dump", "hook", "that", "formats", "serialized", "data", "as", "a", "top", "-", "level", "JSON", "API", "object", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L123-L132
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema._do_load
def _do_load(self, data, many=None, **kwargs): """Override `marshmallow.Schema._do_load` for custom JSON API handling. Specifically, we do this to format errors as JSON API Error objects, and to support loading of included data. """ many = self.many if many is None else bool(many) # Store this on the instance so we have access to the included data # when processing relationships (``included`` is outside of the # ``data``). self.included_data = data.get('included', {}) self.document_meta = data.get('meta', {}) try: result = super(Schema, self)._do_load(data, many, **kwargs) except ValidationError as err: # strict mode error_messages = err.messages if '_schema' in error_messages: error_messages = error_messages['_schema'] formatted_messages = self.format_errors(error_messages, many=many) err.messages = formatted_messages raise err else: # On marshmallow 2, _do_load returns a tuple (load_data, errors) if _MARSHMALLOW_VERSION_INFO[0] < 3: data, error_messages = result if '_schema' in error_messages: error_messages = error_messages['_schema'] formatted_messages = self.format_errors(error_messages, many=many) return data, formatted_messages return result
python
def _do_load(self, data, many=None, **kwargs): """Override `marshmallow.Schema._do_load` for custom JSON API handling. Specifically, we do this to format errors as JSON API Error objects, and to support loading of included data. """ many = self.many if many is None else bool(many) # Store this on the instance so we have access to the included data # when processing relationships (``included`` is outside of the # ``data``). self.included_data = data.get('included', {}) self.document_meta = data.get('meta', {}) try: result = super(Schema, self)._do_load(data, many, **kwargs) except ValidationError as err: # strict mode error_messages = err.messages if '_schema' in error_messages: error_messages = error_messages['_schema'] formatted_messages = self.format_errors(error_messages, many=many) err.messages = formatted_messages raise err else: # On marshmallow 2, _do_load returns a tuple (load_data, errors) if _MARSHMALLOW_VERSION_INFO[0] < 3: data, error_messages = result if '_schema' in error_messages: error_messages = error_messages['_schema'] formatted_messages = self.format_errors(error_messages, many=many) return data, formatted_messages return result
[ "def", "_do_load", "(", "self", ",", "data", ",", "many", "=", "None", ",", "*", "*", "kwargs", ")", ":", "many", "=", "self", ".", "many", "if", "many", "is", "None", "else", "bool", "(", "many", ")", "# Store this on the instance so we have access to the included data", "# when processing relationships (``included`` is outside of the", "# ``data``).", "self", ".", "included_data", "=", "data", ".", "get", "(", "'included'", ",", "{", "}", ")", "self", ".", "document_meta", "=", "data", ".", "get", "(", "'meta'", ",", "{", "}", ")", "try", ":", "result", "=", "super", "(", "Schema", ",", "self", ")", ".", "_do_load", "(", "data", ",", "many", ",", "*", "*", "kwargs", ")", "except", "ValidationError", "as", "err", ":", "# strict mode", "error_messages", "=", "err", ".", "messages", "if", "'_schema'", "in", "error_messages", ":", "error_messages", "=", "error_messages", "[", "'_schema'", "]", "formatted_messages", "=", "self", ".", "format_errors", "(", "error_messages", ",", "many", "=", "many", ")", "err", ".", "messages", "=", "formatted_messages", "raise", "err", "else", ":", "# On marshmallow 2, _do_load returns a tuple (load_data, errors)", "if", "_MARSHMALLOW_VERSION_INFO", "[", "0", "]", "<", "3", ":", "data", ",", "error_messages", "=", "result", "if", "'_schema'", "in", "error_messages", ":", "error_messages", "=", "error_messages", "[", "'_schema'", "]", "formatted_messages", "=", "self", ".", "format_errors", "(", "error_messages", ",", "many", "=", "many", ")", "return", "data", ",", "formatted_messages", "return", "result" ]
Override `marshmallow.Schema._do_load` for custom JSON API handling. Specifically, we do this to format errors as JSON API Error objects, and to support loading of included data.
[ "Override", "marshmallow", ".", "Schema", ".", "_do_load", "for", "custom", "JSON", "API", "handling", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L229-L260
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema._extract_from_included
def _extract_from_included(self, data): """Extract included data matching the items in ``data``. For each item in ``data``, extract the full data from the included data. """ return (item for item in self.included_data if item['type'] == data['type'] and str(item['id']) == str(data['id']))
python
def _extract_from_included(self, data): """Extract included data matching the items in ``data``. For each item in ``data``, extract the full data from the included data. """ return (item for item in self.included_data if item['type'] == data['type'] and str(item['id']) == str(data['id']))
[ "def", "_extract_from_included", "(", "self", ",", "data", ")", ":", "return", "(", "item", "for", "item", "in", "self", ".", "included_data", "if", "item", "[", "'type'", "]", "==", "data", "[", "'type'", "]", "and", "str", "(", "item", "[", "'id'", "]", ")", "==", "str", "(", "data", "[", "'id'", "]", ")", ")" ]
Extract included data matching the items in ``data``. For each item in ``data``, extract the full data from the included data.
[ "Extract", "included", "data", "matching", "the", "items", "in", "data", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L262-L270
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.inflect
def inflect(self, text): """Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise do nothing. """ return self.opts.inflect(text) if self.opts.inflect else text
python
def inflect(self, text): """Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise do nothing. """ return self.opts.inflect(text) if self.opts.inflect else text
[ "def", "inflect", "(", "self", ",", "text", ")", ":", "return", "self", ".", "opts", ".", "inflect", "(", "text", ")", "if", "self", ".", "opts", ".", "inflect", "else", "text" ]
Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise do nothing.
[ "Inflect", "text", "if", "the", "inflect", "class", "Meta", "option", "is", "defined", "otherwise", "do", "nothing", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L272-L276
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_errors
def format_errors(self, errors, many): """Format validation errors as JSON Error objects.""" if not errors: return {} if isinstance(errors, (list, tuple)): return {'errors': errors} formatted_errors = [] if many: for index, errors in iteritems(errors): for field_name, field_errors in iteritems(errors): formatted_errors.extend([ self.format_error(field_name, message, index=index) for message in field_errors ]) else: for field_name, field_errors in iteritems(errors): formatted_errors.extend([ self.format_error(field_name, message) for message in field_errors ]) return {'errors': formatted_errors}
python
def format_errors(self, errors, many): """Format validation errors as JSON Error objects.""" if not errors: return {} if isinstance(errors, (list, tuple)): return {'errors': errors} formatted_errors = [] if many: for index, errors in iteritems(errors): for field_name, field_errors in iteritems(errors): formatted_errors.extend([ self.format_error(field_name, message, index=index) for message in field_errors ]) else: for field_name, field_errors in iteritems(errors): formatted_errors.extend([ self.format_error(field_name, message) for message in field_errors ]) return {'errors': formatted_errors}
[ "def", "format_errors", "(", "self", ",", "errors", ",", "many", ")", ":", "if", "not", "errors", ":", "return", "{", "}", "if", "isinstance", "(", "errors", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "{", "'errors'", ":", "errors", "}", "formatted_errors", "=", "[", "]", "if", "many", ":", "for", "index", ",", "errors", "in", "iteritems", "(", "errors", ")", ":", "for", "field_name", ",", "field_errors", "in", "iteritems", "(", "errors", ")", ":", "formatted_errors", ".", "extend", "(", "[", "self", ".", "format_error", "(", "field_name", ",", "message", ",", "index", "=", "index", ")", "for", "message", "in", "field_errors", "]", ")", "else", ":", "for", "field_name", ",", "field_errors", "in", "iteritems", "(", "errors", ")", ":", "formatted_errors", ".", "extend", "(", "[", "self", ".", "format_error", "(", "field_name", ",", "message", ")", "for", "message", "in", "field_errors", "]", ")", "return", "{", "'errors'", ":", "formatted_errors", "}" ]
Format validation errors as JSON Error objects.
[ "Format", "validation", "errors", "as", "JSON", "Error", "objects", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L280-L301
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_error
def format_error(self, field_name, message, index=None): """Override-able hook to format a single error message as an Error object. See: http://jsonapi.org/format/#error-objects """ pointer = ['/data'] if index is not None: pointer.append(str(index)) relationship = isinstance( self.declared_fields.get(field_name), BaseRelationship, ) if relationship: pointer.append('relationships') elif field_name != 'id': # JSONAPI identifier is a special field that exists above the attribute object. pointer.append('attributes') pointer.append(self.inflect(field_name)) if relationship: pointer.append('data') return { 'detail': message, 'source': { 'pointer': '/'.join(pointer), }, }
python
def format_error(self, field_name, message, index=None): """Override-able hook to format a single error message as an Error object. See: http://jsonapi.org/format/#error-objects """ pointer = ['/data'] if index is not None: pointer.append(str(index)) relationship = isinstance( self.declared_fields.get(field_name), BaseRelationship, ) if relationship: pointer.append('relationships') elif field_name != 'id': # JSONAPI identifier is a special field that exists above the attribute object. pointer.append('attributes') pointer.append(self.inflect(field_name)) if relationship: pointer.append('data') return { 'detail': message, 'source': { 'pointer': '/'.join(pointer), }, }
[ "def", "format_error", "(", "self", ",", "field_name", ",", "message", ",", "index", "=", "None", ")", ":", "pointer", "=", "[", "'/data'", "]", "if", "index", "is", "not", "None", ":", "pointer", ".", "append", "(", "str", "(", "index", ")", ")", "relationship", "=", "isinstance", "(", "self", ".", "declared_fields", ".", "get", "(", "field_name", ")", ",", "BaseRelationship", ",", ")", "if", "relationship", ":", "pointer", ".", "append", "(", "'relationships'", ")", "elif", "field_name", "!=", "'id'", ":", "# JSONAPI identifier is a special field that exists above the attribute object.", "pointer", ".", "append", "(", "'attributes'", ")", "pointer", ".", "append", "(", "self", ".", "inflect", "(", "field_name", ")", ")", "if", "relationship", ":", "pointer", ".", "append", "(", "'data'", ")", "return", "{", "'detail'", ":", "message", ",", "'source'", ":", "{", "'pointer'", ":", "'/'", ".", "join", "(", "pointer", ")", ",", "}", ",", "}" ]
Override-able hook to format a single error message as an Error object. See: http://jsonapi.org/format/#error-objects
[ "Override", "-", "able", "hook", "to", "format", "a", "single", "error", "message", "as", "an", "Error", "object", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L303-L332
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_item
def format_item(self, item): """Format a single datum as a Resource object. See: http://jsonapi.org/format/#document-resource-objects """ # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identifier object, or null, for requests that target single resources if not item: return None ret = self.dict_class() ret[TYPE] = self.opts.type_ # Get the schema attributes so we can confirm `dump-to` values exist attributes = { (get_dump_key(self.fields[field]) or field): field for field in self.fields } for field_name, value in iteritems(item): attribute = attributes[field_name] if attribute == ID: ret[ID] = value elif isinstance(self.fields[attribute], DocumentMeta): if not self.document_meta: self.document_meta = self.dict_class() self.document_meta.update(value) elif isinstance(self.fields[attribute], ResourceMeta): if 'meta' not in ret: ret['meta'] = self.dict_class() ret['meta'].update(value) elif isinstance(self.fields[attribute], BaseRelationship): if value: if 'relationships' not in ret: ret['relationships'] = self.dict_class() ret['relationships'][self.inflect(field_name)] = value else: if 'attributes' not in ret: ret['attributes'] = self.dict_class() ret['attributes'][self.inflect(field_name)] = value links = self.get_resource_links(item) if links: ret['links'] = links return ret
python
def format_item(self, item): """Format a single datum as a Resource object. See: http://jsonapi.org/format/#document-resource-objects """ # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identifier object, or null, for requests that target single resources if not item: return None ret = self.dict_class() ret[TYPE] = self.opts.type_ # Get the schema attributes so we can confirm `dump-to` values exist attributes = { (get_dump_key(self.fields[field]) or field): field for field in self.fields } for field_name, value in iteritems(item): attribute = attributes[field_name] if attribute == ID: ret[ID] = value elif isinstance(self.fields[attribute], DocumentMeta): if not self.document_meta: self.document_meta = self.dict_class() self.document_meta.update(value) elif isinstance(self.fields[attribute], ResourceMeta): if 'meta' not in ret: ret['meta'] = self.dict_class() ret['meta'].update(value) elif isinstance(self.fields[attribute], BaseRelationship): if value: if 'relationships' not in ret: ret['relationships'] = self.dict_class() ret['relationships'][self.inflect(field_name)] = value else: if 'attributes' not in ret: ret['attributes'] = self.dict_class() ret['attributes'][self.inflect(field_name)] = value links = self.get_resource_links(item) if links: ret['links'] = links return ret
[ "def", "format_item", "(", "self", ",", "item", ")", ":", "# http://jsonapi.org/format/#document-top-level", "# Primary data MUST be either... a single resource object, a single resource", "# identifier object, or null, for requests that target single resources", "if", "not", "item", ":", "return", "None", "ret", "=", "self", ".", "dict_class", "(", ")", "ret", "[", "TYPE", "]", "=", "self", ".", "opts", ".", "type_", "# Get the schema attributes so we can confirm `dump-to` values exist", "attributes", "=", "{", "(", "get_dump_key", "(", "self", ".", "fields", "[", "field", "]", ")", "or", "field", ")", ":", "field", "for", "field", "in", "self", ".", "fields", "}", "for", "field_name", ",", "value", "in", "iteritems", "(", "item", ")", ":", "attribute", "=", "attributes", "[", "field_name", "]", "if", "attribute", "==", "ID", ":", "ret", "[", "ID", "]", "=", "value", "elif", "isinstance", "(", "self", ".", "fields", "[", "attribute", "]", ",", "DocumentMeta", ")", ":", "if", "not", "self", ".", "document_meta", ":", "self", ".", "document_meta", "=", "self", ".", "dict_class", "(", ")", "self", ".", "document_meta", ".", "update", "(", "value", ")", "elif", "isinstance", "(", "self", ".", "fields", "[", "attribute", "]", ",", "ResourceMeta", ")", ":", "if", "'meta'", "not", "in", "ret", ":", "ret", "[", "'meta'", "]", "=", "self", ".", "dict_class", "(", ")", "ret", "[", "'meta'", "]", ".", "update", "(", "value", ")", "elif", "isinstance", "(", "self", ".", "fields", "[", "attribute", "]", ",", "BaseRelationship", ")", ":", "if", "value", ":", "if", "'relationships'", "not", "in", "ret", ":", "ret", "[", "'relationships'", "]", "=", "self", ".", "dict_class", "(", ")", "ret", "[", "'relationships'", "]", "[", "self", ".", "inflect", "(", "field_name", ")", "]", "=", "value", "else", ":", "if", "'attributes'", "not", "in", "ret", ":", "ret", "[", "'attributes'", "]", "=", "self", ".", "dict_class", "(", ")", "ret", "[", "'attributes'", "]", "[", "self", ".", "inflect", "(", "field_name", ")", "]", "=", "value", "links", "=", "self", ".", "get_resource_links", "(", "item", ")", "if", "links", ":", "ret", "[", "'links'", "]", "=", "links", "return", "ret" ]
Format a single datum as a Resource object. See: http://jsonapi.org/format/#document-resource-objects
[ "Format", "a", "single", "datum", "as", "a", "Resource", "object", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L334-L379
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_items
def format_items(self, data, many): """Format data as a Resource object or list of Resource objects. See: http://jsonapi.org/format/#document-resource-objects """ if many: return [self.format_item(item) for item in data] else: return self.format_item(data)
python
def format_items(self, data, many): """Format data as a Resource object or list of Resource objects. See: http://jsonapi.org/format/#document-resource-objects """ if many: return [self.format_item(item) for item in data] else: return self.format_item(data)
[ "def", "format_items", "(", "self", ",", "data", ",", "many", ")", ":", "if", "many", ":", "return", "[", "self", ".", "format_item", "(", "item", ")", "for", "item", "in", "data", "]", "else", ":", "return", "self", ".", "format_item", "(", "data", ")" ]
Format data as a Resource object or list of Resource objects. See: http://jsonapi.org/format/#document-resource-objects
[ "Format", "data", "as", "a", "Resource", "object", "or", "list", "of", "Resource", "objects", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L381-L389
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.get_top_level_links
def get_top_level_links(self, data, many): """Hook for adding links to the root of the response data.""" self_link = None if many: if self.opts.self_url_many: self_link = self.generate_url(self.opts.self_url_many) else: if self.opts.self_url: self_link = data.get('links', {}).get('self', None) return {'self': self_link}
python
def get_top_level_links(self, data, many): """Hook for adding links to the root of the response data.""" self_link = None if many: if self.opts.self_url_many: self_link = self.generate_url(self.opts.self_url_many) else: if self.opts.self_url: self_link = data.get('links', {}).get('self', None) return {'self': self_link}
[ "def", "get_top_level_links", "(", "self", ",", "data", ",", "many", ")", ":", "self_link", "=", "None", "if", "many", ":", "if", "self", ".", "opts", ".", "self_url_many", ":", "self_link", "=", "self", ".", "generate_url", "(", "self", ".", "opts", ".", "self_url_many", ")", "else", ":", "if", "self", ".", "opts", ".", "self_url", ":", "self_link", "=", "data", ".", "get", "(", "'links'", ",", "{", "}", ")", ".", "get", "(", "'self'", ",", "None", ")", "return", "{", "'self'", ":", "self_link", "}" ]
Hook for adding links to the root of the response data.
[ "Hook", "for", "adding", "links", "to", "the", "root", "of", "the", "response", "data", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L391-L402
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.get_resource_links
def get_resource_links(self, item): """Hook for adding links to a resource object.""" if self.opts.self_url: ret = self.dict_class() kwargs = resolve_params(item, self.opts.self_url_kwargs or {}) ret['self'] = self.generate_url(self.opts.self_url, **kwargs) return ret return None
python
def get_resource_links(self, item): """Hook for adding links to a resource object.""" if self.opts.self_url: ret = self.dict_class() kwargs = resolve_params(item, self.opts.self_url_kwargs or {}) ret['self'] = self.generate_url(self.opts.self_url, **kwargs) return ret return None
[ "def", "get_resource_links", "(", "self", ",", "item", ")", ":", "if", "self", ".", "opts", ".", "self_url", ":", "ret", "=", "self", ".", "dict_class", "(", ")", "kwargs", "=", "resolve_params", "(", "item", ",", "self", ".", "opts", ".", "self_url_kwargs", "or", "{", "}", ")", "ret", "[", "'self'", "]", "=", "self", ".", "generate_url", "(", "self", ".", "opts", ".", "self_url", ",", "*", "*", "kwargs", ")", "return", "ret", "return", "None" ]
Hook for adding links to a resource object.
[ "Hook", "for", "adding", "links", "to", "a", "resource", "object", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L404-L411
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.wrap_response
def wrap_response(self, data, many): """Wrap data and links according to the JSON API """ ret = {'data': data} # self_url_many is still valid when there isn't any data, but self_url # may only be included if there is data in the ret if many or data: top_level_links = self.get_top_level_links(data, many) if top_level_links['self']: ret['links'] = top_level_links return ret
python
def wrap_response(self, data, many): """Wrap data and links according to the JSON API """ ret = {'data': data} # self_url_many is still valid when there isn't any data, but self_url # may only be included if there is data in the ret if many or data: top_level_links = self.get_top_level_links(data, many) if top_level_links['self']: ret['links'] = top_level_links return ret
[ "def", "wrap_response", "(", "self", ",", "data", ",", "many", ")", ":", "ret", "=", "{", "'data'", ":", "data", "}", "# self_url_many is still valid when there isn't any data, but self_url", "# may only be included if there is data in the ret", "if", "many", "or", "data", ":", "top_level_links", "=", "self", ".", "get_top_level_links", "(", "data", ",", "many", ")", "if", "top_level_links", "[", "'self'", "]", ":", "ret", "[", "'links'", "]", "=", "top_level_links", "return", "ret" ]
Wrap data and links according to the JSON API
[ "Wrap", "data", "and", "links", "according", "to", "the", "JSON", "API" ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L413-L422
train
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/fields.py
Relationship.extract_value
def extract_value(self, data): """Extract the id key and validate the request structure.""" errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self.type_: errors.append('Invalid `type` specified') if errors: raise ValidationError(errors) # If ``attributes`` is set, we've folded included data into this # relationship. Unserialize it if we have a schema set; otherwise we # fall back below to old behaviour of only IDs. if 'attributes' in data and self.__schema: result = self.schema.load({'data': data, 'included': self.root.included_data}) return result.data if _MARSHMALLOW_VERSION_INFO[0] < 3 else result id_value = data.get('id') if self.__schema: id_value = self.schema.fields['id'].deserialize(id_value) return id_value
python
def extract_value(self, data): """Extract the id key and validate the request structure.""" errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self.type_: errors.append('Invalid `type` specified') if errors: raise ValidationError(errors) # If ``attributes`` is set, we've folded included data into this # relationship. Unserialize it if we have a schema set; otherwise we # fall back below to old behaviour of only IDs. if 'attributes' in data and self.__schema: result = self.schema.load({'data': data, 'included': self.root.included_data}) return result.data if _MARSHMALLOW_VERSION_INFO[0] < 3 else result id_value = data.get('id') if self.__schema: id_value = self.schema.fields['id'].deserialize(id_value) return id_value
[ "def", "extract_value", "(", "self", ",", "data", ")", ":", "errors", "=", "[", "]", "if", "'id'", "not", "in", "data", ":", "errors", ".", "append", "(", "'Must have an `id` field'", ")", "if", "'type'", "not", "in", "data", ":", "errors", ".", "append", "(", "'Must have a `type` field'", ")", "elif", "data", "[", "'type'", "]", "!=", "self", ".", "type_", ":", "errors", ".", "append", "(", "'Invalid `type` specified'", ")", "if", "errors", ":", "raise", "ValidationError", "(", "errors", ")", "# If ``attributes`` is set, we've folded included data into this", "# relationship. Unserialize it if we have a schema set; otherwise we", "# fall back below to old behaviour of only IDs.", "if", "'attributes'", "in", "data", "and", "self", ".", "__schema", ":", "result", "=", "self", ".", "schema", ".", "load", "(", "{", "'data'", ":", "data", ",", "'included'", ":", "self", ".", "root", ".", "included_data", "}", ")", "return", "result", ".", "data", "if", "_MARSHMALLOW_VERSION_INFO", "[", "0", "]", "<", "3", "else", "result", "id_value", "=", "data", ".", "get", "(", "'id'", ")", "if", "self", ".", "__schema", ":", "id_value", "=", "self", ".", "schema", ".", "fields", "[", "'id'", "]", ".", "deserialize", "(", "id_value", ")", "return", "id_value" ]
Extract the id key and validate the request structure.
[ "Extract", "the", "id", "key", "and", "validate", "the", "request", "structure", "." ]
7183c9bb5cdeace4143e6678bab48d433ac439a1
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/fields.py#L183-L208
train
thoth-station/python
thoth/python/helpers.py
fill_package_digests
def fill_package_digests(generated_project: Project) -> Project: """Temporary fill package digests stated in Pipfile.lock.""" for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages): if package_version.hashes: # Already filled from the last run. continue if package_version.index: scanned_hashes = package_version.index.get_package_hashes( package_version.name, package_version.locked_version ) else: for source in generated_project.pipfile.meta.sources.values(): try: scanned_hashes = source.get_package_hashes(package_version.name, package_version.locked_version) break except Exception: continue else: raise ValueError("Unable to find package hashes") for entry in scanned_hashes: package_version.hashes.append("sha256:" + entry["sha256"]) return generated_project
python
def fill_package_digests(generated_project: Project) -> Project: """Temporary fill package digests stated in Pipfile.lock.""" for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages): if package_version.hashes: # Already filled from the last run. continue if package_version.index: scanned_hashes = package_version.index.get_package_hashes( package_version.name, package_version.locked_version ) else: for source in generated_project.pipfile.meta.sources.values(): try: scanned_hashes = source.get_package_hashes(package_version.name, package_version.locked_version) break except Exception: continue else: raise ValueError("Unable to find package hashes") for entry in scanned_hashes: package_version.hashes.append("sha256:" + entry["sha256"]) return generated_project
[ "def", "fill_package_digests", "(", "generated_project", ":", "Project", ")", "->", "Project", ":", "for", "package_version", "in", "chain", "(", "generated_project", ".", "pipfile_lock", ".", "packages", ",", "generated_project", ".", "pipfile_lock", ".", "dev_packages", ")", ":", "if", "package_version", ".", "hashes", ":", "# Already filled from the last run.", "continue", "if", "package_version", ".", "index", ":", "scanned_hashes", "=", "package_version", ".", "index", ".", "get_package_hashes", "(", "package_version", ".", "name", ",", "package_version", ".", "locked_version", ")", "else", ":", "for", "source", "in", "generated_project", ".", "pipfile", ".", "meta", ".", "sources", ".", "values", "(", ")", ":", "try", ":", "scanned_hashes", "=", "source", ".", "get_package_hashes", "(", "package_version", ".", "name", ",", "package_version", ".", "locked_version", ")", "break", "except", "Exception", ":", "continue", "else", ":", "raise", "ValueError", "(", "\"Unable to find package hashes\"", ")", "for", "entry", "in", "scanned_hashes", ":", "package_version", ".", "hashes", ".", "append", "(", "\"sha256:\"", "+", "entry", "[", "\"sha256\"", "]", ")", "return", "generated_project" ]
Temporary fill package digests stated in Pipfile.lock.
[ "Temporary", "fill", "package", "digests", "stated", "in", "Pipfile", ".", "lock", "." ]
bd2a4a4f552faf54834ce9febea4e2834a1d0bab
https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/helpers.py#L26-L50
train
thoth-station/python
thoth/python/digests_fetcher.py
PythonDigestsFetcher.fetch_digests
def fetch_digests(self, package_name: str, package_version: str) -> dict: """Fetch digests for the given package in specified version from the given package index.""" report = {} for source in self._sources: try: report[source.url] = source.get_package_hashes(package_name, package_version) except NotFound as exc: _LOGGER.debug( f"Package {package_name} in version {package_version} not " f"found on index {source.name}: {str(exc)}" ) return report
python
def fetch_digests(self, package_name: str, package_version: str) -> dict: """Fetch digests for the given package in specified version from the given package index.""" report = {} for source in self._sources: try: report[source.url] = source.get_package_hashes(package_name, package_version) except NotFound as exc: _LOGGER.debug( f"Package {package_name} in version {package_version} not " f"found on index {source.name}: {str(exc)}" ) return report
[ "def", "fetch_digests", "(", "self", ",", "package_name", ":", "str", ",", "package_version", ":", "str", ")", "->", "dict", ":", "report", "=", "{", "}", "for", "source", "in", "self", ".", "_sources", ":", "try", ":", "report", "[", "source", ".", "url", "]", "=", "source", ".", "get_package_hashes", "(", "package_name", ",", "package_version", ")", "except", "NotFound", "as", "exc", ":", "_LOGGER", ".", "debug", "(", "f\"Package {package_name} in version {package_version} not \"", "f\"found on index {source.name}: {str(exc)}\"", ")", "return", "report" ]
Fetch digests for the given package in specified version from the given package index.
[ "Fetch", "digests", "for", "the", "given", "package", "in", "specified", "version", "from", "the", "given", "package", "index", "." ]
bd2a4a4f552faf54834ce9febea4e2834a1d0bab
https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/digests_fetcher.py#L44-L57
train
blockstack/pybitcoin
pybitcoin/passphrases/legacy.py
random_passphrase_from_wordlist
def random_passphrase_from_wordlist(phrase_length, wordlist): """ An extremely entropy efficient passphrase generator. This function: -Pulls entropy from the safer alternative to /dev/urandom: /dev/random -Doesn't rely on random.seed (words are selected right from the entropy) -Only requires 2 entropy bytes/word for word lists of up to 65536 words """ passphrase_words = [] numbytes_of_entropy = phrase_length * 2 entropy = list(dev_random_entropy(numbytes_of_entropy, fallback_to_urandom=True)) bytes_per_word = int(ceil(log(len(wordlist), 2) / 8)) if (phrase_length * bytes_per_word > 64): raise Exception("Error! This operation requires too much entropy. \ Try a shorter phrase length or word list.") for i in range(phrase_length): current_entropy = entropy[i*bytes_per_word:(i+1)*bytes_per_word] index = int(''.join(current_entropy).encode('hex'), 16) % len(wordlist) word = wordlist[index] passphrase_words.append(word) return " ".join(passphrase_words)
python
def random_passphrase_from_wordlist(phrase_length, wordlist): """ An extremely entropy efficient passphrase generator. This function: -Pulls entropy from the safer alternative to /dev/urandom: /dev/random -Doesn't rely on random.seed (words are selected right from the entropy) -Only requires 2 entropy bytes/word for word lists of up to 65536 words """ passphrase_words = [] numbytes_of_entropy = phrase_length * 2 entropy = list(dev_random_entropy(numbytes_of_entropy, fallback_to_urandom=True)) bytes_per_word = int(ceil(log(len(wordlist), 2) / 8)) if (phrase_length * bytes_per_word > 64): raise Exception("Error! This operation requires too much entropy. \ Try a shorter phrase length or word list.") for i in range(phrase_length): current_entropy = entropy[i*bytes_per_word:(i+1)*bytes_per_word] index = int(''.join(current_entropy).encode('hex'), 16) % len(wordlist) word = wordlist[index] passphrase_words.append(word) return " ".join(passphrase_words)
[ "def", "random_passphrase_from_wordlist", "(", "phrase_length", ",", "wordlist", ")", ":", "passphrase_words", "=", "[", "]", "numbytes_of_entropy", "=", "phrase_length", "*", "2", "entropy", "=", "list", "(", "dev_random_entropy", "(", "numbytes_of_entropy", ",", "fallback_to_urandom", "=", "True", ")", ")", "bytes_per_word", "=", "int", "(", "ceil", "(", "log", "(", "len", "(", "wordlist", ")", ",", "2", ")", "/", "8", ")", ")", "if", "(", "phrase_length", "*", "bytes_per_word", ">", "64", ")", ":", "raise", "Exception", "(", "\"Error! This operation requires too much entropy. \\\n Try a shorter phrase length or word list.\"", ")", "for", "i", "in", "range", "(", "phrase_length", ")", ":", "current_entropy", "=", "entropy", "[", "i", "*", "bytes_per_word", ":", "(", "i", "+", "1", ")", "*", "bytes_per_word", "]", "index", "=", "int", "(", "''", ".", "join", "(", "current_entropy", ")", ".", "encode", "(", "'hex'", ")", ",", "16", ")", "%", "len", "(", "wordlist", ")", "word", "=", "wordlist", "[", "index", "]", "passphrase_words", ".", "append", "(", "word", ")", "return", "\" \"", ".", "join", "(", "passphrase_words", ")" ]
An extremely entropy efficient passphrase generator. This function: -Pulls entropy from the safer alternative to /dev/urandom: /dev/random -Doesn't rely on random.seed (words are selected right from the entropy) -Only requires 2 entropy bytes/word for word lists of up to 65536 words
[ "An", "extremely", "entropy", "efficient", "passphrase", "generator", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/legacy.py#L15-L41
train
blockstack/pybitcoin
pybitcoin/hash.py
reverse_hash
def reverse_hash(hash, hex_format=True): """ hash is in hex or binary format """ if not hex_format: hash = hexlify(hash) return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))
python
def reverse_hash(hash, hex_format=True): """ hash is in hex or binary format """ if not hex_format: hash = hexlify(hash) return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))
[ "def", "reverse_hash", "(", "hash", ",", "hex_format", "=", "True", ")", ":", "if", "not", "hex_format", ":", "hash", "=", "hexlify", "(", "hash", ")", "return", "\"\"", ".", "join", "(", "reversed", "(", "[", "hash", "[", "i", ":", "i", "+", "2", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "hash", ")", ",", "2", ")", "]", ")", ")" ]
hash is in hex or binary format
[ "hash", "is", "in", "hex", "or", "binary", "format" ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/hash.py#L45-L50
train
blockstack/pybitcoin
pybitcoin/passphrases/passphrase.py
get_num_words_with_entropy
def get_num_words_with_entropy(bits_of_entropy, wordlist): """ Gets the number of words randomly selected from a given wordlist that would result in the number of bits of entropy specified. """ entropy_per_word = math.log(len(wordlist))/math.log(2) num_words = int(math.ceil(bits_of_entropy/entropy_per_word)) return num_words
python
def get_num_words_with_entropy(bits_of_entropy, wordlist): """ Gets the number of words randomly selected from a given wordlist that would result in the number of bits of entropy specified. """ entropy_per_word = math.log(len(wordlist))/math.log(2) num_words = int(math.ceil(bits_of_entropy/entropy_per_word)) return num_words
[ "def", "get_num_words_with_entropy", "(", "bits_of_entropy", ",", "wordlist", ")", ":", "entropy_per_word", "=", "math", ".", "log", "(", "len", "(", "wordlist", ")", ")", "/", "math", ".", "log", "(", "2", ")", "num_words", "=", "int", "(", "math", ".", "ceil", "(", "bits_of_entropy", "/", "entropy_per_word", ")", ")", "return", "num_words" ]
Gets the number of words randomly selected from a given wordlist that would result in the number of bits of entropy specified.
[ "Gets", "the", "number", "of", "words", "randomly", "selected", "from", "a", "given", "wordlist", "that", "would", "result", "in", "the", "number", "of", "bits", "of", "entropy", "specified", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L29-L35
train
blockstack/pybitcoin
pybitcoin/passphrases/passphrase.py
create_passphrase
def create_passphrase(bits_of_entropy=None, num_words=None, language='english', word_source='wiktionary'): """ Creates a passphrase that has a certain number of bits of entropy OR a certain number of words. """ wordlist = get_wordlist(language, word_source) if not num_words: if not bits_of_entropy: bits_of_entropy = 80 num_words = get_num_words_with_entropy(bits_of_entropy, wordlist) return ' '.join(pick_random_words_from_wordlist(wordlist, num_words))
python
def create_passphrase(bits_of_entropy=None, num_words=None, language='english', word_source='wiktionary'): """ Creates a passphrase that has a certain number of bits of entropy OR a certain number of words. """ wordlist = get_wordlist(language, word_source) if not num_words: if not bits_of_entropy: bits_of_entropy = 80 num_words = get_num_words_with_entropy(bits_of_entropy, wordlist) return ' '.join(pick_random_words_from_wordlist(wordlist, num_words))
[ "def", "create_passphrase", "(", "bits_of_entropy", "=", "None", ",", "num_words", "=", "None", ",", "language", "=", "'english'", ",", "word_source", "=", "'wiktionary'", ")", ":", "wordlist", "=", "get_wordlist", "(", "language", ",", "word_source", ")", "if", "not", "num_words", ":", "if", "not", "bits_of_entropy", ":", "bits_of_entropy", "=", "80", "num_words", "=", "get_num_words_with_entropy", "(", "bits_of_entropy", ",", "wordlist", ")", "return", "' '", ".", "join", "(", "pick_random_words_from_wordlist", "(", "wordlist", ",", "num_words", ")", ")" ]
Creates a passphrase that has a certain number of bits of entropy OR a certain number of words.
[ "Creates", "a", "passphrase", "that", "has", "a", "certain", "number", "of", "bits", "of", "entropy", "OR", "a", "certain", "number", "of", "words", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L42-L54
train
blockstack/pybitcoin
pybitcoin/transactions/serialize.py
serialize_input
def serialize_input(input, signature_script_hex=''): """ Serializes a transaction input. """ if not (isinstance(input, dict) and 'transaction_hash' in input \ and 'output_index' in input): raise Exception('Required parameters: transaction_hash, output_index') if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64: raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash']) elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32: raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash'])) if not 'sequence' in input: input['sequence'] = UINT_MAX return ''.join([ flip_endian(input['transaction_hash']), hexlify(struct.pack('<I', input['output_index'])), hexlify(variable_length_int(len(signature_script_hex)/2)), signature_script_hex, hexlify(struct.pack('<I', input['sequence'])) ])
python
def serialize_input(input, signature_script_hex=''): """ Serializes a transaction input. """ if not (isinstance(input, dict) and 'transaction_hash' in input \ and 'output_index' in input): raise Exception('Required parameters: transaction_hash, output_index') if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64: raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash']) elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32: raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash'])) if not 'sequence' in input: input['sequence'] = UINT_MAX return ''.join([ flip_endian(input['transaction_hash']), hexlify(struct.pack('<I', input['output_index'])), hexlify(variable_length_int(len(signature_script_hex)/2)), signature_script_hex, hexlify(struct.pack('<I', input['sequence'])) ])
[ "def", "serialize_input", "(", "input", ",", "signature_script_hex", "=", "''", ")", ":", "if", "not", "(", "isinstance", "(", "input", ",", "dict", ")", "and", "'transaction_hash'", "in", "input", "and", "'output_index'", "in", "input", ")", ":", "raise", "Exception", "(", "'Required parameters: transaction_hash, output_index'", ")", "if", "is_hex", "(", "str", "(", "input", "[", "'transaction_hash'", "]", ")", ")", "and", "len", "(", "str", "(", "input", "[", "'transaction_hash'", "]", ")", ")", "!=", "64", ":", "raise", "Exception", "(", "\"Transaction hash '%s' must be 32 bytes\"", "%", "input", "[", "'transaction_hash'", "]", ")", "elif", "not", "is_hex", "(", "str", "(", "input", "[", "'transaction_hash'", "]", ")", ")", "and", "len", "(", "str", "(", "input", "[", "'transaction_hash'", "]", ")", ")", "!=", "32", ":", "raise", "Exception", "(", "\"Transaction hash '%s' must be 32 bytes\"", "%", "hexlify", "(", "input", "[", "'transaction_hash'", "]", ")", ")", "if", "not", "'sequence'", "in", "input", ":", "input", "[", "'sequence'", "]", "=", "UINT_MAX", "return", "''", ".", "join", "(", "[", "flip_endian", "(", "input", "[", "'transaction_hash'", "]", ")", ",", "hexlify", "(", "struct", ".", "pack", "(", "'<I'", ",", "input", "[", "'output_index'", "]", ")", ")", ",", "hexlify", "(", "variable_length_int", "(", "len", "(", "signature_script_hex", ")", "/", "2", ")", ")", ",", "signature_script_hex", ",", "hexlify", "(", "struct", ".", "pack", "(", "'<I'", ",", "input", "[", "'sequence'", "]", ")", ")", "]", ")" ]
Serializes a transaction input.
[ "Serializes", "a", "transaction", "input", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L20-L42
train
blockstack/pybitcoin
pybitcoin/transactions/serialize.py
serialize_output
def serialize_output(output): """ Serializes a transaction output. """ if not ('value' in output and 'script_hex' in output): raise Exception('Invalid output') return ''.join([ hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites hexlify(variable_length_int(len(output['script_hex'])/2)), output['script_hex'] ])
python
def serialize_output(output): """ Serializes a transaction output. """ if not ('value' in output and 'script_hex' in output): raise Exception('Invalid output') return ''.join([ hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites hexlify(variable_length_int(len(output['script_hex'])/2)), output['script_hex'] ])
[ "def", "serialize_output", "(", "output", ")", ":", "if", "not", "(", "'value'", "in", "output", "and", "'script_hex'", "in", "output", ")", ":", "raise", "Exception", "(", "'Invalid output'", ")", "return", "''", ".", "join", "(", "[", "hexlify", "(", "struct", ".", "pack", "(", "'<Q'", ",", "output", "[", "'value'", "]", ")", ")", ",", "# pack into 8 bites", "hexlify", "(", "variable_length_int", "(", "len", "(", "output", "[", "'script_hex'", "]", ")", "/", "2", ")", ")", ",", "output", "[", "'script_hex'", "]", "]", ")" ]
Serializes a transaction output.
[ "Serializes", "a", "transaction", "output", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L45-L55
train
blockstack/pybitcoin
pybitcoin/transactions/serialize.py
serialize_transaction
def serialize_transaction(inputs, outputs, lock_time=0, version=1): """ Serializes a transaction. """ # add in the inputs serialized_inputs = ''.join([serialize_input(input) for input in inputs]) # add in the outputs serialized_outputs = ''.join([serialize_output(output) for output in outputs]) return ''.join([ # add in the version number hexlify(struct.pack('<I', version)), # add in the number of inputs hexlify(variable_length_int(len(inputs))), # add in the inputs serialized_inputs, # add in the number of outputs hexlify(variable_length_int(len(outputs))), # add in the outputs serialized_outputs, # add in the lock time hexlify(struct.pack('<I', lock_time)), ])
python
def serialize_transaction(inputs, outputs, lock_time=0, version=1): """ Serializes a transaction. """ # add in the inputs serialized_inputs = ''.join([serialize_input(input) for input in inputs]) # add in the outputs serialized_outputs = ''.join([serialize_output(output) for output in outputs]) return ''.join([ # add in the version number hexlify(struct.pack('<I', version)), # add in the number of inputs hexlify(variable_length_int(len(inputs))), # add in the inputs serialized_inputs, # add in the number of outputs hexlify(variable_length_int(len(outputs))), # add in the outputs serialized_outputs, # add in the lock time hexlify(struct.pack('<I', lock_time)), ])
[ "def", "serialize_transaction", "(", "inputs", ",", "outputs", ",", "lock_time", "=", "0", ",", "version", "=", "1", ")", ":", "# add in the inputs", "serialized_inputs", "=", "''", ".", "join", "(", "[", "serialize_input", "(", "input", ")", "for", "input", "in", "inputs", "]", ")", "# add in the outputs", "serialized_outputs", "=", "''", ".", "join", "(", "[", "serialize_output", "(", "output", ")", "for", "output", "in", "outputs", "]", ")", "return", "''", ".", "join", "(", "[", "# add in the version number", "hexlify", "(", "struct", ".", "pack", "(", "'<I'", ",", "version", ")", ")", ",", "# add in the number of inputs", "hexlify", "(", "variable_length_int", "(", "len", "(", "inputs", ")", ")", ")", ",", "# add in the inputs", "serialized_inputs", ",", "# add in the number of outputs", "hexlify", "(", "variable_length_int", "(", "len", "(", "outputs", ")", ")", ")", ",", "# add in the outputs", "serialized_outputs", ",", "# add in the lock time", "hexlify", "(", "struct", ".", "pack", "(", "'<I'", ",", "lock_time", ")", ")", ",", "]", ")" ]
Serializes a transaction.
[ "Serializes", "a", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L58-L81
train
blockstack/pybitcoin
pybitcoin/transactions/serialize.py
deserialize_transaction
def deserialize_transaction(tx_hex): """ Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string Each output will have: * value: int * script_hex: string """ tx = bitcoin.deserialize(str(tx_hex)) inputs = tx["ins"] outputs = tx["outs"] ret_inputs = [] ret_outputs = [] for inp in inputs: ret_inp = { "transaction_hash": inp["outpoint"]["hash"], "output_index": int(inp["outpoint"]["index"]), } if "sequence" in inp: ret_inp["sequence"] = int(inp["sequence"]) if "script" in inp: ret_inp["script_sig"] = inp["script"] ret_inputs.append(ret_inp) for out in outputs: ret_out = { "value": out["value"], "script_hex": out["script"] } ret_outputs.append(ret_out) return ret_inputs, ret_outputs, tx["locktime"], tx["version"]
python
def deserialize_transaction(tx_hex): """ Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string Each output will have: * value: int * script_hex: string """ tx = bitcoin.deserialize(str(tx_hex)) inputs = tx["ins"] outputs = tx["outs"] ret_inputs = [] ret_outputs = [] for inp in inputs: ret_inp = { "transaction_hash": inp["outpoint"]["hash"], "output_index": int(inp["outpoint"]["index"]), } if "sequence" in inp: ret_inp["sequence"] = int(inp["sequence"]) if "script" in inp: ret_inp["script_sig"] = inp["script"] ret_inputs.append(ret_inp) for out in outputs: ret_out = { "value": out["value"], "script_hex": out["script"] } ret_outputs.append(ret_out) return ret_inputs, ret_outputs, tx["locktime"], tx["version"]
[ "def", "deserialize_transaction", "(", "tx_hex", ")", ":", "tx", "=", "bitcoin", ".", "deserialize", "(", "str", "(", "tx_hex", ")", ")", "inputs", "=", "tx", "[", "\"ins\"", "]", "outputs", "=", "tx", "[", "\"outs\"", "]", "ret_inputs", "=", "[", "]", "ret_outputs", "=", "[", "]", "for", "inp", "in", "inputs", ":", "ret_inp", "=", "{", "\"transaction_hash\"", ":", "inp", "[", "\"outpoint\"", "]", "[", "\"hash\"", "]", ",", "\"output_index\"", ":", "int", "(", "inp", "[", "\"outpoint\"", "]", "[", "\"index\"", "]", ")", ",", "}", "if", "\"sequence\"", "in", "inp", ":", "ret_inp", "[", "\"sequence\"", "]", "=", "int", "(", "inp", "[", "\"sequence\"", "]", ")", "if", "\"script\"", "in", "inp", ":", "ret_inp", "[", "\"script_sig\"", "]", "=", "inp", "[", "\"script\"", "]", "ret_inputs", ".", "append", "(", "ret_inp", ")", "for", "out", "in", "outputs", ":", "ret_out", "=", "{", "\"value\"", ":", "out", "[", "\"value\"", "]", ",", "\"script_hex\"", ":", "out", "[", "\"script\"", "]", "}", "ret_outputs", ".", "append", "(", "ret_out", ")", "return", "ret_inputs", ",", "ret_outputs", ",", "tx", "[", "\"locktime\"", "]", ",", "tx", "[", "\"version\"", "]" ]
Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string Each output will have: * value: int * script_hex: string
[ "Given", "a", "serialized", "transaction", "return", "its", "inputs", "outputs", "locktime", "and", "version" ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L84-L130
train
blockstack/pybitcoin
pybitcoin/transactions/utils.py
variable_length_int
def variable_length_int(i): """ Encodes integers into variable length integers, which are used in Bitcoin in order to save space. """ if not isinstance(i, (int,long)): raise Exception('i must be an integer') if i < (2**8-3): return chr(i) # pack the integer into one byte elif i < (2**16): return chr(253) + struct.pack('<H', i) # pack into 2 bytes elif i < (2**32): return chr(254) + struct.pack('<I', i) # pack into 4 bytes elif i < (2**64): return chr(255) + struct.pack('<Q', i) # pack into 8 bites else: raise Exception('Integer cannot exceed 8 bytes in length.')
python
def variable_length_int(i): """ Encodes integers into variable length integers, which are used in Bitcoin in order to save space. """ if not isinstance(i, (int,long)): raise Exception('i must be an integer') if i < (2**8-3): return chr(i) # pack the integer into one byte elif i < (2**16): return chr(253) + struct.pack('<H', i) # pack into 2 bytes elif i < (2**32): return chr(254) + struct.pack('<I', i) # pack into 4 bytes elif i < (2**64): return chr(255) + struct.pack('<Q', i) # pack into 8 bites else: raise Exception('Integer cannot exceed 8 bytes in length.')
[ "def", "variable_length_int", "(", "i", ")", ":", "if", "not", "isinstance", "(", "i", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "Exception", "(", "'i must be an integer'", ")", "if", "i", "<", "(", "2", "**", "8", "-", "3", ")", ":", "return", "chr", "(", "i", ")", "# pack the integer into one byte", "elif", "i", "<", "(", "2", "**", "16", ")", ":", "return", "chr", "(", "253", ")", "+", "struct", ".", "pack", "(", "'<H'", ",", "i", ")", "# pack into 2 bytes", "elif", "i", "<", "(", "2", "**", "32", ")", ":", "return", "chr", "(", "254", ")", "+", "struct", ".", "pack", "(", "'<I'", ",", "i", ")", "# pack into 4 bytes", "elif", "i", "<", "(", "2", "**", "64", ")", ":", "return", "chr", "(", "255", ")", "+", "struct", ".", "pack", "(", "'<Q'", ",", "i", ")", "# pack into 8 bites", "else", ":", "raise", "Exception", "(", "'Integer cannot exceed 8 bytes in length.'", ")" ]
Encodes integers into variable length integers, which are used in Bitcoin in order to save space.
[ "Encodes", "integers", "into", "variable", "length", "integers", "which", "are", "used", "in", "Bitcoin", "in", "order", "to", "save", "space", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/utils.py#L25-L41
train
blockstack/pybitcoin
pybitcoin/transactions/scripts.py
make_pay_to_address_script
def make_pay_to_address_script(address): """ Takes in an address and returns the script """ hash160 = hexlify(b58check_decode(address)) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex(script_string)
python
def make_pay_to_address_script(address): """ Takes in an address and returns the script """ hash160 = hexlify(b58check_decode(address)) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex(script_string)
[ "def", "make_pay_to_address_script", "(", "address", ")", ":", "hash160", "=", "hexlify", "(", "b58check_decode", "(", "address", ")", ")", "script_string", "=", "'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG'", "%", "hash160", "return", "script_to_hex", "(", "script_string", ")" ]
Takes in an address and returns the script
[ "Takes", "in", "an", "address", "and", "returns", "the", "script" ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L37-L42
train
blockstack/pybitcoin
pybitcoin/transactions/scripts.py
make_op_return_script
def make_op_return_script(data, format='bin'): """ Takes in raw ascii data to be embedded and returns a script. """ if format == 'hex': assert(is_hex(data)) hex_data = data elif format == 'bin': hex_data = hexlify(data) else: raise Exception("Format must be either 'hex' or 'bin'") num_bytes = count_bytes(hex_data) if num_bytes > MAX_BYTES_AFTER_OP_RETURN: raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes) script_string = 'OP_RETURN %s' % hex_data return script_to_hex(script_string)
python
def make_op_return_script(data, format='bin'): """ Takes in raw ascii data to be embedded and returns a script. """ if format == 'hex': assert(is_hex(data)) hex_data = data elif format == 'bin': hex_data = hexlify(data) else: raise Exception("Format must be either 'hex' or 'bin'") num_bytes = count_bytes(hex_data) if num_bytes > MAX_BYTES_AFTER_OP_RETURN: raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes) script_string = 'OP_RETURN %s' % hex_data return script_to_hex(script_string)
[ "def", "make_op_return_script", "(", "data", ",", "format", "=", "'bin'", ")", ":", "if", "format", "==", "'hex'", ":", "assert", "(", "is_hex", "(", "data", ")", ")", "hex_data", "=", "data", "elif", "format", "==", "'bin'", ":", "hex_data", "=", "hexlify", "(", "data", ")", "else", ":", "raise", "Exception", "(", "\"Format must be either 'hex' or 'bin'\"", ")", "num_bytes", "=", "count_bytes", "(", "hex_data", ")", "if", "num_bytes", ">", "MAX_BYTES_AFTER_OP_RETURN", ":", "raise", "Exception", "(", "'Data is %i bytes - must not exceed 40.'", "%", "num_bytes", ")", "script_string", "=", "'OP_RETURN %s'", "%", "hex_data", "return", "script_to_hex", "(", "script_string", ")" ]
Takes in raw ascii data to be embedded and returns a script.
[ "Takes", "in", "raw", "ascii", "data", "to", "be", "embedded", "and", "returns", "a", "script", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L44-L60
train
blockstack/pybitcoin
pybitcoin/services/bitcoind.py
create_bitcoind_service_proxy
def create_bitcoind_service_proxy( rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False): """ create a bitcoind service proxy """ protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port) return AuthServiceProxy(uri)
python
def create_bitcoind_service_proxy( rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False): """ create a bitcoind service proxy """ protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port) return AuthServiceProxy(uri)
[ "def", "create_bitcoind_service_proxy", "(", "rpc_username", ",", "rpc_password", ",", "server", "=", "'127.0.0.1'", ",", "port", "=", "8332", ",", "use_https", "=", "False", ")", ":", "protocol", "=", "'https'", "if", "use_https", "else", "'http'", "uri", "=", "'%s://%s:%s@%s:%s'", "%", "(", "protocol", ",", "rpc_username", ",", "rpc_password", ",", "server", ",", "port", ")", "return", "AuthServiceProxy", "(", "uri", ")" ]
create a bitcoind service proxy
[ "create", "a", "bitcoind", "service", "proxy" ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/services/bitcoind.py#L21-L28
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
get_unspents
def get_unspents(address, blockchain_client=BlockchainInfoClient()): """ Gets the unspent outputs for a given address. """ if isinstance(blockchain_client, BlockcypherClient): return blockcypher.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): return blockchain_info.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, ChainComClient): return chain_com.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)): return bitcoind.get_unspents(address, blockchain_client) elif hasattr(blockchain_client, "get_unspents"): return blockchain_client.get_unspents( address ) elif isinstance(blockchain_client, BlockchainClient): raise Exception('That blockchain interface is not supported.') else: raise Exception('A BlockchainClient object is required')
python
def get_unspents(address, blockchain_client=BlockchainInfoClient()): """ Gets the unspent outputs for a given address. """ if isinstance(blockchain_client, BlockcypherClient): return blockcypher.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): return blockchain_info.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, ChainComClient): return chain_com.get_unspents(address, blockchain_client) elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)): return bitcoind.get_unspents(address, blockchain_client) elif hasattr(blockchain_client, "get_unspents"): return blockchain_client.get_unspents( address ) elif isinstance(blockchain_client, BlockchainClient): raise Exception('That blockchain interface is not supported.') else: raise Exception('A BlockchainClient object is required')
[ "def", "get_unspents", "(", "address", ",", "blockchain_client", "=", "BlockchainInfoClient", "(", ")", ")", ":", "if", "isinstance", "(", "blockchain_client", ",", "BlockcypherClient", ")", ":", "return", "blockcypher", ".", "get_unspents", "(", "address", ",", "blockchain_client", ")", "elif", "isinstance", "(", "blockchain_client", ",", "BlockchainInfoClient", ")", ":", "return", "blockchain_info", ".", "get_unspents", "(", "address", ",", "blockchain_client", ")", "elif", "isinstance", "(", "blockchain_client", ",", "ChainComClient", ")", ":", "return", "chain_com", ".", "get_unspents", "(", "address", ",", "blockchain_client", ")", "elif", "isinstance", "(", "blockchain_client", ",", "(", "BitcoindClient", ",", "AuthServiceProxy", ")", ")", ":", "return", "bitcoind", ".", "get_unspents", "(", "address", ",", "blockchain_client", ")", "elif", "hasattr", "(", "blockchain_client", ",", "\"get_unspents\"", ")", ":", "return", "blockchain_client", ".", "get_unspents", "(", "address", ")", "elif", "isinstance", "(", "blockchain_client", ",", "BlockchainClient", ")", ":", "raise", "Exception", "(", "'That blockchain interface is not supported.'", ")", "else", ":", "raise", "Exception", "(", "'A BlockchainClient object is required'", ")" ]
Gets the unspent outputs for a given address.
[ "Gets", "the", "unspent", "outputs", "for", "a", "given", "address", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L32-L48
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
broadcast_transaction
def broadcast_transaction(hex_tx, blockchain_client): """ Dispatches a raw hex transaction to the network. """ if isinstance(blockchain_client, BlockcypherClient): return blockcypher.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): return blockchain_info.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, ChainComClient): return chain_com.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)): return bitcoind.broadcast_transaction(hex_tx, blockchain_client) elif hasattr(blockchain_client, "broadcast_transaction"): return blockchain_client.broadcast_transaction( hex_tx ) elif isinstance(blockchain_client, BlockchainClient): raise Exception('That blockchain interface is not supported.') else: raise Exception('A BlockchainClient object is required')
python
def broadcast_transaction(hex_tx, blockchain_client): """ Dispatches a raw hex transaction to the network. """ if isinstance(blockchain_client, BlockcypherClient): return blockcypher.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): return blockchain_info.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, ChainComClient): return chain_com.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)): return bitcoind.broadcast_transaction(hex_tx, blockchain_client) elif hasattr(blockchain_client, "broadcast_transaction"): return blockchain_client.broadcast_transaction( hex_tx ) elif isinstance(blockchain_client, BlockchainClient): raise Exception('That blockchain interface is not supported.') else: raise Exception('A BlockchainClient object is required')
[ "def", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", ":", "if", "isinstance", "(", "blockchain_client", ",", "BlockcypherClient", ")", ":", "return", "blockcypher", ".", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", "elif", "isinstance", "(", "blockchain_client", ",", "BlockchainInfoClient", ")", ":", "return", "blockchain_info", ".", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", "elif", "isinstance", "(", "blockchain_client", ",", "ChainComClient", ")", ":", "return", "chain_com", ".", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", "elif", "isinstance", "(", "blockchain_client", ",", "(", "BitcoindClient", ",", "AuthServiceProxy", ")", ")", ":", "return", "bitcoind", ".", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", "elif", "hasattr", "(", "blockchain_client", ",", "\"broadcast_transaction\"", ")", ":", "return", "blockchain_client", ".", "broadcast_transaction", "(", "hex_tx", ")", "elif", "isinstance", "(", "blockchain_client", ",", "BlockchainClient", ")", ":", "raise", "Exception", "(", "'That blockchain interface is not supported.'", ")", "else", ":", "raise", "Exception", "(", "'A BlockchainClient object is required'", ")" ]
Dispatches a raw hex transaction to the network.
[ "Dispatches", "a", "raw", "hex", "transaction", "to", "the", "network", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L51-L67
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
make_send_to_address_tx
def make_send_to_address_tx(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): """ Builds and signs a "send to address" transaction. """ # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client) # get the change address if not change_address: change_address = from_address # create the outputs outputs = make_pay_to_address_outputs(recipient_address, amount, inputs, change_address, fee=fee) # serialize the transaction unsigned_tx = serialize_transaction(inputs, outputs) # generate a scriptSig for each input for i in xrange(0, len(inputs)): signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex()) unsigned_tx = signed_tx # return the signed tx return signed_tx
python
def make_send_to_address_tx(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): """ Builds and signs a "send to address" transaction. """ # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client) # get the change address if not change_address: change_address = from_address # create the outputs outputs = make_pay_to_address_outputs(recipient_address, amount, inputs, change_address, fee=fee) # serialize the transaction unsigned_tx = serialize_transaction(inputs, outputs) # generate a scriptSig for each input for i in xrange(0, len(inputs)): signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex()) unsigned_tx = signed_tx # return the signed tx return signed_tx
[ "def", "make_send_to_address_tx", "(", "recipient_address", ",", "amount", ",", "private_key", ",", "blockchain_client", "=", "BlockchainInfoClient", "(", ")", ",", "fee", "=", "STANDARD_FEE", ",", "change_address", "=", "None", ")", ":", "# get out the private key object, sending address, and inputs", "private_key_obj", ",", "from_address", ",", "inputs", "=", "analyze_private_key", "(", "private_key", ",", "blockchain_client", ")", "# get the change address", "if", "not", "change_address", ":", "change_address", "=", "from_address", "# create the outputs", "outputs", "=", "make_pay_to_address_outputs", "(", "recipient_address", ",", "amount", ",", "inputs", ",", "change_address", ",", "fee", "=", "fee", ")", "# serialize the transaction", "unsigned_tx", "=", "serialize_transaction", "(", "inputs", ",", "outputs", ")", "# generate a scriptSig for each input", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "inputs", ")", ")", ":", "signed_tx", "=", "sign_transaction", "(", "unsigned_tx", ",", "i", ",", "private_key_obj", ".", "to_hex", "(", ")", ")", "unsigned_tx", "=", "signed_tx", "# return the signed tx", "return", "signed_tx" ]
Builds and signs a "send to address" transaction.
[ "Builds", "and", "signs", "a", "send", "to", "address", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L87-L110
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
make_op_return_tx
def make_op_return_tx(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): """ Builds and signs an OP_RETURN transaction. """ # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client) # get the change address if not change_address: change_address = from_address # create the outputs outputs = make_op_return_outputs(data, inputs, change_address, fee=fee, format=format) # serialize the transaction unsigned_tx = serialize_transaction(inputs, outputs) # generate a scriptSig for each input for i in xrange(0, len(inputs)): signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex()) unsigned_tx = signed_tx # return the signed tx return signed_tx
python
def make_op_return_tx(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): """ Builds and signs an OP_RETURN transaction. """ # get out the private key object, sending address, and inputs private_key_obj, from_address, inputs = analyze_private_key(private_key, blockchain_client) # get the change address if not change_address: change_address = from_address # create the outputs outputs = make_op_return_outputs(data, inputs, change_address, fee=fee, format=format) # serialize the transaction unsigned_tx = serialize_transaction(inputs, outputs) # generate a scriptSig for each input for i in xrange(0, len(inputs)): signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex()) unsigned_tx = signed_tx # return the signed tx return signed_tx
[ "def", "make_op_return_tx", "(", "data", ",", "private_key", ",", "blockchain_client", "=", "BlockchainInfoClient", "(", ")", ",", "fee", "=", "OP_RETURN_FEE", ",", "change_address", "=", "None", ",", "format", "=", "'bin'", ")", ":", "# get out the private key object, sending address, and inputs", "private_key_obj", ",", "from_address", ",", "inputs", "=", "analyze_private_key", "(", "private_key", ",", "blockchain_client", ")", "# get the change address", "if", "not", "change_address", ":", "change_address", "=", "from_address", "# create the outputs", "outputs", "=", "make_op_return_outputs", "(", "data", ",", "inputs", ",", "change_address", ",", "fee", "=", "fee", ",", "format", "=", "format", ")", "# serialize the transaction", "unsigned_tx", "=", "serialize_transaction", "(", "inputs", ",", "outputs", ")", "# generate a scriptSig for each input", "for", "i", "in", "xrange", "(", "0", ",", "len", "(", "inputs", ")", ")", ":", "signed_tx", "=", "sign_transaction", "(", "unsigned_tx", ",", "i", ",", "private_key_obj", ".", "to_hex", "(", ")", ")", "unsigned_tx", "=", "signed_tx", "# return the signed tx", "return", "signed_tx" ]
Builds and signs an OP_RETURN transaction.
[ "Builds", "and", "signs", "an", "OP_RETURN", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L113-L136
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
send_to_address
def send_to_address(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): """ Builds, signs, and dispatches a "send to address" transaction. """ # build and sign the tx signed_tx = make_send_to_address_tx(recipient_address, amount, private_key, blockchain_client, fee=fee, change_address=change_address) # dispatch the signed transction to the network response = broadcast_transaction(signed_tx, blockchain_client) # return the response return response
python
def send_to_address(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): """ Builds, signs, and dispatches a "send to address" transaction. """ # build and sign the tx signed_tx = make_send_to_address_tx(recipient_address, amount, private_key, blockchain_client, fee=fee, change_address=change_address) # dispatch the signed transction to the network response = broadcast_transaction(signed_tx, blockchain_client) # return the response return response
[ "def", "send_to_address", "(", "recipient_address", ",", "amount", ",", "private_key", ",", "blockchain_client", "=", "BlockchainInfoClient", "(", ")", ",", "fee", "=", "STANDARD_FEE", ",", "change_address", "=", "None", ")", ":", "# build and sign the tx", "signed_tx", "=", "make_send_to_address_tx", "(", "recipient_address", ",", "amount", ",", "private_key", ",", "blockchain_client", ",", "fee", "=", "fee", ",", "change_address", "=", "change_address", ")", "# dispatch the signed transction to the network", "response", "=", "broadcast_transaction", "(", "signed_tx", ",", "blockchain_client", ")", "# return the response", "return", "response" ]
Builds, signs, and dispatches a "send to address" transaction.
[ "Builds", "signs", "and", "dispatches", "a", "send", "to", "address", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L139-L151
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
embed_data_in_blockchain
def embed_data_in_blockchain(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): """ Builds, signs, and dispatches an OP_RETURN transaction. """ # build and sign the tx signed_tx = make_op_return_tx(data, private_key, blockchain_client, fee=fee, change_address=change_address, format=format) # dispatch the signed transction to the network response = broadcast_transaction(signed_tx, blockchain_client) # return the response return response
python
def embed_data_in_blockchain(data, private_key, blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE, change_address=None, format='bin'): """ Builds, signs, and dispatches an OP_RETURN transaction. """ # build and sign the tx signed_tx = make_op_return_tx(data, private_key, blockchain_client, fee=fee, change_address=change_address, format=format) # dispatch the signed transction to the network response = broadcast_transaction(signed_tx, blockchain_client) # return the response return response
[ "def", "embed_data_in_blockchain", "(", "data", ",", "private_key", ",", "blockchain_client", "=", "BlockchainInfoClient", "(", ")", ",", "fee", "=", "OP_RETURN_FEE", ",", "change_address", "=", "None", ",", "format", "=", "'bin'", ")", ":", "# build and sign the tx", "signed_tx", "=", "make_op_return_tx", "(", "data", ",", "private_key", ",", "blockchain_client", ",", "fee", "=", "fee", ",", "change_address", "=", "change_address", ",", "format", "=", "format", ")", "# dispatch the signed transction to the network", "response", "=", "broadcast_transaction", "(", "signed_tx", ",", "blockchain_client", ")", "# return the response", "return", "response" ]
Builds, signs, and dispatches an OP_RETURN transaction.
[ "Builds", "signs", "and", "dispatches", "an", "OP_RETURN", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L154-L165
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
sign_all_unsigned_inputs
def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex): """ Sign a serialized transaction's unsigned inputs @hex_privkey: private key that should sign inputs @unsigned_tx_hex: hex transaction with unsigned inputs Returns: signed hex transaction """ inputs, outputs, locktime, version = deserialize_transaction(unsigned_tx_hex) tx_hex = unsigned_tx_hex for index in xrange(0, len(inputs)): if len(inputs[index]['script_sig']) == 0: # tx with index i signed with privkey tx_hex = sign_transaction(str(unsigned_tx_hex), index, hex_privkey) unsigned_tx_hex = tx_hex return tx_hex
python
def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex): """ Sign a serialized transaction's unsigned inputs @hex_privkey: private key that should sign inputs @unsigned_tx_hex: hex transaction with unsigned inputs Returns: signed hex transaction """ inputs, outputs, locktime, version = deserialize_transaction(unsigned_tx_hex) tx_hex = unsigned_tx_hex for index in xrange(0, len(inputs)): if len(inputs[index]['script_sig']) == 0: # tx with index i signed with privkey tx_hex = sign_transaction(str(unsigned_tx_hex), index, hex_privkey) unsigned_tx_hex = tx_hex return tx_hex
[ "def", "sign_all_unsigned_inputs", "(", "hex_privkey", ",", "unsigned_tx_hex", ")", ":", "inputs", ",", "outputs", ",", "locktime", ",", "version", "=", "deserialize_transaction", "(", "unsigned_tx_hex", ")", "tx_hex", "=", "unsigned_tx_hex", "for", "index", "in", "xrange", "(", "0", ",", "len", "(", "inputs", ")", ")", ":", "if", "len", "(", "inputs", "[", "index", "]", "[", "'script_sig'", "]", ")", "==", "0", ":", "# tx with index i signed with privkey", "tx_hex", "=", "sign_transaction", "(", "str", "(", "unsigned_tx_hex", ")", ",", "index", ",", "hex_privkey", ")", "unsigned_tx_hex", "=", "tx_hex", "return", "tx_hex" ]
Sign a serialized transaction's unsigned inputs @hex_privkey: private key that should sign inputs @unsigned_tx_hex: hex transaction with unsigned inputs Returns: signed hex transaction
[ "Sign", "a", "serialized", "transaction", "s", "unsigned", "inputs" ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L187-L205
train
blockstack/pybitcoin
pybitcoin/merkle.py
calculate_merkle_root
def calculate_merkle_root(hashes, hash_function=bin_double_sha256, hex_format=True): """ takes in a list of binary hashes, returns a binary hash """ if hex_format: hashes = hex_to_bin_reversed_hashes(hashes) # keep moving up the merkle tree, constructing one row at a time while len(hashes) > 1: hashes = calculate_merkle_pairs(hashes, hash_function) # get the merkle root merkle_root = hashes[0] # if the user wants the merkle root in hex format, convert it if hex_format: return bin_to_hex_reversed(merkle_root) # return the binary merkle root return merkle_root
python
def calculate_merkle_root(hashes, hash_function=bin_double_sha256, hex_format=True): """ takes in a list of binary hashes, returns a binary hash """ if hex_format: hashes = hex_to_bin_reversed_hashes(hashes) # keep moving up the merkle tree, constructing one row at a time while len(hashes) > 1: hashes = calculate_merkle_pairs(hashes, hash_function) # get the merkle root merkle_root = hashes[0] # if the user wants the merkle root in hex format, convert it if hex_format: return bin_to_hex_reversed(merkle_root) # return the binary merkle root return merkle_root
[ "def", "calculate_merkle_root", "(", "hashes", ",", "hash_function", "=", "bin_double_sha256", ",", "hex_format", "=", "True", ")", ":", "if", "hex_format", ":", "hashes", "=", "hex_to_bin_reversed_hashes", "(", "hashes", ")", "# keep moving up the merkle tree, constructing one row at a time", "while", "len", "(", "hashes", ")", ">", "1", ":", "hashes", "=", "calculate_merkle_pairs", "(", "hashes", ",", "hash_function", ")", "# get the merkle root", "merkle_root", "=", "hashes", "[", "0", "]", "# if the user wants the merkle root in hex format, convert it", "if", "hex_format", ":", "return", "bin_to_hex_reversed", "(", "merkle_root", ")", "# return the binary merkle root", "return", "merkle_root" ]
takes in a list of binary hashes, returns a binary hash
[ "takes", "in", "a", "list", "of", "binary", "hashes", "returns", "a", "binary", "hash" ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/merkle.py#L23-L38
train
blockstack/pybitcoin
pybitcoin/b58check.py
b58check_encode
def b58check_encode(bin_s, version_byte=0): """ Takes in a binary string and converts it to a base 58 check string. """ # append the version byte to the beginning bin_s = chr(int(version_byte)) + bin_s # calculate the number of leading zeros num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0)) # add in the checksum add the end bin_s = bin_s + bin_checksum(bin_s) # convert from b2 to b16 hex_s = hexlify(bin_s) # convert from b16 to b58 b58_s = change_charset(hex_s, HEX_KEYSPACE, B58_KEYSPACE) return B58_KEYSPACE[0] * num_leading_zeros + b58_s
python
def b58check_encode(bin_s, version_byte=0): """ Takes in a binary string and converts it to a base 58 check string. """ # append the version byte to the beginning bin_s = chr(int(version_byte)) + bin_s # calculate the number of leading zeros num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0)) # add in the checksum add the end bin_s = bin_s + bin_checksum(bin_s) # convert from b2 to b16 hex_s = hexlify(bin_s) # convert from b16 to b58 b58_s = change_charset(hex_s, HEX_KEYSPACE, B58_KEYSPACE) return B58_KEYSPACE[0] * num_leading_zeros + b58_s
[ "def", "b58check_encode", "(", "bin_s", ",", "version_byte", "=", "0", ")", ":", "# append the version byte to the beginning", "bin_s", "=", "chr", "(", "int", "(", "version_byte", ")", ")", "+", "bin_s", "# calculate the number of leading zeros", "num_leading_zeros", "=", "len", "(", "re", ".", "match", "(", "r'^\\x00*'", ",", "bin_s", ")", ".", "group", "(", "0", ")", ")", "# add in the checksum add the end", "bin_s", "=", "bin_s", "+", "bin_checksum", "(", "bin_s", ")", "# convert from b2 to b16", "hex_s", "=", "hexlify", "(", "bin_s", ")", "# convert from b16 to b58", "b58_s", "=", "change_charset", "(", "hex_s", ",", "HEX_KEYSPACE", ",", "B58_KEYSPACE", ")", "return", "B58_KEYSPACE", "[", "0", "]", "*", "num_leading_zeros", "+", "b58_s" ]
Takes in a binary string and converts it to a base 58 check string.
[ "Takes", "in", "a", "binary", "string", "and", "converts", "it", "to", "a", "base", "58", "check", "string", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/b58check.py#L20-L33
train
blockstack/pybitcoin
pybitcoin/transactions/outputs.py
make_pay_to_address_outputs
def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address, fee=STANDARD_FEE): """ Builds the outputs for a "pay to address" transaction. """ return [ # main output { "script_hex": make_pay_to_address_script(to_address), "value": send_amount }, # change output { "script_hex": make_pay_to_address_script(change_address), "value": calculate_change_amount(inputs, send_amount, fee) } ]
python
def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address, fee=STANDARD_FEE): """ Builds the outputs for a "pay to address" transaction. """ return [ # main output { "script_hex": make_pay_to_address_script(to_address), "value": send_amount }, # change output { "script_hex": make_pay_to_address_script(change_address), "value": calculate_change_amount(inputs, send_amount, fee) } ]
[ "def", "make_pay_to_address_outputs", "(", "to_address", ",", "send_amount", ",", "inputs", ",", "change_address", ",", "fee", "=", "STANDARD_FEE", ")", ":", "return", "[", "# main output", "{", "\"script_hex\"", ":", "make_pay_to_address_script", "(", "to_address", ")", ",", "\"value\"", ":", "send_amount", "}", ",", "# change output", "{", "\"script_hex\"", ":", "make_pay_to_address_script", "(", "change_address", ")", ",", "\"value\"", ":", "calculate_change_amount", "(", "inputs", ",", "send_amount", ",", "fee", ")", "}", "]" ]
Builds the outputs for a "pay to address" transaction.
[ "Builds", "the", "outputs", "for", "a", "pay", "to", "address", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L23-L34
train
blockstack/pybitcoin
pybitcoin/transactions/outputs.py
make_op_return_outputs
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE, send_amount=0, format='bin'): """ Builds the outputs for an OP_RETURN transaction. """ return [ # main output { "script_hex": make_op_return_script(data, format=format), "value": send_amount }, # change output { "script_hex": make_pay_to_address_script(change_address), "value": calculate_change_amount(inputs, send_amount, fee) } ]
python
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE, send_amount=0, format='bin'): """ Builds the outputs for an OP_RETURN transaction. """ return [ # main output { "script_hex": make_op_return_script(data, format=format), "value": send_amount }, # change output { "script_hex": make_pay_to_address_script(change_address), "value": calculate_change_amount(inputs, send_amount, fee) } ]
[ "def", "make_op_return_outputs", "(", "data", ",", "inputs", ",", "change_address", ",", "fee", "=", "OP_RETURN_FEE", ",", "send_amount", "=", "0", ",", "format", "=", "'bin'", ")", ":", "return", "[", "# main output", "{", "\"script_hex\"", ":", "make_op_return_script", "(", "data", ",", "format", "=", "format", ")", ",", "\"value\"", ":", "send_amount", "}", ",", "# change output", "{", "\"script_hex\"", ":", "make_pay_to_address_script", "(", "change_address", ")", ",", "\"value\"", ":", "calculate_change_amount", "(", "inputs", ",", "send_amount", ",", "fee", ")", "}", "]" ]
Builds the outputs for an OP_RETURN transaction.
[ "Builds", "the", "outputs", "for", "an", "OP_RETURN", "transaction", "." ]
92c8da63c40f7418594b1ce395990c3f5a4787cc
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L36-L47
train
caktus/django-timepiece
timepiece/utils/__init__.py
add_timezone
def add_timezone(value, tz=None): """If the value is naive, then the timezone is added to it. If no timezone is given, timezone.get_current_timezone() is used. """ tz = tz or timezone.get_current_timezone() try: if timezone.is_naive(value): return timezone.make_aware(value, tz) except AttributeError: # 'datetime.date' object has no attribute 'tzinfo' dt = datetime.datetime.combine(value, datetime.time()) return timezone.make_aware(dt, tz) return value
python
def add_timezone(value, tz=None): """If the value is naive, then the timezone is added to it. If no timezone is given, timezone.get_current_timezone() is used. """ tz = tz or timezone.get_current_timezone() try: if timezone.is_naive(value): return timezone.make_aware(value, tz) except AttributeError: # 'datetime.date' object has no attribute 'tzinfo' dt = datetime.datetime.combine(value, datetime.time()) return timezone.make_aware(dt, tz) return value
[ "def", "add_timezone", "(", "value", ",", "tz", "=", "None", ")", ":", "tz", "=", "tz", "or", "timezone", ".", "get_current_timezone", "(", ")", "try", ":", "if", "timezone", ".", "is_naive", "(", "value", ")", ":", "return", "timezone", ".", "make_aware", "(", "value", ",", "tz", ")", "except", "AttributeError", ":", "# 'datetime.date' object has no attribute 'tzinfo'", "dt", "=", "datetime", ".", "datetime", ".", "combine", "(", "value", ",", "datetime", ".", "time", "(", ")", ")", "return", "timezone", ".", "make_aware", "(", "dt", ",", "tz", ")", "return", "value" ]
If the value is naive, then the timezone is added to it. If no timezone is given, timezone.get_current_timezone() is used.
[ "If", "the", "value", "is", "naive", "then", "the", "timezone", "is", "added", "to", "it", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L16-L28
train
caktus/django-timepiece
timepiece/utils/__init__.py
get_active_entry
def get_active_entry(user, select_for_update=False): """Returns the user's currently-active entry, or None.""" entries = apps.get_model('entries', 'Entry').no_join if select_for_update: entries = entries.select_for_update() entries = entries.filter(user=user, end_time__isnull=True) if not entries.exists(): return None if entries.count() > 1: raise ActiveEntryError('Only one active entry is allowed.') return entries[0]
python
def get_active_entry(user, select_for_update=False): """Returns the user's currently-active entry, or None.""" entries = apps.get_model('entries', 'Entry').no_join if select_for_update: entries = entries.select_for_update() entries = entries.filter(user=user, end_time__isnull=True) if not entries.exists(): return None if entries.count() > 1: raise ActiveEntryError('Only one active entry is allowed.') return entries[0]
[ "def", "get_active_entry", "(", "user", ",", "select_for_update", "=", "False", ")", ":", "entries", "=", "apps", ".", "get_model", "(", "'entries'", ",", "'Entry'", ")", ".", "no_join", "if", "select_for_update", ":", "entries", "=", "entries", ".", "select_for_update", "(", ")", "entries", "=", "entries", ".", "filter", "(", "user", "=", "user", ",", "end_time__isnull", "=", "True", ")", "if", "not", "entries", ".", "exists", "(", ")", ":", "return", "None", "if", "entries", ".", "count", "(", ")", ">", "1", ":", "raise", "ActiveEntryError", "(", "'Only one active entry is allowed.'", ")", "return", "entries", "[", "0", "]" ]
Returns the user's currently-active entry, or None.
[ "Returns", "the", "user", "s", "currently", "-", "active", "entry", "or", "None", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L31-L42
train
caktus/django-timepiece
timepiece/utils/__init__.py
get_month_start
def get_month_start(day=None): """Returns the first day of the given month.""" day = add_timezone(day or datetime.date.today()) return day.replace(day=1)
python
def get_month_start(day=None): """Returns the first day of the given month.""" day = add_timezone(day or datetime.date.today()) return day.replace(day=1)
[ "def", "get_month_start", "(", "day", "=", "None", ")", ":", "day", "=", "add_timezone", "(", "day", "or", "datetime", ".", "date", ".", "today", "(", ")", ")", "return", "day", ".", "replace", "(", "day", "=", "1", ")" ]
Returns the first day of the given month.
[ "Returns", "the", "first", "day", "of", "the", "given", "month", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L64-L67
train
caktus/django-timepiece
timepiece/utils/__init__.py
get_setting
def get_setting(name, **kwargs): """Returns the user-defined value for the setting, or a default value.""" if hasattr(settings, name): # Try user-defined settings first. return getattr(settings, name) if 'default' in kwargs: # Fall back to a specified default value. return kwargs['default'] if hasattr(defaults, name): # If that's not given, look in defaults file. return getattr(defaults, name) msg = '{0} must be specified in your project settings.'.format(name) raise AttributeError(msg)
python
def get_setting(name, **kwargs): """Returns the user-defined value for the setting, or a default value.""" if hasattr(settings, name): # Try user-defined settings first. return getattr(settings, name) if 'default' in kwargs: # Fall back to a specified default value. return kwargs['default'] if hasattr(defaults, name): # If that's not given, look in defaults file. return getattr(defaults, name) msg = '{0} must be specified in your project settings.'.format(name) raise AttributeError(msg)
[ "def", "get_setting", "(", "name", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "settings", ",", "name", ")", ":", "# Try user-defined settings first.", "return", "getattr", "(", "settings", ",", "name", ")", "if", "'default'", "in", "kwargs", ":", "# Fall back to a specified default value.", "return", "kwargs", "[", "'default'", "]", "if", "hasattr", "(", "defaults", ",", "name", ")", ":", "# If that's not given, look in defaults file.", "return", "getattr", "(", "defaults", ",", "name", ")", "msg", "=", "'{0} must be specified in your project settings.'", ".", "format", "(", "name", ")", "raise", "AttributeError", "(", "msg", ")" ]
Returns the user-defined value for the setting, or a default value.
[ "Returns", "the", "user", "-", "defined", "value", "for", "the", "setting", "or", "a", "default", "value", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L73-L82
train
caktus/django-timepiece
timepiece/utils/__init__.py
get_week_start
def get_week_start(day=None): """Returns the Monday of the given week.""" day = add_timezone(day or datetime.date.today()) days_since_monday = day.weekday() if days_since_monday != 0: day = day - relativedelta(days=days_since_monday) return day
python
def get_week_start(day=None): """Returns the Monday of the given week.""" day = add_timezone(day or datetime.date.today()) days_since_monday = day.weekday() if days_since_monday != 0: day = day - relativedelta(days=days_since_monday) return day
[ "def", "get_week_start", "(", "day", "=", "None", ")", ":", "day", "=", "add_timezone", "(", "day", "or", "datetime", ".", "date", ".", "today", "(", ")", ")", "days_since_monday", "=", "day", ".", "weekday", "(", ")", "if", "days_since_monday", "!=", "0", ":", "day", "=", "day", "-", "relativedelta", "(", "days", "=", "days_since_monday", ")", "return", "day" ]
Returns the Monday of the given week.
[ "Returns", "the", "Monday", "of", "the", "given", "week", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L85-L91
train
caktus/django-timepiece
timepiece/utils/__init__.py
get_year_start
def get_year_start(day=None): """Returns January 1 of the given year.""" day = add_timezone(day or datetime.date.today()) return day.replace(month=1).replace(day=1)
python
def get_year_start(day=None): """Returns January 1 of the given year.""" day = add_timezone(day or datetime.date.today()) return day.replace(month=1).replace(day=1)
[ "def", "get_year_start", "(", "day", "=", "None", ")", ":", "day", "=", "add_timezone", "(", "day", "or", "datetime", ".", "date", ".", "today", "(", ")", ")", "return", "day", ".", "replace", "(", "month", "=", "1", ")", ".", "replace", "(", "day", "=", "1", ")" ]
Returns January 1 of the given year.
[ "Returns", "January", "1", "of", "the", "given", "year", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L94-L97
train
caktus/django-timepiece
timepiece/utils/__init__.py
to_datetime
def to_datetime(date): """Transforms a date or datetime object into a date object.""" return datetime.datetime(date.year, date.month, date.day)
python
def to_datetime(date): """Transforms a date or datetime object into a date object.""" return datetime.datetime(date.year, date.month, date.day)
[ "def", "to_datetime", "(", "date", ")", ":", "return", "datetime", ".", "datetime", "(", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ")" ]
Transforms a date or datetime object into a date object.
[ "Transforms", "a", "date", "or", "datetime", "object", "into", "a", "date", "object", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L100-L102
train
caktus/django-timepiece
timepiece/reports/views.py
report_estimation_accuracy
def report_estimation_accuracy(request): """ Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3. """ contracts = ProjectContract.objects.filter( status=ProjectContract.STATUS_COMPLETE, type=ProjectContract.PROJECT_FIXED ) data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')] for c in contracts: if c.contracted_hours() == 0: continue pt_label = "%s (%.2f%%)" % (c.name, c.hours_worked / c.contracted_hours() * 100) data.append((c.contracted_hours(), c.hours_worked, pt_label)) chart_max = max([max(x[0], x[1]) for x in data[1:]]) # max of all targets & actuals return render(request, 'timepiece/reports/estimation_accuracy.html', { 'data': json.dumps(data, cls=DecimalEncoder), 'chart_max': chart_max, })
python
def report_estimation_accuracy(request): """ Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3. """ contracts = ProjectContract.objects.filter( status=ProjectContract.STATUS_COMPLETE, type=ProjectContract.PROJECT_FIXED ) data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')] for c in contracts: if c.contracted_hours() == 0: continue pt_label = "%s (%.2f%%)" % (c.name, c.hours_worked / c.contracted_hours() * 100) data.append((c.contracted_hours(), c.hours_worked, pt_label)) chart_max = max([max(x[0], x[1]) for x in data[1:]]) # max of all targets & actuals return render(request, 'timepiece/reports/estimation_accuracy.html', { 'data': json.dumps(data, cls=DecimalEncoder), 'chart_max': chart_max, })
[ "def", "report_estimation_accuracy", "(", "request", ")", ":", "contracts", "=", "ProjectContract", ".", "objects", ".", "filter", "(", "status", "=", "ProjectContract", ".", "STATUS_COMPLETE", ",", "type", "=", "ProjectContract", ".", "PROJECT_FIXED", ")", "data", "=", "[", "(", "'Target (hrs)'", ",", "'Actual (hrs)'", ",", "'Point Label'", ")", "]", "for", "c", "in", "contracts", ":", "if", "c", ".", "contracted_hours", "(", ")", "==", "0", ":", "continue", "pt_label", "=", "\"%s (%.2f%%)\"", "%", "(", "c", ".", "name", ",", "c", ".", "hours_worked", "/", "c", ".", "contracted_hours", "(", ")", "*", "100", ")", "data", ".", "append", "(", "(", "c", ".", "contracted_hours", "(", ")", ",", "c", ".", "hours_worked", ",", "pt_label", ")", ")", "chart_max", "=", "max", "(", "[", "max", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ")", "for", "x", "in", "data", "[", "1", ":", "]", "]", ")", "# max of all targets & actuals", "return", "render", "(", "request", ",", "'timepiece/reports/estimation_accuracy.html'", ",", "{", "'data'", ":", "json", ".", "dumps", "(", "data", ",", "cls", "=", "DecimalEncoder", ")", ",", "'chart_max'", ":", "chart_max", ",", "}", ")" ]
Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.
[ "Idea", "from", "Software", "Estimation", "Demystifying", "the", "Black", "Art", "McConnel", "2006", "Fig", "3", "-", "3", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L468-L487
train
caktus/django-timepiece
timepiece/reports/views.py
ReportMixin.get_context_data
def get_context_data(self, **kwargs): """Processes form data to get relevant entries & date_headers.""" context = super(ReportMixin, self).get_context_data(**kwargs) form = self.get_form() if form.is_valid(): data = form.cleaned_data start, end = form.save() entryQ = self.get_entry_query(start, end, data) trunc = data['trunc'] if entryQ: vals = ('pk', 'activity', 'project', 'project__name', 'project__status', 'project__type__label') entries = Entry.objects.date_trunc( trunc, extra_values=vals).filter(entryQ) else: entries = Entry.objects.none() end = end - relativedelta(days=1) date_headers = generate_dates(start, end, by=trunc) context.update({ 'from_date': start, 'to_date': end, 'date_headers': date_headers, 'entries': entries, 'filter_form': form, 'trunc': trunc, }) else: context.update({ 'from_date': None, 'to_date': None, 'date_headers': [], 'entries': Entry.objects.none(), 'filter_form': form, 'trunc': '', }) return context
python
def get_context_data(self, **kwargs): """Processes form data to get relevant entries & date_headers.""" context = super(ReportMixin, self).get_context_data(**kwargs) form = self.get_form() if form.is_valid(): data = form.cleaned_data start, end = form.save() entryQ = self.get_entry_query(start, end, data) trunc = data['trunc'] if entryQ: vals = ('pk', 'activity', 'project', 'project__name', 'project__status', 'project__type__label') entries = Entry.objects.date_trunc( trunc, extra_values=vals).filter(entryQ) else: entries = Entry.objects.none() end = end - relativedelta(days=1) date_headers = generate_dates(start, end, by=trunc) context.update({ 'from_date': start, 'to_date': end, 'date_headers': date_headers, 'entries': entries, 'filter_form': form, 'trunc': trunc, }) else: context.update({ 'from_date': None, 'to_date': None, 'date_headers': [], 'entries': Entry.objects.none(), 'filter_form': form, 'trunc': '', }) return context
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "ReportMixin", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "form", "=", "self", ".", "get_form", "(", ")", "if", "form", ".", "is_valid", "(", ")", ":", "data", "=", "form", ".", "cleaned_data", "start", ",", "end", "=", "form", ".", "save", "(", ")", "entryQ", "=", "self", ".", "get_entry_query", "(", "start", ",", "end", ",", "data", ")", "trunc", "=", "data", "[", "'trunc'", "]", "if", "entryQ", ":", "vals", "=", "(", "'pk'", ",", "'activity'", ",", "'project'", ",", "'project__name'", ",", "'project__status'", ",", "'project__type__label'", ")", "entries", "=", "Entry", ".", "objects", ".", "date_trunc", "(", "trunc", ",", "extra_values", "=", "vals", ")", ".", "filter", "(", "entryQ", ")", "else", ":", "entries", "=", "Entry", ".", "objects", ".", "none", "(", ")", "end", "=", "end", "-", "relativedelta", "(", "days", "=", "1", ")", "date_headers", "=", "generate_dates", "(", "start", ",", "end", ",", "by", "=", "trunc", ")", "context", ".", "update", "(", "{", "'from_date'", ":", "start", ",", "'to_date'", ":", "end", ",", "'date_headers'", ":", "date_headers", ",", "'entries'", ":", "entries", ",", "'filter_form'", ":", "form", ",", "'trunc'", ":", "trunc", ",", "}", ")", "else", ":", "context", ".", "update", "(", "{", "'from_date'", ":", "None", ",", "'to_date'", ":", "None", ",", "'date_headers'", ":", "[", "]", ",", "'entries'", ":", "Entry", ".", "objects", ".", "none", "(", ")", ",", "'filter_form'", ":", "form", ",", "'trunc'", ":", "''", ",", "}", ")", "return", "context" ]
Processes form data to get relevant entries & date_headers.
[ "Processes", "form", "data", "to", "get", "relevant", "entries", "&", "date_headers", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L36-L74
train
caktus/django-timepiece
timepiece/reports/views.py
ReportMixin.get_entry_query
def get_entry_query(self, start, end, data): """Builds Entry query from form data.""" # Entry types. incl_billable = data.get('billable', True) incl_nonbillable = data.get('non_billable', True) incl_leave = data.get('paid_leave', True) # If no types are selected, shortcut & return nothing. if not any((incl_billable, incl_nonbillable, incl_leave)): return None # All entries must meet time period requirements. basicQ = Q(end_time__gte=start, end_time__lt=end) # Filter by project for HourlyReport. projects = data.get('projects', None) basicQ &= Q(project__in=projects) if projects else Q() # Filter by user, activity, and project type for BillableReport. if 'users' in data: basicQ &= Q(user__in=data.get('users')) if 'activities' in data: basicQ &= Q(activity__in=data.get('activities')) if 'project_types' in data: basicQ &= Q(project__type__in=data.get('project_types')) # If all types are selected, no further filtering is required. if all((incl_billable, incl_nonbillable, incl_leave)): return basicQ # Filter by whether a project is billable or non-billable. billableQ = None if incl_billable and not incl_nonbillable: billableQ = Q(activity__billable=True, project__type__billable=True) if incl_nonbillable and not incl_billable: billableQ = Q(activity__billable=False) | Q(project__type__billable=False) # Filter by whether the entry is paid leave. leave_ids = utils.get_setting('TIMEPIECE_PAID_LEAVE_PROJECTS').values() leaveQ = Q(project__in=leave_ids) if incl_leave: extraQ = (leaveQ | billableQ) if billableQ else leaveQ else: extraQ = (~leaveQ & billableQ) if billableQ else ~leaveQ return basicQ & extraQ
python
def get_entry_query(self, start, end, data): """Builds Entry query from form data.""" # Entry types. incl_billable = data.get('billable', True) incl_nonbillable = data.get('non_billable', True) incl_leave = data.get('paid_leave', True) # If no types are selected, shortcut & return nothing. if not any((incl_billable, incl_nonbillable, incl_leave)): return None # All entries must meet time period requirements. basicQ = Q(end_time__gte=start, end_time__lt=end) # Filter by project for HourlyReport. projects = data.get('projects', None) basicQ &= Q(project__in=projects) if projects else Q() # Filter by user, activity, and project type for BillableReport. if 'users' in data: basicQ &= Q(user__in=data.get('users')) if 'activities' in data: basicQ &= Q(activity__in=data.get('activities')) if 'project_types' in data: basicQ &= Q(project__type__in=data.get('project_types')) # If all types are selected, no further filtering is required. if all((incl_billable, incl_nonbillable, incl_leave)): return basicQ # Filter by whether a project is billable or non-billable. billableQ = None if incl_billable and not incl_nonbillable: billableQ = Q(activity__billable=True, project__type__billable=True) if incl_nonbillable and not incl_billable: billableQ = Q(activity__billable=False) | Q(project__type__billable=False) # Filter by whether the entry is paid leave. leave_ids = utils.get_setting('TIMEPIECE_PAID_LEAVE_PROJECTS').values() leaveQ = Q(project__in=leave_ids) if incl_leave: extraQ = (leaveQ | billableQ) if billableQ else leaveQ else: extraQ = (~leaveQ & billableQ) if billableQ else ~leaveQ return basicQ & extraQ
[ "def", "get_entry_query", "(", "self", ",", "start", ",", "end", ",", "data", ")", ":", "# Entry types.", "incl_billable", "=", "data", ".", "get", "(", "'billable'", ",", "True", ")", "incl_nonbillable", "=", "data", ".", "get", "(", "'non_billable'", ",", "True", ")", "incl_leave", "=", "data", ".", "get", "(", "'paid_leave'", ",", "True", ")", "# If no types are selected, shortcut & return nothing.", "if", "not", "any", "(", "(", "incl_billable", ",", "incl_nonbillable", ",", "incl_leave", ")", ")", ":", "return", "None", "# All entries must meet time period requirements.", "basicQ", "=", "Q", "(", "end_time__gte", "=", "start", ",", "end_time__lt", "=", "end", ")", "# Filter by project for HourlyReport.", "projects", "=", "data", ".", "get", "(", "'projects'", ",", "None", ")", "basicQ", "&=", "Q", "(", "project__in", "=", "projects", ")", "if", "projects", "else", "Q", "(", ")", "# Filter by user, activity, and project type for BillableReport.", "if", "'users'", "in", "data", ":", "basicQ", "&=", "Q", "(", "user__in", "=", "data", ".", "get", "(", "'users'", ")", ")", "if", "'activities'", "in", "data", ":", "basicQ", "&=", "Q", "(", "activity__in", "=", "data", ".", "get", "(", "'activities'", ")", ")", "if", "'project_types'", "in", "data", ":", "basicQ", "&=", "Q", "(", "project__type__in", "=", "data", ".", "get", "(", "'project_types'", ")", ")", "# If all types are selected, no further filtering is required.", "if", "all", "(", "(", "incl_billable", ",", "incl_nonbillable", ",", "incl_leave", ")", ")", ":", "return", "basicQ", "# Filter by whether a project is billable or non-billable.", "billableQ", "=", "None", "if", "incl_billable", "and", "not", "incl_nonbillable", ":", "billableQ", "=", "Q", "(", "activity__billable", "=", "True", ",", "project__type__billable", "=", "True", ")", "if", "incl_nonbillable", "and", "not", "incl_billable", ":", "billableQ", "=", "Q", "(", "activity__billable", "=", "False", ")", "|", "Q", "(", "project__type__billable", "=", "False", ")", "# Filter by whether the entry is paid leave.", "leave_ids", "=", "utils", ".", "get_setting", "(", "'TIMEPIECE_PAID_LEAVE_PROJECTS'", ")", ".", "values", "(", ")", "leaveQ", "=", "Q", "(", "project__in", "=", "leave_ids", ")", "if", "incl_leave", ":", "extraQ", "=", "(", "leaveQ", "|", "billableQ", ")", "if", "billableQ", "else", "leaveQ", "else", ":", "extraQ", "=", "(", "~", "leaveQ", "&", "billableQ", ")", "if", "billableQ", "else", "~", "leaveQ", "return", "basicQ", "&", "extraQ" ]
Builds Entry query from form data.
[ "Builds", "Entry", "query", "from", "form", "data", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L76-L121
train
caktus/django-timepiece
timepiece/reports/views.py
ReportMixin.get_headers
def get_headers(self, date_headers, from_date, to_date, trunc): """Adjust date headers & get range headers.""" date_headers = list(date_headers) # Earliest date should be no earlier than from_date. if date_headers and date_headers[0] < from_date: date_headers[0] = from_date # When organizing by week or month, create a list of the range for # each date header. if date_headers and trunc != 'day': count = len(date_headers) range_headers = [0] * count for i in range(count - 1): range_headers[i] = ( date_headers[i], date_headers[i + 1] - relativedelta(days=1)) range_headers[count - 1] = (date_headers[count - 1], to_date) else: range_headers = date_headers return date_headers, range_headers
python
def get_headers(self, date_headers, from_date, to_date, trunc): """Adjust date headers & get range headers.""" date_headers = list(date_headers) # Earliest date should be no earlier than from_date. if date_headers and date_headers[0] < from_date: date_headers[0] = from_date # When organizing by week or month, create a list of the range for # each date header. if date_headers and trunc != 'day': count = len(date_headers) range_headers = [0] * count for i in range(count - 1): range_headers[i] = ( date_headers[i], date_headers[i + 1] - relativedelta(days=1)) range_headers[count - 1] = (date_headers[count - 1], to_date) else: range_headers = date_headers return date_headers, range_headers
[ "def", "get_headers", "(", "self", ",", "date_headers", ",", "from_date", ",", "to_date", ",", "trunc", ")", ":", "date_headers", "=", "list", "(", "date_headers", ")", "# Earliest date should be no earlier than from_date.", "if", "date_headers", "and", "date_headers", "[", "0", "]", "<", "from_date", ":", "date_headers", "[", "0", "]", "=", "from_date", "# When organizing by week or month, create a list of the range for", "# each date header.", "if", "date_headers", "and", "trunc", "!=", "'day'", ":", "count", "=", "len", "(", "date_headers", ")", "range_headers", "=", "[", "0", "]", "*", "count", "for", "i", "in", "range", "(", "count", "-", "1", ")", ":", "range_headers", "[", "i", "]", "=", "(", "date_headers", "[", "i", "]", ",", "date_headers", "[", "i", "+", "1", "]", "-", "relativedelta", "(", "days", "=", "1", ")", ")", "range_headers", "[", "count", "-", "1", "]", "=", "(", "date_headers", "[", "count", "-", "1", "]", ",", "to_date", ")", "else", ":", "range_headers", "=", "date_headers", "return", "date_headers", ",", "range_headers" ]
Adjust date headers & get range headers.
[ "Adjust", "date", "headers", "&", "get", "range", "headers", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L123-L142
train
caktus/django-timepiece
timepiece/reports/views.py
ReportMixin.get_previous_month
def get_previous_month(self): """Returns date range for the previous full month.""" end = utils.get_month_start() - relativedelta(days=1) end = utils.to_datetime(end) start = utils.get_month_start(end) return start, end
python
def get_previous_month(self): """Returns date range for the previous full month.""" end = utils.get_month_start() - relativedelta(days=1) end = utils.to_datetime(end) start = utils.get_month_start(end) return start, end
[ "def", "get_previous_month", "(", "self", ")", ":", "end", "=", "utils", ".", "get_month_start", "(", ")", "-", "relativedelta", "(", "days", "=", "1", ")", "end", "=", "utils", ".", "to_datetime", "(", "end", ")", "start", "=", "utils", ".", "get_month_start", "(", "end", ")", "return", "start", ",", "end" ]
Returns date range for the previous full month.
[ "Returns", "date", "range", "for", "the", "previous", "full", "month", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L144-L149
train
caktus/django-timepiece
timepiece/reports/views.py
HourlyReport.convert_context_to_csv
def convert_context_to_csv(self, context): """Convert the context dictionary into a CSV file.""" content = [] date_headers = context['date_headers'] headers = ['Name'] headers.extend([date.strftime('%m/%d/%Y') for date in date_headers]) headers.append('Total') content.append(headers) summaries = context['summaries'] summary = summaries.get(self.export, []) for rows, totals in summary: for name, user_id, hours in rows: data = [name] data.extend(hours) content.append(data) total = ['Totals'] total.extend(totals) content.append(total) return content
python
def convert_context_to_csv(self, context): """Convert the context dictionary into a CSV file.""" content = [] date_headers = context['date_headers'] headers = ['Name'] headers.extend([date.strftime('%m/%d/%Y') for date in date_headers]) headers.append('Total') content.append(headers) summaries = context['summaries'] summary = summaries.get(self.export, []) for rows, totals in summary: for name, user_id, hours in rows: data = [name] data.extend(hours) content.append(data) total = ['Totals'] total.extend(totals) content.append(total) return content
[ "def", "convert_context_to_csv", "(", "self", ",", "context", ")", ":", "content", "=", "[", "]", "date_headers", "=", "context", "[", "'date_headers'", "]", "headers", "=", "[", "'Name'", "]", "headers", ".", "extend", "(", "[", "date", ".", "strftime", "(", "'%m/%d/%Y'", ")", "for", "date", "in", "date_headers", "]", ")", "headers", ".", "append", "(", "'Total'", ")", "content", ".", "append", "(", "headers", ")", "summaries", "=", "context", "[", "'summaries'", "]", "summary", "=", "summaries", ".", "get", "(", "self", ".", "export", ",", "[", "]", ")", "for", "rows", ",", "totals", "in", "summary", ":", "for", "name", ",", "user_id", ",", "hours", "in", "rows", ":", "data", "=", "[", "name", "]", "data", ".", "extend", "(", "hours", ")", "content", ".", "append", "(", "data", ")", "total", "=", "[", "'Totals'", "]", "total", ".", "extend", "(", "totals", ")", "content", ".", "append", "(", "total", ")", "return", "content" ]
Convert the context dictionary into a CSV file.
[ "Convert", "the", "context", "dictionary", "into", "a", "CSV", "file", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L155-L177
train
caktus/django-timepiece
timepiece/reports/views.py
HourlyReport.defaults
def defaults(self): """Default filter form data when no GET data is provided.""" # Set default date span to previous week. (start, end) = get_week_window(timezone.now() - relativedelta(days=7)) return { 'from_date': start, 'to_date': end, 'billable': True, 'non_billable': False, 'paid_leave': False, 'trunc': 'day', 'projects': [], }
python
def defaults(self): """Default filter form data when no GET data is provided.""" # Set default date span to previous week. (start, end) = get_week_window(timezone.now() - relativedelta(days=7)) return { 'from_date': start, 'to_date': end, 'billable': True, 'non_billable': False, 'paid_leave': False, 'trunc': 'day', 'projects': [], }
[ "def", "defaults", "(", "self", ")", ":", "# Set default date span to previous week.", "(", "start", ",", "end", ")", "=", "get_week_window", "(", "timezone", ".", "now", "(", ")", "-", "relativedelta", "(", "days", "=", "7", ")", ")", "return", "{", "'from_date'", ":", "start", ",", "'to_date'", ":", "end", ",", "'billable'", ":", "True", ",", "'non_billable'", ":", "False", ",", "'paid_leave'", ":", "False", ",", "'trunc'", ":", "'day'", ",", "'projects'", ":", "[", "]", ",", "}" ]
Default filter form data when no GET data is provided.
[ "Default", "filter", "form", "data", "when", "no", "GET", "data", "is", "provided", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L180-L192
train
caktus/django-timepiece
timepiece/reports/views.py
BillableHours.get_hours_data
def get_hours_data(self, entries, date_headers): """Sum billable and non-billable hours across all users.""" project_totals = get_project_totals( entries, date_headers, total_column=False) if entries else [] data_map = {} for rows, totals in project_totals: for user, user_id, periods in rows: for period in periods: day = period['day'] if day not in data_map: data_map[day] = {'billable': 0, 'nonbillable': 0} data_map[day]['billable'] += period['billable'] data_map[day]['nonbillable'] += period['nonbillable'] return data_map
python
def get_hours_data(self, entries, date_headers): """Sum billable and non-billable hours across all users.""" project_totals = get_project_totals( entries, date_headers, total_column=False) if entries else [] data_map = {} for rows, totals in project_totals: for user, user_id, periods in rows: for period in periods: day = period['day'] if day not in data_map: data_map[day] = {'billable': 0, 'nonbillable': 0} data_map[day]['billable'] += period['billable'] data_map[day]['nonbillable'] += period['nonbillable'] return data_map
[ "def", "get_hours_data", "(", "self", ",", "entries", ",", "date_headers", ")", ":", "project_totals", "=", "get_project_totals", "(", "entries", ",", "date_headers", ",", "total_column", "=", "False", ")", "if", "entries", "else", "[", "]", "data_map", "=", "{", "}", "for", "rows", ",", "totals", "in", "project_totals", ":", "for", "user", ",", "user_id", ",", "periods", "in", "rows", ":", "for", "period", "in", "periods", ":", "day", "=", "period", "[", "'day'", "]", "if", "day", "not", "in", "data_map", ":", "data_map", "[", "day", "]", "=", "{", "'billable'", ":", "0", ",", "'nonbillable'", ":", "0", "}", "data_map", "[", "day", "]", "[", "'billable'", "]", "+=", "period", "[", "'billable'", "]", "data_map", "[", "day", "]", "[", "'nonbillable'", "]", "+=", "period", "[", "'nonbillable'", "]", "return", "data_map" ]
Sum billable and non-billable hours across all users.
[ "Sum", "billable", "and", "non", "-", "billable", "hours", "across", "all", "users", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L314-L329
train
caktus/django-timepiece
timepiece/templatetags/timepiece_tags.py
add_parameters
def add_parameters(url, parameters): """ Appends URL-encoded parameters to the base URL. It appends after '&' if '?' is found in the URL; otherwise it appends using '?'. Keep in mind that this tag does not take into account the value of existing params; it is therefore possible to add another value for a pre-existing parameter. For example:: {% url 'this_view' as current_url %} {% with complete_url=current_url|add_parameters:request.GET %} The <a href="{% url 'other' %}?next={{ complete_url|urlencode }}"> other page</a> will redirect back to the current page (including any GET parameters). {% endwith %} """ if parameters: sep = '&' if '?' in url else '?' return '{0}{1}{2}'.format(url, sep, urlencode(parameters)) return url
python
def add_parameters(url, parameters): """ Appends URL-encoded parameters to the base URL. It appends after '&' if '?' is found in the URL; otherwise it appends using '?'. Keep in mind that this tag does not take into account the value of existing params; it is therefore possible to add another value for a pre-existing parameter. For example:: {% url 'this_view' as current_url %} {% with complete_url=current_url|add_parameters:request.GET %} The <a href="{% url 'other' %}?next={{ complete_url|urlencode }}"> other page</a> will redirect back to the current page (including any GET parameters). {% endwith %} """ if parameters: sep = '&' if '?' in url else '?' return '{0}{1}{2}'.format(url, sep, urlencode(parameters)) return url
[ "def", "add_parameters", "(", "url", ",", "parameters", ")", ":", "if", "parameters", ":", "sep", "=", "'&'", "if", "'?'", "in", "url", "else", "'?'", "return", "'{0}{1}{2}'", ".", "format", "(", "url", ",", "sep", ",", "urlencode", "(", "parameters", ")", ")", "return", "url" ]
Appends URL-encoded parameters to the base URL. It appends after '&' if '?' is found in the URL; otherwise it appends using '?'. Keep in mind that this tag does not take into account the value of existing params; it is therefore possible to add another value for a pre-existing parameter. For example:: {% url 'this_view' as current_url %} {% with complete_url=current_url|add_parameters:request.GET %} The <a href="{% url 'other' %}?next={{ complete_url|urlencode }}"> other page</a> will redirect back to the current page (including any GET parameters). {% endwith %}
[ "Appends", "URL", "-", "encoded", "parameters", "to", "the", "base", "URL", ".", "It", "appends", "after", "&", "if", "?", "is", "found", "in", "the", "URL", ";", "otherwise", "it", "appends", "using", "?", ".", "Keep", "in", "mind", "that", "this", "tag", "does", "not", "take", "into", "account", "the", "value", "of", "existing", "params", ";", "it", "is", "therefore", "possible", "to", "add", "another", "value", "for", "a", "pre", "-", "existing", "parameter", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L22-L41
train
caktus/django-timepiece
timepiece/templatetags/timepiece_tags.py
get_max_hours
def get_max_hours(context): """Return the largest number of hours worked or assigned on any project.""" progress = context['project_progress'] return max([0] + [max(p['worked'], p['assigned']) for p in progress])
python
def get_max_hours(context): """Return the largest number of hours worked or assigned on any project.""" progress = context['project_progress'] return max([0] + [max(p['worked'], p['assigned']) for p in progress])
[ "def", "get_max_hours", "(", "context", ")", ":", "progress", "=", "context", "[", "'project_progress'", "]", "return", "max", "(", "[", "0", "]", "+", "[", "max", "(", "p", "[", "'worked'", "]", ",", "p", "[", "'assigned'", "]", ")", "for", "p", "in", "progress", "]", ")" ]
Return the largest number of hours worked or assigned on any project.
[ "Return", "the", "largest", "number", "of", "hours", "worked", "or", "assigned", "on", "any", "project", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L109-L112
train
caktus/django-timepiece
timepiece/templatetags/timepiece_tags.py
get_uninvoiced_hours
def get_uninvoiced_hours(entries, billable=None): """Given an iterable of entries, return the total hours that have not been invoiced. If billable is passed as 'billable' or 'nonbillable', limit to the corresponding entries. """ statuses = ('invoiced', 'not-invoiced') if billable is not None: billable = (billable.lower() == u'billable') entries = [e for e in entries if e.activity.billable == billable] hours = sum([e.hours for e in entries if e.status not in statuses]) return '{0:.2f}'.format(hours)
python
def get_uninvoiced_hours(entries, billable=None): """Given an iterable of entries, return the total hours that have not been invoiced. If billable is passed as 'billable' or 'nonbillable', limit to the corresponding entries. """ statuses = ('invoiced', 'not-invoiced') if billable is not None: billable = (billable.lower() == u'billable') entries = [e for e in entries if e.activity.billable == billable] hours = sum([e.hours for e in entries if e.status not in statuses]) return '{0:.2f}'.format(hours)
[ "def", "get_uninvoiced_hours", "(", "entries", ",", "billable", "=", "None", ")", ":", "statuses", "=", "(", "'invoiced'", ",", "'not-invoiced'", ")", "if", "billable", "is", "not", "None", ":", "billable", "=", "(", "billable", ".", "lower", "(", ")", "==", "u'billable'", ")", "entries", "=", "[", "e", "for", "e", "in", "entries", "if", "e", ".", "activity", ".", "billable", "==", "billable", "]", "hours", "=", "sum", "(", "[", "e", ".", "hours", "for", "e", "in", "entries", "if", "e", ".", "status", "not", "in", "statuses", "]", ")", "return", "'{0:.2f}'", ".", "format", "(", "hours", ")" ]
Given an iterable of entries, return the total hours that have not been invoiced. If billable is passed as 'billable' or 'nonbillable', limit to the corresponding entries.
[ "Given", "an", "iterable", "of", "entries", "return", "the", "total", "hours", "that", "have", "not", "been", "invoiced", ".", "If", "billable", "is", "passed", "as", "billable", "or", "nonbillable", "limit", "to", "the", "corresponding", "entries", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L116-L126
train
caktus/django-timepiece
timepiece/templatetags/timepiece_tags.py
humanize_hours
def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): """Given time in hours, return a string representing the time.""" seconds = int(float(total_hours) * 3600) return humanize_seconds(seconds, frmt, negative_frmt)
python
def humanize_hours(total_hours, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): """Given time in hours, return a string representing the time.""" seconds = int(float(total_hours) * 3600) return humanize_seconds(seconds, frmt, negative_frmt)
[ "def", "humanize_hours", "(", "total_hours", ",", "frmt", "=", "'{hours:02d}:{minutes:02d}:{seconds:02d}'", ",", "negative_frmt", "=", "None", ")", ":", "seconds", "=", "int", "(", "float", "(", "total_hours", ")", "*", "3600", ")", "return", "humanize_seconds", "(", "seconds", ",", "frmt", ",", "negative_frmt", ")" ]
Given time in hours, return a string representing the time.
[ "Given", "time", "in", "hours", "return", "a", "string", "representing", "the", "time", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L130-L134
train
caktus/django-timepiece
timepiece/templatetags/timepiece_tags.py
_timesheet_url
def _timesheet_url(url_name, pk, date=None): """Utility to create a time sheet URL with optional date parameters.""" url = reverse(url_name, args=(pk,)) if date: params = {'month': date.month, 'year': date.year} return '?'.join((url, urlencode(params))) return url
python
def _timesheet_url(url_name, pk, date=None): """Utility to create a time sheet URL with optional date parameters.""" url = reverse(url_name, args=(pk,)) if date: params = {'month': date.month, 'year': date.year} return '?'.join((url, urlencode(params))) return url
[ "def", "_timesheet_url", "(", "url_name", ",", "pk", ",", "date", "=", "None", ")", ":", "url", "=", "reverse", "(", "url_name", ",", "args", "=", "(", "pk", ",", ")", ")", "if", "date", ":", "params", "=", "{", "'month'", ":", "date", ".", "month", ",", "'year'", ":", "date", ".", "year", "}", "return", "'?'", ".", "join", "(", "(", "url", ",", "urlencode", "(", "params", ")", ")", ")", "return", "url" ]
Utility to create a time sheet URL with optional date parameters.
[ "Utility", "to", "create", "a", "time", "sheet", "URL", "with", "optional", "date", "parameters", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L222-L228
train
caktus/django-timepiece
timepiece/crm/views.py
reject_user_timesheet
def reject_user_timesheet(request, user_id): """ This allows admins to reject all entries, instead of just one """ form = YearMonthForm(request.GET or request.POST) user = User.objects.get(pk=user_id) if form.is_valid(): from_date, to_date = form.save() entries = Entry.no_join.filter( status=Entry.VERIFIED, user=user, start_time__gte=from_date, end_time__lte=to_date) if request.POST.get('yes'): if entries.exists(): count = entries.count() Entry.no_join.filter(pk__in=entries).update(status=Entry.UNVERIFIED) msg = 'You have rejected %d previously verified entries.' \ % count else: msg = 'There are no verified entries to reject.' messages.info(request, msg) else: return render(request, 'timepiece/user/timesheet/reject.html', { 'date': from_date, 'timesheet_user': user }) else: msg = 'You must provide a month and year for entries to be rejected.' messages.error(request, msg) url = reverse('view_user_timesheet', args=(user_id,)) return HttpResponseRedirect(url)
python
def reject_user_timesheet(request, user_id): """ This allows admins to reject all entries, instead of just one """ form = YearMonthForm(request.GET or request.POST) user = User.objects.get(pk=user_id) if form.is_valid(): from_date, to_date = form.save() entries = Entry.no_join.filter( status=Entry.VERIFIED, user=user, start_time__gte=from_date, end_time__lte=to_date) if request.POST.get('yes'): if entries.exists(): count = entries.count() Entry.no_join.filter(pk__in=entries).update(status=Entry.UNVERIFIED) msg = 'You have rejected %d previously verified entries.' \ % count else: msg = 'There are no verified entries to reject.' messages.info(request, msg) else: return render(request, 'timepiece/user/timesheet/reject.html', { 'date': from_date, 'timesheet_user': user }) else: msg = 'You must provide a month and year for entries to be rejected.' messages.error(request, msg) url = reverse('view_user_timesheet', args=(user_id,)) return HttpResponseRedirect(url)
[ "def", "reject_user_timesheet", "(", "request", ",", "user_id", ")", ":", "form", "=", "YearMonthForm", "(", "request", ".", "GET", "or", "request", ".", "POST", ")", "user", "=", "User", ".", "objects", ".", "get", "(", "pk", "=", "user_id", ")", "if", "form", ".", "is_valid", "(", ")", ":", "from_date", ",", "to_date", "=", "form", ".", "save", "(", ")", "entries", "=", "Entry", ".", "no_join", ".", "filter", "(", "status", "=", "Entry", ".", "VERIFIED", ",", "user", "=", "user", ",", "start_time__gte", "=", "from_date", ",", "end_time__lte", "=", "to_date", ")", "if", "request", ".", "POST", ".", "get", "(", "'yes'", ")", ":", "if", "entries", ".", "exists", "(", ")", ":", "count", "=", "entries", ".", "count", "(", ")", "Entry", ".", "no_join", ".", "filter", "(", "pk__in", "=", "entries", ")", ".", "update", "(", "status", "=", "Entry", ".", "UNVERIFIED", ")", "msg", "=", "'You have rejected %d previously verified entries.'", "%", "count", "else", ":", "msg", "=", "'There are no verified entries to reject.'", "messages", ".", "info", "(", "request", ",", "msg", ")", "else", ":", "return", "render", "(", "request", ",", "'timepiece/user/timesheet/reject.html'", ",", "{", "'date'", ":", "from_date", ",", "'timesheet_user'", ":", "user", "}", ")", "else", ":", "msg", "=", "'You must provide a month and year for entries to be rejected.'", "messages", ".", "error", "(", "request", ",", "msg", ")", "url", "=", "reverse", "(", "'view_user_timesheet'", ",", "args", "=", "(", "user_id", ",", ")", ")", "return", "HttpResponseRedirect", "(", "url", ")" ]
This allows admins to reject all entries, instead of just one
[ "This", "allows", "admins", "to", "reject", "all", "entries", "instead", "of", "just", "one" ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/crm/views.py#L47-L77
train
caktus/django-timepiece
setup.py
_is_requirement
def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not (line.startswith("-r") or line.startswith("#"))
python
def _is_requirement(line): """Returns whether the line is a valid package requirement.""" line = line.strip() return line and not (line.startswith("-r") or line.startswith("#"))
[ "def", "_is_requirement", "(", "line", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "return", "line", "and", "not", "(", "line", ".", "startswith", "(", "\"-r\"", ")", "or", "line", ".", "startswith", "(", "\"#\"", ")", ")" ]
Returns whether the line is a valid package requirement.
[ "Returns", "whether", "the", "line", "is", "a", "valid", "package", "requirement", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/setup.py#L4-L7
train
caktus/django-timepiece
timepiece/utils/search.py
SearchMixin.render_to_response
def render_to_response(self, context): """ When the user makes a search and there is only one result, redirect to the result's detail page rather than rendering the list. """ if self.redirect_if_one_result: if self.object_list.count() == 1 and self.form.is_bound: return redirect(self.object_list.get().get_absolute_url()) return super(SearchMixin, self).render_to_response(context)
python
def render_to_response(self, context): """ When the user makes a search and there is only one result, redirect to the result's detail page rather than rendering the list. """ if self.redirect_if_one_result: if self.object_list.count() == 1 and self.form.is_bound: return redirect(self.object_list.get().get_absolute_url()) return super(SearchMixin, self).render_to_response(context)
[ "def", "render_to_response", "(", "self", ",", "context", ")", ":", "if", "self", ".", "redirect_if_one_result", ":", "if", "self", ".", "object_list", ".", "count", "(", ")", "==", "1", "and", "self", ".", "form", ".", "is_bound", ":", "return", "redirect", "(", "self", ".", "object_list", ".", "get", "(", ")", ".", "get_absolute_url", "(", ")", ")", "return", "super", "(", "SearchMixin", ",", "self", ")", ".", "render_to_response", "(", "context", ")" ]
When the user makes a search and there is only one result, redirect to the result's detail page rather than rendering the list.
[ "When", "the", "user", "makes", "a", "search", "and", "there", "is", "only", "one", "result", "redirect", "to", "the", "result", "s", "detail", "page", "rather", "than", "rendering", "the", "list", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/search.py#L61-L69
train
caktus/django-timepiece
timepiece/entries/forms.py
ClockInForm.clean_start_time
def clean_start_time(self): """ Make sure that the start time doesn't come before the active entry """ start = self.cleaned_data.get('start_time') if not start: return start active_entries = self.user.timepiece_entries.filter( start_time__gte=start, end_time__isnull=True) for entry in active_entries: output = ('The start time is on or before the current entry: ' '%s - %s starting at %s' % (entry.project, entry.activity, entry.start_time.strftime('%H:%M:%S'))) raise forms.ValidationError(output) return start
python
def clean_start_time(self): """ Make sure that the start time doesn't come before the active entry """ start = self.cleaned_data.get('start_time') if not start: return start active_entries = self.user.timepiece_entries.filter( start_time__gte=start, end_time__isnull=True) for entry in active_entries: output = ('The start time is on or before the current entry: ' '%s - %s starting at %s' % (entry.project, entry.activity, entry.start_time.strftime('%H:%M:%S'))) raise forms.ValidationError(output) return start
[ "def", "clean_start_time", "(", "self", ")", ":", "start", "=", "self", ".", "cleaned_data", ".", "get", "(", "'start_time'", ")", "if", "not", "start", ":", "return", "start", "active_entries", "=", "self", ".", "user", ".", "timepiece_entries", ".", "filter", "(", "start_time__gte", "=", "start", ",", "end_time__isnull", "=", "True", ")", "for", "entry", "in", "active_entries", ":", "output", "=", "(", "'The start time is on or before the current entry: '", "'%s - %s starting at %s'", "%", "(", "entry", ".", "project", ",", "entry", ".", "activity", ",", "entry", ".", "start_time", ".", "strftime", "(", "'%H:%M:%S'", ")", ")", ")", "raise", "forms", ".", "ValidationError", "(", "output", ")", "return", "start" ]
Make sure that the start time doesn't come before the active entry
[ "Make", "sure", "that", "the", "start", "time", "doesn", "t", "come", "before", "the", "active", "entry" ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/forms.py#L64-L78
train
caktus/django-timepiece
timepiece/entries/forms.py
AddUpdateEntryForm.clean
def clean(self): """ If we're not editing the active entry, ensure that this entry doesn't conflict with or come after the active entry. """ active = utils.get_active_entry(self.user) start_time = self.cleaned_data.get('start_time', None) end_time = self.cleaned_data.get('end_time', None) if active and active.pk != self.instance.pk: if (start_time and start_time > active.start_time) or \ (end_time and end_time > active.start_time): raise forms.ValidationError( 'The start time or end time conflict with the active ' 'entry: {activity} on {project} starting at ' '{start_time}.'.format( project=active.project, activity=active.activity, start_time=active.start_time.strftime('%H:%M:%S'), )) month_start = utils.get_month_start(start_time) next_month = month_start + relativedelta(months=1) entries = self.instance.user.timepiece_entries.filter( Q(status=Entry.APPROVED) | Q(status=Entry.INVOICED), start_time__gte=month_start, end_time__lt=next_month ) entry = self.instance if not self.acting_user.is_superuser: if (entries.exists() and not entry.id or entry.id and entry.status == Entry.INVOICED): message = 'You cannot add/edit entries after a timesheet has been ' \ 'approved or invoiced. Please correct the start and end times.' raise forms.ValidationError(message) return self.cleaned_data
python
def clean(self): """ If we're not editing the active entry, ensure that this entry doesn't conflict with or come after the active entry. """ active = utils.get_active_entry(self.user) start_time = self.cleaned_data.get('start_time', None) end_time = self.cleaned_data.get('end_time', None) if active and active.pk != self.instance.pk: if (start_time and start_time > active.start_time) or \ (end_time and end_time > active.start_time): raise forms.ValidationError( 'The start time or end time conflict with the active ' 'entry: {activity} on {project} starting at ' '{start_time}.'.format( project=active.project, activity=active.activity, start_time=active.start_time.strftime('%H:%M:%S'), )) month_start = utils.get_month_start(start_time) next_month = month_start + relativedelta(months=1) entries = self.instance.user.timepiece_entries.filter( Q(status=Entry.APPROVED) | Q(status=Entry.INVOICED), start_time__gte=month_start, end_time__lt=next_month ) entry = self.instance if not self.acting_user.is_superuser: if (entries.exists() and not entry.id or entry.id and entry.status == Entry.INVOICED): message = 'You cannot add/edit entries after a timesheet has been ' \ 'approved or invoiced. Please correct the start and end times.' raise forms.ValidationError(message) return self.cleaned_data
[ "def", "clean", "(", "self", ")", ":", "active", "=", "utils", ".", "get_active_entry", "(", "self", ".", "user", ")", "start_time", "=", "self", ".", "cleaned_data", ".", "get", "(", "'start_time'", ",", "None", ")", "end_time", "=", "self", ".", "cleaned_data", ".", "get", "(", "'end_time'", ",", "None", ")", "if", "active", "and", "active", ".", "pk", "!=", "self", ".", "instance", ".", "pk", ":", "if", "(", "start_time", "and", "start_time", ">", "active", ".", "start_time", ")", "or", "(", "end_time", "and", "end_time", ">", "active", ".", "start_time", ")", ":", "raise", "forms", ".", "ValidationError", "(", "'The start time or end time conflict with the active '", "'entry: {activity} on {project} starting at '", "'{start_time}.'", ".", "format", "(", "project", "=", "active", ".", "project", ",", "activity", "=", "active", ".", "activity", ",", "start_time", "=", "active", ".", "start_time", ".", "strftime", "(", "'%H:%M:%S'", ")", ",", ")", ")", "month_start", "=", "utils", ".", "get_month_start", "(", "start_time", ")", "next_month", "=", "month_start", "+", "relativedelta", "(", "months", "=", "1", ")", "entries", "=", "self", ".", "instance", ".", "user", ".", "timepiece_entries", ".", "filter", "(", "Q", "(", "status", "=", "Entry", ".", "APPROVED", ")", "|", "Q", "(", "status", "=", "Entry", ".", "INVOICED", ")", ",", "start_time__gte", "=", "month_start", ",", "end_time__lt", "=", "next_month", ")", "entry", "=", "self", ".", "instance", "if", "not", "self", ".", "acting_user", ".", "is_superuser", ":", "if", "(", "entries", ".", "exists", "(", ")", "and", "not", "entry", ".", "id", "or", "entry", ".", "id", "and", "entry", ".", "status", "==", "Entry", ".", "INVOICED", ")", ":", "message", "=", "'You cannot add/edit entries after a timesheet has been '", "'approved or invoiced. Please correct the start and end times.'", "raise", "forms", ".", "ValidationError", "(", "message", ")", "return", "self", ".", "cleaned_data" ]
If we're not editing the active entry, ensure that this entry doesn't conflict with or come after the active entry.
[ "If", "we", "re", "not", "editing", "the", "active", "entry", "ensure", "that", "this", "entry", "doesn", "t", "conflict", "with", "or", "come", "after", "the", "active", "entry", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/forms.py#L145-L181
train
caktus/django-timepiece
timepiece/entries/views.py
clock_in
def clock_in(request): """For clocking the user into a project.""" user = request.user # Lock the active entry for the duration of this transaction, to prevent # creating multiple active entries. active_entry = utils.get_active_entry(user, select_for_update=True) initial = dict([(k, v) for k, v in request.GET.items()]) data = request.POST or None form = ClockInForm(data, initial=initial, user=user, active=active_entry) if form.is_valid(): entry = form.save() message = 'You have clocked into {0} on {1}.'.format( entry.activity.name, entry.project) messages.info(request, message) return HttpResponseRedirect(reverse('dashboard')) return render(request, 'timepiece/entry/clock_in.html', { 'form': form, 'active': active_entry, })
python
def clock_in(request): """For clocking the user into a project.""" user = request.user # Lock the active entry for the duration of this transaction, to prevent # creating multiple active entries. active_entry = utils.get_active_entry(user, select_for_update=True) initial = dict([(k, v) for k, v in request.GET.items()]) data = request.POST or None form = ClockInForm(data, initial=initial, user=user, active=active_entry) if form.is_valid(): entry = form.save() message = 'You have clocked into {0} on {1}.'.format( entry.activity.name, entry.project) messages.info(request, message) return HttpResponseRedirect(reverse('dashboard')) return render(request, 'timepiece/entry/clock_in.html', { 'form': form, 'active': active_entry, })
[ "def", "clock_in", "(", "request", ")", ":", "user", "=", "request", ".", "user", "# Lock the active entry for the duration of this transaction, to prevent", "# creating multiple active entries.", "active_entry", "=", "utils", ".", "get_active_entry", "(", "user", ",", "select_for_update", "=", "True", ")", "initial", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "request", ".", "GET", ".", "items", "(", ")", "]", ")", "data", "=", "request", ".", "POST", "or", "None", "form", "=", "ClockInForm", "(", "data", ",", "initial", "=", "initial", ",", "user", "=", "user", ",", "active", "=", "active_entry", ")", "if", "form", ".", "is_valid", "(", ")", ":", "entry", "=", "form", ".", "save", "(", ")", "message", "=", "'You have clocked into {0} on {1}.'", ".", "format", "(", "entry", ".", "activity", ".", "name", ",", "entry", ".", "project", ")", "messages", ".", "info", "(", "request", ",", "message", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'dashboard'", ")", ")", "return", "render", "(", "request", ",", "'timepiece/entry/clock_in.html'", ",", "{", "'form'", ":", "form", ",", "'active'", ":", "active_entry", ",", "}", ")" ]
For clocking the user into a project.
[ "For", "clocking", "the", "user", "into", "a", "project", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L139-L159
train
caktus/django-timepiece
timepiece/entries/views.py
toggle_pause
def toggle_pause(request): """Allow the user to pause and unpause the active entry.""" entry = utils.get_active_entry(request.user) if not entry: raise Http404 # toggle the paused state entry.toggle_paused() entry.save() # create a message that can be displayed to the user action = 'paused' if entry.is_paused else 'resumed' message = 'Your entry, {0} on {1}, has been {2}.'.format( entry.activity.name, entry.project, action) messages.info(request, message) # redirect to the log entry list return HttpResponseRedirect(reverse('dashboard'))
python
def toggle_pause(request): """Allow the user to pause and unpause the active entry.""" entry = utils.get_active_entry(request.user) if not entry: raise Http404 # toggle the paused state entry.toggle_paused() entry.save() # create a message that can be displayed to the user action = 'paused' if entry.is_paused else 'resumed' message = 'Your entry, {0} on {1}, has been {2}.'.format( entry.activity.name, entry.project, action) messages.info(request, message) # redirect to the log entry list return HttpResponseRedirect(reverse('dashboard'))
[ "def", "toggle_pause", "(", "request", ")", ":", "entry", "=", "utils", ".", "get_active_entry", "(", "request", ".", "user", ")", "if", "not", "entry", ":", "raise", "Http404", "# toggle the paused state", "entry", ".", "toggle_paused", "(", ")", "entry", ".", "save", "(", ")", "# create a message that can be displayed to the user", "action", "=", "'paused'", "if", "entry", ".", "is_paused", "else", "'resumed'", "message", "=", "'Your entry, {0} on {1}, has been {2}.'", ".", "format", "(", "entry", ".", "activity", ".", "name", ",", "entry", ".", "project", ",", "action", ")", "messages", ".", "info", "(", "request", ",", "message", ")", "# redirect to the log entry list", "return", "HttpResponseRedirect", "(", "reverse", "(", "'dashboard'", ")", ")" ]
Allow the user to pause and unpause the active entry.
[ "Allow", "the", "user", "to", "pause", "and", "unpause", "the", "active", "entry", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L189-L206
train
caktus/django-timepiece
timepiece/entries/views.py
reject_entry
def reject_entry(request, entry_id): """ Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix. """ return_url = request.GET.get('next', reverse('dashboard')) try: entry = Entry.no_join.get(pk=entry_id) except: message = 'No such log entry.' messages.error(request, message) return redirect(return_url) if entry.status == Entry.UNVERIFIED or entry.status == Entry.INVOICED: msg_text = 'This entry is unverified or is already invoiced.' messages.error(request, msg_text) return redirect(return_url) if request.POST.get('Yes'): entry.status = Entry.UNVERIFIED entry.save() msg_text = 'The entry\'s status was set to unverified.' messages.info(request, msg_text) return redirect(return_url) return render(request, 'timepiece/entry/reject.html', { 'entry': entry, 'next': request.GET.get('next'), })
python
def reject_entry(request, entry_id): """ Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix. """ return_url = request.GET.get('next', reverse('dashboard')) try: entry = Entry.no_join.get(pk=entry_id) except: message = 'No such log entry.' messages.error(request, message) return redirect(return_url) if entry.status == Entry.UNVERIFIED or entry.status == Entry.INVOICED: msg_text = 'This entry is unverified or is already invoiced.' messages.error(request, msg_text) return redirect(return_url) if request.POST.get('Yes'): entry.status = Entry.UNVERIFIED entry.save() msg_text = 'The entry\'s status was set to unverified.' messages.info(request, msg_text) return redirect(return_url) return render(request, 'timepiece/entry/reject.html', { 'entry': entry, 'next': request.GET.get('next'), })
[ "def", "reject_entry", "(", "request", ",", "entry_id", ")", ":", "return_url", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "reverse", "(", "'dashboard'", ")", ")", "try", ":", "entry", "=", "Entry", ".", "no_join", ".", "get", "(", "pk", "=", "entry_id", ")", "except", ":", "message", "=", "'No such log entry.'", "messages", ".", "error", "(", "request", ",", "message", ")", "return", "redirect", "(", "return_url", ")", "if", "entry", ".", "status", "==", "Entry", ".", "UNVERIFIED", "or", "entry", ".", "status", "==", "Entry", ".", "INVOICED", ":", "msg_text", "=", "'This entry is unverified or is already invoiced.'", "messages", ".", "error", "(", "request", ",", "msg_text", ")", "return", "redirect", "(", "return_url", ")", "if", "request", ".", "POST", ".", "get", "(", "'Yes'", ")", ":", "entry", ".", "status", "=", "Entry", ".", "UNVERIFIED", "entry", ".", "save", "(", ")", "msg_text", "=", "'The entry\\'s status was set to unverified.'", "messages", ".", "info", "(", "request", ",", "msg_text", ")", "return", "redirect", "(", "return_url", ")", "return", "render", "(", "request", ",", "'timepiece/entry/reject.html'", ",", "{", "'entry'", ":", "entry", ",", "'next'", ":", "request", ".", "GET", ".", "get", "(", "'next'", ")", ",", "}", ")" ]
Admins can reject an entry that has been verified or approved but not invoiced to set its status to 'unverified' for the user to fix.
[ "Admins", "can", "reject", "an", "entry", "that", "has", "been", "verified", "or", "approved", "but", "not", "invoiced", "to", "set", "its", "status", "to", "unverified", "for", "the", "user", "to", "fix", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L255-L282
train
caktus/django-timepiece
timepiece/entries/views.py
delete_entry
def delete_entry(request, entry_id): """ Give the user the ability to delete a log entry, with a confirmation beforehand. If this method is invoked via a GET request, a form asking for a confirmation of intent will be presented to the user. If this method is invoked via a POST request, the entry will be deleted. """ try: entry = Entry.no_join.get(pk=entry_id, user=request.user) except Entry.DoesNotExist: message = 'No such entry found.' messages.info(request, message) url = request.GET.get('next', reverse('dashboard')) return HttpResponseRedirect(url) if request.method == 'POST': key = request.POST.get('key', None) if key and key == entry.delete_key: entry.delete() message = 'Deleted {0} for {1}.'.format(entry.activity.name, entry.project) messages.info(request, message) url = request.GET.get('next', reverse('dashboard')) return HttpResponseRedirect(url) else: message = 'You are not authorized to delete this entry!' messages.error(request, message) return render(request, 'timepiece/entry/delete.html', { 'entry': entry, })
python
def delete_entry(request, entry_id): """ Give the user the ability to delete a log entry, with a confirmation beforehand. If this method is invoked via a GET request, a form asking for a confirmation of intent will be presented to the user. If this method is invoked via a POST request, the entry will be deleted. """ try: entry = Entry.no_join.get(pk=entry_id, user=request.user) except Entry.DoesNotExist: message = 'No such entry found.' messages.info(request, message) url = request.GET.get('next', reverse('dashboard')) return HttpResponseRedirect(url) if request.method == 'POST': key = request.POST.get('key', None) if key and key == entry.delete_key: entry.delete() message = 'Deleted {0} for {1}.'.format(entry.activity.name, entry.project) messages.info(request, message) url = request.GET.get('next', reverse('dashboard')) return HttpResponseRedirect(url) else: message = 'You are not authorized to delete this entry!' messages.error(request, message) return render(request, 'timepiece/entry/delete.html', { 'entry': entry, })
[ "def", "delete_entry", "(", "request", ",", "entry_id", ")", ":", "try", ":", "entry", "=", "Entry", ".", "no_join", ".", "get", "(", "pk", "=", "entry_id", ",", "user", "=", "request", ".", "user", ")", "except", "Entry", ".", "DoesNotExist", ":", "message", "=", "'No such entry found.'", "messages", ".", "info", "(", "request", ",", "message", ")", "url", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "reverse", "(", "'dashboard'", ")", ")", "return", "HttpResponseRedirect", "(", "url", ")", "if", "request", ".", "method", "==", "'POST'", ":", "key", "=", "request", ".", "POST", ".", "get", "(", "'key'", ",", "None", ")", "if", "key", "and", "key", "==", "entry", ".", "delete_key", ":", "entry", ".", "delete", "(", ")", "message", "=", "'Deleted {0} for {1}.'", ".", "format", "(", "entry", ".", "activity", ".", "name", ",", "entry", ".", "project", ")", "messages", ".", "info", "(", "request", ",", "message", ")", "url", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "reverse", "(", "'dashboard'", ")", ")", "return", "HttpResponseRedirect", "(", "url", ")", "else", ":", "message", "=", "'You are not authorized to delete this entry!'", "messages", ".", "error", "(", "request", ",", "message", ")", "return", "render", "(", "request", ",", "'timepiece/entry/delete.html'", ",", "{", "'entry'", ":", "entry", ",", "}", ")" ]
Give the user the ability to delete a log entry, with a confirmation beforehand. If this method is invoked via a GET request, a form asking for a confirmation of intent will be presented to the user. If this method is invoked via a POST request, the entry will be deleted.
[ "Give", "the", "user", "the", "ability", "to", "delete", "a", "log", "entry", "with", "a", "confirmation", "beforehand", ".", "If", "this", "method", "is", "invoked", "via", "a", "GET", "request", "a", "form", "asking", "for", "a", "confirmation", "of", "intent", "will", "be", "presented", "to", "the", "user", ".", "If", "this", "method", "is", "invoked", "via", "a", "POST", "request", "the", "entry", "will", "be", "deleted", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L286-L315
train
caktus/django-timepiece
timepiece/entries/views.py
Dashboard.get_hours_per_week
def get_hours_per_week(self, user=None): """Retrieves the number of hours the user should work per week.""" try: profile = UserProfile.objects.get(user=user or self.user) except UserProfile.DoesNotExist: profile = None return profile.hours_per_week if profile else Decimal('40.00')
python
def get_hours_per_week(self, user=None): """Retrieves the number of hours the user should work per week.""" try: profile = UserProfile.objects.get(user=user or self.user) except UserProfile.DoesNotExist: profile = None return profile.hours_per_week if profile else Decimal('40.00')
[ "def", "get_hours_per_week", "(", "self", ",", "user", "=", "None", ")", ":", "try", ":", "profile", "=", "UserProfile", ".", "objects", ".", "get", "(", "user", "=", "user", "or", "self", ".", "user", ")", "except", "UserProfile", ".", "DoesNotExist", ":", "profile", "=", "None", "return", "profile", ".", "hours_per_week", "if", "profile", "else", "Decimal", "(", "'40.00'", ")" ]
Retrieves the number of hours the user should work per week.
[ "Retrieves", "the", "number", "of", "hours", "the", "user", "should", "work", "per", "week", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L57-L63
train
caktus/django-timepiece
timepiece/entries/views.py
ScheduleMixin.get_hours_for_week
def get_hours_for_week(self, week_start=None): """ Gets all ProjectHours entries in the 7-day period beginning on week_start. """ week_start = week_start if week_start else self.week_start week_end = week_start + relativedelta(days=7) return ProjectHours.objects.filter( week_start__gte=week_start, week_start__lt=week_end)
python
def get_hours_for_week(self, week_start=None): """ Gets all ProjectHours entries in the 7-day period beginning on week_start. """ week_start = week_start if week_start else self.week_start week_end = week_start + relativedelta(days=7) return ProjectHours.objects.filter( week_start__gte=week_start, week_start__lt=week_end)
[ "def", "get_hours_for_week", "(", "self", ",", "week_start", "=", "None", ")", ":", "week_start", "=", "week_start", "if", "week_start", "else", "self", ".", "week_start", "week_end", "=", "week_start", "+", "relativedelta", "(", "days", "=", "7", ")", "return", "ProjectHours", ".", "objects", ".", "filter", "(", "week_start__gte", "=", "week_start", ",", "week_start__lt", "=", "week_end", ")" ]
Gets all ProjectHours entries in the 7-day period beginning on week_start.
[ "Gets", "all", "ProjectHours", "entries", "in", "the", "7", "-", "day", "period", "beginning", "on", "week_start", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L336-L345
train
caktus/django-timepiece
timepiece/entries/views.py
ScheduleView.get_users_from_project_hours
def get_users_from_project_hours(self, project_hours): """ Gets a list of the distinct users included in the project hours entries, ordered by name. """ name = ('user__first_name', 'user__last_name') users = project_hours.values_list('user__id', *name).distinct()\ .order_by(*name) return users
python
def get_users_from_project_hours(self, project_hours): """ Gets a list of the distinct users included in the project hours entries, ordered by name. """ name = ('user__first_name', 'user__last_name') users = project_hours.values_list('user__id', *name).distinct()\ .order_by(*name) return users
[ "def", "get_users_from_project_hours", "(", "self", ",", "project_hours", ")", ":", "name", "=", "(", "'user__first_name'", ",", "'user__last_name'", ")", "users", "=", "project_hours", ".", "values_list", "(", "'user__id'", ",", "*", "name", ")", ".", "distinct", "(", ")", ".", "order_by", "(", "*", "name", ")", "return", "users" ]
Gets a list of the distinct users included in the project hours entries, ordered by name.
[ "Gets", "a", "list", "of", "the", "distinct", "users", "included", "in", "the", "project", "hours", "entries", "ordered", "by", "name", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L357-L365
train
caktus/django-timepiece
timepiece/management/commands/check_entries.py
Command.check_all
def check_all(self, all_entries, *args, **kwargs): """ Go through lists of entries, find overlaps among each, return the total """ all_overlaps = 0 while True: try: user_entries = all_entries.next() except StopIteration: return all_overlaps else: user_total_overlaps = self.check_entry( user_entries, *args, **kwargs) all_overlaps += user_total_overlaps
python
def check_all(self, all_entries, *args, **kwargs): """ Go through lists of entries, find overlaps among each, return the total """ all_overlaps = 0 while True: try: user_entries = all_entries.next() except StopIteration: return all_overlaps else: user_total_overlaps = self.check_entry( user_entries, *args, **kwargs) all_overlaps += user_total_overlaps
[ "def", "check_all", "(", "self", ",", "all_entries", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "all_overlaps", "=", "0", "while", "True", ":", "try", ":", "user_entries", "=", "all_entries", ".", "next", "(", ")", "except", "StopIteration", ":", "return", "all_overlaps", "else", ":", "user_total_overlaps", "=", "self", ".", "check_entry", "(", "user_entries", ",", "*", "args", ",", "*", "*", "kwargs", ")", "all_overlaps", "+=", "user_total_overlaps" ]
Go through lists of entries, find overlaps among each, return the total
[ "Go", "through", "lists", "of", "entries", "find", "overlaps", "among", "each", "return", "the", "total" ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L69-L82
train
caktus/django-timepiece
timepiece/management/commands/check_entries.py
Command.check_entry
def check_entry(self, entries, *args, **kwargs): """ With a list of entries, check each entry against every other """ verbosity = kwargs.get('verbosity', 1) user_total_overlaps = 0 user = '' for index_a, entry_a in enumerate(entries): # Show the name the first time through if index_a == 0: if args and verbosity >= 1 or verbosity >= 2: self.show_name(entry_a.user) user = entry_a.user for index_b in range(index_a, len(entries)): entry_b = entries[index_b] if entry_a.check_overlap(entry_b): user_total_overlaps += 1 self.show_overlap(entry_a, entry_b, verbosity=verbosity) if user_total_overlaps and user and verbosity >= 1: overlap_data = { 'first': user.first_name, 'last': user.last_name, 'total': user_total_overlaps, } self.stdout.write('Total overlapping entries for user ' + '%(first)s %(last)s: %(total)d' % overlap_data) return user_total_overlaps
python
def check_entry(self, entries, *args, **kwargs): """ With a list of entries, check each entry against every other """ verbosity = kwargs.get('verbosity', 1) user_total_overlaps = 0 user = '' for index_a, entry_a in enumerate(entries): # Show the name the first time through if index_a == 0: if args and verbosity >= 1 or verbosity >= 2: self.show_name(entry_a.user) user = entry_a.user for index_b in range(index_a, len(entries)): entry_b = entries[index_b] if entry_a.check_overlap(entry_b): user_total_overlaps += 1 self.show_overlap(entry_a, entry_b, verbosity=verbosity) if user_total_overlaps and user and verbosity >= 1: overlap_data = { 'first': user.first_name, 'last': user.last_name, 'total': user_total_overlaps, } self.stdout.write('Total overlapping entries for user ' + '%(first)s %(last)s: %(total)d' % overlap_data) return user_total_overlaps
[ "def", "check_entry", "(", "self", ",", "entries", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "verbosity", "=", "kwargs", ".", "get", "(", "'verbosity'", ",", "1", ")", "user_total_overlaps", "=", "0", "user", "=", "''", "for", "index_a", ",", "entry_a", "in", "enumerate", "(", "entries", ")", ":", "# Show the name the first time through", "if", "index_a", "==", "0", ":", "if", "args", "and", "verbosity", ">=", "1", "or", "verbosity", ">=", "2", ":", "self", ".", "show_name", "(", "entry_a", ".", "user", ")", "user", "=", "entry_a", ".", "user", "for", "index_b", "in", "range", "(", "index_a", ",", "len", "(", "entries", ")", ")", ":", "entry_b", "=", "entries", "[", "index_b", "]", "if", "entry_a", ".", "check_overlap", "(", "entry_b", ")", ":", "user_total_overlaps", "+=", "1", "self", ".", "show_overlap", "(", "entry_a", ",", "entry_b", ",", "verbosity", "=", "verbosity", ")", "if", "user_total_overlaps", "and", "user", "and", "verbosity", ">=", "1", ":", "overlap_data", "=", "{", "'first'", ":", "user", ".", "first_name", ",", "'last'", ":", "user", ".", "last_name", ",", "'total'", ":", "user_total_overlaps", ",", "}", "self", ".", "stdout", ".", "write", "(", "'Total overlapping entries for user '", "+", "'%(first)s %(last)s: %(total)d'", "%", "overlap_data", ")", "return", "user_total_overlaps" ]
With a list of entries, check each entry against every other
[ "With", "a", "list", "of", "entries", "check", "each", "entry", "against", "every", "other" ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L84-L110
train
caktus/django-timepiece
timepiece/management/commands/check_entries.py
Command.find_start
def find_start(self, **kwargs): """ Determine the starting point of the query using CLI keyword arguments """ week = kwargs.get('week', False) month = kwargs.get('month', False) year = kwargs.get('year', False) days = kwargs.get('days', 0) # If no flags are True, set to the beginning of last billing window # to assure we catch all recent violations start = timezone.now() - relativedelta(months=1, day=1) # Set the start date based on arguments provided through options if week: start = utils.get_week_start() if month: start = timezone.now() - relativedelta(day=1) if year: start = timezone.now() - relativedelta(day=1, month=1) if days: start = timezone.now() - relativedelta(days=days) start -= relativedelta(hour=0, minute=0, second=0, microsecond=0) return start
python
def find_start(self, **kwargs): """ Determine the starting point of the query using CLI keyword arguments """ week = kwargs.get('week', False) month = kwargs.get('month', False) year = kwargs.get('year', False) days = kwargs.get('days', 0) # If no flags are True, set to the beginning of last billing window # to assure we catch all recent violations start = timezone.now() - relativedelta(months=1, day=1) # Set the start date based on arguments provided through options if week: start = utils.get_week_start() if month: start = timezone.now() - relativedelta(day=1) if year: start = timezone.now() - relativedelta(day=1, month=1) if days: start = timezone.now() - relativedelta(days=days) start -= relativedelta(hour=0, minute=0, second=0, microsecond=0) return start
[ "def", "find_start", "(", "self", ",", "*", "*", "kwargs", ")", ":", "week", "=", "kwargs", ".", "get", "(", "'week'", ",", "False", ")", "month", "=", "kwargs", ".", "get", "(", "'month'", ",", "False", ")", "year", "=", "kwargs", ".", "get", "(", "'year'", ",", "False", ")", "days", "=", "kwargs", ".", "get", "(", "'days'", ",", "0", ")", "# If no flags are True, set to the beginning of last billing window", "# to assure we catch all recent violations", "start", "=", "timezone", ".", "now", "(", ")", "-", "relativedelta", "(", "months", "=", "1", ",", "day", "=", "1", ")", "# Set the start date based on arguments provided through options", "if", "week", ":", "start", "=", "utils", ".", "get_week_start", "(", ")", "if", "month", ":", "start", "=", "timezone", ".", "now", "(", ")", "-", "relativedelta", "(", "day", "=", "1", ")", "if", "year", ":", "start", "=", "timezone", ".", "now", "(", ")", "-", "relativedelta", "(", "day", "=", "1", ",", "month", "=", "1", ")", "if", "days", ":", "start", "=", "timezone", ".", "now", "(", ")", "-", "relativedelta", "(", "days", "=", "days", ")", "start", "-=", "relativedelta", "(", "hour", "=", "0", ",", "minute", "=", "0", ",", "second", "=", "0", ",", "microsecond", "=", "0", ")", "return", "start" ]
Determine the starting point of the query using CLI keyword arguments
[ "Determine", "the", "starting", "point", "of", "the", "query", "using", "CLI", "keyword", "arguments" ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L112-L133
train
caktus/django-timepiece
timepiece/management/commands/check_entries.py
Command.find_users
def find_users(self, *args): """ Returns the users to search given names as args. Return all users if there are no args provided. """ if args: names = reduce(lambda query, arg: query | (Q(first_name__icontains=arg) | Q(last_name__icontains=arg)), args, Q()) # noqa users = User.objects.filter(names) # If no args given, check every user else: users = User.objects.all() # Display errors if no user was found if not users.count() and args: if len(args) == 1: raise CommandError('No user was found with the name %s' % args[0]) else: arg_list = ', '.join(args) raise CommandError('No users found with the names: %s' % arg_list) return users
python
def find_users(self, *args): """ Returns the users to search given names as args. Return all users if there are no args provided. """ if args: names = reduce(lambda query, arg: query | (Q(first_name__icontains=arg) | Q(last_name__icontains=arg)), args, Q()) # noqa users = User.objects.filter(names) # If no args given, check every user else: users = User.objects.all() # Display errors if no user was found if not users.count() and args: if len(args) == 1: raise CommandError('No user was found with the name %s' % args[0]) else: arg_list = ', '.join(args) raise CommandError('No users found with the names: %s' % arg_list) return users
[ "def", "find_users", "(", "self", ",", "*", "args", ")", ":", "if", "args", ":", "names", "=", "reduce", "(", "lambda", "query", ",", "arg", ":", "query", "|", "(", "Q", "(", "first_name__icontains", "=", "arg", ")", "|", "Q", "(", "last_name__icontains", "=", "arg", ")", ")", ",", "args", ",", "Q", "(", ")", ")", "# noqa", "users", "=", "User", ".", "objects", ".", "filter", "(", "names", ")", "# If no args given, check every user", "else", ":", "users", "=", "User", ".", "objects", ".", "all", "(", ")", "# Display errors if no user was found", "if", "not", "users", ".", "count", "(", ")", "and", "args", ":", "if", "len", "(", "args", ")", "==", "1", ":", "raise", "CommandError", "(", "'No user was found with the name %s'", "%", "args", "[", "0", "]", ")", "else", ":", "arg_list", "=", "', '", ".", "join", "(", "args", ")", "raise", "CommandError", "(", "'No users found with the names: %s'", "%", "arg_list", ")", "return", "users" ]
Returns the users to search given names as args. Return all users if there are no args provided.
[ "Returns", "the", "users", "to", "search", "given", "names", "as", "args", ".", "Return", "all", "users", "if", "there", "are", "no", "args", "provided", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L135-L155
train
caktus/django-timepiece
timepiece/management/commands/check_entries.py
Command.find_entries
def find_entries(self, users, start, *args, **kwargs): """ Find all entries for all users, from a given starting point. If no starting point is provided, all entries are returned. """ forever = kwargs.get('all', False) for user in users: if forever: entries = Entry.objects.filter(user=user).order_by('start_time') else: entries = Entry.objects.filter( user=user, start_time__gte=start).order_by( 'start_time') yield entries
python
def find_entries(self, users, start, *args, **kwargs): """ Find all entries for all users, from a given starting point. If no starting point is provided, all entries are returned. """ forever = kwargs.get('all', False) for user in users: if forever: entries = Entry.objects.filter(user=user).order_by('start_time') else: entries = Entry.objects.filter( user=user, start_time__gte=start).order_by( 'start_time') yield entries
[ "def", "find_entries", "(", "self", ",", "users", ",", "start", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "forever", "=", "kwargs", ".", "get", "(", "'all'", ",", "False", ")", "for", "user", "in", "users", ":", "if", "forever", ":", "entries", "=", "Entry", ".", "objects", ".", "filter", "(", "user", "=", "user", ")", ".", "order_by", "(", "'start_time'", ")", "else", ":", "entries", "=", "Entry", ".", "objects", ".", "filter", "(", "user", "=", "user", ",", "start_time__gte", "=", "start", ")", ".", "order_by", "(", "'start_time'", ")", "yield", "entries" ]
Find all entries for all users, from a given starting point. If no starting point is provided, all entries are returned.
[ "Find", "all", "entries", "for", "all", "users", "from", "a", "given", "starting", "point", ".", "If", "no", "starting", "point", "is", "provided", "all", "entries", "are", "returned", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L157-L170
train
caktus/django-timepiece
timepiece/utils/views.py
cbv_decorator
def cbv_decorator(function_decorator): """Allows a function-based decorator to be used on a CBV.""" def class_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return class_decorator
python
def cbv_decorator(function_decorator): """Allows a function-based decorator to be used on a CBV.""" def class_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return class_decorator
[ "def", "cbv_decorator", "(", "function_decorator", ")", ":", "def", "class_decorator", "(", "View", ")", ":", "View", ".", "dispatch", "=", "method_decorator", "(", "function_decorator", ")", "(", "View", ".", "dispatch", ")", "return", "View", "return", "class_decorator" ]
Allows a function-based decorator to be used on a CBV.
[ "Allows", "a", "function", "-", "based", "decorator", "to", "be", "used", "on", "a", "CBV", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/views.py#L4-L10
train
caktus/django-timepiece
timepiece/reports/utils.py
date_totals
def date_totals(entries, by): """Yield a user's name and a dictionary of their hours""" date_dict = {} for date, date_entries in groupby(entries, lambda x: x['date']): if isinstance(date, datetime.datetime): date = date.date() d_entries = list(date_entries) if by == 'user': name = ' '.join((d_entries[0]['user__first_name'], d_entries[0]['user__last_name'])) elif by == 'project': name = d_entries[0]['project__name'] else: name = d_entries[0][by] pk = d_entries[0][by] hours = get_hours_summary(d_entries) date_dict[date] = hours return name, pk, date_dict
python
def date_totals(entries, by): """Yield a user's name and a dictionary of their hours""" date_dict = {} for date, date_entries in groupby(entries, lambda x: x['date']): if isinstance(date, datetime.datetime): date = date.date() d_entries = list(date_entries) if by == 'user': name = ' '.join((d_entries[0]['user__first_name'], d_entries[0]['user__last_name'])) elif by == 'project': name = d_entries[0]['project__name'] else: name = d_entries[0][by] pk = d_entries[0][by] hours = get_hours_summary(d_entries) date_dict[date] = hours return name, pk, date_dict
[ "def", "date_totals", "(", "entries", ",", "by", ")", ":", "date_dict", "=", "{", "}", "for", "date", ",", "date_entries", "in", "groupby", "(", "entries", ",", "lambda", "x", ":", "x", "[", "'date'", "]", ")", ":", "if", "isinstance", "(", "date", ",", "datetime", ".", "datetime", ")", ":", "date", "=", "date", ".", "date", "(", ")", "d_entries", "=", "list", "(", "date_entries", ")", "if", "by", "==", "'user'", ":", "name", "=", "' '", ".", "join", "(", "(", "d_entries", "[", "0", "]", "[", "'user__first_name'", "]", ",", "d_entries", "[", "0", "]", "[", "'user__last_name'", "]", ")", ")", "elif", "by", "==", "'project'", ":", "name", "=", "d_entries", "[", "0", "]", "[", "'project__name'", "]", "else", ":", "name", "=", "d_entries", "[", "0", "]", "[", "by", "]", "pk", "=", "d_entries", "[", "0", "]", "[", "by", "]", "hours", "=", "get_hours_summary", "(", "d_entries", ")", "date_dict", "[", "date", "]", "=", "hours", "return", "name", ",", "pk", ",", "date_dict" ]
Yield a user's name and a dictionary of their hours
[ "Yield", "a", "user", "s", "name", "and", "a", "dictionary", "of", "their", "hours" ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/utils.py#L12-L31
train
caktus/django-timepiece
timepiece/reports/utils.py
get_project_totals
def get_project_totals(entries, date_headers, hour_type=None, overtime=False, total_column=False, by='user'): """ Yield hour totals grouped by user and date. Optionally including overtime. """ totals = [0 for date in date_headers] rows = [] for thing, thing_entries in groupby(entries, lambda x: x[by]): name, thing_id, date_dict = date_totals(thing_entries, by) dates = [] for index, day in enumerate(date_headers): if isinstance(day, datetime.datetime): day = day.date() if hour_type: total = date_dict.get(day, {}).get(hour_type, 0) dates.append(total) else: billable = date_dict.get(day, {}).get('billable', 0) nonbillable = date_dict.get(day, {}).get('non_billable', 0) total = billable + nonbillable dates.append({ 'day': day, 'billable': billable, 'nonbillable': nonbillable, 'total': total }) totals[index] += total if total_column: dates.append(sum(dates)) if overtime: dates.append(find_overtime(dates)) dates = [date or '' for date in dates] rows.append((name, thing_id, dates)) if total_column: totals.append(sum(totals)) totals = [t or '' for t in totals] yield (rows, totals)
python
def get_project_totals(entries, date_headers, hour_type=None, overtime=False, total_column=False, by='user'): """ Yield hour totals grouped by user and date. Optionally including overtime. """ totals = [0 for date in date_headers] rows = [] for thing, thing_entries in groupby(entries, lambda x: x[by]): name, thing_id, date_dict = date_totals(thing_entries, by) dates = [] for index, day in enumerate(date_headers): if isinstance(day, datetime.datetime): day = day.date() if hour_type: total = date_dict.get(day, {}).get(hour_type, 0) dates.append(total) else: billable = date_dict.get(day, {}).get('billable', 0) nonbillable = date_dict.get(day, {}).get('non_billable', 0) total = billable + nonbillable dates.append({ 'day': day, 'billable': billable, 'nonbillable': nonbillable, 'total': total }) totals[index] += total if total_column: dates.append(sum(dates)) if overtime: dates.append(find_overtime(dates)) dates = [date or '' for date in dates] rows.append((name, thing_id, dates)) if total_column: totals.append(sum(totals)) totals = [t or '' for t in totals] yield (rows, totals)
[ "def", "get_project_totals", "(", "entries", ",", "date_headers", ",", "hour_type", "=", "None", ",", "overtime", "=", "False", ",", "total_column", "=", "False", ",", "by", "=", "'user'", ")", ":", "totals", "=", "[", "0", "for", "date", "in", "date_headers", "]", "rows", "=", "[", "]", "for", "thing", ",", "thing_entries", "in", "groupby", "(", "entries", ",", "lambda", "x", ":", "x", "[", "by", "]", ")", ":", "name", ",", "thing_id", ",", "date_dict", "=", "date_totals", "(", "thing_entries", ",", "by", ")", "dates", "=", "[", "]", "for", "index", ",", "day", "in", "enumerate", "(", "date_headers", ")", ":", "if", "isinstance", "(", "day", ",", "datetime", ".", "datetime", ")", ":", "day", "=", "day", ".", "date", "(", ")", "if", "hour_type", ":", "total", "=", "date_dict", ".", "get", "(", "day", ",", "{", "}", ")", ".", "get", "(", "hour_type", ",", "0", ")", "dates", ".", "append", "(", "total", ")", "else", ":", "billable", "=", "date_dict", ".", "get", "(", "day", ",", "{", "}", ")", ".", "get", "(", "'billable'", ",", "0", ")", "nonbillable", "=", "date_dict", ".", "get", "(", "day", ",", "{", "}", ")", ".", "get", "(", "'non_billable'", ",", "0", ")", "total", "=", "billable", "+", "nonbillable", "dates", ".", "append", "(", "{", "'day'", ":", "day", ",", "'billable'", ":", "billable", ",", "'nonbillable'", ":", "nonbillable", ",", "'total'", ":", "total", "}", ")", "totals", "[", "index", "]", "+=", "total", "if", "total_column", ":", "dates", ".", "append", "(", "sum", "(", "dates", ")", ")", "if", "overtime", ":", "dates", ".", "append", "(", "find_overtime", "(", "dates", ")", ")", "dates", "=", "[", "date", "or", "''", "for", "date", "in", "dates", "]", "rows", ".", "append", "(", "(", "name", ",", "thing_id", ",", "dates", ")", ")", "if", "total_column", ":", "totals", ".", "append", "(", "sum", "(", "totals", ")", ")", "totals", "=", "[", "t", "or", "''", "for", "t", "in", "totals", "]", "yield", "(", "rows", ",", "totals", ")" ]
Yield hour totals grouped by user and date. Optionally including overtime.
[ "Yield", "hour", "totals", "grouped", "by", "user", "and", "date", ".", "Optionally", "including", "overtime", "." ]
52515dec027664890efbc535429e1ba1ee152f40
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/utils.py#L57-L93
train
stanfordnlp/stanza
stanza/research/learner.py
Learner.validate
def validate(self, validation_instances, metrics, iteration=None): ''' Evaluate this model on `validation_instances` during training and output a report. :param validation_instances: The data to use to validate the model. :type validation_instances: list(instance.Instance) :param metrics: Functions like those found in the `metrics` module for quantifying the performance of the learner. :type metrics: list(function) :param iteration: A label (anything with a sensible `str()` conversion) identifying the current iteration in output. ''' if not validation_instances or not metrics: return {} split_id = 'val%s' % iteration if iteration is not None else 'val' train_results = evaluate.evaluate(self, validation_instances, metrics=metrics, split_id=split_id) output.output_results(train_results, split_id) return train_results
python
def validate(self, validation_instances, metrics, iteration=None): ''' Evaluate this model on `validation_instances` during training and output a report. :param validation_instances: The data to use to validate the model. :type validation_instances: list(instance.Instance) :param metrics: Functions like those found in the `metrics` module for quantifying the performance of the learner. :type metrics: list(function) :param iteration: A label (anything with a sensible `str()` conversion) identifying the current iteration in output. ''' if not validation_instances or not metrics: return {} split_id = 'val%s' % iteration if iteration is not None else 'val' train_results = evaluate.evaluate(self, validation_instances, metrics=metrics, split_id=split_id) output.output_results(train_results, split_id) return train_results
[ "def", "validate", "(", "self", ",", "validation_instances", ",", "metrics", ",", "iteration", "=", "None", ")", ":", "if", "not", "validation_instances", "or", "not", "metrics", ":", "return", "{", "}", "split_id", "=", "'val%s'", "%", "iteration", "if", "iteration", "is", "not", "None", "else", "'val'", "train_results", "=", "evaluate", ".", "evaluate", "(", "self", ",", "validation_instances", ",", "metrics", "=", "metrics", ",", "split_id", "=", "split_id", ")", "output", ".", "output_results", "(", "train_results", ",", "split_id", ")", "return", "train_results" ]
Evaluate this model on `validation_instances` during training and output a report. :param validation_instances: The data to use to validate the model. :type validation_instances: list(instance.Instance) :param metrics: Functions like those found in the `metrics` module for quantifying the performance of the learner. :type metrics: list(function) :param iteration: A label (anything with a sensible `str()` conversion) identifying the current iteration in output.
[ "Evaluate", "this", "model", "on", "validation_instances", "during", "training", "and", "output", "a", "report", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L34-L55
train
stanfordnlp/stanza
stanza/research/learner.py
Learner.predict_and_score
def predict_and_score(self, eval_instances, random=False, verbosity=0): ''' Return most likely outputs and scores for the particular set of outputs given in `eval_instances`, as a tuple. Return value should be equivalent to the default implementation of return (self.predict(eval_instances), self.score(eval_instances)) but subclasses can override this to combine the two calls and reduce duplicated work. Either the two separate methods or this one (or all of them) should be overridden. :param eval_instances: The data to use to evaluate the model. Instances should have at least the `input` and `output` fields populated. `output` is needed to define which score is to be returned. :param random: If `True`, sample from the probability distribution defined by the classifier rather than output the most likely prediction. :param verbosity: The level of diagnostic output, relative to the global --verbosity option. Used to adjust output when models are composed of multiple sub-models. :type eval_instances: list(instance.Instance) :returns: tuple(list(output_type), list(float)) ''' if hasattr(self, '_using_default_separate') and self._using_default_separate: raise NotImplementedError self._using_default_combined = True return (self.predict(eval_instances, random=random, verbosity=verbosity), self.score(eval_instances, verbosity=verbosity))
python
def predict_and_score(self, eval_instances, random=False, verbosity=0): ''' Return most likely outputs and scores for the particular set of outputs given in `eval_instances`, as a tuple. Return value should be equivalent to the default implementation of return (self.predict(eval_instances), self.score(eval_instances)) but subclasses can override this to combine the two calls and reduce duplicated work. Either the two separate methods or this one (or all of them) should be overridden. :param eval_instances: The data to use to evaluate the model. Instances should have at least the `input` and `output` fields populated. `output` is needed to define which score is to be returned. :param random: If `True`, sample from the probability distribution defined by the classifier rather than output the most likely prediction. :param verbosity: The level of diagnostic output, relative to the global --verbosity option. Used to adjust output when models are composed of multiple sub-models. :type eval_instances: list(instance.Instance) :returns: tuple(list(output_type), list(float)) ''' if hasattr(self, '_using_default_separate') and self._using_default_separate: raise NotImplementedError self._using_default_combined = True return (self.predict(eval_instances, random=random, verbosity=verbosity), self.score(eval_instances, verbosity=verbosity))
[ "def", "predict_and_score", "(", "self", ",", "eval_instances", ",", "random", "=", "False", ",", "verbosity", "=", "0", ")", ":", "if", "hasattr", "(", "self", ",", "'_using_default_separate'", ")", "and", "self", ".", "_using_default_separate", ":", "raise", "NotImplementedError", "self", ".", "_using_default_combined", "=", "True", "return", "(", "self", ".", "predict", "(", "eval_instances", ",", "random", "=", "random", ",", "verbosity", "=", "verbosity", ")", ",", "self", ".", "score", "(", "eval_instances", ",", "verbosity", "=", "verbosity", ")", ")" ]
Return most likely outputs and scores for the particular set of outputs given in `eval_instances`, as a tuple. Return value should be equivalent to the default implementation of return (self.predict(eval_instances), self.score(eval_instances)) but subclasses can override this to combine the two calls and reduce duplicated work. Either the two separate methods or this one (or all of them) should be overridden. :param eval_instances: The data to use to evaluate the model. Instances should have at least the `input` and `output` fields populated. `output` is needed to define which score is to be returned. :param random: If `True`, sample from the probability distribution defined by the classifier rather than output the most likely prediction. :param verbosity: The level of diagnostic output, relative to the global --verbosity option. Used to adjust output when models are composed of multiple sub-models. :type eval_instances: list(instance.Instance) :returns: tuple(list(output_type), list(float))
[ "Return", "most", "likely", "outputs", "and", "scores", "for", "the", "particular", "set", "of", "outputs", "given", "in", "eval_instances", "as", "a", "tuple", ".", "Return", "value", "should", "be", "equivalent", "to", "the", "default", "implementation", "of" ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L104-L135
train
stanfordnlp/stanza
stanza/research/learner.py
Learner.load
def load(self, infile): ''' Deserialize a model from a stored file. By default, unpickle an entire object. If `dump` is overridden to use a different storage format, `load` should be as well. :param file outfile: A file-like object from which to retrieve the serialized model. ''' model = pickle.load(infile) self.__dict__.update(model.__dict__)
python
def load(self, infile): ''' Deserialize a model from a stored file. By default, unpickle an entire object. If `dump` is overridden to use a different storage format, `load` should be as well. :param file outfile: A file-like object from which to retrieve the serialized model. ''' model = pickle.load(infile) self.__dict__.update(model.__dict__)
[ "def", "load", "(", "self", ",", "infile", ")", ":", "model", "=", "pickle", ".", "load", "(", "infile", ")", "self", ".", "__dict__", ".", "update", "(", "model", ".", "__dict__", ")" ]
Deserialize a model from a stored file. By default, unpickle an entire object. If `dump` is overridden to use a different storage format, `load` should be as well. :param file outfile: A file-like object from which to retrieve the serialized model.
[ "Deserialize", "a", "model", "from", "a", "stored", "file", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L153-L164
train
stanfordnlp/stanza
stanza/research/iterators.py
iter_batches
def iter_batches(iterable, batch_size): ''' Given a sequence or iterable, yield batches from that iterable until it runs out. Note that this function returns a generator, and also each batch will be a generator. :param iterable: The sequence or iterable to split into batches :param int batch_size: The number of elements of `iterable` to iterate over in each batch >>> batches = iter_batches('abcdefghijkl', batch_size=5) >>> list(next(batches)) ['a', 'b', 'c', 'd', 'e'] >>> list(next(batches)) ['f', 'g', 'h', 'i', 'j'] >>> list(next(batches)) ['k', 'l'] >>> list(next(batches)) Traceback (most recent call last): ... StopIteration Warning: It is important to iterate completely over each batch before requesting the next, or batch sizes will be truncated to 1. For example, making a list of all batches before asking for the contents of each will not work: >>> batches = list(iter_batches('abcdefghijkl', batch_size=5)) >>> len(batches) 12 >>> list(batches[0]) ['a'] However, making a list of each individual batch as it is received will produce expected behavior (as shown in the first example). ''' # http://stackoverflow.com/a/8290514/4481448 sourceiter = iter(iterable) while True: batchiter = islice(sourceiter, batch_size) yield chain([batchiter.next()], batchiter)
python
def iter_batches(iterable, batch_size): ''' Given a sequence or iterable, yield batches from that iterable until it runs out. Note that this function returns a generator, and also each batch will be a generator. :param iterable: The sequence or iterable to split into batches :param int batch_size: The number of elements of `iterable` to iterate over in each batch >>> batches = iter_batches('abcdefghijkl', batch_size=5) >>> list(next(batches)) ['a', 'b', 'c', 'd', 'e'] >>> list(next(batches)) ['f', 'g', 'h', 'i', 'j'] >>> list(next(batches)) ['k', 'l'] >>> list(next(batches)) Traceback (most recent call last): ... StopIteration Warning: It is important to iterate completely over each batch before requesting the next, or batch sizes will be truncated to 1. For example, making a list of all batches before asking for the contents of each will not work: >>> batches = list(iter_batches('abcdefghijkl', batch_size=5)) >>> len(batches) 12 >>> list(batches[0]) ['a'] However, making a list of each individual batch as it is received will produce expected behavior (as shown in the first example). ''' # http://stackoverflow.com/a/8290514/4481448 sourceiter = iter(iterable) while True: batchiter = islice(sourceiter, batch_size) yield chain([batchiter.next()], batchiter)
[ "def", "iter_batches", "(", "iterable", ",", "batch_size", ")", ":", "# http://stackoverflow.com/a/8290514/4481448", "sourceiter", "=", "iter", "(", "iterable", ")", "while", "True", ":", "batchiter", "=", "islice", "(", "sourceiter", ",", "batch_size", ")", "yield", "chain", "(", "[", "batchiter", ".", "next", "(", ")", "]", ",", "batchiter", ")" ]
Given a sequence or iterable, yield batches from that iterable until it runs out. Note that this function returns a generator, and also each batch will be a generator. :param iterable: The sequence or iterable to split into batches :param int batch_size: The number of elements of `iterable` to iterate over in each batch >>> batches = iter_batches('abcdefghijkl', batch_size=5) >>> list(next(batches)) ['a', 'b', 'c', 'd', 'e'] >>> list(next(batches)) ['f', 'g', 'h', 'i', 'j'] >>> list(next(batches)) ['k', 'l'] >>> list(next(batches)) Traceback (most recent call last): ... StopIteration Warning: It is important to iterate completely over each batch before requesting the next, or batch sizes will be truncated to 1. For example, making a list of all batches before asking for the contents of each will not work: >>> batches = list(iter_batches('abcdefghijkl', batch_size=5)) >>> len(batches) 12 >>> list(batches[0]) ['a'] However, making a list of each individual batch as it is received will produce expected behavior (as shown in the first example).
[ "Given", "a", "sequence", "or", "iterable", "yield", "batches", "from", "that", "iterable", "until", "it", "runs", "out", ".", "Note", "that", "this", "function", "returns", "a", "generator", "and", "also", "each", "batch", "will", "be", "a", "generator", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L4-L44
train
stanfordnlp/stanza
stanza/research/iterators.py
gen_batches
def gen_batches(iterable, batch_size): ''' Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and only if `iterable` does. This *may* be an iterator, but could be a `SizedGenerator` object. To obtain an iterator (for example, to use the `next()` function), call `iter()` on this iterable. >>> batches = gen_batches('abcdefghijkl', batch_size=5) >>> len(batches) 3 >>> for batch in batches: ... print(list(batch)) ['a', 'b', 'c', 'd', 'e'] ['f', 'g', 'h', 'i', 'j'] ['k', 'l'] ''' def batches_thunk(): return iter_batches(iterable, batch_size) try: length = len(iterable) except TypeError: return batches_thunk() num_batches = (length - 1) // batch_size + 1 return SizedGenerator(batches_thunk, length=num_batches)
python
def gen_batches(iterable, batch_size): ''' Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and only if `iterable` does. This *may* be an iterator, but could be a `SizedGenerator` object. To obtain an iterator (for example, to use the `next()` function), call `iter()` on this iterable. >>> batches = gen_batches('abcdefghijkl', batch_size=5) >>> len(batches) 3 >>> for batch in batches: ... print(list(batch)) ['a', 'b', 'c', 'd', 'e'] ['f', 'g', 'h', 'i', 'j'] ['k', 'l'] ''' def batches_thunk(): return iter_batches(iterable, batch_size) try: length = len(iterable) except TypeError: return batches_thunk() num_batches = (length - 1) // batch_size + 1 return SizedGenerator(batches_thunk, length=num_batches)
[ "def", "gen_batches", "(", "iterable", ",", "batch_size", ")", ":", "def", "batches_thunk", "(", ")", ":", "return", "iter_batches", "(", "iterable", ",", "batch_size", ")", "try", ":", "length", "=", "len", "(", "iterable", ")", "except", "TypeError", ":", "return", "batches_thunk", "(", ")", "num_batches", "=", "(", "length", "-", "1", ")", "//", "batch_size", "+", "1", "return", "SizedGenerator", "(", "batches_thunk", ",", "length", "=", "num_batches", ")" ]
Returns a generator object that yields batches from `iterable`. See `iter_batches` for more details and caveats. Note that `iter_batches` returns an iterator, which never supports `len()`, `gen_batches` returns an iterable which supports `len()` if and only if `iterable` does. This *may* be an iterator, but could be a `SizedGenerator` object. To obtain an iterator (for example, to use the `next()` function), call `iter()` on this iterable. >>> batches = gen_batches('abcdefghijkl', batch_size=5) >>> len(batches) 3 >>> for batch in batches: ... print(list(batch)) ['a', 'b', 'c', 'd', 'e'] ['f', 'g', 'h', 'i', 'j'] ['k', 'l']
[ "Returns", "a", "generator", "object", "that", "yields", "batches", "from", "iterable", ".", "See", "iter_batches", "for", "more", "details", "and", "caveats", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L47-L76
train
stanfordnlp/stanza
stanza/research/instance.py
Instance.inverted
def inverted(self): ''' Return a version of this instance with inputs replaced by outputs and vice versa. ''' return Instance(input=self.output, output=self.input, annotated_input=self.annotated_output, annotated_output=self.annotated_input, alt_inputs=self.alt_outputs, alt_outputs=self.alt_inputs, source=self.source)
python
def inverted(self): ''' Return a version of this instance with inputs replaced by outputs and vice versa. ''' return Instance(input=self.output, output=self.input, annotated_input=self.annotated_output, annotated_output=self.annotated_input, alt_inputs=self.alt_outputs, alt_outputs=self.alt_inputs, source=self.source)
[ "def", "inverted", "(", "self", ")", ":", "return", "Instance", "(", "input", "=", "self", ".", "output", ",", "output", "=", "self", ".", "input", ",", "annotated_input", "=", "self", ".", "annotated_output", ",", "annotated_output", "=", "self", ".", "annotated_input", ",", "alt_inputs", "=", "self", ".", "alt_outputs", ",", "alt_outputs", "=", "self", ".", "alt_inputs", ",", "source", "=", "self", ".", "source", ")" ]
Return a version of this instance with inputs replaced by outputs and vice versa.
[ "Return", "a", "version", "of", "this", "instance", "with", "inputs", "replaced", "by", "outputs", "and", "vice", "versa", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/instance.py#L36-L45
train
stanfordnlp/stanza
stanza/util/resource.py
get_data_or_download
def get_data_or_download(dir_name, file_name, url='', size='unknown'): """Returns the data. if the data hasn't been downloaded, then first download the data. :param dir_name: directory to look in :param file_name: file name to retrieve :param url: if the file is not found, then download it from this url :param size: the expected size :return: path to the requested file """ dname = os.path.join(stanza.DATA_DIR, dir_name) fname = os.path.join(dname, file_name) if not os.path.isdir(dname): assert url, 'Could not locate data {}, and url was not specified. Cannot retrieve data.'.format(dname) os.makedirs(dname) if not os.path.isfile(fname): assert url, 'Could not locate data {}, and url was not specified. Cannot retrieve data.'.format(fname) logging.warn('downloading from {}. This file could potentially be *very* large! Actual size ({})'.format(url, size)) with open(fname, 'wb') as f: f.write(get_from_url(url)) return fname
python
def get_data_or_download(dir_name, file_name, url='', size='unknown'): """Returns the data. if the data hasn't been downloaded, then first download the data. :param dir_name: directory to look in :param file_name: file name to retrieve :param url: if the file is not found, then download it from this url :param size: the expected size :return: path to the requested file """ dname = os.path.join(stanza.DATA_DIR, dir_name) fname = os.path.join(dname, file_name) if not os.path.isdir(dname): assert url, 'Could not locate data {}, and url was not specified. Cannot retrieve data.'.format(dname) os.makedirs(dname) if not os.path.isfile(fname): assert url, 'Could not locate data {}, and url was not specified. Cannot retrieve data.'.format(fname) logging.warn('downloading from {}. This file could potentially be *very* large! Actual size ({})'.format(url, size)) with open(fname, 'wb') as f: f.write(get_from_url(url)) return fname
[ "def", "get_data_or_download", "(", "dir_name", ",", "file_name", ",", "url", "=", "''", ",", "size", "=", "'unknown'", ")", ":", "dname", "=", "os", ".", "path", ".", "join", "(", "stanza", ".", "DATA_DIR", ",", "dir_name", ")", "fname", "=", "os", ".", "path", ".", "join", "(", "dname", ",", "file_name", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dname", ")", ":", "assert", "url", ",", "'Could not locate data {}, and url was not specified. Cannot retrieve data.'", ".", "format", "(", "dname", ")", "os", ".", "makedirs", "(", "dname", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "assert", "url", ",", "'Could not locate data {}, and url was not specified. Cannot retrieve data.'", ".", "format", "(", "fname", ")", "logging", ".", "warn", "(", "'downloading from {}. This file could potentially be *very* large! Actual size ({})'", ".", "format", "(", "url", ",", "size", ")", ")", "with", "open", "(", "fname", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "get_from_url", "(", "url", ")", ")", "return", "fname" ]
Returns the data. if the data hasn't been downloaded, then first download the data. :param dir_name: directory to look in :param file_name: file name to retrieve :param url: if the file is not found, then download it from this url :param size: the expected size :return: path to the requested file
[ "Returns", "the", "data", ".", "if", "the", "data", "hasn", "t", "been", "downloaded", "then", "first", "download", "the", "data", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/util/resource.py#L16-L35
train
stanfordnlp/stanza
stanza/text/vocab.py
Vocab.add
def add(self, word, count=1): """Add a word to the vocabulary and return its index. :param word: word to add to the dictionary. :param count: how many times to add the word. :return: index of the added word. WARNING: this function assumes that if the Vocab currently has N words, then there is a perfect bijection between these N words and the integers 0 through N-1. """ if word not in self: super(Vocab, self).__setitem__(word, len(self)) self._counts[word] += count return self[word]
python
def add(self, word, count=1): """Add a word to the vocabulary and return its index. :param word: word to add to the dictionary. :param count: how many times to add the word. :return: index of the added word. WARNING: this function assumes that if the Vocab currently has N words, then there is a perfect bijection between these N words and the integers 0 through N-1. """ if word not in self: super(Vocab, self).__setitem__(word, len(self)) self._counts[word] += count return self[word]
[ "def", "add", "(", "self", ",", "word", ",", "count", "=", "1", ")", ":", "if", "word", "not", "in", "self", ":", "super", "(", "Vocab", ",", "self", ")", ".", "__setitem__", "(", "word", ",", "len", "(", "self", ")", ")", "self", ".", "_counts", "[", "word", "]", "+=", "count", "return", "self", "[", "word", "]" ]
Add a word to the vocabulary and return its index. :param word: word to add to the dictionary. :param count: how many times to add the word. :return: index of the added word. WARNING: this function assumes that if the Vocab currently has N words, then there is a perfect bijection between these N words and the integers 0 through N-1.
[ "Add", "a", "word", "to", "the", "vocabulary", "and", "return", "its", "index", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L93-L108
train
stanfordnlp/stanza
stanza/text/vocab.py
Vocab.subset
def subset(self, words): """Get a new Vocab containing only the specified subset of words. If w is in words, but not in the original vocab, it will NOT be in the subset vocab. Indices will be in the order of `words`. Counts from the original vocab are preserved. :return (Vocab): a new Vocab object """ v = self.__class__(unk=self._unk) unique = lambda seq: len(set(seq)) == len(seq) assert unique(words) for w in words: if w in self: v.add(w, count=self.count(w)) return v
python
def subset(self, words): """Get a new Vocab containing only the specified subset of words. If w is in words, but not in the original vocab, it will NOT be in the subset vocab. Indices will be in the order of `words`. Counts from the original vocab are preserved. :return (Vocab): a new Vocab object """ v = self.__class__(unk=self._unk) unique = lambda seq: len(set(seq)) == len(seq) assert unique(words) for w in words: if w in self: v.add(w, count=self.count(w)) return v
[ "def", "subset", "(", "self", ",", "words", ")", ":", "v", "=", "self", ".", "__class__", "(", "unk", "=", "self", ".", "_unk", ")", "unique", "=", "lambda", "seq", ":", "len", "(", "set", "(", "seq", ")", ")", "==", "len", "(", "seq", ")", "assert", "unique", "(", "words", ")", "for", "w", "in", "words", ":", "if", "w", "in", "self", ":", "v", ".", "add", "(", "w", ",", "count", "=", "self", ".", "count", "(", "w", ")", ")", "return", "v" ]
Get a new Vocab containing only the specified subset of words. If w is in words, but not in the original vocab, it will NOT be in the subset vocab. Indices will be in the order of `words`. Counts from the original vocab are preserved. :return (Vocab): a new Vocab object
[ "Get", "a", "new", "Vocab", "containing", "only", "the", "specified", "subset", "of", "words", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L136-L150
train
stanfordnlp/stanza
stanza/text/vocab.py
Vocab._index2word
def _index2word(self): """Mapping from indices to words. WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab. :return: a list of strings """ # TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable compute_index2word = lambda: self.keys() # this works because self is an OrderedDict # create if it doesn't exist try: self._index2word_cache except AttributeError: self._index2word_cache = compute_index2word() # update if it is out of date if len(self._index2word_cache) != len(self): self._index2word_cache = compute_index2word() return self._index2word_cache
python
def _index2word(self): """Mapping from indices to words. WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab. :return: a list of strings """ # TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable compute_index2word = lambda: self.keys() # this works because self is an OrderedDict # create if it doesn't exist try: self._index2word_cache except AttributeError: self._index2word_cache = compute_index2word() # update if it is out of date if len(self._index2word_cache) != len(self): self._index2word_cache = compute_index2word() return self._index2word_cache
[ "def", "_index2word", "(", "self", ")", ":", "# TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable", "compute_index2word", "=", "lambda", ":", "self", ".", "keys", "(", ")", "# this works because self is an OrderedDict", "# create if it doesn't exist", "try", ":", "self", ".", "_index2word_cache", "except", "AttributeError", ":", "self", ".", "_index2word_cache", "=", "compute_index2word", "(", ")", "# update if it is out of date", "if", "len", "(", "self", ".", "_index2word_cache", ")", "!=", "len", "(", "self", ")", ":", "self", ".", "_index2word_cache", "=", "compute_index2word", "(", ")", "return", "self", ".", "_index2word_cache" ]
Mapping from indices to words. WARNING: this may go out-of-date, because it is a copy, not a view into the Vocab. :return: a list of strings
[ "Mapping", "from", "indices", "to", "words", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L153-L174
train
stanfordnlp/stanza
stanza/text/vocab.py
Vocab.from_dict
def from_dict(cls, word2index, unk, counts=None): """Create Vocab from an existing string to integer dictionary. All counts are set to 0. :param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1. UNK must be assigned the 0 index. :param unk: the string representing unk in word2index. :param counts: (optional) a Counter object mapping words to counts :return: a created vocab object. """ try: if word2index[unk] != 0: raise ValueError('unk must be assigned index 0') except KeyError: raise ValueError('word2index must have an entry for unk.') # check that word2index is a bijection vals = set(word2index.values()) # unique indices n = len(vals) bijection = (len(word2index) == n) and (vals == set(range(n))) if not bijection: raise ValueError('word2index is not a bijection between N words and the integers 0 through N-1.') # reverse the dictionary index2word = {idx: word for word, idx in word2index.iteritems()} vocab = cls(unk=unk) for i in xrange(n): vocab.add(index2word[i]) if counts: matching_entries = set(word2index.keys()) == set(counts.keys()) if not matching_entries: raise ValueError('entries of word2index do not match counts (did you include UNK?)') vocab._counts = counts return vocab
python
def from_dict(cls, word2index, unk, counts=None): """Create Vocab from an existing string to integer dictionary. All counts are set to 0. :param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1. UNK must be assigned the 0 index. :param unk: the string representing unk in word2index. :param counts: (optional) a Counter object mapping words to counts :return: a created vocab object. """ try: if word2index[unk] != 0: raise ValueError('unk must be assigned index 0') except KeyError: raise ValueError('word2index must have an entry for unk.') # check that word2index is a bijection vals = set(word2index.values()) # unique indices n = len(vals) bijection = (len(word2index) == n) and (vals == set(range(n))) if not bijection: raise ValueError('word2index is not a bijection between N words and the integers 0 through N-1.') # reverse the dictionary index2word = {idx: word for word, idx in word2index.iteritems()} vocab = cls(unk=unk) for i in xrange(n): vocab.add(index2word[i]) if counts: matching_entries = set(word2index.keys()) == set(counts.keys()) if not matching_entries: raise ValueError('entries of word2index do not match counts (did you include UNK?)') vocab._counts = counts return vocab
[ "def", "from_dict", "(", "cls", ",", "word2index", ",", "unk", ",", "counts", "=", "None", ")", ":", "try", ":", "if", "word2index", "[", "unk", "]", "!=", "0", ":", "raise", "ValueError", "(", "'unk must be assigned index 0'", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'word2index must have an entry for unk.'", ")", "# check that word2index is a bijection", "vals", "=", "set", "(", "word2index", ".", "values", "(", ")", ")", "# unique indices", "n", "=", "len", "(", "vals", ")", "bijection", "=", "(", "len", "(", "word2index", ")", "==", "n", ")", "and", "(", "vals", "==", "set", "(", "range", "(", "n", ")", ")", ")", "if", "not", "bijection", ":", "raise", "ValueError", "(", "'word2index is not a bijection between N words and the integers 0 through N-1.'", ")", "# reverse the dictionary", "index2word", "=", "{", "idx", ":", "word", "for", "word", ",", "idx", "in", "word2index", ".", "iteritems", "(", ")", "}", "vocab", "=", "cls", "(", "unk", "=", "unk", ")", "for", "i", "in", "xrange", "(", "n", ")", ":", "vocab", ".", "add", "(", "index2word", "[", "i", "]", ")", "if", "counts", ":", "matching_entries", "=", "set", "(", "word2index", ".", "keys", "(", ")", ")", "==", "set", "(", "counts", ".", "keys", "(", ")", ")", "if", "not", "matching_entries", ":", "raise", "ValueError", "(", "'entries of word2index do not match counts (did you include UNK?)'", ")", "vocab", ".", "_counts", "=", "counts", "return", "vocab" ]
Create Vocab from an existing string to integer dictionary. All counts are set to 0. :param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1. UNK must be assigned the 0 index. :param unk: the string representing unk in word2index. :param counts: (optional) a Counter object mapping words to counts :return: a created vocab object.
[ "Create", "Vocab", "from", "an", "existing", "string", "to", "integer", "dictionary", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L205-L246
train
stanfordnlp/stanza
stanza/text/vocab.py
Vocab.to_file
def to_file(self, f): """Write vocab to a file. :param (file) f: a file object, e.g. as returned by calling `open` File format: word0<TAB>count0 word1<TAB>count1 ... word with index 0 is on the 0th line and so on... """ for word in self._index2word: count = self._counts[word] f.write(u'{}\t{}\n'.format(word, count).encode('utf-8'))
python
def to_file(self, f): """Write vocab to a file. :param (file) f: a file object, e.g. as returned by calling `open` File format: word0<TAB>count0 word1<TAB>count1 ... word with index 0 is on the 0th line and so on... """ for word in self._index2word: count = self._counts[word] f.write(u'{}\t{}\n'.format(word, count).encode('utf-8'))
[ "def", "to_file", "(", "self", ",", "f", ")", ":", "for", "word", "in", "self", ".", "_index2word", ":", "count", "=", "self", ".", "_counts", "[", "word", "]", "f", ".", "write", "(", "u'{}\\t{}\\n'", ".", "format", "(", "word", ",", "count", ")", ".", "encode", "(", "'utf-8'", ")", ")" ]
Write vocab to a file. :param (file) f: a file object, e.g. as returned by calling `open` File format: word0<TAB>count0 word1<TAB>count1 ... word with index 0 is on the 0th line and so on...
[ "Write", "vocab", "to", "a", "file", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L248-L262
train
stanfordnlp/stanza
stanza/text/vocab.py
EmbeddedVocab.backfill_unk_emb
def backfill_unk_emb(self, E, filled_words): """ Backfills an embedding matrix with the embedding for the unknown token. :param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`. :param filled_words: these words will not be backfilled with unk. NOTE: this function is for internal use. """ unk_emb = E[self[self._unk]] for i, word in enumerate(self): if word not in filled_words: E[i] = unk_emb
python
def backfill_unk_emb(self, E, filled_words): """ Backfills an embedding matrix with the embedding for the unknown token. :param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`. :param filled_words: these words will not be backfilled with unk. NOTE: this function is for internal use. """ unk_emb = E[self[self._unk]] for i, word in enumerate(self): if word not in filled_words: E[i] = unk_emb
[ "def", "backfill_unk_emb", "(", "self", ",", "E", ",", "filled_words", ")", ":", "unk_emb", "=", "E", "[", "self", "[", "self", ".", "_unk", "]", "]", "for", "i", ",", "word", "in", "enumerate", "(", "self", ")", ":", "if", "word", "not", "in", "filled_words", ":", "E", "[", "i", "]", "=", "unk_emb" ]
Backfills an embedding matrix with the embedding for the unknown token. :param E: original embedding matrix of dimensions `(vocab_size, emb_dim)`. :param filled_words: these words will not be backfilled with unk. NOTE: this function is for internal use.
[ "Backfills", "an", "embedding", "matrix", "with", "the", "embedding", "for", "the", "unknown", "token", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L304-L315
train
stanfordnlp/stanza
stanza/cluster/pick_gpu.py
best_gpu
def best_gpu(max_usage=USAGE_THRESHOLD, verbose=False): ''' Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',... The least-used GPU with usage under the constant threshold will be chosen; ties are broken randomly. ''' try: proc = subprocess.Popen("nvidia-smi", stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = proc.communicate() if error: raise Exception(error) except Exception, e: sys.stderr.write("Couldn't run nvidia-smi to find best GPU, using CPU: %s\n" % str(e)) sys.stderr.write("(This is normal if you have no GPU or haven't configured CUDA.)\n") return "cpu" usages = parse_output(output) pct_usage = [max(u.mem, cpu_backoff(u)) for u in usages] max_usage = min(max_usage, min(pct_usage)) open_gpus = [index for index, usage in enumerate(usages) if max(usage.mem, cpu_backoff(usage)) <= max_usage] if verbose: print('Best GPUs:') for index in open_gpus: print('%d: %s fan, %s mem, %s cpu' % (index, format_percent(usages[index].fan), format_percent(usages[index].mem), format_percent(usages[index].cpu))) if open_gpus: result = "gpu" + str(random.choice(open_gpus)) else: result = "cpu" if verbose: print('Chosen: ' + result) return result
python
def best_gpu(max_usage=USAGE_THRESHOLD, verbose=False): ''' Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',... The least-used GPU with usage under the constant threshold will be chosen; ties are broken randomly. ''' try: proc = subprocess.Popen("nvidia-smi", stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = proc.communicate() if error: raise Exception(error) except Exception, e: sys.stderr.write("Couldn't run nvidia-smi to find best GPU, using CPU: %s\n" % str(e)) sys.stderr.write("(This is normal if you have no GPU or haven't configured CUDA.)\n") return "cpu" usages = parse_output(output) pct_usage = [max(u.mem, cpu_backoff(u)) for u in usages] max_usage = min(max_usage, min(pct_usage)) open_gpus = [index for index, usage in enumerate(usages) if max(usage.mem, cpu_backoff(usage)) <= max_usage] if verbose: print('Best GPUs:') for index in open_gpus: print('%d: %s fan, %s mem, %s cpu' % (index, format_percent(usages[index].fan), format_percent(usages[index].mem), format_percent(usages[index].cpu))) if open_gpus: result = "gpu" + str(random.choice(open_gpus)) else: result = "cpu" if verbose: print('Chosen: ' + result) return result
[ "def", "best_gpu", "(", "max_usage", "=", "USAGE_THRESHOLD", ",", "verbose", "=", "False", ")", ":", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "\"nvidia-smi\"", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "output", ",", "error", "=", "proc", ".", "communicate", "(", ")", "if", "error", ":", "raise", "Exception", "(", "error", ")", "except", "Exception", ",", "e", ":", "sys", ".", "stderr", ".", "write", "(", "\"Couldn't run nvidia-smi to find best GPU, using CPU: %s\\n\"", "%", "str", "(", "e", ")", ")", "sys", ".", "stderr", ".", "write", "(", "\"(This is normal if you have no GPU or haven't configured CUDA.)\\n\"", ")", "return", "\"cpu\"", "usages", "=", "parse_output", "(", "output", ")", "pct_usage", "=", "[", "max", "(", "u", ".", "mem", ",", "cpu_backoff", "(", "u", ")", ")", "for", "u", "in", "usages", "]", "max_usage", "=", "min", "(", "max_usage", ",", "min", "(", "pct_usage", ")", ")", "open_gpus", "=", "[", "index", "for", "index", ",", "usage", "in", "enumerate", "(", "usages", ")", "if", "max", "(", "usage", ".", "mem", ",", "cpu_backoff", "(", "usage", ")", ")", "<=", "max_usage", "]", "if", "verbose", ":", "print", "(", "'Best GPUs:'", ")", "for", "index", "in", "open_gpus", ":", "print", "(", "'%d: %s fan, %s mem, %s cpu'", "%", "(", "index", ",", "format_percent", "(", "usages", "[", "index", "]", ".", "fan", ")", ",", "format_percent", "(", "usages", "[", "index", "]", ".", "mem", ")", ",", "format_percent", "(", "usages", "[", "index", "]", ".", "cpu", ")", ")", ")", "if", "open_gpus", ":", "result", "=", "\"gpu\"", "+", "str", "(", "random", ".", "choice", "(", "open_gpus", ")", ")", "else", ":", "result", "=", "\"cpu\"", "if", "verbose", ":", "print", "(", "'Chosen: '", "+", "result", ")", "return", "result" ]
Return the name of a device to use, either 'cpu' or 'gpu0', 'gpu1',... The least-used GPU with usage under the constant threshold will be chosen; ties are broken randomly.
[ "Return", "the", "name", "of", "a", "device", "to", "use", "either", "cpu", "or", "gpu0", "gpu1", "...", "The", "least", "-", "used", "GPU", "with", "usage", "under", "the", "constant", "threshold", "will", "be", "chosen", ";", "ties", "are", "broken", "randomly", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/cluster/pick_gpu.py#L28-L67
train
stanfordnlp/stanza
stanza/research/evaluate.py
evaluate
def evaluate(learner, eval_data, metrics, metric_names=None, split_id=None, write_data=False): ''' Evaluate `learner` on the instances in `eval_data` according to each metric in `metric`, and return a dictionary summarizing the values of the metrics. Dump the predictions, scores, and metric summaries in JSON format to "{predictions|scores|results}.`split_id`.json" in the run directory. :param learner: The model to be evaluated. :type learner: learner.Learner :param eval_data: The data to use to evaluate the model. :type eval_data: list(instance.Instance) :param metrics: An iterable of functions that defines the standard by which predictions are evaluated. :type metrics: Iterable(function(eval_data: list(instance.Instance), predictions: list(output_type), scores: list(float)) -> list(float)) :param bool write_data: If `True`, write out the instances in `eval_data` as JSON, one per line, to the file `data.<split_id>.jsons`. ''' if metric_names is None: metric_names = [ (metric.__name__ if hasattr(metric, '__name__') else ('m%d' % i)) for i, metric in enumerate(metrics) ] split_prefix = split_id + '.' if split_id else '' if write_data: config.dump([inst.__dict__ for inst in eval_data], 'data.%sjsons' % split_prefix, default=json_default, lines=True) results = {split_prefix + 'num_params': learner.num_params} predictions, scores = learner.predict_and_score(eval_data) config.dump(predictions, 'predictions.%sjsons' % split_prefix, lines=True) config.dump(scores, 'scores.%sjsons' % split_prefix, lines=True) for metric, metric_name in zip(metrics, metric_names): prefix = split_prefix + (metric_name + '.' if metric_name else '') inst_outputs = metric(eval_data, predictions, scores, learner) if metric_name in ['data', 'predictions', 'scores']: warnings.warn('not outputting metric scores for metric "%s" because it would shadow ' 'another results file') else: config.dump(inst_outputs, '%s.%sjsons' % (metric_name, split_prefix), lines=True) mean = np.mean(inst_outputs) gmean = np.exp(np.log(inst_outputs).mean()) sum = np.sum(inst_outputs) std = np.std(inst_outputs) results.update({ prefix + 'mean': mean, prefix + 'gmean': gmean, prefix + 'sum': sum, prefix + 'std': std, # prefix + 'ci_lower': ci_lower, # prefix + 'ci_upper': ci_upper, }) config.dump_pretty(results, 'results.%sjson' % split_prefix) return results
python
def evaluate(learner, eval_data, metrics, metric_names=None, split_id=None, write_data=False): ''' Evaluate `learner` on the instances in `eval_data` according to each metric in `metric`, and return a dictionary summarizing the values of the metrics. Dump the predictions, scores, and metric summaries in JSON format to "{predictions|scores|results}.`split_id`.json" in the run directory. :param learner: The model to be evaluated. :type learner: learner.Learner :param eval_data: The data to use to evaluate the model. :type eval_data: list(instance.Instance) :param metrics: An iterable of functions that defines the standard by which predictions are evaluated. :type metrics: Iterable(function(eval_data: list(instance.Instance), predictions: list(output_type), scores: list(float)) -> list(float)) :param bool write_data: If `True`, write out the instances in `eval_data` as JSON, one per line, to the file `data.<split_id>.jsons`. ''' if metric_names is None: metric_names = [ (metric.__name__ if hasattr(metric, '__name__') else ('m%d' % i)) for i, metric in enumerate(metrics) ] split_prefix = split_id + '.' if split_id else '' if write_data: config.dump([inst.__dict__ for inst in eval_data], 'data.%sjsons' % split_prefix, default=json_default, lines=True) results = {split_prefix + 'num_params': learner.num_params} predictions, scores = learner.predict_and_score(eval_data) config.dump(predictions, 'predictions.%sjsons' % split_prefix, lines=True) config.dump(scores, 'scores.%sjsons' % split_prefix, lines=True) for metric, metric_name in zip(metrics, metric_names): prefix = split_prefix + (metric_name + '.' if metric_name else '') inst_outputs = metric(eval_data, predictions, scores, learner) if metric_name in ['data', 'predictions', 'scores']: warnings.warn('not outputting metric scores for metric "%s" because it would shadow ' 'another results file') else: config.dump(inst_outputs, '%s.%sjsons' % (metric_name, split_prefix), lines=True) mean = np.mean(inst_outputs) gmean = np.exp(np.log(inst_outputs).mean()) sum = np.sum(inst_outputs) std = np.std(inst_outputs) results.update({ prefix + 'mean': mean, prefix + 'gmean': gmean, prefix + 'sum': sum, prefix + 'std': std, # prefix + 'ci_lower': ci_lower, # prefix + 'ci_upper': ci_upper, }) config.dump_pretty(results, 'results.%sjson' % split_prefix) return results
[ "def", "evaluate", "(", "learner", ",", "eval_data", ",", "metrics", ",", "metric_names", "=", "None", ",", "split_id", "=", "None", ",", "write_data", "=", "False", ")", ":", "if", "metric_names", "is", "None", ":", "metric_names", "=", "[", "(", "metric", ".", "__name__", "if", "hasattr", "(", "metric", ",", "'__name__'", ")", "else", "(", "'m%d'", "%", "i", ")", ")", "for", "i", ",", "metric", "in", "enumerate", "(", "metrics", ")", "]", "split_prefix", "=", "split_id", "+", "'.'", "if", "split_id", "else", "''", "if", "write_data", ":", "config", ".", "dump", "(", "[", "inst", ".", "__dict__", "for", "inst", "in", "eval_data", "]", ",", "'data.%sjsons'", "%", "split_prefix", ",", "default", "=", "json_default", ",", "lines", "=", "True", ")", "results", "=", "{", "split_prefix", "+", "'num_params'", ":", "learner", ".", "num_params", "}", "predictions", ",", "scores", "=", "learner", ".", "predict_and_score", "(", "eval_data", ")", "config", ".", "dump", "(", "predictions", ",", "'predictions.%sjsons'", "%", "split_prefix", ",", "lines", "=", "True", ")", "config", ".", "dump", "(", "scores", ",", "'scores.%sjsons'", "%", "split_prefix", ",", "lines", "=", "True", ")", "for", "metric", ",", "metric_name", "in", "zip", "(", "metrics", ",", "metric_names", ")", ":", "prefix", "=", "split_prefix", "+", "(", "metric_name", "+", "'.'", "if", "metric_name", "else", "''", ")", "inst_outputs", "=", "metric", "(", "eval_data", ",", "predictions", ",", "scores", ",", "learner", ")", "if", "metric_name", "in", "[", "'data'", ",", "'predictions'", ",", "'scores'", "]", ":", "warnings", ".", "warn", "(", "'not outputting metric scores for metric \"%s\" because it would shadow '", "'another results file'", ")", "else", ":", "config", ".", "dump", "(", "inst_outputs", ",", "'%s.%sjsons'", "%", "(", "metric_name", ",", "split_prefix", ")", ",", "lines", "=", "True", ")", "mean", "=", "np", ".", "mean", "(", "inst_outputs", ")", "gmean", "=", "np", ".", "exp", "(", "np", ".", "log", "(", "inst_outputs", ")", ".", "mean", "(", ")", ")", "sum", "=", "np", ".", "sum", "(", "inst_outputs", ")", "std", "=", "np", ".", "std", "(", "inst_outputs", ")", "results", ".", "update", "(", "{", "prefix", "+", "'mean'", ":", "mean", ",", "prefix", "+", "'gmean'", ":", "gmean", ",", "prefix", "+", "'sum'", ":", "sum", ",", "prefix", "+", "'std'", ":", "std", ",", "# prefix + 'ci_lower': ci_lower,", "# prefix + 'ci_upper': ci_upper,", "}", ")", "config", ".", "dump_pretty", "(", "results", ",", "'results.%sjson'", "%", "split_prefix", ")", "return", "results" ]
Evaluate `learner` on the instances in `eval_data` according to each metric in `metric`, and return a dictionary summarizing the values of the metrics. Dump the predictions, scores, and metric summaries in JSON format to "{predictions|scores|results}.`split_id`.json" in the run directory. :param learner: The model to be evaluated. :type learner: learner.Learner :param eval_data: The data to use to evaluate the model. :type eval_data: list(instance.Instance) :param metrics: An iterable of functions that defines the standard by which predictions are evaluated. :type metrics: Iterable(function(eval_data: list(instance.Instance), predictions: list(output_type), scores: list(float)) -> list(float)) :param bool write_data: If `True`, write out the instances in `eval_data` as JSON, one per line, to the file `data.<split_id>.jsons`.
[ "Evaluate", "learner", "on", "the", "instances", "in", "eval_data", "according", "to", "each", "metric", "in", "metric", "and", "return", "a", "dictionary", "summarizing", "the", "values", "of", "the", "metrics", "." ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/evaluate.py#L7-L78
train
stanfordnlp/stanza
stanza/nlp/protobuf_json.py
json2pb
def json2pb(pb, js, useFieldNumber=False): ''' convert JSON string to google.protobuf.descriptor instance ''' for field in pb.DESCRIPTOR.fields: if useFieldNumber: key = field.number else: key = field.name if key not in js: continue if field.type == FD.TYPE_MESSAGE: pass elif field.type in _js2ftype: ftype = _js2ftype[field.type] else: raise ParseError("Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type, )) value = js[key] if field.label == FD.LABEL_REPEATED: pb_value = getattr(pb, field.name, None) for v in value: if field.type == FD.TYPE_MESSAGE: json2pb(pb_value.add(), v, useFieldNumber=useFieldNumber) else: pb_value.append(ftype(v)) else: if field.type == FD.TYPE_MESSAGE: json2pb(getattr(pb, field.name, None), value, useFieldNumber=useFieldNumber) else: setattr(pb, field.name, ftype(value)) return pb
python
def json2pb(pb, js, useFieldNumber=False): ''' convert JSON string to google.protobuf.descriptor instance ''' for field in pb.DESCRIPTOR.fields: if useFieldNumber: key = field.number else: key = field.name if key not in js: continue if field.type == FD.TYPE_MESSAGE: pass elif field.type in _js2ftype: ftype = _js2ftype[field.type] else: raise ParseError("Field %s.%s of type '%d' is not supported" % (pb.__class__.__name__, field.name, field.type, )) value = js[key] if field.label == FD.LABEL_REPEATED: pb_value = getattr(pb, field.name, None) for v in value: if field.type == FD.TYPE_MESSAGE: json2pb(pb_value.add(), v, useFieldNumber=useFieldNumber) else: pb_value.append(ftype(v)) else: if field.type == FD.TYPE_MESSAGE: json2pb(getattr(pb, field.name, None), value, useFieldNumber=useFieldNumber) else: setattr(pb, field.name, ftype(value)) return pb
[ "def", "json2pb", "(", "pb", ",", "js", ",", "useFieldNumber", "=", "False", ")", ":", "for", "field", "in", "pb", ".", "DESCRIPTOR", ".", "fields", ":", "if", "useFieldNumber", ":", "key", "=", "field", ".", "number", "else", ":", "key", "=", "field", ".", "name", "if", "key", "not", "in", "js", ":", "continue", "if", "field", ".", "type", "==", "FD", ".", "TYPE_MESSAGE", ":", "pass", "elif", "field", ".", "type", "in", "_js2ftype", ":", "ftype", "=", "_js2ftype", "[", "field", ".", "type", "]", "else", ":", "raise", "ParseError", "(", "\"Field %s.%s of type '%d' is not supported\"", "%", "(", "pb", ".", "__class__", ".", "__name__", ",", "field", ".", "name", ",", "field", ".", "type", ",", ")", ")", "value", "=", "js", "[", "key", "]", "if", "field", ".", "label", "==", "FD", ".", "LABEL_REPEATED", ":", "pb_value", "=", "getattr", "(", "pb", ",", "field", ".", "name", ",", "None", ")", "for", "v", "in", "value", ":", "if", "field", ".", "type", "==", "FD", ".", "TYPE_MESSAGE", ":", "json2pb", "(", "pb_value", ".", "add", "(", ")", ",", "v", ",", "useFieldNumber", "=", "useFieldNumber", ")", "else", ":", "pb_value", ".", "append", "(", "ftype", "(", "v", ")", ")", "else", ":", "if", "field", ".", "type", "==", "FD", ".", "TYPE_MESSAGE", ":", "json2pb", "(", "getattr", "(", "pb", ",", "field", ".", "name", ",", "None", ")", ",", "value", ",", "useFieldNumber", "=", "useFieldNumber", ")", "else", ":", "setattr", "(", "pb", ",", "field", ".", "name", ",", "ftype", "(", "value", ")", ")", "return", "pb" ]
convert JSON string to google.protobuf.descriptor instance
[ "convert", "JSON", "string", "to", "google", ".", "protobuf", ".", "descriptor", "instance" ]
920c55d8eaa1e7105971059c66eb448a74c100d6
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/nlp/protobuf_json.py#L51-L79
train