text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> fethces friend id's from twitter <END_TASK> <USER_TASK:> Description: def fetch_friend_ids(self, user): """ fethces friend id's from twitter Return: collection of friend ids """
friends = self.fetch_friends(user) friend_ids = [] for friend in friends: friend_ids.append(friend.id) return friend_ids
<SYSTEM_TASK:> Synthesize a output numpy docstring section. <END_TASK> <USER_TASK:> Description: def merge_section(key, prnt_sec, child_sec): """ Synthesize a output numpy docstring section. Parameters ---------- key: str The numpy-section being merged. prnt_sec: Optional[str] The docstring section from the parent's attribute. child_sec: Optional[str] The docstring section from the child's attribute. Returns ------- Optional[str] The output docstring section."""
if prnt_sec is None and child_sec is None: return None if key == "Short Summary": header = '' else: header = "\n".join((key, "".join("-" for i in range(len(key))), "")) if child_sec is None: body = prnt_sec else: body = child_sec return header + body
<SYSTEM_TASK:> Accepts an ordered sequence of TopLevel instances and returns a navigable object structure representation of the <END_TASK> <USER_TASK:> Description: def structure(table_toplevels): """ Accepts an ordered sequence of TopLevel instances and returns a navigable object structure representation of the TOML file. """
table_toplevels = tuple(table_toplevels) obj = NamedDict() last_array_of_tables = None # The Name of the last array-of-tables header for toplevel in table_toplevels: if isinstance(toplevel, toplevels.AnonymousTable): obj[''] = toplevel.table_element elif isinstance(toplevel, toplevels.Table): if last_array_of_tables and toplevel.name.is_prefixed_with(last_array_of_tables): seq = obj[last_array_of_tables] unprefixed_name = toplevel.name.without_prefix(last_array_of_tables) seq[-1] = CascadeDict(seq[-1], NamedDict({unprefixed_name: toplevel.table_element})) else: obj[toplevel.name] = toplevel.table_element else: # It's an ArrayOfTables if last_array_of_tables and toplevel.name != last_array_of_tables and \ toplevel.name.is_prefixed_with(last_array_of_tables): seq = obj[last_array_of_tables] unprefixed_name = toplevel.name.without_prefix(last_array_of_tables) if unprefixed_name in seq[-1]: seq[-1][unprefixed_name].append(toplevel.table_element) else: cascaded_with = NamedDict({unprefixed_name: [toplevel.table_element]}) seq[-1] = CascadeDict(seq[-1], cascaded_with) else: obj.append(toplevel.name, toplevel.table_element) last_array_of_tables = toplevel.name return obj
<SYSTEM_TASK:> Removes all unused and expired authorization codes from the database. <END_TASK> <USER_TASK:> Description: def prune_old_authorization_codes(): """ Removes all unused and expired authorization codes from the database. """
from .compat import now from .models import AuthorizationCode AuthorizationCode.objects.with_expiration_before(now()).delete()
<SYSTEM_TASK:> Imports the module for a DOAC handler based on the string representation of the module path that is provided. <END_TASK> <USER_TASK:> Description: def get_handler(handler_name): """ Imports the module for a DOAC handler based on the string representation of the module path that is provided. """
from .conf import options handlers = options.handlers for handler in handlers: handler_path = handler.split(".") name = handler_path[-2] if handler_name == name: handler_module = __import__(".".join(handler_path[:-1]), {}, {}, str(handler_path[-1])) return getattr(handler_module, handler_path[-1])() return None
<SYSTEM_TASK:> Generates the error header for a request using a Bearer token based on a given OAuth exception. <END_TASK> <USER_TASK:> Description: def request_error_header(exception): """ Generates the error header for a request using a Bearer token based on a given OAuth exception. """
from .conf import options header = "Bearer realm=\"%s\"" % (options.realm, ) if hasattr(exception, "error"): header = header + ", error=\"%s\"" % (exception.error, ) if hasattr(exception, "reason"): header = header + ", error_description=\"%s\"" % (exception.reason, ) return header
<SYSTEM_TASK:> Set the default starting location of our character. <END_TASK> <USER_TASK:> Description: def set_default_pos(self, defaultPos): """Set the default starting location of our character."""
self.coords = defaultPos self.velocity = r.Vector2() self.desired_position = defaultPos r.Ragnarok.get_world().Camera.pan = self.coords r.Ragnarok.get_world().Camera.desired_pan = self.coords
<SYSTEM_TASK:> Reset the location of the cloud once it has left the viewable area of the screen. <END_TASK> <USER_TASK:> Description: def __generate_location(self): """ Reset the location of the cloud once it has left the viewable area of the screen. """
screen_width = world.get_backbuffer_size().X self.movement_speed = random.randrange(10, 25) # This line of code places the cloud to the right of the viewable screen, so it appears to # gradually move in from the right instead of randomally appearing on some portion of the viewable # window. self.coords = R.Vector2(screen_width + self.image.get_width(), random.randrange(0, 100))
<SYSTEM_TASK:> True if a line consists only of a single punctuation character. <END_TASK> <USER_TASK:> Description: def is_delimiter(line): """ True if a line consists only of a single punctuation character."""
return bool(line) and line[0] in punctuation and line[0]*len(line) == line
<SYSTEM_TASK:> Extract the headers, delimiters, and text from reST-formatted docstrings. <END_TASK> <USER_TASK:> Description: def parse_rest_doc(doc): """ Extract the headers, delimiters, and text from reST-formatted docstrings. Parameters ---------- doc: Union[str, None] Returns ------- Dict[str, Section] """
class Section(object): def __init__(self, header=None, body=None): self.header = header # str self.body = body # str doc_sections = OrderedDict([('', Section(header=''))]) if not doc: return doc_sections doc = cleandoc(doc) lines = iter(doc.splitlines()) header = '' body = [] section = Section(header=header) line = '' while True: try: prev_line = line line = next(lines) # section header encountered if is_delimiter(line) and 0 < len(prev_line) <= len(line): # prev-prev-line is overline if len(body) >= 2 and len(body[-2]) == len(line) \ and body[-2][0] == line[0] and is_delimiter(body[-2]): lim = -2 else: lim = -1 section.body = "\n".join(body[:lim]).rstrip() doc_sections.update([(header.strip(), section)]) section = Section(header="\n".join(body[lim:] + [line])) header = prev_line body = [] line = '' else: body.append(line) except StopIteration: section.body = "\n".join(body).rstrip() doc_sections.update([(header.strip(), section)]) break return doc_sections
<SYSTEM_TASK:> Parse an apple .strings file and create a stringset with <END_TASK> <USER_TASK:> Description: def parse_strings(content="", filename=None): """Parse an apple .strings file and create a stringset with all entries in the file. See http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPInternational/Articles/StringsFiles.html for details. """
if filename is not None: content = _get_content(filename=filename) stringset = [] f = content if f.startswith(u'\ufeff'): f = f.lstrip(u'\ufeff') #regex for finding all comments in a file cp = r'(?:/\*(?P<comment>(?:[^*]|(?:\*+[^*/]))*\**)\*/)' p = re.compile(r'(?:%s[ \t]*[\n]|[\r\n]|[\r]){0,1}(?P<line>(("(?P<key>[^"\\]*(?:\\.[^"\\]*)*)")|(?P<property>\w+))\s*=\s*"(?P<value>[^"\\]*(?:\\.[^"\\]*)*)"\s*;)'%cp, re.DOTALL|re.U) #c = re.compile(r'\s*/\*(.|\s)*?\*/\s*', re.U) c = re.compile(r'//[^\n]*\n|/\*(?:.|[\r\n])*?\*/', re.U) ws = re.compile(r'\s+', re.U) end=0 start = 0 for i in p.finditer(f): start = i.start('line') end_ = i.end() key = i.group('key') comment = i.group('comment') or '' if not key: key = i.group('property') value = i.group('value') while end < start: m = c.match(f, end, start) or ws.match(f, end, start) if not m or m.start() != end: print("Invalid syntax: %s" %\ f[end:start]) end = m.end() end = end_ key = _unescape_key(key) stringset.append({'key': key, 'value': _unescape(value), 'comment': comment}) return stringset
<SYSTEM_TASK:> Outputs an ordered sequence of instances of TopLevel types. <END_TASK> <USER_TASK:> Description: def identify(file_elements): """ Outputs an ordered sequence of instances of TopLevel types. Elements start with an optional TableElement, followed by zero or more pairs of (TableHeaderElement, TableElement). """
if not file_elements: return _validate_file_elements(file_elements) # An iterator over enumerate(the non-metadata) elements iterator = PeekableIterator((element_i, element) for (element_i, element) in enumerate(file_elements) if element.type != elements.TYPE_METADATA) try: _, first_element = iterator.peek() if isinstance(first_element, TableElement): iterator.next() yield AnonymousTable(first_element) except KeyError: pass except StopIteration: return for element_i, element in iterator: if not isinstance(element, TableHeaderElement): continue # If TableHeader of a regular table, return Table following it if not element.is_array_of_tables: table_element_i, table_element = next(iterator) yield Table(names=element.names, table_element=table_element) # If TableHeader of an array of tables, do your thing else: table_element_i, table_element = next(iterator) yield ArrayOfTables(names=element.names, table_element=table_element)
<SYSTEM_TASK:> Create an instance of the main character and return it. <END_TASK> <USER_TASK:> Description: def load_character(tile_map, gamescreen): """Create an instance of the main character and return it."""
tile_obj = thc.TileHeroCharacter(tile_map, gamescreen) tile_obj.load_texture("..//Textures//character.png") tile_obj.origin = r.Vector2(0, 0) tile_obj.hazard_touched_method = hazard_touched_method tile_obj.special_touched_method = special_touched_method return tile_obj
<SYSTEM_TASK:> The authorzation URL that should be provided to the user <END_TASK> <USER_TASK:> Description: def auth_uri(self): """The authorzation URL that should be provided to the user"""
return self.oauth.auth_uri(redirect_uri=self.redirect_uri, scope=self.scope)
<SYSTEM_TASK:> Fetch user journals from user <END_TASK> <USER_TASK:> Description: def browse_userjournals(self, username, featured=False, offset=0, limit=10): """Fetch user journals from user :param username: name of user to retrieve journals from :param featured: fetch only featured or not :param offset: the pagination offset :param limit: the pagination limit """
response = self._req('/browse/user/journals', { "username":username, "featured":featured, "offset":offset, "limit":limit }) deviations = [] for item in response['results']: d = Deviation() d.from_dict(item) deviations.append(d) return { "results" : deviations, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch More Like This preview result for a seed deviation <END_TASK> <USER_TASK:> Description: def browse_morelikethis_preview(self, seed): """Fetch More Like This preview result for a seed deviation :param seed: The deviationid to fetch more like """
response = self._req('/browse/morelikethis/preview', { "seed":seed }) returned_seed = response['seed'] author = User() author.from_dict(response['author']) more_from_artist = [] for item in response['more_from_artist']: d = Deviation() d.from_dict(item) more_from_artist.append(d) more_from_da = [] for item in response['more_from_da']: d = Deviation() d.from_dict(item) more_from_da.append(d) return { "seed" : returned_seed, "author" : author, "more_from_artist" : more_from_artist, "more_from_da" : more_from_da }
<SYSTEM_TASK:> Fetch deviations from public endpoints <END_TASK> <USER_TASK:> Description: def browse(self, endpoint="hot", category_path="", seed="", q="", timerange="24hr", tag="", offset=0, limit=10): """Fetch deviations from public endpoints :param endpoint: The endpoint from which the deviations will be fetched (hot/morelikethis/newest/undiscovered/popular/tags) :param category_path: category path to fetch from :param q: Search query term :param timerange: The timerange :param tag: The tag to browse :param offset: the pagination offset :param limit: the pagination limit """
if endpoint == "hot": response = self._req('/browse/hot', { "category_path":category_path, "offset":offset, "limit":limit }) elif endpoint == "morelikethis": if seed: response = self._req('/browse/morelikethis', { "seed":seed, "category_path":category_path, "offset":offset, "limit":limit }) else: raise DeviantartError("No seed defined.") elif endpoint == "newest": response = self._req('/browse/newest', { "category_path":category_path, "q":q, "offset":offset, "limit":limit }) elif endpoint == "undiscovered": response = self._req('/browse/undiscovered', { "category_path":category_path, "offset":offset, "limit":limit }) elif endpoint == "popular": response = self._req('/browse/popular', { "category_path":category_path, "q":q, "timerange":timerange, "offset":offset, "limit":limit }) elif endpoint == "tags": if tag: response = self._req('/browse/tags', { "tag":tag, "offset":offset, "limit":limit }) else: raise DeviantartError("No tag defined.") else: raise DeviantartError("Unknown endpoint.") deviations = [] for item in response['results']: d = Deviation() d.from_dict(item) deviations.append(d) return { "results" : deviations, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch the categorytree <END_TASK> <USER_TASK:> Description: def get_categories(self, catpath="/"): """Fetch the categorytree :param catpath: The category to list children of """
response = self._req('/browse/categorytree', { "catpath":catpath }) categories = response['categories'] return categories
<SYSTEM_TASK:> Searches for tags <END_TASK> <USER_TASK:> Description: def search_tags(self, tag_name): """Searches for tags :param tag_name: Partial tag name to get autocomplete suggestions for """
response = self._req('/browse/tags/search', { "tag_name":tag_name }) tags = list() for item in response['results']: tags.append(item['tag_name']) return tags
<SYSTEM_TASK:> Fetch a single deviation <END_TASK> <USER_TASK:> Description: def get_deviation(self, deviationid): """Fetch a single deviation :param deviationid: The deviationid you want to fetch """
response = self._req('/deviation/{}'.format(deviationid)) d = Deviation() d.from_dict(response) return d
<SYSTEM_TASK:> Fetch a list of users who faved the deviation <END_TASK> <USER_TASK:> Description: def whofaved_deviation(self, deviationid, offset=0, limit=10): """Fetch a list of users who faved the deviation :param deviationid: The deviationid you want to fetch :param offset: the pagination offset :param limit: the pagination limit """
response = self._req('/deviation/whofaved', get_data={ 'deviationid' : deviationid, 'offset' : offset, 'limit' : limit }) users = [] for item in response['results']: u = {} u['user'] = User() u['user'].from_dict(item['user']) u['time'] = item['time'] users.append(u) return { "results" : users, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch deviation metadata for a set of deviations <END_TASK> <USER_TASK:> Description: def get_deviation_metadata(self, deviationids, ext_submission=False, ext_camera=False, ext_stats=False, ext_collection=False): """Fetch deviation metadata for a set of deviations :param deviationid: The deviationid you want to fetch :param ext_submission: Return extended information - submission information :param ext_camera: Return extended information - EXIF information (if available) :param ext_stats: Return extended information - deviation statistics :param ext_collection: Return extended information - favourited folder information """
response = self._req('/deviation/metadata', { 'ext_submission' : ext_submission, 'ext_camera' : ext_camera, 'ext_stats' : ext_stats, 'ext_collection' : ext_collection }, post_data={ 'deviationids[]' : deviationids }) metadata = [] for item in response['metadata']: m = {} m['deviationid'] = item['deviationid'] m['printid'] = item['printid'] m['author'] = User() m['author'].from_dict(item['author']) m['is_watching'] = item['is_watching'] m['title'] = item['title'] m['description'] = item['description'] m['license'] = item['license'] m['allows_comments'] = item['allows_comments'] m['tags'] = item['tags'] m['is_favourited'] = item['is_favourited'] m['is_mature'] = item['is_mature'] if "submission" in item: m['submission'] = item['submission'] if "camera" in item: m['camera'] = item['camera'] if "collections" in item: m['collections'] = item['collections'] metadata.append(m) return metadata
<SYSTEM_TASK:> Fetch content embedded in a deviation <END_TASK> <USER_TASK:> Description: def get_deviation_embeddedcontent(self, deviationid, offset_deviationid="", offset=0, limit=10): """Fetch content embedded in a deviation :param deviationid: The deviationid of container deviation :param offset_deviationid: UUID of embedded deviation to use as an offset :param offset: the pagination offset :param limit: the pagination limit """
response = self._req('/deviation/embeddedcontent', { 'deviationid' : deviationid, 'offset_deviationid' : offset_deviationid, 'offset' : 0, 'limit' : 0 }) deviations = [] for item in response['results']: d = Deviation() d.from_dict(item) deviations.append(d) return { "results" : deviations, "has_less" : response['has_less'], "has_more" : response['has_more'], "prev_offset" : response['prev_offset'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch full data that is not included in the main devaition object <END_TASK> <USER_TASK:> Description: def get_deviation_content(self, deviationid): """Fetch full data that is not included in the main devaition object The endpoint works with journals and literatures. Deviation objects returned from API contain only excerpt of a journal, use this endpoint to load full content. Any custom CSS rules and fonts applied to journal are also returned. :param deviationid: UUID of the deviation to fetch full data for """
response = self._req('/deviation/content', { 'deviationid':deviationid }) content = {} if "html" in response: content['html'] = response['html'] if "css" in response: content['css'] = response['css'] if "css_fonts" in response: content['css_fonts'] = response['css_fonts'] return content
<SYSTEM_TASK:> Fetch collection folders <END_TASK> <USER_TASK:> Description: def get_collections(self, username="", calculate_size=False, ext_preload=False, offset=0, limit=10): """Fetch collection folders :param username: The user to list folders for, if omitted the authenticated user is used :param calculate_size: The option to include the content count per each collection folder :param ext_preload: Include first 5 deviations from the folder :param offset: the pagination offset :param limit: the pagination limit """
if not username and self.standard_grant_type == "authorization_code": response = self._req('/collections/folders', { "calculate_size":calculate_size, "ext_preload":ext_preload, "offset":offset, "limit":limit }) else: if not username: raise DeviantartError("No username defined.") else: response = self._req('/collections/folders', { "username":username, "calculate_size":calculate_size, "ext_preload":ext_preload, "offset":offset, "limit":limit }) folders = [] for item in response['results']: f = {} f['folderid'] = item['folderid'] f['name'] = item['name'] if "size" in item: f['size'] = item['size'] if "deviations" in item: f['deviations'] = [] for deviation_item in item['deviations']: d = Deviation() d.from_dict(deviation_item) f['deviations'].append(d) folders.append(f) return { "results" : folders, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch collection folder contents <END_TASK> <USER_TASK:> Description: def get_collection(self, folderid, username="", offset=0, limit=10): """Fetch collection folder contents :param folderid: UUID of the folder to list :param username: The user to list folders for, if omitted the authenticated user is used :param offset: the pagination offset :param limit: the pagination limit """
if not username and self.standard_grant_type == "authorization_code": response = self._req('/collections/{}'.format(folderid), { "offset":offset, "limit":limit }) else: if not username: raise DeviantartError("No username defined.") else: response = self._req('/collections/{}'.format(folderid), { "username":username, "offset":offset, "limit":limit }) deviations = [] for item in response['results']: d = Deviation() d.from_dict(item) deviations.append(d) if "name" in response: name = response['name'] else: name = None return { "results" : deviations, "name" : name, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Add deviation to favourites <END_TASK> <USER_TASK:> Description: def fave(self, deviationid, folderid=""): """Add deviation to favourites :param deviationid: Id of the Deviation to favourite :param folderid: Optional UUID of the Collection folder to add the favourite into """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") post_data = {} post_data['deviationid'] = deviationid if folderid: post_data['folderid'] = folderid response = self._req('/collections/fave', post_data = post_data) return response
<SYSTEM_TASK:> Get all of a user's deviations <END_TASK> <USER_TASK:> Description: def get_gallery_all(self, username='', offset=0, limit=10): """ Get all of a user's deviations :param username: The user to query, defaults to current user :param offset: the pagination offset :param limit: the pagination limit """
if not username: raise DeviantartError('No username defined.') response = self._req('/gallery/all', {'username': username, 'offset': offset, 'limit': limit}) deviations = [] for item in response['results']: d = Deviation() d.from_dict(item) deviations.append(d) if "name" in response: name = response['name'] else: name = None return { "results": deviations, "name": name, "has_more": response['has_more'], "next_offset": response['next_offset'] }
<SYSTEM_TASK:> Get user profile information <END_TASK> <USER_TASK:> Description: def get_user(self, username="", ext_collections=False, ext_galleries=False): """Get user profile information :param username: username to lookup profile of :param ext_collections: Include collection folder info :param ext_galleries: Include gallery folder info """
if not username and self.standard_grant_type == "authorization_code": response = self._req('/user/whoami') u = User() u.from_dict(response) else: if not username: raise DeviantartError("No username defined.") else: response = self._req('/user/profile/{}'.format(username), { 'ext_collections' : ext_collections, 'ext_galleries' : ext_galleries }) u = User() u.from_dict(response['user']) return u
<SYSTEM_TASK:> Fetch user info for given usernames <END_TASK> <USER_TASK:> Description: def get_users(self, usernames): """Fetch user info for given usernames :param username: The usernames you want metadata for (max. 50) """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/whois', post_data={ "usernames":usernames }) users = [] for item in response['results']: u = User() u.from_dict(item) users.append(u) return users
<SYSTEM_TASK:> Unwatch a user <END_TASK> <USER_TASK:> Description: def unwatch(self, username): """Unwatch a user :param username: The username you want to unwatch """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/friends/unwatch/{}'.format(username)) return response['success']
<SYSTEM_TASK:> Check if user is being watched by the given user <END_TASK> <USER_TASK:> Description: def is_watching(self, username): """Check if user is being watched by the given user :param username: Check if username is watching you """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/friends/watching/{}'.format(username)) return response['watching']
<SYSTEM_TASK:> Update the users profile information <END_TASK> <USER_TASK:> Description: def update_user(self, user_is_artist="", artist_level="", artist_specialty="", real_name="", tagline="", countryid="", website="", bio=""): """Update the users profile information :param user_is_artist: Is the user an artist? :param artist_level: If the user is an artist, what level are they :param artist_specialty: If the user is an artist, what is their specialty :param real_name: The users real name :param tagline: The users tagline :param countryid: The users location :param website: The users personal website :param bio: The users bio """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") post_data = {} if user_is_artist: post_data["user_is_artist"] = user_is_artist if artist_level: post_data["artist_level"] = artist_level if artist_specialty: post_data["artist_specialty"] = artist_specialty if real_name: post_data["real_name"] = real_name if tagline: post_data["tagline"] = tagline if countryid: post_data["countryid"] = countryid if website: post_data["website"] = website if bio: post_data["bio"] = bio response = self._req('/user/profile/update', post_data=post_data) return response['success']
<SYSTEM_TASK:> Get the user's list of watchers <END_TASK> <USER_TASK:> Description: def get_watchers(self, username, offset=0, limit=10): """Get the user's list of watchers :param username: The username you want to get a list of watchers of :param offset: the pagination offset :param limit: the pagination limit """
response = self._req('/user/watchers/{}'.format(username), { 'offset' : offset, 'limit' : limit }) watchers = [] for item in response['results']: w = {} w['user'] = User() w['user'].from_dict(item['user']) w['is_watching'] = item['is_watching'] w['lastvisit'] = item['lastvisit'] w['watch'] = { "friend" : item['watch']['friend'], "deviations" : item['watch']['deviations'], "journals" : item['watch']['journals'], "forum_threads" : item['watch']['forum_threads'], "critiques" : item['watch']['critiques'], "scraps" : item['watch']['scraps'], "activity" : item['watch']['activity'], "collections" : item['watch']['collections'] } watchers.append(w) return { "results" : watchers, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Get the users list of friends <END_TASK> <USER_TASK:> Description: def get_friends(self, username, offset=0, limit=10): """Get the users list of friends :param username: The username you want to get a list of friends of :param offset: the pagination offset :param limit: the pagination limit """
response = self._req('/user/friends/{}'.format(username), { 'offset' : offset, 'limit' : limit }) friends = [] for item in response['results']: f = {} f['user'] = User() f['user'].from_dict(item['user']) f['is_watching'] = item['is_watching'] f['lastvisit'] = item['lastvisit'] f['watch'] = { "friend" : item['watch']['friend'], "deviations" : item['watch']['deviations'], "journals" : item['watch']['journals'], "forum_threads" : item['watch']['forum_threads'], "critiques" : item['watch']['critiques'], "scraps" : item['watch']['scraps'], "activity" : item['watch']['activity'], "collections" : item['watch']['collections'] } friends.append(f) return { "results" : friends, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch status updates of a user <END_TASK> <USER_TASK:> Description: def get_statuses(self, username, offset=0, limit=10): """Fetch status updates of a user :param username: The username you want to get a list of status updates from :param offset: the pagination offset :param limit: the pagination limit """
response = self._req('/user/statuses/', { "username" : username, 'offset' : offset, 'limit' : limit }) statuses = [] for item in response['results']: s = Status() s.from_dict(item) statuses.append(s) return { "results" : statuses, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Post a status <END_TASK> <USER_TASK:> Description: def post_status(self, body="", id="", parentid="", stashid=""): """Post a status :param username: The body of the status :param id: The id of the object you wish to share :param parentid: The parentid of the object you wish to share :param stashid: The stashid of the object you wish to add to the status """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/user/statuses/post', post_data={ "body":body, "id":id, "parentid":parentid, "stashid":stashid }) return response['statusid']
<SYSTEM_TASK:> Feed of all messages <END_TASK> <USER_TASK:> Description: def get_messages(self, folderid="", stack=1, cursor=""): """Feed of all messages :param folderid: The folder to fetch messages from, defaults to inbox :param stack: True to use stacked mode, false to use flat mode """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/feed', { 'folderid' : folderid, 'stack' : stack, 'cursor' : cursor }) messages = [] for item in response['results']: m = Message() m.from_dict(item) messages.append(m) return { "results" : messages, "has_more" : response['has_more'], "cursor" : response['cursor'] }
<SYSTEM_TASK:> Delete a message or a message stack <END_TASK> <USER_TASK:> Description: def delete_message(self, messageid="", folderid="", stackid=""): """Delete a message or a message stack :param folderid: The folder to delete the message from, defaults to inbox :param messageid: The message to delete :param stackid: The stack to delete """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/delete', post_data={ 'folderid' : folderid, 'messageid' : messageid, 'stackid' : stackid }) return response
<SYSTEM_TASK:> Fetch feedback messages <END_TASK> <USER_TASK:> Description: def get_feedback(self, feedbacktype="comments", folderid="", stack=1, offset=0, limit=10): """Fetch feedback messages :param feedbacktype: Type of feedback messages to fetch (comments/replies/activity) :param folderid: The folder to fetch messages from, defaults to inbox :param stack: True to use stacked mode, false to use flat mode :param offset: the pagination offset :param limit: the pagination limit """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/feedback', { 'type' : feedbacktype, 'folderid' : folderid, 'stack' : stack, 'offset' : offset, 'limit' : limit }) messages = [] for item in response['results']: m = Message() m.from_dict(item) messages.append(m) return { "results" : messages, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch feedback messages in a stack <END_TASK> <USER_TASK:> Description: def get_feedback_in_stack(self, stackid, offset=0, limit=10): """Fetch feedback messages in a stack :param stackid: Id of the stack :param offset: the pagination offset :param limit: the pagination limit """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/messages/feedback/{}'.format(stackid), { 'offset' : offset, 'limit' : limit }) messages = [] for item in response['results']: m = Message() m.from_dict(item) messages.append(m) return { "results" : messages, "has_more" : response['has_more'], "next_offset" : response['next_offset'] }
<SYSTEM_TASK:> Fetch a single note <END_TASK> <USER_TASK:> Description: def get_note(self, noteid): """Fetch a single note :param folderid: The UUID of the note """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/{}'.format(noteid)) return response
<SYSTEM_TASK:> Send a note <END_TASK> <USER_TASK:> Description: def send_note(self, to, subject="", body="", noetid=""): """Send a note :param to: The username(s) that this note is to :param subject: The subject of the note :param body: The body of the note :param noetid: The UUID of the note that is being responded to """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/send', post_data={ 'to[]' : to, 'subject' : subject, 'body' : body, 'noetid' : noetid }) sent_notes = [] for item in response['results']: n = {} n['success'] = item['success'] n['user'] = User() n['user'].from_dict(item['user']) sent_notes.append(n) return sent_notes
<SYSTEM_TASK:> Move notes to a folder <END_TASK> <USER_TASK:> Description: def move_notes(self, noteids, folderid): """Move notes to a folder :param noteids: The noteids to move :param folderid: The folderid to move notes to """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/move', post_data={ 'noteids[]' : noteids, 'folderid' : folderid }) return response
<SYSTEM_TASK:> Delete a note or notes <END_TASK> <USER_TASK:> Description: def delete_notes(self, noteids): """Delete a note or notes :param noteids: The noteids to delete """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/delete', post_data={ 'noteids[]' : noteids }) return response
<SYSTEM_TASK:> Rename a folder <END_TASK> <USER_TASK:> Description: def rename_notes_folder(self, title, folderid): """Rename a folder :param title: New title of the folder :param folderid: The UUID of the folder to rename """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/folders/rename/{}'.format(folderid), post_data={ 'title' : title }) return response
<SYSTEM_TASK:> Delete note folder <END_TASK> <USER_TASK:> Description: def delete_notes_folder(self, folderid): """Delete note folder :param folderid: The UUID of the folder to delete """
if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.") response = self._req('/notes/folders/remove/{}'.format(folderid)) return response
<SYSTEM_TASK:> Helper method to make API calls <END_TASK> <USER_TASK:> Description: def _req(self, endpoint, get_data=dict(), post_data=dict()): """Helper method to make API calls :param endpoint: The endpoint to make the API call to :param get_data: data send through GET :param post_data: data send through POST """
if get_data: request_parameter = "{}?{}".format(endpoint, urlencode(get_data)) else: request_parameter = endpoint try: encdata = urlencode(post_data, True).encode('utf-8') response = self.oauth.request(request_parameter, data=encdata) self._checkResponseForErrors(response) except HTTPError as e: raise DeviantartError(e) return response
<SYSTEM_TASK:> Revoke the authorization token and all tokens that were generated using it. <END_TASK> <USER_TASK:> Description: def revoke_tokens(self): """ Revoke the authorization token and all tokens that were generated using it. """
self.is_active = False self.save() self.refresh_token.revoke_tokens()
<SYSTEM_TASK:> Revokes the refresh token and all access tokens that were generated using it. <END_TASK> <USER_TASK:> Description: def revoke_tokens(self): """ Revokes the refresh token and all access tokens that were generated using it. """
self.is_active = False self.save() for access_token in self.access_tokens.all(): access_token.revoke()
<SYSTEM_TASK:> Try to authenticate the user based on any given tokens that have been provided <END_TASK> <USER_TASK:> Description: def process_request(self, request): """ Try to authenticate the user based on any given tokens that have been provided to the request object. This will try to detect the authentication type and assign the detected User object to the `request.user` variable, similar to the standard Django authentication. """
request.auth_type = None http_authorization = request.META.get("HTTP_AUTHORIZATION", None) if not http_authorization: return auth = http_authorization.split() self.auth_type = auth[0].lower() self.auth_value = " ".join(auth[1:]).strip() request.auth_type = self.auth_type self.validate_auth_type() if not self.handler_name: raise Exception("There is no handler defined for this authentication type.") self.load_handler() response = self.handler.validate(self.auth_value, request) if response is not None: return response request.access_token = self.handler.access_token(self.auth_value, request) request.user = self.handler.authenticate(self.auth_value, request)
<SYSTEM_TASK:> Load the detected handler. <END_TASK> <USER_TASK:> Description: def load_handler(self): """ Load the detected handler. """
handler_path = self.handler_name.split(".") handler_module = __import__(".".join(handler_path[:-1]), {}, {}, str(handler_path[-1])) self.handler = getattr(handler_module, handler_path[-1])()
<SYSTEM_TASK:> Validate the detected authorization type against the list of handlers. This will return the full <END_TASK> <USER_TASK:> Description: def validate_auth_type(self): """ Validate the detected authorization type against the list of handlers. This will return the full module path to the detected handler. """
for handler in HANDLERS: handler_type = handler.split(".")[-2] if handler_type == self.auth_type: self.handler_name = handler return self.handler_name = None
<SYSTEM_TASK:> Return the show feed URL with different protocol. <END_TASK> <USER_TASK:> Description: def show_url(context, **kwargs): """Return the show feed URL with different protocol."""
if len(kwargs) != 2: raise TemplateSyntaxError(_('"show_url" tag takes exactly two keyword arguments.')) request = context['request'] current_site = get_current_site(request) url = add_domain(current_site.domain, kwargs['url']) return re.sub(r'https?:\/\/', '%s://' % kwargs['protocol'], url)
<SYSTEM_TASK:> Parses TOML text into a dict-like object and returns it. <END_TASK> <USER_TASK:> Description: def loads(text): """ Parses TOML text into a dict-like object and returns it. """
from prettytoml.parser import parse_tokens from prettytoml.lexer import tokenize as lexer from .file import TOMLFile tokens = tuple(lexer(text, is_top_level=True)) elements = parse_tokens(tokens) return TOMLFile(elements)
<SYSTEM_TASK:> Dumps a data structure to TOML source code. <END_TASK> <USER_TASK:> Description: def dumps(value): """ Dumps a data structure to TOML source code. The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module. """
from contoml.file.file import TOMLFile if not isinstance(value, TOMLFile): raise RuntimeError("Can only dump a TOMLFile instance loaded by load() or loads()") return value.dumps()
<SYSTEM_TASK:> Dumps a data structure to the filesystem as TOML. <END_TASK> <USER_TASK:> Description: def dump(obj, file_path, prettify=False): """ Dumps a data structure to the filesystem as TOML. The given value must be either a dict of dict values, a dict, or a TOML file constructed by this module. """
with open(file_path, 'w') as fp: fp.write(dumps(obj))
<SYSTEM_TASK:> Get current exchange rate. <END_TASK> <USER_TASK:> Description: def rate(base, target, error_log=None): """Get current exchange rate. :param base: A base currency :param target: Convert to the target currency :param error_log: A callable function to track the exception It parses current exchange rate from these services: 1) Yahoo finance 2) fixer.io 3) European Central Bank It will fallback to the next service when previous not available. The exchane rate is a decimal number. If `None` is returned, it means the parsing goes wrong:: >>> import exchange >>> exchange.rate('USD', 'CNY') Decimal('6.2045') """
if base == target: return decimal.Decimal(1.00) services = [yahoo, fixer, ecb] if error_log is None: error_log = _error_log for fn in services: try: return fn(base, target) except Exception as e: error_log(e) return None
<SYSTEM_TASK:> Parse data from European Central Bank. <END_TASK> <USER_TASK:> Description: def ecb(base, target): """Parse data from European Central Bank."""
api_url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' resp = requests.get(api_url, timeout=1) text = resp.text def _find_rate(symbol): if symbol == 'EUR': return decimal.Decimal(1.00) m = re.findall(r"currency='%s' rate='([0-9\.]+)'" % symbol, text) return decimal.Decimal(m[0]) return _find_rate(target) / _find_rate(base)
<SYSTEM_TASK:> Returns the dot product of two Vectors <END_TASK> <USER_TASK:> Description: def dot(vec1, vec2): """Returns the dot product of two Vectors"""
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) elif isinstance(vec1, Vector4) and isinstance(vec2, Vector4): return (vec1.x * vec2.x) + (vec1.y * vec2.y) + (vec1.z * vec2.z) + (vec1.w * vec2.w) else: raise TypeError("vec1 and vec2 must a Vector type")
<SYSTEM_TASK:> Returns the angle between two vectors <END_TASK> <USER_TASK:> Description: def angle(vec1, vec2): """Returns the angle between two vectors"""
dot_vec = dot(vec1, vec2) mag1 = vec1.length() mag2 = vec2.length() result = dot_vec / (mag1 * mag2) return math.acos(result)
<SYSTEM_TASK:> Add each of the components of vec1 and vec2 together and return a new vector. <END_TASK> <USER_TASK:> Description: def component_add(vec1, vec2): """Add each of the components of vec1 and vec2 together and return a new vector."""
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): addVec = Vector3() addVec.x = vec1.x + vec2.x addVec.y = vec1.y + vec2.y addVec.z = vec1.z + vec2.z return addVec if isinstance(vec1, Vector4) and isinstance(vec2, Vector4): addVec = Vector4() addVec.x = vec1.x + vec2.x addVec.y = vec1.y + vec2.y addVec.z = vec1.z + vec2.z addVec.w = vec1.w + vec2.w return addVec
<SYSTEM_TASK:> Take vec1 and reflect it about vec2. <END_TASK> <USER_TASK:> Description: def reflect(vec1, vec2): """Take vec1 and reflect it about vec2."""
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3) \ or isinstance(vec1, Vector4) and isinstance(vec2, Vector4): return 2 * dot(vec1, vec2) * vec2 - vec2 else: raise ValueError("vec1 and vec2 must both be a Vector type")
<SYSTEM_TASK:> Create a copy of this Vector <END_TASK> <USER_TASK:> Description: def copy(self): """Create a copy of this Vector"""
new_vec = Vector2() new_vec.X = self.X new_vec.Y = self.Y return new_vec
<SYSTEM_TASK:> Gets the length of this Vector <END_TASK> <USER_TASK:> Description: def length(self): """Gets the length of this Vector"""
return math.sqrt((self.X * self.X) + (self.Y * self.Y))
<SYSTEM_TASK:> Calculate the distance between two Vectors <END_TASK> <USER_TASK:> Description: def distance(vec1, vec2): """Calculate the distance between two Vectors"""
if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): dist_vec = vec2 - vec1 return dist_vec.length() else: raise TypeError("vec1 and vec2 must be Vector2's")
<SYSTEM_TASK:> Calculate the dot product between two Vectors <END_TASK> <USER_TASK:> Description: def dot(vec1, vec2): """Calculate the dot product between two Vectors"""
if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): return ((vec1.X * vec2.X) + (vec1.Y * vec2.Y)) else: raise TypeError("vec1 and vec2 must be Vector2's")
<SYSTEM_TASK:> Calculate the angle between two Vector2's <END_TASK> <USER_TASK:> Description: def angle(vec1, vec2): """Calculate the angle between two Vector2's"""
dotp = Vector2.dot(vec1, vec2) mag1 = vec1.length() mag2 = vec2.length() result = dotp / (mag1 * mag2) return math.acos(result)
<SYSTEM_TASK:> Lerp between vec1 to vec2 based on time. Time is clamped between 0 and 1. <END_TASK> <USER_TASK:> Description: def lerp(vec1, vec2, time): """Lerp between vec1 to vec2 based on time. Time is clamped between 0 and 1."""
if isinstance(vec1, Vector2) \ and isinstance(vec2, Vector2): # Clamp the time value into the 0-1 range. if time < 0: time = 0 elif time > 1: time = 1 x_lerp = vec1[0] + time * (vec2[0] - vec1[0]) y_lerp = vec1[1] + time * (vec2[1] - vec1[1]) return Vector2(x_lerp, y_lerp) else: raise TypeError("Objects must be of type Vector2")
<SYSTEM_TASK:> Convert polar coordinates to Carteasian Coordinates <END_TASK> <USER_TASK:> Description: def from_polar(degrees, magnitude): """Convert polar coordinates to Carteasian Coordinates"""
vec = Vector2() vec.X = math.cos(math.radians(degrees)) * magnitude # Negate because y in screen coordinates points down, oppisite from what is # expected in traditional mathematics. vec.Y = -math.sin(math.radians(degrees)) * magnitude return vec
<SYSTEM_TASK:> Multiply the components of the vectors and return the result. <END_TASK> <USER_TASK:> Description: def component_mul(vec1, vec2): """Multiply the components of the vectors and return the result."""
new_vec = Vector2() new_vec.X = vec1.X * vec2.X new_vec.Y = vec1.Y * vec2.Y return new_vec
<SYSTEM_TASK:> Divide the components of the vectors and return the result. <END_TASK> <USER_TASK:> Description: def component_div(vec1, vec2): """Divide the components of the vectors and return the result."""
new_vec = Vector2() new_vec.X = vec1.X / vec2.X new_vec.Y = vec1.Y / vec2.Y return new_vec
<SYSTEM_TASK:> Converts this vector3 into a vector4 instance. <END_TASK> <USER_TASK:> Description: def to_vec4(self, isPoint): """Converts this vector3 into a vector4 instance."""
vec4 = Vector4() vec4.x = self.x vec4.y = self.y vec4.z = self.z if isPoint: vec4.w = 1 else: vec4.w = 0 return vec4
<SYSTEM_TASK:> Generates a Vector3 from a tuple or list. <END_TASK> <USER_TASK:> Description: def tuple_as_vec(xyz): """ Generates a Vector3 from a tuple or list. """
vec = Vector3() vec[0] = xyz[0] vec[1] = xyz[1] vec[2] = xyz[2] return vec
<SYSTEM_TASK:> Returns the cross product of two Vectors <END_TASK> <USER_TASK:> Description: def cross(vec1, vec2): """Returns the cross product of two Vectors"""
if isinstance(vec1, Vector3) and isinstance(vec2, Vector3): vec3 = Vector3() vec3.x = (vec1.y * vec2.z) - (vec1.z * vec2.y) vec3.y = (vec1.z * vec2.x) - (vec1.x * vec2.z) vec3.z = (vec1.x * vec2.y) - (vec1.y * vec2.x) return vec3 else: raise TypeError("vec1 and vec2 must be Vector3's")
<SYSTEM_TASK:> Convert this vector4 instance into a vector3 instance. <END_TASK> <USER_TASK:> Description: def to_vec3(self): """Convert this vector4 instance into a vector3 instance."""
vec3 = Vector3() vec3.x = self.x vec3.y = self.y vec3.z = self.z if self.w != 0: vec3 /= self.w return vec3
<SYSTEM_TASK:> Gets the length of the Vector <END_TASK> <USER_TASK:> Description: def length(self): """Gets the length of the Vector"""
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w))
<SYSTEM_TASK:> Clamps all the components in the vector to the specified clampVal. <END_TASK> <USER_TASK:> Description: def clamp(self, clampVal): """Clamps all the components in the vector to the specified clampVal."""
if self.x > clampVal: self.x = clampVal if self.y > clampVal: self.y = clampVal if self.z > clampVal: self.z = clampVal if self.w > clampVal: self.w = clampVal
<SYSTEM_TASK:> Generates a Vector4 from a tuple or list. <END_TASK> <USER_TASK:> Description: def tuple_as_vec(xyzw): """ Generates a Vector4 from a tuple or list. """
vec = Vector4() vec[0] = xyzw[0] vec[1] = xyzw[1] vec[2] = xyzw[2] vec[3] = xyzw[3] return vec
<SYSTEM_TASK:> Create a transpose of this matrix. <END_TASK> <USER_TASK:> Description: def transpose(self): """Create a transpose of this matrix."""
ma4 = Matrix4(self.get_col(0), self.get_col(1), self.get_col(2), self.get_col(3)) return ma4
<SYSTEM_TASK:> Create a translation matrix. <END_TASK> <USER_TASK:> Description: def translate(translationAmt): """Create a translation matrix."""
if not isinstance(translationAmt, Vector3): raise ValueError("translationAmt must be a Vector3") ma4 = Matrix4((1, 0, 0, translationAmt.x), (0, 1, 0, translationAmt.y), (0, 0, 1, translationAmt.z), (0, 0, 0, 1)) return ma4
<SYSTEM_TASK:> Create a scale matrix. <END_TASK> <USER_TASK:> Description: def scale(scaleAmt): """ Create a scale matrix. scaleAmt is a Vector3 defining the x, y, and z scale values. """
if not isinstance(scaleAmt, Vector3): raise ValueError("scaleAmt must be a Vector3") ma4 = Matrix4((scaleAmt.x, 0, 0, 0), (0, scaleAmt.y, 0, 0), (0, 0, scaleAmt.z, 0), (0, 0, 0, 1)) return ma4
<SYSTEM_TASK:> Create a matrix that rotates around the z axis. <END_TASK> <USER_TASK:> Description: def z_rotate(rotationAmt): """Create a matrix that rotates around the z axis."""
ma4 = Matrix4((math.cos(rotationAmt), -math.sin(rotationAmt), 0, 0), (math.sin(rotationAmt), math.cos(rotationAmt), 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)) return ma4
<SYSTEM_TASK:> Create a matrix that rotates around the y axis. <END_TASK> <USER_TASK:> Description: def y_rotate(rotationAmt): """Create a matrix that rotates around the y axis."""
ma4 = Matrix4((math.cos(rotationAmt), 0, math.sin(rotationAmt), 0), (0, 1, 0, 0), (-math.sin(rotationAmt), 0, math.cos(rotationAmt), 0), (0, 0, 0, 1)) return ma4
<SYSTEM_TASK:> Create a matrix that rotates around the x axis. <END_TASK> <USER_TASK:> Description: def x_rotate(rotationAmt): """Create a matrix that rotates around the x axis."""
ma4 = Matrix4((1, 0, 0, 0), (0, math.cos(rotationAmt), -math.sin(rotationAmt), 0), (0, math.sin(rotationAmt), math.cos(rotationAmt), 0), (0, 0, 0, 1)) return ma4
<SYSTEM_TASK:> Build a rotation matrix. <END_TASK> <USER_TASK:> Description: def build_rotation(vec3): """ Build a rotation matrix. vec3 is a Vector3 defining the axis about which to rotate the object. """
if not isinstance(vec3, Vector3): raise ValueError("rotAmt must be a Vector3") return Matrix4.x_rotate(vec3.x) * Matrix4.y_rotate(vec3.y) * Matrix4.z_rotate(vec3.z)
<SYSTEM_TASK:> This is the place to put all event handeling. <END_TASK> <USER_TASK:> Description: def __handle_events(self): """This is the place to put all event handeling."""
events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit()
<SYSTEM_TASK:> Create a new object for the pool. <END_TASK> <USER_TASK:> Description: def __init_object(self): """Create a new object for the pool."""
# Check to see if the user created a specific initalization function for this object. if self.init_function is not None: new_obj = self.init_function() self.__enqueue(new_obj) else: raise TypeError("The Pool must have a non None function to fill the pool.")
<SYSTEM_TASK:> Sets the origin to the center of the image. <END_TASK> <USER_TASK:> Description: def center_origin(self): """Sets the origin to the center of the image."""
self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.0))
<SYSTEM_TASK:> Scale the texture to the specfied width and height. <END_TASK> <USER_TASK:> Description: def scale_to(self, width_height=Vector2()): """Scale the texture to the specfied width and height."""
scale_amt = Vector2() scale_amt.X = float(width_height.X) / self.image.get_width() scale_amt.Y = float(width_height.Y) / self.image.get_height() self.set_scale(scale_amt)
<SYSTEM_TASK:> val is True or False that determines if we should horizontally flip the surface or not. <END_TASK> <USER_TASK:> Description: def set_hflip(self, val): """val is True or False that determines if we should horizontally flip the surface or not."""
if self.__horizontal_flip is not val: self.__horizontal_flip = val self.image = pygame.transform.flip(self.untransformed_image, val, self.__vertical_flip)
<SYSTEM_TASK:> Generate our sprite's surface by loading the specified image from disk. <END_TASK> <USER_TASK:> Description: def load_texture(self, file_path): """Generate our sprite's surface by loading the specified image from disk. Note that this automatically centers the origin."""
self.image = pygame.image.load(file_path) self.apply_texture(self.image)
<SYSTEM_TASK:> Executes the rotating operation <END_TASK> <USER_TASK:> Description: def __execute_rot(self, surface): """Executes the rotating operation"""
self.image = pygame.transform.rotate(surface, self.__rotation) self.__resize_surface_extents()
<SYSTEM_TASK:> Handle scaling and rotation of the surface <END_TASK> <USER_TASK:> Description: def __handle_scale_rot(self): """Handle scaling and rotation of the surface"""
if self.__is_rot_pending: self.__execute_rot(self.untransformed_image) self.__is_rot_pending = False # Scale the image using the recently rotated surface to keep the orientation correct self.__execute_scale(self.image, self.image.get_size()) self.__is_scale_pending = False # The image is not rotating while scaling, thus use the untransformed image to scale. if self.__is_scale_pending: self.__execute_scale(self.untransformed_image, self.untransformed_image.get_size()) self.__is_scale_pending = False
<SYSTEM_TASK:> Load the specified font from a file. <END_TASK> <USER_TASK:> Description: def load_font(self, font_path, font_size): """Load the specified font from a file."""
self.__font_path = font_path self.__font_size = font_size if font_path != "": self.__font = pygame.font.Font(font_path, font_size) self.__set_text(self.__text)
<SYSTEM_TASK:> Prepare our particle for use. <END_TASK> <USER_TASK:> Description: def initalize(self, physics_dta): """ Prepare our particle for use. physics_dta describes the velocity, coordinates, and acceleration of the particle. """
self.rotation = random.randint(self.rotation_range[0], self.rotation_range[1]) self.current_time = 0.0 self.color = self.start_color self.scale = self.start_scale self.physics = physics_dta
<SYSTEM_TASK:> Pull a particle from the queue and add it to the active list. <END_TASK> <USER_TASK:> Description: def __release_particle(self): """Pull a particle from the queue and add it to the active list."""
# Calculate a potential angle for the particle. angle = random.randint(int(self.direction_range[0]), int(self.direction_range[1])) velocity = Vector2.from_polar(angle, self.particle_speed) physics = PhysicsObj(self.coords, Vector2(), velocity) particle = self.particle_pool.request_object() particle.initalize(physics) self.particles.append(particle) self.current_particle_count += 1
<SYSTEM_TASK:> Load a spritesheet texture. <END_TASK> <USER_TASK:> Description: def load_texture(self, file_path, cell_size=(256, 256)): """ Load a spritesheet texture. cell_size is the uniform size of each cell in the spritesheet. """
super(SpriteSheet, self).load_texture(file_path) self.__cell_bounds = cell_size self.__generate_cells()
<SYSTEM_TASK:> Draw out the specified cell <END_TASK> <USER_TASK:> Description: def draw(self, milliseconds, surface, cell): """Draw out the specified cell"""
# print self.cells[cell] self.source = self.cells[cell].copy() # Find the current scale of the image in relation to its original scale. current_scale = Vector2() current_scale.X = self.rect.width / float(self.untransformed_image.get_width()) current_scale.Y = self.rect.height / float(self.untransformed_image.get_height()) # self.source.x *= self.scale.X # self.source.y *= self.scale.Y self.source.width *= current_scale.X self.source.height *= current_scale.Y super(SpriteSheet, self).draw(milliseconds, surface)
<SYSTEM_TASK:> Set all the images contained in the animation to the specified value. <END_TASK> <USER_TASK:> Description: def set_coords(self, value): """Set all the images contained in the animation to the specified value."""
self.__coords = value for image in self.images: image.coords = value