repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
spotify/snakebite | snakebite/channel.py | SocketRpcChannel.create_rpc_request_header | def create_rpc_request_header(self):
'''Creates and serializes a delimited RpcRequestHeaderProto message.'''
rpcheader = RpcRequestHeaderProto()
rpcheader.rpcKind = 2 # rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')
rpcheader.rpcOp = 0 # rpcheaderproto.RpcPayloadOperationProto.Value('RPC_FINAL_PACKET')
rpcheader.callId = self.call_id
rpcheader.retryCount = -1
rpcheader.clientId = self.client_id[0:16]
if self.call_id == -3:
self.call_id = 0
else:
self.call_id += 1
# Serialize delimited
s_rpcHeader = rpcheader.SerializeToString()
log_protobuf_message("RpcRequestHeaderProto (len: %d)" % (len(s_rpcHeader)), rpcheader)
return s_rpcHeader | python | def create_rpc_request_header(self):
'''Creates and serializes a delimited RpcRequestHeaderProto message.'''
rpcheader = RpcRequestHeaderProto()
rpcheader.rpcKind = 2 # rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')
rpcheader.rpcOp = 0 # rpcheaderproto.RpcPayloadOperationProto.Value('RPC_FINAL_PACKET')
rpcheader.callId = self.call_id
rpcheader.retryCount = -1
rpcheader.clientId = self.client_id[0:16]
if self.call_id == -3:
self.call_id = 0
else:
self.call_id += 1
# Serialize delimited
s_rpcHeader = rpcheader.SerializeToString()
log_protobuf_message("RpcRequestHeaderProto (len: %d)" % (len(s_rpcHeader)), rpcheader)
return s_rpcHeader | [
"def",
"create_rpc_request_header",
"(",
"self",
")",
":",
"rpcheader",
"=",
"RpcRequestHeaderProto",
"(",
")",
"rpcheader",
".",
"rpcKind",
"=",
"2",
"# rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')",
"rpcheader",
".",
"rpcOp",
"=",
"0",
"# rpcheaderproto.RpcP... | Creates and serializes a delimited RpcRequestHeaderProto message. | [
"Creates",
"and",
"serializes",
"a",
"delimited",
"RpcRequestHeaderProto",
"message",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L274-L291 | train | 199,000 |
spotify/snakebite | snakebite/channel.py | SocketRpcChannel.send_rpc_message | def send_rpc_message(self, method, request):
'''Sends a Hadoop RPC request to the NameNode.
The IpcConnectionContextProto, RpcPayloadHeaderProto and HadoopRpcRequestProto
should already be serialized in the right way (delimited or not) before
they are passed in this method.
The Hadoop RPC protocol looks like this for sending requests:
When sending requests
+---------------------------------------------------------------------+
| Length of the next three parts (4 bytes/32 bit int) |
+---------------------------------------------------------------------+
| Delimited serialized RpcRequestHeaderProto (varint len + header) |
+---------------------------------------------------------------------+
| Delimited serialized RequestHeaderProto (varint len + header) |
+---------------------------------------------------------------------+
| Delimited serialized Request (varint len + request) |
+---------------------------------------------------------------------+
'''
log.debug("############## SENDING ##############")
#0. RpcRequestHeaderProto
rpc_request_header = self.create_rpc_request_header()
#1. RequestHeaderProto
request_header = self.create_request_header(method)
#2. Param
param = request.SerializeToString()
if log.getEffectiveLevel() == logging.DEBUG:
log_protobuf_message("Request", request)
rpc_message_length = len(rpc_request_header) + encoder._VarintSize(len(rpc_request_header)) + \
len(request_header) + encoder._VarintSize(len(request_header)) + \
len(param) + encoder._VarintSize(len(param))
if log.getEffectiveLevel() == logging.DEBUG:
log.debug("RPC message length: %s (%s)" % (rpc_message_length, format_bytes(struct.pack('!I', rpc_message_length))))
self.write(struct.pack('!I', rpc_message_length))
self.write_delimited(rpc_request_header)
self.write_delimited(request_header)
self.write_delimited(param) | python | def send_rpc_message(self, method, request):
'''Sends a Hadoop RPC request to the NameNode.
The IpcConnectionContextProto, RpcPayloadHeaderProto and HadoopRpcRequestProto
should already be serialized in the right way (delimited or not) before
they are passed in this method.
The Hadoop RPC protocol looks like this for sending requests:
When sending requests
+---------------------------------------------------------------------+
| Length of the next three parts (4 bytes/32 bit int) |
+---------------------------------------------------------------------+
| Delimited serialized RpcRequestHeaderProto (varint len + header) |
+---------------------------------------------------------------------+
| Delimited serialized RequestHeaderProto (varint len + header) |
+---------------------------------------------------------------------+
| Delimited serialized Request (varint len + request) |
+---------------------------------------------------------------------+
'''
log.debug("############## SENDING ##############")
#0. RpcRequestHeaderProto
rpc_request_header = self.create_rpc_request_header()
#1. RequestHeaderProto
request_header = self.create_request_header(method)
#2. Param
param = request.SerializeToString()
if log.getEffectiveLevel() == logging.DEBUG:
log_protobuf_message("Request", request)
rpc_message_length = len(rpc_request_header) + encoder._VarintSize(len(rpc_request_header)) + \
len(request_header) + encoder._VarintSize(len(request_header)) + \
len(param) + encoder._VarintSize(len(param))
if log.getEffectiveLevel() == logging.DEBUG:
log.debug("RPC message length: %s (%s)" % (rpc_message_length, format_bytes(struct.pack('!I', rpc_message_length))))
self.write(struct.pack('!I', rpc_message_length))
self.write_delimited(rpc_request_header)
self.write_delimited(request_header)
self.write_delimited(param) | [
"def",
"send_rpc_message",
"(",
"self",
",",
"method",
",",
"request",
")",
":",
"log",
".",
"debug",
"(",
"\"############## SENDING ##############\"",
")",
"#0. RpcRequestHeaderProto",
"rpc_request_header",
"=",
"self",
".",
"create_rpc_request_header",
"(",
")",
"#1... | Sends a Hadoop RPC request to the NameNode.
The IpcConnectionContextProto, RpcPayloadHeaderProto and HadoopRpcRequestProto
should already be serialized in the right way (delimited or not) before
they are passed in this method.
The Hadoop RPC protocol looks like this for sending requests:
When sending requests
+---------------------------------------------------------------------+
| Length of the next three parts (4 bytes/32 bit int) |
+---------------------------------------------------------------------+
| Delimited serialized RpcRequestHeaderProto (varint len + header) |
+---------------------------------------------------------------------+
| Delimited serialized RequestHeaderProto (varint len + header) |
+---------------------------------------------------------------------+
| Delimited serialized Request (varint len + request) |
+---------------------------------------------------------------------+ | [
"Sends",
"a",
"Hadoop",
"RPC",
"request",
"to",
"the",
"NameNode",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L303-L344 | train | 199,001 |
spotify/snakebite | snakebite/channel.py | SocketRpcChannel.parse_response | def parse_response(self, byte_stream, response_class):
'''Parses a Hadoop RPC response.
The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR.
The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests.
+-----------------------------------------------------------+
| Length of the RPC resonse (4 bytes/32 bit int) |
+-----------------------------------------------------------+
| Delimited serialized RpcResponseHeaderProto |
+-----------------------------------------------------------+
| Serialized delimited RPC response |
+-----------------------------------------------------------+
In case of an error, the header status is set to ERROR and the error fields are set.
'''
log.debug("############## PARSING ##############")
log.debug("Payload class: %s" % response_class)
# Read first 4 bytes to get the total length
len_bytes = byte_stream.read(4)
total_length = struct.unpack("!I", len_bytes)[0]
log.debug("Total response length: %s" % total_length)
header = RpcResponseHeaderProto()
(header_len, header_bytes) = get_delimited_message_bytes(byte_stream)
log.debug("Header read %d" % header_len)
header.ParseFromString(header_bytes)
log_protobuf_message("RpcResponseHeaderProto", header)
if header.status == 0:
log.debug("header: %s, total: %s" % (header_len, total_length))
if header_len >= total_length:
return
response = response_class()
response_bytes = get_delimited_message_bytes(byte_stream, total_length - header_len)[1]
if len(response_bytes) > 0:
response.ParseFromString(response_bytes)
if log.getEffectiveLevel() == logging.DEBUG:
log_protobuf_message("Response", response)
return response
else:
self.handle_error(header) | python | def parse_response(self, byte_stream, response_class):
'''Parses a Hadoop RPC response.
The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR.
The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests.
+-----------------------------------------------------------+
| Length of the RPC resonse (4 bytes/32 bit int) |
+-----------------------------------------------------------+
| Delimited serialized RpcResponseHeaderProto |
+-----------------------------------------------------------+
| Serialized delimited RPC response |
+-----------------------------------------------------------+
In case of an error, the header status is set to ERROR and the error fields are set.
'''
log.debug("############## PARSING ##############")
log.debug("Payload class: %s" % response_class)
# Read first 4 bytes to get the total length
len_bytes = byte_stream.read(4)
total_length = struct.unpack("!I", len_bytes)[0]
log.debug("Total response length: %s" % total_length)
header = RpcResponseHeaderProto()
(header_len, header_bytes) = get_delimited_message_bytes(byte_stream)
log.debug("Header read %d" % header_len)
header.ParseFromString(header_bytes)
log_protobuf_message("RpcResponseHeaderProto", header)
if header.status == 0:
log.debug("header: %s, total: %s" % (header_len, total_length))
if header_len >= total_length:
return
response = response_class()
response_bytes = get_delimited_message_bytes(byte_stream, total_length - header_len)[1]
if len(response_bytes) > 0:
response.ParseFromString(response_bytes)
if log.getEffectiveLevel() == logging.DEBUG:
log_protobuf_message("Response", response)
return response
else:
self.handle_error(header) | [
"def",
"parse_response",
"(",
"self",
",",
"byte_stream",
",",
"response_class",
")",
":",
"log",
".",
"debug",
"(",
"\"############## PARSING ##############\"",
")",
"log",
".",
"debug",
"(",
"\"Payload class: %s\"",
"%",
"response_class",
")",
"# Read first 4 bytes ... | Parses a Hadoop RPC response.
The RpcResponseHeaderProto contains a status field that marks SUCCESS or ERROR.
The Hadoop RPC protocol looks like the diagram below for receiving SUCCESS requests.
+-----------------------------------------------------------+
| Length of the RPC resonse (4 bytes/32 bit int) |
+-----------------------------------------------------------+
| Delimited serialized RpcResponseHeaderProto |
+-----------------------------------------------------------+
| Serialized delimited RPC response |
+-----------------------------------------------------------+
In case of an error, the header status is set to ERROR and the error fields are set. | [
"Parses",
"a",
"Hadoop",
"RPC",
"response",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L375-L418 | train | 199,002 |
spotify/snakebite | snakebite/channel.py | SocketRpcChannel.close_socket | def close_socket(self):
'''Closes the socket and resets the channel.'''
log.debug("Closing socket")
if self.sock:
try:
self.sock.close()
except:
pass
self.sock = None | python | def close_socket(self):
'''Closes the socket and resets the channel.'''
log.debug("Closing socket")
if self.sock:
try:
self.sock.close()
except:
pass
self.sock = None | [
"def",
"close_socket",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Closing socket\"",
")",
"if",
"self",
".",
"sock",
":",
"try",
":",
"self",
".",
"sock",
".",
"close",
"(",
")",
"except",
":",
"pass",
"self",
".",
"sock",
"=",
"None"
] | Closes the socket and resets the channel. | [
"Closes",
"the",
"socket",
"and",
"resets",
"the",
"channel",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L423-L432 | train | 199,003 |
spotify/snakebite | snakebite/channel.py | SocketRpcChannel.CallMethod | def CallMethod(self, method, controller, request, response_class, done):
'''Call the RPC method. The naming doesn't confirm PEP8, since it's
a method called by protobuf
'''
try:
self.validate_request(request)
if not self.sock:
self.get_connection(self.host, self.port)
self.send_rpc_message(method, request)
byte_stream = self.recv_rpc_message()
return self.parse_response(byte_stream, response_class)
except RequestError: # Raise a request error, but don't close the socket
raise
except Exception: # All other errors close the socket
self.close_socket()
raise | python | def CallMethod(self, method, controller, request, response_class, done):
'''Call the RPC method. The naming doesn't confirm PEP8, since it's
a method called by protobuf
'''
try:
self.validate_request(request)
if not self.sock:
self.get_connection(self.host, self.port)
self.send_rpc_message(method, request)
byte_stream = self.recv_rpc_message()
return self.parse_response(byte_stream, response_class)
except RequestError: # Raise a request error, but don't close the socket
raise
except Exception: # All other errors close the socket
self.close_socket()
raise | [
"def",
"CallMethod",
"(",
"self",
",",
"method",
",",
"controller",
",",
"request",
",",
"response_class",
",",
"done",
")",
":",
"try",
":",
"self",
".",
"validate_request",
"(",
"request",
")",
"if",
"not",
"self",
".",
"sock",
":",
"self",
".",
"get... | Call the RPC method. The naming doesn't confirm PEP8, since it's
a method called by protobuf | [
"Call",
"the",
"RPC",
"method",
".",
"The",
"naming",
"doesn",
"t",
"confirm",
"PEP8",
"since",
"it",
"s",
"a",
"method",
"called",
"by",
"protobuf"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/channel.py#L434-L452 | train | 199,004 |
spotify/snakebite | snakebite/logger.py | getLogger | def getLogger(name):
''' Create and return a logger with the specified name. '''
# Create logger and add a default NULL handler
log = logging.getLogger(name)
log.addHandler(_NullHandler())
return log | python | def getLogger(name):
''' Create and return a logger with the specified name. '''
# Create logger and add a default NULL handler
log = logging.getLogger(name)
log.addHandler(_NullHandler())
return log | [
"def",
"getLogger",
"(",
"name",
")",
":",
"# Create logger and add a default NULL handler",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"log",
".",
"addHandler",
"(",
"_NullHandler",
"(",
")",
")",
"return",
"log"
] | Create and return a logger with the specified name. | [
"Create",
"and",
"return",
"a",
"logger",
"with",
"the",
"specified",
"name",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/logger.py#L51-L58 | train | 199,005 |
spotify/snakebite | snakebite/minicluster.py | MiniCluster.put | def put(self, src, dst):
'''Upload a file to HDFS
This will take a file from the ``testfiles_path`` supplied in the constuctor.
'''
src = "%s%s" % (self._testfiles_path, src)
return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-put', src, self._full_hdfs_path(dst)], True) | python | def put(self, src, dst):
'''Upload a file to HDFS
This will take a file from the ``testfiles_path`` supplied in the constuctor.
'''
src = "%s%s" % (self._testfiles_path, src)
return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-put', src, self._full_hdfs_path(dst)], True) | [
"def",
"put",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"src",
"=",
"\"%s%s\"",
"%",
"(",
"self",
".",
"_testfiles_path",
",",
"src",
")",
"return",
"self",
".",
"_getStdOutCmd",
"(",
"[",
"self",
".",
"_hadoop_cmd",
",",
"'fs'",
",",
"'-put'",
... | Upload a file to HDFS
This will take a file from the ``testfiles_path`` supplied in the constuctor. | [
"Upload",
"a",
"file",
"to",
"HDFS"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L87-L93 | train | 199,006 |
spotify/snakebite | snakebite/minicluster.py | MiniCluster.ls | def ls(self, src, extra_args=[]):
'''List files in a directory'''
src = [self._full_hdfs_path(x) for x in src]
output = self._getStdOutCmd([self._hadoop_cmd, 'fs', '-ls'] + extra_args + src, True)
return self._transform_ls_output(output, self.hdfs_url) | python | def ls(self, src, extra_args=[]):
'''List files in a directory'''
src = [self._full_hdfs_path(x) for x in src]
output = self._getStdOutCmd([self._hadoop_cmd, 'fs', '-ls'] + extra_args + src, True)
return self._transform_ls_output(output, self.hdfs_url) | [
"def",
"ls",
"(",
"self",
",",
"src",
",",
"extra_args",
"=",
"[",
"]",
")",
":",
"src",
"=",
"[",
"self",
".",
"_full_hdfs_path",
"(",
"x",
")",
"for",
"x",
"in",
"src",
"]",
"output",
"=",
"self",
".",
"_getStdOutCmd",
"(",
"[",
"self",
".",
... | List files in a directory | [
"List",
"files",
"in",
"a",
"directory"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L120-L124 | train | 199,007 |
spotify/snakebite | snakebite/minicluster.py | MiniCluster.df | def df(self, src):
'''Perform ``df`` on a path'''
return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-df', self._full_hdfs_path(src)], True) | python | def df(self, src):
'''Perform ``df`` on a path'''
return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-df', self._full_hdfs_path(src)], True) | [
"def",
"df",
"(",
"self",
",",
"src",
")",
":",
"return",
"self",
".",
"_getStdOutCmd",
"(",
"[",
"self",
".",
"_hadoop_cmd",
",",
"'fs'",
",",
"'-df'",
",",
"self",
".",
"_full_hdfs_path",
"(",
"src",
")",
"]",
",",
"True",
")"
] | Perform ``df`` on a path | [
"Perform",
"df",
"on",
"a",
"path"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L130-L132 | train | 199,008 |
spotify/snakebite | snakebite/minicluster.py | MiniCluster.du | def du(self, src, extra_args=[]):
'''Perform ``du`` on a path'''
src = [self._full_hdfs_path(x) for x in src]
return self._transform_du_output(self._getStdOutCmd([self._hadoop_cmd, 'fs', '-du'] + extra_args + src, True), self.hdfs_url) | python | def du(self, src, extra_args=[]):
'''Perform ``du`` on a path'''
src = [self._full_hdfs_path(x) for x in src]
return self._transform_du_output(self._getStdOutCmd([self._hadoop_cmd, 'fs', '-du'] + extra_args + src, True), self.hdfs_url) | [
"def",
"du",
"(",
"self",
",",
"src",
",",
"extra_args",
"=",
"[",
"]",
")",
":",
"src",
"=",
"[",
"self",
".",
"_full_hdfs_path",
"(",
"x",
")",
"for",
"x",
"in",
"src",
"]",
"return",
"self",
".",
"_transform_du_output",
"(",
"self",
".",
"_getSt... | Perform ``du`` on a path | [
"Perform",
"du",
"on",
"a",
"path"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L134-L137 | train | 199,009 |
spotify/snakebite | snakebite/minicluster.py | MiniCluster.count | def count(self, src):
'''Perform ``count`` on a path'''
src = [self._full_hdfs_path(x) for x in src]
return self._transform_count_output(self._getStdOutCmd([self._hadoop_cmd, 'fs', '-count'] + src, True), self.hdfs_url) | python | def count(self, src):
'''Perform ``count`` on a path'''
src = [self._full_hdfs_path(x) for x in src]
return self._transform_count_output(self._getStdOutCmd([self._hadoop_cmd, 'fs', '-count'] + src, True), self.hdfs_url) | [
"def",
"count",
"(",
"self",
",",
"src",
")",
":",
"src",
"=",
"[",
"self",
".",
"_full_hdfs_path",
"(",
"x",
")",
"for",
"x",
"in",
"src",
"]",
"return",
"self",
".",
"_transform_count_output",
"(",
"self",
".",
"_getStdOutCmd",
"(",
"[",
"self",
".... | Perform ``count`` on a path | [
"Perform",
"count",
"on",
"a",
"path"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/minicluster.py#L139-L142 | train | 199,010 |
spotify/snakebite | snakebite/service.py | SocketRpcController.handleError | def handleError(self, error_code, message):
'''Log and set the controller state.'''
self._fail = True
self.reason = error_code
self._error = message | python | def handleError(self, error_code, message):
'''Log and set the controller state.'''
self._fail = True
self.reason = error_code
self._error = message | [
"def",
"handleError",
"(",
"self",
",",
"error_code",
",",
"message",
")",
":",
"self",
".",
"_fail",
"=",
"True",
"self",
".",
"reason",
"=",
"error_code",
"self",
".",
"_error",
"=",
"message"
] | Log and set the controller state. | [
"Log",
"and",
"set",
"the",
"controller",
"state",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/service.py#L61-L65 | train | 199,011 |
spotify/snakebite | snakebite/client.py | Client.ls | def ls(self, paths, recurse=False, include_toplevel=False, include_children=True):
''' Issues 'ls' command and returns a list of maps that contain fileinfo
:param paths: Paths to list
:type paths: list
:param recurse: Recursive listing
:type recurse: boolean
:param include_toplevel: Include the given path in the listing. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the listing.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Directory listing
>>> list(client.ls(["/"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317325431L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/build'}, {'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317326510L, 'block_replication': 1, 'modification_time': 1367317326522L, 'length': 100L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/index.asciidoc'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
File listing
>>> list(client.ls(["/Makefile"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}]
Get directory information
>>> list(client.ls(["/source"], include_toplevel=True, include_children=False))
[{'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
for item in self._find_items(paths, self._handle_ls,
include_toplevel=include_toplevel,
include_children=include_children,
recurse=recurse):
if item:
yield item | python | def ls(self, paths, recurse=False, include_toplevel=False, include_children=True):
''' Issues 'ls' command and returns a list of maps that contain fileinfo
:param paths: Paths to list
:type paths: list
:param recurse: Recursive listing
:type recurse: boolean
:param include_toplevel: Include the given path in the listing. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the listing.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Directory listing
>>> list(client.ls(["/"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317325431L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/build'}, {'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317326510L, 'block_replication': 1, 'modification_time': 1367317326522L, 'length': 100L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/index.asciidoc'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
File listing
>>> list(client.ls(["/Makefile"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}]
Get directory information
>>> list(client.ls(["/source"], include_toplevel=True, include_children=False))
[{'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
for item in self._find_items(paths, self._handle_ls,
include_toplevel=include_toplevel,
include_children=include_children,
recurse=recurse):
if item:
yield item | [
"def",
"ls",
"(",
"self",
",",
"paths",
",",
"recurse",
"=",
"False",
",",
"include_toplevel",
"=",
"False",
",",
"include_children",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
... | Issues 'ls' command and returns a list of maps that contain fileinfo
:param paths: Paths to list
:type paths: list
:param recurse: Recursive listing
:type recurse: boolean
:param include_toplevel: Include the given path in the listing. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the listing.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Directory listing
>>> list(client.ls(["/"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317325431L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/build'}, {'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317326510L, 'block_replication': 1, 'modification_time': 1367317326522L, 'length': 100L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/index.asciidoc'}, {'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}]
File listing
>>> list(client.ls(["/Makefile"]))
[{'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'access_time': 1367317324982L, 'block_replication': 1, 'modification_time': 1367317325346L, 'length': 6783L, 'blocksize': 134217728L, 'owner': u'wouter', 'path': '/Makefile'}]
Get directory information
>>> list(client.ls(["/source"], include_toplevel=True, include_children=False))
[{'group': u'supergroup', 'permission': 493, 'file_type': 'd', 'access_time': 0L, 'block_replication': 0, 'modification_time': 1367317326628L, 'length': 0L, 'blocksize': 0L, 'owner': u'wouter', 'path': '/source'}] | [
"Issues",
"ls",
"command",
"and",
"returns",
"a",
"list",
"of",
"maps",
"that",
"contain",
"fileinfo"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L132-L170 | train | 199,012 |
spotify/snakebite | snakebite/client.py | Client._handle_ls | def _handle_ls(self, path, node):
''' Handle every node received for an ls request'''
entry = {}
entry["file_type"] = self.FILETYPES[node.fileType]
entry["permission"] = node.permission.perm
entry["path"] = path
for attribute in self.LISTING_ATTRIBUTES:
entry[attribute] = node.__getattribute__(attribute)
return entry | python | def _handle_ls(self, path, node):
''' Handle every node received for an ls request'''
entry = {}
entry["file_type"] = self.FILETYPES[node.fileType]
entry["permission"] = node.permission.perm
entry["path"] = path
for attribute in self.LISTING_ATTRIBUTES:
entry[attribute] = node.__getattribute__(attribute)
return entry | [
"def",
"_handle_ls",
"(",
"self",
",",
"path",
",",
"node",
")",
":",
"entry",
"=",
"{",
"}",
"entry",
"[",
"\"file_type\"",
"]",
"=",
"self",
".",
"FILETYPES",
"[",
"node",
".",
"fileType",
"]",
"entry",
"[",
"\"permission\"",
"]",
"=",
"node",
".",... | Handle every node received for an ls request | [
"Handle",
"every",
"node",
"received",
"for",
"an",
"ls",
"request"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L175-L186 | train | 199,013 |
spotify/snakebite | snakebite/client.py | Client.chmod | def chmod(self, paths, mode, recurse=False):
''' Change the mode for paths. This returns a list of maps containing the resut of the operation.
:param paths: List of paths to chmod
:type paths: list
:param mode: Octal mode (e.g. 0o755)
:type mode: int
:param recurse: Recursive chmod
:type recurse: boolean
:returns: a generator that yields dictionaries
.. note:: The top level directory is always included when `recurse=True`'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("chmod: no path given")
if not mode:
raise InvalidInputException("chmod: no mode given")
processor = lambda path, node, mode=mode: self._handle_chmod(path, node, mode)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item | python | def chmod(self, paths, mode, recurse=False):
''' Change the mode for paths. This returns a list of maps containing the resut of the operation.
:param paths: List of paths to chmod
:type paths: list
:param mode: Octal mode (e.g. 0o755)
:type mode: int
:param recurse: Recursive chmod
:type recurse: boolean
:returns: a generator that yields dictionaries
.. note:: The top level directory is always included when `recurse=True`'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("chmod: no path given")
if not mode:
raise InvalidInputException("chmod: no mode given")
processor = lambda path, node, mode=mode: self._handle_chmod(path, node, mode)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item | [
"def",
"chmod",
"(",
"self",
",",
"paths",
",",
"mode",
",",
"recurse",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"paths",
... | Change the mode for paths. This returns a list of maps containing the resut of the operation.
:param paths: List of paths to chmod
:type paths: list
:param mode: Octal mode (e.g. 0o755)
:type mode: int
:param recurse: Recursive chmod
:type recurse: boolean
:returns: a generator that yields dictionaries
.. note:: The top level directory is always included when `recurse=True` | [
"Change",
"the",
"mode",
"for",
"paths",
".",
"This",
"returns",
"a",
"list",
"of",
"maps",
"containing",
"the",
"resut",
"of",
"the",
"operation",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L188-L211 | train | 199,014 |
spotify/snakebite | snakebite/client.py | Client.count | def count(self, paths):
''' Count files in a path
:param paths: List of paths to count
:type paths: list
:returns: a generator that yields dictionaries
**Examples:**
>>> list(client.count(['/']))
[{'spaceConsumed': 260185L, 'quota': 2147483647L, 'spaceQuota': 18446744073709551615L, 'length': 260185L, 'directoryCount': 9L, 'path': '/', 'fileCount': 34L}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("count: no path given")
for item in self._find_items(paths, self._handle_count, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item | python | def count(self, paths):
''' Count files in a path
:param paths: List of paths to count
:type paths: list
:returns: a generator that yields dictionaries
**Examples:**
>>> list(client.count(['/']))
[{'spaceConsumed': 260185L, 'quota': 2147483647L, 'spaceQuota': 18446744073709551615L, 'length': 260185L, 'directoryCount': 9L, 'path': '/', 'fileCount': 34L}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("count: no path given")
for item in self._find_items(paths, self._handle_count, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item | [
"def",
"count",
"(",
"self",
",",
"paths",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"paths",
":",
"raise",
"InvalidInputException",
"(",
"... | Count files in a path
:param paths: List of paths to count
:type paths: list
:returns: a generator that yields dictionaries
**Examples:**
>>> list(client.count(['/']))
[{'spaceConsumed': 260185L, 'quota': 2147483647L, 'spaceQuota': 18446744073709551615L, 'length': 260185L, 'directoryCount': 9L, 'path': '/', 'fileCount': 34L}] | [
"Count",
"files",
"in",
"a",
"path"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L286-L307 | train | 199,015 |
spotify/snakebite | snakebite/client.py | Client.df | def df(self):
''' Get FS information
:returns: a dictionary
**Examples:**
>>> client.df()
{'used': 491520L, 'capacity': 120137519104L, 'under_replicated': 0L, 'missing_blocks': 0L, 'filesystem': 'hdfs://localhost:8020', 'remaining': 19669295104L, 'corrupt_blocks': 0L}
'''
processor = lambda path, node: self._handle_df(path, node)
return list(self._find_items(['/'], processor, include_toplevel=True, include_children=False, recurse=False))[0] | python | def df(self):
''' Get FS information
:returns: a dictionary
**Examples:**
>>> client.df()
{'used': 491520L, 'capacity': 120137519104L, 'under_replicated': 0L, 'missing_blocks': 0L, 'filesystem': 'hdfs://localhost:8020', 'remaining': 19669295104L, 'corrupt_blocks': 0L}
'''
processor = lambda path, node: self._handle_df(path, node)
return list(self._find_items(['/'], processor, include_toplevel=True, include_children=False, recurse=False))[0] | [
"def",
"df",
"(",
"self",
")",
":",
"processor",
"=",
"lambda",
"path",
",",
"node",
":",
"self",
".",
"_handle_df",
"(",
"path",
",",
"node",
")",
"return",
"list",
"(",
"self",
".",
"_find_items",
"(",
"[",
"'/'",
"]",
",",
"processor",
",",
"inc... | Get FS information
:returns: a dictionary
**Examples:**
>>> client.df()
{'used': 491520L, 'capacity': 120137519104L, 'under_replicated': 0L, 'missing_blocks': 0L, 'filesystem': 'hdfs://localhost:8020', 'remaining': 19669295104L, 'corrupt_blocks': 0L} | [
"Get",
"FS",
"information"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L320-L331 | train | 199,016 |
spotify/snakebite | snakebite/client.py | Client.du | def du(self, paths, include_toplevel=False, include_children=True):
'''Returns size information for paths
:param paths: Paths to du
:type paths: list
:param include_toplevel: Include the given path in the result. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the result.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Children:
>>> list(client.du(['/']))
[{'path': '/Makefile', 'length': 6783L}, {'path': '/build', 'length': 244778L}, {'path': '/index.asciidoc', 'length': 100L}, {'path': '/source', 'length': 8524L}]
Directory only:
>>> list(client.du(['/'], include_toplevel=True, include_children=False))
[{'path': '/', 'length': 260185L}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("du: no path given")
processor = lambda path, node: self._handle_du(path, node)
for item in self._find_items(paths, processor, include_toplevel=include_toplevel,
include_children=include_children, recurse=False):
if item:
yield item | python | def du(self, paths, include_toplevel=False, include_children=True):
'''Returns size information for paths
:param paths: Paths to du
:type paths: list
:param include_toplevel: Include the given path in the result. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the result.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Children:
>>> list(client.du(['/']))
[{'path': '/Makefile', 'length': 6783L}, {'path': '/build', 'length': 244778L}, {'path': '/index.asciidoc', 'length': 100L}, {'path': '/source', 'length': 8524L}]
Directory only:
>>> list(client.du(['/'], include_toplevel=True, include_children=False))
[{'path': '/', 'length': 260185L}]
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("du: no path given")
processor = lambda path, node: self._handle_du(path, node)
for item in self._find_items(paths, processor, include_toplevel=include_toplevel,
include_children=include_children, recurse=False):
if item:
yield item | [
"def",
"du",
"(",
"self",
",",
"paths",
",",
"include_toplevel",
"=",
"False",
",",
"include_children",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
... | Returns size information for paths
:param paths: Paths to du
:type paths: list
:param include_toplevel: Include the given path in the result. If the path is a file, include_toplevel is always True.
:type include_toplevel: boolean
:param include_children: Include child nodes in the result.
:type include_children: boolean
:returns: a generator that yields dictionaries
**Examples:**
Children:
>>> list(client.du(['/']))
[{'path': '/Makefile', 'length': 6783L}, {'path': '/build', 'length': 244778L}, {'path': '/index.asciidoc', 'length': 100L}, {'path': '/source', 'length': 8524L}]
Directory only:
>>> list(client.du(['/'], include_toplevel=True, include_children=False))
[{'path': '/', 'length': 260185L}] | [
"Returns",
"size",
"information",
"for",
"paths"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L342-L375 | train | 199,017 |
spotify/snakebite | snakebite/client.py | Client.rmdir | def rmdir(self, paths):
''' Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty.
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("rmdir: no path given")
processor = lambda path, node: self._handle_rmdir(path, node)
for item in self._find_items(paths, processor, include_toplevel=True):
if item:
yield item | python | def rmdir(self, paths):
''' Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty.
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("rmdir: no path given")
processor = lambda path, node: self._handle_rmdir(path, node)
for item in self._find_items(paths, processor, include_toplevel=True):
if item:
yield item | [
"def",
"rmdir",
"(",
"self",
",",
"paths",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"paths",
":",
"raise",
"InvalidInputException",
"(",
"... | Delete a directory
:param paths: Paths to delete
:type paths: list
:returns: a generator that yields dictionaries
.. note: directories have to be empty. | [
"Delete",
"a",
"directory"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L566-L583 | train | 199,018 |
spotify/snakebite | snakebite/client.py | Client.touchz | def touchz(self, paths, replication=None, blocksize=None):
''' Create a zero length file or updates the timestamp on a zero length file
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param blocksize: Block size (in bytes) of the newly created file
:type blocksize: int
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("touchz: no path given")
# Let's get the blocksize and replication from the server defaults
# provided by the namenode if they are not specified
if not replication or not blocksize:
defaults = self.serverdefaults()
if not replication:
replication = defaults['replication']
if not blocksize:
blocksize = defaults['blockSize']
processor = lambda path, node, replication=replication, blocksize=blocksize: self._handle_touchz(path, node, replication, blocksize)
for item in self._find_items(paths, processor, include_toplevel=True, check_nonexistence=True, include_children=False):
if item:
yield item | python | def touchz(self, paths, replication=None, blocksize=None):
''' Create a zero length file or updates the timestamp on a zero length file
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param blocksize: Block size (in bytes) of the newly created file
:type blocksize: int
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("touchz: no path given")
# Let's get the blocksize and replication from the server defaults
# provided by the namenode if they are not specified
if not replication or not blocksize:
defaults = self.serverdefaults()
if not replication:
replication = defaults['replication']
if not blocksize:
blocksize = defaults['blockSize']
processor = lambda path, node, replication=replication, blocksize=blocksize: self._handle_touchz(path, node, replication, blocksize)
for item in self._find_items(paths, processor, include_toplevel=True, check_nonexistence=True, include_children=False):
if item:
yield item | [
"def",
"touchz",
"(",
"self",
",",
"paths",
",",
"replication",
"=",
"None",
",",
"blocksize",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
... | Create a zero length file or updates the timestamp on a zero length file
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param blocksize: Block size (in bytes) of the newly created file
:type blocksize: int
:returns: a generator that yields dictionaries | [
"Create",
"a",
"zero",
"length",
"file",
"or",
"updates",
"the",
"timestamp",
"on",
"a",
"zero",
"length",
"file"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L596-L626 | train | 199,019 |
spotify/snakebite | snakebite/client.py | Client.setrep | def setrep(self, paths, replication, recurse=False):
''' Set the replication factor for paths
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param recurse: Apply replication factor recursive
:type recurse: boolean
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("setrep: no path given")
if not replication:
raise InvalidInputException("setrep: no replication given")
processor = lambda path, node, replication=replication: self._handle_setrep(path, node, replication)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item | python | def setrep(self, paths, replication, recurse=False):
''' Set the replication factor for paths
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param recurse: Apply replication factor recursive
:type recurse: boolean
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("setrep: no path given")
if not replication:
raise InvalidInputException("setrep: no replication given")
processor = lambda path, node, replication=replication: self._handle_setrep(path, node, replication)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=recurse):
if item:
yield item | [
"def",
"setrep",
"(",
"self",
",",
"paths",
",",
"replication",
",",
"recurse",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"... | Set the replication factor for paths
:param paths: Paths
:type paths: list
:param replication: Replication factor
:type recurse: int
:param recurse: Apply replication factor recursive
:type recurse: boolean
:returns: a generator that yields dictionaries | [
"Set",
"the",
"replication",
"factor",
"for",
"paths"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L646-L668 | train | 199,020 |
spotify/snakebite | snakebite/client.py | Client.cat | def cat(self, paths, check_crc=False):
''' Fetch all files that match the source file pattern
and display their content on stdout.
:param paths: Paths to display
:type paths: list of strings
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("cat: no path given")
processor = lambda path, node, check_crc=check_crc: self._handle_cat(path, node, check_crc)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item | python | def cat(self, paths, check_crc=False):
''' Fetch all files that match the source file pattern
and display their content on stdout.
:param paths: Paths to display
:type paths: list of strings
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("cat: no path given")
processor = lambda path, node, check_crc=check_crc: self._handle_cat(path, node, check_crc)
for item in self._find_items(paths, processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item | [
"def",
"cat",
"(",
"self",
",",
"paths",
",",
"check_crc",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"paths",
":",
"raise",... | Fetch all files that match the source file pattern
and display their content on stdout.
:param paths: Paths to display
:type paths: list of strings
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings | [
"Fetch",
"all",
"files",
"that",
"match",
"the",
"source",
"file",
"pattern",
"and",
"display",
"their",
"content",
"on",
"stdout",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L678-L697 | train | 199,021 |
spotify/snakebite | snakebite/client.py | Client.copyToLocal | def copyToLocal(self, paths, dst, check_crc=False):
''' Copy files that match the file source pattern
to the local name. Source is kept. When copying multiple,
files, the destination must be a directory.
:param paths: Paths to copy
:type paths: list of strings
:param dst: Destination path
:type dst: string
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("copyToLocal: no path given")
if not dst:
raise InvalidInputException("copyToLocal: no destination given")
dst = self._normalize_path(dst)
processor = lambda path, node, dst=dst, check_crc=check_crc: self._handle_copyToLocal(path, node, dst, check_crc)
for path in paths:
self.base_source = None
for item in self._find_items([path], processor, include_toplevel=True, recurse=True, include_children=True):
if item:
yield item | python | def copyToLocal(self, paths, dst, check_crc=False):
''' Copy files that match the file source pattern
to the local name. Source is kept. When copying multiple,
files, the destination must be a directory.
:param paths: Paths to copy
:type paths: list of strings
:param dst: Destination path
:type dst: string
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("copyToLocal: no path given")
if not dst:
raise InvalidInputException("copyToLocal: no destination given")
dst = self._normalize_path(dst)
processor = lambda path, node, dst=dst, check_crc=check_crc: self._handle_copyToLocal(path, node, dst, check_crc)
for path in paths:
self.base_source = None
for item in self._find_items([path], processor, include_toplevel=True, recurse=True, include_children=True):
if item:
yield item | [
"def",
"copyToLocal",
"(",
"self",
",",
"paths",
",",
"dst",
",",
"check_crc",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"p... | Copy files that match the file source pattern
to the local name. Source is kept. When copying multiple,
files, the destination must be a directory.
:param paths: Paths to copy
:type paths: list of strings
:param dst: Destination path
:type dst: string
:param check_crc: Check for checksum errors
:type check_crc: boolean
:returns: a generator that yields strings | [
"Copy",
"files",
"that",
"match",
"the",
"file",
"source",
"pattern",
"to",
"the",
"local",
"name",
".",
"Source",
"is",
"kept",
".",
"When",
"copying",
"multiple",
"files",
"the",
"destination",
"must",
"be",
"a",
"directory",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L707-L734 | train | 199,022 |
spotify/snakebite | snakebite/client.py | Client.getmerge | def getmerge(self, path, dst, newline=False, check_crc=False):
''' Get all the files in the directories that
match the source file pattern and merge and sort them to only
one file on local fs.
:param paths: Directory containing files that will be merged
:type paths: string
:param dst: Path of file that will be written
:type dst: string
:param nl: Add a newline character at the end of each file.
:type nl: boolean
:returns: string content of the merged file at dst
'''
if not path:
raise InvalidInputException("getmerge: no path given")
if not dst:
raise InvalidInputException("getmerge: no destination given")
temporary_target = "%s._COPYING_" % dst
f = open(temporary_target, 'w')
processor = lambda path, node, dst=dst, check_crc=check_crc: self._handle_getmerge(path, node, dst, check_crc)
try:
for item in self._find_items([path], processor, include_toplevel=True, recurse=False, include_children=True):
for load in item:
if load['result']:
f.write(load['response'])
elif not load['error'] is '':
if os.path.isfile(temporary_target):
os.remove(temporary_target)
raise FatalException(load['error'])
if newline and load['response']:
f.write("\n")
yield {"path": dst, "response": '', "result": True, "error": load['error'], "source_path": path}
finally:
if os.path.isfile(temporary_target):
f.close()
os.rename(temporary_target, dst) | python | def getmerge(self, path, dst, newline=False, check_crc=False):
''' Get all the files in the directories that
match the source file pattern and merge and sort them to only
one file on local fs.
:param paths: Directory containing files that will be merged
:type paths: string
:param dst: Path of file that will be written
:type dst: string
:param nl: Add a newline character at the end of each file.
:type nl: boolean
:returns: string content of the merged file at dst
'''
if not path:
raise InvalidInputException("getmerge: no path given")
if not dst:
raise InvalidInputException("getmerge: no destination given")
temporary_target = "%s._COPYING_" % dst
f = open(temporary_target, 'w')
processor = lambda path, node, dst=dst, check_crc=check_crc: self._handle_getmerge(path, node, dst, check_crc)
try:
for item in self._find_items([path], processor, include_toplevel=True, recurse=False, include_children=True):
for load in item:
if load['result']:
f.write(load['response'])
elif not load['error'] is '':
if os.path.isfile(temporary_target):
os.remove(temporary_target)
raise FatalException(load['error'])
if newline and load['response']:
f.write("\n")
yield {"path": dst, "response": '', "result": True, "error": load['error'], "source_path": path}
finally:
if os.path.isfile(temporary_target):
f.close()
os.rename(temporary_target, dst) | [
"def",
"getmerge",
"(",
"self",
",",
"path",
",",
"dst",
",",
"newline",
"=",
"False",
",",
"check_crc",
"=",
"False",
")",
":",
"if",
"not",
"path",
":",
"raise",
"InvalidInputException",
"(",
"\"getmerge: no path given\"",
")",
"if",
"not",
"dst",
":",
... | Get all the files in the directories that
match the source file pattern and merge and sort them to only
one file on local fs.
:param paths: Directory containing files that will be merged
:type paths: string
:param dst: Path of file that will be written
:type dst: string
:param nl: Add a newline character at the end of each file.
:type nl: boolean
:returns: string content of the merged file at dst | [
"Get",
"all",
"the",
"files",
"in",
"the",
"directories",
"that",
"match",
"the",
"source",
"file",
"pattern",
"and",
"merge",
"and",
"sort",
"them",
"to",
"only",
"one",
"file",
"on",
"local",
"fs",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L783-L821 | train | 199,023 |
spotify/snakebite | snakebite/client.py | Client.stat | def stat(self, paths):
''' Stat a fileCount
:param paths: Path
:type paths: string
:returns: a dictionary
**Example:**
>>> client.stat(['/index.asciidoc'])
{'blocksize': 134217728L, 'owner': u'wouter', 'length': 100L, 'access_time': 1367317326510L, 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'path': '/index.asciidoc', 'modification_time': 1367317326522L, 'block_replication': 1}
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("stat: no path given")
processor = lambda path, node: self._handle_stat(path, node)
return list(self._find_items(paths, processor, include_toplevel=True))[0] | python | def stat(self, paths):
''' Stat a fileCount
:param paths: Path
:type paths: string
:returns: a dictionary
**Example:**
>>> client.stat(['/index.asciidoc'])
{'blocksize': 134217728L, 'owner': u'wouter', 'length': 100L, 'access_time': 1367317326510L, 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'path': '/index.asciidoc', 'modification_time': 1367317326522L, 'block_replication': 1}
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("stat: no path given")
processor = lambda path, node: self._handle_stat(path, node)
return list(self._find_items(paths, processor, include_toplevel=True))[0] | [
"def",
"stat",
"(",
"self",
",",
"paths",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"if",
"not",
"paths",
":",
"raise",
"InvalidInputException",
"(",
"\... | Stat a fileCount
:param paths: Path
:type paths: string
:returns: a dictionary
**Example:**
>>> client.stat(['/index.asciidoc'])
{'blocksize': 134217728L, 'owner': u'wouter', 'length': 100L, 'access_time': 1367317326510L, 'group': u'supergroup', 'permission': 420, 'file_type': 'f', 'path': '/index.asciidoc', 'modification_time': 1367317326522L, 'block_replication': 1} | [
"Stat",
"a",
"fileCount"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L849-L867 | train | 199,024 |
spotify/snakebite | snakebite/client.py | Client.tail | def tail(self, path, tail_length=1024, append=False):
# Note: append is currently not implemented.
''' Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end of the file - default 1KB, up to block size.
:type tail_length: int
:param append: Currently not implemented
:type append: bool
:returns: a generator that yields strings
'''
#TODO: Make tail support multiple files at a time, like most other methods do
if not path:
raise InvalidInputException("tail: no path given")
block_size = self.serverdefaults()['blockSize']
if tail_length > block_size:
raise InvalidInputException("tail: currently supports length up to the block size (%d)" % (block_size,))
if tail_length <= 0:
raise InvalidInputException("tail: tail_length cannot be less than or equal to zero")
processor = lambda path, node: self._handle_tail(path, node, tail_length, append)
for item in self._find_items([path], processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item | python | def tail(self, path, tail_length=1024, append=False):
# Note: append is currently not implemented.
''' Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end of the file - default 1KB, up to block size.
:type tail_length: int
:param append: Currently not implemented
:type append: bool
:returns: a generator that yields strings
'''
#TODO: Make tail support multiple files at a time, like most other methods do
if not path:
raise InvalidInputException("tail: no path given")
block_size = self.serverdefaults()['blockSize']
if tail_length > block_size:
raise InvalidInputException("tail: currently supports length up to the block size (%d)" % (block_size,))
if tail_length <= 0:
raise InvalidInputException("tail: tail_length cannot be less than or equal to zero")
processor = lambda path, node: self._handle_tail(path, node, tail_length, append)
for item in self._find_items([path], processor, include_toplevel=True,
include_children=False, recurse=False):
if item:
yield item | [
"def",
"tail",
"(",
"self",
",",
"path",
",",
"tail_length",
"=",
"1024",
",",
"append",
"=",
"False",
")",
":",
"# Note: append is currently not implemented.",
"#TODO: Make tail support multiple files at a time, like most other methods do",
"if",
"not",
"path",
":",
"rai... | Show the end of the file - default 1KB, supports up to the Hadoop block size.
:param path: Path to read
:type path: string
:param tail_length: The length to read from the end of the file - default 1KB, up to block size.
:type tail_length: int
:param append: Currently not implemented
:type append: bool
:returns: a generator that yields strings | [
"Show",
"the",
"end",
"of",
"the",
"file",
"-",
"default",
"1KB",
"supports",
"up",
"to",
"the",
"Hadoop",
"block",
"size",
"."
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L881-L909 | train | 199,025 |
spotify/snakebite | snakebite/client.py | Client.mkdir | def mkdir(self, paths, create_parent=False, mode=0o755):
''' Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be created with
:type mode: int
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("mkdirs: no path given")
for path in paths:
if not path.startswith("/"):
path = self._join_user_path(path)
fileinfo = self._get_file_info(path)
if not fileinfo:
try:
request = client_proto.MkdirsRequestProto()
request.src = path
request.masked.perm = mode
request.createParent = create_parent
response = self.service.mkdirs(request)
yield {"path": path, "result": response.result}
except RequestError as e:
yield {"path": path, "result": False, "error": str(e)}
else:
yield {"path": path, "result": False, "error": "mkdir: `%s': File exists" % path} | python | def mkdir(self, paths, create_parent=False, mode=0o755):
''' Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be created with
:type mode: int
:returns: a generator that yields dictionaries
'''
if not isinstance(paths, list):
raise InvalidInputException("Paths should be a list")
if not paths:
raise InvalidInputException("mkdirs: no path given")
for path in paths:
if not path.startswith("/"):
path = self._join_user_path(path)
fileinfo = self._get_file_info(path)
if not fileinfo:
try:
request = client_proto.MkdirsRequestProto()
request.src = path
request.masked.perm = mode
request.createParent = create_parent
response = self.service.mkdirs(request)
yield {"path": path, "result": response.result}
except RequestError as e:
yield {"path": path, "result": False, "error": str(e)}
else:
yield {"path": path, "result": False, "error": "mkdir: `%s': File exists" % path} | [
"def",
"mkdir",
"(",
"self",
",",
"paths",
",",
"create_parent",
"=",
"False",
",",
"mode",
"=",
"0o755",
")",
":",
"if",
"not",
"isinstance",
"(",
"paths",
",",
"list",
")",
":",
"raise",
"InvalidInputException",
"(",
"\"Paths should be a list\"",
")",
"i... | Create a directoryCount
:param paths: Paths to create
:type paths: list of strings
:param create_parent: Also create the parent directories
:type create_parent: boolean
:param mode: Mode the directory should be created with
:type mode: int
:returns: a generator that yields dictionaries | [
"Create",
"a",
"directoryCount"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L991-L1023 | train | 199,026 |
spotify/snakebite | snakebite/client.py | Client.serverdefaults | def serverdefaults(self, force_reload=False):
'''Get server defaults, caching the results. If there are no results saved, or the force_reload flag is True,
it will query the HDFS server for its default parameter values. Otherwise, it will simply return the results
it has already queried.
Note: This function returns a copy of the results loaded from the server, so you can manipulate or change
them as you'd like. If for any reason you need to change the results the client saves, you must access
the property client._server_defaults directly.
:param force_reload: Should the server defaults be reloaded even if they already exist?
:type force_reload: bool
:returns: dictionary with the following keys: blockSize, bytesPerChecksum, writePacketSize, replication, fileBufferSize, encryptDataTransfer, trashInterval, checksumType
**Example:**
>>> client.serverdefaults()
[{'writePacketSize': 65536, 'fileBufferSize': 4096, 'replication': 1, 'bytesPerChecksum': 512, 'trashInterval': 0L, 'blockSize': 134217728L, 'encryptDataTransfer': False, 'checksumType': 2}]
'''
if not self._server_defaults or force_reload:
request = client_proto.GetServerDefaultsRequestProto()
response = self.service.getServerDefaults(request).serverDefaults
self._server_defaults = {'blockSize': response.blockSize, 'bytesPerChecksum': response.bytesPerChecksum,
'writePacketSize': response.writePacketSize, 'replication': response.replication,
'fileBufferSize': response.fileBufferSize, 'encryptDataTransfer': response.encryptDataTransfer,
'trashInterval': response.trashInterval, 'checksumType': response.checksumType}
# return a copy, so if the user changes any values, they won't be saved in the client
return self._server_defaults.copy() | python | def serverdefaults(self, force_reload=False):
'''Get server defaults, caching the results. If there are no results saved, or the force_reload flag is True,
it will query the HDFS server for its default parameter values. Otherwise, it will simply return the results
it has already queried.
Note: This function returns a copy of the results loaded from the server, so you can manipulate or change
them as you'd like. If for any reason you need to change the results the client saves, you must access
the property client._server_defaults directly.
:param force_reload: Should the server defaults be reloaded even if they already exist?
:type force_reload: bool
:returns: dictionary with the following keys: blockSize, bytesPerChecksum, writePacketSize, replication, fileBufferSize, encryptDataTransfer, trashInterval, checksumType
**Example:**
>>> client.serverdefaults()
[{'writePacketSize': 65536, 'fileBufferSize': 4096, 'replication': 1, 'bytesPerChecksum': 512, 'trashInterval': 0L, 'blockSize': 134217728L, 'encryptDataTransfer': False, 'checksumType': 2}]
'''
if not self._server_defaults or force_reload:
request = client_proto.GetServerDefaultsRequestProto()
response = self.service.getServerDefaults(request).serverDefaults
self._server_defaults = {'blockSize': response.blockSize, 'bytesPerChecksum': response.bytesPerChecksum,
'writePacketSize': response.writePacketSize, 'replication': response.replication,
'fileBufferSize': response.fileBufferSize, 'encryptDataTransfer': response.encryptDataTransfer,
'trashInterval': response.trashInterval, 'checksumType': response.checksumType}
# return a copy, so if the user changes any values, they won't be saved in the client
return self._server_defaults.copy() | [
"def",
"serverdefaults",
"(",
"self",
",",
"force_reload",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_server_defaults",
"or",
"force_reload",
":",
"request",
"=",
"client_proto",
".",
"GetServerDefaultsRequestProto",
"(",
")",
"response",
"=",
"self",
... | Get server defaults, caching the results. If there are no results saved, or the force_reload flag is True,
it will query the HDFS server for its default parameter values. Otherwise, it will simply return the results
it has already queried.
Note: This function returns a copy of the results loaded from the server, so you can manipulate or change
them as you'd like. If for any reason you need to change the results the client saves, you must access
the property client._server_defaults directly.
:param force_reload: Should the server defaults be reloaded even if they already exist?
:type force_reload: bool
:returns: dictionary with the following keys: blockSize, bytesPerChecksum, writePacketSize, replication, fileBufferSize, encryptDataTransfer, trashInterval, checksumType
**Example:**
>>> client.serverdefaults()
[{'writePacketSize': 65536, 'fileBufferSize': 4096, 'replication': 1, 'bytesPerChecksum': 512, 'trashInterval': 0L, 'blockSize': 134217728L, 'encryptDataTransfer': False, 'checksumType': 2}] | [
"Get",
"server",
"defaults",
"caching",
"the",
"results",
".",
"If",
"there",
"are",
"no",
"results",
"saved",
"or",
"the",
"force_reload",
"flag",
"is",
"True",
"it",
"will",
"query",
"the",
"HDFS",
"server",
"for",
"its",
"default",
"parameter",
"values",
... | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L1025-L1054 | train | 199,027 |
spotify/snakebite | snakebite/client.py | Client._glob_find | def _glob_find(self, path, processor, include_toplevel):
'''Handle globs in paths.
This is done by listing the directory before a glob and checking which
node matches the initial glob. If there are more globs in the path,
we don't add the found children to the result, but traverse into paths
that did have a match.
'''
# Split path elements and check where the first occurence of magic is
path_elements = path.split("/")
for i, element in enumerate(path_elements):
if glob.has_magic(element):
first_magic = i
break
# Create path that we check first to get a listing we match all children
# against. If the 2nd path element is a glob, we need to check "/", and
# we hardcode that, since "/".join(['']) doesn't return "/"
if first_magic == 1:
check_path = "/"
else:
check_path = "/".join(path_elements[:first_magic])
# Path that we need to match against
match_path = "/".join(path_elements[:first_magic + 1])
# Rest of the unmatched path. In case the rest is only one element long
# we prepend it with "/", since "/".join(['x']) doesn't return "/x"
rest_elements = path_elements[first_magic + 1:]
if len(rest_elements) == 1:
rest = rest_elements[0]
else:
rest = "/".join(rest_elements)
# Check if the path exists and that it's a directory (which it should..)
fileinfo = self._get_file_info(check_path)
if fileinfo and self._is_dir(fileinfo.fs):
# List all child nodes and match them agains the glob
for node in self._get_dir_listing(check_path):
full_path = self._get_full_path(check_path, node)
if fnmatch.fnmatch(full_path, match_path):
# If we have a match, but need to go deeper, we recurse
if rest and glob.has_magic(rest):
traverse_path = "/".join([full_path, rest])
for item in self._glob_find(traverse_path, processor, include_toplevel):
yield item
elif rest:
# we have more rest, but it's not magic, which is either a file or a directory
final_path = posixpath.join(full_path, rest)
fi = self._get_file_info(final_path)
if fi and self._is_dir(fi.fs):
for n in self._get_dir_listing(final_path):
full_child_path = self._get_full_path(final_path, n)
yield processor(full_child_path, n)
elif fi:
yield processor(final_path, fi.fs)
else:
# If the matching node is a directory, we list the directory
# This is what the hadoop client does at least.
if self._is_dir(node):
if include_toplevel:
yield processor(full_path, node)
fp = self._get_full_path(check_path, node)
dir_list = self._get_dir_listing(fp)
if dir_list: # It might happen that the directory above has been removed
for n in dir_list:
full_child_path = self._get_full_path(fp, n)
yield processor(full_child_path, n)
else:
yield processor(full_path, node) | python | def _glob_find(self, path, processor, include_toplevel):
'''Handle globs in paths.
This is done by listing the directory before a glob and checking which
node matches the initial glob. If there are more globs in the path,
we don't add the found children to the result, but traverse into paths
that did have a match.
'''
# Split path elements and check where the first occurence of magic is
path_elements = path.split("/")
for i, element in enumerate(path_elements):
if glob.has_magic(element):
first_magic = i
break
# Create path that we check first to get a listing we match all children
# against. If the 2nd path element is a glob, we need to check "/", and
# we hardcode that, since "/".join(['']) doesn't return "/"
if first_magic == 1:
check_path = "/"
else:
check_path = "/".join(path_elements[:first_magic])
# Path that we need to match against
match_path = "/".join(path_elements[:first_magic + 1])
# Rest of the unmatched path. In case the rest is only one element long
# we prepend it with "/", since "/".join(['x']) doesn't return "/x"
rest_elements = path_elements[first_magic + 1:]
if len(rest_elements) == 1:
rest = rest_elements[0]
else:
rest = "/".join(rest_elements)
# Check if the path exists and that it's a directory (which it should..)
fileinfo = self._get_file_info(check_path)
if fileinfo and self._is_dir(fileinfo.fs):
# List all child nodes and match them agains the glob
for node in self._get_dir_listing(check_path):
full_path = self._get_full_path(check_path, node)
if fnmatch.fnmatch(full_path, match_path):
# If we have a match, but need to go deeper, we recurse
if rest and glob.has_magic(rest):
traverse_path = "/".join([full_path, rest])
for item in self._glob_find(traverse_path, processor, include_toplevel):
yield item
elif rest:
# we have more rest, but it's not magic, which is either a file or a directory
final_path = posixpath.join(full_path, rest)
fi = self._get_file_info(final_path)
if fi and self._is_dir(fi.fs):
for n in self._get_dir_listing(final_path):
full_child_path = self._get_full_path(final_path, n)
yield processor(full_child_path, n)
elif fi:
yield processor(final_path, fi.fs)
else:
# If the matching node is a directory, we list the directory
# This is what the hadoop client does at least.
if self._is_dir(node):
if include_toplevel:
yield processor(full_path, node)
fp = self._get_full_path(check_path, node)
dir_list = self._get_dir_listing(fp)
if dir_list: # It might happen that the directory above has been removed
for n in dir_list:
full_child_path = self._get_full_path(fp, n)
yield processor(full_child_path, n)
else:
yield processor(full_path, node) | [
"def",
"_glob_find",
"(",
"self",
",",
"path",
",",
"processor",
",",
"include_toplevel",
")",
":",
"# Split path elements and check where the first occurence of magic is",
"path_elements",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"for",
"i",
",",
"element",
"i... | Handle globs in paths.
This is done by listing the directory before a glob and checking which
node matches the initial glob. If there are more globs in the path,
we don't add the found children to the result, but traverse into paths
that did have a match. | [
"Handle",
"globs",
"in",
"paths",
".",
"This",
"is",
"done",
"by",
"listing",
"the",
"directory",
"before",
"a",
"glob",
"and",
"checking",
"which",
"node",
"matches",
"the",
"initial",
"glob",
".",
"If",
"there",
"are",
"more",
"globs",
"in",
"the",
"pa... | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L1263-L1331 | train | 199,028 |
spotify/snakebite | snakebite/client.py | HAClient._ha_return_method | def _ha_return_method(func):
''' Method decorator for 'return type' methods '''
def wrapped(self, *args, **kw):
self._reset_retries()
while(True): # switch between all namenodes
try:
return func(self, *args, **kw)
except RequestError as e:
self.__handle_request_error(e)
except socket.error as e:
self.__handle_socket_error(e)
return wrapped | python | def _ha_return_method(func):
''' Method decorator for 'return type' methods '''
def wrapped(self, *args, **kw):
self._reset_retries()
while(True): # switch between all namenodes
try:
return func(self, *args, **kw)
except RequestError as e:
self.__handle_request_error(e)
except socket.error as e:
self.__handle_socket_error(e)
return wrapped | [
"def",
"_ha_return_method",
"(",
"func",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_reset_retries",
"(",
")",
"while",
"(",
"True",
")",
":",
"# switch between all namenodes",
"try",
":",
"r... | Method decorator for 'return type' methods | [
"Method",
"decorator",
"for",
"return",
"type",
"methods"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L1518-L1529 | train | 199,029 |
spotify/snakebite | snakebite/client.py | HAClient._ha_gen_method | def _ha_gen_method(func):
''' Method decorator for 'generator type' methods '''
def wrapped(self, *args, **kw):
self._reset_retries()
while(True): # switch between all namenodes
try:
results = func(self, *args, **kw)
while(True): # yield all results
yield results.next()
except RequestError as e:
self.__handle_request_error(e)
except socket.error as e:
self.__handle_socket_error(e)
return wrapped | python | def _ha_gen_method(func):
''' Method decorator for 'generator type' methods '''
def wrapped(self, *args, **kw):
self._reset_retries()
while(True): # switch between all namenodes
try:
results = func(self, *args, **kw)
while(True): # yield all results
yield results.next()
except RequestError as e:
self.__handle_request_error(e)
except socket.error as e:
self.__handle_socket_error(e)
return wrapped | [
"def",
"_ha_gen_method",
"(",
"func",
")",
":",
"def",
"wrapped",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_reset_retries",
"(",
")",
"while",
"(",
"True",
")",
":",
"# switch between all namenodes",
"try",
":",
"resu... | Method decorator for 'generator type' methods | [
"Method",
"decorator",
"for",
"generator",
"type",
"methods"
] | 6a456e6100b0c1be66cc1f7f9d7f50494f369da3 | https://github.com/spotify/snakebite/blob/6a456e6100b0c1be66cc1f7f9d7f50494f369da3/snakebite/client.py#L1532-L1545 | train | 199,030 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion._validate_number_sequence | def _validate_number_sequence(self, seq, n):
"""Validate a sequence to be of a certain length and ensure it's a numpy array of floats.
Raises:
ValueError: Invalid length or non-numeric value
"""
if seq is None:
return np.zeros(n)
if len(seq) is n:
try:
l = [float(e) for e in seq]
except ValueError:
raise ValueError("One or more elements in sequence <" + repr(seq) + "> cannot be interpreted as a real number")
else:
return np.asarray(l)
elif len(seq) is 0:
return np.zeros(n)
else:
raise ValueError("Unexpected number of elements in sequence. Got: " + str(len(seq)) + ", Expected: " + str(n) + ".") | python | def _validate_number_sequence(self, seq, n):
"""Validate a sequence to be of a certain length and ensure it's a numpy array of floats.
Raises:
ValueError: Invalid length or non-numeric value
"""
if seq is None:
return np.zeros(n)
if len(seq) is n:
try:
l = [float(e) for e in seq]
except ValueError:
raise ValueError("One or more elements in sequence <" + repr(seq) + "> cannot be interpreted as a real number")
else:
return np.asarray(l)
elif len(seq) is 0:
return np.zeros(n)
else:
raise ValueError("Unexpected number of elements in sequence. Got: " + str(len(seq)) + ", Expected: " + str(n) + ".") | [
"def",
"_validate_number_sequence",
"(",
"self",
",",
"seq",
",",
"n",
")",
":",
"if",
"seq",
"is",
"None",
":",
"return",
"np",
".",
"zeros",
"(",
"n",
")",
"if",
"len",
"(",
"seq",
")",
"is",
"n",
":",
"try",
":",
"l",
"=",
"[",
"float",
"(",... | Validate a sequence to be of a certain length and ensure it's a numpy array of floats.
Raises:
ValueError: Invalid length or non-numeric value | [
"Validate",
"a",
"sequence",
"to",
"be",
"of",
"a",
"certain",
"length",
"and",
"ensure",
"it",
"s",
"a",
"numpy",
"array",
"of",
"floats",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L137-L155 | train | 199,031 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion._from_axis_angle | def _from_axis_angle(cls, axis, angle):
"""Initialise from axis and angle representation
Create a Quaternion by specifying the 3-vector rotation axis and rotation
angle (in radians) from which the quaternion's rotation should be created.
Params:
axis: a valid numpy 3-vector
angle: a real valued angle in radians
"""
mag_sq = np.dot(axis, axis)
if mag_sq == 0.0:
raise ZeroDivisionError("Provided rotation axis has no length")
# Ensure axis is in unit vector form
if (abs(1.0 - mag_sq) > 1e-12):
axis = axis / sqrt(mag_sq)
theta = angle / 2.0
r = cos(theta)
i = axis * sin(theta)
return cls(r, i[0], i[1], i[2]) | python | def _from_axis_angle(cls, axis, angle):
"""Initialise from axis and angle representation
Create a Quaternion by specifying the 3-vector rotation axis and rotation
angle (in radians) from which the quaternion's rotation should be created.
Params:
axis: a valid numpy 3-vector
angle: a real valued angle in radians
"""
mag_sq = np.dot(axis, axis)
if mag_sq == 0.0:
raise ZeroDivisionError("Provided rotation axis has no length")
# Ensure axis is in unit vector form
if (abs(1.0 - mag_sq) > 1e-12):
axis = axis / sqrt(mag_sq)
theta = angle / 2.0
r = cos(theta)
i = axis * sin(theta)
return cls(r, i[0], i[1], i[2]) | [
"def",
"_from_axis_angle",
"(",
"cls",
",",
"axis",
",",
"angle",
")",
":",
"mag_sq",
"=",
"np",
".",
"dot",
"(",
"axis",
",",
"axis",
")",
"if",
"mag_sq",
"==",
"0.0",
":",
"raise",
"ZeroDivisionError",
"(",
"\"Provided rotation axis has no length\"",
")",
... | Initialise from axis and angle representation
Create a Quaternion by specifying the 3-vector rotation axis and rotation
angle (in radians) from which the quaternion's rotation should be created.
Params:
axis: a valid numpy 3-vector
angle: a real valued angle in radians | [
"Initialise",
"from",
"axis",
"and",
"angle",
"representation"
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L237-L257 | train | 199,032 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.random | def random(cls):
"""Generate a random unit quaternion.
Uniformly distributed across the rotation space
As per: http://planning.cs.uiuc.edu/node198.html
"""
r1, r2, r3 = np.random.random(3)
q1 = sqrt(1.0 - r1) * (sin(2 * pi * r2))
q2 = sqrt(1.0 - r1) * (cos(2 * pi * r2))
q3 = sqrt(r1) * (sin(2 * pi * r3))
q4 = sqrt(r1) * (cos(2 * pi * r3))
return cls(q1, q2, q3, q4) | python | def random(cls):
"""Generate a random unit quaternion.
Uniformly distributed across the rotation space
As per: http://planning.cs.uiuc.edu/node198.html
"""
r1, r2, r3 = np.random.random(3)
q1 = sqrt(1.0 - r1) * (sin(2 * pi * r2))
q2 = sqrt(1.0 - r1) * (cos(2 * pi * r2))
q3 = sqrt(r1) * (sin(2 * pi * r3))
q4 = sqrt(r1) * (cos(2 * pi * r3))
return cls(q1, q2, q3, q4) | [
"def",
"random",
"(",
"cls",
")",
":",
"r1",
",",
"r2",
",",
"r3",
"=",
"np",
".",
"random",
".",
"random",
"(",
"3",
")",
"q1",
"=",
"sqrt",
"(",
"1.0",
"-",
"r1",
")",
"*",
"(",
"sin",
"(",
"2",
"*",
"pi",
"*",
"r2",
")",
")",
"q2",
"... | Generate a random unit quaternion.
Uniformly distributed across the rotation space
As per: http://planning.cs.uiuc.edu/node198.html | [
"Generate",
"a",
"random",
"unit",
"quaternion",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L260-L273 | train | 199,033 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.conjugate | def conjugate(self):
"""Quaternion conjugate, encapsulated in a new instance.
For a unit quaternion, this is the same as the inverse.
Returns:
A new Quaternion object clone with its vector part negated
"""
return self.__class__(scalar=self.scalar, vector= -self.vector) | python | def conjugate(self):
"""Quaternion conjugate, encapsulated in a new instance.
For a unit quaternion, this is the same as the inverse.
Returns:
A new Quaternion object clone with its vector part negated
"""
return self.__class__(scalar=self.scalar, vector= -self.vector) | [
"def",
"conjugate",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"scalar",
"=",
"self",
".",
"scalar",
",",
"vector",
"=",
"-",
"self",
".",
"vector",
")"
] | Quaternion conjugate, encapsulated in a new instance.
For a unit quaternion, this is the same as the inverse.
Returns:
A new Quaternion object clone with its vector part negated | [
"Quaternion",
"conjugate",
"encapsulated",
"in",
"a",
"new",
"instance",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L446-L454 | train | 199,034 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.inverse | def inverse(self):
"""Inverse of the quaternion object, encapsulated in a new instance.
For a unit quaternion, this is the inverse rotation, i.e. when combined with the original rotation, will result in the null rotation.
Returns:
A new Quaternion object representing the inverse of this object
"""
ss = self._sum_of_squares()
if ss > 0:
return self.__class__(array=(self._vector_conjugate() / ss))
else:
raise ZeroDivisionError("a zero quaternion (0 + 0i + 0j + 0k) cannot be inverted") | python | def inverse(self):
"""Inverse of the quaternion object, encapsulated in a new instance.
For a unit quaternion, this is the inverse rotation, i.e. when combined with the original rotation, will result in the null rotation.
Returns:
A new Quaternion object representing the inverse of this object
"""
ss = self._sum_of_squares()
if ss > 0:
return self.__class__(array=(self._vector_conjugate() / ss))
else:
raise ZeroDivisionError("a zero quaternion (0 + 0i + 0j + 0k) cannot be inverted") | [
"def",
"inverse",
"(",
"self",
")",
":",
"ss",
"=",
"self",
".",
"_sum_of_squares",
"(",
")",
"if",
"ss",
">",
"0",
":",
"return",
"self",
".",
"__class__",
"(",
"array",
"=",
"(",
"self",
".",
"_vector_conjugate",
"(",
")",
"/",
"ss",
")",
")",
... | Inverse of the quaternion object, encapsulated in a new instance.
For a unit quaternion, this is the inverse rotation, i.e. when combined with the original rotation, will result in the null rotation.
Returns:
A new Quaternion object representing the inverse of this object | [
"Inverse",
"of",
"the",
"quaternion",
"object",
"encapsulated",
"in",
"a",
"new",
"instance",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L457-L469 | train | 199,035 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion._fast_normalise | def _fast_normalise(self):
"""Normalise the object to a unit quaternion using a fast approximation method if appropriate.
Object is guaranteed to be a quaternion of approximately unit length
after calling this operation UNLESS the object is equivalent to Quaternion(0)
"""
if not self.is_unit():
mag_squared = np.dot(self.q, self.q)
if (mag_squared == 0):
return
if (abs(1.0 - mag_squared) < 2.107342e-08):
mag = ((1.0 + mag_squared) / 2.0) # More efficient. Pade approximation valid if error is small
else:
mag = sqrt(mag_squared) # Error is too big, take the performance hit to calculate the square root properly
self.q = self.q / mag | python | def _fast_normalise(self):
"""Normalise the object to a unit quaternion using a fast approximation method if appropriate.
Object is guaranteed to be a quaternion of approximately unit length
after calling this operation UNLESS the object is equivalent to Quaternion(0)
"""
if not self.is_unit():
mag_squared = np.dot(self.q, self.q)
if (mag_squared == 0):
return
if (abs(1.0 - mag_squared) < 2.107342e-08):
mag = ((1.0 + mag_squared) / 2.0) # More efficient. Pade approximation valid if error is small
else:
mag = sqrt(mag_squared) # Error is too big, take the performance hit to calculate the square root properly
self.q = self.q / mag | [
"def",
"_fast_normalise",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_unit",
"(",
")",
":",
"mag_squared",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"q",
",",
"self",
".",
"q",
")",
"if",
"(",
"mag_squared",
"==",
"0",
")",
":",
"return",... | Normalise the object to a unit quaternion using a fast approximation method if appropriate.
Object is guaranteed to be a quaternion of approximately unit length
after calling this operation UNLESS the object is equivalent to Quaternion(0) | [
"Normalise",
"the",
"object",
"to",
"a",
"unit",
"quaternion",
"using",
"a",
"fast",
"approximation",
"method",
"if",
"appropriate",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L497-L512 | train | 199,036 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.rotate | def rotate(self, vector):
"""Rotate a 3D vector by the rotation stored in the Quaternion object.
Params:
vector: A 3-vector specified as any ordered sequence of 3 real numbers corresponding to x, y, and z values.
Some types that are recognised are: numpy arrays, lists and tuples.
A 3-vector can also be represented by a Quaternion object who's scalar part is 0 and vector part is the required 3-vector.
Thus it is possible to call `Quaternion.rotate(q)` with another quaternion object as an input.
Returns:
The rotated vector returned as the same type it was specified at input.
Raises:
TypeError: if any of the vector elements cannot be converted to a real number.
ValueError: if `vector` cannot be interpreted as a 3-vector or a Quaternion object.
"""
if isinstance(vector, Quaternion):
return self._rotate_quaternion(vector)
q = Quaternion(vector=vector)
a = self._rotate_quaternion(q).vector
if isinstance(vector, list):
l = [x for x in a]
return l
elif isinstance(vector, tuple):
l = [x for x in a]
return tuple(l)
else:
return a | python | def rotate(self, vector):
"""Rotate a 3D vector by the rotation stored in the Quaternion object.
Params:
vector: A 3-vector specified as any ordered sequence of 3 real numbers corresponding to x, y, and z values.
Some types that are recognised are: numpy arrays, lists and tuples.
A 3-vector can also be represented by a Quaternion object who's scalar part is 0 and vector part is the required 3-vector.
Thus it is possible to call `Quaternion.rotate(q)` with another quaternion object as an input.
Returns:
The rotated vector returned as the same type it was specified at input.
Raises:
TypeError: if any of the vector elements cannot be converted to a real number.
ValueError: if `vector` cannot be interpreted as a 3-vector or a Quaternion object.
"""
if isinstance(vector, Quaternion):
return self._rotate_quaternion(vector)
q = Quaternion(vector=vector)
a = self._rotate_quaternion(q).vector
if isinstance(vector, list):
l = [x for x in a]
return l
elif isinstance(vector, tuple):
l = [x for x in a]
return tuple(l)
else:
return a | [
"def",
"rotate",
"(",
"self",
",",
"vector",
")",
":",
"if",
"isinstance",
"(",
"vector",
",",
"Quaternion",
")",
":",
"return",
"self",
".",
"_rotate_quaternion",
"(",
"vector",
")",
"q",
"=",
"Quaternion",
"(",
"vector",
"=",
"vector",
")",
"a",
"=",... | Rotate a 3D vector by the rotation stored in the Quaternion object.
Params:
vector: A 3-vector specified as any ordered sequence of 3 real numbers corresponding to x, y, and z values.
Some types that are recognised are: numpy arrays, lists and tuples.
A 3-vector can also be represented by a Quaternion object who's scalar part is 0 and vector part is the required 3-vector.
Thus it is possible to call `Quaternion.rotate(q)` with another quaternion object as an input.
Returns:
The rotated vector returned as the same type it was specified at input.
Raises:
TypeError: if any of the vector elements cannot be converted to a real number.
ValueError: if `vector` cannot be interpreted as a 3-vector or a Quaternion object. | [
"Rotate",
"a",
"3D",
"vector",
"by",
"the",
"rotation",
"stored",
"in",
"the",
"Quaternion",
"object",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L594-L622 | train | 199,037 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.exp | def exp(cls, q):
"""Quaternion Exponential.
Find the exponential of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing the exp(q). See [Source](https://math.stackexchange.com/questions/1030737/exponential-function-of-quaternion-derivation for more information and mathematical background).
Note:
The method can compute the exponential of any quaternion.
"""
tolerance = 1e-17
v_norm = np.linalg.norm(q.vector)
vec = q.vector
if v_norm > tolerance:
vec = vec / v_norm
magnitude = exp(q.scalar)
return Quaternion(scalar = magnitude * cos(v_norm), vector = magnitude * sin(v_norm) * vec) | python | def exp(cls, q):
"""Quaternion Exponential.
Find the exponential of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing the exp(q). See [Source](https://math.stackexchange.com/questions/1030737/exponential-function-of-quaternion-derivation for more information and mathematical background).
Note:
The method can compute the exponential of any quaternion.
"""
tolerance = 1e-17
v_norm = np.linalg.norm(q.vector)
vec = q.vector
if v_norm > tolerance:
vec = vec / v_norm
magnitude = exp(q.scalar)
return Quaternion(scalar = magnitude * cos(v_norm), vector = magnitude * sin(v_norm) * vec) | [
"def",
"exp",
"(",
"cls",
",",
"q",
")",
":",
"tolerance",
"=",
"1e-17",
"v_norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"q",
".",
"vector",
")",
"vec",
"=",
"q",
".",
"vector",
"if",
"v_norm",
">",
"tolerance",
":",
"vec",
"=",
"vec",
"/... | Quaternion Exponential.
Find the exponential of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing the exp(q). See [Source](https://math.stackexchange.com/questions/1030737/exponential-function-of-quaternion-derivation for more information and mathematical background).
Note:
The method can compute the exponential of any quaternion. | [
"Quaternion",
"Exponential",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L625-L645 | train | 199,038 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.log | def log(cls, q):
"""Quaternion Logarithm.
Find the logarithm of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing log(q) := (log(|q|), v/|v|acos(w/|q|)).
Note:
The method computes the logarithm of general quaternions. See [Source](https://math.stackexchange.com/questions/2552/the-logarithm-of-quaternion/2554#2554) for more details.
"""
v_norm = np.linalg.norm(q.vector)
q_norm = q.norm
tolerance = 1e-17
if q_norm < tolerance:
# 0 quaternion - undefined
return Quaternion(scalar=-float('inf'), vector=float('nan')*q.vector)
if v_norm < tolerance:
# real quaternions - no imaginary part
return Quaternion(scalar=log(q_norm), vector=[0,0,0])
vec = q.vector / v_norm
return Quaternion(scalar=log(q_norm), vector=acos(q.scalar/q_norm)*vec) | python | def log(cls, q):
"""Quaternion Logarithm.
Find the logarithm of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing log(q) := (log(|q|), v/|v|acos(w/|q|)).
Note:
The method computes the logarithm of general quaternions. See [Source](https://math.stackexchange.com/questions/2552/the-logarithm-of-quaternion/2554#2554) for more details.
"""
v_norm = np.linalg.norm(q.vector)
q_norm = q.norm
tolerance = 1e-17
if q_norm < tolerance:
# 0 quaternion - undefined
return Quaternion(scalar=-float('inf'), vector=float('nan')*q.vector)
if v_norm < tolerance:
# real quaternions - no imaginary part
return Quaternion(scalar=log(q_norm), vector=[0,0,0])
vec = q.vector / v_norm
return Quaternion(scalar=log(q_norm), vector=acos(q.scalar/q_norm)*vec) | [
"def",
"log",
"(",
"cls",
",",
"q",
")",
":",
"v_norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"q",
".",
"vector",
")",
"q_norm",
"=",
"q",
".",
"norm",
"tolerance",
"=",
"1e-17",
"if",
"q_norm",
"<",
"tolerance",
":",
"# 0 quaternion - undefine... | Quaternion Logarithm.
Find the logarithm of a quaternion amount.
Params:
q: the input quaternion/argument as a Quaternion object.
Returns:
A quaternion amount representing log(q) := (log(|q|), v/|v|acos(w/|q|)).
Note:
The method computes the logarithm of general quaternions. See [Source](https://math.stackexchange.com/questions/2552/the-logarithm-of-quaternion/2554#2554) for more details. | [
"Quaternion",
"Logarithm",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L648-L672 | train | 199,039 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.sym_exp_map | def sym_exp_map(cls, q, eta):
"""Quaternion symmetrized exponential map.
Find the symmetrized exponential map on the quaternion Riemannian
manifold.
Params:
q: the base point as a Quaternion object
eta: the tangent vector argument of the exponential map
as a Quaternion object
Returns:
A quaternion p.
Note:
The symmetrized exponential formulation is akin to the exponential
formulation for symmetric positive definite tensors [Source](http://www.academia.edu/7656761/On_the_Averaging_of_Symmetric_Positive-Definite_Tensors)
"""
sqrt_q = q ** 0.5
return sqrt_q * Quaternion.exp(eta) * sqrt_q | python | def sym_exp_map(cls, q, eta):
"""Quaternion symmetrized exponential map.
Find the symmetrized exponential map on the quaternion Riemannian
manifold.
Params:
q: the base point as a Quaternion object
eta: the tangent vector argument of the exponential map
as a Quaternion object
Returns:
A quaternion p.
Note:
The symmetrized exponential formulation is akin to the exponential
formulation for symmetric positive definite tensors [Source](http://www.academia.edu/7656761/On_the_Averaging_of_Symmetric_Positive-Definite_Tensors)
"""
sqrt_q = q ** 0.5
return sqrt_q * Quaternion.exp(eta) * sqrt_q | [
"def",
"sym_exp_map",
"(",
"cls",
",",
"q",
",",
"eta",
")",
":",
"sqrt_q",
"=",
"q",
"**",
"0.5",
"return",
"sqrt_q",
"*",
"Quaternion",
".",
"exp",
"(",
"eta",
")",
"*",
"sqrt_q"
] | Quaternion symmetrized exponential map.
Find the symmetrized exponential map on the quaternion Riemannian
manifold.
Params:
q: the base point as a Quaternion object
eta: the tangent vector argument of the exponential map
as a Quaternion object
Returns:
A quaternion p.
Note:
The symmetrized exponential formulation is akin to the exponential
formulation for symmetric positive definite tensors [Source](http://www.academia.edu/7656761/On_the_Averaging_of_Symmetric_Positive-Definite_Tensors) | [
"Quaternion",
"symmetrized",
"exponential",
"map",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L697-L716 | train | 199,040 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.sym_log_map | def sym_log_map(cls, q, p):
"""Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
p: the argument of the quaternion map, a Quaternion object
Returns:
A tangent vector corresponding to the symmetrized geodesic curve formulation.
Note:
Information on the symmetrized formulations given in [Source](https://www.researchgate.net/publication/267191489_Riemannian_L_p_Averaging_on_Lie_Group_of_Nonzero_Quaternions).
"""
inv_sqrt_q = (q ** (-0.5))
return Quaternion.log(inv_sqrt_q * p * inv_sqrt_q) | python | def sym_log_map(cls, q, p):
"""Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
p: the argument of the quaternion map, a Quaternion object
Returns:
A tangent vector corresponding to the symmetrized geodesic curve formulation.
Note:
Information on the symmetrized formulations given in [Source](https://www.researchgate.net/publication/267191489_Riemannian_L_p_Averaging_on_Lie_Group_of_Nonzero_Quaternions).
"""
inv_sqrt_q = (q ** (-0.5))
return Quaternion.log(inv_sqrt_q * p * inv_sqrt_q) | [
"def",
"sym_log_map",
"(",
"cls",
",",
"q",
",",
"p",
")",
":",
"inv_sqrt_q",
"=",
"(",
"q",
"**",
"(",
"-",
"0.5",
")",
")",
"return",
"Quaternion",
".",
"log",
"(",
"inv_sqrt_q",
"*",
"p",
"*",
"inv_sqrt_q",
")"
] | Quaternion symmetrized logarithm map.
Find the symmetrized logarithm map on the quaternion Riemannian manifold.
Params:
q: the base point at which the logarithm is computed, i.e.
a Quaternion object
p: the argument of the quaternion map, a Quaternion object
Returns:
A tangent vector corresponding to the symmetrized geodesic curve formulation.
Note:
Information on the symmetrized formulations given in [Source](https://www.researchgate.net/publication/267191489_Riemannian_L_p_Averaging_on_Lie_Group_of_Nonzero_Quaternions). | [
"Quaternion",
"symmetrized",
"logarithm",
"map",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L736-L753 | train | 199,041 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.absolute_distance | def absolute_distance(cls, q0, q1):
"""Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to the chord of the shortest path/arc that
connects q0 to q1.
Note:
This function does not measure the distance on the hypersphere, but
it takes into account the fact that q and -q encode the same rotation.
It is thus a good indicator for rotation similarities.
"""
q0_minus_q1 = q0 - q1
q0_plus_q1 = q0 + q1
d_minus = q0_minus_q1.norm
d_plus = q0_plus_q1.norm
if (d_minus < d_plus):
return d_minus
else:
return d_plus | python | def absolute_distance(cls, q0, q1):
"""Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to the chord of the shortest path/arc that
connects q0 to q1.
Note:
This function does not measure the distance on the hypersphere, but
it takes into account the fact that q and -q encode the same rotation.
It is thus a good indicator for rotation similarities.
"""
q0_minus_q1 = q0 - q1
q0_plus_q1 = q0 + q1
d_minus = q0_minus_q1.norm
d_plus = q0_plus_q1.norm
if (d_minus < d_plus):
return d_minus
else:
return d_plus | [
"def",
"absolute_distance",
"(",
"cls",
",",
"q0",
",",
"q1",
")",
":",
"q0_minus_q1",
"=",
"q0",
"-",
"q1",
"q0_plus_q1",
"=",
"q0",
"+",
"q1",
"d_minus",
"=",
"q0_minus_q1",
".",
"norm",
"d_plus",
"=",
"q0_plus_q1",
".",
"norm",
"if",
"(",
"d_minus",... | Quaternion absolute distance.
Find the distance between two quaternions accounting for the sign ambiguity.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive scalar corresponding to the chord of the shortest path/arc that
connects q0 to q1.
Note:
This function does not measure the distance on the hypersphere, but
it takes into account the fact that q and -q encode the same rotation.
It is thus a good indicator for rotation similarities. | [
"Quaternion",
"absolute",
"distance",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L756-L781 | train | 199,042 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.distance | def distance(cls, q0, q1):
"""Quaternion intrinsic distance.
Find the intrinsic geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the geodesic arc
connecting q0 to q1.
Note:
Although the q0^(-1)*q1 != q1^(-1)*q0, the length of the path joining
them is given by the logarithm of those product quaternions, the norm
of which is the same.
"""
q = Quaternion.log_map(q0, q1)
return q.norm | python | def distance(cls, q0, q1):
"""Quaternion intrinsic distance.
Find the intrinsic geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the geodesic arc
connecting q0 to q1.
Note:
Although the q0^(-1)*q1 != q1^(-1)*q0, the length of the path joining
them is given by the logarithm of those product quaternions, the norm
of which is the same.
"""
q = Quaternion.log_map(q0, q1)
return q.norm | [
"def",
"distance",
"(",
"cls",
",",
"q0",
",",
"q1",
")",
":",
"q",
"=",
"Quaternion",
".",
"log_map",
"(",
"q0",
",",
"q1",
")",
"return",
"q",
".",
"norm"
] | Quaternion intrinsic distance.
Find the intrinsic geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the geodesic arc
connecting q0 to q1.
Note:
Although the q0^(-1)*q1 != q1^(-1)*q0, the length of the path joining
them is given by the logarithm of those product quaternions, the norm
of which is the same. | [
"Quaternion",
"intrinsic",
"distance",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L784-L803 | train | 199,043 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.sym_distance | def sym_distance(cls, q0, q1):
"""Quaternion symmetrized distance.
Find the intrinsic symmetrized geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the symmetrized
geodesic curve connecting q0 to q1.
Note:
This formulation is more numerically stable when performing
iterative gradient descent on the Riemannian quaternion manifold.
However, the distance between q and -q is equal to pi, rendering this
formulation not useful for measuring rotation similarities when the
samples are spread over a "solid" angle of more than pi/2 radians
(the spread refers to quaternions as point samples on the unit hypersphere).
"""
q = Quaternion.sym_log_map(q0, q1)
return q.norm | python | def sym_distance(cls, q0, q1):
"""Quaternion symmetrized distance.
Find the intrinsic symmetrized geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the symmetrized
geodesic curve connecting q0 to q1.
Note:
This formulation is more numerically stable when performing
iterative gradient descent on the Riemannian quaternion manifold.
However, the distance between q and -q is equal to pi, rendering this
formulation not useful for measuring rotation similarities when the
samples are spread over a "solid" angle of more than pi/2 radians
(the spread refers to quaternions as point samples on the unit hypersphere).
"""
q = Quaternion.sym_log_map(q0, q1)
return q.norm | [
"def",
"sym_distance",
"(",
"cls",
",",
"q0",
",",
"q1",
")",
":",
"q",
"=",
"Quaternion",
".",
"sym_log_map",
"(",
"q0",
",",
"q1",
")",
"return",
"q",
".",
"norm"
] | Quaternion symmetrized distance.
Find the intrinsic symmetrized geodesic distance between q0 and q1.
Params:
q0: the first quaternion
q1: the second quaternion
Returns:
A positive amount corresponding to the length of the symmetrized
geodesic curve connecting q0 to q1.
Note:
This formulation is more numerically stable when performing
iterative gradient descent on the Riemannian quaternion manifold.
However, the distance between q and -q is equal to pi, rendering this
formulation not useful for measuring rotation similarities when the
samples are spread over a "solid" angle of more than pi/2 radians
(the spread refers to quaternions as point samples on the unit hypersphere). | [
"Quaternion",
"symmetrized",
"distance",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L806-L828 | train | 199,044 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.intermediates | def intermediates(cls, q0, q1, n, include_endpoints=False):
"""Generator method to get an iterable sequence of `n` evenly spaced quaternion
rotations between any two existing quaternion endpoints lying on the unit
radius hypersphere.
This is a convenience function that is based on `Quaternion.slerp()` as defined above.
This is a class method and is called as a method of the class itself rather than on a particular instance.
Params:
q_start: initial endpoint rotation as a Quaternion object
q_end: final endpoint rotation as a Quaternion object
n: number of intermediate quaternion objects to include within the interval
include_endpoints: [optional] if set to `True`, the sequence of intermediates
will be 'bookended' by `q_start` and `q_end`, resulting in a sequence length of `n + 2`.
If set to `False`, endpoints are not included. Defaults to `False`.
Yields:
A generator object iterating over a sequence of intermediate quaternion objects.
Note:
This feature only makes sense when interpolating between unit quaternions (those lying on the unit radius hypersphere).
Calling this method will implicitly normalise the endpoints to unit quaternions if they are not already unit length.
"""
step_size = 1.0 / (n + 1)
if include_endpoints:
steps = [i * step_size for i in range(0, n + 2)]
else:
steps = [i * step_size for i in range(1, n + 1)]
for step in steps:
yield cls.slerp(q0, q1, step) | python | def intermediates(cls, q0, q1, n, include_endpoints=False):
"""Generator method to get an iterable sequence of `n` evenly spaced quaternion
rotations between any two existing quaternion endpoints lying on the unit
radius hypersphere.
This is a convenience function that is based on `Quaternion.slerp()` as defined above.
This is a class method and is called as a method of the class itself rather than on a particular instance.
Params:
q_start: initial endpoint rotation as a Quaternion object
q_end: final endpoint rotation as a Quaternion object
n: number of intermediate quaternion objects to include within the interval
include_endpoints: [optional] if set to `True`, the sequence of intermediates
will be 'bookended' by `q_start` and `q_end`, resulting in a sequence length of `n + 2`.
If set to `False`, endpoints are not included. Defaults to `False`.
Yields:
A generator object iterating over a sequence of intermediate quaternion objects.
Note:
This feature only makes sense when interpolating between unit quaternions (those lying on the unit radius hypersphere).
Calling this method will implicitly normalise the endpoints to unit quaternions if they are not already unit length.
"""
step_size = 1.0 / (n + 1)
if include_endpoints:
steps = [i * step_size for i in range(0, n + 2)]
else:
steps = [i * step_size for i in range(1, n + 1)]
for step in steps:
yield cls.slerp(q0, q1, step) | [
"def",
"intermediates",
"(",
"cls",
",",
"q0",
",",
"q1",
",",
"n",
",",
"include_endpoints",
"=",
"False",
")",
":",
"step_size",
"=",
"1.0",
"/",
"(",
"n",
"+",
"1",
")",
"if",
"include_endpoints",
":",
"steps",
"=",
"[",
"i",
"*",
"step_size",
"... | Generator method to get an iterable sequence of `n` evenly spaced quaternion
rotations between any two existing quaternion endpoints lying on the unit
radius hypersphere.
This is a convenience function that is based on `Quaternion.slerp()` as defined above.
This is a class method and is called as a method of the class itself rather than on a particular instance.
Params:
q_start: initial endpoint rotation as a Quaternion object
q_end: final endpoint rotation as a Quaternion object
n: number of intermediate quaternion objects to include within the interval
include_endpoints: [optional] if set to `True`, the sequence of intermediates
will be 'bookended' by `q_start` and `q_end`, resulting in a sequence length of `n + 2`.
If set to `False`, endpoints are not included. Defaults to `False`.
Yields:
A generator object iterating over a sequence of intermediate quaternion objects.
Note:
This feature only makes sense when interpolating between unit quaternions (those lying on the unit radius hypersphere).
Calling this method will implicitly normalise the endpoints to unit quaternions if they are not already unit length. | [
"Generator",
"method",
"to",
"get",
"an",
"iterable",
"sequence",
"of",
"n",
"evenly",
"spaced",
"quaternion",
"rotations",
"between",
"any",
"two",
"existing",
"quaternion",
"endpoints",
"lying",
"on",
"the",
"unit",
"radius",
"hypersphere",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L888-L918 | train | 199,045 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.derivative | def derivative(self, rate):
"""Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
Returns:
A unit quaternion describing the rotation rate
"""
rate = self._validate_number_sequence(rate, 3)
return 0.5 * self * Quaternion(vector=rate) | python | def derivative(self, rate):
"""Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
Returns:
A unit quaternion describing the rotation rate
"""
rate = self._validate_number_sequence(rate, 3)
return 0.5 * self * Quaternion(vector=rate) | [
"def",
"derivative",
"(",
"self",
",",
"rate",
")",
":",
"rate",
"=",
"self",
".",
"_validate_number_sequence",
"(",
"rate",
",",
"3",
")",
"return",
"0.5",
"*",
"self",
"*",
"Quaternion",
"(",
"vector",
"=",
"rate",
")"
] | Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
Returns:
A unit quaternion describing the rotation rate | [
"Get",
"the",
"instantaneous",
"quaternion",
"derivative",
"representing",
"a",
"quaternion",
"rotating",
"at",
"a",
"3D",
"rate",
"vector",
"rate"
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L920-L930 | train | 199,046 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.integrate | def integrate(self, rate, timestep):
"""Advance a time varying quaternion to its value at a time `timestep` in the future.
The Quaternion object will be modified to its future value.
It is guaranteed to remain a unit quaternion.
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the
global x, y and z axes respectively.
timestep: interval over which to integrate into the future.
Assuming *now* is `T=0`, the integration occurs over the interval
`T=0` to `T=timestep`. Smaller intervals are more accurate when
`rate` changes over time.
Note:
The solution is closed form given the assumption that `rate` is constant
over the interval of length `timestep`.
"""
self._fast_normalise()
rate = self._validate_number_sequence(rate, 3)
rotation_vector = rate * timestep
rotation_norm = np.linalg.norm(rotation_vector)
if rotation_norm > 0:
axis = rotation_vector / rotation_norm
angle = rotation_norm
q2 = Quaternion(axis=axis, angle=angle)
self.q = (self * q2).q
self._fast_normalise() | python | def integrate(self, rate, timestep):
"""Advance a time varying quaternion to its value at a time `timestep` in the future.
The Quaternion object will be modified to its future value.
It is guaranteed to remain a unit quaternion.
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the
global x, y and z axes respectively.
timestep: interval over which to integrate into the future.
Assuming *now* is `T=0`, the integration occurs over the interval
`T=0` to `T=timestep`. Smaller intervals are more accurate when
`rate` changes over time.
Note:
The solution is closed form given the assumption that `rate` is constant
over the interval of length `timestep`.
"""
self._fast_normalise()
rate = self._validate_number_sequence(rate, 3)
rotation_vector = rate * timestep
rotation_norm = np.linalg.norm(rotation_vector)
if rotation_norm > 0:
axis = rotation_vector / rotation_norm
angle = rotation_norm
q2 = Quaternion(axis=axis, angle=angle)
self.q = (self * q2).q
self._fast_normalise() | [
"def",
"integrate",
"(",
"self",
",",
"rate",
",",
"timestep",
")",
":",
"self",
".",
"_fast_normalise",
"(",
")",
"rate",
"=",
"self",
".",
"_validate_number_sequence",
"(",
"rate",
",",
"3",
")",
"rotation_vector",
"=",
"rate",
"*",
"timestep",
"rotation... | Advance a time varying quaternion to its value at a time `timestep` in the future.
The Quaternion object will be modified to its future value.
It is guaranteed to remain a unit quaternion.
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the
global x, y and z axes respectively.
timestep: interval over which to integrate into the future.
Assuming *now* is `T=0`, the integration occurs over the interval
`T=0` to `T=timestep`. Smaller intervals are more accurate when
`rate` changes over time.
Note:
The solution is closed form given the assumption that `rate` is constant
over the interval of length `timestep`. | [
"Advance",
"a",
"time",
"varying",
"quaternion",
"to",
"its",
"value",
"at",
"a",
"time",
"timestep",
"in",
"the",
"future",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L932-L961 | train | 199,047 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.rotation_matrix | def rotation_matrix(self):
"""Get the 3x3 rotation matrix equivalent of the quaternion rotation.
Returns:
A 3x3 orthogonal rotation matrix as a 3x3 Numpy array
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
self._normalise()
product_matrix = np.dot(self._q_matrix(), self._q_bar_matrix().conj().transpose())
return product_matrix[1:][:,1:] | python | def rotation_matrix(self):
"""Get the 3x3 rotation matrix equivalent of the quaternion rotation.
Returns:
A 3x3 orthogonal rotation matrix as a 3x3 Numpy array
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
self._normalise()
product_matrix = np.dot(self._q_matrix(), self._q_bar_matrix().conj().transpose())
return product_matrix[1:][:,1:] | [
"def",
"rotation_matrix",
"(",
"self",
")",
":",
"self",
".",
"_normalise",
"(",
")",
"product_matrix",
"=",
"np",
".",
"dot",
"(",
"self",
".",
"_q_matrix",
"(",
")",
",",
"self",
".",
"_q_bar_matrix",
"(",
")",
".",
"conj",
"(",
")",
".",
"transpos... | Get the 3x3 rotation matrix equivalent of the quaternion rotation.
Returns:
A 3x3 orthogonal rotation matrix as a 3x3 Numpy array
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. | [
"Get",
"the",
"3x3",
"rotation",
"matrix",
"equivalent",
"of",
"the",
"quaternion",
"rotation",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L965-L977 | train | 199,048 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.transformation_matrix | def transformation_matrix(self):
"""Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation.
Returns:
A 4x4 homogeneous transformation matrix as a 4x4 Numpy array
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
t = np.array([[0.0], [0.0], [0.0]])
Rt = np.hstack([self.rotation_matrix, t])
return np.vstack([Rt, np.array([0.0, 0.0, 0.0, 1.0])]) | python | def transformation_matrix(self):
"""Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation.
Returns:
A 4x4 homogeneous transformation matrix as a 4x4 Numpy array
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
t = np.array([[0.0], [0.0], [0.0]])
Rt = np.hstack([self.rotation_matrix, t])
return np.vstack([Rt, np.array([0.0, 0.0, 0.0, 1.0])]) | [
"def",
"transformation_matrix",
"(",
"self",
")",
":",
"t",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"0.0",
"]",
",",
"[",
"0.0",
"]",
",",
"[",
"0.0",
"]",
"]",
")",
"Rt",
"=",
"np",
".",
"hstack",
"(",
"[",
"self",
".",
"rotation_matrix",
",",... | Get the 4x4 homogeneous transformation matrix equivalent of the quaternion rotation.
Returns:
A 4x4 homogeneous transformation matrix as a 4x4 Numpy array
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. | [
"Get",
"the",
"4x4",
"homogeneous",
"transformation",
"matrix",
"equivalent",
"of",
"the",
"quaternion",
"rotation",
"."
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L980-L991 | train | 199,049 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.yaw_pitch_roll | def yaw_pitch_roll(self):
"""Get the equivalent yaw-pitch-roll angles aka. intrinsic Tait-Bryan angles following the z-y'-x'' convention
Returns:
yaw: rotation angle around the z-axis in radians, in the range `[-pi, pi]`
pitch: rotation angle around the y'-axis in radians, in the range `[-pi/2, -pi/2]`
roll: rotation angle around the x''-axis in radians, in the range `[-pi, pi]`
The resulting rotation_matrix would be R = R_x(roll) R_y(pitch) R_z(yaw)
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
self._normalise()
yaw = np.arctan2(2*(self.q[0]*self.q[3] - self.q[1]*self.q[2]),
1 - 2*(self.q[2]**2 + self.q[3]**2))
pitch = np.arcsin(2*(self.q[0]*self.q[2] + self.q[3]*self.q[1]))
roll = np.arctan2(2*(self.q[0]*self.q[1] - self.q[2]*self.q[3]),
1 - 2*(self.q[1]**2 + self.q[2]**2))
return yaw, pitch, roll | python | def yaw_pitch_roll(self):
"""Get the equivalent yaw-pitch-roll angles aka. intrinsic Tait-Bryan angles following the z-y'-x'' convention
Returns:
yaw: rotation angle around the z-axis in radians, in the range `[-pi, pi]`
pitch: rotation angle around the y'-axis in radians, in the range `[-pi/2, -pi/2]`
roll: rotation angle around the x''-axis in radians, in the range `[-pi, pi]`
The resulting rotation_matrix would be R = R_x(roll) R_y(pitch) R_z(yaw)
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
self._normalise()
yaw = np.arctan2(2*(self.q[0]*self.q[3] - self.q[1]*self.q[2]),
1 - 2*(self.q[2]**2 + self.q[3]**2))
pitch = np.arcsin(2*(self.q[0]*self.q[2] + self.q[3]*self.q[1]))
roll = np.arctan2(2*(self.q[0]*self.q[1] - self.q[2]*self.q[3]),
1 - 2*(self.q[1]**2 + self.q[2]**2))
return yaw, pitch, roll | [
"def",
"yaw_pitch_roll",
"(",
"self",
")",
":",
"self",
".",
"_normalise",
"(",
")",
"yaw",
"=",
"np",
".",
"arctan2",
"(",
"2",
"*",
"(",
"self",
".",
"q",
"[",
"0",
"]",
"*",
"self",
".",
"q",
"[",
"3",
"]",
"-",
"self",
".",
"q",
"[",
"1... | Get the equivalent yaw-pitch-roll angles aka. intrinsic Tait-Bryan angles following the z-y'-x'' convention
Returns:
yaw: rotation angle around the z-axis in radians, in the range `[-pi, pi]`
pitch: rotation angle around the y'-axis in radians, in the range `[-pi/2, -pi/2]`
roll: rotation angle around the x''-axis in radians, in the range `[-pi, pi]`
The resulting rotation_matrix would be R = R_x(roll) R_y(pitch) R_z(yaw)
Note:
This feature only makes sense when referring to a unit quaternion. Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. | [
"Get",
"the",
"equivalent",
"yaw",
"-",
"pitch",
"-",
"roll",
"angles",
"aka",
".",
"intrinsic",
"Tait",
"-",
"Bryan",
"angles",
"following",
"the",
"z",
"-",
"y",
"-",
"x",
"convention"
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L994-L1015 | train | 199,050 |
KieranWynn/pyquaternion | pyquaternion/quaternion.py | Quaternion.get_axis | def get_axis(self, undefined=np.zeros(3)):
"""Get the axis or vector about which the quaternion rotation occurs
For a null rotation (a purely real quaternion), the rotation angle will
always be `0`, but the rotation axis is undefined.
It is by default assumed to be `[0, 0, 0]`.
Params:
undefined: [optional] specify the axis vector that should define a null rotation.
This is geometrically meaningless, and could be any of an infinite set of vectors,
but can be specified if the default (`[0, 0, 0]`) causes undesired behaviour.
Returns:
A Numpy unit 3-vector describing the Quaternion object's axis of rotation.
Note:
This feature only makes sense when referring to a unit quaternion.
Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
tolerance = 1e-17
self._normalise()
norm = np.linalg.norm(self.vector)
if norm < tolerance:
# Here there are an infinite set of possible axes, use what has been specified as an undefined axis.
return undefined
else:
return self.vector / norm | python | def get_axis(self, undefined=np.zeros(3)):
"""Get the axis or vector about which the quaternion rotation occurs
For a null rotation (a purely real quaternion), the rotation angle will
always be `0`, but the rotation axis is undefined.
It is by default assumed to be `[0, 0, 0]`.
Params:
undefined: [optional] specify the axis vector that should define a null rotation.
This is geometrically meaningless, and could be any of an infinite set of vectors,
but can be specified if the default (`[0, 0, 0]`) causes undesired behaviour.
Returns:
A Numpy unit 3-vector describing the Quaternion object's axis of rotation.
Note:
This feature only makes sense when referring to a unit quaternion.
Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one.
"""
tolerance = 1e-17
self._normalise()
norm = np.linalg.norm(self.vector)
if norm < tolerance:
# Here there are an infinite set of possible axes, use what has been specified as an undefined axis.
return undefined
else:
return self.vector / norm | [
"def",
"get_axis",
"(",
"self",
",",
"undefined",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
")",
":",
"tolerance",
"=",
"1e-17",
"self",
".",
"_normalise",
"(",
")",
"norm",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"self",
".",
"vector",
")",
"i... | Get the axis or vector about which the quaternion rotation occurs
For a null rotation (a purely real quaternion), the rotation angle will
always be `0`, but the rotation axis is undefined.
It is by default assumed to be `[0, 0, 0]`.
Params:
undefined: [optional] specify the axis vector that should define a null rotation.
This is geometrically meaningless, and could be any of an infinite set of vectors,
but can be specified if the default (`[0, 0, 0]`) causes undesired behaviour.
Returns:
A Numpy unit 3-vector describing the Quaternion object's axis of rotation.
Note:
This feature only makes sense when referring to a unit quaternion.
Calling this method will implicitly normalise the Quaternion object to a unit quaternion if it is not already one. | [
"Get",
"the",
"axis",
"or",
"vector",
"about",
"which",
"the",
"quaternion",
"rotation",
"occurs"
] | d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9 | https://github.com/KieranWynn/pyquaternion/blob/d2aad7f3fb0d4b9cc23aa72b390e9b2e1273eae9/pyquaternion/quaternion.py#L1026-L1052 | train | 199,051 |
Yubico/python-yubico | yubico/yubikey_config_util.py | YubiKeyFlag.req_string | def req_string(self, model):
""" Return string describing model and version requirement. """
if model not in self.models:
model = self.models
if self.min_ykver and self.max_ykver:
return "%s %d.%d..%d.%d" % (model, \
self.min_ykver[0], self.min_ykver[1], \
self.max_ykver[0], self.max_ykver[1], \
)
if self.max_ykver:
return "%s <= %d.%d" % (model, self.max_ykver[0], self.max_ykver[1])
return "%s >= %d.%d" % (model, self.min_ykver[0], self.min_ykver[1]) | python | def req_string(self, model):
""" Return string describing model and version requirement. """
if model not in self.models:
model = self.models
if self.min_ykver and self.max_ykver:
return "%s %d.%d..%d.%d" % (model, \
self.min_ykver[0], self.min_ykver[1], \
self.max_ykver[0], self.max_ykver[1], \
)
if self.max_ykver:
return "%s <= %d.%d" % (model, self.max_ykver[0], self.max_ykver[1])
return "%s >= %d.%d" % (model, self.min_ykver[0], self.min_ykver[1]) | [
"def",
"req_string",
"(",
"self",
",",
"model",
")",
":",
"if",
"model",
"not",
"in",
"self",
".",
"models",
":",
"model",
"=",
"self",
".",
"models",
"if",
"self",
".",
"min_ykver",
"and",
"self",
".",
"max_ykver",
":",
"return",
"\"%s %d.%d..%d.%d\"",
... | Return string describing model and version requirement. | [
"Return",
"string",
"describing",
"model",
"and",
"version",
"requirement",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config_util.py#L72-L84 | train | 199,052 |
Yubico/python-yubico | yubico/yubikey_config_util.py | YubiKeyFlag.is_compatible | def is_compatible(self, model, version):
""" Check if this flag is compatible with a YubiKey of version 'ver'. """
if not model in self.models:
return False
if self.max_ykver:
return (version >= self.min_ykver and
version <= self.max_ykver)
else:
return version >= self.min_ykver | python | def is_compatible(self, model, version):
""" Check if this flag is compatible with a YubiKey of version 'ver'. """
if not model in self.models:
return False
if self.max_ykver:
return (version >= self.min_ykver and
version <= self.max_ykver)
else:
return version >= self.min_ykver | [
"def",
"is_compatible",
"(",
"self",
",",
"model",
",",
"version",
")",
":",
"if",
"not",
"model",
"in",
"self",
".",
"models",
":",
"return",
"False",
"if",
"self",
".",
"max_ykver",
":",
"return",
"(",
"version",
">=",
"self",
".",
"min_ykver",
"and"... | Check if this flag is compatible with a YubiKey of version 'ver'. | [
"Check",
"if",
"this",
"flag",
"is",
"compatible",
"with",
"a",
"YubiKey",
"of",
"version",
"ver",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config_util.py#L86-L94 | train | 199,053 |
Yubico/python-yubico | yubico/yubikey_config_util.py | YubiKeyConfigBits.get_set | def get_set(self, flag, new):
"""
Return the boolean value of 'flag'. If 'new' is set,
the flag is updated, and the value before update is
returned.
"""
old = self._is_set(flag)
if new is True:
self._set(flag)
elif new is False:
self._clear(flag)
return old | python | def get_set(self, flag, new):
"""
Return the boolean value of 'flag'. If 'new' is set,
the flag is updated, and the value before update is
returned.
"""
old = self._is_set(flag)
if new is True:
self._set(flag)
elif new is False:
self._clear(flag)
return old | [
"def",
"get_set",
"(",
"self",
",",
"flag",
",",
"new",
")",
":",
"old",
"=",
"self",
".",
"_is_set",
"(",
"flag",
")",
"if",
"new",
"is",
"True",
":",
"self",
".",
"_set",
"(",
"flag",
")",
"elif",
"new",
"is",
"False",
":",
"self",
".",
"_cle... | Return the boolean value of 'flag'. If 'new' is set,
the flag is updated, and the value before update is
returned. | [
"Return",
"the",
"boolean",
"value",
"of",
"flag",
".",
"If",
"new",
"is",
"set",
"the",
"flag",
"is",
"updated",
"and",
"the",
"value",
"before",
"update",
"is",
"returned",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config_util.py#L144-L155 | train | 199,054 |
Yubico/python-yubico | yubico/yubikey_4_usb_hid.py | YubiKey4_USBHID._read_capabilities | def _read_capabilities(self):
""" Read the capabilities list from a YubiKey >= 4.0.0 """
frame = yubikey_frame.YubiKeyFrame(command=SLOT.YK4_CAPABILITIES)
self._device._write(frame)
response = self._device._read_response()
r_len = yubico_util.ord_byte(response[0])
# 1 byte length, 2 byte CRC.
if not yubico_util.validate_crc16(response[:r_len+3]):
raise YubiKey4_USBHIDError("Read from device failed CRC check")
return response[1:r_len+1] | python | def _read_capabilities(self):
""" Read the capabilities list from a YubiKey >= 4.0.0 """
frame = yubikey_frame.YubiKeyFrame(command=SLOT.YK4_CAPABILITIES)
self._device._write(frame)
response = self._device._read_response()
r_len = yubico_util.ord_byte(response[0])
# 1 byte length, 2 byte CRC.
if not yubico_util.validate_crc16(response[:r_len+3]):
raise YubiKey4_USBHIDError("Read from device failed CRC check")
return response[1:r_len+1] | [
"def",
"_read_capabilities",
"(",
"self",
")",
":",
"frame",
"=",
"yubikey_frame",
".",
"YubiKeyFrame",
"(",
"command",
"=",
"SLOT",
".",
"YK4_CAPABILITIES",
")",
"self",
".",
"_device",
".",
"_write",
"(",
"frame",
")",
"response",
"=",
"self",
".",
"_dev... | Read the capabilities list from a YubiKey >= 4.0.0 | [
"Read",
"the",
"capabilities",
"list",
"from",
"a",
"YubiKey",
">",
"=",
"4",
".",
"0",
".",
"0"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_4_usb_hid.py#L101-L113 | train | 199,055 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice.status | def status(self):
"""
Poll YubiKey for status.
"""
data = self._read()
self._status = YubiKeyUSBHIDStatus(data)
return self._status | python | def status(self):
"""
Poll YubiKey for status.
"""
data = self._read()
self._status = YubiKeyUSBHIDStatus(data)
return self._status | [
"def",
"status",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_read",
"(",
")",
"self",
".",
"_status",
"=",
"YubiKeyUSBHIDStatus",
"(",
"data",
")",
"return",
"self",
".",
"_status"
] | Poll YubiKey for status. | [
"Poll",
"YubiKey",
"for",
"status",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L127-L133 | train | 199,056 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._write_config | def _write_config(self, cfg, slot):
""" Write configuration to YubiKey. """
old_pgm_seq = self._status.pgm_seq
frame = cfg.to_frame(slot=slot)
self._debug("Writing %s frame :\n%s\n" % \
(yubikey_config.command2str(frame.command), cfg))
self._write(frame)
self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)
# make sure we have a fresh pgm_seq value
self.status()
self._debug("Programmed slot %i, sequence %i -> %i\n" % (slot, old_pgm_seq, self._status.pgm_seq))
cfgs = self._status.valid_configs()
if not cfgs and self._status.pgm_seq == 0:
return
if self._status.pgm_seq == old_pgm_seq + 1:
return
raise YubiKeyUSBHIDError('YubiKey programming failed (seq %i not increased (%i))' % \
(old_pgm_seq, self._status.pgm_seq)) | python | def _write_config(self, cfg, slot):
""" Write configuration to YubiKey. """
old_pgm_seq = self._status.pgm_seq
frame = cfg.to_frame(slot=slot)
self._debug("Writing %s frame :\n%s\n" % \
(yubikey_config.command2str(frame.command), cfg))
self._write(frame)
self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)
# make sure we have a fresh pgm_seq value
self.status()
self._debug("Programmed slot %i, sequence %i -> %i\n" % (slot, old_pgm_seq, self._status.pgm_seq))
cfgs = self._status.valid_configs()
if not cfgs and self._status.pgm_seq == 0:
return
if self._status.pgm_seq == old_pgm_seq + 1:
return
raise YubiKeyUSBHIDError('YubiKey programming failed (seq %i not increased (%i))' % \
(old_pgm_seq, self._status.pgm_seq)) | [
"def",
"_write_config",
"(",
"self",
",",
"cfg",
",",
"slot",
")",
":",
"old_pgm_seq",
"=",
"self",
".",
"_status",
".",
"pgm_seq",
"frame",
"=",
"cfg",
".",
"to_frame",
"(",
"slot",
"=",
"slot",
")",
"self",
".",
"_debug",
"(",
"\"Writing %s frame :\\n%... | Write configuration to YubiKey. | [
"Write",
"configuration",
"to",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L142-L161 | train | 199,057 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._read_response | def _read_response(self, may_block=False):
""" Wait for a response to become available, and read it. """
# wait for response to become available
res = self._waitfor_set(yubikey_defs.RESP_PENDING_FLAG, may_block)[:7]
# continue reading while response pending is set
while True:
this = self._read()
flags = yubico_util.ord_byte(this[7])
if flags & yubikey_defs.RESP_PENDING_FLAG:
seq = flags & 0b00011111
if res and (seq == 0):
break
res += this[:7]
else:
break
self._write_reset()
return res | python | def _read_response(self, may_block=False):
""" Wait for a response to become available, and read it. """
# wait for response to become available
res = self._waitfor_set(yubikey_defs.RESP_PENDING_FLAG, may_block)[:7]
# continue reading while response pending is set
while True:
this = self._read()
flags = yubico_util.ord_byte(this[7])
if flags & yubikey_defs.RESP_PENDING_FLAG:
seq = flags & 0b00011111
if res and (seq == 0):
break
res += this[:7]
else:
break
self._write_reset()
return res | [
"def",
"_read_response",
"(",
"self",
",",
"may_block",
"=",
"False",
")",
":",
"# wait for response to become available",
"res",
"=",
"self",
".",
"_waitfor_set",
"(",
"yubikey_defs",
".",
"RESP_PENDING_FLAG",
",",
"may_block",
")",
"[",
":",
"7",
"]",
"# conti... | Wait for a response to become available, and read it. | [
"Wait",
"for",
"a",
"response",
"to",
"become",
"available",
"and",
"read",
"it",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L163-L179 | train | 199,058 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._read | def _read(self):
""" Read a USB HID feature report from the YubiKey. """
request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN
value = _REPORT_TYPE_FEATURE << 8 # apparently required for YubiKey 1.3.2, but not 2.2.x
recv = self._usb_handle.controlMsg(request_type,
_HID_GET_REPORT,
_FEATURE_RPT_SIZE,
value = value,
timeout = _USB_TIMEOUT_MS)
if len(recv) != _FEATURE_RPT_SIZE:
self._debug("Failed reading %i bytes (got %i) from USB HID YubiKey.\n"
% (_FEATURE_RPT_SIZE, recv))
raise YubiKeyUSBHIDError('Failed reading from USB HID YubiKey')
data = b''.join(yubico_util.chr_byte(c) for c in recv)
self._debug("READ : %s" % (yubico_util.hexdump(data, colorize=True)))
return data | python | def _read(self):
""" Read a USB HID feature report from the YubiKey. """
request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_IN
value = _REPORT_TYPE_FEATURE << 8 # apparently required for YubiKey 1.3.2, but not 2.2.x
recv = self._usb_handle.controlMsg(request_type,
_HID_GET_REPORT,
_FEATURE_RPT_SIZE,
value = value,
timeout = _USB_TIMEOUT_MS)
if len(recv) != _FEATURE_RPT_SIZE:
self._debug("Failed reading %i bytes (got %i) from USB HID YubiKey.\n"
% (_FEATURE_RPT_SIZE, recv))
raise YubiKeyUSBHIDError('Failed reading from USB HID YubiKey')
data = b''.join(yubico_util.chr_byte(c) for c in recv)
self._debug("READ : %s" % (yubico_util.hexdump(data, colorize=True)))
return data | [
"def",
"_read",
"(",
"self",
")",
":",
"request_type",
"=",
"_USB_TYPE_CLASS",
"|",
"_USB_RECIP_INTERFACE",
"|",
"_USB_ENDPOINT_IN",
"value",
"=",
"_REPORT_TYPE_FEATURE",
"<<",
"8",
"# apparently required for YubiKey 1.3.2, but not 2.2.x",
"recv",
"=",
"self",
".",
"_us... | Read a USB HID feature report from the YubiKey. | [
"Read",
"a",
"USB",
"HID",
"feature",
"report",
"from",
"the",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L181-L196 | train | 199,059 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._write | def _write(self, frame):
"""
Write a YubiKeyFrame to the USB HID.
Includes polling for YubiKey readiness before each write.
"""
for data in frame.to_feature_reports(debug=self.debug):
debug_str = None
if self.debug:
(data, debug_str) = data
# first, we ensure the YubiKey will accept a write
self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)
self._raw_write(data, debug_str)
return True | python | def _write(self, frame):
"""
Write a YubiKeyFrame to the USB HID.
Includes polling for YubiKey readiness before each write.
"""
for data in frame.to_feature_reports(debug=self.debug):
debug_str = None
if self.debug:
(data, debug_str) = data
# first, we ensure the YubiKey will accept a write
self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)
self._raw_write(data, debug_str)
return True | [
"def",
"_write",
"(",
"self",
",",
"frame",
")",
":",
"for",
"data",
"in",
"frame",
".",
"to_feature_reports",
"(",
"debug",
"=",
"self",
".",
"debug",
")",
":",
"debug_str",
"=",
"None",
"if",
"self",
".",
"debug",
":",
"(",
"data",
",",
"debug_str"... | Write a YubiKeyFrame to the USB HID.
Includes polling for YubiKey readiness before each write. | [
"Write",
"a",
"YubiKeyFrame",
"to",
"the",
"USB",
"HID",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L198-L211 | train | 199,060 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._write_reset | def _write_reset(self):
"""
Reset read mode by issuing a dummy write.
"""
data = b'\x00\x00\x00\x00\x00\x00\x00\x8f'
self._raw_write(data)
self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)
return True | python | def _write_reset(self):
"""
Reset read mode by issuing a dummy write.
"""
data = b'\x00\x00\x00\x00\x00\x00\x00\x8f'
self._raw_write(data)
self._waitfor_clear(yubikey_defs.SLOT_WRITE_FLAG)
return True | [
"def",
"_write_reset",
"(",
"self",
")",
":",
"data",
"=",
"b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x8f'",
"self",
".",
"_raw_write",
"(",
"data",
")",
"self",
".",
"_waitfor_clear",
"(",
"yubikey_defs",
".",
"SLOT_WRITE_FLAG",
")",
"return",
"True"
] | Reset read mode by issuing a dummy write. | [
"Reset",
"read",
"mode",
"by",
"issuing",
"a",
"dummy",
"write",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L213-L220 | train | 199,061 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._raw_write | def _raw_write(self, data, debug_str = None):
"""
Write data to YubiKey.
"""
if self.debug:
if not debug_str:
debug_str = ''
hexdump = yubico_util.hexdump(data, colorize=True)[:-1] # strip LF
self._debug("WRITE : %s %s\n" % (hexdump, debug_str))
request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_OUT
value = _REPORT_TYPE_FEATURE << 8 # apparently required for YubiKey 1.3.2, but not 2.2.x
sent = self._usb_handle.controlMsg(request_type,
_HID_SET_REPORT,
data,
value = value,
timeout = _USB_TIMEOUT_MS)
if sent != _FEATURE_RPT_SIZE:
self.debug("Failed writing %i bytes (wrote %i) to USB HID YubiKey.\n"
% (_FEATURE_RPT_SIZE, sent))
raise YubiKeyUSBHIDError('Failed talking to USB HID YubiKey')
return sent | python | def _raw_write(self, data, debug_str = None):
"""
Write data to YubiKey.
"""
if self.debug:
if not debug_str:
debug_str = ''
hexdump = yubico_util.hexdump(data, colorize=True)[:-1] # strip LF
self._debug("WRITE : %s %s\n" % (hexdump, debug_str))
request_type = _USB_TYPE_CLASS | _USB_RECIP_INTERFACE | _USB_ENDPOINT_OUT
value = _REPORT_TYPE_FEATURE << 8 # apparently required for YubiKey 1.3.2, but not 2.2.x
sent = self._usb_handle.controlMsg(request_type,
_HID_SET_REPORT,
data,
value = value,
timeout = _USB_TIMEOUT_MS)
if sent != _FEATURE_RPT_SIZE:
self.debug("Failed writing %i bytes (wrote %i) to USB HID YubiKey.\n"
% (_FEATURE_RPT_SIZE, sent))
raise YubiKeyUSBHIDError('Failed talking to USB HID YubiKey')
return sent | [
"def",
"_raw_write",
"(",
"self",
",",
"data",
",",
"debug_str",
"=",
"None",
")",
":",
"if",
"self",
".",
"debug",
":",
"if",
"not",
"debug_str",
":",
"debug_str",
"=",
"''",
"hexdump",
"=",
"yubico_util",
".",
"hexdump",
"(",
"data",
",",
"colorize",... | Write data to YubiKey. | [
"Write",
"data",
"to",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L222-L242 | train | 199,062 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._waitfor | def _waitfor(self, mode, mask, may_block, timeout=2):
"""
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds)
"""
finished = False
sleep = 0.01
# After six sleeps, we've slept 0.64 seconds.
wait_num = (timeout * 2) - 1 + 6
resp_timeout = False # YubiKey hasn't indicated RESP_TIMEOUT (yet)
while not finished:
time.sleep(sleep)
this = self._read()
flags = yubico_util.ord_byte(this[7])
if flags & yubikey_defs.RESP_TIMEOUT_WAIT_FLAG:
if not resp_timeout:
resp_timeout = True
seconds_left = flags & yubikey_defs.RESP_TIMEOUT_WAIT_MASK
self._debug("Device indicates RESP_TIMEOUT (%i seconds left)\n" \
% (seconds_left))
if may_block:
# calculate new wait_num - never more than 20 seconds
seconds_left = min(20, seconds_left)
wait_num = (seconds_left * 2) - 1 + 6
if mode is 'nand':
if not flags & mask == mask:
finished = True
else:
self._debug("Status %s (0x%x) has not cleared bits %s (0x%x)\n"
% (bin(flags), flags, bin(mask), mask))
elif mode is 'and':
if flags & mask == mask:
finished = True
else:
self._debug("Status %s (0x%x) has not set bits %s (0x%x)\n"
% (bin(flags), flags, bin(mask), mask))
else:
assert()
if not finished:
wait_num -= 1
if wait_num == 0:
if mode is 'nand':
reason = 'Timed out waiting for YubiKey to clear status 0x%x' % mask
else:
reason = 'Timed out waiting for YubiKey to set status 0x%x' % mask
raise yubikey_base.YubiKeyTimeout(reason)
sleep = min(sleep + sleep, 0.5)
else:
return this | python | def _waitfor(self, mode, mask, may_block, timeout=2):
"""
Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds)
"""
finished = False
sleep = 0.01
# After six sleeps, we've slept 0.64 seconds.
wait_num = (timeout * 2) - 1 + 6
resp_timeout = False # YubiKey hasn't indicated RESP_TIMEOUT (yet)
while not finished:
time.sleep(sleep)
this = self._read()
flags = yubico_util.ord_byte(this[7])
if flags & yubikey_defs.RESP_TIMEOUT_WAIT_FLAG:
if not resp_timeout:
resp_timeout = True
seconds_left = flags & yubikey_defs.RESP_TIMEOUT_WAIT_MASK
self._debug("Device indicates RESP_TIMEOUT (%i seconds left)\n" \
% (seconds_left))
if may_block:
# calculate new wait_num - never more than 20 seconds
seconds_left = min(20, seconds_left)
wait_num = (seconds_left * 2) - 1 + 6
if mode is 'nand':
if not flags & mask == mask:
finished = True
else:
self._debug("Status %s (0x%x) has not cleared bits %s (0x%x)\n"
% (bin(flags), flags, bin(mask), mask))
elif mode is 'and':
if flags & mask == mask:
finished = True
else:
self._debug("Status %s (0x%x) has not set bits %s (0x%x)\n"
% (bin(flags), flags, bin(mask), mask))
else:
assert()
if not finished:
wait_num -= 1
if wait_num == 0:
if mode is 'nand':
reason = 'Timed out waiting for YubiKey to clear status 0x%x' % mask
else:
reason = 'Timed out waiting for YubiKey to set status 0x%x' % mask
raise yubikey_base.YubiKeyTimeout(reason)
sleep = min(sleep + sleep, 0.5)
else:
return this | [
"def",
"_waitfor",
"(",
"self",
",",
"mode",
",",
"mask",
",",
"may_block",
",",
"timeout",
"=",
"2",
")",
":",
"finished",
"=",
"False",
"sleep",
"=",
"0.01",
"# After six sleeps, we've slept 0.64 seconds.",
"wait_num",
"=",
"(",
"timeout",
"*",
"2",
")",
... | Wait for the YubiKey to either turn ON or OFF certain bits in the status byte.
mode is either 'and' or 'nand'
timeout is a number of seconds (precision about ~0.5 seconds) | [
"Wait",
"for",
"the",
"YubiKey",
"to",
"either",
"turn",
"ON",
"or",
"OFF",
"certain",
"bits",
"in",
"the",
"status",
"byte",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L260-L313 | train | 199,063 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._open | def _open(self, skip=0):
""" Perform HID initialization """
usb_device = self._get_usb_device(skip)
if usb_device:
usb_conf = usb_device.configurations[0]
self._usb_int = usb_conf.interfaces[0][0]
else:
raise YubiKeyUSBHIDError('No USB YubiKey found')
try:
self._usb_handle = usb_device.open()
self._usb_handle.detachKernelDriver(0)
except Exception as error:
if 'could not detach kernel driver from interface' in str(error):
self._debug('The in-kernel-HID driver has already been detached\n')
else:
self._debug("detachKernelDriver not supported!\n")
try:
self._usb_handle.setConfiguration(1)
except usb.USBError:
self._debug("Unable to set configuration, ignoring...\n")
self._usb_handle.claimInterface(self._usb_int)
return True | python | def _open(self, skip=0):
""" Perform HID initialization """
usb_device = self._get_usb_device(skip)
if usb_device:
usb_conf = usb_device.configurations[0]
self._usb_int = usb_conf.interfaces[0][0]
else:
raise YubiKeyUSBHIDError('No USB YubiKey found')
try:
self._usb_handle = usb_device.open()
self._usb_handle.detachKernelDriver(0)
except Exception as error:
if 'could not detach kernel driver from interface' in str(error):
self._debug('The in-kernel-HID driver has already been detached\n')
else:
self._debug("detachKernelDriver not supported!\n")
try:
self._usb_handle.setConfiguration(1)
except usb.USBError:
self._debug("Unable to set configuration, ignoring...\n")
self._usb_handle.claimInterface(self._usb_int)
return True | [
"def",
"_open",
"(",
"self",
",",
"skip",
"=",
"0",
")",
":",
"usb_device",
"=",
"self",
".",
"_get_usb_device",
"(",
"skip",
")",
"if",
"usb_device",
":",
"usb_conf",
"=",
"usb_device",
".",
"configurations",
"[",
"0",
"]",
"self",
".",
"_usb_int",
"=... | Perform HID initialization | [
"Perform",
"HID",
"initialization"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L315-L339 | train | 199,064 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._close | def _close(self):
"""
Release the USB interface again.
"""
self._usb_handle.releaseInterface()
try:
# If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.
self._usb_handle.dev.attach_kernel_driver(0)
except:
pass
self._usb_int = None
self._usb_handle = None
return True | python | def _close(self):
"""
Release the USB interface again.
"""
self._usb_handle.releaseInterface()
try:
# If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.
self._usb_handle.dev.attach_kernel_driver(0)
except:
pass
self._usb_int = None
self._usb_handle = None
return True | [
"def",
"_close",
"(",
"self",
")",
":",
"self",
".",
"_usb_handle",
".",
"releaseInterface",
"(",
")",
"try",
":",
"# If we're using PyUSB >= 1.0 we can re-attach the kernel driver here.",
"self",
".",
"_usb_handle",
".",
"dev",
".",
"attach_kernel_driver",
"(",
"0",
... | Release the USB interface again. | [
"Release",
"the",
"USB",
"interface",
"again",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L341-L353 | train | 199,065 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._get_usb_device | def _get_usb_device(self, skip=0):
"""
Get YubiKey USB device.
Optionally allows you to skip n devices, to support multiple attached YubiKeys.
"""
try:
# PyUSB >= 1.0, this is a workaround for a problem with libusbx
# on Windows.
import usb.core
import usb.legacy
devices = [usb.legacy.Device(d) for d in usb.core.find(
find_all=True, idVendor=YUBICO_VID)]
except ImportError:
# Using PyUsb < 1.0.
import usb
devices = [d for bus in usb.busses() for d in bus.devices]
for device in devices:
if device.idVendor == YUBICO_VID:
if device.idProduct in PID.all(otp=True):
if skip == 0:
return device
skip -= 1
return None | python | def _get_usb_device(self, skip=0):
"""
Get YubiKey USB device.
Optionally allows you to skip n devices, to support multiple attached YubiKeys.
"""
try:
# PyUSB >= 1.0, this is a workaround for a problem with libusbx
# on Windows.
import usb.core
import usb.legacy
devices = [usb.legacy.Device(d) for d in usb.core.find(
find_all=True, idVendor=YUBICO_VID)]
except ImportError:
# Using PyUsb < 1.0.
import usb
devices = [d for bus in usb.busses() for d in bus.devices]
for device in devices:
if device.idVendor == YUBICO_VID:
if device.idProduct in PID.all(otp=True):
if skip == 0:
return device
skip -= 1
return None | [
"def",
"_get_usb_device",
"(",
"self",
",",
"skip",
"=",
"0",
")",
":",
"try",
":",
"# PyUSB >= 1.0, this is a workaround for a problem with libusbx",
"# on Windows.",
"import",
"usb",
".",
"core",
"import",
"usb",
".",
"legacy",
"devices",
"=",
"[",
"usb",
".",
... | Get YubiKey USB device.
Optionally allows you to skip n devices, to support multiple attached YubiKeys. | [
"Get",
"YubiKey",
"USB",
"device",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L355-L378 | train | 199,066 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyHIDDevice._debug | def _debug(self, out, print_prefix=True):
""" Print out to stderr, if debugging is enabled. """
if self.debug:
if print_prefix:
pre = self.__class__.__name__
if hasattr(self, 'debug_prefix'):
pre = getattr(self, 'debug_prefix')
sys.stderr.write("%s: " % pre)
sys.stderr.write(out) | python | def _debug(self, out, print_prefix=True):
""" Print out to stderr, if debugging is enabled. """
if self.debug:
if print_prefix:
pre = self.__class__.__name__
if hasattr(self, 'debug_prefix'):
pre = getattr(self, 'debug_prefix')
sys.stderr.write("%s: " % pre)
sys.stderr.write(out) | [
"def",
"_debug",
"(",
"self",
",",
"out",
",",
"print_prefix",
"=",
"True",
")",
":",
"if",
"self",
".",
"debug",
":",
"if",
"print_prefix",
":",
"pre",
"=",
"self",
".",
"__class__",
".",
"__name__",
"if",
"hasattr",
"(",
"self",
",",
"'debug_prefix'"... | Print out to stderr, if debugging is enabled. | [
"Print",
"out",
"to",
"stderr",
"if",
"debugging",
"is",
"enabled",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L380-L388 | train | 199,067 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyUSBHID.init_config | def init_config(self, **kw):
""" Get a configuration object for this type of YubiKey. """
return YubiKeyConfigUSBHID(ykver=self.version_num(), \
capabilities = self.capabilities, \
**kw) | python | def init_config(self, **kw):
""" Get a configuration object for this type of YubiKey. """
return YubiKeyConfigUSBHID(ykver=self.version_num(), \
capabilities = self.capabilities, \
**kw) | [
"def",
"init_config",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"return",
"YubiKeyConfigUSBHID",
"(",
"ykver",
"=",
"self",
".",
"version_num",
"(",
")",
",",
"capabilities",
"=",
"self",
".",
"capabilities",
",",
"*",
"*",
"kw",
")"
] | Get a configuration object for this type of YubiKey. | [
"Get",
"a",
"configuration",
"object",
"for",
"this",
"type",
"of",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L463-L467 | train | 199,068 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyUSBHID.write_config | def write_config(self, cfg, slot=1):
""" Write a configuration to the YubiKey. """
cfg_req_ver = cfg.version_required()
if cfg_req_ver > self.version_num():
raise yubikey_base.YubiKeyVersionError('Configuration requires YubiKey version %i.%i (this is %s)' % \
(cfg_req_ver[0], cfg_req_ver[1], self.version()))
if not self.capabilities.have_configuration_slot(slot):
raise YubiKeyUSBHIDError("Can't write configuration to slot %i" % (slot))
return self._device._write_config(cfg, slot) | python | def write_config(self, cfg, slot=1):
""" Write a configuration to the YubiKey. """
cfg_req_ver = cfg.version_required()
if cfg_req_ver > self.version_num():
raise yubikey_base.YubiKeyVersionError('Configuration requires YubiKey version %i.%i (this is %s)' % \
(cfg_req_ver[0], cfg_req_ver[1], self.version()))
if not self.capabilities.have_configuration_slot(slot):
raise YubiKeyUSBHIDError("Can't write configuration to slot %i" % (slot))
return self._device._write_config(cfg, slot) | [
"def",
"write_config",
"(",
"self",
",",
"cfg",
",",
"slot",
"=",
"1",
")",
":",
"cfg_req_ver",
"=",
"cfg",
".",
"version_required",
"(",
")",
"if",
"cfg_req_ver",
">",
"self",
".",
"version_num",
"(",
")",
":",
"raise",
"yubikey_base",
".",
"YubiKeyVers... | Write a configuration to the YubiKey. | [
"Write",
"a",
"configuration",
"to",
"the",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L469-L477 | train | 199,069 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyUSBHID._read_serial | def _read_serial(self, may_block):
""" Read the serial number from a YubiKey > 2.2. """
frame = yubikey_frame.YubiKeyFrame(command = SLOT.DEVICE_SERIAL)
self._device._write(frame)
response = self._device._read_response(may_block=may_block)
if not yubico_util.validate_crc16(response[:6]):
raise YubiKeyUSBHIDError("Read from device failed CRC check")
# the serial number is big-endian, although everything else is little-endian
serial = struct.unpack('>lxxx', response)
return serial[0] | python | def _read_serial(self, may_block):
""" Read the serial number from a YubiKey > 2.2. """
frame = yubikey_frame.YubiKeyFrame(command = SLOT.DEVICE_SERIAL)
self._device._write(frame)
response = self._device._read_response(may_block=may_block)
if not yubico_util.validate_crc16(response[:6]):
raise YubiKeyUSBHIDError("Read from device failed CRC check")
# the serial number is big-endian, although everything else is little-endian
serial = struct.unpack('>lxxx', response)
return serial[0] | [
"def",
"_read_serial",
"(",
"self",
",",
"may_block",
")",
":",
"frame",
"=",
"yubikey_frame",
".",
"YubiKeyFrame",
"(",
"command",
"=",
"SLOT",
".",
"DEVICE_SERIAL",
")",
"self",
".",
"_device",
".",
"_write",
"(",
"frame",
")",
"response",
"=",
"self",
... | Read the serial number from a YubiKey > 2.2. | [
"Read",
"the",
"serial",
"number",
"from",
"a",
"YubiKey",
">",
"2",
".",
"2",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L479-L489 | train | 199,070 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyUSBHID._challenge_response | def _challenge_response(self, challenge, mode, slot, variable, may_block):
""" Do challenge-response with a YubiKey > 2.0. """
# Check length and pad challenge if appropriate
if mode == 'HMAC':
if len(challenge) > yubikey_defs.SHA1_MAX_BLOCK_SIZE:
raise yubico_exception.InputError('Mode HMAC challenge too big (%i/%i)' \
% (yubikey_defs.SHA1_MAX_BLOCK_SIZE, len(challenge)))
if len(challenge) < yubikey_defs.SHA1_MAX_BLOCK_SIZE:
pad_with = b'\0'
if variable and challenge[-1:] == pad_with:
pad_with = b'\xff'
challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, pad_with)
response_len = yubikey_defs.SHA1_DIGEST_SIZE
elif mode == 'OTP':
if len(challenge) != yubikey_defs.UID_SIZE:
raise yubico_exception.InputError('Mode OTP challenge must be %i bytes (got %i)' \
% (yubikey_defs.UID_SIZE, len(challenge)))
challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, b'\0')
response_len = 16
else:
raise yubico_exception.InputError('Invalid mode supplied (%s, valid values are HMAC and OTP)' \
% (mode))
try:
command = _CMD_CHALLENGE[mode][slot]
except:
raise yubico_exception.InputError('Invalid slot specified (%s)' % (slot))
frame = yubikey_frame.YubiKeyFrame(command=command, payload=challenge)
self._device._write(frame)
response = self._device._read_response(may_block=may_block)
if not yubico_util.validate_crc16(response[:response_len + 2]):
raise YubiKeyUSBHIDError("Read from device failed CRC check")
return response[:response_len] | python | def _challenge_response(self, challenge, mode, slot, variable, may_block):
""" Do challenge-response with a YubiKey > 2.0. """
# Check length and pad challenge if appropriate
if mode == 'HMAC':
if len(challenge) > yubikey_defs.SHA1_MAX_BLOCK_SIZE:
raise yubico_exception.InputError('Mode HMAC challenge too big (%i/%i)' \
% (yubikey_defs.SHA1_MAX_BLOCK_SIZE, len(challenge)))
if len(challenge) < yubikey_defs.SHA1_MAX_BLOCK_SIZE:
pad_with = b'\0'
if variable and challenge[-1:] == pad_with:
pad_with = b'\xff'
challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, pad_with)
response_len = yubikey_defs.SHA1_DIGEST_SIZE
elif mode == 'OTP':
if len(challenge) != yubikey_defs.UID_SIZE:
raise yubico_exception.InputError('Mode OTP challenge must be %i bytes (got %i)' \
% (yubikey_defs.UID_SIZE, len(challenge)))
challenge = challenge.ljust(yubikey_defs.SHA1_MAX_BLOCK_SIZE, b'\0')
response_len = 16
else:
raise yubico_exception.InputError('Invalid mode supplied (%s, valid values are HMAC and OTP)' \
% (mode))
try:
command = _CMD_CHALLENGE[mode][slot]
except:
raise yubico_exception.InputError('Invalid slot specified (%s)' % (slot))
frame = yubikey_frame.YubiKeyFrame(command=command, payload=challenge)
self._device._write(frame)
response = self._device._read_response(may_block=may_block)
if not yubico_util.validate_crc16(response[:response_len + 2]):
raise YubiKeyUSBHIDError("Read from device failed CRC check")
return response[:response_len] | [
"def",
"_challenge_response",
"(",
"self",
",",
"challenge",
",",
"mode",
",",
"slot",
",",
"variable",
",",
"may_block",
")",
":",
"# Check length and pad challenge if appropriate",
"if",
"mode",
"==",
"'HMAC'",
":",
"if",
"len",
"(",
"challenge",
")",
">",
"... | Do challenge-response with a YubiKey > 2.0. | [
"Do",
"challenge",
"-",
"response",
"with",
"a",
"YubiKey",
">",
"2",
".",
"0",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L491-L524 | train | 199,071 |
Yubico/python-yubico | yubico/yubikey_usb_hid.py | YubiKeyUSBHIDStatus.valid_configs | def valid_configs(self):
""" Return a list of slots having a valid configurtion. Requires firmware 2.1. """
if self.ykver() < (2,1,0):
raise YubiKeyUSBHIDError('Valid configs unsupported in firmware %s' % (self.version()))
res = []
if self.touch_level & self.CONFIG1_VALID == self.CONFIG1_VALID:
res.append(1)
if self.touch_level & self.CONFIG2_VALID == self.CONFIG2_VALID:
res.append(2)
return res | python | def valid_configs(self):
""" Return a list of slots having a valid configurtion. Requires firmware 2.1. """
if self.ykver() < (2,1,0):
raise YubiKeyUSBHIDError('Valid configs unsupported in firmware %s' % (self.version()))
res = []
if self.touch_level & self.CONFIG1_VALID == self.CONFIG1_VALID:
res.append(1)
if self.touch_level & self.CONFIG2_VALID == self.CONFIG2_VALID:
res.append(2)
return res | [
"def",
"valid_configs",
"(",
"self",
")",
":",
"if",
"self",
".",
"ykver",
"(",
")",
"<",
"(",
"2",
",",
"1",
",",
"0",
")",
":",
"raise",
"YubiKeyUSBHIDError",
"(",
"'Valid configs unsupported in firmware %s'",
"%",
"(",
"self",
".",
"version",
"(",
")"... | Return a list of slots having a valid configurtion. Requires firmware 2.1. | [
"Return",
"a",
"list",
"of",
"slots",
"having",
"a",
"valid",
"configurtion",
".",
"Requires",
"firmware",
"2",
".",
"1",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_usb_hid.py#L578-L587 | train | 199,072 |
Yubico/python-yubico | yubico/yubikey_config.py | command2str | def command2str(num):
""" Turn command number into name """
for attr in SLOT.__dict__.keys():
if not attr.startswith('_') and attr == attr.upper():
if getattr(SLOT, attr) == num:
return 'SLOT_%s' % attr
return "0x%02x" % (num) | python | def command2str(num):
""" Turn command number into name """
for attr in SLOT.__dict__.keys():
if not attr.startswith('_') and attr == attr.upper():
if getattr(SLOT, attr) == num:
return 'SLOT_%s' % attr
return "0x%02x" % (num) | [
"def",
"command2str",
"(",
"num",
")",
":",
"for",
"attr",
"in",
"SLOT",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'_'",
")",
"and",
"attr",
"==",
"attr",
".",
"upper",
"(",
")",
":",
"if",
"getatt... | Turn command number into name | [
"Turn",
"command",
"number",
"into",
"name"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L32-L39 | train | 199,073 |
Yubico/python-yubico | yubico/yubikey_config.py | _get_flag | def _get_flag(which, flags):
""" Find 'which' entry in 'flags'. """
res = [this for this in flags if this.is_equal(which)]
if len(res) == 0:
return None
if len(res) == 1:
return res[0]
assert() | python | def _get_flag(which, flags):
""" Find 'which' entry in 'flags'. """
res = [this for this in flags if this.is_equal(which)]
if len(res) == 0:
return None
if len(res) == 1:
return res[0]
assert() | [
"def",
"_get_flag",
"(",
"which",
",",
"flags",
")",
":",
"res",
"=",
"[",
"this",
"for",
"this",
"in",
"flags",
"if",
"this",
".",
"is_equal",
"(",
"which",
")",
"]",
"if",
"len",
"(",
"res",
")",
"==",
"0",
":",
"return",
"None",
"if",
"len",
... | Find 'which' entry in 'flags'. | [
"Find",
"which",
"entry",
"in",
"flags",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L550-L557 | train | 199,074 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.fixed_string | def fixed_string(self, data=None):
"""
The fixed string is used to identify a particular Yubikey device.
The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode.
The length of the fixed string can be set between 0 and 16 bytes.
Tip: This can also be used to extend the length of a static password.
"""
old = self.fixed
if data != None:
new = self._decode_input_string(data)
if len(new) <= 16:
self.fixed = new
else:
raise yubico_exception.InputError('The "fixed" string must be 0..16 bytes')
return old | python | def fixed_string(self, data=None):
"""
The fixed string is used to identify a particular Yubikey device.
The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode.
The length of the fixed string can be set between 0 and 16 bytes.
Tip: This can also be used to extend the length of a static password.
"""
old = self.fixed
if data != None:
new = self._decode_input_string(data)
if len(new) <= 16:
self.fixed = new
else:
raise yubico_exception.InputError('The "fixed" string must be 0..16 bytes')
return old | [
"def",
"fixed_string",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"old",
"=",
"self",
".",
"fixed",
"if",
"data",
"!=",
"None",
":",
"new",
"=",
"self",
".",
"_decode_input_string",
"(",
"data",
")",
"if",
"len",
"(",
"new",
")",
"<=",
"16",
... | The fixed string is used to identify a particular Yubikey device.
The fixed string is referred to as the 'Token Identifier' in OATH-HOTP mode.
The length of the fixed string can be set between 0 and 16 bytes.
Tip: This can also be used to extend the length of a static password. | [
"The",
"fixed",
"string",
"is",
"used",
"to",
"identify",
"a",
"particular",
"Yubikey",
"device",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L188-L205 | train | 199,075 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.enable_extended_scan_code_mode | def enable_extended_scan_code_mode(self):
"""
Extended scan code mode means the Yubikey will output the bytes in
the 'fixed string' as scan codes, without modhex encoding the data.
Because of the way this is stored in the config flags, it is not
possible to disable this option once it is enabled (of course, you
can abort config update or reprogram the YubiKey again).
Requires YubiKey 2.x.
"""
if not self.capabilities.have_extended_scan_code_mode():
raise
self._require_version(major=2)
self.config_flag('SHORT_TICKET', True)
self.config_flag('STATIC_TICKET', False) | python | def enable_extended_scan_code_mode(self):
"""
Extended scan code mode means the Yubikey will output the bytes in
the 'fixed string' as scan codes, without modhex encoding the data.
Because of the way this is stored in the config flags, it is not
possible to disable this option once it is enabled (of course, you
can abort config update or reprogram the YubiKey again).
Requires YubiKey 2.x.
"""
if not self.capabilities.have_extended_scan_code_mode():
raise
self._require_version(major=2)
self.config_flag('SHORT_TICKET', True)
self.config_flag('STATIC_TICKET', False) | [
"def",
"enable_extended_scan_code_mode",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_extended_scan_code_mode",
"(",
")",
":",
"raise",
"self",
".",
"_require_version",
"(",
"major",
"=",
"2",
")",
"self",
".",
"config_flag",
"("... | Extended scan code mode means the Yubikey will output the bytes in
the 'fixed string' as scan codes, without modhex encoding the data.
Because of the way this is stored in the config flags, it is not
possible to disable this option once it is enabled (of course, you
can abort config update or reprogram the YubiKey again).
Requires YubiKey 2.x. | [
"Extended",
"scan",
"code",
"mode",
"means",
"the",
"Yubikey",
"will",
"output",
"the",
"bytes",
"in",
"the",
"fixed",
"string",
"as",
"scan",
"codes",
"without",
"modhex",
"encoding",
"the",
"data",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L207-L222 | train | 199,076 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.aes_key | def aes_key(self, data):
"""
AES128 key to program into YubiKey.
Supply data as either a raw string, or a hexlified string prefixed by 'h:'.
The result, after any hex decoding, must be 16 bytes.
"""
old = self.key
if data:
new = self._decode_input_string(data)
if len(new) == 16:
self.key = new
else:
raise yubico_exception.InputError('AES128 key must be exactly 16 bytes')
return old | python | def aes_key(self, data):
"""
AES128 key to program into YubiKey.
Supply data as either a raw string, or a hexlified string prefixed by 'h:'.
The result, after any hex decoding, must be 16 bytes.
"""
old = self.key
if data:
new = self._decode_input_string(data)
if len(new) == 16:
self.key = new
else:
raise yubico_exception.InputError('AES128 key must be exactly 16 bytes')
return old | [
"def",
"aes_key",
"(",
"self",
",",
"data",
")",
":",
"old",
"=",
"self",
".",
"key",
"if",
"data",
":",
"new",
"=",
"self",
".",
"_decode_input_string",
"(",
"data",
")",
"if",
"len",
"(",
"new",
")",
"==",
"16",
":",
"self",
".",
"key",
"=",
... | AES128 key to program into YubiKey.
Supply data as either a raw string, or a hexlified string prefixed by 'h:'.
The result, after any hex decoding, must be 16 bytes. | [
"AES128",
"key",
"to",
"program",
"into",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L240-L255 | train | 199,077 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.unlock_key | def unlock_key(self, data):
"""
Access code to allow re-programming of your YubiKey.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 6 bytes.
"""
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 6:
self.unlock_code = new
if not self.access_code:
# Don't reset the access code when programming, unless that seems
# to be the intent of the calling program.
self.access_code = new
else:
raise yubico_exception.InputError('Unlock key must be exactly 6 bytes') | python | def unlock_key(self, data):
"""
Access code to allow re-programming of your YubiKey.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 6 bytes.
"""
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 6:
self.unlock_code = new
if not self.access_code:
# Don't reset the access code when programming, unless that seems
# to be the intent of the calling program.
self.access_code = new
else:
raise yubico_exception.InputError('Unlock key must be exactly 6 bytes') | [
"def",
"unlock_key",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"startswith",
"(",
"b'h:'",
")",
":",
"new",
"=",
"binascii",
".",
"unhexlify",
"(",
"data",
"[",
"2",
":",
"]",
")",
"else",
":",
"new",
"=",
"data",
"if",
"len",
"(",
... | Access code to allow re-programming of your YubiKey.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 6 bytes. | [
"Access",
"code",
"to",
"allow",
"re",
"-",
"programming",
"of",
"your",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L257-L275 | train | 199,078 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.access_key | def access_key(self, data):
"""
Set a new access code which will be required for future re-programmings of your YubiKey.
Supply data as either a raw string, or a hexlified string prefixed by 'h:'.
The result, after any hex decoding, must be 6 bytes.
"""
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 6:
self.access_code = new
else:
raise yubico_exception.InputError('Access key must be exactly 6 bytes') | python | def access_key(self, data):
"""
Set a new access code which will be required for future re-programmings of your YubiKey.
Supply data as either a raw string, or a hexlified string prefixed by 'h:'.
The result, after any hex decoding, must be 6 bytes.
"""
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 6:
self.access_code = new
else:
raise yubico_exception.InputError('Access key must be exactly 6 bytes') | [
"def",
"access_key",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"startswith",
"(",
"b'h:'",
")",
":",
"new",
"=",
"binascii",
".",
"unhexlify",
"(",
"data",
"[",
"2",
":",
"]",
")",
"else",
":",
"new",
"=",
"data",
"if",
"len",
"(",
... | Set a new access code which will be required for future re-programmings of your YubiKey.
Supply data as either a raw string, or a hexlified string prefixed by 'h:'.
The result, after any hex decoding, must be 6 bytes. | [
"Set",
"a",
"new",
"access",
"code",
"which",
"will",
"be",
"required",
"for",
"future",
"re",
"-",
"programmings",
"of",
"your",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L277-L291 | train | 199,079 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.mode_yubikey_otp | def mode_yubikey_otp(self, private_uid, aes_key):
"""
Set the YubiKey up for standard OTP validation.
"""
if not self.capabilities.have_yubico_OTP():
raise yubikey_base.YubiKeyVersionError('Yubico OTP not available in %s version %d.%d' \
% (self.capabilities.model, self.ykver[0], self.ykver[1]))
if private_uid.startswith(b'h:'):
private_uid = binascii.unhexlify(private_uid[2:])
if len(private_uid) != yubikey_defs.UID_SIZE:
raise yubico_exception.InputError('Private UID must be %i bytes' % (yubikey_defs.UID_SIZE))
self._change_mode('YUBIKEY_OTP', major=0, minor=9)
self.uid = private_uid
self.aes_key(aes_key) | python | def mode_yubikey_otp(self, private_uid, aes_key):
"""
Set the YubiKey up for standard OTP validation.
"""
if not self.capabilities.have_yubico_OTP():
raise yubikey_base.YubiKeyVersionError('Yubico OTP not available in %s version %d.%d' \
% (self.capabilities.model, self.ykver[0], self.ykver[1]))
if private_uid.startswith(b'h:'):
private_uid = binascii.unhexlify(private_uid[2:])
if len(private_uid) != yubikey_defs.UID_SIZE:
raise yubico_exception.InputError('Private UID must be %i bytes' % (yubikey_defs.UID_SIZE))
self._change_mode('YUBIKEY_OTP', major=0, minor=9)
self.uid = private_uid
self.aes_key(aes_key) | [
"def",
"mode_yubikey_otp",
"(",
"self",
",",
"private_uid",
",",
"aes_key",
")",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_yubico_OTP",
"(",
")",
":",
"raise",
"yubikey_base",
".",
"YubiKeyVersionError",
"(",
"'Yubico OTP not available in %s version ... | Set the YubiKey up for standard OTP validation. | [
"Set",
"the",
"YubiKey",
"up",
"for",
"standard",
"OTP",
"validation",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L293-L307 | train | 199,080 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.mode_oath_hotp | def mode_oath_hotp(self, secret, digits=6, factor_seed=None, omp=0x0, tt=0x0, mui=''):
"""
Set the YubiKey up for OATH-HOTP operation.
Requires YubiKey 2.1.
"""
if not self.capabilities.have_OATH('HOTP'):
raise yubikey_base.YubiKeyVersionError('OATH HOTP not available in %s version %d.%d' \
% (self.capabilities.model, self.ykver[0], self.ykver[1]))
if digits != 6 and digits != 8:
raise yubico_exception.InputError('OATH-HOTP digits must be 6 or 8')
self._change_mode('OATH_HOTP', major=2, minor=1)
self._set_20_bytes_key(secret)
if digits == 8:
self.config_flag('OATH_HOTP8', True)
if omp or tt or mui:
decoded_mui = self._decode_input_string(mui)
fixed = yubico_util.chr_byte(omp) + yubico_util.chr_byte(tt) + decoded_mui
self.fixed_string(fixed)
if factor_seed:
self.uid = self.uid + struct.pack('<H', factor_seed) | python | def mode_oath_hotp(self, secret, digits=6, factor_seed=None, omp=0x0, tt=0x0, mui=''):
"""
Set the YubiKey up for OATH-HOTP operation.
Requires YubiKey 2.1.
"""
if not self.capabilities.have_OATH('HOTP'):
raise yubikey_base.YubiKeyVersionError('OATH HOTP not available in %s version %d.%d' \
% (self.capabilities.model, self.ykver[0], self.ykver[1]))
if digits != 6 and digits != 8:
raise yubico_exception.InputError('OATH-HOTP digits must be 6 or 8')
self._change_mode('OATH_HOTP', major=2, minor=1)
self._set_20_bytes_key(secret)
if digits == 8:
self.config_flag('OATH_HOTP8', True)
if omp or tt or mui:
decoded_mui = self._decode_input_string(mui)
fixed = yubico_util.chr_byte(omp) + yubico_util.chr_byte(tt) + decoded_mui
self.fixed_string(fixed)
if factor_seed:
self.uid = self.uid + struct.pack('<H', factor_seed) | [
"def",
"mode_oath_hotp",
"(",
"self",
",",
"secret",
",",
"digits",
"=",
"6",
",",
"factor_seed",
"=",
"None",
",",
"omp",
"=",
"0x0",
",",
"tt",
"=",
"0x0",
",",
"mui",
"=",
"''",
")",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_OATH... | Set the YubiKey up for OATH-HOTP operation.
Requires YubiKey 2.1. | [
"Set",
"the",
"YubiKey",
"up",
"for",
"OATH",
"-",
"HOTP",
"operation",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L309-L330 | train | 199,081 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.mode_challenge_response | def mode_challenge_response(self, secret, type='HMAC', variable=True, require_button=False):
"""
Set the YubiKey up for challenge-response operation.
`type' can be 'HMAC' or 'OTP'.
`variable' is only applicable to type 'HMAC'.
For type HMAC, `secret' is expected to be 20 bytes (160 bits).
For type OTP, `secret' is expected to be 16 bytes (128 bits).
Requires YubiKey 2.2.
"""
if not type.upper() in ['HMAC', 'OTP']:
raise yubico_exception.InputError('Invalid \'type\' (%s)' % type)
if not self.capabilities.have_challenge_response(type.upper()):
raise yubikey_base.YubiKeyVersionError('%s Challenge-Response not available in %s version %d.%d' \
% (type.upper(), self.capabilities.model, \
self.ykver[0], self.ykver[1]))
self._change_mode('CHAL_RESP', major=2, minor=2)
if type.upper() == 'HMAC':
self.config_flag('CHAL_HMAC', True)
self.config_flag('HMAC_LT64', variable)
self._set_20_bytes_key(secret)
else:
# type is 'OTP', checked above
self.config_flag('CHAL_YUBICO', True)
self.aes_key(secret)
self.config_flag('CHAL_BTN_TRIG', require_button) | python | def mode_challenge_response(self, secret, type='HMAC', variable=True, require_button=False):
"""
Set the YubiKey up for challenge-response operation.
`type' can be 'HMAC' or 'OTP'.
`variable' is only applicable to type 'HMAC'.
For type HMAC, `secret' is expected to be 20 bytes (160 bits).
For type OTP, `secret' is expected to be 16 bytes (128 bits).
Requires YubiKey 2.2.
"""
if not type.upper() in ['HMAC', 'OTP']:
raise yubico_exception.InputError('Invalid \'type\' (%s)' % type)
if not self.capabilities.have_challenge_response(type.upper()):
raise yubikey_base.YubiKeyVersionError('%s Challenge-Response not available in %s version %d.%d' \
% (type.upper(), self.capabilities.model, \
self.ykver[0], self.ykver[1]))
self._change_mode('CHAL_RESP', major=2, minor=2)
if type.upper() == 'HMAC':
self.config_flag('CHAL_HMAC', True)
self.config_flag('HMAC_LT64', variable)
self._set_20_bytes_key(secret)
else:
# type is 'OTP', checked above
self.config_flag('CHAL_YUBICO', True)
self.aes_key(secret)
self.config_flag('CHAL_BTN_TRIG', require_button) | [
"def",
"mode_challenge_response",
"(",
"self",
",",
"secret",
",",
"type",
"=",
"'HMAC'",
",",
"variable",
"=",
"True",
",",
"require_button",
"=",
"False",
")",
":",
"if",
"not",
"type",
".",
"upper",
"(",
")",
"in",
"[",
"'HMAC'",
",",
"'OTP'",
"]",
... | Set the YubiKey up for challenge-response operation.
`type' can be 'HMAC' or 'OTP'.
`variable' is only applicable to type 'HMAC'.
For type HMAC, `secret' is expected to be 20 bytes (160 bits).
For type OTP, `secret' is expected to be 16 bytes (128 bits).
Requires YubiKey 2.2. | [
"Set",
"the",
"YubiKey",
"up",
"for",
"challenge",
"-",
"response",
"operation",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L332-L360 | train | 199,082 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.ticket_flag | def ticket_flag(self, which, new=None):
"""
Get or set a ticket flag.
'which' can be either a string ('APPEND_CR' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, TicketFlags)
if flag:
if not self.capabilities.have_ticket_flag(flag):
raise yubikey_base.YubiKeyVersionError('Ticket flag %s requires %s, and this is %s %d.%d'
% (which, flag.req_string(self.capabilities.model), \
self.capabilities.model, self.ykver[0], self.ykver[1]))
req_major, req_minor = flag.req_version()
self._require_version(major=req_major, minor=req_minor)
value = flag.to_integer()
else:
if type(which) is not int:
raise yubico_exception.InputError('Unknown non-integer TicketFlag (%s)' % which)
value = which
return self.ticket_flags.get_set(value, new) | python | def ticket_flag(self, which, new=None):
"""
Get or set a ticket flag.
'which' can be either a string ('APPEND_CR' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, TicketFlags)
if flag:
if not self.capabilities.have_ticket_flag(flag):
raise yubikey_base.YubiKeyVersionError('Ticket flag %s requires %s, and this is %s %d.%d'
% (which, flag.req_string(self.capabilities.model), \
self.capabilities.model, self.ykver[0], self.ykver[1]))
req_major, req_minor = flag.req_version()
self._require_version(major=req_major, minor=req_minor)
value = flag.to_integer()
else:
if type(which) is not int:
raise yubico_exception.InputError('Unknown non-integer TicketFlag (%s)' % which)
value = which
return self.ticket_flags.get_set(value, new) | [
"def",
"ticket_flag",
"(",
"self",
",",
"which",
",",
"new",
"=",
"None",
")",
":",
"flag",
"=",
"_get_flag",
"(",
"which",
",",
"TicketFlags",
")",
"if",
"flag",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_ticket_flag",
"(",
"flag",
")",... | Get or set a ticket flag.
'which' can be either a string ('APPEND_CR' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing. | [
"Get",
"or",
"set",
"a",
"ticket",
"flag",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L362-L383 | train | 199,083 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.config_flag | def config_flag(self, which, new=None):
"""
Get or set a config flag.
'which' can be either a string ('PACING_20MS' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, ConfigFlags)
if flag:
if not self.capabilities.have_config_flag(flag):
raise yubikey_base.YubiKeyVersionError('Config flag %s requires %s, and this is %s %d.%d'
% (which, flag.req_string(self.capabilities.model), \
self.capabilities.model, self.ykver[0], self.ykver[1]))
req_major, req_minor = flag.req_version()
self._require_version(major=req_major, minor=req_minor)
value = flag.to_integer()
else:
if type(which) is not int:
raise yubico_exception.InputError('Unknown non-integer ConfigFlag (%s)' % which)
value = which
return self.config_flags.get_set(value, new) | python | def config_flag(self, which, new=None):
"""
Get or set a config flag.
'which' can be either a string ('PACING_20MS' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, ConfigFlags)
if flag:
if not self.capabilities.have_config_flag(flag):
raise yubikey_base.YubiKeyVersionError('Config flag %s requires %s, and this is %s %d.%d'
% (which, flag.req_string(self.capabilities.model), \
self.capabilities.model, self.ykver[0], self.ykver[1]))
req_major, req_minor = flag.req_version()
self._require_version(major=req_major, minor=req_minor)
value = flag.to_integer()
else:
if type(which) is not int:
raise yubico_exception.InputError('Unknown non-integer ConfigFlag (%s)' % which)
value = which
return self.config_flags.get_set(value, new) | [
"def",
"config_flag",
"(",
"self",
",",
"which",
",",
"new",
"=",
"None",
")",
":",
"flag",
"=",
"_get_flag",
"(",
"which",
",",
"ConfigFlags",
")",
"if",
"flag",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_config_flag",
"(",
"flag",
")",... | Get or set a config flag.
'which' can be either a string ('PACING_20MS' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing. | [
"Get",
"or",
"set",
"a",
"config",
"flag",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L385-L406 | train | 199,084 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig.extended_flag | def extended_flag(self, which, new=None):
"""
Get or set a extended flag.
'which' can be either a string ('SERIAL_API_VISIBLE' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, ExtendedFlags)
if flag:
if not self.capabilities.have_extended_flag(flag):
raise yubikey_base.YubiKeyVersionError('Extended flag %s requires %s, and this is %s %d.%d'
% (which, flag.req_string(self.capabilities.model), \
self.capabilities.model, self.ykver[0], self.ykver[1]))
req_major, req_minor = flag.req_version()
self._require_version(major=req_major, minor=req_minor)
value = flag.to_integer()
else:
if type(which) is not int:
raise yubico_exception.InputError('Unknown non-integer ExtendedFlag (%s)' % which)
value = which
return self.extended_flags.get_set(value, new) | python | def extended_flag(self, which, new=None):
"""
Get or set a extended flag.
'which' can be either a string ('SERIAL_API_VISIBLE' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing.
"""
flag = _get_flag(which, ExtendedFlags)
if flag:
if not self.capabilities.have_extended_flag(flag):
raise yubikey_base.YubiKeyVersionError('Extended flag %s requires %s, and this is %s %d.%d'
% (which, flag.req_string(self.capabilities.model), \
self.capabilities.model, self.ykver[0], self.ykver[1]))
req_major, req_minor = flag.req_version()
self._require_version(major=req_major, minor=req_minor)
value = flag.to_integer()
else:
if type(which) is not int:
raise yubico_exception.InputError('Unknown non-integer ExtendedFlag (%s)' % which)
value = which
return self.extended_flags.get_set(value, new) | [
"def",
"extended_flag",
"(",
"self",
",",
"which",
",",
"new",
"=",
"None",
")",
":",
"flag",
"=",
"_get_flag",
"(",
"which",
",",
"ExtendedFlags",
")",
"if",
"flag",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_extended_flag",
"(",
"flag",
... | Get or set a extended flag.
'which' can be either a string ('SERIAL_API_VISIBLE' etc.), or an integer.
You should ALWAYS use a string, unless you really know what you are doing. | [
"Get",
"or",
"set",
"a",
"extended",
"flag",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L408-L429 | train | 199,085 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig._require_version | def _require_version(self, major, minor=0):
""" Update the minimum version of YubiKey this configuration can be applied to. """
new_ver = (major, minor)
if self.ykver and new_ver > self.ykver:
raise yubikey_base.YubiKeyVersionError('Configuration requires YubiKey %d.%d, and this is %d.%d'
% (major, minor, self.ykver[0], self.ykver[1]))
if new_ver > self.yk_req_version:
self.yk_req_version = new_ver | python | def _require_version(self, major, minor=0):
""" Update the minimum version of YubiKey this configuration can be applied to. """
new_ver = (major, minor)
if self.ykver and new_ver > self.ykver:
raise yubikey_base.YubiKeyVersionError('Configuration requires YubiKey %d.%d, and this is %d.%d'
% (major, minor, self.ykver[0], self.ykver[1]))
if new_ver > self.yk_req_version:
self.yk_req_version = new_ver | [
"def",
"_require_version",
"(",
"self",
",",
"major",
",",
"minor",
"=",
"0",
")",
":",
"new_ver",
"=",
"(",
"major",
",",
"minor",
")",
"if",
"self",
".",
"ykver",
"and",
"new_ver",
">",
"self",
".",
"ykver",
":",
"raise",
"yubikey_base",
".",
"Yubi... | Update the minimum version of YubiKey this configuration can be applied to. | [
"Update",
"the",
"minimum",
"version",
"of",
"YubiKey",
"this",
"configuration",
"can",
"be",
"applied",
"to",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L499-L506 | train | 199,086 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig._change_mode | def _change_mode(self, mode, major, minor):
""" Change mode of operation, with some sanity checks. """
if self._mode:
if self._mode != mode:
raise RuntimeError('Can\'t change mode (from %s to %s)' % (self._mode, mode))
self._require_version(major=major, minor=minor)
self._mode = mode
# when setting mode, we reset all flags
self.ticket_flags = YubiKeyConfigBits(0x0)
self.config_flags = YubiKeyConfigBits(0x0)
self.extended_flags = YubiKeyConfigBits(0x0)
if mode != 'YUBIKEY_OTP':
self.ticket_flag(mode, True) | python | def _change_mode(self, mode, major, minor):
""" Change mode of operation, with some sanity checks. """
if self._mode:
if self._mode != mode:
raise RuntimeError('Can\'t change mode (from %s to %s)' % (self._mode, mode))
self._require_version(major=major, minor=minor)
self._mode = mode
# when setting mode, we reset all flags
self.ticket_flags = YubiKeyConfigBits(0x0)
self.config_flags = YubiKeyConfigBits(0x0)
self.extended_flags = YubiKeyConfigBits(0x0)
if mode != 'YUBIKEY_OTP':
self.ticket_flag(mode, True) | [
"def",
"_change_mode",
"(",
"self",
",",
"mode",
",",
"major",
",",
"minor",
")",
":",
"if",
"self",
".",
"_mode",
":",
"if",
"self",
".",
"_mode",
"!=",
"mode",
":",
"raise",
"RuntimeError",
"(",
"'Can\\'t change mode (from %s to %s)'",
"%",
"(",
"self",
... | Change mode of operation, with some sanity checks. | [
"Change",
"mode",
"of",
"operation",
"with",
"some",
"sanity",
"checks",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L518-L530 | train | 199,087 |
Yubico/python-yubico | yubico/yubikey_config.py | YubiKeyConfig._set_20_bytes_key | def _set_20_bytes_key(self, data):
"""
Set a 20 bytes key. This is used in CHAL_HMAC and OATH_HOTP mode.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 20 bytes.
"""
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 20:
self.key = new[:16]
self.uid = new[16:]
else:
raise yubico_exception.InputError('HMAC key must be exactly 20 bytes') | python | def _set_20_bytes_key(self, data):
"""
Set a 20 bytes key. This is used in CHAL_HMAC and OATH_HOTP mode.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 20 bytes.
"""
if data.startswith(b'h:'):
new = binascii.unhexlify(data[2:])
else:
new = data
if len(new) == 20:
self.key = new[:16]
self.uid = new[16:]
else:
raise yubico_exception.InputError('HMAC key must be exactly 20 bytes') | [
"def",
"_set_20_bytes_key",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"startswith",
"(",
"b'h:'",
")",
":",
"new",
"=",
"binascii",
".",
"unhexlify",
"(",
"data",
"[",
"2",
":",
"]",
")",
"else",
":",
"new",
"=",
"data",
"if",
"len",
... | Set a 20 bytes key. This is used in CHAL_HMAC and OATH_HOTP mode.
Supply data as either a raw bytestring, or a hexlified bytestring prefixed by 'h:'.
The result, after any hex decoding, must be 20 bytes. | [
"Set",
"a",
"20",
"bytes",
"key",
".",
"This",
"is",
"used",
"in",
"CHAL_HMAC",
"and",
"OATH_HOTP",
"mode",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L532-L547 | train | 199,088 |
Yubico/python-yubico | yubico/yubico_util.py | modhex_decode | def modhex_decode(data):
""" Convert a modhex bytestring to ordinary hex. """
try:
maketrans = string.maketrans
except AttributeError:
# Python 3
maketrans = bytes.maketrans
t_map = maketrans(b"cbdefghijklnrtuv", b"0123456789abcdef")
return data.translate(t_map) | python | def modhex_decode(data):
""" Convert a modhex bytestring to ordinary hex. """
try:
maketrans = string.maketrans
except AttributeError:
# Python 3
maketrans = bytes.maketrans
t_map = maketrans(b"cbdefghijklnrtuv", b"0123456789abcdef")
return data.translate(t_map) | [
"def",
"modhex_decode",
"(",
"data",
")",
":",
"try",
":",
"maketrans",
"=",
"string",
".",
"maketrans",
"except",
"AttributeError",
":",
"# Python 3",
"maketrans",
"=",
"bytes",
".",
"maketrans",
"t_map",
"=",
"maketrans",
"(",
"b\"cbdefghijklnrtuv\"",
",",
"... | Convert a modhex bytestring to ordinary hex. | [
"Convert",
"a",
"modhex",
"bytestring",
"to",
"ordinary",
"hex",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubico_util.py#L128-L136 | train | 199,089 |
Yubico/python-yubico | yubico/yubico_util.py | hotp_truncate | def hotp_truncate(hmac_result, length=6):
""" Perform the HOTP Algorithm truncating.
Input is a bytestring.
"""
if len(hmac_result) != 20:
raise yubico_exception.YubicoError("HMAC-SHA-1 not 20 bytes long")
offset = ord_byte(hmac_result[19]) & 0xf
bin_code = (ord_byte(hmac_result[offset]) & 0x7f) << 24 \
| (ord_byte(hmac_result[offset+1]) & 0xff) << 16 \
| (ord_byte(hmac_result[offset+2]) & 0xff) << 8 \
| (ord_byte(hmac_result[offset+3]) & 0xff)
return bin_code % (10 ** length) | python | def hotp_truncate(hmac_result, length=6):
""" Perform the HOTP Algorithm truncating.
Input is a bytestring.
"""
if len(hmac_result) != 20:
raise yubico_exception.YubicoError("HMAC-SHA-1 not 20 bytes long")
offset = ord_byte(hmac_result[19]) & 0xf
bin_code = (ord_byte(hmac_result[offset]) & 0x7f) << 24 \
| (ord_byte(hmac_result[offset+1]) & 0xff) << 16 \
| (ord_byte(hmac_result[offset+2]) & 0xff) << 8 \
| (ord_byte(hmac_result[offset+3]) & 0xff)
return bin_code % (10 ** length) | [
"def",
"hotp_truncate",
"(",
"hmac_result",
",",
"length",
"=",
"6",
")",
":",
"if",
"len",
"(",
"hmac_result",
")",
"!=",
"20",
":",
"raise",
"yubico_exception",
".",
"YubicoError",
"(",
"\"HMAC-SHA-1 not 20 bytes long\"",
")",
"offset",
"=",
"ord_byte",
"(",... | Perform the HOTP Algorithm truncating.
Input is a bytestring. | [
"Perform",
"the",
"HOTP",
"Algorithm",
"truncating",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubico_util.py#L138-L150 | train | 199,090 |
Yubico/python-yubico | yubico/yubico_util.py | tlv_parse | def tlv_parse(data):
""" Parses a bytestring of TLV values into a dict with the tags as keys."""
parsed = {}
while data:
t, l, data = ord_byte(data[0]), ord_byte(data[1]), data[2:]
parsed[t], data = data[:l], data[l:]
return parsed | python | def tlv_parse(data):
""" Parses a bytestring of TLV values into a dict with the tags as keys."""
parsed = {}
while data:
t, l, data = ord_byte(data[0]), ord_byte(data[1]), data[2:]
parsed[t], data = data[:l], data[l:]
return parsed | [
"def",
"tlv_parse",
"(",
"data",
")",
":",
"parsed",
"=",
"{",
"}",
"while",
"data",
":",
"t",
",",
"l",
",",
"data",
"=",
"ord_byte",
"(",
"data",
"[",
"0",
"]",
")",
",",
"ord_byte",
"(",
"data",
"[",
"1",
"]",
")",
",",
"data",
"[",
"2",
... | Parses a bytestring of TLV values into a dict with the tags as keys. | [
"Parses",
"a",
"bytestring",
"of",
"TLV",
"values",
"into",
"a",
"dict",
"with",
"the",
"tags",
"as",
"keys",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubico_util.py#L152-L158 | train | 199,091 |
Yubico/python-yubico | yubico/yubico_util.py | DumpColors.get | def get(self, what):
"""
Get the ANSI code for 'what'
Returns an empty string if disabled/not found
"""
if self.enabled:
if what in self.colors:
return self.colors[what]
return '' | python | def get(self, what):
"""
Get the ANSI code for 'what'
Returns an empty string if disabled/not found
"""
if self.enabled:
if what in self.colors:
return self.colors[what]
return '' | [
"def",
"get",
"(",
"self",
",",
"what",
")",
":",
"if",
"self",
".",
"enabled",
":",
"if",
"what",
"in",
"self",
".",
"colors",
":",
"return",
"self",
".",
"colors",
"[",
"what",
"]",
"return",
"''"
] | Get the ANSI code for 'what'
Returns an empty string if disabled/not found | [
"Get",
"the",
"ANSI",
"code",
"for",
"what"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubico_util.py#L76-L85 | train | 199,092 |
Yubico/python-yubico | yubico/yubikey_defs.py | MODE.all | def all(cls, otp=False, ccid=False, u2f=False):
"""Returns a set of all USB modes, with optional filtering"""
modes = set([
cls.OTP,
cls.CCID,
cls.OTP_CCID,
cls.U2F,
cls.OTP_U2F,
cls.U2F_CCID,
cls.OTP_U2F_CCID
])
if otp:
modes.difference_update(set([
cls.CCID,
cls.U2F,
cls.U2F_CCID
]))
if ccid:
modes.difference_update(set([
cls.OTP,
cls.U2F,
cls.OTP_U2F
]))
if u2f:
modes.difference_update(set([
cls.OTP,
cls.CCID,
cls.OTP_CCID
]))
return modes | python | def all(cls, otp=False, ccid=False, u2f=False):
"""Returns a set of all USB modes, with optional filtering"""
modes = set([
cls.OTP,
cls.CCID,
cls.OTP_CCID,
cls.U2F,
cls.OTP_U2F,
cls.U2F_CCID,
cls.OTP_U2F_CCID
])
if otp:
modes.difference_update(set([
cls.CCID,
cls.U2F,
cls.U2F_CCID
]))
if ccid:
modes.difference_update(set([
cls.OTP,
cls.U2F,
cls.OTP_U2F
]))
if u2f:
modes.difference_update(set([
cls.OTP,
cls.CCID,
cls.OTP_CCID
]))
return modes | [
"def",
"all",
"(",
"cls",
",",
"otp",
"=",
"False",
",",
"ccid",
"=",
"False",
",",
"u2f",
"=",
"False",
")",
":",
"modes",
"=",
"set",
"(",
"[",
"cls",
".",
"OTP",
",",
"cls",
".",
"CCID",
",",
"cls",
".",
"OTP_CCID",
",",
"cls",
".",
"U2F",... | Returns a set of all USB modes, with optional filtering | [
"Returns",
"a",
"set",
"of",
"all",
"USB",
"modes",
"with",
"optional",
"filtering"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_defs.py#L78-L111 | train | 199,093 |
Yubico/python-yubico | yubico/yubikey_defs.py | PID.all | def all(cls, otp=False, ccid=False, u2f=False):
"""Returns a set of all PIDs, with optional filtering"""
pids = set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_OTP_CCID,
cls.NEO_CCID,
cls.NEO_U2F,
cls.NEO_OTP_U2F,
cls.NEO_U2F_CCID,
cls.NEO_OTP_U2F_CCID,
cls.NEO_SKY,
cls.YK4_OTP,
cls.YK4_U2F,
cls.YK4_OTP_U2F,
cls.YK4_CCID,
cls.YK4_OTP_CCID,
cls.YK4_U2F_CCID,
cls.YK4_OTP_U2F_CCID,
cls.PLUS_U2F_OTP
])
if otp:
pids.difference_update(set([
cls.NEO_CCID,
cls.NEO_U2F,
cls.NEO_U2F_CCID,
cls.NEO_SKY,
cls.YK4_U2F,
cls.YK4_CCID,
cls.YK4_U2F_CCID
]))
if ccid:
pids.difference_update(set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_U2F,
cls.NEO_OTP_U2F,
cls.NEO_SKY,
cls.YK4_OTP,
cls.YK4_U2F,
cls.YK4_OTP_U2F,
cls.PLUS_U2F_OTP
]))
if u2f:
pids.difference_update(set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_OTP_CCID,
cls.NEO_CCID,
cls.YK4_OTP,
cls.YK4_CCID,
cls.YK4_OTP_CCID
]))
return pids | python | def all(cls, otp=False, ccid=False, u2f=False):
"""Returns a set of all PIDs, with optional filtering"""
pids = set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_OTP_CCID,
cls.NEO_CCID,
cls.NEO_U2F,
cls.NEO_OTP_U2F,
cls.NEO_U2F_CCID,
cls.NEO_OTP_U2F_CCID,
cls.NEO_SKY,
cls.YK4_OTP,
cls.YK4_U2F,
cls.YK4_OTP_U2F,
cls.YK4_CCID,
cls.YK4_OTP_CCID,
cls.YK4_U2F_CCID,
cls.YK4_OTP_U2F_CCID,
cls.PLUS_U2F_OTP
])
if otp:
pids.difference_update(set([
cls.NEO_CCID,
cls.NEO_U2F,
cls.NEO_U2F_CCID,
cls.NEO_SKY,
cls.YK4_U2F,
cls.YK4_CCID,
cls.YK4_U2F_CCID
]))
if ccid:
pids.difference_update(set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_U2F,
cls.NEO_OTP_U2F,
cls.NEO_SKY,
cls.YK4_OTP,
cls.YK4_U2F,
cls.YK4_OTP_U2F,
cls.PLUS_U2F_OTP
]))
if u2f:
pids.difference_update(set([
cls.YUBIKEY,
cls.NEO_OTP,
cls.NEO_OTP_CCID,
cls.NEO_CCID,
cls.YK4_OTP,
cls.YK4_CCID,
cls.YK4_OTP_CCID
]))
return pids | [
"def",
"all",
"(",
"cls",
",",
"otp",
"=",
"False",
",",
"ccid",
"=",
"False",
",",
"u2f",
"=",
"False",
")",
":",
"pids",
"=",
"set",
"(",
"[",
"cls",
".",
"YUBIKEY",
",",
"cls",
".",
"NEO_OTP",
",",
"cls",
".",
"NEO_OTP_CCID",
",",
"cls",
"."... | Returns a set of all PIDs, with optional filtering | [
"Returns",
"a",
"set",
"of",
"all",
"PIDs",
"with",
"optional",
"filtering"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_defs.py#L142-L199 | train | 199,094 |
Yubico/python-yubico | yubico/yubikey_frame.py | YubiKeyFrame.to_string | def to_string(self):
"""
Return the frame as a 70 byte string.
"""
# From ykdef.h :
#
# // Frame structure
# #define SLOT_DATA_SIZE 64
# typedef struct {
# unsigned char payload[SLOT_DATA_SIZE];
# unsigned char slot;
# unsigned short crc;
# unsigned char filler[3];
# } YKFRAME;
filler = b''
return struct.pack('<64sBH3s',
self.payload, self.command, self.crc, filler) | python | def to_string(self):
"""
Return the frame as a 70 byte string.
"""
# From ykdef.h :
#
# // Frame structure
# #define SLOT_DATA_SIZE 64
# typedef struct {
# unsigned char payload[SLOT_DATA_SIZE];
# unsigned char slot;
# unsigned short crc;
# unsigned char filler[3];
# } YKFRAME;
filler = b''
return struct.pack('<64sBH3s',
self.payload, self.command, self.crc, filler) | [
"def",
"to_string",
"(",
"self",
")",
":",
"# From ykdef.h :",
"#",
"# // Frame structure",
"# #define SLOT_DATA_SIZE 64",
"# typedef struct {",
"# unsigned char payload[SLOT_DATA_SIZE];",
"# unsigned char slot;",
"# unsigned short crc;",
"# unsigned char filler[3];",
... | Return the frame as a 70 byte string. | [
"Return",
"the",
"frame",
"as",
"a",
"70",
"byte",
"string",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_frame.py#L52-L68 | train | 199,095 |
Yubico/python-yubico | yubico/yubikey_frame.py | YubiKeyFrame.to_feature_reports | def to_feature_reports(self, debug=False):
"""
Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey.
"""
rest = self.to_string()
seq = 0
out = []
# When sending a frame to the YubiKey, we can (should) remove any
# 7-byte serie that only consists of '\x00', besides the first
# and last serie.
while rest:
this, rest = rest[:7], rest[7:]
if seq > 0 and rest:
# never skip first or last serie
if this != b'\x00\x00\x00\x00\x00\x00\x00':
this += yubico_util.chr_byte(yubikey_defs.SLOT_WRITE_FLAG + seq)
out.append(self._debug_string(debug, this))
else:
this += yubico_util.chr_byte(yubikey_defs.SLOT_WRITE_FLAG + seq)
out.append(self._debug_string(debug, this))
seq += 1
return out | python | def to_feature_reports(self, debug=False):
"""
Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey.
"""
rest = self.to_string()
seq = 0
out = []
# When sending a frame to the YubiKey, we can (should) remove any
# 7-byte serie that only consists of '\x00', besides the first
# and last serie.
while rest:
this, rest = rest[:7], rest[7:]
if seq > 0 and rest:
# never skip first or last serie
if this != b'\x00\x00\x00\x00\x00\x00\x00':
this += yubico_util.chr_byte(yubikey_defs.SLOT_WRITE_FLAG + seq)
out.append(self._debug_string(debug, this))
else:
this += yubico_util.chr_byte(yubikey_defs.SLOT_WRITE_FLAG + seq)
out.append(self._debug_string(debug, this))
seq += 1
return out | [
"def",
"to_feature_reports",
"(",
"self",
",",
"debug",
"=",
"False",
")",
":",
"rest",
"=",
"self",
".",
"to_string",
"(",
")",
"seq",
"=",
"0",
"out",
"=",
"[",
"]",
"# When sending a frame to the YubiKey, we can (should) remove any",
"# 7-byte serie that only con... | Return the frame as an array of 8-byte parts, ready to be sent to a YubiKey. | [
"Return",
"the",
"frame",
"as",
"an",
"array",
"of",
"8",
"-",
"byte",
"parts",
"ready",
"to",
"be",
"sent",
"to",
"a",
"YubiKey",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_frame.py#L70-L91 | train | 199,096 |
Yubico/python-yubico | yubico/yubikey_frame.py | YubiKeyFrame._debug_string | def _debug_string(self, debug, data):
"""
Annotate a frames data, if debug is True.
"""
if not debug:
return data
if self.command in [
SLOT.CONFIG,
SLOT.CONFIG2,
SLOT.UPDATE1,
SLOT.UPDATE2,
SLOT.SWAP,
]:
# annotate according to config_st (see ykdef.h)
if yubico_util.ord_byte(data[-1]) == 0x80:
return (data, "FFFFFFF") # F = Fixed data (16 bytes)
if yubico_util.ord_byte(data[-1]) == 0x81:
return (data, "FFFFFFF")
if yubico_util.ord_byte(data[-1]) == 0x82:
return (data, "FFUUUUU") # U = UID (6 bytes)
if yubico_util.ord_byte(data[-1]) == 0x83:
return (data, "UKKKKKK") # K = Key (16 bytes)
if yubico_util.ord_byte(data[-1]) == 0x84:
return (data, "KKKKKKK")
if yubico_util.ord_byte(data[-1]) == 0x85:
return (data, "KKKAAAA") # A = Access code to set (6 bytes)
if yubico_util.ord_byte(data[-1]) == 0x86:
return (data, "AAlETCr") # l = Length of fixed field (1 byte)
# E = extFlags (1 byte)
# T = tktFlags (1 byte)
# C = cfgFlags (1 byte)
# r = RFU (2 bytes)
if yubico_util.ord_byte(data[-1]) == 0x87:
return (data, "rCRaaaa") # CR = CRC16 checksum (2 bytes)
# a = Access code to use (6 bytes)
if yubico_util.ord_byte(data[-1]) == 0x88:
return (data, 'aa')
# after payload
if yubico_util.ord_byte(data[-1]) == 0x89:
return (data, " Scr")
return (data, '') | python | def _debug_string(self, debug, data):
"""
Annotate a frames data, if debug is True.
"""
if not debug:
return data
if self.command in [
SLOT.CONFIG,
SLOT.CONFIG2,
SLOT.UPDATE1,
SLOT.UPDATE2,
SLOT.SWAP,
]:
# annotate according to config_st (see ykdef.h)
if yubico_util.ord_byte(data[-1]) == 0x80:
return (data, "FFFFFFF") # F = Fixed data (16 bytes)
if yubico_util.ord_byte(data[-1]) == 0x81:
return (data, "FFFFFFF")
if yubico_util.ord_byte(data[-1]) == 0x82:
return (data, "FFUUUUU") # U = UID (6 bytes)
if yubico_util.ord_byte(data[-1]) == 0x83:
return (data, "UKKKKKK") # K = Key (16 bytes)
if yubico_util.ord_byte(data[-1]) == 0x84:
return (data, "KKKKKKK")
if yubico_util.ord_byte(data[-1]) == 0x85:
return (data, "KKKAAAA") # A = Access code to set (6 bytes)
if yubico_util.ord_byte(data[-1]) == 0x86:
return (data, "AAlETCr") # l = Length of fixed field (1 byte)
# E = extFlags (1 byte)
# T = tktFlags (1 byte)
# C = cfgFlags (1 byte)
# r = RFU (2 bytes)
if yubico_util.ord_byte(data[-1]) == 0x87:
return (data, "rCRaaaa") # CR = CRC16 checksum (2 bytes)
# a = Access code to use (6 bytes)
if yubico_util.ord_byte(data[-1]) == 0x88:
return (data, 'aa')
# after payload
if yubico_util.ord_byte(data[-1]) == 0x89:
return (data, " Scr")
return (data, '') | [
"def",
"_debug_string",
"(",
"self",
",",
"debug",
",",
"data",
")",
":",
"if",
"not",
"debug",
":",
"return",
"data",
"if",
"self",
".",
"command",
"in",
"[",
"SLOT",
".",
"CONFIG",
",",
"SLOT",
".",
"CONFIG2",
",",
"SLOT",
".",
"UPDATE1",
",",
"S... | Annotate a frames data, if debug is True. | [
"Annotate",
"a",
"frames",
"data",
"if",
"debug",
"is",
"True",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_frame.py#L93-L134 | train | 199,097 |
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | YubiKeyNEO_USBHID.write_ndef | def write_ndef(self, ndef, slot=1):
"""
Write an NDEF tag configuration to the YubiKey NEO.
"""
if not self.capabilities.have_nfc_ndef(slot):
raise yubikey_base.YubiKeyVersionError("NDEF slot %i unsupported in %s" % (slot, self))
return self._device._write_config(ndef, _NDEF_SLOTS[slot]) | python | def write_ndef(self, ndef, slot=1):
"""
Write an NDEF tag configuration to the YubiKey NEO.
"""
if not self.capabilities.have_nfc_ndef(slot):
raise yubikey_base.YubiKeyVersionError("NDEF slot %i unsupported in %s" % (slot, self))
return self._device._write_config(ndef, _NDEF_SLOTS[slot]) | [
"def",
"write_ndef",
"(",
"self",
",",
"ndef",
",",
"slot",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_nfc_ndef",
"(",
"slot",
")",
":",
"raise",
"yubikey_base",
".",
"YubiKeyVersionError",
"(",
"\"NDEF slot %i unsupported in %s\"... | Write an NDEF tag configuration to the YubiKey NEO. | [
"Write",
"an",
"NDEF",
"tag",
"configuration",
"to",
"the",
"YubiKey",
"NEO",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L145-L152 | train | 199,098 |
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | YubiKeyNEO_USBHID.write_device_config | def write_device_config(self, device_config):
"""
Write a DEVICE_CONFIG to the YubiKey NEO.
"""
if not self.capabilities.have_usb_mode(device_config._mode):
raise yubikey_base.YubiKeyVersionError("USB mode: %02x not supported for %s" % (device_config._mode, self))
return self._device._write_config(device_config, SLOT.DEVICE_CONFIG) | python | def write_device_config(self, device_config):
"""
Write a DEVICE_CONFIG to the YubiKey NEO.
"""
if not self.capabilities.have_usb_mode(device_config._mode):
raise yubikey_base.YubiKeyVersionError("USB mode: %02x not supported for %s" % (device_config._mode, self))
return self._device._write_config(device_config, SLOT.DEVICE_CONFIG) | [
"def",
"write_device_config",
"(",
"self",
",",
"device_config",
")",
":",
"if",
"not",
"self",
".",
"capabilities",
".",
"have_usb_mode",
"(",
"device_config",
".",
"_mode",
")",
":",
"raise",
"yubikey_base",
".",
"YubiKeyVersionError",
"(",
"\"USB mode: %02x not... | Write a DEVICE_CONFIG to the YubiKey NEO. | [
"Write",
"a",
"DEVICE_CONFIG",
"to",
"the",
"YubiKey",
"NEO",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L157-L163 | train | 199,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.