text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Flip all the images in the animation list horizontally. <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:> Flip all the images in the animation list vertically. <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:> Render the bounds of this collision ojbect onto the specified surface. <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:> Check to see if two AABoundingBoxes are colliding. <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:> Remove the collision object from the Manager <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:> Check to see if the specified object is colliding with any of the objects currently in the Collision Manager <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:> Render each of the collision objects onto the specified surface. <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:> Wraps the current_index to the other side of the menu. <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:> Try to select the button above the currently selected one. <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:> Try to select the button under the currently selected one. <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:> Use the keyboard to control selection of the buttons. <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:> Is a button depressed? <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:> Did the user depress and release the button to signify a click? <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:> Is any button depressed? <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:> Is any button clicked? <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:> Create a bounding box around this tile so that it can collide with objects not included in the TileManager <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:> Convert pixel coordinates into tile coordinates. <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:> Clamp x and y so that they fall within range of the tilemap. <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:> Check to see if the requested tile is part of the tile map. <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:> Unload the current map from the world. <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:> Parse the tile map and add it to the world. <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:> Get the amount the camera has moved since get_movement_delta was last called. <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:> Reset the camera back to its defaults. <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:> Make sure the camera is not outside if its legal range. <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:> Return the bounds of the camera in x, y, xMax, and yMax format. <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:> Create the backbuffer for the game. <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:> Sets the resolution to the display's native resolution. <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:> Get the width and height of the backbuffer as a Vector2. <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:> Search through all the objects in the world and <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:> Remove the first encountered object with the specified tag from the world. <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:> Defines how our drawable objects should be sorted <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:> Updates all of the objects in our world. <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:> Check if path to `filename` exists and if not, create the necessary <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:> Locate all files matching fiven filename pattern in and below <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:> Remove all files and directories in supplied root directory. <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:> Edit a file name by add a prefix, inserting a suffix in front of a file <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:> fethces friends from facebook using the oauth_token <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:> Send the request through the authentication middleware that <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:> Test for specific scopes that the access token has been authenticated for before <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:> prepare the social friend model <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:> checks if there is SocialFrind model record for the user <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:> Check if any of the requirement files used by testenv is updated. <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:> Parses requirements using the pip API. <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:> Check requirements file is updated relatively to prev. version of the file. <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:> Check to see if we are colliding with the player. <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:> Discover Raumfeld devices in the network <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:> fetches the friends from g+ using the <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:> fetches friend email's from g+ <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:> Handle a unspecified exception and return the correct method that should be used <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:> Build the query string for the exception and return a redirect to the <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:> Return a response with the body containing a JSON-formatter version of the exception. <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:> Based on a provided `dict`, validate all of the contents of that dictionary that are <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:> Verify a provided client id against the database and set the `Client` object that is <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:> Gets the normalized Vector <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:> Check to see if this matrix is an identity matrix. <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
<SYSTEM_TASK:> Start the game loop <END_TASK> <USER_TASK:> Description: def run(self): """Start the game loop"""
global world self.__is_running = True while(self.__is_running): #Our game loop #Catch our events self.__handle_events() #Update our clock self.__clock.tick(self.preferred_fps) elapsed_milliseconds = self.__clock.get_time() if 2 in self.event_flags: self.elapsed_milliseconds = 0 #Print the fps that the game is running at. if self.print_frames: self.fpsTimer += elapsed_milliseconds if self.fpsTimer > self.print_fps_frequency: print "FPS: ", self.__clock.get_fps() self.fpsTimer = 0.0 #Update all of our objects if not 0 in self.event_flags: world.update(elapsed_milliseconds) #Draw all of our objects if not 1 in self.event_flags: world.draw(elapsed_milliseconds) #Make our world visible pygame.display.flip()
<SYSTEM_TASK:> Grab an object from the pool. If the pool is empty, a new object will be generated and returned. <END_TASK> <USER_TASK:> Description: def request_object(self): """Grab an object from the pool. If the pool is empty, a new object will be generated and returned."""
obj_to_return = None if self.queue.count > 0: obj_to_return = self.__dequeue() else: #The queue is empty, generate a new item. self.__init_object() object_to_return = self.__dequeue() self.active_objects += 1 return obj_to_return
<SYSTEM_TASK:> Place a preexisting texture as the sprite's texture. <END_TASK> <USER_TASK:> Description: def apply_texture(self, image): """Place a preexisting texture as the sprite's texture."""
self.image = image.convert_alpha() self.untransformed_image = self.image.copy() ## self.rect.x = 0 ## self.rect.y = 0 ## self.rect.width = self.image.get_width() ## self.rect.height = self.image.get_height() self.source.x = 0 self.source.y = 0 self.source.width = self.image.get_width() self.source.height = self.image.get_height() center = Vector2(self.source.width / 2.0, self.source.height / 2.0) self.set_origin(center)
<SYSTEM_TASK:> Handles surface cleanup once a scale or rotation operation has been performed. <END_TASK> <USER_TASK:> Description: def __resize_surface_extents(self): """Handles surface cleanup once a scale or rotation operation has been performed."""
#Set the new location of the origin, as the surface size may increase with rotation self.__origin.X = self.image.get_width() * self.__untransformed_nor_origin.X self.__origin.Y = self.image.get_height() * self.__untransformed_nor_origin.Y ## #Update the size of the rectangle ## self.rect = self.image.get_rect() ## ## #Reset the coordinates of the rectangle to the user defined value ## self.set_coords(self.w_coords) #We must now resize the source rectangle to prevent clipping self.source.width = self.image.get_width() self.source.height = self.image.get_height()
<SYSTEM_TASK:> Execute the scaling operation <END_TASK> <USER_TASK:> Description: def __execute_scale(self, surface, size_to_scale_from): """Execute the scaling operation"""
x = size_to_scale_from[0] * self.__scale[0] y = size_to_scale_from[1] * self.__scale[1] scaled_value = (int(x), int(y)) ## #Find out what scaling technique we should use. ## if self.image.get_bitsize >= 24: ## #We have sufficient bit depth to run smooth scale ## self.image = pygame.transform.smoothscale(self.image, scaled_value) ## else: ##Surface doesn't support smooth scale, revert to regular scale self.image = pygame.transform.scale(self.image, scaled_value) self.__resize_surface_extents()
<SYSTEM_TASK:> Check to see if two circles are colliding. <END_TASK> <USER_TASK:> Description: def is_colliding(self, other): """Check to see if two circles are colliding."""
if isinstance(other, BoundingCircle): #Calculate the distance between two circles. distance = Vector2.distance(self.coords, other.coords) #Check to see if the sum of thier radi are greater than or equal to the distance. radi_sum = self.radius + other.radius if distance <= radi_sum: #There has been a collision ## print "Distance: ", distance, "\nRadi Sum: ", radi_sum ## print "Self Coords: ", self.coords, "\nOther Coords: ", other.coords return True #No collision. return False
<SYSTEM_TASK:> Check for and return the full list of objects colliding with collision_object <END_TASK> <USER_TASK:> Description: def query_all_collisions(collision_object): """ Check for and return the full list of objects colliding with collision_object """
global collidable_objects colliding = [] for obj in collidable_objects: #Make sure we don't check ourself against ourself. if obj is not collision_object: if collision_object.is_colliding(obj): #A collision has been detected. Add the object that we are colliding with. colliding.append(obj) return colliding
<SYSTEM_TASK:> A nightmare if looked at by a performance standpoint, but it gets the job done, <END_TASK> <USER_TASK:> Description: def run_brute(self): """ A nightmare if looked at by a performance standpoint, but it gets the job done, at least for now. Checks everything against everything and handles all collision reactions. """
global collidable_objects if self.collision_depth == self.SHALLOW_DEPTH: for obj in collidable_objects: collision = self.query_collision(obj) if collision is not None: #Execute the reactions for both of the colliding objects. obj.collision_response(collision) collision.collision_response(obj) elif self.collision_depth == self.DEEP_DEPTH: for obj in collidable_objects: collisions = self.query_all_collisions(obj) for collision in collisions: #Execute the reactions for both of the colliding objects. obj.collision_response(collision) collision.collision_response(obj)
<SYSTEM_TASK:> Set the keyboard as the object that controls the menu. <END_TASK> <USER_TASK:> Description: def set_keyboard_focus(self, move_up, move_down, select): """ Set the keyboard as the object that controls the menu. move_up is from the pygame.KEYS enum that defines what button causes the menu selection to move up. move_down is from the pygame.KEYS enum that defines what button causes the menu selection to move down. select is from the pygame.KEYS enum that defines what button causes the button to be selected. """
self.input_focus = StateTypes.KEYBOARD self.move_up_button = move_up self.move_down_button = move_down self.select_button = select
<SYSTEM_TASK:> Use the mouse to control selection of the buttons. <END_TASK> <USER_TASK:> Description: def __update_mouse(self, milliseconds): """ Use the mouse to control selection of the buttons. """
for button in self.gui_buttons: was_hovering = button.is_mouse_hovering button.update(milliseconds) #Provides capibilities for the mouse to select a button if the mouse is the focus of input. if was_hovering == False and button.is_mouse_hovering: #The user has just moved the mouse over the button. Set it as active. old_index = self.current_index self.current_index = self.gui_buttons.index(button) self.__handle_selections(old_index, self.current_index) elif Ragnarok.get_world().Mouse.is_clicked(self.mouse_select_button) and button.is_mouse_hovering: #The main mouse button has just depressed, click the current button. button.clicked_action()
<SYSTEM_TASK:> Warp the tile map object from one warp to another. <END_TASK> <USER_TASK:> Description: def warp_object(self, tileMapObj): """Warp the tile map object from one warp to another."""
print "Collision" if tileMapObj.can_warp: #Check to see if we need to load a different tile map if self.map_association != self.exitWarp.map_association: #Load the new tile map. TileMapManager.load(exitWarp.map_association) tileMapObj.parent.coords = self.exitWarp.coords
<SYSTEM_TASK:> Parses the collision map and sets the tile states as necessary. <END_TASK> <USER_TASK:> Description: def parse_collisions(self): """Parses the collision map and sets the tile states as necessary."""
fs = open(self.collisionmap_path, "r") self.collisionmap = fs.readlines() fs.close() x_index = 0 y_index = 0 for line in self.collisionmap: if line[0] is "#": continue for char in line: if char is "": continue #An empty character is the same as collision type 0 elif char is " ": char = "0" elif char is "s": #Placing the start location self.start_location = self.tiles_to_pixels(Vector2(x_index, y_index)) char = "0" elif not (char in self.tile_bindings): continue self.tiles[y_index][x_index].binding_type = self.tile_bindings[char] x_index += 1 x_index = 0 y_index += 1
<SYSTEM_TASK:> Draw out the tilemap. <END_TASK> <USER_TASK:> Description: def draw(self, milliseconds, surface): """Draw out the tilemap."""
self.drawn_rects = [] cam = Ragnarok.get_world().Camera cX, cY, cXMax, cYMax = cam.get_cam_bounds() #Draw out only the tiles visible to the camera. start_pos = self.pixels_to_tiles( (cX, cY) ) start_pos -= Vector2(1, 1) end_pos = self.pixels_to_tiles( (cXMax, cYMax) ) end_pos += Vector2(1, 1) start_pos.X, start_pos.Y = self.clamp_within_range(start_pos.X, start_pos.Y) end_pos.X, end_pos.Y = self.clamp_within_range(end_pos.X, end_pos.Y) cam_pos = cam.get_world_pos() for x in range(start_pos.X, end_pos.X + 1): for y in range(start_pos.Y, end_pos.Y + 1): tile = self.tiles[y][x] translate_posX = tile.coords.X - cam_pos.X translate_posY = tile.coords.Y - cam_pos.Y surface.blit(self.spritesheet.image, (translate_posX, translate_posY), tile.source, special_flags = 0)
<SYSTEM_TASK:> Draws all of the objects in our world. <END_TASK> <USER_TASK:> Description: def draw(self, milliseconds): """Draws all of the objects in our world."""
cam = Ragnarok.get_world().Camera camPos = cam.get_world_pos() self.__sort_draw() self.clear_backbuffer() for obj in self.__draw_objects: #Check to see if the object is visible to the camera before doing anything to it. if obj.is_static or obj.is_visible_to_camera(cam): #Offset all of our objects by the camera offset. old_pos = obj.coords xVal = obj.coords.X - camPos.X yVal = obj.coords.Y - camPos.Y obj.coords = Vector2(xVal, yVal) obj.draw(milliseconds, self.backbuffer) obj.coords = old_pos
<SYSTEM_TASK:> Time measurement utility. <END_TASK> <USER_TASK:> Description: def mark_time(times, msg=None): """ Time measurement utility. Measures times of execution between subsequent calls using time.clock(). The time is printed if the msg argument is not None. Examples -------- >>> times = [] >>> mark_time(times) ... do something >>> mark_time(times, 'elapsed') elapsed 0.1 ... do something else >>> mark_time(times, 'elapsed again') elapsed again 0.05 >>> times [0.10000000000000001, 0.050000000000000003] """
tt = time.clock() times.append(tt) if (msg is not None) and (len(times) > 1): print msg, times[-1] - times[-2]
<SYSTEM_TASK:> Import a file as a module. The module is explicitly reloaded to <END_TASK> <USER_TASK:> Description: def import_file(filename, package_name=None): """ Import a file as a module. The module is explicitly reloaded to prevent undesirable interactions. """
path = os.path.dirname(filename) if not path in sys.path: sys.path.append( path ) remove_path = True else: remove_path = False name = os.path.splitext(os.path.basename(filename))[0] if name in sys.modules: force_reload = True else: force_reload = False if package_name is not None: mod = __import__('.'.join((package_name, name)), fromlist=[name]) else: mod = __import__(name) if force_reload: reload(mod) if remove_path: sys.path.pop(-1) return mod
<SYSTEM_TASK:> Prints the line number and waits for a keypress. <END_TASK> <USER_TASK:> Description: def pause( msg = None ): """ Prints the line number and waits for a keypress. If you press: "q" ............. it will call sys.exit() any other key ... it will continue execution of the program This is useful for debugging. """
f = sys._getframe(1) ff = f.f_code if (msg): print '%s, %d: %s(), %d: %s' % (ff.co_filename, ff.co_firstlineno, ff.co_name, f.f_lineno, msg) else: print '%s, %d: %s(), %d' % (ff.co_filename, ff.co_firstlineno, ff.co_name, f.f_lineno) spause()
<SYSTEM_TASK:> fetches the user's social friends from its provider <END_TASK> <USER_TASK:> Description: def fetch_social_friend_ids(self, social_auth_user): """ fetches the user's social friends from its provider user is an instance of UserSocialAuth returns collection of ids this method can be used asynchronously as a background process (celery) """
# Type check self.assert_user_is_social_auth_user(social_auth_user) # Get friend finder backend friends_provider = SocialFriendsFinderBackendFactory.get_backend(social_auth_user.provider) # Get friend ids friend_ids = friends_provider.fetch_friend_ids(social_auth_user) return friend_ids
<SYSTEM_TASK:> fetches and matches social friends <END_TASK> <USER_TASK:> Description: def existing_social_friends(self, user_social_auth=None, friend_ids=None): """ fetches and matches social friends if friend_ids is None, then fetches them from social network Return: User collection """
# Type check self.assert_user_is_social_auth_user(user_social_auth) if not friend_ids: friend_ids = self.fetch_social_friend_ids(user_social_auth) # Convert comma sepearated string to the list if isinstance(friend_ids, basestring): friend_ids = eval(friend_ids) # Match them with the ones on the website if USING_ALLAUTH: return User.objects.filter(socialaccount__uid__in=friend_ids).all() else: return User.objects.filter(social_auth__uid__in=friend_ids).all()
<SYSTEM_TASK:> Return object with episode number attached to episode. <END_TASK> <USER_TASK:> Description: def get_object(self, queryset=None): """Return object with episode number attached to episode."""
if settings.PODCAST_SINGULAR: show = get_object_or_404(Show, id=settings.PODCAST_ID) else: show = get_object_or_404(Show, slug=self.kwargs['show_slug']) obj = get_object_or_404(Episode, show=show, slug=self.kwargs['slug']) index = Episode.objects.is_public_or_secret().filter(show=show, pub_date__lt=obj.pub_date).count() obj.index = index + 1 obj.index_next = obj.index + 1 obj.index_previous = obj.index - 1 return obj
<SYSTEM_TASK:> returns the given backend instance <END_TASK> <USER_TASK:> Description: def get_backend(self, backend_name): """ returns the given backend instance """
if backend_name == 'twitter': from social_friends_finder.backends.twitter_backend import TwitterFriendsProvider friends_provider = TwitterFriendsProvider() elif backend_name == 'facebook': from social_friends_finder.backends.facebook_backend import FacebookFriendsProvider friends_provider = FacebookFriendsProvider() elif backend_name == 'vkontakte-oauth2': from social_friends_finder.backends.vkontakte_backend import VKontakteFriendsProvider friends_provider = VKontakteFriendsProvider() else: raise NotImplementedError("provider: %s is not implemented") return friends_provider
<SYSTEM_TASK:> fethces friends from VKontakte using the access_token <END_TASK> <USER_TASK:> Description: def fetch_friends(self, user): """ fethces friends from VKontakte using the access_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 VKontakte """
if USING_ALLAUTH: raise NotImplementedError("VKontakte support is not implemented for django-allauth") #social_app = SocialApp.objects.get_current('vkontakte') #oauth_token = SocialToken.objects.get(account=user, app=social_app).token else: social_auth_backend = VKOAuth2Backend() # Get the access_token tokens = social_auth_backend.tokens(user) oauth_token = tokens['access_token'] api = vkontakte.API(token=oauth_token) return api.get("friends.get")
<SYSTEM_TASK:> Convenience method for adding an element with no children. <END_TASK> <USER_TASK:> Description: def addQuickElement(self, name, contents=None, attrs=None, escape=True, cdata=False): """Convenience method for adding an element with no children."""
if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents, escape=escape, cdata=cdata) self.endElement(name)
<SYSTEM_TASK:> Sets a the value in the TOML file located by the given key sequence. <END_TASK> <USER_TASK:> Description: def _setitem_with_key_seq(self, key_seq, value): """ Sets a the value in the TOML file located by the given key sequence. Example: self._setitem(('key1', 'key2', 'key3'), 'text_value') is equivalent to doing self['key1']['key2']['key3'] = 'text_value' """
table = self key_so_far = tuple() for key in key_seq[:-1]: key_so_far += (key,) self._make_sure_table_exists(key_so_far) table = table[key] table[key_seq[-1]] = value
<SYSTEM_TASK:> Sets a the array value in the TOML file located by the given key sequence. <END_TASK> <USER_TASK:> Description: def _array_setitem_with_key_seq(self, array_name, index, key_seq, value): """ Sets a the array value in the TOML file located by the given key sequence. Example: self._array_setitem(array_name, index, ('key1', 'key2', 'key3'), 'text_value') is equivalent to doing self.array(array_name)[index]['key1']['key2']['key3'] = 'text_value' """
table = self.array(array_name)[index] key_so_far = tuple() for key in key_seq[:-1]: key_so_far += (key,) new_table = self._array_make_sure_table_exists(array_name, index, key_so_far) if new_table is not None: table = new_table else: table = table[key] table[key_seq[-1]] = value
<SYSTEM_TASK:> Returns a sequence of TopLevel instances for the current state of this table. <END_TASK> <USER_TASK:> Description: def _detect_toplevels(self): """ Returns a sequence of TopLevel instances for the current state of this table. """
return tuple(e for e in toplevels.identify(self.elements) if isinstance(e, toplevels.Table))
<SYSTEM_TASK:> Updates the fallbacks on all the table elements to make relative table access possible. <END_TASK> <USER_TASK:> Description: def _update_table_fallbacks(self, table_toplevels): """ Updates the fallbacks on all the table elements to make relative table access possible. Raises DuplicateKeysError if appropriate. """
if len(self.elements) <= 1: return def parent_of(toplevel): # Returns an TopLevel parent of the given entry, or None. for parent_toplevel in table_toplevels: if toplevel.name.sub_names[:-1] == parent_toplevel.name.sub_names: return parent_toplevel for entry in table_toplevels: if entry.name.is_qualified: parent = parent_of(entry) if parent: child_name = entry.name.without_prefix(parent.name) parent.table_element.set_fallback({child_name.sub_names[0]: entry.table_element})
<SYSTEM_TASK:> Returns the array of tables with the given name. <END_TASK> <USER_TASK:> Description: def array(self, name): """ Returns the array of tables with the given name. """
if name in self._navigable: if isinstance(self._navigable[name], (list, tuple)): return self[name] else: raise NoArrayFoundError else: return ArrayOfTables(toml_file=self, name=name)
<SYSTEM_TASK:> Appends more elements to the contained internal elements. <END_TASK> <USER_TASK:> Description: def append_elements(self, elements): """ Appends more elements to the contained internal elements. """
self._elements = self._elements + list(elements) self._on_element_change()
<SYSTEM_TASK:> Prepends more elements to the contained internal elements. <END_TASK> <USER_TASK:> Description: def prepend_elements(self, elements): """ Prepends more elements to the contained internal elements. """
self._elements = list(elements) + self._elements self._on_element_change()
<SYSTEM_TASK:> Gets called by FreshTable instances when they get written to. <END_TASK> <USER_TASK:> Description: def append_fresh_table(self, fresh_table): """ Gets called by FreshTable instances when they get written to. """
if fresh_table.name: elements = [] if fresh_table.is_array: elements += [element_factory.create_array_of_tables_header_element(fresh_table.name)] else: elements += [element_factory.create_table_header_element(fresh_table.name)] elements += [fresh_table, element_factory.create_newline_element()] self.append_elements(elements) else: # It's an anonymous table self.prepend_elements([fresh_table, element_factory.create_newline_element()])
<SYSTEM_TASK:> Executes the given shell command and returns its output. <END_TASK> <USER_TASK:> Description: def shell_exec(command): """Executes the given shell command and returns its output."""
out = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] return out.decode('utf-8')
<SYSTEM_TASK:> Get locale. <END_TASK> <USER_TASK:> Description: def get_locale(): """Get locale. Searches for locale in the following the order: - User has specified a concrete language in the query string. - Current session has a language set. - User has a language set in the profile. - Headers of the HTTP request. - Default language from ``BABEL_DEFAULT_LOCALE``. Will only accept languages defined in ``I18N_LANGUAGES``. """
locales = [x[0] for x in current_app.extensions['invenio-i18n'].get_languages()] # In the case of the user specifies a language for the resource. if 'ln' in request.args: language = request.args.get('ln') if language in locales: return language # In the case of the user has set a language for the current session. language_session_key = current_app.config['I18N_SESSION_KEY'] if language_session_key in session: language = session[language_session_key] if language in locales: return language # In the case of the registered user has a prefered language. language_user_key = current_app.config['I18N_USER_LANG_ATTR'] if language_user_key is not None and \ hasattr(current_app, 'login_manager') and \ current_user.is_authenticated: language = getattr(current_user, language_user_key, None) if language is not None and language in locales: return language # Using the headers that the navigator has sent. headers_best_match = request.accept_languages.best_match(locales) if headers_best_match is not None: return headers_best_match # If there is no way to know the language, return BABEL_DEFAULT_LOCALE return current_app.config['BABEL_DEFAULT_LOCALE']
<SYSTEM_TASK:> This is an alternative "constructor" for the DBVuln class which loads <END_TASK> <USER_TASK:> Description: def from_file(cls, db_file, language=DEFAULT_LANG): """ This is an alternative "constructor" for the DBVuln class which loads the data from a file. :param db_file: Contents of a json file from the DB :param language: The user's language (en, es, etc.) """
data = DBVuln.load_from_json(db_file, language=language) return cls(**data)
<SYSTEM_TASK:> This is an alternative "constructor" for the DBVuln class which searches <END_TASK> <USER_TASK:> Description: def from_id(cls, _id, language=DEFAULT_LANG): """ This is an alternative "constructor" for the DBVuln class which searches the db directory to find the right file for the provided _id """
db_file = DBVuln.get_file_for_id(_id, language=language) data = DBVuln.load_from_json(db_file, language=language) return cls(**data)
<SYSTEM_TASK:> Given _id, search the DB for the file which contains the data <END_TASK> <USER_TASK:> Description: def get_file_for_id(_id, language=DEFAULT_LANG): """ Given _id, search the DB for the file which contains the data :param _id: The id to search (int) :param language: The user's language (en, es, etc.) :return: The filename """
file_start = '%s-' % _id json_path = DBVuln.get_json_path(language=language) for _file in os.listdir(json_path): if _file.startswith(file_start): return os.path.join(json_path, _file) raise NotFoundException('No data for ID %s' % _id)
<SYSTEM_TASK:> Parses the JSON data and returns it <END_TASK> <USER_TASK:> Description: def load_from_json(db_file, language=DEFAULT_LANG): """ Parses the JSON data and returns it :param db_file: File and path pointing to the JSON file to parse :param language: The user's language (en, es, etc.) :raises: All kind of exceptions if the file doesn't exist or JSON is invalid. :return: None """
# There are a couple of things I don't do here, and are on purpose: # - I want to fail if the file doesn't exist # - I want to fail if the file doesn't contain valid JSON raw = json.loads(file(db_file).read()) # Here I don't do any error handling either, I expect the JSON files to # be valid data = { '_id': raw['id'], 'title': raw['title'], 'description': DBVuln.handle_ref(raw['description'], language=language), 'severity': raw['severity'], 'wasc': raw.get('wasc', []), 'tags': raw.get('tags', []), 'cwe': raw.get('cwe', []), 'owasp_top_10': raw.get('owasp_top_10', {}), 'fix_effort': raw['fix']['effort'], 'fix_guidance': DBVuln.handle_ref(raw['fix']['guidance'], language=language), 'references': DBVuln.handle_references(raw.get('references', [])), 'db_file': db_file, } return data
<SYSTEM_TASK:> Mounts the sftp system if it's not already mounted. <END_TASK> <USER_TASK:> Description: def mount(self): """Mounts the sftp system if it's not already mounted."""
if self.mounted: return self._mount_point_local_create() if len(self.system.mount_opts) == 0: sshfs_opts = "" else: sshfs_opts = " -o %s" % " -o ".join(self.system.mount_opts) if self.system.auth_method == self.system.AUTH_METHOD_PUBLIC_KEY: ssh_opts = '-o PreferredAuthentications=publickey -i %s' % self.system.ssh_key elif self.system.auth_method: ssh_opts = '-o PreferredAuthentications=%s' % self.system.auth_method else: ssh_opts = '-o PreferredAuthentications=password' cmd = ("{cmd_before_mount} &&" " sshfs -o ssh_command=" "'ssh -o ConnectTimeout={timeout} -p {port} {ssh_opts}'" " {sshfs_opts} {user}@{host}:{remote_path} {local_path}") cmd = cmd.format( cmd_before_mount = self.system.cmd_before_mount, timeout = self.SSH_CONNECT_TIMEOUT, port = self.system.port, ssh_opts = ssh_opts, sshfs_opts = sshfs_opts, host = self.system.host, user = self.system.user, remote_path = self.mount_point_remote, local_path = self.mount_point_local, ) output = shell_exec(cmd).strip() if not self.mounted: # Clean up the directory tree self._mount_point_local_delete() if output == '': output = 'Mounting failed for a reason unknown to sftpman.' raise SftpMountException(cmd, output)
<SYSTEM_TASK:> Unmounts the sftp system if it's currently mounted. <END_TASK> <USER_TASK:> Description: def unmount(self): """Unmounts the sftp system if it's currently mounted."""
if not self.mounted: return # Try to unmount properly. cmd = 'fusermount -u %s' % self.mount_point_local shell_exec(cmd) # The filesystem is probably still in use. # kill sshfs and re-run this same command (which will work then). if self.mounted: self._kill() shell_exec(cmd) self._mount_point_local_delete()
<SYSTEM_TASK:> Return an API wrapper for the given order book. <END_TASK> <USER_TASK:> Description: def book(self, name): """Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookError: If an invalid order book is given. **Example**: .. doctest:: >>> from quadriga import QuadrigaClient >>> >>> client = QuadrigaClient() >>> >>> eth = client.book('eth_cad').get_ticker() # doctest:+ELLIPSIS >>> btc = client.book('btc_cad').get_ticker() # doctest:+ELLIPSIS """
self._validate_order_book(name) return OrderBook(name, self._rest_client, self._logger)
<SYSTEM_TASK:> Return the deposit address for the given major currency. <END_TASK> <USER_TASK:> Description: def get_deposit_address(self, currency): """Return the deposit address for the given major currency. :param currency: Major currency name in lowercase (e.g. "btc", "eth"). :type currency: str | unicode :return: Deposit address. :rtype: str | unicode """
self._validate_currency(currency) self._log('get deposit address for {}'.format(currency)) coin_name = self.major_currencies[currency] return self._rest_client.post( endpoint='/{}_deposit_address'.format(coin_name) )
<SYSTEM_TASK:> Withdraw a major currency from QuadrigaCX to the given wallet. <END_TASK> <USER_TASK:> Description: def withdraw(self, currency, amount, address): """Withdraw a major currency from QuadrigaCX to the given wallet. :param currency: Major currency name in lowercase (e.g. "btc", "eth"). :type currency: str | unicode :param amount: Withdrawal amount. :type amount: int | float | str | unicode | decimal.Decimal :param address: Wallet address. :type address: str | unicode .. warning:: Specifying incorrect major currency or wallet address could result in permanent loss of your coins. Please be careful when using this method! """
self._validate_currency(currency) self._log('withdraw {} {} to {}'.format(amount, currency, address)) coin_name = self.major_currencies[currency] return self._rest_client.post( endpoint='/{}_withdrawal'.format(coin_name) )
<SYSTEM_TASK:> Add a node to cluster. <END_TASK> <USER_TASK:> Description: def add_node(self, node): """Add a node to cluster. :param node: should be formated like this `{"addr": "", "role": "slave", "master": "master_node_id"} """
new = ClusterNode.from_uri(node["addr"]) cluster_member = self.nodes[0] check_new_nodes([new], [cluster_member]) new.meet(cluster_member.host, cluster_member.port) self.nodes.append(new) self.wait() if node["role"] != "slave": return if "master" in node: target = self.get_node(node["master"]) if not target: raise NodeNotFound(node["master"]) else: masters = sorted(self.masters, key=lambda x: len(x.slaves(x.name))) target = masters[0] new.replicate(target.name) new.flush_cache() target.flush_cache()
<SYSTEM_TASK:> Set Babel localization in request context. <END_TASK> <USER_TASK:> Description: def set_locale(ln): """Set Babel localization in request context. :param ln: Language identifier. """
ctx = _request_ctx_stack.top if ctx is None: raise RuntimeError('Working outside of request context.') new_locale = current_app.extensions['babel'].load_locale(ln) old_locale = getattr(ctx, 'babel_locale', None) setattr(ctx, 'babel_locale', new_locale) yield setattr(ctx, 'babel_locale', old_locale)
<SYSTEM_TASK:> Load translations from an entry point. <END_TASK> <USER_TASK:> Description: def add_entrypoint(self, entry_point_group): """Load translations from an entry point."""
for ep in iter_entry_points(group=entry_point_group): if not resource_isdir(ep.module_name, 'translations'): continue dirname = resource_filename(ep.module_name, 'translations') self.add_path(dirname)