text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) + ".") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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])]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(self):
""" Poll YubiKey for status. """ |
data = self._read()
self._status = YubiKeyUSBHIDStatus(data)
return self._status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_config(self, **kw):
""" Get a configuration object for this type of YubiKey. """ |
return YubiKeyConfigUSBHID(ykver=self.version_num(), \
capabilities = self.capabilities, \
**kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, '') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def text(self, encoding = 'UTF-8', language = 'en'):
""" Configure parameters for NDEF type TEXT. @param encoding: The encoding used. Should be either 'UTF-8' or 'UTF16'. @param language: ISO/IANA language code (see RFC 3066). """ |
self.ndef_type = _NDEF_TEXT_TYPE
self.ndef_text_lang = language
self.ndef_text_enc = encoding
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type(self, url = False, text = False, other = None):
""" Change the NDEF type. """ |
if (url, text, other) == (True, False, None):
self.ndef_type = _NDEF_URI_TYPE
elif (url, text, other) == (False, True, None):
self.ndef_type = _NDEF_TEXT_TYPE
elif (url, text, type(other)) == (False, False, int):
self.ndef_type = other
else:
raise YubiKeyNEO_USBHIDError("Bad or conflicting NDEF type specified")
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _encode_ndef_uri_type(self, data):
""" Implement NDEF URI Identifier Code. This is a small hack to replace some well known prefixes (such as http://) with a one byte code. If the prefix is not known, 0x00 is used. """ |
t = 0x0
for (code, prefix) in uri_identifiers:
if data[:len(prefix)].decode('latin-1').lower() == prefix:
t = code
data = data[len(prefix):]
break
data = yubico_util.chr_byte(t) + data
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _encode_ndef_text_params(self, data):
""" Prepend language and enconding information to data, according to nfcforum-ts-rtd-text-1-0.pdf """ |
status = len(self.ndef_text_lang)
if self.ndef_text_enc == 'UTF16':
status = status & 0b10000000
return yubico_util.chr_byte(status) + self.ndef_text_lang + data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_key(debug=False, skip=0):
""" Locate a connected YubiKey. Throws an exception if none is found. This function is supposed to be possible to extend if any other YubiKeys appear in the future. Attributes : skip -- number of YubiKeys to skip debug -- True or False """ |
try:
hid_device = YubiKeyHIDDevice(debug, skip)
yk_version = hid_device.status().ykver()
if (2, 1, 4) <= yk_version <= (2, 1, 9):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
if yk_version < (3, 0, 0):
return YubiKeyUSBHID(debug, skip, hid_device)
if yk_version < (4, 0, 0):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
return YubiKey4_USBHID(debug, skip, hid_device)
except YubiKeyUSBHIDError as inst:
if 'No USB YubiKey found' in str(inst):
# generalize this error
raise YubiKeyError('No YubiKey found')
else:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses.""" |
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.join(v for v in version if v.strip())
else:
version = ''
return version |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_spec(spec, sep):
"""Split a spec by separator and return stripped start and end parts.""" |
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_specification(spec):
""" Parse a requirement from a python distribution metadata and return a tuple with name, extras, constraints, marker and url components. This method does not enforce strict specifications but extracts the information which is assumed to be *correct*. As such no errors are raised. Example ------- spec = 'requests[security, tests] >=3.3.0 ; foo >= 2.7 or bar == 1' ('requests', ['security', 'pyfoo'], '>=3.3.0', 'foo >= 2.7 or bar == 1', '') """ |
name, extras, const = spec, [], ''
# Remove excess whitespace
spec = ' '.join(p for p in spec.split(' ') if p).strip()
# Extract marker (Assumes that there can only be one ';' inside the spec)
spec, marker = split_spec(spec, ';')
# Extract url (Assumes that there can only be one '@' inside the spec)
spec, url = split_spec(spec, '@')
# Find name, extras and constraints
r = PARTIAL_PYPI_SPEC_PATTERN.match(spec)
if r:
# Normalize name
name = r.group('name')
# Clean extras
extras = r.group('extras')
extras = [e.strip() for e in extras.split(',') if e] if extras else []
# Clean constraints
const = r.group('constraints')
const = ''.join(c for c in const.split(' ') if c).strip()
if const.startswith('(') and const.endswith(')'):
# Remove parens
const = const[1:-1]
return name, extras, const, marker, url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_header_description(filedata):
"""Get description from metadata file and remove any empty lines at end.""" |
python_version = sys.version_info.major
if python_version == 3:
filedata = Parser().parsestr(filedata)
else:
filedata = Parser().parsestr(filedata.encode("UTF-8", "replace"))
payload = filedata.get_payload()
lines = payload.split('\n')
while True:
if lines and lines[-1] == '':
lines.pop()
else:
break
return '\n'.join(lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_server(self):
""" Checks if the server is reachable and throws and exception if it isn't """ |
msg = 'API server not found. Please check your API url configuration.'
try:
response = self.session.head(self.domain)
except Exception as e:
raise_from(errors.ServerError(msg), e)
try:
self._check_response(response)
except errors.NotFound as e:
raise raise_from(errors.ServerError(msg), e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _authenticate(self,
auth,
application,
application_url=None,
for_user=None,
scopes=None,
created_with=None,
max_age=None,
strength='strong',
fail_if_already_exists=False,
hostname=platform.node()):
'''
Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:param application: The application that is requesting access
:param application_url: The application's home page
:param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens.
'''
url = '%s/authentications' % (self.domain)
payload = {"scopes": scopes, "note": application, "note_url": application_url,
'hostname': hostname,
'user': for_user,
'max-age': max_age,
'created_with': None,
'strength': strength,
'fail-if-exists': fail_if_already_exists}
data, headers = jencode(payload)
res = self.session.post(url, auth=auth, data=data, headers=headers)
self._check_response(res)
res = res.json()
token = res['token']
self.session.headers.update({'Authorization': 'token %s' % (token)})
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def authentication(self):
'''
Retrieve information on the current authentication token
'''
url = '%s/authentication' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_authentication(self, auth_name=None, organization=None):
""" Remove the current authentication or the one given by `auth_name` """ |
if auth_name:
if organization:
url = '%s/authentications/org/%s/name/%s' % (self.domain, organization, auth_name)
else:
url = '%s/authentications/name/%s' % (self.domain, auth_name)
else:
url = '%s/authentications' % (self.domain,)
res = self.session.delete(url)
self._check_response(res, [201]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None):
'''
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
:param platform: only find packages that include files for this platform.
(e.g. 'linux-64', 'osx-64', 'win-32')
:param package_type: only find packages that have this kind of file
(e.g. 'env', 'conda', 'pypi')
:param type_: only find packages that have this conda `type`
(i.e. 'app')
:param access: only find packages that have this access level
(e.g. 'private', 'authenticated', 'public')
'''
if login:
url = '{0}/packages/{1}'.format(self.domain, login)
else:
url = '{0}/packages'.format(self.domain)
arguments = collections.OrderedDict()
if platform:
arguments['platform'] = platform
if package_type:
arguments['package_type'] = package_type
if type_:
arguments['type'] = type_
if access:
arguments['access'] = access
res = self.session.get(url, params=arguments)
self._check_response(res)
return res.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def package(self, login, package_name):
'''
Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
res = self.session.get(url)
self._check_response(res)
return res.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_package(self, login, package_name,
summary=None,
license=None,
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None):
'''
Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:param license: the name of the package license
:param license_url: the url of the package license
:param public: if true then the package will be hosted publicly
:param attrs: A dictionary of extra attributes for this package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
attrs = attrs or {}
attrs['summary'] = summary
attrs['package_types'] = [package_type]
attrs['license'] = {
'name': license,
'url': license_url,
'family': license_family,
}
payload = dict(public=bool(public),
publish=False,
public_attrs=dict(attrs or {})
)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def release(self, login, package_name, version):
'''
Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
res = self.session.get(url)
self._check_response(res)
return res.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_release(self, username, package_name, version):
'''
remove a release and all files under it
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, username, package_name, version)
res = self.session.delete(url)
self._check_response(res, [201])
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_release(self, login, package_name, version, requirements, announce, release_attrs):
'''
Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements TODO: describe
:param announce: An announcement that will be posted to all package watchers
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
if not release_attrs:
release_attrs = {}
payload = {
'requirements': requirements,
'announce': announce,
'description': None, # Will be updated with the one on release_attrs
}
payload.update(release_attrs)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download(self, login, package_name, release, basename, md5=None):
'''
Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the download if given and the package has not changed
None will be returned
:returns: a file like object or None
'''
url = '%s/download/%s/%s/%s/%s' % (self.domain, login, package_name, release, basename)
if md5:
headers = {'ETag':md5, }
else:
headers = {}
res = self.session.get(url, headers=headers, allow_redirects=False)
self._check_response(res, allowed=[200, 302, 304])
if res.status_code == 200:
# We received the content directly from anaconda.org
return res
elif res.status_code == 304:
# The content has not changed
return None
elif res.status_code == 302:
# Download from s3:
# We need to create a new request (without using session) to avoid
# sending the custom headers set on our session to S3 (which causes
# a failure).
res2 = requests.get(res.headers['location'], stream=True)
return res2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def upload(self, login, package_name, release, basename, fd, distribution_type,
description='', md5=None, size=None, dependencies=None, attrs=None, channels=('main',), callback=None):
'''
Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd: a file like object to upload
:param distribution_type: pypi or conda or ipynb, etc
:param description: (optional) a short description about the file
:param attrs: any extra attributes about the file (eg. build=1, pyversion='2.7', os='osx')
'''
url = '%s/stage/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
if attrs is None:
attrs = {}
if not isinstance(attrs, dict):
raise TypeError('argument attrs must be a dictionary')
payload = dict(distribution_type=distribution_type, description=description, attrs=attrs,
dependencies=dependencies, channels=channels)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
obj = res.json()
s3url = obj['post_url']
s3data = obj['form_data']
if md5 is None:
_hexmd5, b64md5, size = compute_hash(fd, size=size)
elif size is None:
spos = fd.tell()
fd.seek(0, os.SEEK_END)
size = fd.tell() - spos
fd.seek(spos)
s3data['Content-Length'] = size
s3data['Content-MD5'] = b64md5
data_stream, headers = stream_multipart(s3data, files={'file':(basename, fd)},
callback=callback)
request_method = self.session if s3url.startswith(self.domain) else requests
s3res = request_method.post(
s3url, data=data_stream,
verify=self.session.verify, timeout=10 * 60 * 60,
headers=headers
)
if s3res.status_code != 201:
logger.info(s3res.text)
logger.info('')
logger.info('')
raise errors.BinstarError('Error uploading package', s3res.status_code)
url = '%s/commit/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
payload = dict(dist_id=obj['dist_id'])
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.