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()
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 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_ler... |
<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:
... |
<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))
retu... |
<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.__i... |
<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.requ... |
<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.h... |
<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.d... |
<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:
prin... |
<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 t... |
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.
... |
<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 la... |
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 fir... |
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.cu... |
<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
re... |
<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 und... |
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 TileM... |
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... |
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 = R... |
<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... |
<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_fullsc... |
# 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
... |
<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. Ret... |
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 re... |
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 -... |
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_back... |
<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():
... |
<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. T... |
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
... |
<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 ... |
<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 nex... |
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['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 are_requirements_changed(config):
"""Check if any of the requirement files used by testenv is updated. :param tox.config.TestenvConfig config: Configuration ... |
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, fn... |
<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 p... |
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 requireme... |
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))
# Re... |
<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_til... |
<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 shoul... |
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"',
... |
<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 t... |
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_bac... |
<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... |
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 requ... |
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 pr... |
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: D... |
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... |
<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
No community queries yet
The top public SQL queries from the community will appear here once available.