repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
CZ-NIC/python-rt | rt.py | Rt.get_attachments_ids | def get_attachments_ids(self, ticket_id):
""" Get IDs of attachments for given ticket.
:param ticket_id: ID of ticket
:returns: List of IDs (type int) of attachments belonging to given
ticket. Returns None if ticket does not exist.
"""
attachments = self.get_attachments(ticket_id)
return [int(at[0]) for at in attachments] if attachments else attachments | python | def get_attachments_ids(self, ticket_id):
attachments = self.get_attachments(ticket_id)
return [int(at[0]) for at in attachments] if attachments else attachments | [
"def",
"get_attachments_ids",
"(",
"self",
",",
"ticket_id",
")",
":",
"attachments",
"=",
"self",
".",
"get_attachments",
"(",
"ticket_id",
")",
"return",
"[",
"int",
"(",
"at",
"[",
"0",
"]",
")",
"for",
"at",
"in",
"attachments",
"]",
"if",
"attachments",
"else",
"attachments"
]
| Get IDs of attachments for given ticket.
:param ticket_id: ID of ticket
:returns: List of IDs (type int) of attachments belonging to given
ticket. Returns None if ticket does not exist. | [
"Get",
"IDs",
"of",
"attachments",
"for",
"given",
"ticket",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L953-L961 |
CZ-NIC/python-rt | rt.py | Rt.get_attachment | def get_attachment(self, ticket_id, attachment_id):
""" Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
* Parent
* Creator
* Created
* Filename
* Content (bytes type)
* Headers
* MessageId
* ContentEncoding
* id
* Subject
All these fields are strings, just 'Headers' holds another
dictionary with attachment headers as strings e.g.:
* Delivered-To
* From
* Return-Path
* Content-Length
* To
* X-Seznam-User
* X-QM-Mark
* Domainkey-Signature
* RT-Message-ID
* X-RT-Incoming-Encryption
* X-Original-To
* Message-ID
* X-Spam-Status
* In-Reply-To
* Date
* Received
* X-Country
* X-Spam-Checker-Version
* X-Abuse
* MIME-Version
* Content-Type
* Subject
.. warning:: Content-Length parameter is set after opening
ticket in web interface!
Set of headers available depends on mailservers sending
emails not on Request Tracker!
Returns None if ticket or attachment does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message.
"""
msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)),
text_response=False)
msg = msg.split(b'\n')
if (len(msg) > 2) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])):
return None
msg = msg[2:]
head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)]
head_id = head_matching[0] if head_matching else None
if not head_id:
raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \
Missing line starting with `Headers:`.')
msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id])
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_matching:
raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \
Missing line starting with `Content:`.')
pairs = {}
for i in range(head_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
headers = {}
for i in range(head_id, cont_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
pairs['Headers'] = headers
content = msg[cont_id][9:]
for i in range(cont_id + 1, len(msg)):
if msg[i][:9] == (b' ' * 9):
content += b'\n' + msg[i][9:]
pairs['Content'] = content
return pairs | python | def get_attachment(self, ticket_id, attachment_id):
msg = self.__request('ticket/{}/attachments/{}'.format(str(ticket_id), str(attachment_id)),
text_response=False)
msg = msg.split(b'\n')
if (len(msg) > 2) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(msg[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(msg[2])):
return None
msg = msg[2:]
head_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['headers_pattern_bytes'].match(m)]
head_id = head_matching[0] if head_matching else None
if not head_id:
raise UnexpectedMessageFormat('Unexpected headers part of attachment entry. \
Missing line starting with `Headers:`.')
msg[head_id] = re.sub(b'^Headers: (.*)$', r'\1', msg[head_id])
cont_matching = [i for i, m in enumerate(msg) if self.RE_PATTERNS['content_pattern_bytes'].match(m)]
cont_id = cont_matching[0] if cont_matching else None
if not cont_matching:
raise UnexpectedMessageFormat('Unexpected content part of attachment entry. \
Missing line starting with `Content:`.')
pairs = {}
for i in range(head_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
pairs[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
headers = {}
for i in range(head_id, cont_id):
if b': ' in msg[i]:
header, content = msg[i].split(b': ', 1)
headers[header.strip().decode('utf-8')] = content.strip().decode('utf-8')
pairs['Headers'] = headers
content = msg[cont_id][9:]
for i in range(cont_id + 1, len(msg)):
if msg[i][:9] == (b' ' * 9):
content += b'\n' + msg[i][9:]
pairs['Content'] = content
return pairs | [
"def",
"get_attachment",
"(",
"self",
",",
"ticket_id",
",",
"attachment_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments/{}'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"attachment_id",
")",
")",
",",
"text_response",
"=",
"False",
")",
"msg",
"=",
"msg",
".",
"split",
"(",
"b'\\n'",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'invalid_attachment_pattern_bytes'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern_bytes'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"msg",
"=",
"msg",
"[",
"2",
":",
"]",
"head_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'headers_pattern_bytes'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"head_id",
"=",
"head_matching",
"[",
"0",
"]",
"if",
"head_matching",
"else",
"None",
"if",
"not",
"head_id",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected headers part of attachment entry. \\\n Missing line starting with `Headers:`.'",
")",
"msg",
"[",
"head_id",
"]",
"=",
"re",
".",
"sub",
"(",
"b'^Headers: (.*)$'",
",",
"r'\\1'",
",",
"msg",
"[",
"head_id",
"]",
")",
"cont_matching",
"=",
"[",
"i",
"for",
"i",
",",
"m",
"in",
"enumerate",
"(",
"msg",
")",
"if",
"self",
".",
"RE_PATTERNS",
"[",
"'content_pattern_bytes'",
"]",
".",
"match",
"(",
"m",
")",
"]",
"cont_id",
"=",
"cont_matching",
"[",
"0",
"]",
"if",
"cont_matching",
"else",
"None",
"if",
"not",
"cont_matching",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Unexpected content part of attachment entry. \\\n Missing line starting with `Content:`.'",
")",
"pairs",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"head_id",
")",
":",
"if",
"b': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"msg",
"[",
"i",
"]",
".",
"split",
"(",
"b': '",
",",
"1",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"headers",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"head_id",
",",
"cont_id",
")",
":",
"if",
"b': '",
"in",
"msg",
"[",
"i",
"]",
":",
"header",
",",
"content",
"=",
"msg",
"[",
"i",
"]",
".",
"split",
"(",
"b': '",
",",
"1",
")",
"headers",
"[",
"header",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"pairs",
"[",
"'Headers'",
"]",
"=",
"headers",
"content",
"=",
"msg",
"[",
"cont_id",
"]",
"[",
"9",
":",
"]",
"for",
"i",
"in",
"range",
"(",
"cont_id",
"+",
"1",
",",
"len",
"(",
"msg",
")",
")",
":",
"if",
"msg",
"[",
"i",
"]",
"[",
":",
"9",
"]",
"==",
"(",
"b' '",
"*",
"9",
")",
":",
"content",
"+=",
"b'\\n'",
"+",
"msg",
"[",
"i",
"]",
"[",
"9",
":",
"]",
"pairs",
"[",
"'Content'",
"]",
"=",
"content",
"return",
"pairs"
]
| Get attachment.
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment for obtain
:returns: Attachment as dictionary with these keys:
* Transaction
* ContentType
* Parent
* Creator
* Created
* Filename
* Content (bytes type)
* Headers
* MessageId
* ContentEncoding
* id
* Subject
All these fields are strings, just 'Headers' holds another
dictionary with attachment headers as strings e.g.:
* Delivered-To
* From
* Return-Path
* Content-Length
* To
* X-Seznam-User
* X-QM-Mark
* Domainkey-Signature
* RT-Message-ID
* X-RT-Incoming-Encryption
* X-Original-To
* Message-ID
* X-Spam-Status
* In-Reply-To
* Date
* Received
* X-Country
* X-Spam-Checker-Version
* X-Abuse
* MIME-Version
* Content-Type
* Subject
.. warning:: Content-Length parameter is set after opening
ticket in web interface!
Set of headers available depends on mailservers sending
emails not on Request Tracker!
Returns None if ticket or attachment does not exist.
:raises UnexpectedMessageFormat: Unexpected format of returned message. | [
"Get",
"attachment",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L963-L1051 |
CZ-NIC/python-rt | rt.py | Rt.get_attachment_content | def get_attachment_content(self, ticket_id, attachment_id):
""" Get content of attachment without headers.
This function is necessary to use for binary attachment,
as it can contain ``\\n`` chars, which would disrupt parsing
of message if :py:meth:`~Rt.get_attachment` is used.
Format of message::
RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment
Returns: Bytes with content of attachment or None if ticket or
attachment does not exist.
"""
msg = self.__request('ticket/{}/attachments/{}/content'.format
(str(ticket_id), str(attachment_id)),
text_response=False)
lines = msg.split(b'\n', 3)
if (len(lines) == 4) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])):
return None
return msg[msg.find(b'\n') + 2:-3] | python | def get_attachment_content(self, ticket_id, attachment_id):
msg = self.__request('ticket/{}/attachments/{}/content'.format
(str(ticket_id), str(attachment_id)),
text_response=False)
lines = msg.split(b'\n', 3)
if (len(lines) == 4) and (self.RE_PATTERNS['invalid_attachment_pattern_bytes'].match(lines[2]) or self.RE_PATTERNS['does_not_exist_pattern_bytes'].match(lines[2])):
return None
return msg[msg.find(b'\n') + 2:-3] | [
"def",
"get_attachment_content",
"(",
"self",
",",
"ticket_id",
",",
"attachment_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/attachments/{}/content'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"attachment_id",
")",
")",
",",
"text_response",
"=",
"False",
")",
"lines",
"=",
"msg",
".",
"split",
"(",
"b'\\n'",
",",
"3",
")",
"if",
"(",
"len",
"(",
"lines",
")",
"==",
"4",
")",
"and",
"(",
"self",
".",
"RE_PATTERNS",
"[",
"'invalid_attachment_pattern_bytes'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
"or",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern_bytes'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
")",
":",
"return",
"None",
"return",
"msg",
"[",
"msg",
".",
"find",
"(",
"b'\\n'",
")",
"+",
"2",
":",
"-",
"3",
"]"
]
| Get content of attachment without headers.
This function is necessary to use for binary attachment,
as it can contain ``\\n`` chars, which would disrupt parsing
of message if :py:meth:`~Rt.get_attachment` is used.
Format of message::
RT/3.8.7 200 Ok\n\nStart of the content...End of the content\n\n\n
:param ticket_id: ID of ticket
:param attachment_id: ID of attachment
Returns: Bytes with content of attachment or None if ticket or
attachment does not exist. | [
"Get",
"content",
"of",
"attachment",
"without",
"headers",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1053-L1077 |
CZ-NIC/python-rt | rt.py | Rt.get_user | def get_user(self, user_id):
""" Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
* RealName
* Privileged
* Disabled
* Gecos
* EmailAddress
* Password
* id
* Name
Or these keys for external users (e.g. Requestors replying
to email from RT:
* RealName
* Disabled
* EmailAddress
* Password
* id
* Name
None is returned if user does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200
"""
msg = self.__request('user/{}'.format(str(user_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
for line in lines[2:]:
if ': ' in line:
header, content = line.split(': ', 1)
pairs[header.strip()] = content.strip()
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | python | def get_user(self, user_id):
msg = self.__request('user/{}'.format(str(user_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
lines = msg.split('\n')
if (len(lines) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(lines[2]):
return None
for line in lines[2:]:
if ': ' in line:
header, content = line.split(': ', 1)
pairs[header.strip()] = content.strip()
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | [
"def",
"get_user",
"(",
"self",
",",
"user_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'user/{}'",
".",
"format",
"(",
"str",
"(",
"user_id",
")",
",",
")",
")",
"status_code",
"=",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"if",
"(",
"status_code",
"==",
"200",
")",
":",
"pairs",
"=",
"{",
"}",
"lines",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"lines",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"lines",
"[",
"2",
"]",
")",
":",
"return",
"None",
"for",
"line",
"in",
"lines",
"[",
"2",
":",
"]",
":",
"if",
"': '",
"in",
"line",
":",
"header",
",",
"content",
"=",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")",
"pairs",
"[",
"header",
".",
"strip",
"(",
")",
"]",
"=",
"content",
".",
"strip",
"(",
")",
"return",
"pairs",
"else",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Received status code is {:d} instead of 200.'",
".",
"format",
"(",
"status_code",
")",
")"
]
| Get user details.
:param user_id: Identification of user by username (str) or user ID
(int)
:returns: User details as strings in dictionary with these keys for RT
users:
* Lang
* RealName
* Privileged
* Disabled
* Gecos
* EmailAddress
* Password
* id
* Name
Or these keys for external users (e.g. Requestors replying
to email from RT:
* RealName
* Disabled
* EmailAddress
* Password
* id
* Name
None is returned if user does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200 | [
"Get",
"user",
"details",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1079-L1123 |
CZ-NIC/python-rt | rt.py | Rt.create_user | def create_user(self, Name, EmailAddress, **kwargs):
""" Create user (undocumented API feature).
:param Name: User name (login for privileged, required)
:param EmailAddress: Email address (required)
:param kwargs: Optional fields to set (see edit_user)
:returns: ID of new user or False when create fails
:raises BadRequest: When user already exists
:raises InvalidUse: When invalid fields are set
"""
return self.edit_user('new', Name=Name, EmailAddress=EmailAddress, **kwargs) | python | def create_user(self, Name, EmailAddress, **kwargs):
return self.edit_user('new', Name=Name, EmailAddress=EmailAddress, **kwargs) | [
"def",
"create_user",
"(",
"self",
",",
"Name",
",",
"EmailAddress",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"edit_user",
"(",
"'new'",
",",
"Name",
"=",
"Name",
",",
"EmailAddress",
"=",
"EmailAddress",
",",
"*",
"*",
"kwargs",
")"
]
| Create user (undocumented API feature).
:param Name: User name (login for privileged, required)
:param EmailAddress: Email address (required)
:param kwargs: Optional fields to set (see edit_user)
:returns: ID of new user or False when create fails
:raises BadRequest: When user already exists
:raises InvalidUse: When invalid fields are set | [
"Create",
"user",
"(",
"undocumented",
"API",
"feature",
")",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1125-L1136 |
CZ-NIC/python-rt | rt.py | Rt.edit_queue | def edit_queue(self, queue_id, **kwargs):
""" Edit queue (undocumented API feature).
:param queue_id: Identification of queue by name (str) or ID (int)
:param kwargs: Other fields to edit from the following list:
* Name
* Description
* CorrespondAddress
* CommentAddress
* InitialPriority
* FinalPriority
* DefaultDueIn
:returns: ID or name of edited queue or False when edit fails
:raises BadRequest: When queue does not exist
:raises InvalidUse: When invalid fields are set
"""
valid_fields = set(
('name', 'description', 'correspondaddress', 'commentaddress', 'initialpriority', 'finalpriority', 'defaultduein'))
used_fields = set(map(lambda x: x.lower(), kwargs.keys()))
if not used_fields <= valid_fields:
invalid_fields = ", ".join(list(used_fields - valid_fields))
raise InvalidUse("Unsupported names of fields: {}.".format(invalid_fields))
post_data = 'id: queue/{}\n'.format(str(queue_id))
for key, val in iteritems(kwargs):
post_data += '{}: {}\n'.format(key, val)
msg = self.__request('edit', post_data={'content': post_data})
msgs = msg.split('\n')
if (self.__get_status_code(msg) == 200) and (len(msgs) > 2):
match = self.RE_PATTERNS['queue_pattern'].match(msgs[2])
if match:
return match.group(1)
return False | python | def edit_queue(self, queue_id, **kwargs):
valid_fields = set(
('name', 'description', 'correspondaddress', 'commentaddress', 'initialpriority', 'finalpriority', 'defaultduein'))
used_fields = set(map(lambda x: x.lower(), kwargs.keys()))
if not used_fields <= valid_fields:
invalid_fields = ", ".join(list(used_fields - valid_fields))
raise InvalidUse("Unsupported names of fields: {}.".format(invalid_fields))
post_data = 'id: queue/{}\n'.format(str(queue_id))
for key, val in iteritems(kwargs):
post_data += '{}: {}\n'.format(key, val)
msg = self.__request('edit', post_data={'content': post_data})
msgs = msg.split('\n')
if (self.__get_status_code(msg) == 200) and (len(msgs) > 2):
match = self.RE_PATTERNS['queue_pattern'].match(msgs[2])
if match:
return match.group(1)
return False | [
"def",
"edit_queue",
"(",
"self",
",",
"queue_id",
",",
"*",
"*",
"kwargs",
")",
":",
"valid_fields",
"=",
"set",
"(",
"(",
"'name'",
",",
"'description'",
",",
"'correspondaddress'",
",",
"'commentaddress'",
",",
"'initialpriority'",
",",
"'finalpriority'",
",",
"'defaultduein'",
")",
")",
"used_fields",
"=",
"set",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"lower",
"(",
")",
",",
"kwargs",
".",
"keys",
"(",
")",
")",
")",
"if",
"not",
"used_fields",
"<=",
"valid_fields",
":",
"invalid_fields",
"=",
"\", \"",
".",
"join",
"(",
"list",
"(",
"used_fields",
"-",
"valid_fields",
")",
")",
"raise",
"InvalidUse",
"(",
"\"Unsupported names of fields: {}.\"",
".",
"format",
"(",
"invalid_fields",
")",
")",
"post_data",
"=",
"'id: queue/{}\\n'",
".",
"format",
"(",
"str",
"(",
"queue_id",
")",
")",
"for",
"key",
",",
"val",
"in",
"iteritems",
"(",
"kwargs",
")",
":",
"post_data",
"+=",
"'{}: {}\\n'",
".",
"format",
"(",
"key",
",",
"val",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'edit'",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
")",
"msgs",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"==",
"200",
")",
"and",
"(",
"len",
"(",
"msgs",
")",
">",
"2",
")",
":",
"match",
"=",
"self",
".",
"RE_PATTERNS",
"[",
"'queue_pattern'",
"]",
".",
"match",
"(",
"msgs",
"[",
"2",
"]",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
")",
"return",
"False"
]
| Edit queue (undocumented API feature).
:param queue_id: Identification of queue by name (str) or ID (int)
:param kwargs: Other fields to edit from the following list:
* Name
* Description
* CorrespondAddress
* CommentAddress
* InitialPriority
* FinalPriority
* DefaultDueIn
:returns: ID or name of edited queue or False when edit fails
:raises BadRequest: When queue does not exist
:raises InvalidUse: When invalid fields are set | [
"Edit",
"queue",
"(",
"undocumented",
"API",
"feature",
")",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1237-L1272 |
CZ-NIC/python-rt | rt.py | Rt.create_queue | def create_queue(self, Name, **kwargs):
""" Create queue (undocumented API feature).
:param Name: Queue name (required)
:param kwargs: Optional fields to set (see edit_queue)
:returns: ID of new queue or False when create fails
:raises BadRequest: When queue already exists
:raises InvalidUse: When invalid fields are set
"""
return int(self.edit_queue('new', Name=Name, **kwargs)) | python | def create_queue(self, Name, **kwargs):
return int(self.edit_queue('new', Name=Name, **kwargs)) | [
"def",
"create_queue",
"(",
"self",
",",
"Name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"int",
"(",
"self",
".",
"edit_queue",
"(",
"'new'",
",",
"Name",
"=",
"Name",
",",
"*",
"*",
"kwargs",
")",
")"
]
| Create queue (undocumented API feature).
:param Name: Queue name (required)
:param kwargs: Optional fields to set (see edit_queue)
:returns: ID of new queue or False when create fails
:raises BadRequest: When queue already exists
:raises InvalidUse: When invalid fields are set | [
"Create",
"queue",
"(",
"undocumented",
"API",
"feature",
")",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1274-L1284 |
CZ-NIC/python-rt | rt.py | Rt.get_links | def get_links(self, ticket_id):
""" Gets the ticket links for a single ticket.
:param ticket_id: ticket ID
:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):
* id
* Members
* MemberOf
* RefersTo
* ReferredToBy
* DependsOn
* DependedOnBy
None is returned if ticket does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200
"""
msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
msg = msg.split('\n')
if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]):
return None
i = 2
while i < len(msg):
if ': ' in msg[i]:
key, link = self.split_header(msg[i])
links = [link.strip()]
j = i + 1
pad = len(key) + 2
# loop over next lines for the same key
while (j < len(msg)) and msg[j].startswith(' ' * pad):
links[-1] = links[-1][:-1] # remove trailing comma from previous item
links.append(msg[j][pad:].strip())
j += 1
pairs[key] = links
i = j - 1
i += 1
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | python | def get_links(self, ticket_id):
msg = self.__request('ticket/{}/links/show'.format(str(ticket_id), ))
status_code = self.__get_status_code(msg)
if (status_code == 200):
pairs = {}
msg = msg.split('\n')
if (len(msg) > 2) and self.RE_PATTERNS['does_not_exist_pattern'].match(msg[2]):
return None
i = 2
while i < len(msg):
if ': ' in msg[i]:
key, link = self.split_header(msg[i])
links = [link.strip()]
j = i + 1
pad = len(key) + 2
while (j < len(msg)) and msg[j].startswith(' ' * pad):
links[-1] = links[-1][:-1]
links.append(msg[j][pad:].strip())
j += 1
pairs[key] = links
i = j - 1
i += 1
return pairs
else:
raise UnexpectedMessageFormat('Received status code is {:d} instead of 200.'.format(status_code)) | [
"def",
"get_links",
"(",
"self",
",",
"ticket_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/links/show'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
")",
"status_code",
"=",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"if",
"(",
"status_code",
"==",
"200",
")",
":",
"pairs",
"=",
"{",
"}",
"msg",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"if",
"(",
"len",
"(",
"msg",
")",
">",
"2",
")",
"and",
"self",
".",
"RE_PATTERNS",
"[",
"'does_not_exist_pattern'",
"]",
".",
"match",
"(",
"msg",
"[",
"2",
"]",
")",
":",
"return",
"None",
"i",
"=",
"2",
"while",
"i",
"<",
"len",
"(",
"msg",
")",
":",
"if",
"': '",
"in",
"msg",
"[",
"i",
"]",
":",
"key",
",",
"link",
"=",
"self",
".",
"split_header",
"(",
"msg",
"[",
"i",
"]",
")",
"links",
"=",
"[",
"link",
".",
"strip",
"(",
")",
"]",
"j",
"=",
"i",
"+",
"1",
"pad",
"=",
"len",
"(",
"key",
")",
"+",
"2",
"# loop over next lines for the same key",
"while",
"(",
"j",
"<",
"len",
"(",
"msg",
")",
")",
"and",
"msg",
"[",
"j",
"]",
".",
"startswith",
"(",
"' '",
"*",
"pad",
")",
":",
"links",
"[",
"-",
"1",
"]",
"=",
"links",
"[",
"-",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"# remove trailing comma from previous item",
"links",
".",
"append",
"(",
"msg",
"[",
"j",
"]",
"[",
"pad",
":",
"]",
".",
"strip",
"(",
")",
")",
"j",
"+=",
"1",
"pairs",
"[",
"key",
"]",
"=",
"links",
"i",
"=",
"j",
"-",
"1",
"i",
"+=",
"1",
"return",
"pairs",
"else",
":",
"raise",
"UnexpectedMessageFormat",
"(",
"'Received status code is {:d} instead of 200.'",
".",
"format",
"(",
"status_code",
")",
")"
]
| Gets the ticket links for a single ticket.
:param ticket_id: ticket ID
:returns: Links as lists of strings in dictionary with these keys
(just those which are defined):
* id
* Members
* MemberOf
* RefersTo
* ReferredToBy
* DependsOn
* DependedOnBy
None is returned if ticket does not exist.
:raises UnexpectedMessageFormat: In case that returned status code is not 200 | [
"Gets",
"the",
"ticket",
"links",
"for",
"a",
"single",
"ticket",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1286-L1329 |
CZ-NIC/python-rt | rt.py | Rt.edit_ticket_links | def edit_ticket_links(self, ticket_id, **kwargs):
""" Edit ticket links.
.. warning:: This method is deprecated in favour of edit_link method, because
there exists bug in RT 3.8 REST API causing mapping created links to
ticket/1. The only drawback is that edit_link cannot process multiple
links all at once.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set: DependsOn,
DependedOnBy, RefersTo, ReferredToBy, Members,
MemberOf. Each value should be either ticker ID or
external link. Int types are converted. Use empty
string as value to delete existing link.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed)
"""
post_data = ''
for key in kwargs:
post_data += "{}: {}\n".format(key, str(kwargs[key]))
msg = self.__request('ticket/{}/links'.format(str(ticket_id), ),
post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None | python | def edit_ticket_links(self, ticket_id, **kwargs):
post_data = ''
for key in kwargs:
post_data += "{}: {}\n".format(key, str(kwargs[key]))
msg = self.__request('ticket/{}/links'.format(str(ticket_id), ),
post_data={'content': post_data})
state = msg.split('\n')[2]
return self.RE_PATTERNS['links_updated_pattern'].match(state) is not None | [
"def",
"edit_ticket_links",
"(",
"self",
",",
"ticket_id",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"''",
"for",
"key",
"in",
"kwargs",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"str",
"(",
"kwargs",
"[",
"key",
"]",
")",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/links'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
")",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'links_updated_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
]
| Edit ticket links.
.. warning:: This method is deprecated in favour of edit_link method, because
there exists bug in RT 3.8 REST API causing mapping created links to
ticket/1. The only drawback is that edit_link cannot process multiple
links all at once.
:param ticket_id: ID of ticket to edit
:keyword kwargs: Other arguments possible to set: DependsOn,
DependedOnBy, RefersTo, ReferredToBy, Members,
MemberOf. Each value should be either ticker ID or
external link. Int types are converted. Use empty
string as value to delete existing link.
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or unknown parameter
was set (in this case all other valid fields are changed) | [
"Edit",
"ticket",
"links",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1331-L1357 |
CZ-NIC/python-rt | rt.py | Rt.edit_link | def edit_link(self, ticket_id, link_name, link_value, delete=False):
""" Creates or deletes a link between the specified tickets (undocumented API feature).
:param ticket_id: ID of ticket to edit
:param link_name: Name of link to edit (DependsOn, DependedOnBy,
RefersTo, ReferredToBy, HasMember or MemberOf)
:param link_value: Either ticker ID or external link.
:param delete: if True the link is deleted instead of created
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or link to delete is
not found
:raises InvalidUse: When none or more then one links are specified. Also
when wrong link name is used.
"""
valid_link_names = set(('dependson', 'dependedonby', 'refersto',
'referredtoby', 'hasmember', 'memberof'))
if not link_name.lower() in valid_link_names:
raise InvalidUse("Unsupported name of link.")
post_data = {'rel': link_name.lower(),
'to': link_value,
'id': ticket_id,
'del': 1 if delete else 0
}
msg = self.__request('ticket/link', post_data=post_data)
state = msg.split('\n')[2]
if delete:
return self.RE_PATTERNS['deleted_link_pattern'].match(state) is not None
else:
return self.RE_PATTERNS['created_link_pattern'].match(state) is not None | python | def edit_link(self, ticket_id, link_name, link_value, delete=False):
valid_link_names = set(('dependson', 'dependedonby', 'refersto',
'referredtoby', 'hasmember', 'memberof'))
if not link_name.lower() in valid_link_names:
raise InvalidUse("Unsupported name of link.")
post_data = {'rel': link_name.lower(),
'to': link_value,
'id': ticket_id,
'del': 1 if delete else 0
}
msg = self.__request('ticket/link', post_data=post_data)
state = msg.split('\n')[2]
if delete:
return self.RE_PATTERNS['deleted_link_pattern'].match(state) is not None
else:
return self.RE_PATTERNS['created_link_pattern'].match(state) is not None | [
"def",
"edit_link",
"(",
"self",
",",
"ticket_id",
",",
"link_name",
",",
"link_value",
",",
"delete",
"=",
"False",
")",
":",
"valid_link_names",
"=",
"set",
"(",
"(",
"'dependson'",
",",
"'dependedonby'",
",",
"'refersto'",
",",
"'referredtoby'",
",",
"'hasmember'",
",",
"'memberof'",
")",
")",
"if",
"not",
"link_name",
".",
"lower",
"(",
")",
"in",
"valid_link_names",
":",
"raise",
"InvalidUse",
"(",
"\"Unsupported name of link.\"",
")",
"post_data",
"=",
"{",
"'rel'",
":",
"link_name",
".",
"lower",
"(",
")",
",",
"'to'",
":",
"link_value",
",",
"'id'",
":",
"ticket_id",
",",
"'del'",
":",
"1",
"if",
"delete",
"else",
"0",
"}",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/link'",
",",
"post_data",
"=",
"post_data",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"if",
"delete",
":",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'deleted_link_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None",
"else",
":",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'created_link_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
]
| Creates or deletes a link between the specified tickets (undocumented API feature).
:param ticket_id: ID of ticket to edit
:param link_name: Name of link to edit (DependsOn, DependedOnBy,
RefersTo, ReferredToBy, HasMember or MemberOf)
:param link_value: Either ticker ID or external link.
:param delete: if True the link is deleted instead of created
:returns: ``True``
Operation was successful
``False``
Ticket with given ID does not exist or link to delete is
not found
:raises InvalidUse: When none or more then one links are specified. Also
when wrong link name is used. | [
"Creates",
"or",
"deletes",
"a",
"link",
"between",
"the",
"specified",
"tickets",
"(",
"undocumented",
"API",
"feature",
")",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1359-L1389 |
CZ-NIC/python-rt | rt.py | Rt.merge_ticket | def merge_ticket(self, ticket_id, into_id):
""" Merge ticket into another (undocumented API feature).
:param ticket_id: ID of ticket to be merged
:param into: ID of destination ticket
:returns: ``True``
Operation was successful
``False``
Either origin or destination ticket does not
exist or user does not have ModifyTicket permission.
"""
msg = self.__request('ticket/{}/merge/{}'.format(str(ticket_id),
str(into_id)))
state = msg.split('\n')[2]
return self.RE_PATTERNS['merge_successful_pattern'].match(state) is not None | python | def merge_ticket(self, ticket_id, into_id):
msg = self.__request('ticket/{}/merge/{}'.format(str(ticket_id),
str(into_id)))
state = msg.split('\n')[2]
return self.RE_PATTERNS['merge_successful_pattern'].match(state) is not None | [
"def",
"merge_ticket",
"(",
"self",
",",
"ticket_id",
",",
"into_id",
")",
":",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/merge/{}'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
",",
"str",
"(",
"into_id",
")",
")",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'merge_successful_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
]
| Merge ticket into another (undocumented API feature).
:param ticket_id: ID of ticket to be merged
:param into: ID of destination ticket
:returns: ``True``
Operation was successful
``False``
Either origin or destination ticket does not
exist or user does not have ModifyTicket permission. | [
"Merge",
"ticket",
"into",
"another",
"(",
"undocumented",
"API",
"feature",
")",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1391-L1405 |
CZ-NIC/python-rt | rt.py | Rt.untake | def untake(self, ticket_id):
""" Untake ticket
:param ticket_id: ID of ticket to be merged
:returns: ``True``
Operation was successful
``False``
Either the ticket does not exist or user does not
own the ticket.
"""
post_data = {'content': "Ticket: {}\nAction: untake".format(str(ticket_id))}
msg = self.__request('ticket/{}/take'.format(str(ticket_id)), post_data=post_data)
return self.__get_status_code(msg) == 200 | python | def untake(self, ticket_id):
post_data = {'content': "Ticket: {}\nAction: untake".format(str(ticket_id))}
msg = self.__request('ticket/{}/take'.format(str(ticket_id)), post_data=post_data)
return self.__get_status_code(msg) == 200 | [
"def",
"untake",
"(",
"self",
",",
"ticket_id",
")",
":",
"post_data",
"=",
"{",
"'content'",
":",
"\"Ticket: {}\\nAction: untake\"",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
")",
"}",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/take'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
")",
",",
"post_data",
"=",
"post_data",
")",
"return",
"self",
".",
"__get_status_code",
"(",
"msg",
")",
"==",
"200"
]
| Untake ticket
:param ticket_id: ID of ticket to be merged
:returns: ``True``
Operation was successful
``False``
Either the ticket does not exist or user does not
own the ticket. | [
"Untake",
"ticket"
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1435-L1447 |
CZ-NIC/python-rt | rt.py | Rt.split_header | def split_header(line):
""" Split a header line into field name and field value.
Note that custom fields may contain colons inside the curly braces,
so we need a special test for them.
:param line: A message line to be split.
:returns: (Field name, field value) tuple.
"""
match = re.match(r'^(CF\.\{.*?}): (.*)$', line)
if match:
return (match.group(1), match.group(2))
return line.split(': ', 1) | python | def split_header(line):
match = re.match(r'^(CF\.\{.*?}): (.*)$', line)
if match:
return (match.group(1), match.group(2))
return line.split(': ', 1) | [
"def",
"split_header",
"(",
"line",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(CF\\.\\{.*?}): (.*)$'",
",",
"line",
")",
"if",
"match",
":",
"return",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
"group",
"(",
"2",
")",
")",
"return",
"line",
".",
"split",
"(",
"': '",
",",
"1",
")"
]
| Split a header line into field name and field value.
Note that custom fields may contain colons inside the curly braces,
so we need a special test for them.
:param line: A message line to be split.
:returns: (Field name, field value) tuple. | [
"Split",
"a",
"header",
"line",
"into",
"field",
"name",
"and",
"field",
"value",
"."
]
| train | https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L1450-L1463 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.PrivateKeyFromWIF | def PrivateKeyFromWIF(wif):
"""
Get the private key from a WIF key
Args:
wif (str): The wif key
Returns:
bytes: The private key
"""
if wif is None or len(wif) is not 52:
raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))
data = base58.b58decode(wif)
length = len(data)
if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
raise ValueError("Invalid format!")
checksum = Crypto.Hash256(data[0:34])[0:4]
if checksum != data[34:]:
raise ValueError("Invalid WIF Checksum!")
return data[1:33] | python | def PrivateKeyFromWIF(wif):
if wif is None or len(wif) is not 52:
raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))
data = base58.b58decode(wif)
length = len(data)
if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
raise ValueError("Invalid format!")
checksum = Crypto.Hash256(data[0:34])[0:4]
if checksum != data[34:]:
raise ValueError("Invalid WIF Checksum!")
return data[1:33] | [
"def",
"PrivateKeyFromWIF",
"(",
"wif",
")",
":",
"if",
"wif",
"is",
"None",
"or",
"len",
"(",
"wif",
")",
"is",
"not",
"52",
":",
"raise",
"ValueError",
"(",
"'Please provide a wif with a length of 52 bytes (LEN: {0:d})'",
".",
"format",
"(",
"len",
"(",
"wif",
")",
")",
")",
"data",
"=",
"base58",
".",
"b58decode",
"(",
"wif",
")",
"length",
"=",
"len",
"(",
"data",
")",
"if",
"length",
"is",
"not",
"38",
"or",
"data",
"[",
"0",
"]",
"is",
"not",
"0x80",
"or",
"data",
"[",
"33",
"]",
"is",
"not",
"0x01",
":",
"raise",
"ValueError",
"(",
"\"Invalid format!\"",
")",
"checksum",
"=",
"Crypto",
".",
"Hash256",
"(",
"data",
"[",
"0",
":",
"34",
"]",
")",
"[",
"0",
":",
"4",
"]",
"if",
"checksum",
"!=",
"data",
"[",
"34",
":",
"]",
":",
"raise",
"ValueError",
"(",
"\"Invalid WIF Checksum!\"",
")",
"return",
"data",
"[",
"1",
":",
"33",
"]"
]
| Get the private key from a WIF key
Args:
wif (str): The wif key
Returns:
bytes: The private key | [
"Get",
"the",
"private",
"key",
"from",
"a",
"WIF",
"key"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L81-L106 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.PrivateKeyFromNEP2 | def PrivateKeyFromNEP2(nep2_key, passphrase):
"""
Gets the private key from a NEP-2 encrypted private key
Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
bytes: The private key
"""
if not nep2_key or len(nep2_key) != 58:
raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key)))
ADDRESS_HASH_SIZE = 4
ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER)
try:
decoded_key = base58.b58decode_check(nep2_key)
except Exception as e:
raise ValueError("Invalid nep2_key")
address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE]
encrypted = decoded_key[-32:]
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
derived1 = derived[:32]
derived2 = derived[32:]
cipher = AES.new(derived2, AES.MODE_ECB)
decrypted = cipher.decrypt(encrypted)
private_key = xor_bytes(decrypted, derived1)
# Now check that the address hashes match. If they don't, the password was wrong.
kp_new = KeyPair(priv_key=private_key)
kp_new_address = kp_new.GetAddress()
kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest()
kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest()
kp_new_address_hash = kp_new_address_hash_tmp2[:4]
if (kp_new_address_hash != address_hash):
raise ValueError("Wrong passphrase")
return private_key | python | def PrivateKeyFromNEP2(nep2_key, passphrase):
if not nep2_key or len(nep2_key) != 58:
raise ValueError('Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'.format(len(nep2_key)))
ADDRESS_HASH_SIZE = 4
ADDRESS_HASH_OFFSET = len(NEP_FLAG) + len(NEP_HEADER)
try:
decoded_key = base58.b58decode_check(nep2_key)
except Exception as e:
raise ValueError("Invalid nep2_key")
address_hash = decoded_key[ADDRESS_HASH_OFFSET:ADDRESS_HASH_OFFSET + ADDRESS_HASH_SIZE]
encrypted = decoded_key[-32:]
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
derived1 = derived[:32]
derived2 = derived[32:]
cipher = AES.new(derived2, AES.MODE_ECB)
decrypted = cipher.decrypt(encrypted)
private_key = xor_bytes(decrypted, derived1)
kp_new = KeyPair(priv_key=private_key)
kp_new_address = kp_new.GetAddress()
kp_new_address_hash_tmp = hashlib.sha256(kp_new_address.encode("utf-8")).digest()
kp_new_address_hash_tmp2 = hashlib.sha256(kp_new_address_hash_tmp).digest()
kp_new_address_hash = kp_new_address_hash_tmp2[:4]
if (kp_new_address_hash != address_hash):
raise ValueError("Wrong passphrase")
return private_key | [
"def",
"PrivateKeyFromNEP2",
"(",
"nep2_key",
",",
"passphrase",
")",
":",
"if",
"not",
"nep2_key",
"or",
"len",
"(",
"nep2_key",
")",
"!=",
"58",
":",
"raise",
"ValueError",
"(",
"'Please provide a nep2_key with a length of 58 bytes (LEN: {0:d})'",
".",
"format",
"(",
"len",
"(",
"nep2_key",
")",
")",
")",
"ADDRESS_HASH_SIZE",
"=",
"4",
"ADDRESS_HASH_OFFSET",
"=",
"len",
"(",
"NEP_FLAG",
")",
"+",
"len",
"(",
"NEP_HEADER",
")",
"try",
":",
"decoded_key",
"=",
"base58",
".",
"b58decode_check",
"(",
"nep2_key",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Invalid nep2_key\"",
")",
"address_hash",
"=",
"decoded_key",
"[",
"ADDRESS_HASH_OFFSET",
":",
"ADDRESS_HASH_OFFSET",
"+",
"ADDRESS_HASH_SIZE",
"]",
"encrypted",
"=",
"decoded_key",
"[",
"-",
"32",
":",
"]",
"pwd_normalized",
"=",
"bytes",
"(",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"passphrase",
")",
",",
"'utf-8'",
")",
"derived",
"=",
"scrypt",
".",
"hash",
"(",
"pwd_normalized",
",",
"address_hash",
",",
"N",
"=",
"SCRYPT_ITERATIONS",
",",
"r",
"=",
"SCRYPT_BLOCKSIZE",
",",
"p",
"=",
"SCRYPT_PARALLEL_FACTOR",
",",
"buflen",
"=",
"SCRYPT_KEY_LEN_BYTES",
")",
"derived1",
"=",
"derived",
"[",
":",
"32",
"]",
"derived2",
"=",
"derived",
"[",
"32",
":",
"]",
"cipher",
"=",
"AES",
".",
"new",
"(",
"derived2",
",",
"AES",
".",
"MODE_ECB",
")",
"decrypted",
"=",
"cipher",
".",
"decrypt",
"(",
"encrypted",
")",
"private_key",
"=",
"xor_bytes",
"(",
"decrypted",
",",
"derived1",
")",
"# Now check that the address hashes match. If they don't, the password was wrong.",
"kp_new",
"=",
"KeyPair",
"(",
"priv_key",
"=",
"private_key",
")",
"kp_new_address",
"=",
"kp_new",
".",
"GetAddress",
"(",
")",
"kp_new_address_hash_tmp",
"=",
"hashlib",
".",
"sha256",
"(",
"kp_new_address",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"digest",
"(",
")",
"kp_new_address_hash_tmp2",
"=",
"hashlib",
".",
"sha256",
"(",
"kp_new_address_hash_tmp",
")",
".",
"digest",
"(",
")",
"kp_new_address_hash",
"=",
"kp_new_address_hash_tmp2",
"[",
":",
"4",
"]",
"if",
"(",
"kp_new_address_hash",
"!=",
"address_hash",
")",
":",
"raise",
"ValueError",
"(",
"\"Wrong passphrase\"",
")",
"return",
"private_key"
]
| Gets the private key from a NEP-2 encrypted private key
Args:
nep2_key (str): The nep-2 encrypted private key
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
bytes: The private key | [
"Gets",
"the",
"private",
"key",
"from",
"a",
"NEP",
"-",
"2",
"encrypted",
"private",
"key"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L109-L157 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.GetAddress | def GetAddress(self):
"""
Returns the public NEO address for this KeyPair
Returns:
str: The private key
"""
script = b'21' + self.PublicKey.encode_point(True) + b'ac'
script_hash = Crypto.ToScriptHash(script)
address = Crypto.ToAddress(script_hash)
return address | python | def GetAddress(self):
script = b'21' + self.PublicKey.encode_point(True) + b'ac'
script_hash = Crypto.ToScriptHash(script)
address = Crypto.ToAddress(script_hash)
return address | [
"def",
"GetAddress",
"(",
"self",
")",
":",
"script",
"=",
"b'21'",
"+",
"self",
".",
"PublicKey",
".",
"encode_point",
"(",
"True",
")",
"+",
"b'ac'",
"script_hash",
"=",
"Crypto",
".",
"ToScriptHash",
"(",
"script",
")",
"address",
"=",
"Crypto",
".",
"ToAddress",
"(",
"script_hash",
")",
"return",
"address"
]
| Returns the public NEO address for this KeyPair
Returns:
str: The private key | [
"Returns",
"the",
"public",
"NEO",
"address",
"for",
"this",
"KeyPair"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L159-L169 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.Export | def Export(self):
"""
Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format
"""
data = bytearray(38)
data[0] = 0x80
data[1:33] = self.PrivateKey[0:32]
data[33] = 0x01
checksum = Crypto.Default().Hash256(data[0:34])
data[34:38] = checksum[0:4]
b58 = base58.b58encode(bytes(data))
return b58.decode("utf-8") | python | def Export(self):
data = bytearray(38)
data[0] = 0x80
data[1:33] = self.PrivateKey[0:32]
data[33] = 0x01
checksum = Crypto.Default().Hash256(data[0:34])
data[34:38] = checksum[0:4]
b58 = base58.b58encode(bytes(data))
return b58.decode("utf-8") | [
"def",
"Export",
"(",
"self",
")",
":",
"data",
"=",
"bytearray",
"(",
"38",
")",
"data",
"[",
"0",
"]",
"=",
"0x80",
"data",
"[",
"1",
":",
"33",
"]",
"=",
"self",
".",
"PrivateKey",
"[",
"0",
":",
"32",
"]",
"data",
"[",
"33",
"]",
"=",
"0x01",
"checksum",
"=",
"Crypto",
".",
"Default",
"(",
")",
".",
"Hash256",
"(",
"data",
"[",
"0",
":",
"34",
"]",
")",
"data",
"[",
"34",
":",
"38",
"]",
"=",
"checksum",
"[",
"0",
":",
"4",
"]",
"b58",
"=",
"base58",
".",
"b58encode",
"(",
"bytes",
"(",
"data",
")",
")",
"return",
"b58",
".",
"decode",
"(",
"\"utf-8\"",
")"
]
| Export this KeyPair's private key in WIF format.
Returns:
str: The key in wif format | [
"Export",
"this",
"KeyPair",
"s",
"private",
"key",
"in",
"WIF",
"format",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L171-L187 |
CityOfZion/neo-python-core | neocore/KeyPair.py | KeyPair.ExportNEP2 | def ExportNEP2(self, passphrase):
"""
Export the encrypted private key in NEP-2 format.
Args:
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
str: The NEP-2 encrypted private key
"""
if len(passphrase) < 2:
raise ValueError("Passphrase must have a minimum of 2 characters")
# Hash address twice, then only use the first 4 bytes
address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest()
address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
address_hash = address_hash_tmp2[:4]
# Normalize password and run scrypt over it with the address_hash
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
# Split the scrypt-result into two parts
derived1 = derived[:32]
derived2 = derived[32:]
# Run XOR and encrypt the derived parts with AES
xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
cipher = AES.new(derived2, AES.MODE_ECB)
encrypted = cipher.encrypt(xor_ed)
# Assemble the final result
assembled = bytearray()
assembled.extend(NEP_HEADER)
assembled.extend(NEP_FLAG)
assembled.extend(address_hash)
assembled.extend(encrypted)
# Finally, encode with Base58Check
encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
return encrypted_key_nep2.decode("utf-8") | python | def ExportNEP2(self, passphrase):
if len(passphrase) < 2:
raise ValueError("Passphrase must have a minimum of 2 characters")
address_hash_tmp = hashlib.sha256(self.GetAddress().encode("utf-8")).digest()
address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
address_hash = address_hash_tmp2[:4]
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
derived1 = derived[:32]
derived2 = derived[32:]
xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
cipher = AES.new(derived2, AES.MODE_ECB)
encrypted = cipher.encrypt(xor_ed)
assembled = bytearray()
assembled.extend(NEP_HEADER)
assembled.extend(NEP_FLAG)
assembled.extend(address_hash)
assembled.extend(encrypted)
encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
return encrypted_key_nep2.decode("utf-8") | [
"def",
"ExportNEP2",
"(",
"self",
",",
"passphrase",
")",
":",
"if",
"len",
"(",
"passphrase",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"Passphrase must have a minimum of 2 characters\"",
")",
"# Hash address twice, then only use the first 4 bytes",
"address_hash_tmp",
"=",
"hashlib",
".",
"sha256",
"(",
"self",
".",
"GetAddress",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"digest",
"(",
")",
"address_hash_tmp2",
"=",
"hashlib",
".",
"sha256",
"(",
"address_hash_tmp",
")",
".",
"digest",
"(",
")",
"address_hash",
"=",
"address_hash_tmp2",
"[",
":",
"4",
"]",
"# Normalize password and run scrypt over it with the address_hash",
"pwd_normalized",
"=",
"bytes",
"(",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"passphrase",
")",
",",
"'utf-8'",
")",
"derived",
"=",
"scrypt",
".",
"hash",
"(",
"pwd_normalized",
",",
"address_hash",
",",
"N",
"=",
"SCRYPT_ITERATIONS",
",",
"r",
"=",
"SCRYPT_BLOCKSIZE",
",",
"p",
"=",
"SCRYPT_PARALLEL_FACTOR",
",",
"buflen",
"=",
"SCRYPT_KEY_LEN_BYTES",
")",
"# Split the scrypt-result into two parts",
"derived1",
"=",
"derived",
"[",
":",
"32",
"]",
"derived2",
"=",
"derived",
"[",
"32",
":",
"]",
"# Run XOR and encrypt the derived parts with AES",
"xor_ed",
"=",
"xor_bytes",
"(",
"bytes",
"(",
"self",
".",
"PrivateKey",
")",
",",
"derived1",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"derived2",
",",
"AES",
".",
"MODE_ECB",
")",
"encrypted",
"=",
"cipher",
".",
"encrypt",
"(",
"xor_ed",
")",
"# Assemble the final result",
"assembled",
"=",
"bytearray",
"(",
")",
"assembled",
".",
"extend",
"(",
"NEP_HEADER",
")",
"assembled",
".",
"extend",
"(",
"NEP_FLAG",
")",
"assembled",
".",
"extend",
"(",
"address_hash",
")",
"assembled",
".",
"extend",
"(",
"encrypted",
")",
"# Finally, encode with Base58Check",
"encrypted_key_nep2",
"=",
"base58",
".",
"b58encode_check",
"(",
"bytes",
"(",
"assembled",
")",
")",
"return",
"encrypted_key_nep2",
".",
"decode",
"(",
"\"utf-8\"",
")"
]
| Export the encrypted private key in NEP-2 format.
Args:
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
str: The NEP-2 encrypted private key | [
"Export",
"the",
"encrypted",
"private",
"key",
"in",
"NEP",
"-",
"2",
"format",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/KeyPair.py#L189-L233 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.unpack | def unpack(self, fmt, length=1):
"""
Unpack the stream contents according to the specified format in `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
length (int): amount of bytes to read.
Returns:
variable: the result according to the specified format.
"""
return struct.unpack(fmt, self.stream.read(length))[0] | python | def unpack(self, fmt, length=1):
return struct.unpack(fmt, self.stream.read(length))[0] | [
"def",
"unpack",
"(",
"self",
",",
"fmt",
",",
"length",
"=",
"1",
")",
":",
"return",
"struct",
".",
"unpack",
"(",
"fmt",
",",
"self",
".",
"stream",
".",
"read",
"(",
"length",
")",
")",
"[",
"0",
"]"
]
| Unpack the stream contents according to the specified format in `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
length (int): amount of bytes to read.
Returns:
variable: the result according to the specified format. | [
"Unpack",
"the",
"stream",
"contents",
"according",
"to",
"the",
"specified",
"format",
"in",
"fmt",
".",
"For",
"more",
"information",
"about",
"the",
"fmt",
"format",
"see",
":",
"https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"struct",
".",
"html"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L32-L44 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadByte | def ReadByte(self, do_ord=True):
"""
Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred.
"""
try:
if do_ord:
return ord(self.stream.read(1))
return self.stream.read(1)
except Exception as e:
logger.error("ord expected character but got none")
return 0 | python | def ReadByte(self, do_ord=True):
try:
if do_ord:
return ord(self.stream.read(1))
return self.stream.read(1)
except Exception as e:
logger.error("ord expected character but got none")
return 0 | [
"def",
"ReadByte",
"(",
"self",
",",
"do_ord",
"=",
"True",
")",
":",
"try",
":",
"if",
"do_ord",
":",
"return",
"ord",
"(",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
")",
"return",
"self",
".",
"stream",
".",
"read",
"(",
"1",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"ord expected character but got none\"",
")",
"return",
"0"
]
| Read a single byte.
Args:
do_ord (bool): (default True) convert the byte to an ordinal first.
Returns:
bytes: a single byte if successful. 0 (int) if an exception occurred. | [
"Read",
"a",
"single",
"byte",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L46-L62 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.SafeReadBytes | def SafeReadBytes(self, length):
"""
Read exactly `length` number of bytes from the stream.
Raises:
ValueError is not enough data
Returns:
bytes: `length` number of bytes
"""
data = self.ReadBytes(length)
if len(data) < length:
raise ValueError("Not enough data available")
else:
return data | python | def SafeReadBytes(self, length):
data = self.ReadBytes(length)
if len(data) < length:
raise ValueError("Not enough data available")
else:
return data | [
"def",
"SafeReadBytes",
"(",
"self",
",",
"length",
")",
":",
"data",
"=",
"self",
".",
"ReadBytes",
"(",
"length",
")",
"if",
"len",
"(",
"data",
")",
"<",
"length",
":",
"raise",
"ValueError",
"(",
"\"Not enough data available\"",
")",
"else",
":",
"return",
"data"
]
| Read exactly `length` number of bytes from the stream.
Raises:
ValueError is not enough data
Returns:
bytes: `length` number of bytes | [
"Read",
"exactly",
"length",
"number",
"of",
"bytes",
"from",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L77-L91 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadVarInt | def ReadVarInt(self, max=sys.maxsize):
"""
Read a variable length integer from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
int:
"""
fb = self.ReadByte()
if fb is 0:
return fb
value = 0
if hex(fb) == '0xfd':
value = self.ReadUInt16()
elif hex(fb) == '0xfe':
value = self.ReadUInt32()
elif hex(fb) == '0xff':
value = self.ReadUInt64()
else:
value = fb
if value > max:
raise Exception("Invalid format")
return int(value) | python | def ReadVarInt(self, max=sys.maxsize):
fb = self.ReadByte()
if fb is 0:
return fb
value = 0
if hex(fb) == '0xfd':
value = self.ReadUInt16()
elif hex(fb) == '0xfe':
value = self.ReadUInt32()
elif hex(fb) == '0xff':
value = self.ReadUInt64()
else:
value = fb
if value > max:
raise Exception("Invalid format")
return int(value) | [
"def",
"ReadVarInt",
"(",
"self",
",",
"max",
"=",
"sys",
".",
"maxsize",
")",
":",
"fb",
"=",
"self",
".",
"ReadByte",
"(",
")",
"if",
"fb",
"is",
"0",
":",
"return",
"fb",
"value",
"=",
"0",
"if",
"hex",
"(",
"fb",
")",
"==",
"'0xfd'",
":",
"value",
"=",
"self",
".",
"ReadUInt16",
"(",
")",
"elif",
"hex",
"(",
"fb",
")",
"==",
"'0xfe'",
":",
"value",
"=",
"self",
".",
"ReadUInt32",
"(",
")",
"elif",
"hex",
"(",
"fb",
")",
"==",
"'0xff'",
":",
"value",
"=",
"self",
".",
"ReadUInt64",
"(",
")",
"else",
":",
"value",
"=",
"fb",
"if",
"value",
">",
"max",
":",
"raise",
"Exception",
"(",
"\"Invalid format\"",
")",
"return",
"int",
"(",
"value",
")"
]
| Read a variable length integer from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
int: | [
"Read",
"a",
"variable",
"length",
"integer",
"from",
"the",
"stream",
".",
"The",
"NEO",
"network",
"protocol",
"supports",
"encoded",
"storage",
"for",
"space",
"saving",
".",
"See",
":",
"http",
":",
"//",
"docs",
".",
"neo",
".",
"org",
"/",
"en",
"-",
"us",
"/",
"node",
"/",
"network",
"-",
"protocol",
".",
"html#convention"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L231-L258 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadVarBytes | def ReadVarBytes(self, max=sys.maxsize):
"""
Read a variable length of bytes from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes:
"""
length = self.ReadVarInt(max)
return self.ReadBytes(length) | python | def ReadVarBytes(self, max=sys.maxsize):
length = self.ReadVarInt(max)
return self.ReadBytes(length) | [
"def",
"ReadVarBytes",
"(",
"self",
",",
"max",
"=",
"sys",
".",
"maxsize",
")",
":",
"length",
"=",
"self",
".",
"ReadVarInt",
"(",
"max",
")",
"return",
"self",
".",
"ReadBytes",
"(",
"length",
")"
]
| Read a variable length of bytes from the stream.
The NEO network protocol supports encoded storage for space saving. See: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes: | [
"Read",
"a",
"variable",
"length",
"of",
"bytes",
"from",
"the",
"stream",
".",
"The",
"NEO",
"network",
"protocol",
"supports",
"encoded",
"storage",
"for",
"space",
"saving",
".",
"See",
":",
"http",
":",
"//",
"docs",
".",
"neo",
".",
"org",
"/",
"en",
"-",
"us",
"/",
"node",
"/",
"network",
"-",
"protocol",
".",
"html#convention"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L260-L272 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadString | def ReadString(self):
"""
Read a string from the stream.
Returns:
str:
"""
length = self.ReadUInt8()
return self.unpack(str(length) + 's', length) | python | def ReadString(self):
length = self.ReadUInt8()
return self.unpack(str(length) + 's', length) | [
"def",
"ReadString",
"(",
"self",
")",
":",
"length",
"=",
"self",
".",
"ReadUInt8",
"(",
")",
"return",
"self",
".",
"unpack",
"(",
"str",
"(",
"length",
")",
"+",
"'s'",
",",
"length",
")"
]
| Read a string from the stream.
Returns:
str: | [
"Read",
"a",
"string",
"from",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L274-L282 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadVarString | def ReadVarString(self, max=sys.maxsize):
"""
Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator.
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes:
"""
length = self.ReadVarInt(max)
return self.unpack(str(length) + 's', length) | python | def ReadVarString(self, max=sys.maxsize):
length = self.ReadVarInt(max)
return self.unpack(str(length) + 's', length) | [
"def",
"ReadVarString",
"(",
"self",
",",
"max",
"=",
"sys",
".",
"maxsize",
")",
":",
"length",
"=",
"self",
".",
"ReadVarInt",
"(",
"max",
")",
"return",
"self",
".",
"unpack",
"(",
"str",
"(",
"length",
")",
"+",
"'s'",
",",
"length",
")"
]
| Similar to `ReadString` but expects a variable length indicator instead of the fixed 1 byte indicator.
Args:
max (int): (Optional) maximum number of bytes to read.
Returns:
bytes: | [
"Similar",
"to",
"ReadString",
"but",
"expects",
"a",
"variable",
"length",
"indicator",
"instead",
"of",
"the",
"fixed",
"1",
"byte",
"indicator",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L284-L295 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadSerializableArray | def ReadSerializableArray(self, class_name, max=sys.maxsize):
"""
Deserialize a stream into the object specific by `class_name`.
Args:
class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block'
max (int): (Optional) maximum number of bytes to read.
Returns:
list: list of `class_name` objects deserialized from the stream.
"""
module = '.'.join(class_name.split('.')[:-1])
klassname = class_name.split('.')[-1]
klass = getattr(importlib.import_module(module), klassname)
length = self.ReadVarInt(max=max)
items = []
# logger.info("READING ITEM %s %s " % (length, class_name))
try:
for i in range(0, length):
item = klass()
item.Deserialize(self)
# logger.info("deserialized item %s %s " % ( i, item))
items.append(item)
except Exception as e:
logger.error("Couldn't deserialize %s " % e)
return items | python | def ReadSerializableArray(self, class_name, max=sys.maxsize):
module = '.'.join(class_name.split('.')[:-1])
klassname = class_name.split('.')[-1]
klass = getattr(importlib.import_module(module), klassname)
length = self.ReadVarInt(max=max)
items = []
try:
for i in range(0, length):
item = klass()
item.Deserialize(self)
items.append(item)
except Exception as e:
logger.error("Couldn't deserialize %s " % e)
return items | [
"def",
"ReadSerializableArray",
"(",
"self",
",",
"class_name",
",",
"max",
"=",
"sys",
".",
"maxsize",
")",
":",
"module",
"=",
"'.'",
".",
"join",
"(",
"class_name",
".",
"split",
"(",
"'.'",
")",
"[",
":",
"-",
"1",
"]",
")",
"klassname",
"=",
"class_name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"klass",
"=",
"getattr",
"(",
"importlib",
".",
"import_module",
"(",
"module",
")",
",",
"klassname",
")",
"length",
"=",
"self",
".",
"ReadVarInt",
"(",
"max",
"=",
"max",
")",
"items",
"=",
"[",
"]",
"# logger.info(\"READING ITEM %s %s \" % (length, class_name))",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"length",
")",
":",
"item",
"=",
"klass",
"(",
")",
"item",
".",
"Deserialize",
"(",
"self",
")",
"# logger.info(\"deserialized item %s %s \" % ( i, item))",
"items",
".",
"append",
"(",
"item",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Couldn't deserialize %s \"",
"%",
"e",
")",
"return",
"items"
]
| Deserialize a stream into the object specific by `class_name`.
Args:
class_name (str): a full path to the class to be deserialized into. e.g. 'neo.Core.Block.Block'
max (int): (Optional) maximum number of bytes to read.
Returns:
list: list of `class_name` objects deserialized from the stream. | [
"Deserialize",
"a",
"stream",
"into",
"the",
"object",
"specific",
"by",
"class_name",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L308-L334 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.Read2000256List | def Read2000256List(self):
"""
Read 2000 times a 64 byte value from the stream.
Returns:
list: a list containing 2000 64 byte values in reversed form.
"""
items = []
for i in range(0, 2000):
data = self.ReadBytes(64)
ba = bytearray(binascii.unhexlify(data))
ba.reverse()
items.append(ba.hex().encode('utf-8'))
return items | python | def Read2000256List(self):
items = []
for i in range(0, 2000):
data = self.ReadBytes(64)
ba = bytearray(binascii.unhexlify(data))
ba.reverse()
items.append(ba.hex().encode('utf-8'))
return items | [
"def",
"Read2000256List",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"2000",
")",
":",
"data",
"=",
"self",
".",
"ReadBytes",
"(",
"64",
")",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"data",
")",
")",
"ba",
".",
"reverse",
"(",
")",
"items",
".",
"append",
"(",
"ba",
".",
"hex",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"items"
]
| Read 2000 times a 64 byte value from the stream.
Returns:
list: a list containing 2000 64 byte values in reversed form. | [
"Read",
"2000",
"times",
"a",
"64",
"byte",
"value",
"from",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L354-L367 |
CityOfZion/neo-python-core | neocore/IO/BinaryReader.py | BinaryReader.ReadHashes | def ReadHashes(self):
"""
Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type.
"""
len = self.ReadVarInt()
items = []
for i in range(0, len):
ba = bytearray(self.ReadBytes(32))
ba.reverse()
items.append(ba.hex())
return items | python | def ReadHashes(self):
len = self.ReadVarInt()
items = []
for i in range(0, len):
ba = bytearray(self.ReadBytes(32))
ba.reverse()
items.append(ba.hex())
return items | [
"def",
"ReadHashes",
"(",
"self",
")",
":",
"len",
"=",
"self",
".",
"ReadVarInt",
"(",
")",
"items",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
")",
":",
"ba",
"=",
"bytearray",
"(",
"self",
".",
"ReadBytes",
"(",
"32",
")",
")",
"ba",
".",
"reverse",
"(",
")",
"items",
".",
"append",
"(",
"ba",
".",
"hex",
"(",
")",
")",
"return",
"items"
]
| Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type. | [
"Read",
"Hash",
"values",
"from",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryReader.py#L369-L382 |
CityOfZion/neo-python-core | neocore/Cryptography/Crypto.py | Crypto.ToScriptHash | def ToScriptHash(data, unhex=True):
"""
Get a script hash of the data.
Args:
data (bytes): data to hash.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
UInt160: script hash.
"""
if len(data) > 1 and unhex:
data = binascii.unhexlify(data)
return UInt160(data=binascii.unhexlify(bytes(Crypto.Hash160(data), encoding='utf-8'))) | python | def ToScriptHash(data, unhex=True):
if len(data) > 1 and unhex:
data = binascii.unhexlify(data)
return UInt160(data=binascii.unhexlify(bytes(Crypto.Hash160(data), encoding='utf-8'))) | [
"def",
"ToScriptHash",
"(",
"data",
",",
"unhex",
"=",
"True",
")",
":",
"if",
"len",
"(",
"data",
")",
">",
"1",
"and",
"unhex",
":",
"data",
"=",
"binascii",
".",
"unhexlify",
"(",
"data",
")",
"return",
"UInt160",
"(",
"data",
"=",
"binascii",
".",
"unhexlify",
"(",
"bytes",
"(",
"Crypto",
".",
"Hash160",
"(",
"data",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
")",
")"
]
| Get a script hash of the data.
Args:
data (bytes): data to hash.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
UInt160: script hash. | [
"Get",
"a",
"script",
"hash",
"of",
"the",
"data",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L77-L90 |
CityOfZion/neo-python-core | neocore/Cryptography/Crypto.py | Crypto.Sign | def Sign(message, private_key):
"""
Sign the message with the given private key.
Args:
message (str): message to be signed
private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64)
Returns:
bytearray: the signature of the message.
"""
hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest()
v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key)
rb = bytearray(r.to_bytes(32, 'big'))
sb = bytearray(s.to_bytes(32, 'big'))
sig = rb + sb
return sig | python | def Sign(message, private_key):
hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest()
v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key)
rb = bytearray(r.to_bytes(32, 'big'))
sb = bytearray(s.to_bytes(32, 'big'))
sig = rb + sb
return sig | [
"def",
"Sign",
"(",
"message",
",",
"private_key",
")",
":",
"hash",
"=",
"hashlib",
".",
"sha256",
"(",
"binascii",
".",
"unhexlify",
"(",
"message",
")",
")",
".",
"hexdigest",
"(",
")",
"v",
",",
"r",
",",
"s",
"=",
"bitcoin",
".",
"ecdsa_raw_sign",
"(",
"hash",
",",
"private_key",
")",
"rb",
"=",
"bytearray",
"(",
"r",
".",
"to_bytes",
"(",
"32",
",",
"'big'",
")",
")",
"sb",
"=",
"bytearray",
"(",
"s",
".",
"to_bytes",
"(",
"32",
",",
"'big'",
")",
")",
"sig",
"=",
"rb",
"+",
"sb",
"return",
"sig"
]
| Sign the message with the given private key.
Args:
message (str): message to be signed
private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64)
Returns:
bytearray: the signature of the message. | [
"Sign",
"the",
"message",
"with",
"the",
"given",
"private",
"key",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L106-L126 |
CityOfZion/neo-python-core | neocore/Cryptography/Crypto.py | Crypto.VerifySignature | def VerifySignature(message, signature, public_key, unhex=True):
"""
Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB').
unhex (bool): whether the message should be unhexlified before verifying
Returns:
bool: True if verification passes. False otherwise.
"""
if type(public_key) is EllipticCurve.ECPoint:
pubkey_x = public_key.x.value.to_bytes(32, 'big')
pubkey_y = public_key.y.value.to_bytes(32, 'big')
public_key = pubkey_x + pubkey_y
if unhex:
try:
message = binascii.unhexlify(message)
except Exception as e:
logger.error("could not get m: %s" % e)
elif isinstance(message, str):
message = message.encode('utf-8')
if len(public_key) == 33:
public_key = bitcoin.decompress(public_key)
public_key = public_key[1:]
try:
vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256)
res = vk.verify(signature, message, hashfunc=hashlib.sha256)
return res
except Exception as e:
pass
return False | python | def VerifySignature(message, signature, public_key, unhex=True):
if type(public_key) is EllipticCurve.ECPoint:
pubkey_x = public_key.x.value.to_bytes(32, 'big')
pubkey_y = public_key.y.value.to_bytes(32, 'big')
public_key = pubkey_x + pubkey_y
if unhex:
try:
message = binascii.unhexlify(message)
except Exception as e:
logger.error("could not get m: %s" % e)
elif isinstance(message, str):
message = message.encode('utf-8')
if len(public_key) == 33:
public_key = bitcoin.decompress(public_key)
public_key = public_key[1:]
try:
vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256)
res = vk.verify(signature, message, hashfunc=hashlib.sha256)
return res
except Exception as e:
pass
return False | [
"def",
"VerifySignature",
"(",
"message",
",",
"signature",
",",
"public_key",
",",
"unhex",
"=",
"True",
")",
":",
"if",
"type",
"(",
"public_key",
")",
"is",
"EllipticCurve",
".",
"ECPoint",
":",
"pubkey_x",
"=",
"public_key",
".",
"x",
".",
"value",
".",
"to_bytes",
"(",
"32",
",",
"'big'",
")",
"pubkey_y",
"=",
"public_key",
".",
"y",
".",
"value",
".",
"to_bytes",
"(",
"32",
",",
"'big'",
")",
"public_key",
"=",
"pubkey_x",
"+",
"pubkey_y",
"if",
"unhex",
":",
"try",
":",
"message",
"=",
"binascii",
".",
"unhexlify",
"(",
"message",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"could not get m: %s\"",
"%",
"e",
")",
"elif",
"isinstance",
"(",
"message",
",",
"str",
")",
":",
"message",
"=",
"message",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"len",
"(",
"public_key",
")",
"==",
"33",
":",
"public_key",
"=",
"bitcoin",
".",
"decompress",
"(",
"public_key",
")",
"public_key",
"=",
"public_key",
"[",
"1",
":",
"]",
"try",
":",
"vk",
"=",
"VerifyingKey",
".",
"from_string",
"(",
"public_key",
",",
"curve",
"=",
"NIST256p",
",",
"hashfunc",
"=",
"hashlib",
".",
"sha256",
")",
"res",
"=",
"vk",
".",
"verify",
"(",
"signature",
",",
"message",
",",
"hashfunc",
"=",
"hashlib",
".",
"sha256",
")",
"return",
"res",
"except",
"Exception",
"as",
"e",
":",
"pass",
"return",
"False"
]
| Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB').
unhex (bool): whether the message should be unhexlified before verifying
Returns:
bool: True if verification passes. False otherwise. | [
"Verify",
"the",
"integrity",
"of",
"the",
"message",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L129-L168 |
CityOfZion/neo-python-core | neocore/Cryptography/Crypto.py | CryptoInstance.VerifySignature | def VerifySignature(self, message, signature, public_key, unhex=True):
"""
Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint): the public key to use for verifying the signature.
unhex (bool): whether the message should be unhexlified before verifying
Returns:
bool: True if verification passes. False otherwise.
"""
return Crypto.VerifySignature(message, signature, public_key, unhex=unhex) | python | def VerifySignature(self, message, signature, public_key, unhex=True):
return Crypto.VerifySignature(message, signature, public_key, unhex=unhex) | [
"def",
"VerifySignature",
"(",
"self",
",",
"message",
",",
"signature",
",",
"public_key",
",",
"unhex",
"=",
"True",
")",
":",
"return",
"Crypto",
".",
"VerifySignature",
"(",
"message",
",",
"signature",
",",
"public_key",
",",
"unhex",
"=",
"unhex",
")"
]
| Verify the integrity of the message.
Args:
message (str): the message to verify.
signature (bytearray): the signature belonging to the message.
public_key (ECPoint): the public key to use for verifying the signature.
unhex (bool): whether the message should be unhexlified before verifying
Returns:
bool: True if verification passes. False otherwise. | [
"Verify",
"the",
"integrity",
"of",
"the",
"message",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Crypto.py#L212-L225 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | _lucas_sequence | def _lucas_sequence(n, P, Q, k):
"""Return the modular Lucas sequence (U_k, V_k, Q_k).
Given a Lucas sequence defined by P, Q, returns the kth values for
U and V, along with Q^k, all modulo n.
"""
D = P * P - 4 * Q
if n < 2:
raise ValueError("n must be >= 2")
if k < 0:
raise ValueError("k must be >= 0")
if D == 0:
raise ValueError("D must not be zero")
if k == 0:
return 0, 2
U = 1
V = P
Qk = Q
b = _bitlength(k)
if Q == 1:
# For strong tests
while b > 1:
U = (U * V) % n
V = (V * V - 2) % n
b -= 1
if (k >> (b - 1)) & 1:
t = U * D
U = U * P + V
if U & 1:
U += n
U >>= 1
V = V * P + t
if V & 1:
V += n
V >>= 1
elif P == 1 and Q == -1:
# For Selfridge parameters
while b > 1:
U = (U * V) % n
if Qk == 1:
V = (V * V - 2) % n
else:
V = (V * V + 2) % n
Qk = 1
b -= 1
if (k >> (b - 1)) & 1:
t = U * D
U = U + V
if U & 1:
U += n
U >>= 1
V = V + t
if V & 1:
V += n
V >>= 1
Qk = -1
else:
# The general case with any P and Q
while b > 1:
U = (U * V) % n
V = (V * V - 2 * Qk) % n
Qk *= Qk
b -= 1
if (k >> (b - 1)) & 1:
t = U * D
U = U * P + V
if U & 1:
U += n
U >>= 1
V = V * P + t
if V & 1:
V += n
V >>= 1
Qk *= Q
Qk %= n
U %= n
V %= n
return U, V | python | def _lucas_sequence(n, P, Q, k):
D = P * P - 4 * Q
if n < 2:
raise ValueError("n must be >= 2")
if k < 0:
raise ValueError("k must be >= 0")
if D == 0:
raise ValueError("D must not be zero")
if k == 0:
return 0, 2
U = 1
V = P
Qk = Q
b = _bitlength(k)
if Q == 1:
while b > 1:
U = (U * V) % n
V = (V * V - 2) % n
b -= 1
if (k >> (b - 1)) & 1:
t = U * D
U = U * P + V
if U & 1:
U += n
U >>= 1
V = V * P + t
if V & 1:
V += n
V >>= 1
elif P == 1 and Q == -1:
while b > 1:
U = (U * V) % n
if Qk == 1:
V = (V * V - 2) % n
else:
V = (V * V + 2) % n
Qk = 1
b -= 1
if (k >> (b - 1)) & 1:
t = U * D
U = U + V
if U & 1:
U += n
U >>= 1
V = V + t
if V & 1:
V += n
V >>= 1
Qk = -1
else:
while b > 1:
U = (U * V) % n
V = (V * V - 2 * Qk) % n
Qk *= Qk
b -= 1
if (k >> (b - 1)) & 1:
t = U * D
U = U * P + V
if U & 1:
U += n
U >>= 1
V = V * P + t
if V & 1:
V += n
V >>= 1
Qk *= Q
Qk %= n
U %= n
V %= n
return U, V | [
"def",
"_lucas_sequence",
"(",
"n",
",",
"P",
",",
"Q",
",",
"k",
")",
":",
"D",
"=",
"P",
"*",
"P",
"-",
"4",
"*",
"Q",
"if",
"n",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"n must be >= 2\"",
")",
"if",
"k",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"k must be >= 0\"",
")",
"if",
"D",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"D must not be zero\"",
")",
"if",
"k",
"==",
"0",
":",
"return",
"0",
",",
"2",
"U",
"=",
"1",
"V",
"=",
"P",
"Qk",
"=",
"Q",
"b",
"=",
"_bitlength",
"(",
"k",
")",
"if",
"Q",
"==",
"1",
":",
"# For strong tests",
"while",
"b",
">",
"1",
":",
"U",
"=",
"(",
"U",
"*",
"V",
")",
"%",
"n",
"V",
"=",
"(",
"V",
"*",
"V",
"-",
"2",
")",
"%",
"n",
"b",
"-=",
"1",
"if",
"(",
"k",
">>",
"(",
"b",
"-",
"1",
")",
")",
"&",
"1",
":",
"t",
"=",
"U",
"*",
"D",
"U",
"=",
"U",
"*",
"P",
"+",
"V",
"if",
"U",
"&",
"1",
":",
"U",
"+=",
"n",
"U",
">>=",
"1",
"V",
"=",
"V",
"*",
"P",
"+",
"t",
"if",
"V",
"&",
"1",
":",
"V",
"+=",
"n",
"V",
">>=",
"1",
"elif",
"P",
"==",
"1",
"and",
"Q",
"==",
"-",
"1",
":",
"# For Selfridge parameters",
"while",
"b",
">",
"1",
":",
"U",
"=",
"(",
"U",
"*",
"V",
")",
"%",
"n",
"if",
"Qk",
"==",
"1",
":",
"V",
"=",
"(",
"V",
"*",
"V",
"-",
"2",
")",
"%",
"n",
"else",
":",
"V",
"=",
"(",
"V",
"*",
"V",
"+",
"2",
")",
"%",
"n",
"Qk",
"=",
"1",
"b",
"-=",
"1",
"if",
"(",
"k",
">>",
"(",
"b",
"-",
"1",
")",
")",
"&",
"1",
":",
"t",
"=",
"U",
"*",
"D",
"U",
"=",
"U",
"+",
"V",
"if",
"U",
"&",
"1",
":",
"U",
"+=",
"n",
"U",
">>=",
"1",
"V",
"=",
"V",
"+",
"t",
"if",
"V",
"&",
"1",
":",
"V",
"+=",
"n",
"V",
">>=",
"1",
"Qk",
"=",
"-",
"1",
"else",
":",
"# The general case with any P and Q",
"while",
"b",
">",
"1",
":",
"U",
"=",
"(",
"U",
"*",
"V",
")",
"%",
"n",
"V",
"=",
"(",
"V",
"*",
"V",
"-",
"2",
"*",
"Qk",
")",
"%",
"n",
"Qk",
"*=",
"Qk",
"b",
"-=",
"1",
"if",
"(",
"k",
">>",
"(",
"b",
"-",
"1",
")",
")",
"&",
"1",
":",
"t",
"=",
"U",
"*",
"D",
"U",
"=",
"U",
"*",
"P",
"+",
"V",
"if",
"U",
"&",
"1",
":",
"U",
"+=",
"n",
"U",
">>=",
"1",
"V",
"=",
"V",
"*",
"P",
"+",
"t",
"if",
"V",
"&",
"1",
":",
"V",
"+=",
"n",
"V",
">>=",
"1",
"Qk",
"*=",
"Q",
"Qk",
"%=",
"n",
"U",
"%=",
"n",
"V",
"%=",
"n",
"return",
"U",
",",
"V"
]
| Return the modular Lucas sequence (U_k, V_k, Q_k).
Given a Lucas sequence defined by P, Q, returns the kth values for
U and V, along with Q^k, all modulo n. | [
"Return",
"the",
"modular",
"Lucas",
"sequence",
"(",
"U_k",
"V_k",
"Q_k",
")",
".",
"Given",
"a",
"Lucas",
"sequence",
"defined",
"by",
"P",
"Q",
"returns",
"the",
"kth",
"values",
"for",
"U",
"and",
"V",
"along",
"with",
"Q^k",
"all",
"modulo",
"n",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L67-L144 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | FiniteField.sqrt | def sqrt(self, val, flag):
"""
calculate the square root modulus p
"""
if val.iszero():
return val
sw = self.p % 8
if sw == 3 or sw == 7:
res = val ** ((self.p + 1) / 4)
elif sw == 5:
x = val ** ((self.p + 1) / 4)
if x == 1:
res = val ** ((self.p + 3) / 8)
else:
res = (4 * val) ** ((self.p - 5) / 8) * 2 * val
else:
raise Exception("modsqrt non supported for (p%8)==1")
if res.value % 2 == flag:
return res
else:
return -res | python | def sqrt(self, val, flag):
if val.iszero():
return val
sw = self.p % 8
if sw == 3 or sw == 7:
res = val ** ((self.p + 1) / 4)
elif sw == 5:
x = val ** ((self.p + 1) / 4)
if x == 1:
res = val ** ((self.p + 3) / 8)
else:
res = (4 * val) ** ((self.p - 5) / 8) * 2 * val
else:
raise Exception("modsqrt non supported for (p%8)==1")
if res.value % 2 == flag:
return res
else:
return -res | [
"def",
"sqrt",
"(",
"self",
",",
"val",
",",
"flag",
")",
":",
"if",
"val",
".",
"iszero",
"(",
")",
":",
"return",
"val",
"sw",
"=",
"self",
".",
"p",
"%",
"8",
"if",
"sw",
"==",
"3",
"or",
"sw",
"==",
"7",
":",
"res",
"=",
"val",
"**",
"(",
"(",
"self",
".",
"p",
"+",
"1",
")",
"/",
"4",
")",
"elif",
"sw",
"==",
"5",
":",
"x",
"=",
"val",
"**",
"(",
"(",
"self",
".",
"p",
"+",
"1",
")",
"/",
"4",
")",
"if",
"x",
"==",
"1",
":",
"res",
"=",
"val",
"**",
"(",
"(",
"self",
".",
"p",
"+",
"3",
")",
"/",
"8",
")",
"else",
":",
"res",
"=",
"(",
"4",
"*",
"val",
")",
"**",
"(",
"(",
"self",
".",
"p",
"-",
"5",
")",
"/",
"8",
")",
"*",
"2",
"*",
"val",
"else",
":",
"raise",
"Exception",
"(",
"\"modsqrt non supported for (p%8)==1\"",
")",
"if",
"res",
".",
"value",
"%",
"2",
"==",
"flag",
":",
"return",
"res",
"else",
":",
"return",
"-",
"res"
]
| calculate the square root modulus p | [
"calculate",
"the",
"square",
"root",
"modulus",
"p"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L287-L308 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | FiniteField.value | def value(self, x):
"""
converts an integer or FinitField.Value to a value of this FiniteField.
"""
return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x) | python | def value(self, x):
return x if isinstance(x, FiniteField.Value) and x.field == self else FiniteField.Value(self, x) | [
"def",
"value",
"(",
"self",
",",
"x",
")",
":",
"return",
"x",
"if",
"isinstance",
"(",
"x",
",",
"FiniteField",
".",
"Value",
")",
"and",
"x",
".",
"field",
"==",
"self",
"else",
"FiniteField",
".",
"Value",
"(",
"self",
",",
"x",
")"
]
| converts an integer or FinitField.Value to a value of this FiniteField. | [
"converts",
"an",
"integer",
"or",
"FinitField",
".",
"Value",
"to",
"a",
"value",
"of",
"this",
"FiniteField",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L316-L320 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | FiniteField.integer | def integer(self, x):
"""
returns a plain integer
"""
if type(x) is str:
hex = binascii.unhexlify(x)
return int.from_bytes(hex, 'big')
return x.value if isinstance(x, FiniteField.Value) else x | python | def integer(self, x):
if type(x) is str:
hex = binascii.unhexlify(x)
return int.from_bytes(hex, 'big')
return x.value if isinstance(x, FiniteField.Value) else x | [
"def",
"integer",
"(",
"self",
",",
"x",
")",
":",
"if",
"type",
"(",
"x",
")",
"is",
"str",
":",
"hex",
"=",
"binascii",
".",
"unhexlify",
"(",
"x",
")",
"return",
"int",
".",
"from_bytes",
"(",
"hex",
",",
"'big'",
")",
"return",
"x",
".",
"value",
"if",
"isinstance",
"(",
"x",
",",
"FiniteField",
".",
"Value",
")",
"else",
"x"
]
| returns a plain integer | [
"returns",
"a",
"plain",
"integer"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L322-L330 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.add | def add(self, p, q):
"""
perform elliptic curve addition
"""
if p.iszero():
return q
if q.iszero():
return p
lft = 0
# calculate the slope of the intersection line
if p == q:
if p.y == 0:
return self.zero()
lft = (3 * p.x ** 2 + self.a) / (2 * p.y)
elif p.x == q.x:
return self.zero()
else:
lft = (p.y - q.y) / (p.x - q.x)
# calculate the intersection point
x = lft ** 2 - (p.x + q.x)
y = lft * (p.x - x) - p.y
return self.point(x, y) | python | def add(self, p, q):
if p.iszero():
return q
if q.iszero():
return p
lft = 0
if p == q:
if p.y == 0:
return self.zero()
lft = (3 * p.x ** 2 + self.a) / (2 * p.y)
elif p.x == q.x:
return self.zero()
else:
lft = (p.y - q.y) / (p.x - q.x)
x = lft ** 2 - (p.x + q.x)
y = lft * (p.x - x) - p.y
return self.point(x, y) | [
"def",
"add",
"(",
"self",
",",
"p",
",",
"q",
")",
":",
"if",
"p",
".",
"iszero",
"(",
")",
":",
"return",
"q",
"if",
"q",
".",
"iszero",
"(",
")",
":",
"return",
"p",
"lft",
"=",
"0",
"# calculate the slope of the intersection line",
"if",
"p",
"==",
"q",
":",
"if",
"p",
".",
"y",
"==",
"0",
":",
"return",
"self",
".",
"zero",
"(",
")",
"lft",
"=",
"(",
"3",
"*",
"p",
".",
"x",
"**",
"2",
"+",
"self",
".",
"a",
")",
"/",
"(",
"2",
"*",
"p",
".",
"y",
")",
"elif",
"p",
".",
"x",
"==",
"q",
".",
"x",
":",
"return",
"self",
".",
"zero",
"(",
")",
"else",
":",
"lft",
"=",
"(",
"p",
".",
"y",
"-",
"q",
".",
"y",
")",
"/",
"(",
"p",
".",
"x",
"-",
"q",
".",
"x",
")",
"# calculate the intersection point",
"x",
"=",
"lft",
"**",
"2",
"-",
"(",
"p",
".",
"x",
"+",
"q",
".",
"x",
")",
"y",
"=",
"lft",
"*",
"(",
"p",
".",
"x",
"-",
"x",
")",
"-",
"p",
".",
"y",
"return",
"self",
".",
"point",
"(",
"x",
",",
"y",
")"
]
| perform elliptic curve addition | [
"perform",
"elliptic",
"curve",
"addition"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L486-L509 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.zero | def zero(self):
"""
Return the additive identity point ( aka '0' )
P + 0 = P
"""
return self.point(self.field.zero(), self.field.zero()) | python | def zero(self):
return self.point(self.field.zero(), self.field.zero()) | [
"def",
"zero",
"(",
"self",
")",
":",
"return",
"self",
".",
"point",
"(",
"self",
".",
"field",
".",
"zero",
"(",
")",
",",
"self",
".",
"field",
".",
"zero",
"(",
")",
")"
]
| Return the additive identity point ( aka '0' )
P + 0 = P | [
"Return",
"the",
"additive",
"identity",
"point",
"(",
"aka",
"0",
")",
"P",
"+",
"0",
"=",
"P"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L543-L548 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.point | def point(self, x, y):
"""
construct a point from 2 values
"""
return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y)) | python | def point(self, x, y):
return EllipticCurve.ECPoint(self, self.field.value(x), self.field.value(y)) | [
"def",
"point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"return",
"EllipticCurve",
".",
"ECPoint",
"(",
"self",
",",
"self",
".",
"field",
".",
"value",
"(",
"x",
")",
",",
"self",
".",
"field",
".",
"value",
"(",
"y",
")",
")"
]
| construct a point from 2 values | [
"construct",
"a",
"point",
"from",
"2",
"values"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L550-L554 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.isoncurve | def isoncurve(self, p):
"""
verifies if a point is on the curve
"""
return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b | python | def isoncurve(self, p):
return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b | [
"def",
"isoncurve",
"(",
"self",
",",
"p",
")",
":",
"return",
"p",
".",
"iszero",
"(",
")",
"or",
"p",
".",
"y",
"**",
"2",
"==",
"p",
".",
"x",
"**",
"3",
"+",
"self",
".",
"a",
"*",
"p",
".",
"x",
"+",
"self",
".",
"b"
]
| verifies if a point is on the curve | [
"verifies",
"if",
"a",
"point",
"is",
"on",
"the",
"curve"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L556-L560 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.decompress | def decompress(self, x, flag):
"""
calculate the y coordinate given only the x value.
there are 2 possible solutions, use 'flag' to select.
"""
x = self.field.value(x)
ysquare = x ** 3 + self.a * x + self.b
return self.point(x, ysquare.sqrt(flag)) | python | def decompress(self, x, flag):
x = self.field.value(x)
ysquare = x ** 3 + self.a * x + self.b
return self.point(x, ysquare.sqrt(flag)) | [
"def",
"decompress",
"(",
"self",
",",
"x",
",",
"flag",
")",
":",
"x",
"=",
"self",
".",
"field",
".",
"value",
"(",
"x",
")",
"ysquare",
"=",
"x",
"**",
"3",
"+",
"self",
".",
"a",
"*",
"x",
"+",
"self",
".",
"b",
"return",
"self",
".",
"point",
"(",
"x",
",",
"ysquare",
".",
"sqrt",
"(",
"flag",
")",
")"
]
| calculate the y coordinate given only the x value.
there are 2 possible solutions, use 'flag' to select. | [
"calculate",
"the",
"y",
"coordinate",
"given",
"only",
"the",
"x",
"value",
".",
"there",
"are",
"2",
"possible",
"solutions",
"use",
"flag",
"to",
"select",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L562-L570 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | EllipticCurve.decompress_from_curve | def decompress_from_curve(self, x, flag):
"""
calculate the y coordinate given only the x value.
there are 2 possible solutions, use 'flag' to select.
"""
cq = self.field.p
x = self.field.value(x)
ysquare = x ** 3 + self.a * x + self.b
ysquare_root = sqrtCQ(ysquare.value, cq)
bit0 = 0
if ysquare_root % 2 is not 0:
bit0 = 1
if bit0 != flag:
beta = (cq - ysquare_root) % cq
else:
beta = ysquare_root
return self.point(x, beta) | python | def decompress_from_curve(self, x, flag):
cq = self.field.p
x = self.field.value(x)
ysquare = x ** 3 + self.a * x + self.b
ysquare_root = sqrtCQ(ysquare.value, cq)
bit0 = 0
if ysquare_root % 2 is not 0:
bit0 = 1
if bit0 != flag:
beta = (cq - ysquare_root) % cq
else:
beta = ysquare_root
return self.point(x, beta) | [
"def",
"decompress_from_curve",
"(",
"self",
",",
"x",
",",
"flag",
")",
":",
"cq",
"=",
"self",
".",
"field",
".",
"p",
"x",
"=",
"self",
".",
"field",
".",
"value",
"(",
"x",
")",
"ysquare",
"=",
"x",
"**",
"3",
"+",
"self",
".",
"a",
"*",
"x",
"+",
"self",
".",
"b",
"ysquare_root",
"=",
"sqrtCQ",
"(",
"ysquare",
".",
"value",
",",
"cq",
")",
"bit0",
"=",
"0",
"if",
"ysquare_root",
"%",
"2",
"is",
"not",
"0",
":",
"bit0",
"=",
"1",
"if",
"bit0",
"!=",
"flag",
":",
"beta",
"=",
"(",
"cq",
"-",
"ysquare_root",
")",
"%",
"cq",
"else",
":",
"beta",
"=",
"ysquare_root",
"return",
"self",
".",
"point",
"(",
"x",
",",
"beta",
")"
]
| calculate the y coordinate given only the x value.
there are 2 possible solutions, use 'flag' to select. | [
"calculate",
"the",
"y",
"coordinate",
"given",
"only",
"the",
"x",
"value",
".",
"there",
"are",
"2",
"possible",
"solutions",
"use",
"flag",
"to",
"select",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L648-L670 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.sign | def sign(self, message, privkey, secret):
"""
sign the message using private key and sign secret
for signsecret k, message m, privatekey x
return (G*k, (m+x*r)/k)
"""
m = self.GFn.value(message)
x = self.GFn.value(privkey)
k = self.GFn.value(secret)
R = self.G * k
r = self.GFn.value(R.x)
s = (m + x * r) / k
return (r, s) | python | def sign(self, message, privkey, secret):
m = self.GFn.value(message)
x = self.GFn.value(privkey)
k = self.GFn.value(secret)
R = self.G * k
r = self.GFn.value(R.x)
s = (m + x * r) / k
return (r, s) | [
"def",
"sign",
"(",
"self",
",",
"message",
",",
"privkey",
",",
"secret",
")",
":",
"m",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"message",
")",
"x",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"privkey",
")",
"k",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"secret",
")",
"R",
"=",
"self",
".",
"G",
"*",
"k",
"r",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"R",
".",
"x",
")",
"s",
"=",
"(",
"m",
"+",
"x",
"*",
"r",
")",
"/",
"k",
"return",
"(",
"r",
",",
"s",
")"
]
| sign the message using private key and sign secret
for signsecret k, message m, privatekey x
return (G*k, (m+x*r)/k) | [
"sign",
"the",
"message",
"using",
"private",
"key",
"and",
"sign",
"secret",
"for",
"signsecret",
"k",
"message",
"m",
"privatekey",
"x",
"return",
"(",
"G",
"*",
"k",
"(",
"m",
"+",
"x",
"*",
"r",
")",
"/",
"k",
")"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L694-L709 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.verify | def verify(self, message, pubkey, rnum, snum):
"""
Verify the signature
for message m, pubkey Y, signature (r,s)
r = xcoord(R)
verify that : G*m+Y*r=R*s
this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k }
G*m+G*x*r = G*k*(m+x*r)/k ->
G*(m+x*r) = G*(m+x*r)
several ways to do the verification:
r == xcoord[ G*(m/s) + Y*(r/s) ] <<< the standard way
R * s == G*m + Y*r
r == xcoord[ (G*m + Y*r)/s) ]
"""
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
R = self.G * (m / s) + pubkey * (r / s)
# alternative methods of verifying
# RORG= self.ec.decompress(r, 0)
# RR = self.G * m + pubkey * r
# print "#1: %s .. %s" % (RR, RORG*s)
# print "#2: %s .. %s" % (RR*(1/s), r)
# print "#3: %s .. %s" % (R, r)
return R.x == r | python | def verify(self, message, pubkey, rnum, snum):
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
R = self.G * (m / s) + pubkey * (r / s)
return R.x == r | [
"def",
"verify",
"(",
"self",
",",
"message",
",",
"pubkey",
",",
"rnum",
",",
"snum",
")",
":",
"m",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"message",
")",
"r",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"rnum",
")",
"s",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"snum",
")",
"R",
"=",
"self",
".",
"G",
"*",
"(",
"m",
"/",
"s",
")",
"+",
"pubkey",
"*",
"(",
"r",
"/",
"s",
")",
"# alternative methods of verifying",
"# RORG= self.ec.decompress(r, 0)",
"# RR = self.G * m + pubkey * r",
"# print \"#1: %s .. %s\" % (RR, RORG*s)",
"# print \"#2: %s .. %s\" % (RR*(1/s), r)",
"# print \"#3: %s .. %s\" % (R, r)",
"return",
"R",
".",
"x",
"==",
"r"
]
| Verify the signature
for message m, pubkey Y, signature (r,s)
r = xcoord(R)
verify that : G*m+Y*r=R*s
this is true because: { Y=G*x, and R=G*k, s=(m+x*r)/k }
G*m+G*x*r = G*k*(m+x*r)/k ->
G*(m+x*r) = G*(m+x*r)
several ways to do the verification:
r == xcoord[ G*(m/s) + Y*(r/s) ] <<< the standard way
R * s == G*m + Y*r
r == xcoord[ (G*m + Y*r)/s) ] | [
"Verify",
"the",
"signature",
"for",
"message",
"m",
"pubkey",
"Y",
"signature",
"(",
"r",
"s",
")",
"r",
"=",
"xcoord",
"(",
"R",
")",
"verify",
"that",
":",
"G",
"*",
"m",
"+",
"Y",
"*",
"r",
"=",
"R",
"*",
"s",
"this",
"is",
"true",
"because",
":",
"{",
"Y",
"=",
"G",
"*",
"x",
"and",
"R",
"=",
"G",
"*",
"k",
"s",
"=",
"(",
"m",
"+",
"x",
"*",
"r",
")",
"/",
"k",
"}"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L711-L740 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.findpk | def findpk(self, message, rnum, snum, flag):
"""
find pubkey Y from message m, signature (r,s)
Y = (R*s-G*m)/r
note that there are 2 pubkeys related to a signature
"""
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
R = self.ec.decompress(r, flag)
# return (R*s - self.G * m)*(1/r)
return R * (s / r) - self.G * (m / r) | python | def findpk(self, message, rnum, snum, flag):
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
R = self.ec.decompress(r, flag)
return R * (s / r) - self.G * (m / r) | [
"def",
"findpk",
"(",
"self",
",",
"message",
",",
"rnum",
",",
"snum",
",",
"flag",
")",
":",
"m",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"message",
")",
"r",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"rnum",
")",
"s",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"snum",
")",
"R",
"=",
"self",
".",
"ec",
".",
"decompress",
"(",
"r",
",",
"flag",
")",
"# return (R*s - self.G * m)*(1/r)",
"return",
"R",
"*",
"(",
"s",
"/",
"r",
")",
"-",
"self",
".",
"G",
"*",
"(",
"m",
"/",
"r",
")"
]
| find pubkey Y from message m, signature (r,s)
Y = (R*s-G*m)/r
note that there are 2 pubkeys related to a signature | [
"find",
"pubkey",
"Y",
"from",
"message",
"m",
"signature",
"(",
"r",
"s",
")",
"Y",
"=",
"(",
"R",
"*",
"s",
"-",
"G",
"*",
"m",
")",
"/",
"r",
"note",
"that",
"there",
"are",
"2",
"pubkeys",
"related",
"to",
"a",
"signature"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L742-L755 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.findpk2 | def findpk2(self, r1, s1, r2, s2, flag1, flag2):
"""
find pubkey Y from 2 different signature on the same message
sigs: (r1,s1) and (r2,s2)
returns (R1*s1-R2*s2)/(r1-r2)
"""
R1 = self.ec.decompress(r1, flag1)
R2 = self.ec.decompress(r2, flag2)
rdiff = self.GFn.value(r1 - r2)
return (R1 * s1 - R2 * s2) * (1 / rdiff) | python | def findpk2(self, r1, s1, r2, s2, flag1, flag2):
R1 = self.ec.decompress(r1, flag1)
R2 = self.ec.decompress(r2, flag2)
rdiff = self.GFn.value(r1 - r2)
return (R1 * s1 - R2 * s2) * (1 / rdiff) | [
"def",
"findpk2",
"(",
"self",
",",
"r1",
",",
"s1",
",",
"r2",
",",
"s2",
",",
"flag1",
",",
"flag2",
")",
":",
"R1",
"=",
"self",
".",
"ec",
".",
"decompress",
"(",
"r1",
",",
"flag1",
")",
"R2",
"=",
"self",
".",
"ec",
".",
"decompress",
"(",
"r2",
",",
"flag2",
")",
"rdiff",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"r1",
"-",
"r2",
")",
"return",
"(",
"R1",
"*",
"s1",
"-",
"R2",
"*",
"s2",
")",
"*",
"(",
"1",
"/",
"rdiff",
")"
]
| find pubkey Y from 2 different signature on the same message
sigs: (r1,s1) and (r2,s2)
returns (R1*s1-R2*s2)/(r1-r2) | [
"find",
"pubkey",
"Y",
"from",
"2",
"different",
"signature",
"on",
"the",
"same",
"message",
"sigs",
":",
"(",
"r1",
"s1",
")",
"and",
"(",
"r2",
"s2",
")",
"returns",
"(",
"R1",
"*",
"s1",
"-",
"R2",
"*",
"s2",
")",
"/",
"(",
"r1",
"-",
"r2",
")"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L757-L768 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.crack2 | def crack2(self, r, s1, s2, m1, m2):
"""
find signsecret and privkey from duplicate 'r'
signature (r,s1) for message m1
and signature (r,s2) for message m2
s1= (m1 + x*r)/k
s2= (m2 + x*r)/k
subtract -> (s1-s2) = (m1-m2)/k -> k = (m1-m2)/(s1-s2)
-> privkey = (s1*k-m1)/r .. or (s2*k-m2)/r
"""
sdelta = self.GFn.value(s1 - s2)
mdelta = self.GFn.value(m1 - m2)
secret = mdelta / sdelta
x1 = self.crack1(r, s1, m1, secret)
x2 = self.crack1(r, s2, m2, secret)
if x1 != x2:
logger.info("x1= %s" % x1)
logger.info("x2= %s" % x2)
return (secret, x1) | python | def crack2(self, r, s1, s2, m1, m2):
sdelta = self.GFn.value(s1 - s2)
mdelta = self.GFn.value(m1 - m2)
secret = mdelta / sdelta
x1 = self.crack1(r, s1, m1, secret)
x2 = self.crack1(r, s2, m2, secret)
if x1 != x2:
logger.info("x1= %s" % x1)
logger.info("x2= %s" % x2)
return (secret, x1) | [
"def",
"crack2",
"(",
"self",
",",
"r",
",",
"s1",
",",
"s2",
",",
"m1",
",",
"m2",
")",
":",
"sdelta",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"s1",
"-",
"s2",
")",
"mdelta",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"m1",
"-",
"m2",
")",
"secret",
"=",
"mdelta",
"/",
"sdelta",
"x1",
"=",
"self",
".",
"crack1",
"(",
"r",
",",
"s1",
",",
"m1",
",",
"secret",
")",
"x2",
"=",
"self",
".",
"crack1",
"(",
"r",
",",
"s2",
",",
"m2",
",",
"secret",
")",
"if",
"x1",
"!=",
"x2",
":",
"logger",
".",
"info",
"(",
"\"x1= %s\"",
"%",
"x1",
")",
"logger",
".",
"info",
"(",
"\"x2= %s\"",
"%",
"x2",
")",
"return",
"(",
"secret",
",",
"x1",
")"
]
| find signsecret and privkey from duplicate 'r'
signature (r,s1) for message m1
and signature (r,s2) for message m2
s1= (m1 + x*r)/k
s2= (m2 + x*r)/k
subtract -> (s1-s2) = (m1-m2)/k -> k = (m1-m2)/(s1-s2)
-> privkey = (s1*k-m1)/r .. or (s2*k-m2)/r | [
"find",
"signsecret",
"and",
"privkey",
"from",
"duplicate",
"r",
"signature",
"(",
"r",
"s1",
")",
"for",
"message",
"m1",
"and",
"signature",
"(",
"r",
"s2",
")",
"for",
"message",
"m2",
"s1",
"=",
"(",
"m1",
"+",
"x",
"*",
"r",
")",
"/",
"k",
"s2",
"=",
"(",
"m2",
"+",
"x",
"*",
"r",
")",
"/",
"k",
"subtract",
"-",
">",
"(",
"s1",
"-",
"s2",
")",
"=",
"(",
"m1",
"-",
"m2",
")",
"/",
"k",
"-",
">",
"k",
"=",
"(",
"m1",
"-",
"m2",
")",
"/",
"(",
"s1",
"-",
"s2",
")",
"-",
">",
"privkey",
"=",
"(",
"s1",
"*",
"k",
"-",
"m1",
")",
"/",
"r",
"..",
"or",
"(",
"s2",
"*",
"k",
"-",
"m2",
")",
"/",
"r"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L770-L791 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.crack1 | def crack1(self, rnum, snum, message, signsecret):
"""
find privkey, given signsecret k, message m, signature (r,s)
x= (s*k-m)/r
"""
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
k = self.GFn.value(signsecret)
return (s * k - m) / r | python | def crack1(self, rnum, snum, message, signsecret):
m = self.GFn.value(message)
r = self.GFn.value(rnum)
s = self.GFn.value(snum)
k = self.GFn.value(signsecret)
return (s * k - m) / r | [
"def",
"crack1",
"(",
"self",
",",
"rnum",
",",
"snum",
",",
"message",
",",
"signsecret",
")",
":",
"m",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"message",
")",
"r",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"rnum",
")",
"s",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"snum",
")",
"k",
"=",
"self",
".",
"GFn",
".",
"value",
"(",
"signsecret",
")",
"return",
"(",
"s",
"*",
"k",
"-",
"m",
")",
"/",
"r"
]
| find privkey, given signsecret k, message m, signature (r,s)
x= (s*k-m)/r | [
"find",
"privkey",
"given",
"signsecret",
"k",
"message",
"m",
"signature",
"(",
"r",
"s",
")",
"x",
"=",
"(",
"s",
"*",
"k",
"-",
"m",
")",
"/",
"r"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L793-L802 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.secp256r1 | def secp256r1():
"""
create the secp256r1 curve
"""
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291)
# return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
return ECDSA(ec,
ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),
GFp) | python | def secp256r1():
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948, 41058363725152142129326129780047268409114441015993725554835256314039467401291)
return ECDSA(ec,
ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296, 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),
GFp) | [
"def",
"secp256r1",
"(",
")",
":",
"GFp",
"=",
"FiniteField",
"(",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\"",
",",
"16",
")",
")",
"ec",
"=",
"EllipticCurve",
"(",
"GFp",
",",
"115792089210356248762697446949407573530086143415290314195533631308867097853948",
",",
"41058363725152142129326129780047268409114441015993725554835256314039467401291",
")",
"# return ECDSA(GFp, ec.point(0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5),int(\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\", 16))",
"return",
"ECDSA",
"(",
"ec",
",",
"ec",
".",
"point",
"(",
"0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296",
",",
"0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5",
")",
",",
"GFp",
")"
]
| create the secp256r1 curve | [
"create",
"the",
"secp256r1",
"curve"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L805-L814 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.decode_secp256r1 | def decode_secp256r1(str, unhex=True, check_on_curve=True):
"""
decode a public key on the secp256r1 curve
"""
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948,
41058363725152142129326129780047268409114441015993725554835256314039467401291)
point = ec.decode_from_hex(str, unhex=unhex)
if check_on_curve:
if point.isoncurve():
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
else:
raise Exception("Could not decode string")
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) | python | def decode_secp256r1(str, unhex=True, check_on_curve=True):
GFp = FiniteField(int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", 16))
ec = EllipticCurve(GFp, 115792089210356248762697446949407573530086143415290314195533631308867097853948,
41058363725152142129326129780047268409114441015993725554835256314039467401291)
point = ec.decode_from_hex(str, unhex=unhex)
if check_on_curve:
if point.isoncurve():
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16))
else:
raise Exception("Could not decode string")
return ECDSA(GFp, point, int("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", 16)) | [
"def",
"decode_secp256r1",
"(",
"str",
",",
"unhex",
"=",
"True",
",",
"check_on_curve",
"=",
"True",
")",
":",
"GFp",
"=",
"FiniteField",
"(",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\"",
",",
"16",
")",
")",
"ec",
"=",
"EllipticCurve",
"(",
"GFp",
",",
"115792089210356248762697446949407573530086143415290314195533631308867097853948",
",",
"41058363725152142129326129780047268409114441015993725554835256314039467401291",
")",
"point",
"=",
"ec",
".",
"decode_from_hex",
"(",
"str",
",",
"unhex",
"=",
"unhex",
")",
"if",
"check_on_curve",
":",
"if",
"point",
".",
"isoncurve",
"(",
")",
":",
"return",
"ECDSA",
"(",
"GFp",
",",
"point",
",",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\"",
",",
"16",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Could not decode string\"",
")",
"return",
"ECDSA",
"(",
"GFp",
",",
"point",
",",
"int",
"(",
"\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\"",
",",
"16",
")",
")"
]
| decode a public key on the secp256r1 curve | [
"decode",
"a",
"public",
"key",
"on",
"the",
"secp256r1",
"curve"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L817-L834 |
CityOfZion/neo-python-core | neocore/Cryptography/ECCurve.py | ECDSA.secp256k1 | def secp256k1():
"""
create the secp256k1 curve
"""
GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
ec = EllipticCurve(GFp, 0, 7)
return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599) | python | def secp256k1():
GFp = FiniteField(2 ** 256 - 2 ** 32 - 977)
ec = EllipticCurve(GFp, 0, 7)
return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8), 2 ** 256 - 432420386565659656852420866394968145599) | [
"def",
"secp256k1",
"(",
")",
":",
"GFp",
"=",
"FiniteField",
"(",
"2",
"**",
"256",
"-",
"2",
"**",
"32",
"-",
"977",
")",
"# This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F",
"ec",
"=",
"EllipticCurve",
"(",
"GFp",
",",
"0",
",",
"7",
")",
"return",
"ECDSA",
"(",
"ec",
",",
"ec",
".",
"point",
"(",
"0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798",
",",
"0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8",
")",
",",
"2",
"**",
"256",
"-",
"432420386565659656852420866394968145599",
")"
]
| create the secp256k1 curve | [
"create",
"the",
"secp256k1",
"curve"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/ECCurve.py#L864-L870 |
CityOfZion/neo-python-core | neocore/UIntBase.py | UIntBase.GetHashCode | def GetHashCode(self):
"""uint32 identifier"""
slice_length = 4 if len(self.Data) >= 4 else len(self.Data)
return int.from_bytes(self.Data[:slice_length], 'little') | python | def GetHashCode(self):
slice_length = 4 if len(self.Data) >= 4 else len(self.Data)
return int.from_bytes(self.Data[:slice_length], 'little') | [
"def",
"GetHashCode",
"(",
"self",
")",
":",
"slice_length",
"=",
"4",
"if",
"len",
"(",
"self",
".",
"Data",
")",
">=",
"4",
"else",
"len",
"(",
"self",
".",
"Data",
")",
"return",
"int",
".",
"from_bytes",
"(",
"self",
".",
"Data",
"[",
":",
"slice_length",
"]",
",",
"'little'",
")"
]
| uint32 identifier | [
"uint32",
"identifier"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/UIntBase.py#L33-L36 |
CityOfZion/neo-python-core | neocore/Utils.py | isValidPublicAddress | def isValidPublicAddress(address: str) -> bool:
"""Check if address is a valid NEO address"""
valid = False
if len(address) == 34 and address[0] == 'A':
try:
base58.b58decode_check(address.encode())
valid = True
except ValueError:
# checksum mismatch
valid = False
return valid | python | def isValidPublicAddress(address: str) -> bool:
valid = False
if len(address) == 34 and address[0] == 'A':
try:
base58.b58decode_check(address.encode())
valid = True
except ValueError:
valid = False
return valid | [
"def",
"isValidPublicAddress",
"(",
"address",
":",
"str",
")",
"->",
"bool",
":",
"valid",
"=",
"False",
"if",
"len",
"(",
"address",
")",
"==",
"34",
"and",
"address",
"[",
"0",
"]",
"==",
"'A'",
":",
"try",
":",
"base58",
".",
"b58decode_check",
"(",
"address",
".",
"encode",
"(",
")",
")",
"valid",
"=",
"True",
"except",
"ValueError",
":",
"# checksum mismatch",
"valid",
"=",
"False",
"return",
"valid"
]
| Check if address is a valid NEO address | [
"Check",
"if",
"address",
"is",
"a",
"valid",
"NEO",
"address"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Utils.py#L4-L16 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.__Build | def __Build(leaves):
"""
Build the merkle tree.
Args:
leaves (list): items are of type MerkleTreeNode.
Returns:
MerkleTreeNode: the root node.
"""
if len(leaves) < 1:
raise Exception('Leaves must have length')
if len(leaves) == 1:
return leaves[0]
num_parents = int((len(leaves) + 1) / 2)
parents = [MerkleTreeNode() for i in range(0, num_parents)]
for i in range(0, num_parents):
node = parents[i]
node.LeftChild = leaves[i * 2]
leaves[i * 2].Parent = node
if (i * 2 + 1 == len(leaves)):
node.RightChild = node.LeftChild
else:
node.RightChild = leaves[i * 2 + 1]
leaves[i * 2 + 1].Parent = node
hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray())
node.Hash = UInt256(data=Crypto.Hash256(hasharray))
return MerkleTree.__Build(parents) | python | def __Build(leaves):
if len(leaves) < 1:
raise Exception('Leaves must have length')
if len(leaves) == 1:
return leaves[0]
num_parents = int((len(leaves) + 1) / 2)
parents = [MerkleTreeNode() for i in range(0, num_parents)]
for i in range(0, num_parents):
node = parents[i]
node.LeftChild = leaves[i * 2]
leaves[i * 2].Parent = node
if (i * 2 + 1 == len(leaves)):
node.RightChild = node.LeftChild
else:
node.RightChild = leaves[i * 2 + 1]
leaves[i * 2 + 1].Parent = node
hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray())
node.Hash = UInt256(data=Crypto.Hash256(hasharray))
return MerkleTree.__Build(parents) | [
"def",
"__Build",
"(",
"leaves",
")",
":",
"if",
"len",
"(",
"leaves",
")",
"<",
"1",
":",
"raise",
"Exception",
"(",
"'Leaves must have length'",
")",
"if",
"len",
"(",
"leaves",
")",
"==",
"1",
":",
"return",
"leaves",
"[",
"0",
"]",
"num_parents",
"=",
"int",
"(",
"(",
"len",
"(",
"leaves",
")",
"+",
"1",
")",
"/",
"2",
")",
"parents",
"=",
"[",
"MerkleTreeNode",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_parents",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_parents",
")",
":",
"node",
"=",
"parents",
"[",
"i",
"]",
"node",
".",
"LeftChild",
"=",
"leaves",
"[",
"i",
"*",
"2",
"]",
"leaves",
"[",
"i",
"*",
"2",
"]",
".",
"Parent",
"=",
"node",
"if",
"(",
"i",
"*",
"2",
"+",
"1",
"==",
"len",
"(",
"leaves",
")",
")",
":",
"node",
".",
"RightChild",
"=",
"node",
".",
"LeftChild",
"else",
":",
"node",
".",
"RightChild",
"=",
"leaves",
"[",
"i",
"*",
"2",
"+",
"1",
"]",
"leaves",
"[",
"i",
"*",
"2",
"+",
"1",
"]",
".",
"Parent",
"=",
"node",
"hasharray",
"=",
"bytearray",
"(",
"node",
".",
"LeftChild",
".",
"Hash",
".",
"ToArray",
"(",
")",
"+",
"node",
".",
"RightChild",
".",
"Hash",
".",
"ToArray",
"(",
")",
")",
"node",
".",
"Hash",
"=",
"UInt256",
"(",
"data",
"=",
"Crypto",
".",
"Hash256",
"(",
"hasharray",
")",
")",
"return",
"MerkleTree",
".",
"__Build",
"(",
"parents",
")"
]
| Build the merkle tree.
Args:
leaves (list): items are of type MerkleTreeNode.
Returns:
MerkleTreeNode: the root node. | [
"Build",
"the",
"merkle",
"tree",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L70-L101 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.ComputeRoot | def ComputeRoot(hashes):
"""
Compute the root hash.
Args:
hashes (list): the list of hashes to build the root from.
Returns:
bytes: the root hash.
"""
if not len(hashes):
raise Exception('Hashes must have length')
if len(hashes) == 1:
return hashes[0]
tree = MerkleTree(hashes)
return tree.Root.Hash | python | def ComputeRoot(hashes):
if not len(hashes):
raise Exception('Hashes must have length')
if len(hashes) == 1:
return hashes[0]
tree = MerkleTree(hashes)
return tree.Root.Hash | [
"def",
"ComputeRoot",
"(",
"hashes",
")",
":",
"if",
"not",
"len",
"(",
"hashes",
")",
":",
"raise",
"Exception",
"(",
"'Hashes must have length'",
")",
"if",
"len",
"(",
"hashes",
")",
"==",
"1",
":",
"return",
"hashes",
"[",
"0",
"]",
"tree",
"=",
"MerkleTree",
"(",
"hashes",
")",
"return",
"tree",
".",
"Root",
".",
"Hash"
]
| Compute the root hash.
Args:
hashes (list): the list of hashes to build the root from.
Returns:
bytes: the root hash. | [
"Compute",
"the",
"root",
"hash",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L109-L125 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.__DepthFirstSearch | def __DepthFirstSearch(node, hashes):
"""
Internal helper method.
Args:
node (MerkleTreeNode):
hashes (list): each item is a bytearray.
"""
if node.LeftChild is None:
hashes.add(node.Hash)
else:
MerkleTree.__DepthFirstSearch(node.LeftChild, hashes)
MerkleTree.__DepthFirstSearch(node.RightChild, hashes) | python | def __DepthFirstSearch(node, hashes):
if node.LeftChild is None:
hashes.add(node.Hash)
else:
MerkleTree.__DepthFirstSearch(node.LeftChild, hashes)
MerkleTree.__DepthFirstSearch(node.RightChild, hashes) | [
"def",
"__DepthFirstSearch",
"(",
"node",
",",
"hashes",
")",
":",
"if",
"node",
".",
"LeftChild",
"is",
"None",
":",
"hashes",
".",
"add",
"(",
"node",
".",
"Hash",
")",
"else",
":",
"MerkleTree",
".",
"__DepthFirstSearch",
"(",
"node",
".",
"LeftChild",
",",
"hashes",
")",
"MerkleTree",
".",
"__DepthFirstSearch",
"(",
"node",
".",
"RightChild",
",",
"hashes",
")"
]
| Internal helper method.
Args:
node (MerkleTreeNode):
hashes (list): each item is a bytearray. | [
"Internal",
"helper",
"method",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L128-L140 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.ToHashArray | def ToHashArray(self):
"""
Turn the tree into a list of hashes.
Returns:
list:
"""
hashes = set()
MerkleTree.__DepthFirstSearch(self.Root, hashes)
return list(hashes) | python | def ToHashArray(self):
hashes = set()
MerkleTree.__DepthFirstSearch(self.Root, hashes)
return list(hashes) | [
"def",
"ToHashArray",
"(",
"self",
")",
":",
"hashes",
"=",
"set",
"(",
")",
"MerkleTree",
".",
"__DepthFirstSearch",
"(",
"self",
".",
"Root",
",",
"hashes",
")",
"return",
"list",
"(",
"hashes",
")"
]
| Turn the tree into a list of hashes.
Returns:
list: | [
"Turn",
"the",
"tree",
"into",
"a",
"list",
"of",
"hashes",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L142-L151 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree.Trim | def Trim(self, flags):
"""
Trim the nodes from the tree keeping only the root hash.
Args:
flags: "0000" for trimming, any other value for keeping the nodes.
"""
logger.info("Trimming!")
flags = bytearray(flags)
length = 1 << self.Depth - 1
while len(flags) < length:
flags.append(0)
MerkleTree._TrimNode(self.Root, 0, self.Depth, flags) | python | def Trim(self, flags):
logger.info("Trimming!")
flags = bytearray(flags)
length = 1 << self.Depth - 1
while len(flags) < length:
flags.append(0)
MerkleTree._TrimNode(self.Root, 0, self.Depth, flags) | [
"def",
"Trim",
"(",
"self",
",",
"flags",
")",
":",
"logger",
".",
"info",
"(",
"\"Trimming!\"",
")",
"flags",
"=",
"bytearray",
"(",
"flags",
")",
"length",
"=",
"1",
"<<",
"self",
".",
"Depth",
"-",
"1",
"while",
"len",
"(",
"flags",
")",
"<",
"length",
":",
"flags",
".",
"append",
"(",
"0",
")",
"MerkleTree",
".",
"_TrimNode",
"(",
"self",
".",
"Root",
",",
"0",
",",
"self",
".",
"Depth",
",",
"flags",
")"
]
| Trim the nodes from the tree keeping only the root hash.
Args:
flags: "0000" for trimming, any other value for keeping the nodes. | [
"Trim",
"the",
"nodes",
"from",
"the",
"tree",
"keeping",
"only",
"the",
"root",
"hash",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L153-L166 |
CityOfZion/neo-python-core | neocore/Cryptography/MerkleTree.py | MerkleTree._TrimNode | def _TrimNode(node, index, depth, flags):
"""
Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node.
00 to erase, 11 to keep. Will keep the node if either left or right is not-0
"""
if depth == 1 or node.LeftChild is None:
return
if depth == 2:
if not flags[index * 2] and not flags[index * 2 + 1]:
node.LeftChild = None
node.RightChild = None
else:
MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags)
MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags)
if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None:
node.LeftChild = None
node.RightChild = None | python | def _TrimNode(node, index, depth, flags):
if depth == 1 or node.LeftChild is None:
return
if depth == 2:
if not flags[index * 2] and not flags[index * 2 + 1]:
node.LeftChild = None
node.RightChild = None
else:
MerkleTree._TrimNode(node.LeftChild, index * 2, depth - 1, flags)
MerkleTree._TrimNode(node.RightChild, index * 2, depth - 1, flags)
if node.LeftChild.LeftChild is None and node.RightChild.RightChild is None:
node.LeftChild = None
node.RightChild = None | [
"def",
"_TrimNode",
"(",
"node",
",",
"index",
",",
"depth",
",",
"flags",
")",
":",
"if",
"depth",
"==",
"1",
"or",
"node",
".",
"LeftChild",
"is",
"None",
":",
"return",
"if",
"depth",
"==",
"2",
":",
"if",
"not",
"flags",
"[",
"index",
"*",
"2",
"]",
"and",
"not",
"flags",
"[",
"index",
"*",
"2",
"+",
"1",
"]",
":",
"node",
".",
"LeftChild",
"=",
"None",
"node",
".",
"RightChild",
"=",
"None",
"else",
":",
"MerkleTree",
".",
"_TrimNode",
"(",
"node",
".",
"LeftChild",
",",
"index",
"*",
"2",
",",
"depth",
"-",
"1",
",",
"flags",
")",
"MerkleTree",
".",
"_TrimNode",
"(",
"node",
".",
"RightChild",
",",
"index",
"*",
"2",
",",
"depth",
"-",
"1",
",",
"flags",
")",
"if",
"node",
".",
"LeftChild",
".",
"LeftChild",
"is",
"None",
"and",
"node",
".",
"RightChild",
".",
"RightChild",
"is",
"None",
":",
"node",
".",
"LeftChild",
"=",
"None",
"node",
".",
"RightChild",
"=",
"None"
]
| Internal helper method to trim a node.
Args:
node (MerkleTreeNode):
index (int): flag index.
depth (int): node tree depth to start trim from.
flags (bytearray): of left/right pairs. 1 byte for the left node, 1 byte for the right node.
00 to erase, 11 to keep. Will keep the node if either left or right is not-0 | [
"Internal",
"helper",
"method",
"to",
"trim",
"a",
"node",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/MerkleTree.py#L169-L195 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | double_sha256 | def double_sha256(ba):
"""
Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string.
"""
d1 = hashlib.sha256(ba)
d2 = hashlib.sha256()
d1.hexdigest()
d2.update(d1.digest())
return d2.hexdigest() | python | def double_sha256(ba):
d1 = hashlib.sha256(ba)
d2 = hashlib.sha256()
d1.hexdigest()
d2.update(d1.digest())
return d2.hexdigest() | [
"def",
"double_sha256",
"(",
"ba",
")",
":",
"d1",
"=",
"hashlib",
".",
"sha256",
"(",
"ba",
")",
"d2",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"d1",
".",
"hexdigest",
"(",
")",
"d2",
".",
"update",
"(",
"d1",
".",
"digest",
"(",
")",
")",
"return",
"d2",
".",
"hexdigest",
"(",
")"
]
| Perform two SHA256 operations on the input.
Args:
ba (bytes): data to hash.
Returns:
str: hash as a double digit hex string. | [
"Perform",
"two",
"SHA256",
"operations",
"on",
"the",
"input",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L28-L42 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | scripthash_to_address | def scripthash_to_address(scripthash):
"""
Convert a script hash to a public address.
Args:
scripthash (bytes):
Returns:
str: base58 encoded string representing the wallet address.
"""
sb = bytearray([ADDRESS_VERSION]) + scripthash
c256 = bin_dbl_sha256(sb)[0:4]
outb = sb + bytearray(c256)
return base58.b58encode(bytes(outb)).decode("utf-8") | python | def scripthash_to_address(scripthash):
sb = bytearray([ADDRESS_VERSION]) + scripthash
c256 = bin_dbl_sha256(sb)[0:4]
outb = sb + bytearray(c256)
return base58.b58encode(bytes(outb)).decode("utf-8") | [
"def",
"scripthash_to_address",
"(",
"scripthash",
")",
":",
"sb",
"=",
"bytearray",
"(",
"[",
"ADDRESS_VERSION",
"]",
")",
"+",
"scripthash",
"c256",
"=",
"bin_dbl_sha256",
"(",
"sb",
")",
"[",
"0",
":",
"4",
"]",
"outb",
"=",
"sb",
"+",
"bytearray",
"(",
"c256",
")",
"return",
"base58",
".",
"b58encode",
"(",
"bytes",
"(",
"outb",
")",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
]
| Convert a script hash to a public address.
Args:
scripthash (bytes):
Returns:
str: base58 encoded string representing the wallet address. | [
"Convert",
"a",
"script",
"hash",
"to",
"a",
"public",
"address",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L71-L84 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | bin_hash160Bytes | def bin_hash160Bytes(bts):
"""
Get a hash of the provided message using the ripemd160 algorithm.
Args:
bts (str): message to hash.
Returns:
bytes: hash.
"""
intermed = hashlib.sha256(bts).digest()
return hashlib.new('ripemd160', intermed).digest() | python | def bin_hash160Bytes(bts):
intermed = hashlib.sha256(bts).digest()
return hashlib.new('ripemd160', intermed).digest() | [
"def",
"bin_hash160Bytes",
"(",
"bts",
")",
":",
"intermed",
"=",
"hashlib",
".",
"sha256",
"(",
"bts",
")",
".",
"digest",
"(",
")",
"return",
"hashlib",
".",
"new",
"(",
"'ripemd160'",
",",
"intermed",
")",
".",
"digest",
"(",
")"
]
| Get a hash of the provided message using the ripemd160 algorithm.
Args:
bts (str): message to hash.
Returns:
bytes: hash. | [
"Get",
"a",
"hash",
"of",
"the",
"provided",
"message",
"using",
"the",
"ripemd160",
"algorithm",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L113-L124 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | bin_hash160 | def bin_hash160(string):
"""
Get a hash of the provided message using the ripemd160 algorithm.
Args:
string (str): message to hash.
Returns:
str: hash as a double digit hex string.
"""
intermed = hashlib.sha256(string).digest()
return hashlib.new('ripemd160', intermed).hexdigest() | python | def bin_hash160(string):
intermed = hashlib.sha256(string).digest()
return hashlib.new('ripemd160', intermed).hexdigest() | [
"def",
"bin_hash160",
"(",
"string",
")",
":",
"intermed",
"=",
"hashlib",
".",
"sha256",
"(",
"string",
")",
".",
"digest",
"(",
")",
"return",
"hashlib",
".",
"new",
"(",
"'ripemd160'",
",",
"intermed",
")",
".",
"hexdigest",
"(",
")"
]
| Get a hash of the provided message using the ripemd160 algorithm.
Args:
string (str): message to hash.
Returns:
str: hash as a double digit hex string. | [
"Get",
"a",
"hash",
"of",
"the",
"provided",
"message",
"using",
"the",
"ripemd160",
"algorithm",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L127-L138 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | base256_encode | def base256_encode(n, minwidth=0): # int/long to byte array
"""
Encode the input with base256.
Args:
n (int): input value.
minwidth: minimum return value length.
Raises:
ValueError: if a negative number is provided.
Returns:
bytearray:
"""
if n > 0:
arr = []
while n:
n, rem = divmod(n, 256)
arr.append(rem)
b = bytearray(reversed(arr))
elif n == 0:
b = bytearray(b'\x00')
else:
raise ValueError("Negative numbers not supported")
if minwidth > 0 and len(b) < minwidth: # zero padding needed?
padding = (minwidth - len(b)) * b'\x00'
b = bytearray(padding) + b
b.reverse()
return b | python | def base256_encode(n, minwidth=0):
if n > 0:
arr = []
while n:
n, rem = divmod(n, 256)
arr.append(rem)
b = bytearray(reversed(arr))
elif n == 0:
b = bytearray(b'\x00')
else:
raise ValueError("Negative numbers not supported")
if minwidth > 0 and len(b) < minwidth:
padding = (minwidth - len(b)) * b'\x00'
b = bytearray(padding) + b
b.reverse()
return b | [
"def",
"base256_encode",
"(",
"n",
",",
"minwidth",
"=",
"0",
")",
":",
"# int/long to byte array",
"if",
"n",
">",
"0",
":",
"arr",
"=",
"[",
"]",
"while",
"n",
":",
"n",
",",
"rem",
"=",
"divmod",
"(",
"n",
",",
"256",
")",
"arr",
".",
"append",
"(",
"rem",
")",
"b",
"=",
"bytearray",
"(",
"reversed",
"(",
"arr",
")",
")",
"elif",
"n",
"==",
"0",
":",
"b",
"=",
"bytearray",
"(",
"b'\\x00'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Negative numbers not supported\"",
")",
"if",
"minwidth",
">",
"0",
"and",
"len",
"(",
"b",
")",
"<",
"minwidth",
":",
"# zero padding needed?",
"padding",
"=",
"(",
"minwidth",
"-",
"len",
"(",
"b",
")",
")",
"*",
"b'\\x00'",
"b",
"=",
"bytearray",
"(",
"padding",
")",
"+",
"b",
"b",
".",
"reverse",
"(",
")",
"return",
"b"
]
| Encode the input with base256.
Args:
n (int): input value.
minwidth: minimum return value length.
Raises:
ValueError: if a negative number is provided.
Returns:
bytearray: | [
"Encode",
"the",
"input",
"with",
"base256",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L141-L171 |
CityOfZion/neo-python-core | neocore/Cryptography/Helper.py | xor_bytes | def xor_bytes(a, b):
"""
XOR on two bytes objects
Args:
a (bytes): object 1
b (bytes): object 2
Returns:
bytes: The XOR result
"""
assert isinstance(a, bytes)
assert isinstance(b, bytes)
assert len(a) == len(b)
res = bytearray()
for i in range(len(a)):
res.append(a[i] ^ b[i])
return bytes(res) | python | def xor_bytes(a, b):
assert isinstance(a, bytes)
assert isinstance(b, bytes)
assert len(a) == len(b)
res = bytearray()
for i in range(len(a)):
res.append(a[i] ^ b[i])
return bytes(res) | [
"def",
"xor_bytes",
"(",
"a",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"bytes",
")",
"assert",
"isinstance",
"(",
"b",
",",
"bytes",
")",
"assert",
"len",
"(",
"a",
")",
"==",
"len",
"(",
"b",
")",
"res",
"=",
"bytearray",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
":",
"res",
".",
"append",
"(",
"a",
"[",
"i",
"]",
"^",
"b",
"[",
"i",
"]",
")",
"return",
"bytes",
"(",
"res",
")"
]
| XOR on two bytes objects
Args:
a (bytes): object 1
b (bytes): object 2
Returns:
bytes: The XOR result | [
"XOR",
"on",
"two",
"bytes",
"objects"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/Cryptography/Helper.py#L174-L191 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteBytes | def WriteBytes(self, value, unhex=True):
"""
Write a `bytes` type to the stream.
Args:
value (bytes): array of bytes to write to the stream.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
int: the number of bytes written.
"""
if unhex:
try:
value = binascii.unhexlify(value)
except binascii.Error:
pass
return self.stream.write(value) | python | def WriteBytes(self, value, unhex=True):
if unhex:
try:
value = binascii.unhexlify(value)
except binascii.Error:
pass
return self.stream.write(value) | [
"def",
"WriteBytes",
"(",
"self",
",",
"value",
",",
"unhex",
"=",
"True",
")",
":",
"if",
"unhex",
":",
"try",
":",
"value",
"=",
"binascii",
".",
"unhexlify",
"(",
"value",
")",
"except",
"binascii",
".",
"Error",
":",
"pass",
"return",
"self",
".",
"stream",
".",
"write",
"(",
"value",
")"
]
| Write a `bytes` type to the stream.
Args:
value (bytes): array of bytes to write to the stream.
unhex (bool): (Default) True. Set to unhexlify the stream. Use when the bytes are not raw bytes; i.e. b'aabb'
Returns:
int: the number of bytes written. | [
"Write",
"a",
"bytes",
"type",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L88-L104 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.pack | def pack(self, fmt, data):
"""
Write bytes by packing them according to the provided format `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
data (object): the data to write to the raw stream.
Returns:
int: the number of bytes written.
"""
return self.WriteBytes(struct.pack(fmt, data), unhex=False) | python | def pack(self, fmt, data):
return self.WriteBytes(struct.pack(fmt, data), unhex=False) | [
"def",
"pack",
"(",
"self",
",",
"fmt",
",",
"data",
")",
":",
"return",
"self",
".",
"WriteBytes",
"(",
"struct",
".",
"pack",
"(",
"fmt",
",",
"data",
")",
",",
"unhex",
"=",
"False",
")"
]
| Write bytes by packing them according to the provided format `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
data (object): the data to write to the raw stream.
Returns:
int: the number of bytes written. | [
"Write",
"bytes",
"by",
"packing",
"them",
"according",
"to",
"the",
"provided",
"format",
"fmt",
".",
"For",
"more",
"information",
"about",
"the",
"fmt",
"format",
"see",
":",
"https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"struct",
".",
"html"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L106-L118 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteUInt160 | def WriteUInt160(self, value):
"""
Write a UInt160 type to the stream.
Args:
value (UInt160):
Raises:
Exception: when `value` is not of neocore.UInt160 type.
"""
if type(value) is UInt160:
value.Serialize(self)
else:
raise Exception("value must be UInt160 instance ") | python | def WriteUInt160(self, value):
if type(value) is UInt160:
value.Serialize(self)
else:
raise Exception("value must be UInt160 instance ") | [
"def",
"WriteUInt160",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"UInt160",
":",
"value",
".",
"Serialize",
"(",
"self",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"value must be UInt160 instance \"",
")"
]
| Write a UInt160 type to the stream.
Args:
value (UInt160):
Raises:
Exception: when `value` is not of neocore.UInt160 type. | [
"Write",
"a",
"UInt160",
"type",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L274-L287 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteUInt256 | def WriteUInt256(self, value):
"""
Write a UInt256 type to the stream.
Args:
value (UInt256):
Raises:
Exception: when `value` is not of neocore.UInt256 type.
"""
if type(value) is UInt256:
value.Serialize(self)
else:
raise Exception("Cannot write value that is not UInt256") | python | def WriteUInt256(self, value):
if type(value) is UInt256:
value.Serialize(self)
else:
raise Exception("Cannot write value that is not UInt256") | [
"def",
"WriteUInt256",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"UInt256",
":",
"value",
".",
"Serialize",
"(",
"self",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Cannot write value that is not UInt256\"",
")"
]
| Write a UInt256 type to the stream.
Args:
value (UInt256):
Raises:
Exception: when `value` is not of neocore.UInt256 type. | [
"Write",
"a",
"UInt256",
"type",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L289-L302 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteVarBytes | def WriteVarBytes(self, value, endian="<"):
"""
Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specify the endianness. (Default) Little endian ('<'). Use '>' for big endian.
Returns:
int: the number of bytes written.
"""
length = len(value)
self.WriteVarInt(length, endian)
return self.WriteBytes(value, unhex=False) | python | def WriteVarBytes(self, value, endian="<"):
length = len(value)
self.WriteVarInt(length, endian)
return self.WriteBytes(value, unhex=False) | [
"def",
"WriteVarBytes",
"(",
"self",
",",
"value",
",",
"endian",
"=",
"\"<\"",
")",
":",
"length",
"=",
"len",
"(",
"value",
")",
"self",
".",
"WriteVarInt",
"(",
"length",
",",
"endian",
")",
"return",
"self",
".",
"WriteBytes",
"(",
"value",
",",
"unhex",
"=",
"False",
")"
]
| Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specify the endianness. (Default) Little endian ('<'). Use '>' for big endian.
Returns:
int: the number of bytes written. | [
"Write",
"an",
"integer",
"value",
"in",
"a",
"space",
"saving",
"way",
"to",
"the",
"stream",
".",
"Read",
"more",
"about",
"variable",
"size",
"encoding",
"here",
":",
"http",
":",
"//",
"docs",
".",
"neo",
".",
"org",
"/",
"en",
"-",
"us",
"/",
"node",
"/",
"network",
"-",
"protocol",
".",
"html#convention"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L341-L356 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteVarString | def WriteVarString(self, value, encoding="utf-8"):
"""
Write a string value to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (string): value to write to the stream.
encoding (str): string encoding format.
"""
if type(value) is str:
value = value.encode(encoding)
length = len(value)
ba = bytearray(value)
byts = binascii.hexlify(ba)
string = byts.decode(encoding)
self.WriteVarInt(length)
self.WriteBytes(string) | python | def WriteVarString(self, value, encoding="utf-8"):
if type(value) is str:
value = value.encode(encoding)
length = len(value)
ba = bytearray(value)
byts = binascii.hexlify(ba)
string = byts.decode(encoding)
self.WriteVarInt(length)
self.WriteBytes(string) | [
"def",
"WriteVarString",
"(",
"self",
",",
"value",
",",
"encoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"str",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"encoding",
")",
"length",
"=",
"len",
"(",
"value",
")",
"ba",
"=",
"bytearray",
"(",
"value",
")",
"byts",
"=",
"binascii",
".",
"hexlify",
"(",
"ba",
")",
"string",
"=",
"byts",
".",
"decode",
"(",
"encoding",
")",
"self",
".",
"WriteVarInt",
"(",
"length",
")",
"self",
".",
"WriteBytes",
"(",
"string",
")"
]
| Write a string value to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (string): value to write to the stream.
encoding (str): string encoding format. | [
"Write",
"a",
"string",
"value",
"to",
"the",
"stream",
".",
"Read",
"more",
"about",
"variable",
"size",
"encoding",
"here",
":",
"http",
":",
"//",
"docs",
".",
"neo",
".",
"org",
"/",
"en",
"-",
"us",
"/",
"node",
"/",
"network",
"-",
"protocol",
".",
"html#convention"
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L358-L375 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteFixedString | def WriteFixedString(self, value, length):
"""
Write a string value to the stream.
Args:
value (str): value to write to the stream.
length (int): length of the string to write.
"""
towrite = value.encode('utf-8')
slen = len(towrite)
if slen > length:
raise Exception("string longer than fixed length: %s " % length)
self.WriteBytes(towrite)
diff = length - slen
while diff > 0:
self.WriteByte(0)
diff -= 1 | python | def WriteFixedString(self, value, length):
towrite = value.encode('utf-8')
slen = len(towrite)
if slen > length:
raise Exception("string longer than fixed length: %s " % length)
self.WriteBytes(towrite)
diff = length - slen
while diff > 0:
self.WriteByte(0)
diff -= 1 | [
"def",
"WriteFixedString",
"(",
"self",
",",
"value",
",",
"length",
")",
":",
"towrite",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"slen",
"=",
"len",
"(",
"towrite",
")",
"if",
"slen",
">",
"length",
":",
"raise",
"Exception",
"(",
"\"string longer than fixed length: %s \"",
"%",
"length",
")",
"self",
".",
"WriteBytes",
"(",
"towrite",
")",
"diff",
"=",
"length",
"-",
"slen",
"while",
"diff",
">",
"0",
":",
"self",
".",
"WriteByte",
"(",
"0",
")",
"diff",
"-=",
"1"
]
| Write a string value to the stream.
Args:
value (str): value to write to the stream.
length (int): length of the string to write. | [
"Write",
"a",
"string",
"value",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L377-L394 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteSerializableArray | def WriteSerializableArray(self, array):
"""
Write an array of serializable objects to the stream.
Args:
array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin
"""
if array is None:
self.WriteByte(0)
else:
self.WriteVarInt(len(array))
for item in array:
item.Serialize(self) | python | def WriteSerializableArray(self, array):
if array is None:
self.WriteByte(0)
else:
self.WriteVarInt(len(array))
for item in array:
item.Serialize(self) | [
"def",
"WriteSerializableArray",
"(",
"self",
",",
"array",
")",
":",
"if",
"array",
"is",
"None",
":",
"self",
".",
"WriteByte",
"(",
"0",
")",
"else",
":",
"self",
".",
"WriteVarInt",
"(",
"len",
"(",
"array",
")",
")",
"for",
"item",
"in",
"array",
":",
"item",
".",
"Serialize",
"(",
"self",
")"
]
| Write an array of serializable objects to the stream.
Args:
array(list): a list of serializable objects. i.e. extending neo.IO.Mixins.SerializableMixin | [
"Write",
"an",
"array",
"of",
"serializable",
"objects",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L396-L408 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.Write2000256List | def Write2000256List(self, arr):
"""
Write an array of 64 byte items to the stream.
Args:
arr (list): a list of 2000 items of 64 bytes in size.
"""
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
self.WriteBytes(ba) | python | def Write2000256List(self, arr):
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
self.WriteBytes(ba) | [
"def",
"Write2000256List",
"(",
"self",
",",
"arr",
")",
":",
"for",
"item",
"in",
"arr",
":",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"item",
")",
")",
"ba",
".",
"reverse",
"(",
")",
"self",
".",
"WriteBytes",
"(",
"ba",
")"
]
| Write an array of 64 byte items to the stream.
Args:
arr (list): a list of 2000 items of 64 bytes in size. | [
"Write",
"an",
"array",
"of",
"64",
"byte",
"items",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L410-L420 |
CityOfZion/neo-python-core | neocore/IO/BinaryWriter.py | BinaryWriter.WriteHashes | def WriteHashes(self, arr):
"""
Write an array of hashes to the stream.
Args:
arr (list): a list of 32 byte hashes.
"""
length = len(arr)
self.WriteVarInt(length)
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
# logger.info("WRITING HASH %s " % ba)
self.WriteBytes(ba) | python | def WriteHashes(self, arr):
length = len(arr)
self.WriteVarInt(length)
for item in arr:
ba = bytearray(binascii.unhexlify(item))
ba.reverse()
self.WriteBytes(ba) | [
"def",
"WriteHashes",
"(",
"self",
",",
"arr",
")",
":",
"length",
"=",
"len",
"(",
"arr",
")",
"self",
".",
"WriteVarInt",
"(",
"length",
")",
"for",
"item",
"in",
"arr",
":",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"item",
")",
")",
"ba",
".",
"reverse",
"(",
")",
"# logger.info(\"WRITING HASH %s \" % ba)",
"self",
".",
"WriteBytes",
"(",
"ba",
")"
]
| Write an array of hashes to the stream.
Args:
arr (list): a list of 32 byte hashes. | [
"Write",
"an",
"array",
"of",
"hashes",
"to",
"the",
"stream",
"."
]
| train | https://github.com/CityOfZion/neo-python-core/blob/786c02cc2f41712d70b1f064ae3d67f86167107f/neocore/IO/BinaryWriter.py#L422-L435 |
OTA-Insight/djangosaml2idp | djangosaml2idp/processors.py | BaseProcessor.get_user_id | def get_user_id(self, user):
""" Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set
use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field.
"""
user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \
getattr(user, 'USERNAME_FIELD', 'username')
return str(getattr(user, user_field)) | python | def get_user_id(self, user):
user_field = getattr(settings, 'SAML_IDP_DJANGO_USERNAME_FIELD', None) or \
getattr(user, 'USERNAME_FIELD', 'username')
return str(getattr(user, user_field)) | [
"def",
"get_user_id",
"(",
"self",
",",
"user",
")",
":",
"user_field",
"=",
"getattr",
"(",
"settings",
",",
"'SAML_IDP_DJANGO_USERNAME_FIELD'",
",",
"None",
")",
"or",
"getattr",
"(",
"user",
",",
"'USERNAME_FIELD'",
",",
"'username'",
")",
"return",
"str",
"(",
"getattr",
"(",
"user",
",",
"user_field",
")",
")"
]
| Get identifier for a user. Take the one defined in settings.SAML_IDP_DJANGO_USERNAME_FIELD first, if not set
use the USERNAME_FIELD property which is set on the user Model. This defaults to the user.username field. | [
"Get",
"identifier",
"for",
"a",
"user",
".",
"Take",
"the",
"one",
"defined",
"in",
"settings",
".",
"SAML_IDP_DJANGO_USERNAME_FIELD",
"first",
"if",
"not",
"set",
"use",
"the",
"USERNAME_FIELD",
"property",
"which",
"is",
"set",
"on",
"the",
"user",
"Model",
".",
"This",
"defaults",
"to",
"the",
"user",
".",
"username",
"field",
"."
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/processors.py#L22-L28 |
OTA-Insight/djangosaml2idp | djangosaml2idp/processors.py | BaseProcessor.create_identity | def create_identity(self, user, sp_mapping, **extra_config):
""" Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP
"""
return {
out_attr: getattr(user, user_attr)
for user_attr, out_attr in sp_mapping.items()
if hasattr(user, user_attr)
} | python | def create_identity(self, user, sp_mapping, **extra_config):
return {
out_attr: getattr(user, user_attr)
for user_attr, out_attr in sp_mapping.items()
if hasattr(user, user_attr)
} | [
"def",
"create_identity",
"(",
"self",
",",
"user",
",",
"sp_mapping",
",",
"*",
"*",
"extra_config",
")",
":",
"return",
"{",
"out_attr",
":",
"getattr",
"(",
"user",
",",
"user_attr",
")",
"for",
"user_attr",
",",
"out_attr",
"in",
"sp_mapping",
".",
"items",
"(",
")",
"if",
"hasattr",
"(",
"user",
",",
"user_attr",
")",
"}"
]
| Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP | [
"Generate",
"an",
"identity",
"dictionary",
"of",
"the",
"user",
"based",
"on",
"the",
"given",
"mapping",
"of",
"desired",
"user",
"attributes",
"by",
"the",
"SP"
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/processors.py#L30-L38 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | sso_entry | def sso_entry(request):
""" Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session
and redirects the requester to the login_process view.
"""
if request.method == 'POST':
passed_data = request.POST
binding = BINDING_HTTP_POST
else:
passed_data = request.GET
binding = BINDING_HTTP_REDIRECT
request.session['Binding'] = binding
try:
request.session['SAMLRequest'] = passed_data['SAMLRequest']
except (KeyError, MultiValueDictKeyError) as e:
return HttpResponseBadRequest(e)
request.session['RelayState'] = passed_data.get('RelayState', '')
# TODO check how the redirect saml way works. Taken from example idp in pysaml2.
if "SigAlg" in passed_data and "Signature" in passed_data:
request.session['SigAlg'] = passed_data['SigAlg']
request.session['Signature'] = passed_data['Signature']
return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process')) | python | def sso_entry(request):
if request.method == 'POST':
passed_data = request.POST
binding = BINDING_HTTP_POST
else:
passed_data = request.GET
binding = BINDING_HTTP_REDIRECT
request.session['Binding'] = binding
try:
request.session['SAMLRequest'] = passed_data['SAMLRequest']
except (KeyError, MultiValueDictKeyError) as e:
return HttpResponseBadRequest(e)
request.session['RelayState'] = passed_data.get('RelayState', '')
if "SigAlg" in passed_data and "Signature" in passed_data:
request.session['SigAlg'] = passed_data['SigAlg']
request.session['Signature'] = passed_data['Signature']
return HttpResponseRedirect(reverse('djangosaml2idp:saml_login_process')) | [
"def",
"sso_entry",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"passed_data",
"=",
"request",
".",
"POST",
"binding",
"=",
"BINDING_HTTP_POST",
"else",
":",
"passed_data",
"=",
"request",
".",
"GET",
"binding",
"=",
"BINDING_HTTP_REDIRECT",
"request",
".",
"session",
"[",
"'Binding'",
"]",
"=",
"binding",
"try",
":",
"request",
".",
"session",
"[",
"'SAMLRequest'",
"]",
"=",
"passed_data",
"[",
"'SAMLRequest'",
"]",
"except",
"(",
"KeyError",
",",
"MultiValueDictKeyError",
")",
"as",
"e",
":",
"return",
"HttpResponseBadRequest",
"(",
"e",
")",
"request",
".",
"session",
"[",
"'RelayState'",
"]",
"=",
"passed_data",
".",
"get",
"(",
"'RelayState'",
",",
"''",
")",
"# TODO check how the redirect saml way works. Taken from example idp in pysaml2.",
"if",
"\"SigAlg\"",
"in",
"passed_data",
"and",
"\"Signature\"",
"in",
"passed_data",
":",
"request",
".",
"session",
"[",
"'SigAlg'",
"]",
"=",
"passed_data",
"[",
"'SigAlg'",
"]",
"request",
".",
"session",
"[",
"'Signature'",
"]",
"=",
"passed_data",
"[",
"'Signature'",
"]",
"return",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'djangosaml2idp:saml_login_process'",
")",
")"
]
| Entrypoint view for SSO. Gathers the parameters from the HTTP request, stores them in the session
and redirects the requester to the login_process view. | [
"Entrypoint",
"view",
"for",
"SSO",
".",
"Gathers",
"the",
"parameters",
"from",
"the",
"HTTP",
"request",
"stores",
"them",
"in",
"the",
"session",
"and",
"redirects",
"the",
"requester",
"to",
"the",
"login_process",
"view",
"."
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L41-L63 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | metadata | def metadata(request):
""" Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings.
"""
conf = IdPConfig()
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
metadata = entity_descriptor(conf)
return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8") | python | def metadata(request):
conf = IdPConfig()
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
metadata = entity_descriptor(conf)
return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8") | [
"def",
"metadata",
"(",
"request",
")",
":",
"conf",
"=",
"IdPConfig",
"(",
")",
"conf",
".",
"load",
"(",
"copy",
".",
"deepcopy",
"(",
"settings",
".",
"SAML_IDP_CONFIG",
")",
")",
"metadata",
"=",
"entity_descriptor",
"(",
"conf",
")",
"return",
"HttpResponse",
"(",
"content",
"=",
"text_type",
"(",
"metadata",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"content_type",
"=",
"\"text/xml; charset=utf8\"",
")"
]
| Returns an XML with the SAML 2.0 metadata for this Idp.
The metadata is constructed on-the-fly based on the config dict in the django settings. | [
"Returns",
"an",
"XML",
"with",
"the",
"SAML",
"2",
".",
"0",
"metadata",
"for",
"this",
"Idp",
".",
"The",
"metadata",
"is",
"constructed",
"on",
"-",
"the",
"-",
"fly",
"based",
"on",
"the",
"config",
"dict",
"in",
"the",
"django",
"settings",
"."
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L284-L291 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | IdPHandlerViewMixin.dispatch | def dispatch(self, request, *args, **kwargs):
""" Construct IDP server with config from settings dict
"""
conf = IdPConfig()
try:
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
self.IDP = Server(config=conf)
except Exception as e:
return self.handle_error(request, exception=e)
return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs) | python | def dispatch(self, request, *args, **kwargs):
conf = IdPConfig()
try:
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
self.IDP = Server(config=conf)
except Exception as e:
return self.handle_error(request, exception=e)
return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"conf",
"=",
"IdPConfig",
"(",
")",
"try",
":",
"conf",
".",
"load",
"(",
"copy",
".",
"deepcopy",
"(",
"settings",
".",
"SAML_IDP_CONFIG",
")",
")",
"self",
".",
"IDP",
"=",
"Server",
"(",
"config",
"=",
"conf",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"self",
".",
"handle_error",
"(",
"request",
",",
"exception",
"=",
"e",
")",
"return",
"super",
"(",
"IdPHandlerViewMixin",
",",
"self",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Construct IDP server with config from settings dict | [
"Construct",
"IDP",
"server",
"with",
"config",
"from",
"settings",
"dict"
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L74-L83 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | IdPHandlerViewMixin.get_processor | def get_processor(self, entity_id, sp_config):
""" Instantiate user-specified processor or default to an all-access base processor.
Raises an exception if the configured processor class can not be found or initialized.
"""
processor_string = sp_config.get('processor', None)
if processor_string:
try:
return import_string(processor_string)(entity_id)
except Exception as e:
logger.error("Failed to instantiate processor: {} - {}".format(processor_string, e), exc_info=True)
raise
return BaseProcessor(entity_id) | python | def get_processor(self, entity_id, sp_config):
processor_string = sp_config.get('processor', None)
if processor_string:
try:
return import_string(processor_string)(entity_id)
except Exception as e:
logger.error("Failed to instantiate processor: {} - {}".format(processor_string, e), exc_info=True)
raise
return BaseProcessor(entity_id) | [
"def",
"get_processor",
"(",
"self",
",",
"entity_id",
",",
"sp_config",
")",
":",
"processor_string",
"=",
"sp_config",
".",
"get",
"(",
"'processor'",
",",
"None",
")",
"if",
"processor_string",
":",
"try",
":",
"return",
"import_string",
"(",
"processor_string",
")",
"(",
"entity_id",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"error",
"(",
"\"Failed to instantiate processor: {} - {}\"",
".",
"format",
"(",
"processor_string",
",",
"e",
")",
",",
"exc_info",
"=",
"True",
")",
"raise",
"return",
"BaseProcessor",
"(",
"entity_id",
")"
]
| Instantiate user-specified processor or default to an all-access base processor.
Raises an exception if the configured processor class can not be found or initialized. | [
"Instantiate",
"user",
"-",
"specified",
"processor",
"or",
"default",
"to",
"an",
"all",
"-",
"access",
"base",
"processor",
".",
"Raises",
"an",
"exception",
"if",
"the",
"configured",
"processor",
"class",
"can",
"not",
"be",
"found",
"or",
"initialized",
"."
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L85-L96 |
OTA-Insight/djangosaml2idp | djangosaml2idp/views.py | IdPHandlerViewMixin.get_identity | def get_identity(self, processor, user, sp_config):
""" Create Identity dict (using SP-specific mapping)
"""
sp_mapping = sp_config.get('attribute_mapping', {'username': 'username'})
return processor.create_identity(user, sp_mapping, **sp_config.get('extra_config', {})) | python | def get_identity(self, processor, user, sp_config):
sp_mapping = sp_config.get('attribute_mapping', {'username': 'username'})
return processor.create_identity(user, sp_mapping, **sp_config.get('extra_config', {})) | [
"def",
"get_identity",
"(",
"self",
",",
"processor",
",",
"user",
",",
"sp_config",
")",
":",
"sp_mapping",
"=",
"sp_config",
".",
"get",
"(",
"'attribute_mapping'",
",",
"{",
"'username'",
":",
"'username'",
"}",
")",
"return",
"processor",
".",
"create_identity",
"(",
"user",
",",
"sp_mapping",
",",
"*",
"*",
"sp_config",
".",
"get",
"(",
"'extra_config'",
",",
"{",
"}",
")",
")"
]
| Create Identity dict (using SP-specific mapping) | [
"Create",
"Identity",
"dict",
"(",
"using",
"SP",
"-",
"specific",
"mapping",
")"
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/djangosaml2idp/views.py#L98-L102 |
OTA-Insight/djangosaml2idp | example_setup/sp/sp/views.py | custom_update_user | def custom_update_user(sender, instance, attributes, user_modified, **kargs):
""" Default behaviour does not play nice with booleans encoded in SAML as u'true'/u'false'.
This will convert those attributes to real booleans when saving.
"""
for k, v in attributes.items():
u = set.intersection(set(v), set([u'true', u'false']))
if u:
setattr(instance, k, u.pop() == u'true')
return True | python | def custom_update_user(sender, instance, attributes, user_modified, **kargs):
for k, v in attributes.items():
u = set.intersection(set(v), set([u'true', u'false']))
if u:
setattr(instance, k, u.pop() == u'true')
return True | [
"def",
"custom_update_user",
"(",
"sender",
",",
"instance",
",",
"attributes",
",",
"user_modified",
",",
"*",
"*",
"kargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"attributes",
".",
"items",
"(",
")",
":",
"u",
"=",
"set",
".",
"intersection",
"(",
"set",
"(",
"v",
")",
",",
"set",
"(",
"[",
"u'true'",
",",
"u'false'",
"]",
")",
")",
"if",
"u",
":",
"setattr",
"(",
"instance",
",",
"k",
",",
"u",
".",
"pop",
"(",
")",
"==",
"u'true'",
")",
"return",
"True"
]
| Default behaviour does not play nice with booleans encoded in SAML as u'true'/u'false'.
This will convert those attributes to real booleans when saving. | [
"Default",
"behaviour",
"does",
"not",
"play",
"nice",
"with",
"booleans",
"encoded",
"in",
"SAML",
"as",
"u",
"true",
"/",
"u",
"false",
".",
"This",
"will",
"convert",
"those",
"attributes",
"to",
"real",
"booleans",
"when",
"saving",
"."
]
| train | https://github.com/OTA-Insight/djangosaml2idp/blob/8a238063da55bf4823bdc2192168171767c4e056/example_setup/sp/sp/views.py#L26-L34 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | parse_time | def parse_time(s):
"""
Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster.
"""
result = None
if "epoch" in s:
epoch_time = float(s.rstrip().split(' ')[1][:-1])
result = datetime.datetime.utcfromtimestamp(epoch_time)
else:
_, date_part, time_part = s.split(' ')
year, mon, day = date_part.split('/')
hour, minute, sec = time_part.split(':')
result = datetime.datetime(*map(int, (year, mon, day, hour, minute, sec)))
return result | python | def parse_time(s):
result = None
if "epoch" in s:
epoch_time = float(s.rstrip().split(' ')[1][:-1])
result = datetime.datetime.utcfromtimestamp(epoch_time)
else:
_, date_part, time_part = s.split(' ')
year, mon, day = date_part.split('/')
hour, minute, sec = time_part.split(':')
result = datetime.datetime(*map(int, (year, mon, day, hour, minute, sec)))
return result | [
"def",
"parse_time",
"(",
"s",
")",
":",
"result",
"=",
"None",
"if",
"\"epoch\"",
"in",
"s",
":",
"epoch_time",
"=",
"float",
"(",
"s",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
")",
"result",
"=",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"epoch_time",
")",
"else",
":",
"_",
",",
"date_part",
",",
"time_part",
"=",
"s",
".",
"split",
"(",
"' '",
")",
"year",
",",
"mon",
",",
"day",
"=",
"date_part",
".",
"split",
"(",
"'/'",
")",
"hour",
",",
"minute",
",",
"sec",
"=",
"time_part",
".",
"split",
"(",
"':'",
")",
"result",
"=",
"datetime",
".",
"datetime",
"(",
"*",
"map",
"(",
"int",
",",
"(",
"year",
",",
"mon",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
")",
")",
")",
"return",
"result"
]
| Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster. | [
"Like",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"s",
"%w",
"%Y",
"/",
"%m",
"/",
"%d",
"%H",
":",
"%M",
":",
"%S",
")",
"but",
"5x",
"faster",
"."
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L11-L26 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | _extract_prop_option | def _extract_prop_option(line):
"""
Extract the (key,value)-tuple from a string like:
>>> "option foobar 123"
:param line:
:return: tuple (key, value)
"""
line = line[7:]
pos = line.find(' ')
return line[:pos], line[pos + 1:] | python | def _extract_prop_option(line):
line = line[7:]
pos = line.find(' ')
return line[:pos], line[pos + 1:] | [
"def",
"_extract_prop_option",
"(",
"line",
")",
":",
"line",
"=",
"line",
"[",
"7",
":",
"]",
"pos",
"=",
"line",
".",
"find",
"(",
"' '",
")",
"return",
"line",
"[",
":",
"pos",
"]",
",",
"line",
"[",
"pos",
"+",
"1",
":",
"]"
]
| Extract the (key,value)-tuple from a string like:
>>> "option foobar 123"
:param line:
:return: tuple (key, value) | [
"Extract",
"the",
"(",
"key",
"value",
")",
"-",
"tuple",
"from",
"a",
"string",
"like",
":",
">>>",
"option",
"foobar",
"123",
":",
"param",
"line",
":",
":",
"return",
":",
"tuple",
"(",
"key",
"value",
")"
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L29-L38 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | _extract_prop_set | def _extract_prop_set(line):
"""
Extract the (key, value)-tuple from a string like:
>>> 'set foo = "bar"'
:param line:
:return: tuple (key, value)
"""
token = ' = "'
line = line[4:]
pos = line.find(token)
return line[:pos], line[pos + 4:-1] | python | def _extract_prop_set(line):
token = ' = "'
line = line[4:]
pos = line.find(token)
return line[:pos], line[pos + 4:-1] | [
"def",
"_extract_prop_set",
"(",
"line",
")",
":",
"token",
"=",
"' = \"'",
"line",
"=",
"line",
"[",
"4",
":",
"]",
"pos",
"=",
"line",
".",
"find",
"(",
"token",
")",
"return",
"line",
"[",
":",
"pos",
"]",
",",
"line",
"[",
"pos",
"+",
"4",
":",
"-",
"1",
"]"
]
| Extract the (key, value)-tuple from a string like:
>>> 'set foo = "bar"'
:param line:
:return: tuple (key, value) | [
"Extract",
"the",
"(",
"key",
"value",
")",
"-",
"tuple",
"from",
"a",
"string",
"like",
":",
">>>",
"set",
"foo",
"=",
"bar",
":",
"param",
"line",
":",
":",
"return",
":",
"tuple",
"(",
"key",
"value",
")"
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L41-L51 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | _extract_properties | def _extract_properties(config):
"""
Parse a line within a lease block
The line should basically match the expression:
>>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);"
For easier seperation of the cases and faster parsing this is done using substrings etc..
:param config:
:return: tuple of properties dict, options dict and sets dict
"""
general, options, sets = {}, {}, {}
for line in config.splitlines():
# skip empty & malformed lines
if not line or not line[-1:] == ';' and '; #' not in line:
continue
# strip the trailing ';' and remove any whitespaces on the left side
line = line[:-1].lstrip()
# seperate the three cases
if line[:6] == 'option':
key, value = _extract_prop_option(line)
options[key] = value
elif line[:3] == 'set':
key, value = _extract_prop_set(line)
sets[key] = value
else:
# fall through to generic case
key, value = _extract_prop_general(line)
general[key] = value
return general, options, sets | python | def _extract_properties(config):
general, options, sets = {}, {}, {}
for line in config.splitlines():
if not line or not line[-1:] == ';' and ';
continue
line = line[:-1].lstrip()
if line[:6] == 'option':
key, value = _extract_prop_option(line)
options[key] = value
elif line[:3] == 'set':
key, value = _extract_prop_set(line)
sets[key] = value
else:
key, value = _extract_prop_general(line)
general[key] = value
return general, options, sets | [
"def",
"_extract_properties",
"(",
"config",
")",
":",
"general",
",",
"options",
",",
"sets",
"=",
"{",
"}",
",",
"{",
"}",
",",
"{",
"}",
"for",
"line",
"in",
"config",
".",
"splitlines",
"(",
")",
":",
"# skip empty & malformed lines",
"if",
"not",
"line",
"or",
"not",
"line",
"[",
"-",
"1",
":",
"]",
"==",
"';'",
"and",
"'; #'",
"not",
"in",
"line",
":",
"continue",
"# strip the trailing ';' and remove any whitespaces on the left side",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
".",
"lstrip",
"(",
")",
"# seperate the three cases",
"if",
"line",
"[",
":",
"6",
"]",
"==",
"'option'",
":",
"key",
",",
"value",
"=",
"_extract_prop_option",
"(",
"line",
")",
"options",
"[",
"key",
"]",
"=",
"value",
"elif",
"line",
"[",
":",
"3",
"]",
"==",
"'set'",
":",
"key",
",",
"value",
"=",
"_extract_prop_set",
"(",
"line",
")",
"sets",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"# fall through to generic case",
"key",
",",
"value",
"=",
"_extract_prop_general",
"(",
"line",
")",
"general",
"[",
"key",
"]",
"=",
"value",
"return",
"general",
",",
"options",
",",
"sets"
]
| Parse a line within a lease block
The line should basically match the expression:
>>> r"\s+(?P<key>(?:option|set)\s+\S+|\S+) (?P<value>[\s\S]+?);"
For easier seperation of the cases and faster parsing this is done using substrings etc..
:param config:
:return: tuple of properties dict, options dict and sets dict | [
"Parse",
"a",
"line",
"within",
"a",
"lease",
"block",
"The",
"line",
"should",
"basically",
"match",
"the",
"expression",
":",
">>>",
"r",
"\\",
"s",
"+",
"(",
"?P<key",
">",
"(",
"?",
":",
"option|set",
")",
"\\",
"s",
"+",
"\\",
"S",
"+",
"|",
"\\",
"S",
"+",
")",
"(",
"?P<value",
">",
"[",
"\\",
"s",
"\\",
"S",
"]",
"+",
"?",
")",
";",
"For",
"easier",
"seperation",
"of",
"the",
"cases",
"and",
"faster",
"parsing",
"this",
"is",
"done",
"using",
"substrings",
"etc",
"..",
":",
"param",
"config",
":",
":",
"return",
":",
"tuple",
"of",
"properties",
"dict",
"options",
"dict",
"and",
"sets",
"dict"
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L65-L98 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | IscDhcpLeases.get | def get(self, include_backups=False):
"""
Parse the lease file and return a list of Lease instances.
"""
leases = []
with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file:
lease_data = lease_file.read()
if self.gzip:
lease_data = lease_data.decode('utf-8')
for match in self.regex_leaseblock.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
if 'hardware' not in properties and not include_backups:
# E.g. rows like {'binding': 'state abandoned', ...}
continue
lease = Lease(block['ip'], properties=properties, options=options, sets=sets)
leases.append(lease)
for match in self.regex_leaseblock6.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
host_identifier = block['id']
block_type = block['type']
last_client_communication = parse_time(properties['cltt'])
for address_block in self.regex_iaaddr.finditer(block['config']):
block = address_block.groupdict()
properties, options, sets = _extract_properties(block['config'])
lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type,
options=options, sets=sets)
leases.append(lease)
return leases | python | def get(self, include_backups=False):
leases = []
with open(self.filename) if not self.gzip else gzip.open(self.filename) as lease_file:
lease_data = lease_file.read()
if self.gzip:
lease_data = lease_data.decode('utf-8')
for match in self.regex_leaseblock.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
if 'hardware' not in properties and not include_backups:
continue
lease = Lease(block['ip'], properties=properties, options=options, sets=sets)
leases.append(lease)
for match in self.regex_leaseblock6.finditer(lease_data):
block = match.groupdict()
properties, options, sets = _extract_properties(block['config'])
host_identifier = block['id']
block_type = block['type']
last_client_communication = parse_time(properties['cltt'])
for address_block in self.regex_iaaddr.finditer(block['config']):
block = address_block.groupdict()
properties, options, sets = _extract_properties(block['config'])
lease = Lease6(block['ip'], properties, last_client_communication, host_identifier, block_type,
options=options, sets=sets)
leases.append(lease)
return leases | [
"def",
"get",
"(",
"self",
",",
"include_backups",
"=",
"False",
")",
":",
"leases",
"=",
"[",
"]",
"with",
"open",
"(",
"self",
".",
"filename",
")",
"if",
"not",
"self",
".",
"gzip",
"else",
"gzip",
".",
"open",
"(",
"self",
".",
"filename",
")",
"as",
"lease_file",
":",
"lease_data",
"=",
"lease_file",
".",
"read",
"(",
")",
"if",
"self",
".",
"gzip",
":",
"lease_data",
"=",
"lease_data",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"match",
"in",
"self",
".",
"regex_leaseblock",
".",
"finditer",
"(",
"lease_data",
")",
":",
"block",
"=",
"match",
".",
"groupdict",
"(",
")",
"properties",
",",
"options",
",",
"sets",
"=",
"_extract_properties",
"(",
"block",
"[",
"'config'",
"]",
")",
"if",
"'hardware'",
"not",
"in",
"properties",
"and",
"not",
"include_backups",
":",
"# E.g. rows like {'binding': 'state abandoned', ...}",
"continue",
"lease",
"=",
"Lease",
"(",
"block",
"[",
"'ip'",
"]",
",",
"properties",
"=",
"properties",
",",
"options",
"=",
"options",
",",
"sets",
"=",
"sets",
")",
"leases",
".",
"append",
"(",
"lease",
")",
"for",
"match",
"in",
"self",
".",
"regex_leaseblock6",
".",
"finditer",
"(",
"lease_data",
")",
":",
"block",
"=",
"match",
".",
"groupdict",
"(",
")",
"properties",
",",
"options",
",",
"sets",
"=",
"_extract_properties",
"(",
"block",
"[",
"'config'",
"]",
")",
"host_identifier",
"=",
"block",
"[",
"'id'",
"]",
"block_type",
"=",
"block",
"[",
"'type'",
"]",
"last_client_communication",
"=",
"parse_time",
"(",
"properties",
"[",
"'cltt'",
"]",
")",
"for",
"address_block",
"in",
"self",
".",
"regex_iaaddr",
".",
"finditer",
"(",
"block",
"[",
"'config'",
"]",
")",
":",
"block",
"=",
"address_block",
".",
"groupdict",
"(",
")",
"properties",
",",
"options",
",",
"sets",
"=",
"_extract_properties",
"(",
"block",
"[",
"'config'",
"]",
")",
"lease",
"=",
"Lease6",
"(",
"block",
"[",
"'ip'",
"]",
",",
"properties",
",",
"last_client_communication",
",",
"host_identifier",
",",
"block_type",
",",
"options",
"=",
"options",
",",
"sets",
"=",
"sets",
")",
"leases",
".",
"append",
"(",
"lease",
")",
"return",
"leases"
]
| Parse the lease file and return a list of Lease instances. | [
"Parse",
"the",
"lease",
"file",
"and",
"return",
"a",
"list",
"of",
"Lease",
"instances",
"."
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L115-L151 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | IscDhcpLeases.get_current | def get_current(self):
"""
Parse the lease file and return a dict of active and valid Lease instances.
The key for this dict is the ethernet address of the lease.
"""
all_leases = self.get()
leases = {}
for lease in all_leases:
if lease.valid and lease.active:
if type(lease) is Lease:
leases[lease.ethernet] = lease
elif type(lease) is Lease6:
leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease
return leases | python | def get_current(self):
all_leases = self.get()
leases = {}
for lease in all_leases:
if lease.valid and lease.active:
if type(lease) is Lease:
leases[lease.ethernet] = lease
elif type(lease) is Lease6:
leases['%s-%s' % (lease.type, lease.host_identifier_string)] = lease
return leases | [
"def",
"get_current",
"(",
"self",
")",
":",
"all_leases",
"=",
"self",
".",
"get",
"(",
")",
"leases",
"=",
"{",
"}",
"for",
"lease",
"in",
"all_leases",
":",
"if",
"lease",
".",
"valid",
"and",
"lease",
".",
"active",
":",
"if",
"type",
"(",
"lease",
")",
"is",
"Lease",
":",
"leases",
"[",
"lease",
".",
"ethernet",
"]",
"=",
"lease",
"elif",
"type",
"(",
"lease",
")",
"is",
"Lease6",
":",
"leases",
"[",
"'%s-%s'",
"%",
"(",
"lease",
".",
"type",
",",
"lease",
".",
"host_identifier_string",
")",
"]",
"=",
"lease",
"return",
"leases"
]
| Parse the lease file and return a dict of active and valid Lease instances.
The key for this dict is the ethernet address of the lease. | [
"Parse",
"the",
"lease",
"file",
"and",
"return",
"a",
"dict",
"of",
"active",
"and",
"valid",
"Lease",
"instances",
".",
"The",
"key",
"for",
"this",
"dict",
"is",
"the",
"ethernet",
"address",
"of",
"the",
"lease",
"."
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L153-L166 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | Lease.valid | def valid(self):
"""
Checks if the lease is currently valid (not expired and not in the future)
:return: bool: True if lease is valid
"""
if self.end is None:
if self.start is not None:
return self.start <= datetime.datetime.utcnow()
else:
return True
else:
if self.start is not None:
return self.start <= datetime.datetime.utcnow() <= self.end
else:
return datetime.datetime.utcnow() <= self.end | python | def valid(self):
if self.end is None:
if self.start is not None:
return self.start <= datetime.datetime.utcnow()
else:
return True
else:
if self.start is not None:
return self.start <= datetime.datetime.utcnow() <= self.end
else:
return datetime.datetime.utcnow() <= self.end | [
"def",
"valid",
"(",
"self",
")",
":",
"if",
"self",
".",
"end",
"is",
"None",
":",
"if",
"self",
".",
"start",
"is",
"not",
"None",
":",
"return",
"self",
".",
"start",
"<=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"else",
":",
"return",
"True",
"else",
":",
"if",
"self",
".",
"start",
"is",
"not",
"None",
":",
"return",
"self",
".",
"start",
"<=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"<=",
"self",
".",
"end",
"else",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"<=",
"self",
".",
"end"
]
| Checks if the lease is currently valid (not expired and not in the future)
:return: bool: True if lease is valid | [
"Checks",
"if",
"the",
"lease",
"is",
"currently",
"valid",
"(",
"not",
"expired",
"and",
"not",
"in",
"the",
"future",
")",
":",
"return",
":",
"bool",
":",
"True",
"if",
"lease",
"is",
"valid"
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L238-L252 |
MartijnBraam/python-isc-dhcp-leases | isc_dhcp_leases/iscdhcpleases.py | Lease6.valid | def valid(self):
"""
Checks if the lease is currently valid (not expired)
:return: bool: True if lease is valid
"""
if self.end is None:
return True
else:
return datetime.datetime.utcnow() <= self.end | python | def valid(self):
if self.end is None:
return True
else:
return datetime.datetime.utcnow() <= self.end | [
"def",
"valid",
"(",
"self",
")",
":",
"if",
"self",
".",
"end",
"is",
"None",
":",
"return",
"True",
"else",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"<=",
"self",
".",
"end"
]
| Checks if the lease is currently valid (not expired)
:return: bool: True if lease is valid | [
"Checks",
"if",
"the",
"lease",
"is",
"currently",
"valid",
"(",
"not",
"expired",
")",
":",
"return",
":",
"bool",
":",
"True",
"if",
"lease",
"is",
"valid"
]
| train | https://github.com/MartijnBraam/python-isc-dhcp-leases/blob/e96c00e31f3a52c01ef98193577d614d08a93285/isc_dhcp_leases/iscdhcpleases.py#L310-L318 |
crate/crash | src/crate/crash/tabulate.py | _padleft | def _padleft(width, s, has_invisible=True):
"""Flush right.
>>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430'
True
"""
def impl(val):
iwidth = width + len(val) - len(_strip_invisible(val)) if has_invisible else width
fmt = "{0:>%ds}" % iwidth
return fmt.format(val)
num_lines = s.splitlines()
return len(num_lines) > 1 and '\n'.join(map(impl, num_lines)) or impl(s) | python | def _padleft(width, s, has_invisible=True):
def impl(val):
iwidth = width + len(val) - len(_strip_invisible(val)) if has_invisible else width
fmt = "{0:>%ds}" % iwidth
return fmt.format(val)
num_lines = s.splitlines()
return len(num_lines) > 1 and '\n'.join(map(impl, num_lines)) or impl(s) | [
"def",
"_padleft",
"(",
"width",
",",
"s",
",",
"has_invisible",
"=",
"True",
")",
":",
"def",
"impl",
"(",
"val",
")",
":",
"iwidth",
"=",
"width",
"+",
"len",
"(",
"val",
")",
"-",
"len",
"(",
"_strip_invisible",
"(",
"val",
")",
")",
"if",
"has_invisible",
"else",
"width",
"fmt",
"=",
"\"{0:>%ds}\"",
"%",
"iwidth",
"return",
"fmt",
".",
"format",
"(",
"val",
")",
"num_lines",
"=",
"s",
".",
"splitlines",
"(",
")",
"return",
"len",
"(",
"num_lines",
")",
">",
"1",
"and",
"'\\n'",
".",
"join",
"(",
"map",
"(",
"impl",
",",
"num_lines",
")",
")",
"or",
"impl",
"(",
"s",
")"
]
| Flush right.
>>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430'
True | [
"Flush",
"right",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L392-L406 |
crate/crash | src/crate/crash/tabulate.py | _visible_width | def _visible_width(s):
"""Visible width of a printed string. ANSI color codes are removed.
>>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world")
(5, 5)
"""
if isinstance(s, _text_type) or isinstance(s, _binary_type):
return _max_line_width(_strip_invisible(s))
else:
return _max_line_width(_text_type(s)) | python | def _visible_width(s):
if isinstance(s, _text_type) or isinstance(s, _binary_type):
return _max_line_width(_strip_invisible(s))
else:
return _max_line_width(_text_type(s)) | [
"def",
"_visible_width",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"_text_type",
")",
"or",
"isinstance",
"(",
"s",
",",
"_binary_type",
")",
":",
"return",
"_max_line_width",
"(",
"_strip_invisible",
"(",
"s",
")",
")",
"else",
":",
"return",
"_max_line_width",
"(",
"_text_type",
"(",
"s",
")",
")"
]
| Visible width of a printed string. ANSI color codes are removed.
>>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world")
(5, 5) | [
"Visible",
"width",
"of",
"a",
"printed",
"string",
".",
"ANSI",
"color",
"codes",
"are",
"removed",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L468-L478 |
crate/crash | src/crate/crash/tabulate.py | _column_type | def _column_type(values, has_invisible=True):
"""The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type
True
>>> _column_type([None, "brux"]) is _text_type
True
>>> _column_type([1, 2, None]) is _int_type
True
>>> import datetime as dt
>>> _column_type([dt.datetime(1991,2,19), dt.time(17,35)]) is _text_type
True
"""
return reduce(_more_generic, [type(v) for v in values], int) | python | def _column_type(values, has_invisible=True):
return reduce(_more_generic, [type(v) for v in values], int) | [
"def",
"_column_type",
"(",
"values",
",",
"has_invisible",
"=",
"True",
")",
":",
"return",
"reduce",
"(",
"_more_generic",
",",
"[",
"type",
"(",
"v",
")",
"for",
"v",
"in",
"values",
"]",
",",
"int",
")"
]
| The least generic type all column values are convertible to.
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_type(["four", '\u043f\u044f\u0442\u044c']) is _text_type
True
>>> _column_type([None, "brux"]) is _text_type
True
>>> _column_type([1, 2, None]) is _int_type
True
>>> import datetime as dt
>>> _column_type([dt.datetime(1991,2,19), dt.time(17,35)]) is _text_type
True | [
"The",
"least",
"generic",
"type",
"all",
"column",
"values",
"are",
"convertible",
"to",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L582-L602 |
crate/crash | src/crate/crash/tabulate.py | _normalize_tabular_data | def _normalize_tabular_data(tabular_data, headers):
"""Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* list of named tuples (usually used with headers="keys")
* list of dicts (usually used with headers="keys")
* list of OrderedDicts (usually used with headers="keys")
* 2D NumPy arrays
* NumPy record arrays (usually used with headers="keys")
* dict of iterables (usually used with headers="keys")
* pandas.DataFrame (usually used with headers="keys")
The first row can be used as headers if headers="firstrow",
column indices can be used as headers if headers="keys".
"""
if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
# dict-like and pandas.DataFrame?
if hasattr(tabular_data.values, "__call__"):
# likely a conventional dict
keys = tabular_data.keys()
rows = list(izip_longest(*tabular_data.values())) # columns have to be transposed
elif hasattr(tabular_data, "index"):
# values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0)
keys = tabular_data.keys()
vals = tabular_data.values # values matrix doesn't need to be transposed
names = tabular_data.index
rows = [[v] + list(row) for v, row in zip(names, vals)]
else:
raise ValueError("tabular data doesn't appear to be a dict or a DataFrame")
if headers == "keys":
headers = list(map(_text_type, keys)) # headers should be strings
else: # it's a usual an iterable of iterables, or a NumPy array
rows = list(tabular_data)
if (headers == "keys" and
hasattr(tabular_data, "dtype") and
getattr(tabular_data.dtype, "names")):
# numpy record array
headers = tabular_data.dtype.names
elif (headers == "keys"
and len(rows) > 0
and isinstance(rows[0], tuple)
and hasattr(rows[0], "_fields")):
# namedtuple
headers = list(map(_text_type, rows[0]._fields))
elif (len(rows) > 0
and isinstance(rows[0], dict)):
# dict or OrderedDict
uniq_keys = set() # implements hashed lookup
keys = [] # storage for set
if headers == "firstrow":
firstdict = rows[0] if len(rows) > 0 else {}
keys.extend(firstdict.keys())
uniq_keys.update(keys)
rows = rows[1:]
for row in rows:
for k in row.keys():
# Save unique items in input order
if k not in uniq_keys:
keys.append(k)
uniq_keys.add(k)
if headers == 'keys':
headers = keys
elif isinstance(headers, dict):
# a dict of headers for a list of dicts
headers = [headers.get(k, k) for k in keys]
headers = list(map(_text_type, headers))
elif headers == "firstrow":
if len(rows) > 0:
headers = [firstdict.get(k, k) for k in keys]
headers = list(map(_text_type, headers))
else:
headers = []
elif headers:
raise ValueError('headers for a list of dicts is not a dict or a keyword')
rows = [[row.get(k) for k in keys] for row in rows]
elif headers == "keys" and len(rows) > 0:
# keys are column indices
headers = list(map(_text_type, range(len(rows[0]))))
# take headers from the first row if necessary
if headers == "firstrow" and len(rows) > 0:
headers = list(map(_text_type, rows[0])) # headers should be strings
rows = rows[1:]
headers = list(map(_text_type, headers))
rows = list(map(list, rows))
# pad with empty headers for initial columns if necessary
if headers and len(rows) > 0:
nhs = len(headers)
ncols = len(rows[0])
if nhs < ncols:
headers = [""] * (ncols - nhs) + headers
return rows, headers | python | def _normalize_tabular_data(tabular_data, headers):
if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
if hasattr(tabular_data.values, "__call__"):
keys = tabular_data.keys()
rows = list(izip_longest(*tabular_data.values()))
elif hasattr(tabular_data, "index"):
keys = tabular_data.keys()
vals = tabular_data.values
names = tabular_data.index
rows = [[v] + list(row) for v, row in zip(names, vals)]
else:
raise ValueError("tabular data doesn't appear to be a dict or a DataFrame")
if headers == "keys":
headers = list(map(_text_type, keys))
else:
rows = list(tabular_data)
if (headers == "keys" and
hasattr(tabular_data, "dtype") and
getattr(tabular_data.dtype, "names")):
headers = tabular_data.dtype.names
elif (headers == "keys"
and len(rows) > 0
and isinstance(rows[0], tuple)
and hasattr(rows[0], "_fields")):
headers = list(map(_text_type, rows[0]._fields))
elif (len(rows) > 0
and isinstance(rows[0], dict)):
uniq_keys = set()
keys = []
if headers == "firstrow":
firstdict = rows[0] if len(rows) > 0 else {}
keys.extend(firstdict.keys())
uniq_keys.update(keys)
rows = rows[1:]
for row in rows:
for k in row.keys():
if k not in uniq_keys:
keys.append(k)
uniq_keys.add(k)
if headers == 'keys':
headers = keys
elif isinstance(headers, dict):
headers = [headers.get(k, k) for k in keys]
headers = list(map(_text_type, headers))
elif headers == "firstrow":
if len(rows) > 0:
headers = [firstdict.get(k, k) for k in keys]
headers = list(map(_text_type, headers))
else:
headers = []
elif headers:
raise ValueError('headers for a list of dicts is not a dict or a keyword')
rows = [[row.get(k) for k in keys] for row in rows]
elif headers == "keys" and len(rows) > 0:
headers = list(map(_text_type, range(len(rows[0]))))
if headers == "firstrow" and len(rows) > 0:
headers = list(map(_text_type, rows[0]))
rows = rows[1:]
headers = list(map(_text_type, headers))
rows = list(map(list, rows))
if headers and len(rows) > 0:
nhs = len(headers)
ncols = len(rows[0])
if nhs < ncols:
headers = [""] * (ncols - nhs) + headers
return rows, headers | [
"def",
"_normalize_tabular_data",
"(",
"tabular_data",
",",
"headers",
")",
":",
"if",
"hasattr",
"(",
"tabular_data",
",",
"\"keys\"",
")",
"and",
"hasattr",
"(",
"tabular_data",
",",
"\"values\"",
")",
":",
"# dict-like and pandas.DataFrame?",
"if",
"hasattr",
"(",
"tabular_data",
".",
"values",
",",
"\"__call__\"",
")",
":",
"# likely a conventional dict",
"keys",
"=",
"tabular_data",
".",
"keys",
"(",
")",
"rows",
"=",
"list",
"(",
"izip_longest",
"(",
"*",
"tabular_data",
".",
"values",
"(",
")",
")",
")",
"# columns have to be transposed",
"elif",
"hasattr",
"(",
"tabular_data",
",",
"\"index\"",
")",
":",
"# values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0)",
"keys",
"=",
"tabular_data",
".",
"keys",
"(",
")",
"vals",
"=",
"tabular_data",
".",
"values",
"# values matrix doesn't need to be transposed",
"names",
"=",
"tabular_data",
".",
"index",
"rows",
"=",
"[",
"[",
"v",
"]",
"+",
"list",
"(",
"row",
")",
"for",
"v",
",",
"row",
"in",
"zip",
"(",
"names",
",",
"vals",
")",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"\"tabular data doesn't appear to be a dict or a DataFrame\"",
")",
"if",
"headers",
"==",
"\"keys\"",
":",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"keys",
")",
")",
"# headers should be strings",
"else",
":",
"# it's a usual an iterable of iterables, or a NumPy array",
"rows",
"=",
"list",
"(",
"tabular_data",
")",
"if",
"(",
"headers",
"==",
"\"keys\"",
"and",
"hasattr",
"(",
"tabular_data",
",",
"\"dtype\"",
")",
"and",
"getattr",
"(",
"tabular_data",
".",
"dtype",
",",
"\"names\"",
")",
")",
":",
"# numpy record array",
"headers",
"=",
"tabular_data",
".",
"dtype",
".",
"names",
"elif",
"(",
"headers",
"==",
"\"keys\"",
"and",
"len",
"(",
"rows",
")",
">",
"0",
"and",
"isinstance",
"(",
"rows",
"[",
"0",
"]",
",",
"tuple",
")",
"and",
"hasattr",
"(",
"rows",
"[",
"0",
"]",
",",
"\"_fields\"",
")",
")",
":",
"# namedtuple",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"rows",
"[",
"0",
"]",
".",
"_fields",
")",
")",
"elif",
"(",
"len",
"(",
"rows",
")",
">",
"0",
"and",
"isinstance",
"(",
"rows",
"[",
"0",
"]",
",",
"dict",
")",
")",
":",
"# dict or OrderedDict",
"uniq_keys",
"=",
"set",
"(",
")",
"# implements hashed lookup",
"keys",
"=",
"[",
"]",
"# storage for set",
"if",
"headers",
"==",
"\"firstrow\"",
":",
"firstdict",
"=",
"rows",
"[",
"0",
"]",
"if",
"len",
"(",
"rows",
")",
">",
"0",
"else",
"{",
"}",
"keys",
".",
"extend",
"(",
"firstdict",
".",
"keys",
"(",
")",
")",
"uniq_keys",
".",
"update",
"(",
"keys",
")",
"rows",
"=",
"rows",
"[",
"1",
":",
"]",
"for",
"row",
"in",
"rows",
":",
"for",
"k",
"in",
"row",
".",
"keys",
"(",
")",
":",
"# Save unique items in input order",
"if",
"k",
"not",
"in",
"uniq_keys",
":",
"keys",
".",
"append",
"(",
"k",
")",
"uniq_keys",
".",
"add",
"(",
"k",
")",
"if",
"headers",
"==",
"'keys'",
":",
"headers",
"=",
"keys",
"elif",
"isinstance",
"(",
"headers",
",",
"dict",
")",
":",
"# a dict of headers for a list of dicts",
"headers",
"=",
"[",
"headers",
".",
"get",
"(",
"k",
",",
"k",
")",
"for",
"k",
"in",
"keys",
"]",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"headers",
")",
")",
"elif",
"headers",
"==",
"\"firstrow\"",
":",
"if",
"len",
"(",
"rows",
")",
">",
"0",
":",
"headers",
"=",
"[",
"firstdict",
".",
"get",
"(",
"k",
",",
"k",
")",
"for",
"k",
"in",
"keys",
"]",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"headers",
")",
")",
"else",
":",
"headers",
"=",
"[",
"]",
"elif",
"headers",
":",
"raise",
"ValueError",
"(",
"'headers for a list of dicts is not a dict or a keyword'",
")",
"rows",
"=",
"[",
"[",
"row",
".",
"get",
"(",
"k",
")",
"for",
"k",
"in",
"keys",
"]",
"for",
"row",
"in",
"rows",
"]",
"elif",
"headers",
"==",
"\"keys\"",
"and",
"len",
"(",
"rows",
")",
">",
"0",
":",
"# keys are column indices",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"range",
"(",
"len",
"(",
"rows",
"[",
"0",
"]",
")",
")",
")",
")",
"# take headers from the first row if necessary",
"if",
"headers",
"==",
"\"firstrow\"",
"and",
"len",
"(",
"rows",
")",
">",
"0",
":",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"rows",
"[",
"0",
"]",
")",
")",
"# headers should be strings",
"rows",
"=",
"rows",
"[",
"1",
":",
"]",
"headers",
"=",
"list",
"(",
"map",
"(",
"_text_type",
",",
"headers",
")",
")",
"rows",
"=",
"list",
"(",
"map",
"(",
"list",
",",
"rows",
")",
")",
"# pad with empty headers for initial columns if necessary",
"if",
"headers",
"and",
"len",
"(",
"rows",
")",
">",
"0",
":",
"nhs",
"=",
"len",
"(",
"headers",
")",
"ncols",
"=",
"len",
"(",
"rows",
"[",
"0",
"]",
")",
"if",
"nhs",
"<",
"ncols",
":",
"headers",
"=",
"[",
"\"\"",
"]",
"*",
"(",
"ncols",
"-",
"nhs",
")",
"+",
"headers",
"return",
"rows",
",",
"headers"
]
| Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* list of named tuples (usually used with headers="keys")
* list of dicts (usually used with headers="keys")
* list of OrderedDicts (usually used with headers="keys")
* 2D NumPy arrays
* NumPy record arrays (usually used with headers="keys")
* dict of iterables (usually used with headers="keys")
* pandas.DataFrame (usually used with headers="keys")
The first row can be used as headers if headers="firstrow",
column indices can be used as headers if headers="keys". | [
"Transform",
"a",
"supported",
"data",
"type",
"to",
"a",
"list",
"of",
"lists",
"and",
"a",
"list",
"of",
"headers",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L659-L767 |
crate/crash | src/crate/crash/tabulate.py | tabulate | def tabulate(tabular_data, headers=(), tablefmt="simple",
floatfmt="g", numalign="decimal", stralign="left",
missingval=""):
"""Format a fixed width table for pretty printing.
>>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]]))
--- ---------
1 2.34
-56 8.999
2 10001
--- ---------
The first required argument (`tabular_data`) can be a
list-of-lists (or another iterable of iterables), a list of named
tuples, a dictionary of iterables, an iterable of dictionaries,
a two-dimensional NumPy array, NumPy record array, or a Pandas'
dataframe.
Table headers
-------------
To print nice column headers, supply the second argument (`headers`):
- `headers` can be an explicit list of column headers
- if `headers="firstrow"`, then the first row of data is used
- if `headers="keys"`, then dictionary keys or column indices are used
Otherwise a headerless table is produced.
If the number of headers is less than the number of columns, they
are supposed to be names of the last columns. This is consistent
with the plain-text format of R and Pandas' dataframes.
>>> print(tabulate([["sex","age"],["Alice","F",24],["Bob","M",19]],
... headers="firstrow"))
sex age
----- ----- -----
Alice F 24
Bob M 19
Column alignment
----------------
`tabulate` tries to detect column types automatically, and aligns
the values properly. By default it aligns decimal points of the
numbers (or flushes integer numbers to the right), and flushes
everything else to the left. Possible column alignments
(`numalign`, `stralign`) are: "right", "center", "left", "decimal"
(only for `numalign`), and None (to disable alignment).
Table formats
-------------
`floatfmt` is a format specification used for columns which
contain numeric data with a decimal point.
`None` values are replaced with a `missingval` string:
>>> print(tabulate([["spam", 1, None],
... ["eggs", 42, 3.14],
... ["other", None, 2.7]], missingval="?"))
----- -- ----
spam 1 ?
eggs 42 3.14
other ? 2.7
----- -- ----
Various plain-text table formats (`tablefmt`) are supported:
'plain', 'simple', 'grid', 'pipe', 'orgtbl', 'rst', 'mediawiki',
'latex', and 'latex_booktabs'. Variable `tabulate_formats` contains the list of
currently supported formats.
"plain" format doesn't use any pseudographics to draw tables,
it separates columns with a double space:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "plain"))
strings numbers
spam 41.9999
eggs 451
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="plain"))
spam 41.9999
eggs 451
"simple" format is like Pandoc simple_tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "simple"))
strings numbers
--------- ---------
spam 41.9999
eggs 451
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="simple"))
---- --------
spam 41.9999
eggs 451
---- --------
"grid" is similar to tables produced by Emacs table.el package or
Pandoc grid_tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "grid"))
+-----------+-----------+
| strings | numbers |
+===========+===========+
| spam | 41.9999 |
+-----------+-----------+
| eggs | 451 |
+-----------+-----------+
>>> print(tabulate([["this\\nis\\na multiline\\ntext", "41.9999", "foo\\nbar"], ["NULL", "451.0", ""]],
... ["text", "numbers", "other"], "grid"))
+-------------+----------+-------+
| text | numbers | other |
+=============+==========+=======+
| this | 41.9999 | foo |
| is | | bar |
| a multiline | | |
| text | | |
+-------------+----------+-------+
| NULL | 451 | |
+-------------+----------+-------+
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="grid"))
+------+----------+
| spam | 41.9999 |
+------+----------+
| eggs | 451 |
+------+----------+
"fancy_grid" draws a grid using box-drawing characters:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "fancy_grid"))
╒═══════════╤═══════════╕
│ strings │ numbers │
╞═══════════╪═══════════╡
│ spam │ 41.9999 │
├───────────┼───────────┤
│ eggs │ 451 │
╘═══════════╧═══════════╛
"pipe" is like tables in PHP Markdown Extra extension or Pandoc
pipe_tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "pipe"))
| strings | numbers |
|:----------|----------:|
| spam | 41.9999 |
| eggs | 451 |
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="pipe"))
|:-----|---------:|
| spam | 41.9999 |
| eggs | 451 |
"orgtbl" is like tables in Emacs org-mode and orgtbl-mode. They
are slightly different from "pipe" format by not using colons to
define column alignment, and using a "+" sign to indicate line
intersections:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "orgtbl"))
| strings | numbers |
|-----------+-----------|
| spam | 41.9999 |
| eggs | 451 |
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="orgtbl"))
| spam | 41.9999 |
| eggs | 451 |
"rst" is like a simple table format from reStructuredText; please
note that reStructuredText accepts also "grid" tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "rst"))
========= =========
strings numbers
========= =========
spam 41.9999
eggs 451
========= =========
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="rst"))
==== ========
spam 41.9999
eggs 451
==== ========
"mediawiki" produces a table markup used in Wikipedia and on other
MediaWiki-based sites:
>>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]],
... headers="firstrow", tablefmt="mediawiki"))
{| class="wikitable" style="text-align: left;"
|+ <!-- caption -->
|-
! strings !! align="right"| numbers
|-
| spam || align="right"| 41.9999
|-
| eggs || align="right"| 451
|}
"html" produces HTML markup:
>>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]],
... headers="firstrow", tablefmt="html"))
<table>
<tr><th>strings </th><th style="text-align: right;"> numbers</th></tr>
<tr><td>spam </td><td style="text-align: right;"> 41.9999</td></tr>
<tr><td>eggs </td><td style="text-align: right;"> 451 </td></tr>
</table>
"latex" produces a tabular environment of LaTeX document markup:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex"))
\\begin{tabular}{lr}
\\hline
spam & 41.9999 \\\\
eggs & 451 \\\\
\\hline
\\end{tabular}
"latex_booktabs" produces a tabular environment of LaTeX document markup
using the booktabs.sty package:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex_booktabs"))
\\begin{tabular}{lr}
\\toprule
spam & 41.9999 \\\\
eggs & 451 \\\\
\\bottomrule
\end{tabular}
"""
if tabular_data is None:
tabular_data = []
list_of_lists, headers = _normalize_tabular_data(tabular_data, headers)
# optimization: look for ANSI control codes once,
# enable smart width functions only if a control code is found
plain_text = '\n'.join(['\t'.join(map(_text_type, headers))] + \
['\t'.join(map(_text_type, row)) for row in list_of_lists])
has_invisible = re.search(_invisible_codes, plain_text)
enable_widechars = wcwidth is not None and WIDE_CHARS_MODE
is_multiline = _is_multiline(plain_text)
width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline)
# format rows and columns, convert numeric values to strings
cols = list(zip(*list_of_lists))
coltypes = list(map(_column_type, cols))
cols = [[_format(v, ct, floatfmt, missingval, has_invisible) for v in c]
for c, ct in zip(cols, coltypes)]
# align columns
aligns = [numalign if ct in [int, float] else stralign for ct in coltypes]
minwidths = [width_fn(h) + MIN_PADDING for h in headers] if headers else [0] * len(cols)
cols = [_align_column(c, a, minw, has_invisible, enable_widechars, is_multiline)
for c, a, minw in zip(cols, aligns, minwidths)]
if headers:
# align headers and add headers
t_cols = cols or [['']] * len(headers)
t_aligns = aligns or [stralign] * len(headers)
minwidths = [max(minw, width_fn(c[0])) for minw, c in zip(minwidths, t_cols)]
headers = [_align_header(h, a, minw, width_fn(h), enable_widechars, is_multiline)
for h, a, minw in zip(headers, t_aligns, minwidths)]
rows = list(zip(*cols))
else:
minwidths = [width_fn(c[0]) for c in cols]
rows = list(zip(*cols))
if not isinstance(tablefmt, TableFormat):
tablefmt = _table_formats.get(tablefmt, _table_formats["simple"])
return _format_table(tablefmt, headers, rows, minwidths, aligns, is_multiline) | python | def tabulate(tabular_data, headers=(), tablefmt="simple",
floatfmt="g", numalign="decimal", stralign="left",
missingval=""):
if tabular_data is None:
tabular_data = []
list_of_lists, headers = _normalize_tabular_data(tabular_data, headers)
plain_text = '\n'.join(['\t'.join(map(_text_type, headers))] + \
['\t'.join(map(_text_type, row)) for row in list_of_lists])
has_invisible = re.search(_invisible_codes, plain_text)
enable_widechars = wcwidth is not None and WIDE_CHARS_MODE
is_multiline = _is_multiline(plain_text)
width_fn = _choose_width_fn(has_invisible, enable_widechars, is_multiline)
cols = list(zip(*list_of_lists))
coltypes = list(map(_column_type, cols))
cols = [[_format(v, ct, floatfmt, missingval, has_invisible) for v in c]
for c, ct in zip(cols, coltypes)]
aligns = [numalign if ct in [int, float] else stralign for ct in coltypes]
minwidths = [width_fn(h) + MIN_PADDING for h in headers] if headers else [0] * len(cols)
cols = [_align_column(c, a, minw, has_invisible, enable_widechars, is_multiline)
for c, a, minw in zip(cols, aligns, minwidths)]
if headers:
t_cols = cols or [['']] * len(headers)
t_aligns = aligns or [stralign] * len(headers)
minwidths = [max(minw, width_fn(c[0])) for minw, c in zip(minwidths, t_cols)]
headers = [_align_header(h, a, minw, width_fn(h), enable_widechars, is_multiline)
for h, a, minw in zip(headers, t_aligns, minwidths)]
rows = list(zip(*cols))
else:
minwidths = [width_fn(c[0]) for c in cols]
rows = list(zip(*cols))
if not isinstance(tablefmt, TableFormat):
tablefmt = _table_formats.get(tablefmt, _table_formats["simple"])
return _format_table(tablefmt, headers, rows, minwidths, aligns, is_multiline) | [
"def",
"tabulate",
"(",
"tabular_data",
",",
"headers",
"=",
"(",
")",
",",
"tablefmt",
"=",
"\"simple\"",
",",
"floatfmt",
"=",
"\"g\"",
",",
"numalign",
"=",
"\"decimal\"",
",",
"stralign",
"=",
"\"left\"",
",",
"missingval",
"=",
"\"\"",
")",
":",
"if",
"tabular_data",
"is",
"None",
":",
"tabular_data",
"=",
"[",
"]",
"list_of_lists",
",",
"headers",
"=",
"_normalize_tabular_data",
"(",
"tabular_data",
",",
"headers",
")",
"# optimization: look for ANSI control codes once,",
"# enable smart width functions only if a control code is found",
"plain_text",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'\\t'",
".",
"join",
"(",
"map",
"(",
"_text_type",
",",
"headers",
")",
")",
"]",
"+",
"[",
"'\\t'",
".",
"join",
"(",
"map",
"(",
"_text_type",
",",
"row",
")",
")",
"for",
"row",
"in",
"list_of_lists",
"]",
")",
"has_invisible",
"=",
"re",
".",
"search",
"(",
"_invisible_codes",
",",
"plain_text",
")",
"enable_widechars",
"=",
"wcwidth",
"is",
"not",
"None",
"and",
"WIDE_CHARS_MODE",
"is_multiline",
"=",
"_is_multiline",
"(",
"plain_text",
")",
"width_fn",
"=",
"_choose_width_fn",
"(",
"has_invisible",
",",
"enable_widechars",
",",
"is_multiline",
")",
"# format rows and columns, convert numeric values to strings",
"cols",
"=",
"list",
"(",
"zip",
"(",
"*",
"list_of_lists",
")",
")",
"coltypes",
"=",
"list",
"(",
"map",
"(",
"_column_type",
",",
"cols",
")",
")",
"cols",
"=",
"[",
"[",
"_format",
"(",
"v",
",",
"ct",
",",
"floatfmt",
",",
"missingval",
",",
"has_invisible",
")",
"for",
"v",
"in",
"c",
"]",
"for",
"c",
",",
"ct",
"in",
"zip",
"(",
"cols",
",",
"coltypes",
")",
"]",
"# align columns",
"aligns",
"=",
"[",
"numalign",
"if",
"ct",
"in",
"[",
"int",
",",
"float",
"]",
"else",
"stralign",
"for",
"ct",
"in",
"coltypes",
"]",
"minwidths",
"=",
"[",
"width_fn",
"(",
"h",
")",
"+",
"MIN_PADDING",
"for",
"h",
"in",
"headers",
"]",
"if",
"headers",
"else",
"[",
"0",
"]",
"*",
"len",
"(",
"cols",
")",
"cols",
"=",
"[",
"_align_column",
"(",
"c",
",",
"a",
",",
"minw",
",",
"has_invisible",
",",
"enable_widechars",
",",
"is_multiline",
")",
"for",
"c",
",",
"a",
",",
"minw",
"in",
"zip",
"(",
"cols",
",",
"aligns",
",",
"minwidths",
")",
"]",
"if",
"headers",
":",
"# align headers and add headers",
"t_cols",
"=",
"cols",
"or",
"[",
"[",
"''",
"]",
"]",
"*",
"len",
"(",
"headers",
")",
"t_aligns",
"=",
"aligns",
"or",
"[",
"stralign",
"]",
"*",
"len",
"(",
"headers",
")",
"minwidths",
"=",
"[",
"max",
"(",
"minw",
",",
"width_fn",
"(",
"c",
"[",
"0",
"]",
")",
")",
"for",
"minw",
",",
"c",
"in",
"zip",
"(",
"minwidths",
",",
"t_cols",
")",
"]",
"headers",
"=",
"[",
"_align_header",
"(",
"h",
",",
"a",
",",
"minw",
",",
"width_fn",
"(",
"h",
")",
",",
"enable_widechars",
",",
"is_multiline",
")",
"for",
"h",
",",
"a",
",",
"minw",
"in",
"zip",
"(",
"headers",
",",
"t_aligns",
",",
"minwidths",
")",
"]",
"rows",
"=",
"list",
"(",
"zip",
"(",
"*",
"cols",
")",
")",
"else",
":",
"minwidths",
"=",
"[",
"width_fn",
"(",
"c",
"[",
"0",
"]",
")",
"for",
"c",
"in",
"cols",
"]",
"rows",
"=",
"list",
"(",
"zip",
"(",
"*",
"cols",
")",
")",
"if",
"not",
"isinstance",
"(",
"tablefmt",
",",
"TableFormat",
")",
":",
"tablefmt",
"=",
"_table_formats",
".",
"get",
"(",
"tablefmt",
",",
"_table_formats",
"[",
"\"simple\"",
"]",
")",
"return",
"_format_table",
"(",
"tablefmt",
",",
"headers",
",",
"rows",
",",
"minwidths",
",",
"aligns",
",",
"is_multiline",
")"
]
| Format a fixed width table for pretty printing.
>>> print(tabulate([[1, 2.34], [-56, "8.999"], ["2", "10001"]]))
--- ---------
1 2.34
-56 8.999
2 10001
--- ---------
The first required argument (`tabular_data`) can be a
list-of-lists (or another iterable of iterables), a list of named
tuples, a dictionary of iterables, an iterable of dictionaries,
a two-dimensional NumPy array, NumPy record array, or a Pandas'
dataframe.
Table headers
-------------
To print nice column headers, supply the second argument (`headers`):
- `headers` can be an explicit list of column headers
- if `headers="firstrow"`, then the first row of data is used
- if `headers="keys"`, then dictionary keys or column indices are used
Otherwise a headerless table is produced.
If the number of headers is less than the number of columns, they
are supposed to be names of the last columns. This is consistent
with the plain-text format of R and Pandas' dataframes.
>>> print(tabulate([["sex","age"],["Alice","F",24],["Bob","M",19]],
... headers="firstrow"))
sex age
----- ----- -----
Alice F 24
Bob M 19
Column alignment
----------------
`tabulate` tries to detect column types automatically, and aligns
the values properly. By default it aligns decimal points of the
numbers (or flushes integer numbers to the right), and flushes
everything else to the left. Possible column alignments
(`numalign`, `stralign`) are: "right", "center", "left", "decimal"
(only for `numalign`), and None (to disable alignment).
Table formats
-------------
`floatfmt` is a format specification used for columns which
contain numeric data with a decimal point.
`None` values are replaced with a `missingval` string:
>>> print(tabulate([["spam", 1, None],
... ["eggs", 42, 3.14],
... ["other", None, 2.7]], missingval="?"))
----- -- ----
spam 1 ?
eggs 42 3.14
other ? 2.7
----- -- ----
Various plain-text table formats (`tablefmt`) are supported:
'plain', 'simple', 'grid', 'pipe', 'orgtbl', 'rst', 'mediawiki',
'latex', and 'latex_booktabs'. Variable `tabulate_formats` contains the list of
currently supported formats.
"plain" format doesn't use any pseudographics to draw tables,
it separates columns with a double space:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "plain"))
strings numbers
spam 41.9999
eggs 451
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="plain"))
spam 41.9999
eggs 451
"simple" format is like Pandoc simple_tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "simple"))
strings numbers
--------- ---------
spam 41.9999
eggs 451
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="simple"))
---- --------
spam 41.9999
eggs 451
---- --------
"grid" is similar to tables produced by Emacs table.el package or
Pandoc grid_tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "grid"))
+-----------+-----------+
| strings | numbers |
+===========+===========+
| spam | 41.9999 |
+-----------+-----------+
| eggs | 451 |
+-----------+-----------+
>>> print(tabulate([["this\\nis\\na multiline\\ntext", "41.9999", "foo\\nbar"], ["NULL", "451.0", ""]],
... ["text", "numbers", "other"], "grid"))
+-------------+----------+-------+
| text | numbers | other |
+=============+==========+=======+
| this | 41.9999 | foo |
| is | | bar |
| a multiline | | |
| text | | |
+-------------+----------+-------+
| NULL | 451 | |
+-------------+----------+-------+
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="grid"))
+------+----------+
| spam | 41.9999 |
+------+----------+
| eggs | 451 |
+------+----------+
"fancy_grid" draws a grid using box-drawing characters:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "fancy_grid"))
╒═══════════╤═══════════╕
│ strings │ numbers │
╞═══════════╪═══════════╡
│ spam │ 41.9999 │
├───────────┼───────────┤
│ eggs │ 451 │
╘═══════════╧═══════════╛
"pipe" is like tables in PHP Markdown Extra extension or Pandoc
pipe_tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "pipe"))
| strings | numbers |
|:----------|----------:|
| spam | 41.9999 |
| eggs | 451 |
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="pipe"))
|:-----|---------:|
| spam | 41.9999 |
| eggs | 451 |
"orgtbl" is like tables in Emacs org-mode and orgtbl-mode. They
are slightly different from "pipe" format by not using colons to
define column alignment, and using a "+" sign to indicate line
intersections:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "orgtbl"))
| strings | numbers |
|-----------+-----------|
| spam | 41.9999 |
| eggs | 451 |
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="orgtbl"))
| spam | 41.9999 |
| eggs | 451 |
"rst" is like a simple table format from reStructuredText; please
note that reStructuredText accepts also "grid" tables:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],
... ["strings", "numbers"], "rst"))
========= =========
strings numbers
========= =========
spam 41.9999
eggs 451
========= =========
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="rst"))
==== ========
spam 41.9999
eggs 451
==== ========
"mediawiki" produces a table markup used in Wikipedia and on other
MediaWiki-based sites:
>>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]],
... headers="firstrow", tablefmt="mediawiki"))
{| class="wikitable" style="text-align: left;"
|+ <!-- caption -->
|-
! strings !! align="right"| numbers
|-
| spam || align="right"| 41.9999
|-
| eggs || align="right"| 451
|}
"html" produces HTML markup:
>>> print(tabulate([["strings", "numbers"], ["spam", 41.9999], ["eggs", "451.0"]],
... headers="firstrow", tablefmt="html"))
<table>
<tr><th>strings </th><th style="text-align: right;"> numbers</th></tr>
<tr><td>spam </td><td style="text-align: right;"> 41.9999</td></tr>
<tr><td>eggs </td><td style="text-align: right;"> 451 </td></tr>
</table>
"latex" produces a tabular environment of LaTeX document markup:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex"))
\\begin{tabular}{lr}
\\hline
spam & 41.9999 \\\\
eggs & 451 \\\\
\\hline
\\end{tabular}
"latex_booktabs" produces a tabular environment of LaTeX document markup
using the booktabs.sty package:
>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], tablefmt="latex_booktabs"))
\\begin{tabular}{lr}
\\toprule
spam & 41.9999 \\\\
eggs & 451 \\\\
\\bottomrule
\end{tabular} | [
"Format",
"a",
"fixed",
"width",
"table",
"for",
"pretty",
"printing",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L770-L1055 |
crate/crash | src/crate/crash/tabulate.py | _format_table | def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
pad = fmt.padding
headerrow = fmt.headerrow
padded_widths = [(w + 2 * pad) for w in colwidths]
if is_multiline:
pad_row = lambda row, _: row # do it later, in _append_multiline_row
append_row = partial(_append_multiline_row, pad=pad)
else:
pad_row = _pad_row
append_row = _append_basic_row
padded_headers = pad_row(headers, pad)
padded_rows = [pad_row(row, pad) for row in rows]
if fmt.lineabove and "lineabove" not in hidden:
_append_line(lines, padded_widths, colaligns, fmt.lineabove)
if padded_headers:
append_row(lines, padded_headers, padded_widths, colaligns, headerrow)
if fmt.linebelowheader and "linebelowheader" not in hidden:
_append_line(lines, padded_widths, colaligns, fmt.linebelowheader)
if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden:
# initial rows with a line below
for row in padded_rows[:-1]:
append_row(lines, row, padded_widths, colaligns, fmt.datarow)
_append_line(lines, padded_widths, colaligns, fmt.linebetweenrows)
# the last row without a line below
append_row(lines, padded_rows[-1], padded_widths, colaligns, fmt.datarow)
else:
for row in padded_rows:
append_row(lines, row, padded_widths, colaligns, fmt.datarow)
if fmt.linebelow and "linebelow" not in hidden:
_append_line(lines, padded_widths, colaligns, fmt.linebelow)
return "\n".join(lines) | python | def _format_table(fmt, headers, rows, colwidths, colaligns, is_multiline):
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
pad = fmt.padding
headerrow = fmt.headerrow
padded_widths = [(w + 2 * pad) for w in colwidths]
if is_multiline:
pad_row = lambda row, _: row
append_row = partial(_append_multiline_row, pad=pad)
else:
pad_row = _pad_row
append_row = _append_basic_row
padded_headers = pad_row(headers, pad)
padded_rows = [pad_row(row, pad) for row in rows]
if fmt.lineabove and "lineabove" not in hidden:
_append_line(lines, padded_widths, colaligns, fmt.lineabove)
if padded_headers:
append_row(lines, padded_headers, padded_widths, colaligns, headerrow)
if fmt.linebelowheader and "linebelowheader" not in hidden:
_append_line(lines, padded_widths, colaligns, fmt.linebelowheader)
if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden:
for row in padded_rows[:-1]:
append_row(lines, row, padded_widths, colaligns, fmt.datarow)
_append_line(lines, padded_widths, colaligns, fmt.linebetweenrows)
append_row(lines, padded_rows[-1], padded_widths, colaligns, fmt.datarow)
else:
for row in padded_rows:
append_row(lines, row, padded_widths, colaligns, fmt.datarow)
if fmt.linebelow and "linebelow" not in hidden:
_append_line(lines, padded_widths, colaligns, fmt.linebelow)
return "\n".join(lines) | [
"def",
"_format_table",
"(",
"fmt",
",",
"headers",
",",
"rows",
",",
"colwidths",
",",
"colaligns",
",",
"is_multiline",
")",
":",
"lines",
"=",
"[",
"]",
"hidden",
"=",
"fmt",
".",
"with_header_hide",
"if",
"(",
"headers",
"and",
"fmt",
".",
"with_header_hide",
")",
"else",
"[",
"]",
"pad",
"=",
"fmt",
".",
"padding",
"headerrow",
"=",
"fmt",
".",
"headerrow",
"padded_widths",
"=",
"[",
"(",
"w",
"+",
"2",
"*",
"pad",
")",
"for",
"w",
"in",
"colwidths",
"]",
"if",
"is_multiline",
":",
"pad_row",
"=",
"lambda",
"row",
",",
"_",
":",
"row",
"# do it later, in _append_multiline_row",
"append_row",
"=",
"partial",
"(",
"_append_multiline_row",
",",
"pad",
"=",
"pad",
")",
"else",
":",
"pad_row",
"=",
"_pad_row",
"append_row",
"=",
"_append_basic_row",
"padded_headers",
"=",
"pad_row",
"(",
"headers",
",",
"pad",
")",
"padded_rows",
"=",
"[",
"pad_row",
"(",
"row",
",",
"pad",
")",
"for",
"row",
"in",
"rows",
"]",
"if",
"fmt",
".",
"lineabove",
"and",
"\"lineabove\"",
"not",
"in",
"hidden",
":",
"_append_line",
"(",
"lines",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"lineabove",
")",
"if",
"padded_headers",
":",
"append_row",
"(",
"lines",
",",
"padded_headers",
",",
"padded_widths",
",",
"colaligns",
",",
"headerrow",
")",
"if",
"fmt",
".",
"linebelowheader",
"and",
"\"linebelowheader\"",
"not",
"in",
"hidden",
":",
"_append_line",
"(",
"lines",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"linebelowheader",
")",
"if",
"padded_rows",
"and",
"fmt",
".",
"linebetweenrows",
"and",
"\"linebetweenrows\"",
"not",
"in",
"hidden",
":",
"# initial rows with a line below",
"for",
"row",
"in",
"padded_rows",
"[",
":",
"-",
"1",
"]",
":",
"append_row",
"(",
"lines",
",",
"row",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"datarow",
")",
"_append_line",
"(",
"lines",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"linebetweenrows",
")",
"# the last row without a line below",
"append_row",
"(",
"lines",
",",
"padded_rows",
"[",
"-",
"1",
"]",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"datarow",
")",
"else",
":",
"for",
"row",
"in",
"padded_rows",
":",
"append_row",
"(",
"lines",
",",
"row",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"datarow",
")",
"if",
"fmt",
".",
"linebelow",
"and",
"\"linebelow\"",
"not",
"in",
"hidden",
":",
"_append_line",
"(",
"lines",
",",
"padded_widths",
",",
"colaligns",
",",
"fmt",
".",
"linebelow",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"lines",
")"
]
| Produce a plain-text representation of the table. | [
"Produce",
"a",
"plain",
"-",
"text",
"representation",
"of",
"the",
"table",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/tabulate.py#L1118-L1158 |
crate/crash | src/crate/crash/layout.py | create_layout | def create_layout(lexer=None,
reserve_space_for_menu=8,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
extra_input_processors=None, multiline=False,
wrap_lines=True):
"""
Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar container
* a bottom right-aligned side-bar container
+-------------------------------------------+
| cr> select 1; |
| |
| |
+-------------------------------------------+
| bottom_toolbar_tokens sidebar_tokens |
+-------------------------------------------+
"""
# Create processors list.
input_processors = [
ConditionalProcessor(
# Highlight the reverse-i-search buffer
HighlightSearchProcessor(preview_search=True),
HasFocus(SEARCH_BUFFER)),
]
if extra_input_processors:
input_processors.extend(extra_input_processors)
lexer = PygmentsLexer(lexer, sync_from_start=True)
multiline = to_cli_filter(multiline)
sidebar_token = [
(Token.Toolbar.Status.Key, "[ctrl+d]"),
(Token.Toolbar.Status, " Exit")
]
sidebar_width = token_list_width(sidebar_token)
get_sidebar_tokens = lambda _: sidebar_token
def get_height(cli):
# If there is an autocompletion menu to be shown, make sure that our
# layout has at least a minimal height in order to display it.
if reserve_space_for_menu and not cli.is_done:
buff = cli.current_buffer
# Reserve the space, either when there are completions, or when
# `complete_while_typing` is true and we expect completions very
# soon.
if buff.complete_while_typing() or buff.complete_state is not None:
return LayoutDimension(min=reserve_space_for_menu)
return LayoutDimension()
# Create and return Container instance.
return HSplit([
VSplit([
HSplit([
# The main input, with completion menus floating on top of it.
FloatContainer(
HSplit([
Window(
BufferControl(
input_processors=input_processors,
lexer=lexer,
# enable preview search for reverse-i-search
preview_search=True),
get_height=get_height,
wrap_lines=wrap_lines,
left_margins=[
# In multiline mode, use the window margin to display
# the prompt and continuation tokens.
ConditionalMargin(
PromptMargin(get_prompt_tokens),
filter=multiline
)
],
),
]),
[
# Completion menu
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=16,
scroll_offset=1,
extra_filter=HasFocus(DEFAULT_BUFFER))
),
]
),
# reverse-i-search toolbar (ctrl+r)
ConditionalContainer(SearchToolbar(), multiline),
])
]),
] + [
VSplit([
# Left-Aligned Session Toolbar
ConditionalContainer(
Window(
TokenListControl(get_bottom_toolbar_tokens),
height=LayoutDimension.exact(1)
),
filter=~IsDone() & RendererHeightIsKnown()),
# Right-Aligned Container
ConditionalContainer(
Window(
TokenListControl(get_sidebar_tokens),
height=LayoutDimension.exact(1),
width=LayoutDimension.exact(sidebar_width)
),
filter=~IsDone() & RendererHeightIsKnown())
])
]) | python | def create_layout(lexer=None,
reserve_space_for_menu=8,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
extra_input_processors=None, multiline=False,
wrap_lines=True):
input_processors = [
ConditionalProcessor(
HighlightSearchProcessor(preview_search=True),
HasFocus(SEARCH_BUFFER)),
]
if extra_input_processors:
input_processors.extend(extra_input_processors)
lexer = PygmentsLexer(lexer, sync_from_start=True)
multiline = to_cli_filter(multiline)
sidebar_token = [
(Token.Toolbar.Status.Key, "[ctrl+d]"),
(Token.Toolbar.Status, " Exit")
]
sidebar_width = token_list_width(sidebar_token)
get_sidebar_tokens = lambda _: sidebar_token
def get_height(cli):
if reserve_space_for_menu and not cli.is_done:
buff = cli.current_buffer
if buff.complete_while_typing() or buff.complete_state is not None:
return LayoutDimension(min=reserve_space_for_menu)
return LayoutDimension()
return HSplit([
VSplit([
HSplit([
FloatContainer(
HSplit([
Window(
BufferControl(
input_processors=input_processors,
lexer=lexer,
preview_search=True),
get_height=get_height,
wrap_lines=wrap_lines,
left_margins=[
ConditionalMargin(
PromptMargin(get_prompt_tokens),
filter=multiline
)
],
),
]),
[
Float(xcursor=True,
ycursor=True,
content=CompletionsMenu(
max_height=16,
scroll_offset=1,
extra_filter=HasFocus(DEFAULT_BUFFER))
),
]
),
ConditionalContainer(SearchToolbar(), multiline),
])
]),
] + [
VSplit([
ConditionalContainer(
Window(
TokenListControl(get_bottom_toolbar_tokens),
height=LayoutDimension.exact(1)
),
filter=~IsDone() & RendererHeightIsKnown()),
ConditionalContainer(
Window(
TokenListControl(get_sidebar_tokens),
height=LayoutDimension.exact(1),
width=LayoutDimension.exact(sidebar_width)
),
filter=~IsDone() & RendererHeightIsKnown())
])
]) | [
"def",
"create_layout",
"(",
"lexer",
"=",
"None",
",",
"reserve_space_for_menu",
"=",
"8",
",",
"get_prompt_tokens",
"=",
"None",
",",
"get_bottom_toolbar_tokens",
"=",
"None",
",",
"extra_input_processors",
"=",
"None",
",",
"multiline",
"=",
"False",
",",
"wrap_lines",
"=",
"True",
")",
":",
"# Create processors list.",
"input_processors",
"=",
"[",
"ConditionalProcessor",
"(",
"# Highlight the reverse-i-search buffer",
"HighlightSearchProcessor",
"(",
"preview_search",
"=",
"True",
")",
",",
"HasFocus",
"(",
"SEARCH_BUFFER",
")",
")",
",",
"]",
"if",
"extra_input_processors",
":",
"input_processors",
".",
"extend",
"(",
"extra_input_processors",
")",
"lexer",
"=",
"PygmentsLexer",
"(",
"lexer",
",",
"sync_from_start",
"=",
"True",
")",
"multiline",
"=",
"to_cli_filter",
"(",
"multiline",
")",
"sidebar_token",
"=",
"[",
"(",
"Token",
".",
"Toolbar",
".",
"Status",
".",
"Key",
",",
"\"[ctrl+d]\"",
")",
",",
"(",
"Token",
".",
"Toolbar",
".",
"Status",
",",
"\" Exit\"",
")",
"]",
"sidebar_width",
"=",
"token_list_width",
"(",
"sidebar_token",
")",
"get_sidebar_tokens",
"=",
"lambda",
"_",
":",
"sidebar_token",
"def",
"get_height",
"(",
"cli",
")",
":",
"# If there is an autocompletion menu to be shown, make sure that our",
"# layout has at least a minimal height in order to display it.",
"if",
"reserve_space_for_menu",
"and",
"not",
"cli",
".",
"is_done",
":",
"buff",
"=",
"cli",
".",
"current_buffer",
"# Reserve the space, either when there are completions, or when",
"# `complete_while_typing` is true and we expect completions very",
"# soon.",
"if",
"buff",
".",
"complete_while_typing",
"(",
")",
"or",
"buff",
".",
"complete_state",
"is",
"not",
"None",
":",
"return",
"LayoutDimension",
"(",
"min",
"=",
"reserve_space_for_menu",
")",
"return",
"LayoutDimension",
"(",
")",
"# Create and return Container instance.",
"return",
"HSplit",
"(",
"[",
"VSplit",
"(",
"[",
"HSplit",
"(",
"[",
"# The main input, with completion menus floating on top of it.",
"FloatContainer",
"(",
"HSplit",
"(",
"[",
"Window",
"(",
"BufferControl",
"(",
"input_processors",
"=",
"input_processors",
",",
"lexer",
"=",
"lexer",
",",
"# enable preview search for reverse-i-search",
"preview_search",
"=",
"True",
")",
",",
"get_height",
"=",
"get_height",
",",
"wrap_lines",
"=",
"wrap_lines",
",",
"left_margins",
"=",
"[",
"# In multiline mode, use the window margin to display",
"# the prompt and continuation tokens.",
"ConditionalMargin",
"(",
"PromptMargin",
"(",
"get_prompt_tokens",
")",
",",
"filter",
"=",
"multiline",
")",
"]",
",",
")",
",",
"]",
")",
",",
"[",
"# Completion menu",
"Float",
"(",
"xcursor",
"=",
"True",
",",
"ycursor",
"=",
"True",
",",
"content",
"=",
"CompletionsMenu",
"(",
"max_height",
"=",
"16",
",",
"scroll_offset",
"=",
"1",
",",
"extra_filter",
"=",
"HasFocus",
"(",
"DEFAULT_BUFFER",
")",
")",
")",
",",
"]",
")",
",",
"# reverse-i-search toolbar (ctrl+r)",
"ConditionalContainer",
"(",
"SearchToolbar",
"(",
")",
",",
"multiline",
")",
",",
"]",
")",
"]",
")",
",",
"]",
"+",
"[",
"VSplit",
"(",
"[",
"# Left-Aligned Session Toolbar",
"ConditionalContainer",
"(",
"Window",
"(",
"TokenListControl",
"(",
"get_bottom_toolbar_tokens",
")",
",",
"height",
"=",
"LayoutDimension",
".",
"exact",
"(",
"1",
")",
")",
",",
"filter",
"=",
"~",
"IsDone",
"(",
")",
"&",
"RendererHeightIsKnown",
"(",
")",
")",
",",
"# Right-Aligned Container",
"ConditionalContainer",
"(",
"Window",
"(",
"TokenListControl",
"(",
"get_sidebar_tokens",
")",
",",
"height",
"=",
"LayoutDimension",
".",
"exact",
"(",
"1",
")",
",",
"width",
"=",
"LayoutDimension",
".",
"exact",
"(",
"sidebar_width",
")",
")",
",",
"filter",
"=",
"~",
"IsDone",
"(",
")",
"&",
"RendererHeightIsKnown",
"(",
")",
")",
"]",
")",
"]",
")"
]
| Creates a custom `Layout` for the Crash input REPL
This layout includes:
* a bottom left-aligned session toolbar container
* a bottom right-aligned side-bar container
+-------------------------------------------+
| cr> select 1; |
| |
| |
+-------------------------------------------+
| bottom_toolbar_tokens sidebar_tokens |
+-------------------------------------------+ | [
"Creates",
"a",
"custom",
"Layout",
"for",
"the",
"Crash",
"input",
"REPL"
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/layout.py#L39-L157 |
crate/crash | src/crate/crash/command.py | parse_config_path | def parse_config_path(args=sys.argv):
"""
Preprocess sys.argv and extract --config argument.
"""
config = CONFIG_PATH
if '--config' in args:
idx = args.index('--config')
if len(args) > idx + 1:
config = args.pop(idx + 1)
args.pop(idx)
return config | python | def parse_config_path(args=sys.argv):
config = CONFIG_PATH
if '--config' in args:
idx = args.index('--config')
if len(args) > idx + 1:
config = args.pop(idx + 1)
args.pop(idx)
return config | [
"def",
"parse_config_path",
"(",
"args",
"=",
"sys",
".",
"argv",
")",
":",
"config",
"=",
"CONFIG_PATH",
"if",
"'--config'",
"in",
"args",
":",
"idx",
"=",
"args",
".",
"index",
"(",
"'--config'",
")",
"if",
"len",
"(",
"args",
")",
">",
"idx",
"+",
"1",
":",
"config",
"=",
"args",
".",
"pop",
"(",
"idx",
"+",
"1",
")",
"args",
".",
"pop",
"(",
"idx",
")",
"return",
"config"
]
| Preprocess sys.argv and extract --config argument. | [
"Preprocess",
"sys",
".",
"argv",
"and",
"extract",
"--",
"config",
"argument",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L85-L96 |
crate/crash | src/crate/crash/command.py | get_parser | def get_parser(output_formats=[], conf=None):
"""
Create an argument parser that reads default values from a
configuration file if provided.
"""
def _conf_or_default(key, value):
return value if conf is None else conf.get_or_set(key, value)
parser = ArgumentParser(description='crate shell')
parser.add_argument('-v', '--verbose', action='count',
dest='verbose', default=_conf_or_default('verbosity', 0),
help='print debug information to STDOUT')
parser.add_argument('-A', '--no-autocomplete', action='store_false',
dest='autocomplete',
default=_conf_or_default('autocomplete', True),
help='disable SQL keywords autocompletion')
parser.add_argument('-a', '--autocapitalize', action='store_true',
dest='autocapitalize',
default=False,
help='enable automatic capitalization of SQL keywords while typing')
parser.add_argument('-U', '--username', type=str, metavar='USERNAME',
help='Authenticate as USERNAME.')
parser.add_argument('-W', '--password', action='store_true',
dest='force_passwd_prompt', default=_conf_or_default('force_passwd_prompt', False),
help='force a password prompt')
parser.add_argument('--schema', type=str,
help='default schema for statements if schema is not explicitly stated in queries')
parser.add_argument('--history', type=str, metavar='FILENAME',
help='Use FILENAME as a history file', default=HISTORY_PATH)
parser.add_argument('--config', type=str, metavar='FILENAME',
help='use FILENAME as a configuration file', default=CONFIG_PATH)
group = parser.add_mutually_exclusive_group()
group.add_argument('-c', '--command', type=str, metavar='STATEMENT',
help='Execute the STATEMENT and exit.')
group.add_argument('--sysinfo', action='store_true', default=False,
help='print system and cluster information')
parser.add_argument('--hosts', type=str, nargs='*',
default=_conf_or_default('hosts', ['localhost:4200']),
help='connect to HOSTS.', metavar='HOSTS')
parser.add_argument('--verify-ssl', type=boolean, default=True,
help='force the verification of the server SSL certificate')
parser.add_argument('--cert-file', type=file_with_permissions, metavar='FILENAME',
help='use FILENAME as the client certificate file')
parser.add_argument('--key-file', type=file_with_permissions, metavar='FILENAME',
help='Use FILENAME as the client certificate key file')
parser.add_argument('--ca-cert-file', type=file_with_permissions, metavar='FILENAME',
help='use FILENAME as the CA certificate file')
parser.add_argument('--format', type=str,
default=_conf_or_default('format', 'tabular'),
choices=output_formats, metavar='FORMAT',
help='the output FORMAT of the SQL response')
parser.add_argument('--version', action='store_true', default=False,
help='print the Crash version and exit')
return parser | python | def get_parser(output_formats=[], conf=None):
def _conf_or_default(key, value):
return value if conf is None else conf.get_or_set(key, value)
parser = ArgumentParser(description='crate shell')
parser.add_argument('-v', '--verbose', action='count',
dest='verbose', default=_conf_or_default('verbosity', 0),
help='print debug information to STDOUT')
parser.add_argument('-A', '--no-autocomplete', action='store_false',
dest='autocomplete',
default=_conf_or_default('autocomplete', True),
help='disable SQL keywords autocompletion')
parser.add_argument('-a', '--autocapitalize', action='store_true',
dest='autocapitalize',
default=False,
help='enable automatic capitalization of SQL keywords while typing')
parser.add_argument('-U', '--username', type=str, metavar='USERNAME',
help='Authenticate as USERNAME.')
parser.add_argument('-W', '--password', action='store_true',
dest='force_passwd_prompt', default=_conf_or_default('force_passwd_prompt', False),
help='force a password prompt')
parser.add_argument('--schema', type=str,
help='default schema for statements if schema is not explicitly stated in queries')
parser.add_argument('--history', type=str, metavar='FILENAME',
help='Use FILENAME as a history file', default=HISTORY_PATH)
parser.add_argument('--config', type=str, metavar='FILENAME',
help='use FILENAME as a configuration file', default=CONFIG_PATH)
group = parser.add_mutually_exclusive_group()
group.add_argument('-c', '--command', type=str, metavar='STATEMENT',
help='Execute the STATEMENT and exit.')
group.add_argument('--sysinfo', action='store_true', default=False,
help='print system and cluster information')
parser.add_argument('--hosts', type=str, nargs='*',
default=_conf_or_default('hosts', ['localhost:4200']),
help='connect to HOSTS.', metavar='HOSTS')
parser.add_argument('--verify-ssl', type=boolean, default=True,
help='force the verification of the server SSL certificate')
parser.add_argument('--cert-file', type=file_with_permissions, metavar='FILENAME',
help='use FILENAME as the client certificate file')
parser.add_argument('--key-file', type=file_with_permissions, metavar='FILENAME',
help='Use FILENAME as the client certificate key file')
parser.add_argument('--ca-cert-file', type=file_with_permissions, metavar='FILENAME',
help='use FILENAME as the CA certificate file')
parser.add_argument('--format', type=str,
default=_conf_or_default('format', 'tabular'),
choices=output_formats, metavar='FORMAT',
help='the output FORMAT of the SQL response')
parser.add_argument('--version', action='store_true', default=False,
help='print the Crash version and exit')
return parser | [
"def",
"get_parser",
"(",
"output_formats",
"=",
"[",
"]",
",",
"conf",
"=",
"None",
")",
":",
"def",
"_conf_or_default",
"(",
"key",
",",
"value",
")",
":",
"return",
"value",
"if",
"conf",
"is",
"None",
"else",
"conf",
".",
"get_or_set",
"(",
"key",
",",
"value",
")",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'crate shell'",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"action",
"=",
"'count'",
",",
"dest",
"=",
"'verbose'",
",",
"default",
"=",
"_conf_or_default",
"(",
"'verbosity'",
",",
"0",
")",
",",
"help",
"=",
"'print debug information to STDOUT'",
")",
"parser",
".",
"add_argument",
"(",
"'-A'",
",",
"'--no-autocomplete'",
",",
"action",
"=",
"'store_false'",
",",
"dest",
"=",
"'autocomplete'",
",",
"default",
"=",
"_conf_or_default",
"(",
"'autocomplete'",
",",
"True",
")",
",",
"help",
"=",
"'disable SQL keywords autocompletion'",
")",
"parser",
".",
"add_argument",
"(",
"'-a'",
",",
"'--autocapitalize'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'autocapitalize'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'enable automatic capitalization of SQL keywords while typing'",
")",
"parser",
".",
"add_argument",
"(",
"'-U'",
",",
"'--username'",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"'USERNAME'",
",",
"help",
"=",
"'Authenticate as USERNAME.'",
")",
"parser",
".",
"add_argument",
"(",
"'-W'",
",",
"'--password'",
",",
"action",
"=",
"'store_true'",
",",
"dest",
"=",
"'force_passwd_prompt'",
",",
"default",
"=",
"_conf_or_default",
"(",
"'force_passwd_prompt'",
",",
"False",
")",
",",
"help",
"=",
"'force a password prompt'",
")",
"parser",
".",
"add_argument",
"(",
"'--schema'",
",",
"type",
"=",
"str",
",",
"help",
"=",
"'default schema for statements if schema is not explicitly stated in queries'",
")",
"parser",
".",
"add_argument",
"(",
"'--history'",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'Use FILENAME as a history file'",
",",
"default",
"=",
"HISTORY_PATH",
")",
"parser",
".",
"add_argument",
"(",
"'--config'",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'use FILENAME as a configuration file'",
",",
"default",
"=",
"CONFIG_PATH",
")",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
"'-c'",
",",
"'--command'",
",",
"type",
"=",
"str",
",",
"metavar",
"=",
"'STATEMENT'",
",",
"help",
"=",
"'Execute the STATEMENT and exit.'",
")",
"group",
".",
"add_argument",
"(",
"'--sysinfo'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'print system and cluster information'",
")",
"parser",
".",
"add_argument",
"(",
"'--hosts'",
",",
"type",
"=",
"str",
",",
"nargs",
"=",
"'*'",
",",
"default",
"=",
"_conf_or_default",
"(",
"'hosts'",
",",
"[",
"'localhost:4200'",
"]",
")",
",",
"help",
"=",
"'connect to HOSTS.'",
",",
"metavar",
"=",
"'HOSTS'",
")",
"parser",
".",
"add_argument",
"(",
"'--verify-ssl'",
",",
"type",
"=",
"boolean",
",",
"default",
"=",
"True",
",",
"help",
"=",
"'force the verification of the server SSL certificate'",
")",
"parser",
".",
"add_argument",
"(",
"'--cert-file'",
",",
"type",
"=",
"file_with_permissions",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'use FILENAME as the client certificate file'",
")",
"parser",
".",
"add_argument",
"(",
"'--key-file'",
",",
"type",
"=",
"file_with_permissions",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'Use FILENAME as the client certificate key file'",
")",
"parser",
".",
"add_argument",
"(",
"'--ca-cert-file'",
",",
"type",
"=",
"file_with_permissions",
",",
"metavar",
"=",
"'FILENAME'",
",",
"help",
"=",
"'use FILENAME as the CA certificate file'",
")",
"parser",
".",
"add_argument",
"(",
"'--format'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"_conf_or_default",
"(",
"'format'",
",",
"'tabular'",
")",
",",
"choices",
"=",
"output_formats",
",",
"metavar",
"=",
"'FORMAT'",
",",
"help",
"=",
"'the output FORMAT of the SQL response'",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"action",
"=",
"'store_true'",
",",
"default",
"=",
"False",
",",
"help",
"=",
"'print the Crash version and exit'",
")",
"return",
"parser"
]
| Create an argument parser that reads default values from a
configuration file if provided. | [
"Create",
"an",
"argument",
"parser",
"that",
"reads",
"default",
"values",
"from",
"a",
"configuration",
"file",
"if",
"provided",
"."
]
| train | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/command.py#L121-L178 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.