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 component_add(vec1, vec2):
"""Add each of the components of vec1 and vec2 together and return a new vector.""" |
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3):
addVec = Vector3()
addVec.x = vec1.x + vec2.x
addVec.y = vec1.y + vec2.y
addVec.z = vec1.z + vec2.z
return addVec
if isinstance(vec1, Vector4) and isinstance(vec2, Vector4):
addVec = Vector4()
addVec.x = vec1.x + vec2.x
addVec.y = vec1.y + vec2.y
addVec.z = vec1.z + vec2.z
addVec.w = vec1.w + vec2.w
return addVec |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reflect(vec1, vec2):
"""Take vec1 and reflect it about vec2.""" |
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3) \
or isinstance(vec1, Vector4) and isinstance(vec2, Vector4):
return 2 * dot(vec1, vec2) * vec2 - vec2
else:
raise ValueError("vec1 and vec2 must both be a Vector type") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Create a copy of this Vector""" |
new_vec = Vector2()
new_vec.X = self.X
new_vec.Y = self.Y
return new_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 length(self):
"""Gets the length of this Vector""" |
return math.sqrt((self.X * self.X) + (self.Y * self.Y)) |
<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(vec1, vec2):
"""Calculate the distance between two Vectors""" |
if isinstance(vec1, Vector2) \
and isinstance(vec2, Vector2):
dist_vec = vec2 - vec1
return dist_vec.length()
else:
raise TypeError("vec1 and vec2 must be Vector2's") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dot(vec1, vec2):
"""Calculate the dot product between two Vectors""" |
if isinstance(vec1, Vector2) \
and isinstance(vec2, Vector2):
return ((vec1.X * vec2.X) + (vec1.Y * vec2.Y))
else:
raise TypeError("vec1 and vec2 must be Vector2's") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angle(vec1, vec2):
"""Calculate the angle between two Vector2's""" |
dotp = Vector2.dot(vec1, vec2)
mag1 = vec1.length()
mag2 = vec2.length()
result = dotp / (mag1 * mag2)
return math.acos(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lerp(vec1, vec2, time):
"""Lerp between vec1 to vec2 based on time. Time is clamped between 0 and 1.""" |
if isinstance(vec1, Vector2) \
and isinstance(vec2, Vector2):
# Clamp the time value into the 0-1 range.
if time < 0:
time = 0
elif time > 1:
time = 1
x_lerp = vec1[0] + time * (vec2[0] - vec1[0])
y_lerp = vec1[1] + time * (vec2[1] - vec1[1])
return Vector2(x_lerp, y_lerp)
else:
raise TypeError("Objects must be of type Vector2") |
<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_polar(degrees, magnitude):
"""Convert polar coordinates to Carteasian Coordinates""" |
vec = Vector2()
vec.X = math.cos(math.radians(degrees)) * magnitude
# Negate because y in screen coordinates points down, oppisite from what is
# expected in traditional mathematics.
vec.Y = -math.sin(math.radians(degrees)) * magnitude
return 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 component_mul(vec1, vec2):
"""Multiply the components of the vectors and return the result.""" |
new_vec = Vector2()
new_vec.X = vec1.X * vec2.X
new_vec.Y = vec1.Y * vec2.Y
return new_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 component_div(vec1, vec2):
"""Divide the components of the vectors and return the result.""" |
new_vec = Vector2()
new_vec.X = vec1.X / vec2.X
new_vec.Y = vec1.Y / vec2.Y
return new_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 to_vec4(self, isPoint):
"""Converts this vector3 into a vector4 instance.""" |
vec4 = Vector4()
vec4.x = self.x
vec4.y = self.y
vec4.z = self.z
if isPoint:
vec4.w = 1
else:
vec4.w = 0
return vec4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuple_as_vec(xyz):
""" Generates a Vector3 from a tuple or list. """ |
vec = Vector3()
vec[0] = xyz[0]
vec[1] = xyz[1]
vec[2] = xyz[2]
return 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 cross(vec1, vec2):
"""Returns the cross product of two Vectors""" |
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3):
vec3 = Vector3()
vec3.x = (vec1.y * vec2.z) - (vec1.z * vec2.y)
vec3.y = (vec1.z * vec2.x) - (vec1.x * vec2.z)
vec3.z = (vec1.x * vec2.y) - (vec1.y * vec2.x)
return vec3
else:
raise TypeError("vec1 and vec2 must be Vector3's") |
<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_vec3(self):
"""Convert this vector4 instance into a vector3 instance.""" |
vec3 = Vector3()
vec3.x = self.x
vec3.y = self.y
vec3.z = self.z
if self.w != 0:
vec3 /= self.w
return vec3 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def length(self):
"""Gets the length of the Vector""" |
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clamp(self, clampVal):
"""Clamps all the components in the vector to the specified clampVal.""" |
if self.x > clampVal:
self.x = clampVal
if self.y > clampVal:
self.y = clampVal
if self.z > clampVal:
self.z = clampVal
if self.w > clampVal:
self.w = clampVal |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tuple_as_vec(xyzw):
""" Generates a Vector4 from a tuple or list. """ |
vec = Vector4()
vec[0] = xyzw[0]
vec[1] = xyzw[1]
vec[2] = xyzw[2]
vec[3] = xyzw[3]
return 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 transpose(self):
"""Create a transpose of this matrix.""" |
ma4 = Matrix4(self.get_col(0),
self.get_col(1),
self.get_col(2),
self.get_col(3))
return ma4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(translationAmt):
"""Create a translation matrix.""" |
if not isinstance(translationAmt, Vector3):
raise ValueError("translationAmt must be a Vector3")
ma4 = Matrix4((1, 0, 0, translationAmt.x),
(0, 1, 0, translationAmt.y),
(0, 0, 1, translationAmt.z),
(0, 0, 0, 1))
return ma4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale(scaleAmt):
""" Create a scale matrix. scaleAmt is a Vector3 defining the x, y, and z scale values. """ |
if not isinstance(scaleAmt, Vector3):
raise ValueError("scaleAmt must be a Vector3")
ma4 = Matrix4((scaleAmt.x, 0, 0, 0),
(0, scaleAmt.y, 0, 0),
(0, 0, scaleAmt.z, 0),
(0, 0, 0, 1))
return ma4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def z_rotate(rotationAmt):
"""Create a matrix that rotates around the z axis.""" |
ma4 = Matrix4((math.cos(rotationAmt), -math.sin(rotationAmt), 0, 0),
(math.sin(rotationAmt), math.cos(rotationAmt), 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1))
return ma4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def y_rotate(rotationAmt):
"""Create a matrix that rotates around the y axis.""" |
ma4 = Matrix4((math.cos(rotationAmt), 0, math.sin(rotationAmt), 0),
(0, 1, 0, 0),
(-math.sin(rotationAmt), 0, math.cos(rotationAmt), 0),
(0, 0, 0, 1))
return ma4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def x_rotate(rotationAmt):
"""Create a matrix that rotates around the x axis.""" |
ma4 = Matrix4((1, 0, 0, 0),
(0, math.cos(rotationAmt), -math.sin(rotationAmt), 0),
(0, math.sin(rotationAmt), math.cos(rotationAmt), 0),
(0, 0, 0, 1))
return ma4 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_rotation(vec3):
""" Build a rotation matrix. vec3 is a Vector3 defining the axis about which to rotate the object. """ |
if not isinstance(vec3, Vector3):
raise ValueError("rotAmt must be a Vector3")
return Matrix4.x_rotate(vec3.x) * Matrix4.y_rotate(vec3.y) * Matrix4.z_rotate(vec3.z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __handle_events(self):
"""This is the place to put all event handeling.""" |
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
self.exit() |
<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_object(self):
"""Create a new object for the pool.""" |
# Check to see if the user created a specific initalization function for this object.
if self.init_function is not None:
new_obj = self.init_function()
self.__enqueue(new_obj)
else:
raise TypeError("The Pool must have a non None function to fill the pool.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def center_origin(self):
"""Sets the origin to the center of the image.""" |
self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.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 scale_to(self, width_height=Vector2()):
"""Scale the texture to the specfied width and height.""" |
scale_amt = Vector2()
scale_amt.X = float(width_height.X) / self.image.get_width()
scale_amt.Y = float(width_height.Y) / self.image.get_height()
self.set_scale(scale_amt) |
<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_hflip(self, val):
"""val is True or False that determines if we should horizontally flip the surface or not.""" |
if self.__horizontal_flip is not val:
self.__horizontal_flip = val
self.image = pygame.transform.flip(self.untransformed_image, val, self.__vertical_flip) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_texture(self, file_path):
"""Generate our sprite's surface by loading the specified image from disk. Note that this automatically centers the origin.""" |
self.image = pygame.image.load(file_path)
self.apply_texture(self.image) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __execute_rot(self, surface):
"""Executes the rotating operation""" |
self.image = pygame.transform.rotate(surface, self.__rotation)
self.__resize_surface_extents() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __handle_scale_rot(self):
"""Handle scaling and rotation of the surface""" |
if self.__is_rot_pending:
self.__execute_rot(self.untransformed_image)
self.__is_rot_pending = False
# Scale the image using the recently rotated surface to keep the orientation correct
self.__execute_scale(self.image, self.image.get_size())
self.__is_scale_pending = False
# The image is not rotating while scaling, thus use the untransformed image to scale.
if self.__is_scale_pending:
self.__execute_scale(self.untransformed_image, self.untransformed_image.get_size())
self.__is_scale_pending = 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 load_font(self, font_path, font_size):
"""Load the specified font from a file.""" |
self.__font_path = font_path
self.__font_size = font_size
if font_path != "":
self.__font = pygame.font.Font(font_path, font_size)
self.__set_text(self.__text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initalize(self, physics_dta):
""" Prepare our particle for use. physics_dta describes the velocity, coordinates, and acceleration of the particle. """ |
self.rotation = random.randint(self.rotation_range[0], self.rotation_range[1])
self.current_time = 0.0
self.color = self.start_color
self.scale = self.start_scale
self.physics = physics_dta |
<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_particle(self):
"""Pull a particle from the queue and add it to the active list.""" |
# Calculate a potential angle for the particle.
angle = random.randint(int(self.direction_range[0]), int(self.direction_range[1]))
velocity = Vector2.from_polar(angle, self.particle_speed)
physics = PhysicsObj(self.coords, Vector2(), velocity)
particle = self.particle_pool.request_object()
particle.initalize(physics)
self.particles.append(particle)
self.current_particle_count += 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 load_texture(self, file_path, cell_size=(256, 256)):
""" Load a spritesheet texture. cell_size is the uniform size of each cell in the spritesheet. """ |
super(SpriteSheet, self).load_texture(file_path)
self.__cell_bounds = cell_size
self.__generate_cells() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self, milliseconds, surface, cell):
"""Draw out the specified cell""" |
# print self.cells[cell]
self.source = self.cells[cell].copy()
# Find the current scale of the image in relation to its original scale.
current_scale = Vector2()
current_scale.X = self.rect.width / float(self.untransformed_image.get_width())
current_scale.Y = self.rect.height / float(self.untransformed_image.get_height())
# self.source.x *= self.scale.X
# self.source.y *= self.scale.Y
self.source.width *= current_scale.X
self.source.height *= current_scale.Y
super(SpriteSheet, self).draw(milliseconds, surface) |
<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_coords(self, value):
"""Set all the images contained in the animation to the specified value.""" |
self.__coords = value
for image in self.images:
image.coords = value |
<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_hflip(self, val):
"""Flip all the images in the animation list horizontally.""" |
self.__horizontal_flip = val
for image in self.images:
image.h_flip = val |
<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_vflip(self, val):
"""Flip all the images in the animation list vertically.""" |
self.__vertical_flip = val
for image in self.images:
image.v_flip = val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Create a copy of the animation.""" |
animation = AnimationList()
animation.set_frame_rate(self.frame_rate)
animation.__coords = self.__coords
animation.__horizontal_flip = self.__horizontal_flip
animation.__vertical_flip = self.__vertical_flip
animation.should_repeat = self.should_repeat
animation.draw_order = self.draw_order
animation.update_order = self.update_order
for image in self.images:
new_image = Sprite()
new_image.coords = image.coords
new_image.apply_texture(image.image)
animation.images.append(new_image)
return animation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self, milliseconds, surface):
"""Render the bounds of this collision ojbect onto the specified surface.""" |
super(CollidableObj, self).draw(milliseconds, surface) |
<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_colliding(self, other):
"""Check to see if two AABoundingBoxes are colliding.""" |
if isinstance(other, AABoundingBox):
if self.rect.colliderect(other.rect):
return True
return 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 remove_object(collision_object):
"""Remove the collision object from the Manager""" |
global collidable_objects
if isinstance(collision_object, CollidableObj):
# print "Collision object of type ", type(collision_object), " removed from the collision manager."
try:
collidable_objects.remove(collision_object)
except:
print
"Ragnarok Says: Collision_Object with ID # " + str(
collision_object.obj_id) + " could not be found in the Collision Manager. Skipping over..." |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_collision(collision_object):
""" Check to see if the specified object is colliding with any of the objects currently in the Collision Manager Returns the first object we are colliding with if there was a collision and None if no collisions was found """ |
global collidable_objects
# Note that we use a Brute Force approach for the time being.
# It performs horribly under heavy loads, but it meets
# our needs for the time being.
for obj in collidable_objects:
# Make sure we don't check ourself against ourself.
if obj.obj_id is not collision_object.obj_id:
if collision_object.is_colliding(obj):
# A collision has been detected. Return the object that we are colliding with.
return obj
# No collision was noticed. Return None.
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 draw(self, milliseconds, surface):
"""Render each of the collision objects onto the specified surface.""" |
if self.is_visible:
global collidable_objects
for obj in collidable_objects:
if obj.is_visible:
obj.draw(milliseconds, surface)
super(CollisionManager, self).draw(milliseconds, surface) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __wrap_index(self):
"""Wraps the current_index to the other side of the menu.""" |
if self.current_index < 0:
self.current_index = len(self.gui_buttons) - 1
elif self.current_index >= len(self.gui_buttons):
self.current_index = 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 move_up(self):
""" Try to select the button above the currently selected one. If a button is not there, wrap down to the bottom of the menu and select the last button. """ |
old_index = self.current_index
self.current_index -= 1
self.__wrap_index()
self.__handle_selections(old_index, self.current_index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_down(self):
""" Try to select the button under the currently selected one. If a button is not there, wrap down to the top of the menu and select the first button. """ |
old_index = self.current_index
self.current_index += 1
self.__wrap_index()
self.__handle_selections(old_index, self.current_index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __update_keyboard(self, milliseconds):
""" Use the keyboard to control selection of the buttons. """ |
if Ragnarok.get_world().Keyboard.is_clicked(self.move_up_button):
self.move_up()
elif Ragnarok.get_world().Keyboard.is_clicked(self.move_down_button):
self.move_down()
elif Ragnarok.get_world().Keyboard.is_clicked(self.select_button):
self.gui_buttons[self.current_index].clicked_action()
for button in self.gui_buttons:
button.update(milliseconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Create a copy of this MouseState and return it.""" |
ms = MouseState()
ms.left_pressed = self.left_pressed
ms.middle_pressed = self.middle_pressed
ms.right_pressed = self.right_pressed
ms.mouse_pos = self.mouse_pos
return ms |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_state(self, StateType):
""" Is a button depressed? True if a button is pressed, false otherwise. """ |
if StateType == M_LEFT:
# Checking left mouse button
return self.left_pressed
elif StateType == M_MIDDLE:
# Checking middle mouse button
return self.middle_pressed
elif StateType == M_RIGHT:
# Checking right mouse button
return self.right_pressed |
<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_clicked(self, MouseStateType):
""" Did the user depress and release the button to signify a click? MouseStateType is the button to query. Values found under StateTypes.py """ |
return self.previous_mouse_state.query_state(MouseStateType) and (
not self.current_mouse_state.query_state(MouseStateType)) |
<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_any_down(self):
"""Is any button depressed?""" |
for key in range(len(self.current_state.key_states)):
if self.is_down(key):
return True
return 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 is_any_clicked(self):
"""Is any button clicked?""" |
for key in range(len(self.current_state.key_states)):
if self.is_clicked(key):
return True
return 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 generate_bbox(self, collision_function=None, tag=""):
"""Create a bounding box around this tile so that it can collide with objects not included in the TileManager""" |
boundingBox = AABoundingBox(None, collision_function, tag)
CollisionManager.add_object(boundingBox) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pixels_to_tiles(self, coords, clamp=True):
""" Convert pixel coordinates into tile coordinates. clamp determines if we should clamp the tiles to ones only on the tilemap. """ |
tile_coords = Vector2()
tile_coords.X = int(coords[0]) / self.spritesheet[0].width
tile_coords.Y = int(coords[1]) / self.spritesheet[0].height
if clamp:
tile_coords.X, tile_coords.Y = self.clamp_within_range(tile_coords.X, tile_coords.Y)
return tile_coords |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clamp_within_range(self, x, y):
""" Clamp x and y so that they fall within range of the tilemap. """ |
x = int(x)
y = int(y)
if x < 0:
x = 0
if y < 0:
y = 0
if x > self.size_in_tiles.X:
x = self.size_in_tiles.X
if y > self.size_in_tiles.Y:
y = self.size_in_tiles.Y
return x, y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tiles_to_pixels(self, tiles):
"""Convert tile coordinates into pixel coordinates""" |
pixel_coords = Vector2()
pixel_coords.X = tiles[0] * self.spritesheet[0].width
pixel_coords.Y = tiles[1] * self.spritesheet[0].height
return pixel_coords |
<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_valid_tile(self, x, y):
"""Check to see if the requested tile is part of the tile map.""" |
x = int(x)
y = int(y)
if x < 0:
return False
if y < 0:
return False
if x > self.size_in_tiles.X:
return False
if y > self.size_in_tiles.Y:
return False
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 unload():
"""Unload the current map from the world.""" |
global __tile_maps
global active_map
if TileMapManager.active_map != None:
world = Ragnarok.get_world()
for obj in TileMapManager.active_map.objects:
world.remove_obj(obj)
world.remove_obj(TileMapManager.active_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 load(name):
"""Parse the tile map and add it to the world.""" |
global __tile_maps
# Remove the current map.
TileMapManager.unload()
TileMapManager.active_map = __tile_maps[name]
TileMapManager.active_map.parse_tilemap()
TileMapManager.active_map.parse_collisions()
TileMapManager.active_map.parse_objects()
world = Ragnarok.get_world()
world.add_obj(TileMapManager.active_map)
for obj in TileMapManager.active_map.objects:
world.add_obj(obj) |
<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_movement_delta(self):
"""Get the amount the camera has moved since get_movement_delta was last called.""" |
pos = self.pan - self.previous_pos
self.previous_pos = Vector2(self.pan.X, self.pan.Y)
return pos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Reset(self):
"""Reset the camera back to its defaults.""" |
self.pan = self.world_center
self.desired_pan = self.pos |
<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_bounds(self):
"""Make sure the camera is not outside if its legal range.""" |
if not (self.camera_bounds == None):
if self.__pan.X < self.camera_bounds.Left:
self.__pan[0] = self.camera_bounds.Left
if self.__pan.X > self.camera_bounds.Right:
self.__pan[0] = self.camera_bounds.Right
if self.__pan.Y < self.camera_bounds.Top:
self.__pan[1] = self.camera_bounds.Top
if self.__pan.Y > self.camera_bounds.Bottom:
self.__pan[1] = self.camera_bounds.Bottom |
<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_cam_bounds(self):
"""Return the bounds of the camera in x, y, xMax, and yMax format.""" |
world_pos = self.get_world_pos()
screen_res = Ragnarok.get_world().get_backbuffer_size() * .5
return (self.pan.X - screen_res.X), (self.pan.Y - screen_res.Y), (self.pan.X + screen_res.X), (
self.pan.Y + screen_res.Y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_view_bounds(self):
"""Update the camera's view bounds.""" |
self.view_bounds.left = self.pan.X - self.world_center.X
self.view_bounds.top = self.pan.Y - self.world_center.Y
self.view_bounds.width = self.world_center.X * 2
self.view_bounds.height = self.world_center.Y * 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 set_backbuffer(self, preferred_backbuffer_size, flags=0):
"""Create the backbuffer for the game.""" |
if not (isinstance(preferred_backbuffer_size, Vector2)):
raise ValueError("preferred_backbuffer_size must be of type Vector2")
self.__backbuffer = pygame.display.set_mode(preferred_backbuffer_size, flags)
self.Camera.world_center = preferred_backbuffer_size / 2.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 set_display_at_native_res(self, should_be_fullscreen=True):
"""Sets the resolution to the display's native resolution. Sets as fullscreen if should_be_fullscreen is true.""" |
# Loop through all our display modes until we find one that works well.
for mode in self.display_modes:
color_depth = pygame.display.mode_ok(mode)
if color_depth is not 0:
if should_be_fullscreen:
should_fill = pygame.FULLSCREEN
else:
should_fill = 0
self.backbuffer = pygame.display.set_mode(mode, should_fill, color_depth)
break |
<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_backbuffer_size(self):
"""Get the width and height of the backbuffer as a Vector2.""" |
vec = Vector2()
vec.X = self.backbuffer.get_width()
vec.Y = self.backbuffer.get_height()
return 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 find_obj_by_tag(self, tag):
"""Search through all the objects in the world and return the first instance whose tag matches the specified string.""" |
for obj in self.__up_objects:
if obj.tag == tag:
return obj
for obj in self.__draw_objects:
if obj.tag == tag:
return obj
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 remove_by_tag(self, tag):
""" Remove the first encountered object with the specified tag from the world. Returns true if an object was found and removed. Returns false if no object could be removed. """ |
obj = self.find_obj_by_tag(tag)
if obj != None:
self.remove_obj(obj)
return True
return 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 __draw_cmp(self, obj1, obj2):
"""Defines how our drawable objects should be sorted""" |
if obj1.draw_order > obj2.draw_order:
return 1
elif obj1.draw_order < obj2.draw_order:
return -1
else:
return 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 __up_cmp(self, obj1, obj2):
"""Defines how our updatable objects should be sorted""" |
if obj1.update_order > obj2.update_order:
return 1
elif obj1.update_order < obj2.update_order:
return -1
else:
return 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 update(self, milliseconds):
"""Updates all of the objects in our world.""" |
self.__sort_up()
for obj in self.__up_objects:
obj.update(milliseconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_path(filename):
""" Check if path to `filename` exists and if not, create the necessary intermediate directories. """ |
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def locate_files(pattern, root_dir=os.curdir):
""" Locate all files matching fiven filename pattern in and below supplied root directory. """ |
for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
for filename in fnmatch.filter(filenames, pattern):
yield os.path.join(dirpath, filename) |
<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_files(root_dir):
""" Remove all files and directories in supplied root directory. """ |
for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)):
for filename in filenames:
os.remove(os.path.join(root_dir, filename))
for dirname in dirnames:
shutil.rmtree(os.path.join(root_dir, dirname)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit_filename(filename, prefix='', suffix='', new_ext=None):
""" Edit a file name by add a prefix, inserting a suffix in front of a file name extension or replacing the extension. Parameters filename : str The file name. prefix : str The prefix to be added. suffix : str The suffix to be inserted. new_ext : str, optional If not None, it replaces the original file name extension. Returns ------- new_filename : str The new file name. """ |
base, ext = os.path.splitext(filename)
if new_ext is None:
new_filename = base + suffix + ext
else:
new_filename = base + suffix + new_ext
return new_filename |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_friends(self, user, paginate=False):
""" fethces friends from facebook using the oauth_token fethched by django-social-auth. Note - user isn't a user - it's a UserSocialAuth if using social auth, or a SocialAccount if using allauth Returns: collection of friend objects fetched from facebook """ |
if USING_ALLAUTH:
social_app = SocialApp.objects.get_current('facebook')
oauth_token = SocialToken.objects.get(account=user, app=social_app).token
else:
social_auth_backend = FacebookBackend()
# Get the access_token
tokens = social_auth_backend.tokens(user)
oauth_token = tokens['access_token']
graph = facebook.GraphAPI(oauth_token)
friends = graph.get_connections("me", "friends")
if paginate:
total_friends = friends.copy()
total_friends.pop('paging')
while 'paging' in friends and 'next' in friends['paging'] and friends['paging']['next']:
next_url = friends['paging']['next']
next_url_parsed = urlparse.urlparse(next_url)
query_data = urlparse.parse_qs(next_url_parsed.query)
query_data.pop('access_token')
for k, v in query_data.items():
query_data[k] = v[0]
friends = graph.get_connections("me", "friends", **query_data)
total_friends['data'] = sum([total_friends['data'], friends['data']], [])
else:
total_friends = friends
return total_friends |
<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, request):
""" Send the request through the authentication middleware that is provided with DOAC and grab the user and token from it. """ |
from doac.middleware import AuthenticationMiddleware
try:
response = AuthenticationMiddleware().process_request(request)
except:
raise exceptions.AuthenticationFailed("Invalid handler")
if not hasattr(request, "user") or not request.user.is_authenticated():
return None
if not hasattr(request, "access_token"):
raise exceptions.AuthenticationFailed("Access token was not valid")
return request.user, request.access_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 scope_required(*scopes):
""" Test for specific scopes that the access token has been authenticated for before processing the request and eventual response. The scopes that are passed in determine how the decorator will respond to incoming requests: - If no scopes are passed in the arguments, the decorator will test for any available scopes and determine the response based on that. - If specific scopes are passed, the access token will be checked to make sure it has all of the scopes that were requested. This decorator will change the response if the access toke does not have the scope: - If an invalid scope is requested (one that does not exist), all requests will be denied, as no access tokens will be able to fulfill the scope request and the request will be denied. - If the access token does not have one of the requested scopes, the request will be denied and the user will be returned one of two responses: - A 400 response (Bad Request) will be returned if an unauthenticated user tries to access the resource. - A 403 response (Forbidden) will be returned if an authenticated user ties to access the resource but does not have the correct scope. """ |
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
from django.http import HttpResponseBadRequest, HttpResponseForbidden
from .exceptions.base import InvalidRequest, InsufficientScope
from .models import Scope
from .utils import request_error_header
try:
if not hasattr(request, "access_token"):
raise CredentialsNotProvided()
access_token = request.access_token
for scope_name in scopes:
try:
scope = access_token.scope.for_short_name(scope_name)
except Scope.DoesNotExist:
raise ScopeNotEnough()
except InvalidRequest as e:
response = HttpResponseBadRequest()
response["WWW-Authenticate"] = request_error_header(e)
return response
except InsufficientScope as e:
response = HttpResponseForbidden()
response["WWW-Authenticate"] = request_error_header(e)
return response
return view_func(request, *args, **kwargs)
return _wrapped_view
if scopes and hasattr(scopes[0], "__call__"):
func = scopes[0]
scopes = scopes[1:]
return decorator(func)
return decorator |
<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, request, provider=None):
"""prepare the social friend model""" |
# Get the social auth connections
if USING_ALLAUTH:
self.social_auths = request.user.socialaccount_set.all()
else:
self.social_auths = request.user.social_auth.all()
self.social_friend_lists = []
# if the user did not connect any social accounts, no need to continue
if self.social_auths.count() == 0:
if REDIRECT_IF_NO_ACCOUNT:
return HttpResponseRedirect(REDIRECT_URL)
return super(FriendListView, self).get(request)
# for each social network, get or create social_friend_list
self.social_friend_lists = SocialFriendList.objects.get_or_create_with_social_auths(self.social_auths)
return super(FriendListView, self).get(request) |
<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_context_data(self, **kwargs):
""" checks if there is SocialFrind model record for the user if not attempt to create one if all fail, redirects to the next page """ |
context = super(FriendListView, self).get_context_data(**kwargs)
friends = []
for friend_list in self.social_friend_lists:
fs = friend_list.existing_social_friends()
for f in fs:
friends.append(f)
# Add friends to context
context['friends'] = friends
connected_providers = []
for sa in self.social_auths:
connected_providers.append(sa.provider)
context['connected_providers'] = connected_providers
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def are_requirements_changed(config):
"""Check if any of the requirement files used by testenv is updated. :param tox.config.TestenvConfig config: Configuration object to observe. :rtype: bool """ |
deps = (dep.name for dep in config.deps)
def build_fpath_for_previous_version(fname):
tox_dir = config.config.toxworkdir.strpath
envdirkey = _str_to_sha1hex(str(config.envdir))
fname = '{0}.{1}.previous'.format(fname.replace('/', '-'), envdirkey)
return os.path.join(tox_dir, fname)
requirement_files = map(parse_requirements_fname, deps)
return any([
is_changed(reqfile, build_fpath_for_previous_version(reqfile))
for reqfile in requirement_files
if reqfile and os.path.isfile(reqfile)]) |
<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_pip_requirements(requirement_file_path):
""" Parses requirements using the pip API. :param str requirement_file_path: path of the requirement file to parse. :returns list: list of requirements """ |
return sorted(
str(r.req)
for r in parse_requirements(requirement_file_path,
session=PipSession())
if r.req
) |
<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_changed(fpath, prev_version_fpath):
"""Check requirements file is updated relatively to prev. version of the file. :param str fpath: Path to the requirements file. :param str prev_version_fpath: Path to the prev. version requirements file. :rtype: bool :raise ValueError: Requirements file doesn't exist. """ |
if not (fpath and os.path.isfile(fpath)):
raise ValueError("Requirements file {0!r} doesn't exist.".format(fpath))
# Compile the list of new requirements.
new_requirements = parse_pip_requirements(fpath)
# Hash them.
new_requirements_hash = _str_to_sha1hex(str(new_requirements))
# Read the hash of the previous requirements if any.
previous_requirements_hash = 0
if os.path.exists(prev_version_fpath):
with open(prev_version_fpath) as fd:
previous_requirements_hash = fd.read()
# Create/Update the file with the hash of the new requirements.
dirname = os.path.dirname(prev_version_fpath)
# First time when running tox in the project .tox directory is missing.
if not os.path.isdir(dirname):
os.makedirs(dirname)
with open(prev_version_fpath, 'w+') as fd:
fd.write(new_requirements_hash)
# Compare the hash of the new requirements with the hash of the previous
# requirements.
return previous_requirements_hash != new_requirements_hash |
<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_player_collision(self):
"""Check to see if we are colliding with the player.""" |
player_tiles = r.TileMapManager.active_map.grab_collisions(self.char.coords)
enemy_tiles = r.TileMapManager.active_map.grab_collisions(self.coords)
#Check to see if any of the tiles are the same. If so, there is a collision.
for ptile in player_tiles:
for etile in enemy_tiles:
if r.TileMapManager.active_map.pixels_to_tiles(ptile.coords) == r.TileMapManager.active_map.pixels_to_tiles(etile.coords):
return True
return 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 discover(timeout=1, retries=1):
"""Discover Raumfeld devices in the network :param timeout: The timeout in seconds :param retries: How often the search should be retried :returns: A list of raumfeld devices, sorted by name """ |
locations = []
group = ('239.255.255.250', 1900)
service = 'ssdp:urn:schemas-upnp-org:device:MediaRenderer:1' # 'ssdp:all'
message = '\r\n'.join(['M-SEARCH * HTTP/1.1',
'HOST: {group[0]}:{group[1]}',
'MAN: "ssdp:discover"',
'ST: {st}',
'MX: 1', '', '']).format(group=group, st=service)
socket.setdefaulttimeout(timeout)
for _ in range(retries):
sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
# socket options
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
# send group multicast
sock.sendto(message.encode('utf-8'), group)
while True:
try:
response = sock.recv(2048).decode('utf-8')
for line in response.split('\r\n'):
if line.startswith('Location: '):
location = line.split(' ')[1].strip()
if not location in locations:
locations.append(location)
except socket.timeout:
break
devices = [RaumfeldDevice(location) for location in locations]
# only return 'Virtual Media Player' and sort the list
return sorted([device for device in devices
if device.model_description == 'Virtual Media Player'],
key=lambda device: device.friendly_name) |
<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(cls, backend_id):
""" Return an instance of backend type """ |
for backend_class in cls._get_backends_classes():
if backend_class.id == backend_id:
return backend_class.create()
raise InvalidBackendError(
cls.backend_type,
backend_id,
get_installed_pools()[cls.backend_type]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_friends(self, user):
""" fetches the friends from g+ using the information on django-social-auth models user is an instance of UserSocialAuth. Notice that g+ contact api should be enabled in google cloud console and social auth scope has been set this way in settings.py GOOGLE_OAUTH_EXTRA_SCOPE = ['https://www.google.com/m8/feeds/'] Returns: collection of friend data dicts fetched from google contact api """ |
if USING_ALLAUTH:
social_app = SocialApp.objects.get_current('google')
oauth_token = SocialToken.objects.get(account=user, app=social_app).token
else:
social_auth_backend = GoogleOAuth2Backend()
# Get the access_token
tokens = social_auth_backend.tokens(user)
oauth_token = tokens['access_token']
credentials = gdata.gauth.OAuth2Token(
client_id=settings.GOOGLE_OAUTH2_CLIENT_ID,
client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET,
scope='https://www.google.com/m8/feeds/',
user_agent='gdata',
access_token=oauth_token
)
client = gdata.contacts.client.ContactsClient()
credentials.authorize(client)
contacts = client.get_contacts()
data = feedparser.parse(contacts.to_string())['entries']
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 fetch_friend_ids(self, user):
""" fetches friend email's from g+ Return: collection of friend emails (ids) """ |
friends = self.fetch_friends(user)
return [friend['ns1_email']['address']
for friend in friends
if 'ns1_email' in friend] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exception(self, exception):
""" Handle a unspecified exception and return the correct method that should be used for handling it. If the exception has the `can_redirect` property set to False, it is rendered to the browser. Otherwise, it will be redirected to the location provided in the `RedirectUri` object that is associated with the request. """ |
can_redirect = getattr(exception, "can_redirect", True)
redirect_uri = getattr(self, "redirect_uri", None)
if can_redirect and redirect_uri:
return self.redirect_exception(exception)
else:
return self.render_exception(exception) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redirect_exception(self, exception):
""" Build the query string for the exception and return a redirect to the redirect uri that was associated with the request. """ |
from django.http import QueryDict, HttpResponseRedirect
query = QueryDict("").copy()
query["error"] = exception.error
query["error_description"] = exception.reason
query["state"] = self.state
return HttpResponseRedirect(self.redirect_uri.url + "?" + query.urlencode()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_exception_js(self, exception):
""" Return a response with the body containing a JSON-formatter version of the exception. """ |
from .http import JsonResponse
response = {}
response["error"] = exception.error
response["error_description"] = exception.reason
return JsonResponse(response, status=getattr(exception, 'code', 400)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_dictionary(self, dict, *args):
""" Based on a provided `dict`, validate all of the contents of that dictionary that are provided. For each argument provided that isn't the dictionary, this will set the raw value of that key as the instance variable of the same name. It will then call the verification function named `verify_[argument]` to verify the data. """ |
for arg in args:
setattr(self, arg, dict.get(arg, None))
if hasattr(self, "verify_" + arg):
func = getattr(self, "verify_" + arg)
func() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_client_id(self):
""" Verify a provided client id against the database and set the `Client` object that is associated with it to `self.client`. TODO: Document all of the thrown exceptions. """ |
from .models import Client
from .exceptions.invalid_client import ClientDoesNotExist
from .exceptions.invalid_request import ClientNotProvided
if self.client_id:
try:
self.client = Client.objects.for_id(self.client_id)
# Catching also ValueError for the case when client_id doesn't contain an integer.
except (Client.DoesNotExist, ValueError):
raise ClientDoesNotExist()
else:
raise ClientNotProvided() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize(self):
"""Gets the normalized Vector""" |
length = self.length()
if length > 0:
self.X /= length
self.Y /= length
else:
print "Length 0, cannot normalize." |
<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_identity():
"""Check to see if this matrix is an identity matrix.""" |
for index, row in enumerate(self.dta):
if row[index] == 1:
for num, element in enumerate(row):
if num != index:
if element != 0:
return False
else:
return False
return True |
Subsets and Splits