code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
cpy_vec = Vector4()
cpy_vec.x = self.x
cpy_vec.y = self.y
cpy_vec.z = self.z
cpy_vec.w = self.w
return cpy_vec | def copy(self) | Create a copy of the Vector | 2.068546 | 1.878413 | 1.10122 |
vec3 = Vector3()
vec3.x = self.x
vec3.y = self.y
vec3.z = self.z
if self.w != 0:
vec3 /= self.w
return vec3 | def to_vec3(self) | Convert this vector4 instance into a vector3 instance. | 2.311937 | 2.123904 | 1.088532 |
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w)) | def length(self) | Gets the length of the Vector | 2.384764 | 1.997503 | 1.193872 |
vlength = self.length()
# Make sure the length isn't 0
if vlength > 0:
self.x /= vlength
self.y /= vlength
self.z /= vlength
self.w /= vlength
else:
return Vector4(0, 0, 0, 0) | def normalize(self) | Normalizes this Vector | 2.99754 | 2.573144 | 1.164933 |
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 | def clamp(self, clampVal) | Clamps all the components in the vector to the specified clampVal. | 1.631865 | 1.523172 | 1.071359 |
vec = Vector4()
vec[0] = xyzw[0]
vec[1] = xyzw[1]
vec[2] = xyzw[2]
vec[3] = xyzw[3]
return vec | def tuple_as_vec(xyzw) | Generates a Vector4 from a tuple or list. | 2.025819 | 1.646105 | 1.230674 |
ma4 = Matrix4(self.get_col(0),
self.get_col(1),
self.get_col(2),
self.get_col(3))
return ma4 | def transpose(self) | Create a transpose of this matrix. | 3.076916 | 2.896365 | 1.062337 |
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))
... | def translate(translationAmt) | Create a translation matrix. | 2.193403 | 2.010659 | 1.090887 |
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 | def scale(scaleAmt) | Create a scale matrix.
scaleAmt is a Vector3 defining the x, y, and z scale values. | 2.307681 | 1.99288 | 1.157963 |
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 | def z_rotate(rotationAmt) | Create a matrix that rotates around the z axis. | 1.979839 | 1.869648 | 1.058937 |
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 | def y_rotate(rotationAmt) | Create a matrix that rotates around the y axis. | 1.990944 | 1.859451 | 1.070716 |
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 | def x_rotate(rotationAmt) | Create a matrix that rotates around the x axis. | 1.918933 | 1.818668 | 1.055131 |
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) | def build_rotation(vec3) | Build a rotation matrix.
vec3 is a Vector3 defining the axis about which to rotate the object. | 2.868291 | 2.619722 | 1.094884 |
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
self.exit() | def __handle_events(self) | This is the place to put all event handeling. | 2.69617 | 2.279568 | 1.182755 |
# 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 p... | def __init_object(self) | Create a new object for the pool. | 8.502365 | 6.702691 | 1.2685 |
self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.0)) | def center_origin(self) | Sets the origin to the center of the image. | 3.080974 | 2.401816 | 1.282768 |
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) | def scale_to(self, width_height=Vector2()) | Scale the texture to the specfied width and height. | 2.335376 | 2.229574 | 1.047454 |
if self.__horizontal_flip is not val:
self.__horizontal_flip = val
self.image = pygame.transform.flip(self.untransformed_image, val, self.__vertical_flip) | def set_hflip(self, val) | val is True or False that determines if we should horizontally flip the surface or not. | 4.319691 | 3.731287 | 1.157695 |
self.image = pygame.image.load(file_path)
self.apply_texture(self.image) | 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. | 3.791865 | 3.754842 | 1.00986 |
self.image = pygame.transform.rotate(surface, self.__rotation)
self.__resize_surface_extents() | def __execute_rot(self, surface) | Executes the rotating operation | 8.919346 | 8.783593 | 1.015455 |
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())
... | def __handle_scale_rot(self) | Handle scaling and rotation of the surface | 4.18498 | 3.944278 | 1.061026 |
if self.is_visible:
if not (self.__scale[0] == 0 or self.__scale[1] == 0):
if self.image is not None:
# Create our rectangle to describe our sprite.
tmpRect = pygame.Rect(self.coords.X - self.__origin.X,
... | def draw(self, milliseconds, render_surface) | Draw the image to the specified surface. | 3.699862 | 3.641126 | 1.016131 |
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) | def load_font(self, font_path, font_size) | Load the specified font from a file. | 2.300066 | 2.266041 | 1.015015 |
font_surface = self.__font.render(self.__text, True, self.color)
self.__font_sprite.apply_texture(font_surface)
self.__font_sprite.center_origin() | def __render_onto_sprite(self) | Render the font onto a surface and store the surface into a sprite so we can do more complex stuff with it.
(such as rotation and scale) | 4.801295 | 3.67036 | 1.308127 |
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 | def initalize(self, physics_dta) | Prepare our particle for use.
physics_dta describes the velocity, coordinates, and acceleration of the particle. | 3.359773 | 3.268864 | 1.02781 |
# 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_p... | def __release_particle(self) | Pull a particle from the queue and add it to the active list. | 5.426266 | 4.822191 | 1.12527 |
super(SpriteSheet, self).load_texture(file_path)
self.__cell_bounds = cell_size
self.__generate_cells() | 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. | 6.920455 | 5.152992 | 1.342997 |
# 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 = sel... | def draw(self, milliseconds, surface, cell) | Draw out the specified cell | 3.378075 | 3.372218 | 1.001737 |
self.current_frame += 1
if self.current_frame >= self.end_frame:
# Wrap back to the beginning of the animation.
self.current_frame = 0 | def increment_frame(self) | Increment a frame of the animation. | 3.378851 | 2.84049 | 1.189531 |
self.__coords = value
for image in self.images:
image.coords = value | def set_coords(self, value) | Set all the images contained in the animation to the specified value. | 6.026499 | 3.980298 | 1.514082 |
self.__horizontal_flip = val
for image in self.images:
image.h_flip = val | def set_hflip(self, val) | Flip all the images in the animation list horizontally. | 5.619004 | 5.088886 | 1.104172 |
self.__vertical_flip = val
for image in self.images:
image.v_flip = val | def set_vflip(self, val) | Flip all the images in the animation list vertically. | 6.223464 | 5.40597 | 1.151221 |
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
ani... | def copy(self) | Create a copy of the animation. | 3.538799 | 3.206354 | 1.103683 |
if self.current_frame < len(self.images):
self.current_frame += 1
if self.current_frame >= len(self.images):
# Wrap back to the beginning of the animation if should_repeat is true.
if self.should_repeat:
self.current_frame = 0... | def increment_frame(self) | Increment a frame of the animation. | 2.825573 | 2.703743 | 1.04506 |
super(CollidableObj, self).draw(milliseconds, surface) | def draw(self, milliseconds, surface) | Render the bounds of this collision ojbect onto the specified surface. | 10.606109 | 6.169474 | 1.719127 |
if isinstance(other, AABoundingBox):
if self.rect.colliderect(other.rect):
return True
return False | def is_colliding(self, other) | Check to see if two AABoundingBoxes are colliding. | 4.767346 | 2.62553 | 1.815765 |
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:
... | def remove_object(collision_object) | Remove the collision object from the Manager | 5.669153 | 5.358154 | 1.058042 |
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.
... | 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 | 5.84428 | 5.377478 | 1.086807 |
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) | def draw(self, milliseconds, surface) | Render each of the collision objects onto the specified surface. | 3.248547 | 2.816064 | 1.153577 |
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 | def __wrap_index(self) | Wraps the current_index to the other side of the menu. | 2.568948 | 1.918347 | 1.339147 |
old_index = self.current_index
self.current_index -= 1
self.__wrap_index()
self.__handle_selections(old_index, self.current_index) | 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. | 4.789767 | 4.794428 | 0.999028 |
old_index = self.current_index
self.current_index += 1
self.__wrap_index()
self.__handle_selections(old_index, self.current_index) | 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. | 4.857996 | 4.862996 | 0.998972 |
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... | def __update_keyboard(self, milliseconds) | Use the keyboard to control selection of the buttons. | 3.379225 | 3.119237 | 1.08335 |
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 | def copy(self) | Create a copy of this MouseState and return it. | 2.715689 | 2.194166 | 1.237686 |
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
... | def query_state(self, StateType) | Is a button depressed?
True if a button is pressed, false otherwise. | 3.080486 | 2.591059 | 1.188891 |
return self.previous_mouse_state.query_state(MouseStateType) and (
not self.current_mouse_state.query_state(MouseStateType)) | 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 | 5.024014 | 4.475472 | 1.122566 |
for key in range(len(self.current_state.key_states)):
if self.is_down(key):
return True
return False | def is_any_down(self) | Is any button depressed? | 5.663507 | 4.81102 | 1.177195 |
for key in range(len(self.current_state.key_states)):
if self.is_clicked(key):
return True
return False | def is_any_clicked(self) | Is any button clicked? | 6.000334 | 5.381246 | 1.115046 |
boundingBox = AABoundingBox(None, collision_function, tag)
CollisionManager.add_object(boundingBox) | 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 | 10.232527 | 8.400354 | 1.218107 |
surface.blit(self.image, self.coords, self.source, special_flags=0) | def draw(self, milliseconds, surface) | Draw the image to the specified surface. | 8.658562 | 7.044921 | 1.22905 |
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 | 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. | 2.731202 | 2.604422 | 1.048679 |
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 | def clamp_within_range(self, x, y) | Clamp x and y so that they fall within range of the tilemap. | 1.793734 | 1.660722 | 1.080093 |
pixel_coords = Vector2()
pixel_coords.X = tiles[0] * self.spritesheet[0].width
pixel_coords.Y = tiles[1] * self.spritesheet[0].height
return pixel_coords | def tiles_to_pixels(self, tiles) | Convert tile coordinates into pixel coordinates | 3.755896 | 3.388115 | 1.10855 |
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 | def is_valid_tile(self, x, y) | Check to see if the requested tile is part of the tile map. | 2.126042 | 2.020876 | 1.05204 |
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) | def unload() | Unload the current map from the world. | 5.734318 | 5.036426 | 1.138569 |
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()
w... | def load(name) | Parse the tile map and add it to the world. | 3.84382 | 3.263071 | 1.177976 |
pos = self.pan - self.previous_pos
self.previous_pos = Vector2(self.pan.X, self.pan.Y)
return pos | def get_movement_delta(self) | Get the amount the camera has moved since get_movement_delta was last called. | 6.68708 | 5.041341 | 1.326449 |
self.pan = self.world_center
self.desired_pan = self.pos | def Reset(self) | Reset the camera back to its defaults. | 23.339733 | 17.303236 | 1.348865 |
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.camer... | def check_bounds(self) | Make sure the camera is not outside if its legal range. | 1.916111 | 1.728456 | 1.108568 |
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) | def get_cam_bounds(self) | Return the bounds of the camera in x, y, xMax, and yMax format. | 4.845872 | 4.443096 | 1.090652 |
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 | def update_view_bounds(self) | Update the camera's view bounds. | 2.398484 | 2.205837 | 1.087335 |
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 | def set_backbuffer(self, preferred_backbuffer_size, flags=0) | Create the backbuffer for the game. | 3.403125 | 3.060338 | 1.112009 |
# 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
... | 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. | 3.600166 | 3.651819 | 0.985856 |
vec = Vector2()
vec.X = self.backbuffer.get_width()
vec.Y = self.backbuffer.get_height()
return vec | def get_backbuffer_size(self) | Get the width and height of the backbuffer as a Vector2. | 4.085563 | 2.786688 | 1.4661 |
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 | 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. | 3.361062 | 3.551781 | 0.946303 |
obj = self.find_obj_by_tag(tag)
if obj != None:
self.remove_obj(obj)
return True
return False | 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. | 3.311438 | 3.037028 | 1.090355 |
if obj1.draw_order > obj2.draw_order:
return 1
elif obj1.draw_order < obj2.draw_order:
return -1
else:
return 0 | def __draw_cmp(self, obj1, obj2) | Defines how our drawable objects should be sorted | 2.111853 | 1.760282 | 1.199724 |
if obj1.update_order > obj2.update_order:
return 1
elif obj1.update_order < obj2.update_order:
return -1
else:
return 0 | def __up_cmp(self, obj1, obj2) | Defines how our updatable objects should be sorted | 2.092809 | 1.742552 | 1.201002 |
if self.__do_need_sort_up:
self.__up_objects.sort(key=cmp_to_key(self.__up_cmp))
self.__do_need_sort_up = False | def __sort_up(self) | Sort the updatable objects according to ascending order | 3.691977 | 3.025677 | 1.220215 |
if self.__do_need_sort_draw:
self.__draw_objects.sort(key=cmp_to_key(self.__draw_cmp))
self.__do_need_sort_draw = False | def __sort_draw(self) | Sort the drawable objects according to ascending order | 3.569148 | 2.98155 | 1.197078 |
self.__sort_up()
for obj in self.__up_objects:
obj.update(milliseconds) | def update(self, milliseconds) | Updates all of the objects in our world. | 10.284831 | 7.401448 | 1.38957 |
dirname = os.path.dirname(filename)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname) | def ensure_path(filename) | Check if path to `filename` exists and if not, create the necessary
intermediate directories. | 1.829885 | 2.213921 | 0.826536 |
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) | def locate_files(pattern, root_dir=os.curdir) | Locate all files matching fiven filename pattern in and below
supplied root directory. | 1.605229 | 1.807703 | 0.887993 |
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)) | def remove_files(root_dir) | Remove all files and directories in supplied root directory. | 1.692761 | 1.638894 | 1.032868 |
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 | 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... | 2.12435 | 2.534125 | 0.838297 |
if n_step > 1:
n_digit = int(nm.log10(n_step - 1) + 1)
if fill is None:
format = '%%%dd' % n_digit
else:
format = '%%%s%dd' % (fill, n_digit)
else:
n_digit, format = 0, None
return n_digit, format | def get_print_info(n_step, fill=None) | Returns the max. number of digits in range(n_step) and the corresponding
format string.
Examples:
>>> get_print_info(11)
(2, '%2d')
>>> get_print_info(8)
(1, '%1d')
>>> get_print_info(100)
(2, '%2d')
>>> get_print_info(101)
(3, '%3d')
>>> get_print_info(101, fill='0')
(... | 2.61089 | 2.58447 | 1.010223 |
ls = ''
while 1:
try:
line = fd.readline()
except EOFError:
break
if not line:
if no_eof:
raise EOFError
else:
break
ls = line.strip()
if ls and (ls[0] != '#'):
break
... | def skip_read_line(fd, no_eof=False) | Read the first non-empty line (if any) from the given file
object. Return an empty string at EOF, if `no_eof` is False. If it
is True, raise the EOFError instead. | 3.069296 | 2.862274 | 1.072328 |
out = ''
# Skip initial whitespace.
while 1:
ch = fd.read(1)
if ch.isspace(): continue
elif len(ch) == 0: return out
else: break
while not ch.isspace():
out = out + ch
ch = fd.read(1)
if len(ch) == 0: break
return out | def read_token(fd) | Read a single token (sequence of non-whitespace characters) from the
given file object.
Notes
-----
Consumes the first whitespace character after the token. | 3.039916 | 3.263434 | 0.931508 |
if n_col is None:
idx = fd.tell()
row = fd.readline().split()
fd.seek(idx)
n_col = len(row)
count = n_row * n_col
val = nm.fromfile(fd, sep=' ', count=count)
if val.shape[0] < count:
raise ValueError('(%d, %d) array reading failed!' % (n_row, n_col))
v... | def read_array(fd, n_row, n_col, dtype) | Read a NumPy array of shape `(n_row, n_col)` from the given file
object and cast it to type `dtype`.
If `n_col` is None, determine the number of columns automatically. | 2.90357 | 2.941738 | 0.987025 |
fd = pt.openFile(filename, mode='w', title=name)
try:
info = fd.createGroup('/', 'info')
fd.createArray(info, 'dtype', mtx.dtype.str)
fd.createArray(info, 'shape', mtx.shape)
fd.createArray(info, 'format', mtx.format)
data = fd.createGroup('/', 'data')
fd.cr... | def write_sparse_matrix_hdf5(filename, mtx, name='a sparse matrix') | Assume CSR/CSC. | 2.420455 | 2.319686 | 1.043441 |
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_a... | 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 | 2.468163 | 2.42968 | 1.015839 |
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_authenticat... | def authenticate(self, request) | Send the request through the authentication middleware that
is provided with DOAC and grab the user and token from it. | 3.735971 | 2.982746 | 1.252528 |
if yaml is not None:
if hasattr(yaml, 'read'):
settings.update(load_yaml(yaml.read()))
else:
if os.path.exists(yaml):
with open(yaml) as f:
settings.update(load_yaml(f.read()))
if env is not None:
for k, v in os.environ.it... | def override(settings, yaml=None, env=None) | :param dict settings: settings dict to be updated; usually it's ``globals()``
:param yaml: path to YAML file
:type yaml: str or FileIO
:param str env: prefix for environment variables | 1.933721 | 2.065571 | 0.936167 |
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
... | 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 availa... | 2.718595 | 2.828225 | 0.961237 |
# 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... | def get(self, request, provider=None) | prepare the social friend model | 3.600906 | 3.368708 | 1.068928 |
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... | 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 | 3.455106 | 3.336887 | 1.035428 |
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... | 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 | 5.283185 | 5.204957 | 1.01503 |
return sorted(
str(r.req)
for r in parse_requirements(requirement_file_path,
session=PipSession())
if r.req
) | 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 | 3.718537 | 5.277388 | 0.704617 |
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))
... | 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. | 2.980491 | 2.970005 | 1.003531 |
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 e... | def check_player_collision(self) | Check to see if we are colliding with the player. | 3.432693 | 3.227534 | 1.063565 |
if not isinstance(candidate, six.string_types):
candidate = str(candidate)
try:
evens = sum(int(c) for c in candidate[-1::-2])
odds = sum(LUHN_ODD_LOOKUP[int(c)] for c in candidate[-2::-2])
return ((evens + odds) % 10 == 0)
except ValueError: # Raised if an int conversi... | def luhn(candidate) | Checks a candidate number for validity according to the Luhn
algorithm (used in validation of, for example, credit cards).
Both numeric and string candidates are accepted. | 3.097112 | 3.151155 | 0.98285 |
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"',
... | 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 | 2.532049 | 2.545059 | 0.994888 |
if uri:
self.av_transport.SetAVTransportURI(
InstanceID=1, CurrentURI=uri, CurrentURIMetaData="")
else:
self.av_transport.Play(InstanceID=1, Speed=2) | def play(self, uri=None) | Start playing
:param uri: (optional) play a specific uri | 3.269388 | 3.70103 | 0.883373 |
response = self.rendering_control.GetMute(InstanceID=1, Channel=1)
return response.CurrentMute == 1 | def mute(self) | get/set the current mute state | 12.154474 | 9.355285 | 1.299209 |
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]
) | def get(cls, backend_id) | Return an instance of backend type | 5.156293 | 4.685192 | 1.100551 |
def json_dumps(obj):
return pd.io.json.dumps(obj)
_options = dict(options)
_data = data
def clean_function_str(key, n=15):
if key in _options.keys():
new_str = _options[key][:n].replace('\n', '')
new_str = new_str.replace('\r', '')
new... | def html(data, options, center=False, save=False,
save_name=None, save_path='saved', dated=True, notebook=True) | save=True will create a standalone HTML doc under localdir/saved (creating folfer save if necessary)
center=True will center the plot in the output cell, otherwise left-aligned by default. | 3.286177 | 3.329569 | 0.986968 |
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_... | 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 ... | 2.918336 | 2.866845 | 1.017961 |
friends = self.fetch_friends(user)
return [friend['ns1_email']['address']
for friend in friends
if 'ns1_email' in friend] | def fetch_friend_ids(self, user) | fetches friend email's from g+
Return:
collection of friend emails (ids) | 7.151327 | 7.116112 | 1.004949 |
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) | 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 ... | 3.545004 | 2.566093 | 1.381479 |
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.urle... | 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. | 3.345563 | 2.743102 | 1.219628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.