code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''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=[])
List files in a directory
6.177477
6.199542
0.996441
'''Create a directory''' return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-mkdir'] + extra_args + [self._full_hdfs_path(src)], True)
def mkdir(self, src, extra_args=[])
Create a directory
9.751551
11.42742
0.853347
'''Perform ``df`` on a path''' return self._getStdOutCmd([self._hadoop_cmd, 'fs', '-df', self._full_hdfs_path(src)], True)
def df(self, src)
Perform ``df`` on a path
16.582232
13.767361
1.20446
'''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=[])
Perform ``du`` on a path
8.755925
8.418375
1.040097
'''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)
Perform ``count`` on a path
11.077437
9.776622
1.133054
'''Log and set the controller state.''' self._fail = True self.reason = error_code self._error = message
def handleError(self, error_code, message)
Log and set the controller state.
17.999041
8.552106
2.104633
''' 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...
def _handle_ls(self, path, node)
Handle every node received for an ls request
7.037253
5.097052
1.380652
''' 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 ...
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 :retur...
4.463372
2.366078
1.886401
''' Change the owner for paths. The owner can be specified as `user` or `user:group` :param paths: List of paths to chmod :type paths: list :param owner: New owner :type owner: string :param recurse: Recursive chown :type recurse: boolean :returns: a gene...
def chown(self, paths, owner, recurse=False)
Change the owner for paths. The owner can be specified as `user` or `user:group` :param paths: List of paths to chmod :type paths: list :param owner: New owner :type owner: string :param recurse: Recursive chown :type recurse: boolean :returns: a generator that y...
4.504364
2.518812
1.788289
''' 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, 'l...
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': 2601...
4.466878
2.091151
2.136086
''' 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} ''' pr...
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}
7.468299
2.40112
3.110339
'''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...
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 t...
3.821101
1.648726
2.317608
''' Rename (move) path(s) to a destination :param paths: Source paths :type paths: list :param dst: destination :type dst: string :returns: a generator that yields dictionaries ''' if not isinstance(paths, list): raise InvalidInputException("P...
def rename(self, paths, dst)
Rename (move) path(s) to a destination :param paths: Source paths :type paths: list :param dst: destination :type dst: string :returns: a generator that yields dictionaries
4.31148
3.211203
1.342637
''' Rename (but don't move) path to a destination By only renaming, we mean that you can't move a file or folder out or in other folder. The renaming can only happen within the folder the file or folder lies in. Note that this operation "always succeeds" unless an exception is ...
def rename2(self, path, dst, overwriteDest=False)
Rename (but don't move) path to a destination By only renaming, we mean that you can't move a file or folder out or in other folder. The renaming can only happen within the folder the file or folder lies in. Note that this operation "always succeeds" unless an exception is rais...
6.104817
1.605233
3.803072
''' Delete paths :param paths: Paths to delete :type paths: list :param recurse: Recursive delete (use with care!) :type recurse: boolean :returns: a generator that yields dictionaries .. note:: Recursive deletion uses the NameNode recursive deletion functionali...
def delete(self, paths, recurse=False)
Delete paths :param paths: Paths to delete :type paths: list :param recurse: Recursive delete (use with care!) :type recurse: boolean :returns: a generator that yields dictionaries .. note:: Recursive deletion uses the NameNode recursive deletion functionality ...
7.879815
2.354469
3.346748
''' 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") ...
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.
5.610082
3.589176
1.563056
''' 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 ...
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 :return...
4.518074
3.272883
1.380457
''' 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 dictionari...
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
4.001406
2.834788
1.411536
''' 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 ...
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
4.888988
3.058186
1.598656
''' 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 ...
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 ch...
4.322123
2.552214
1.69348
''' 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 ...
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 ...
4.622572
3.036613
1.522279
''' 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...
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, 'fil...
4.840873
1.992739
2.429256
# 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. :t...
def tail(self, path, tail_length=1024, append=False)
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 impleme...
5.019227
3.472089
1.445593
''' 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...
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 t...
3.485956
2.769591
1.258654
'''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 re...
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 loade...
3.714775
1.401205
2.651128
''' Request file info from the NameNode and call the processor on the node(s) returned :param paths: A list of paths that need to be processed :param processor: Method that is called on an node. Method signature should be foo(path, node). For additional (stat...
def _find_items(self, paths, processor, include_toplevel=False, include_children=False, recurse=False, check_nonexistence=False)
Request file info from the NameNode and call the processor on the node(s) returned :param paths: A list of paths that need to be processed :param processor: Method that is called on an node. Method signature should be foo(path, node). For additional (static) params, ...
4.010981
2.321638
1.727651
'''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. ''' ...
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.
3.822248
3.130766
1.220867
''' 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: ...
def _ha_return_method(func)
Method decorator for 'return type' methods
5.293857
4.618368
1.146261
''' 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 ...
def _ha_gen_method(func)
Method decorator for 'generator type' methods
5.413592
4.817888
1.123644
full_url_or_path = self.__url_or_path if rel_path is not None: full_url_or_path += '/' + rel_path result = self.run_command( 'proplist', ['--xml', full_url_or_path], do_combine=True) # query the proper list of this path ...
def properties(self, rel_path=None)
Return a dictionary with all svn-properties associated with a relative path. :param rel_path: relative path in the svn repo to query the properties from :returns: a dictionary with the property name as key and the content as value
2.872514
2.656675
1.081244
full_url_or_path = self.__url_or_path if rel_filepath is not None: full_url_or_path += '/' + rel_filepath timestamp_from_phrase = ('{' + timestamp_from_dt.isoformat() + '}') \ if timestamp_from_dt \ else '' timestamp_to_phrase = ('{' + time...
def log_default(self, timestamp_from_dt=None, timestamp_to_dt=None, limit=None, rel_filepath=None, stop_on_copy=False, revision_from=None, revision_to=None, changelist=False, use_merge_history=False)
Allow for the most-likely kind of log listing: the complete list, a FROM and TO timestamp, a FROM timestamp only, or a quantity limit.
2.395424
2.386733
1.003642
full_url_or_path = self.__url_or_path if rel_path is not None: full_url_or_path += '/' + rel_path result = self.run_command( 'diff', ['--old', '{0}@{1}'.format(full_url_or_path, old), '--new', '{0}@{1}'.format(full_url_or_path, new), ...
def diff_summary(self, old, new, rel_path=None)
Provides a summarized output of a diff between two revisions (file, change type, file type)
2.913405
2.883816
1.01026
full_url_or_path = self.__url_or_path if rel_path is not None: full_url_or_path += '/' + rel_path diff_result = self.run_command( 'diff', ['--old', '{0}@{1}'.format(full_url_or_path, old), '--new', '{0}@{1}'.format(full_url_or_path, new)]...
def diff(self, old, new, rel_path=None)
Provides output of a diff between two revisions (file, change type, file type)
2.912318
2.902879
1.003252
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") ...
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
2.924552
2.893873
1.010601
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...
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
3.111259
3.201761
0.971734
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)
Generate a random unit quaternion. Uniformly distributed across the rotation space As per: http://planning.cs.uiuc.edu/node198.html
2.023258
1.899866
1.064948
return self.__class__(scalar=self.scalar, vector= -self.vector)
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
13.061852
15.5482
0.840088
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)
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
5.874681
6.597632
0.890423
if not self.is_unit(): n = self.norm if n > 0: self.q = self.q / n
def _normalise(self)
Object is guaranteed to be a unit quaternion after calling this operation UNLESS the object is equivalent to Quaternion(0)
7.059459
4.14023
1.705088
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 ...
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)
7.459105
6.670513
1.118221
return np.array([ [self.q[0], -self.q[1], -self.q[2], -self.q[3]], [self.q[1], self.q[0], -self.q[3], self.q[2]], [self.q[2], self.q[3], self.q[0], -self.q[1]], [self.q[3], -self.q[2], self.q[1], self.q[0]]])
def _q_matrix(self)
Matrix representation of quaternion for multiplication purposes.
1.467264
1.273356
1.152281
return np.array([ [self.q[0], -self.q[1], -self.q[2], -self.q[3]], [self.q[1], self.q[0], self.q[3], -self.q[2]], [self.q[2], -self.q[3], self.q[0], self.q[1]], [self.q[3], self.q[2], -self.q[1], self.q[0]]])
def _q_bar_matrix(self)
Matrix representation of quaternion for multiplication purposes.
1.455898
1.283627
1.134206
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): ...
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 ...
2.80358
2.838303
0.987766
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)
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-funct...
4.876607
4.593364
1.061664
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 ...
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 loga...
5.191876
4.621005
1.123538
sqrt_q = q ** 0.5 return sqrt_q * Quaternion.exp(eta) * sqrt_q
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 R...
6.519779
8.560439
0.761617
inv_sqrt_q = (q ** (-0.5)) return Quaternion.log(inv_sqrt_q * p * inv_sqrt_q)
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 ...
6.323565
7.361208
0.859039
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)
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 ...
2.193901
2.514332
0.872558
q = Quaternion.log_map(q0, q1) return q.norm
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. ...
8.530194
11.996419
0.711062
q = Quaternion.sym_log_map(q0, q1) return q.norm
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 curv...
9.376599
12.388986
0.75685
# Ensure quaternion inputs are unit quaternions and 0 <= amount <=1 q0._fast_normalise() q1._fast_normalise() amount = np.clip(amount, 0, 1) dot = np.dot(q0.q, q1.q) # If the dot product is negative, slerp won't take the shorter path. # Note that v1 and...
def slerp(cls, q0, q1, amount=0.5)
Spherical Linear Interpolation between quaternions. Implemented as described in https://en.wikipedia.org/wiki/Slerp Find a valid quaternion rotation at a specified distance along the minor arc of a great circle passing through any two existing quaternion endpoints lying on the unit radi...
2.988113
3.099279
0.964132
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)
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 i...
2.164072
2.327768
0.929677
rate = self._validate_number_sequence(rate, 3) return 0.5 * self * Quaternion(vector=rate)
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
14.333
17.169453
0.834797
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 ...
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 glob...
4.824452
4.413
1.093237
self._normalise() product_matrix = np.dot(self._q_matrix(), self._q_bar_matrix().conj().transpose()) return product_matrix[1:][:,1:]
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 un...
8.86047
7.70318
1.150235
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)
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 ...
2.599371
2.7984
0.928878
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...
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]` ...
1.697061
1.564865
1.084477
result = ((theta + pi) % (2*pi)) - pi if result == -pi: result = pi return result
def _wrap_angle(self, theta)
Helper method: Wrap any angle to lie between -pi and pi Odd multiples of pi are wrapped to +pi (as opposed to -pi)
4.744912
4.029975
1.177405
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 ...
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...
7.957014
7.052191
1.128304
self._normalise() norm = np.linalg.norm(self.vector) return self._wrap_angle(2.0 * atan2(norm,self.scalar))
def angle(self)
Get the angle (in radians) describing the magnitude of the quaternion rotation about its rotation axis. This is guaranteed to be within the range (-pi:pi) with the direction of rotation indicated by the sign. When a particular rotation describes a 180 degree rotation about an arbitrary ...
6.593126
6.289003
1.048358
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], se...
def req_string(self, model)
Return string describing model and version requirement.
2.401773
2.150068
1.117068
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)
Check if this flag is compatible with a YubiKey of version 'ver'.
3.891513
3.196011
1.217616
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)
Return the boolean value of 'flag'. If 'new' is set, the flag is updated, and the value before update is returned.
3.231805
3.201237
1.009549
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]): ...
def _read_capabilities(self)
Read the capabilities list from a YubiKey >= 4.0.0
7.646977
6.580125
1.162132
data = self._read() self._status = YubiKeyUSBHIDStatus(data) return self._status
def status(self)
Poll YubiKey for status.
11.995432
7.223234
1.660673
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 sur...
def _write_config(self, cfg, slot)
Write configuration to YubiKey.
5.384803
4.968529
1.083782
# 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 & yu...
def _read_response(self, may_block=False)
Wait for a response to become available, and read it.
6.618319
6.196764
1.068028
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, ...
def _read(self)
Read a USB HID feature report from the YubiKey.
5.710335
4.633089
1.232511
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_wri...
def _write(self, frame)
Write a YubiKeyFrame to the USB HID. Includes polling for YubiKey readiness before each write.
11.775171
9.715854
1.211954
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)
Reset read mode by issuing a dummy write.
5.49077
5.009694
1.096029
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 ...
def _raw_write(self, data, debug_str = None)
Write data to YubiKey.
5.490589
5.145631
1.067039
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() ...
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)
3.86034
3.595798
1.07357
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.op...
def _open(self, skip=0)
Perform HID initialization
3.940149
3.806779
1.035035
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)
Release the USB interface again.
5.621201
4.637841
1.21203
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 Im...
def _get_usb_device(self, skip=0)
Get YubiKey USB device. Optionally allows you to skip n devices, to support multiple attached YubiKeys.
4.309251
4.097711
1.051624
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)
Print out to stderr, if debugging is enabled.
2.86964
2.585533
1.109883
if not self.capabilities.have_serial_number(): raise yubikey_base.YubiKeyVersionError("Serial number unsupported in YubiKey %s" % self.version() ) return self._read_serial(may_block)
def serial(self, may_block=True)
Get the YubiKey serial number (requires YubiKey 2.2).
7.421482
5.81584
1.276081
if not self.capabilities.have_challenge_response(mode): raise yubikey_base.YubiKeyVersionError("%s challenge-response unsupported in YubiKey %s" % (mode, self.version()) ) return self._challenge_response(challenge, mode, slot, variable, may_block)
def challenge_response(self, challenge, mode='HMAC', slot=1, variable=True, may_block=True)
Issue a challenge to the YubiKey and return the response (requires YubiKey 2.2).
4.823609
4.613019
1.045651
return YubiKeyConfigUSBHID(ykver=self.version_num(), \ capabilities = self.capabilities, \ **kw)
def init_config(self, **kw)
Get a configuration object for this type of YubiKey.
33.324585
18.57016
1.794523
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())) ...
def write_config(self, cfg, slot=1)
Write a configuration to the YubiKey.
5.440699
4.768177
1.141044
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") ...
def _read_serial(self, may_block)
Read the serial number from a YubiKey > 2.2.
7.589771
6.458911
1.175085
# 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.S...
def _challenge_response(self, challenge, mode, slot, variable, may_block)
Do challenge-response with a YubiKey > 2.0.
2.90095
2.93286
0.98912
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.CONF...
def valid_configs(self)
Return a list of slots having a valid configurtion. Requires firmware 2.1.
5.744981
4.281549
1.3418
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)
Turn command number into name
5.170467
5.167004
1.00067
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)
Find 'which' entry in 'flags'.
3.818794
3.612714
1.057043
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)
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.
6.446484
5.4062
1.192424
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)
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 upd...
9.622824
7.20387
1.335785
self._require_version(major=2) self.config_flag('STRONG_PW2', True) self.config_flag('SEND_REF', True)
def enable_shifted_1(self)
This will cause a shifted character 1 (typically '!') to be sent before anything else. This can be used to make the YubiKey output qualify as a password with 'special characters', if such is required. Because of the way this is stored in the config flags, it is not possible to disable t...
18.499857
14.641006
1.263565
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)
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.
5.097244
4.732655
1.077037
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 ...
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.
6.228183
4.511683
1.380457
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)
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.
4.805843
3.055464
1.572869
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:'): ...
def mode_yubikey_otp(self, private_uid, aes_key)
Set the YubiKey up for standard OTP validation.
4.16623
4.141685
1.005926
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: ...
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.
4.571739
4.332654
1.055182
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' \ ...
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.
5.10012
4.88876
1.043234
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(s...
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.
5.372596
5.373095
0.999907
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(s...
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.
5.56951
5.445394
1.022793
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_st...
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.
5.26843
5.08798
1.035466
#define UID_SIZE 6 /* Size of secret ID field */ #define FIXED_SIZE 16 /* Max size of fixed field */ #define KEY_SIZE 16 /* Size of AES key */ #define KEY_SIZE_OATH 20 /* Size of OATH-HOTP key (key field + first 4 of UID fiel...
def to_string(self)
Return the current configuration as a bytestring (always 64 bytes).
4.609531
4.358366
1.057628
data = self.to_string() payload = data.ljust(64, yubico_util.chr_byte(0x0)) if slot is 1: if self._update_config: command = SLOT.UPDATE1 else: command = SLOT.CONFIG elif slot is 2: if self._update_config: ...
def to_frame(self, slot=1)
Return the current configuration as a YubiKeyFrame object.
5.299475
4.614403
1.148464
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.y...
def _require_version(self, major, minor=0)
Update the minimum version of YubiKey this configuration can be applied to.
3.989386
3.303221
1.207726