Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Using the snippet: <|code_start|> """Return unique list of entity names collapsed into shortest forms""" name_list = [] for e in entity_list: name_forms = sorted(e['name_forms'], key=lambda s: len(s)) while name_forms: name = name_forms.pop(0) for i in range(len(name_forms) - 1, -1, -1): s = name_forms[i] if s.find(name) > -1: del name_forms[i] if name not in name_list: name_list.append(name) name_list.extend([s for s in name_forms if s not in name_list]) return name_list def name_tokens(entity): entity_names = set([entity['name']] + entity['name_forms']) entity_name_tokens = [] for name in entity_names: tokens = ALNUM_PAT.findall(name) for token in tokens: if token not in entity_name_tokens: entity_name_tokens.append(token) return entity_name_tokens def best_matches(entity_names, objs, name_key='name'): <|code_end|> , determine the next line of code. You have imports: from collections import defaultdict, namedtuple from .util import get_sentences, pos_tag, tokenize, NLTK_VERSION, \ name_parts, compare_names import codecs import nltk import re and context (class names, function names, or code) available: # Path: context/nlp/util.py # def get_sentences(text): # """Return sentence list""" # if text.strip() == '': # return [] # tokens = nltk.sent_tokenize(text) # sentences = [] # for sent in tokens: # sentences.extend([s.strip() for s in sent.split('\n') if s.strip()]) # sentences_ = [] # skip_next = False # for i, sent in enumerate(sentences): # if skip_next: # skip_next = False # continue # if i == len(sentences): # sentences_.append(sent) # break # if sent.split()[-1].lower() == ('no.'): # try: # s1 = sentences[i+1] # int(s1.split()[0]) # sentences_.append(sent + ' ' + s1) # skip_next = True # except ValueError: # sentences_.append(sent) # else: # sentences_.append(sent) # assert sentences[-1] in sentences_[-1] # return sentences_ # # def pos_tag(tokens): # """Return POS tagged tokens""" # return nltk.pos_tag(tokens) # # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # NLTK_VERSION = nltk_major_version() # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score . Output only the next line.
obj_name_parts = name_parts([obj[name_key] for obj in objs])
Continue the code snippet: <|code_start|> for e in entity_list: name_forms = sorted(e['name_forms'], key=lambda s: len(s)) while name_forms: name = name_forms.pop(0) for i in range(len(name_forms) - 1, -1, -1): s = name_forms[i] if s.find(name) > -1: del name_forms[i] if name not in name_list: name_list.append(name) name_list.extend([s for s in name_forms if s not in name_list]) return name_list def name_tokens(entity): entity_names = set([entity['name']] + entity['name_forms']) entity_name_tokens = [] for name in entity_names: tokens = ALNUM_PAT.findall(name) for token in tokens: if token not in entity_name_tokens: entity_name_tokens.append(token) return entity_name_tokens def best_matches(entity_names, objs, name_key='name'): obj_name_parts = name_parts([obj[name_key] for obj in objs]) entity_name_parts = name_parts(entity_names, flat=True) <|code_end|> . Use current file imports: from collections import defaultdict, namedtuple from .util import get_sentences, pos_tag, tokenize, NLTK_VERSION, \ name_parts, compare_names import codecs import nltk import re and context (classes, functions, or code) from other files: # Path: context/nlp/util.py # def get_sentences(text): # """Return sentence list""" # if text.strip() == '': # return [] # tokens = nltk.sent_tokenize(text) # sentences = [] # for sent in tokens: # sentences.extend([s.strip() for s in sent.split('\n') if s.strip()]) # sentences_ = [] # skip_next = False # for i, sent in enumerate(sentences): # if skip_next: # skip_next = False # continue # if i == len(sentences): # sentences_.append(sent) # break # if sent.split()[-1].lower() == ('no.'): # try: # s1 = sentences[i+1] # int(s1.split()[0]) # sentences_.append(sent + ' ' + s1) # skip_next = True # except ValueError: # sentences_.append(sent) # else: # sentences_.append(sent) # assert sentences[-1] in sentences_[-1] # return sentences_ # # def pos_tag(tokens): # """Return POS tagged tokens""" # return nltk.pos_tag(tokens) # # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # NLTK_VERSION = nltk_major_version() # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score . Output only the next line.
matches = map(lambda x: compare_names(entity_name_parts, x),
Based on the snippet: <|code_start|> CONFIG_LIST_REGEX.split(pundit_panel) if s.strip()] def get_pundit_categories(): """Return list of pundit categories""" config = configuration() return [category for category, value in config.items('punditpanels')] def chunk_iter(seq, n): """ Break seq into chunks of at most n items """ return (seq[pos:pos + n] for pos in xrange(0, len(seq), n)) def pundit_tweets(category, keywords, credentials=None, limit=None): """ Do keyword search of tweets from pundits in category Twitter says to keep keywords and operators < 10 """ categories = get_pundit_categories() if not category in categories: raise Exception( 'No pundit panel available for category "%s"' % category) pundits = get_category_pundits(category) if not pundits: raise Exception('No pundits available for category "%s"' % category) n_keywords = 4 while True: <|code_end|> , predict the immediate next line with the help of imports: import re from context.config import configuration from context.query import twitter_query from context.config import get_twitter_keys from context.services.twitter import search as twitter_search and context (classes, functions, sometimes code) from other files: # Path: context/config.py # def configuration(): # """Return SafeConfigParser for config file""" # global _config # if _config is None: # _config = ConfigParser.SafeConfigParser() # path = config_file_path() # with open(path) as f: # _config.readfp(f) # return _config # # Path: context/query.py # def twitter_query(keywords=None, entities=None): # """ # Form a twitter query string from keywords and/or entities. # See: https://dev.twitter.com/rest/public/search # # Testing shows that OR has precedence over AND: # # a b OR c d is a AND (b OR c) AND d # is not (a AND b) OR (c AND d) # # a OR b c OR d is (a OR b) AND (c OR d) # is not a OR (b AND c) OR d # # For example, the query: # # free OR good beer OR shirt # # is interpreted as: # # (free OR good) AND (beer OR shirt) # # so it will return tweets containing: # # "free" and "beer" # or "free" and "shirt" # or "good" and "beer" # or "good" and "shirt" # # """ # q_entities = [] # if entities: # q_entities = collapse_entities( # [d for d in entities if d['score'] > 0.01]) # # q_keywords = [] # if keywords: # q_keywords = [d['keyword'] for d in keywords \ # if d['count'] > 2 and d['keyword'] not in q_entities] # # q_keywords = quoted_terms(q_keywords[:5]) # q_entities = quoted_terms(q_entities[:5]) # q = '' # # if q_keywords and q_entities: # # at least one keyword and at least one entity # q = '%s %s' % \ # (' OR '.join(q_keywords), ' OR '.join(q_entities)) # elif q_keywords: # # top keyword and at least one other keyword # q = q_keywords.pop(0) # if len(q_keywords) > 0: # q += ' %s' % ' OR '.join(q_keywords) # elif q_entities: # # top entity and at least one other entity # q = q_entities.pop(0) # if len(q_entities) > 0: # q += ' %s' % ' OR '.join(q_entities) # return q # # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # Path: context/services/twitter.py # def search(params, credentials=None): # """ # Execute twitter search # # @params = dictionary of search parameters # @credentials = dictionary containing token/secret overrides # """ # client = get_client(credentials) # return client.api.search.tweets.get(**params).data . Output only the next line.
q_keywords = twitter_query(keywords[:n_keywords])
Based on the snippet: <|code_start|> Break seq into chunks of at most n items """ return (seq[pos:pos + n] for pos in xrange(0, len(seq), n)) def pundit_tweets(category, keywords, credentials=None, limit=None): """ Do keyword search of tweets from pundits in category Twitter says to keep keywords and operators < 10 """ categories = get_pundit_categories() if not category in categories: raise Exception( 'No pundit panel available for category "%s"' % category) pundits = get_category_pundits(category) if not pundits: raise Exception('No pundits available for category "%s"' % category) n_keywords = 4 while True: q_keywords = twitter_query(keywords[:n_keywords]) n_from = (10 - len(q_keywords.split())) / 2 if n_from > 0: break n_keywords -= 1 tweets = [] for group in chunk_iter(pundits, n_from): q_from = ' OR '.join(['from:%s' % x for x in group]) q = '%s AND %s' % (q_from, q_keywords) params = {'q': q, 'count': 20, 'result_type': 'mixed'} <|code_end|> , predict the immediate next line with the help of imports: import re from context.config import configuration from context.query import twitter_query from context.config import get_twitter_keys from context.services.twitter import search as twitter_search and context (classes, functions, sometimes code) from other files: # Path: context/config.py # def configuration(): # """Return SafeConfigParser for config file""" # global _config # if _config is None: # _config = ConfigParser.SafeConfigParser() # path = config_file_path() # with open(path) as f: # _config.readfp(f) # return _config # # Path: context/query.py # def twitter_query(keywords=None, entities=None): # """ # Form a twitter query string from keywords and/or entities. # See: https://dev.twitter.com/rest/public/search # # Testing shows that OR has precedence over AND: # # a b OR c d is a AND (b OR c) AND d # is not (a AND b) OR (c AND d) # # a OR b c OR d is (a OR b) AND (c OR d) # is not a OR (b AND c) OR d # # For example, the query: # # free OR good beer OR shirt # # is interpreted as: # # (free OR good) AND (beer OR shirt) # # so it will return tweets containing: # # "free" and "beer" # or "free" and "shirt" # or "good" and "beer" # or "good" and "shirt" # # """ # q_entities = [] # if entities: # q_entities = collapse_entities( # [d for d in entities if d['score'] > 0.01]) # # q_keywords = [] # if keywords: # q_keywords = [d['keyword'] for d in keywords \ # if d['count'] > 2 and d['keyword'] not in q_entities] # # q_keywords = quoted_terms(q_keywords[:5]) # q_entities = quoted_terms(q_entities[:5]) # q = '' # # if q_keywords and q_entities: # # at least one keyword and at least one entity # q = '%s %s' % \ # (' OR '.join(q_keywords), ' OR '.join(q_entities)) # elif q_keywords: # # top keyword and at least one other keyword # q = q_keywords.pop(0) # if len(q_keywords) > 0: # q += ' %s' % ' OR '.join(q_keywords) # elif q_entities: # # top entity and at least one other entity # q = q_entities.pop(0) # if len(q_entities) > 0: # q += ' %s' % ' OR '.join(q_entities) # return q # # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # Path: context/services/twitter.py # def search(params, credentials=None): # """ # Execute twitter search # # @params = dictionary of search parameters # @credentials = dictionary containing token/secret overrides # """ # client = get_client(credentials) # return client.api.search.tweets.get(**params).data . Output only the next line.
result = twitter_search(params, credentials=credentials)
Given snippet: <|code_start|># -*- coding: utf-8 -*- URL_PAT = re.compile(r'http[^ ]+', re.I) USER_PAT = re.compile(r'@\w{1,15}') LEAD_PAT = re.compile(u'^(RT)?\s*[.?!:;,\'"‘’“”—…\s]*', re.U | re.I) TRAIL_PAT = re.compile(u'[\s.:—…]+$', re.U) class UserClient(birdy.twitter.UserClient): """Twitter UserClient""" def __repr__(self): return dict(self).__repr__ def get_client(credentials=None): """Get credentialed Twitter UserClient""" <|code_end|> , continue by predicting the next line. Consider current file imports: import copy import os import re import urllib import requests import string import birdy.twitter from collections import defaultdict, OrderedDict from birdy.twitter import TwitterAuthError from ..config import get_twitter_keys, get_named_stoplist from ..content import all_page_text from ..nlp.keywords import check_keywords from ..nlp.entities import collapse_entities from ..nlp.util import tokenize, compare_names, name_parts, ALNUM_PAT from nltk import ngrams from nltk.corpus import stopwords and context: # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # def get_named_stoplist(name): # """Return named stoplist.""" # config = configuration() # stoplist = config.get('stoplists', name) # return [s.strip() for s in CONFIG_LIST_REGEX.split(stoplist) if s.strip()] # # Path: context/content.py # def all_page_text(url): # try: # html = requests.get(url).text # doc = BeautifulSoup.BeautifulSoup(html) # return ' '.join([t for t in doc.findAll(text=True) if t.strip()]) # except requests.ConnectionError: # return '' # # Path: context/nlp/keywords.py # def check_keywords(timeline, keywords): # tweets = [] # keywords = [k['keyword'] for k in keywords] # for tweet in timeline: # score = 0 # for kw in keywords: # if kw.lower() in tweet.text.lower(): # score += 1 # if score > 0: # tweets.append({ # 'tweet': tweet, # 'score': score}) # tweets = sorted(tweets, key = lambda x: x['score'], reverse=True) # return tweets # # Path: context/nlp/entities.py # def collapse_entities(entity_list): # """Return unique list of entity names collapsed into shortest forms""" # name_list = [] # # for e in entity_list: # name_forms = sorted(e['name_forms'], key=lambda s: len(s)) # while name_forms: # name = name_forms.pop(0) # for i in range(len(name_forms) - 1, -1, -1): # s = name_forms[i] # if s.find(name) > -1: # del name_forms[i] # if name not in name_list: # name_list.append(name) # name_list.extend([s for s in name_forms if s not in name_list]) # # return name_list # # Path: context/nlp/util.py # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # ALNUM_PAT = re.compile(r'[A-Za-z0-9]+') which might include code, classes, or functions. Output only the next line.
tk = get_twitter_keys()._replace(**credentials or {})
Given the code snippet: <|code_start|>def get_timeline(users, keywords, credentials=None, limit=None): client = get_client(credentials) tweets = [] closed = [] for i, user in enumerate(users): if limit is not None and i >= limit: break for user in user['twitter_users']: if user['id'] not in closed: timeline = client.api.statuses.user_timeline.get( count=200, user_id=user['id']).data if timeline is not None: closed.append(user['id']) twits = check_keywords(timeline, keywords) if len(twits) != 0: tweets.extend(twits) return tweets def screen_name_filter(tweet_list, stoplist): """ Filter list of tweets by screen_names in stoplist. Pulls original tweets out of retweets. stoplist may be a list of usernames, or a string name of a configured named stoplist. """ tweets = [] id_set = set() if isinstance(stoplist, basestring): <|code_end|> , generate the next line using the imports in this file: import copy import os import re import urllib import requests import string import birdy.twitter from collections import defaultdict, OrderedDict from birdy.twitter import TwitterAuthError from ..config import get_twitter_keys, get_named_stoplist from ..content import all_page_text from ..nlp.keywords import check_keywords from ..nlp.entities import collapse_entities from ..nlp.util import tokenize, compare_names, name_parts, ALNUM_PAT from nltk import ngrams from nltk.corpus import stopwords and context (functions, classes, or occasionally code) from other files: # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # def get_named_stoplist(name): # """Return named stoplist.""" # config = configuration() # stoplist = config.get('stoplists', name) # return [s.strip() for s in CONFIG_LIST_REGEX.split(stoplist) if s.strip()] # # Path: context/content.py # def all_page_text(url): # try: # html = requests.get(url).text # doc = BeautifulSoup.BeautifulSoup(html) # return ' '.join([t for t in doc.findAll(text=True) if t.strip()]) # except requests.ConnectionError: # return '' # # Path: context/nlp/keywords.py # def check_keywords(timeline, keywords): # tweets = [] # keywords = [k['keyword'] for k in keywords] # for tweet in timeline: # score = 0 # for kw in keywords: # if kw.lower() in tweet.text.lower(): # score += 1 # if score > 0: # tweets.append({ # 'tweet': tweet, # 'score': score}) # tweets = sorted(tweets, key = lambda x: x['score'], reverse=True) # return tweets # # Path: context/nlp/entities.py # def collapse_entities(entity_list): # """Return unique list of entity names collapsed into shortest forms""" # name_list = [] # # for e in entity_list: # name_forms = sorted(e['name_forms'], key=lambda s: len(s)) # while name_forms: # name = name_forms.pop(0) # for i in range(len(name_forms) - 1, -1, -1): # s = name_forms[i] # if s.find(name) > -1: # del name_forms[i] # if name not in name_list: # name_list.append(name) # name_list.extend([s for s in name_forms if s not in name_list]) # # return name_list # # Path: context/nlp/util.py # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # ALNUM_PAT = re.compile(r'[A-Za-z0-9]+') . Output only the next line.
stoplist = get_named_stoplist(stoplist)
Given the following code snippet before the placeholder: <|code_start|> return tweets def lookup_users(client, handles): if not handles: return [] try: return client.api.users.lookup.post( screen_name=','.join(handles)).data except birdy.twitter.TwitterApiError, e: raise e if str(e).startswith('Invalid API resource.'): return lookup_users(client, handles[:-1]) else: raise e def get_timeline(users, keywords, credentials=None, limit=None): client = get_client(credentials) tweets = [] closed = [] for i, user in enumerate(users): if limit is not None and i >= limit: break for user in user['twitter_users']: if user['id'] not in closed: timeline = client.api.statuses.user_timeline.get( count=200, user_id=user['id']).data if timeline is not None: closed.append(user['id']) <|code_end|> , predict the next line using imports from the current file: import copy import os import re import urllib import requests import string import birdy.twitter from collections import defaultdict, OrderedDict from birdy.twitter import TwitterAuthError from ..config import get_twitter_keys, get_named_stoplist from ..content import all_page_text from ..nlp.keywords import check_keywords from ..nlp.entities import collapse_entities from ..nlp.util import tokenize, compare_names, name_parts, ALNUM_PAT from nltk import ngrams from nltk.corpus import stopwords and context including class names, function names, and sometimes code from other files: # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # def get_named_stoplist(name): # """Return named stoplist.""" # config = configuration() # stoplist = config.get('stoplists', name) # return [s.strip() for s in CONFIG_LIST_REGEX.split(stoplist) if s.strip()] # # Path: context/content.py # def all_page_text(url): # try: # html = requests.get(url).text # doc = BeautifulSoup.BeautifulSoup(html) # return ' '.join([t for t in doc.findAll(text=True) if t.strip()]) # except requests.ConnectionError: # return '' # # Path: context/nlp/keywords.py # def check_keywords(timeline, keywords): # tweets = [] # keywords = [k['keyword'] for k in keywords] # for tweet in timeline: # score = 0 # for kw in keywords: # if kw.lower() in tweet.text.lower(): # score += 1 # if score > 0: # tweets.append({ # 'tweet': tweet, # 'score': score}) # tweets = sorted(tweets, key = lambda x: x['score'], reverse=True) # return tweets # # Path: context/nlp/entities.py # def collapse_entities(entity_list): # """Return unique list of entity names collapsed into shortest forms""" # name_list = [] # # for e in entity_list: # name_forms = sorted(e['name_forms'], key=lambda s: len(s)) # while name_forms: # name = name_forms.pop(0) # for i in range(len(name_forms) - 1, -1, -1): # s = name_forms[i] # if s.find(name) > -1: # del name_forms[i] # if name not in name_list: # name_list.append(name) # name_list.extend([s for s in name_forms if s not in name_list]) # # return name_list # # Path: context/nlp/util.py # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # ALNUM_PAT = re.compile(r'[A-Za-z0-9]+') . Output only the next line.
twits = check_keywords(timeline, keywords)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- URL_PAT = re.compile(r'http[^ ]+', re.I) USER_PAT = re.compile(r'@\w{1,15}') LEAD_PAT = re.compile(u'^(RT)?\s*[.?!:;,\'"‘’“”—…\s]*', re.U | re.I) TRAIL_PAT = re.compile(u'[\s.:—…]+$', re.U) class UserClient(birdy.twitter.UserClient): """Twitter UserClient""" def __repr__(self): return dict(self).__repr__ def get_client(credentials=None): """Get credentialed Twitter UserClient""" tk = get_twitter_keys()._replace(**credentials or {}) return UserClient(*tk) def best_users(entity_names, twitter_objs): twitter_name_parts = name_parts([obj['name'] for obj in twitter_objs]) entity_name_parts = name_parts(entity_names, flat=True) <|code_end|> . Write the next line using the current file imports: import copy import os import re import urllib import requests import string import birdy.twitter from collections import defaultdict, OrderedDict from birdy.twitter import TwitterAuthError from ..config import get_twitter_keys, get_named_stoplist from ..content import all_page_text from ..nlp.keywords import check_keywords from ..nlp.entities import collapse_entities from ..nlp.util import tokenize, compare_names, name_parts, ALNUM_PAT from nltk import ngrams from nltk.corpus import stopwords and context from other files: # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # def get_named_stoplist(name): # """Return named stoplist.""" # config = configuration() # stoplist = config.get('stoplists', name) # return [s.strip() for s in CONFIG_LIST_REGEX.split(stoplist) if s.strip()] # # Path: context/content.py # def all_page_text(url): # try: # html = requests.get(url).text # doc = BeautifulSoup.BeautifulSoup(html) # return ' '.join([t for t in doc.findAll(text=True) if t.strip()]) # except requests.ConnectionError: # return '' # # Path: context/nlp/keywords.py # def check_keywords(timeline, keywords): # tweets = [] # keywords = [k['keyword'] for k in keywords] # for tweet in timeline: # score = 0 # for kw in keywords: # if kw.lower() in tweet.text.lower(): # score += 1 # if score > 0: # tweets.append({ # 'tweet': tweet, # 'score': score}) # tweets = sorted(tweets, key = lambda x: x['score'], reverse=True) # return tweets # # Path: context/nlp/entities.py # def collapse_entities(entity_list): # """Return unique list of entity names collapsed into shortest forms""" # name_list = [] # # for e in entity_list: # name_forms = sorted(e['name_forms'], key=lambda s: len(s)) # while name_forms: # name = name_forms.pop(0) # for i in range(len(name_forms) - 1, -1, -1): # s = name_forms[i] # if s.find(name) > -1: # del name_forms[i] # if name not in name_list: # name_list.append(name) # name_list.extend([s for s in name_forms if s not in name_list]) # # return name_list # # Path: context/nlp/util.py # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # ALNUM_PAT = re.compile(r'[A-Za-z0-9]+') , which may include functions, classes, or code. Output only the next line.
matches = map(lambda x: compare_names(entity_name_parts, x),
Given snippet: <|code_start|># -*- coding: utf-8 -*- URL_PAT = re.compile(r'http[^ ]+', re.I) USER_PAT = re.compile(r'@\w{1,15}') LEAD_PAT = re.compile(u'^(RT)?\s*[.?!:;,\'"‘’“”—…\s]*', re.U | re.I) TRAIL_PAT = re.compile(u'[\s.:—…]+$', re.U) class UserClient(birdy.twitter.UserClient): """Twitter UserClient""" def __repr__(self): return dict(self).__repr__ def get_client(credentials=None): """Get credentialed Twitter UserClient""" tk = get_twitter_keys()._replace(**credentials or {}) return UserClient(*tk) def best_users(entity_names, twitter_objs): <|code_end|> , continue by predicting the next line. Consider current file imports: import copy import os import re import urllib import requests import string import birdy.twitter from collections import defaultdict, OrderedDict from birdy.twitter import TwitterAuthError from ..config import get_twitter_keys, get_named_stoplist from ..content import all_page_text from ..nlp.keywords import check_keywords from ..nlp.entities import collapse_entities from ..nlp.util import tokenize, compare_names, name_parts, ALNUM_PAT from nltk import ngrams from nltk.corpus import stopwords and context: # Path: context/config.py # def get_twitter_keys(section='context'): # """Return namedtuple of Twitter config data""" # config = configuration() # TwitterKeys = collections.namedtuple('TwitterKeys', [ # 'consumer_key', # 'consumer_secret', # 'access_token', # 'access_token_secret']) # k = TwitterKeys( # config.get(section, 'twitter_consumer_key'), # config.get(section, 'twitter_consumer_secret'), # config.get(section, 'twitter_access_token'), # config.get(section, 'twitter_access_token_secret')) # return k # # def get_named_stoplist(name): # """Return named stoplist.""" # config = configuration() # stoplist = config.get('stoplists', name) # return [s.strip() for s in CONFIG_LIST_REGEX.split(stoplist) if s.strip()] # # Path: context/content.py # def all_page_text(url): # try: # html = requests.get(url).text # doc = BeautifulSoup.BeautifulSoup(html) # return ' '.join([t for t in doc.findAll(text=True) if t.strip()]) # except requests.ConnectionError: # return '' # # Path: context/nlp/keywords.py # def check_keywords(timeline, keywords): # tweets = [] # keywords = [k['keyword'] for k in keywords] # for tweet in timeline: # score = 0 # for kw in keywords: # if kw.lower() in tweet.text.lower(): # score += 1 # if score > 0: # tweets.append({ # 'tweet': tweet, # 'score': score}) # tweets = sorted(tweets, key = lambda x: x['score'], reverse=True) # return tweets # # Path: context/nlp/entities.py # def collapse_entities(entity_list): # """Return unique list of entity names collapsed into shortest forms""" # name_list = [] # # for e in entity_list: # name_forms = sorted(e['name_forms'], key=lambda s: len(s)) # while name_forms: # name = name_forms.pop(0) # for i in range(len(name_forms) - 1, -1, -1): # s = name_forms[i] # if s.find(name) > -1: # del name_forms[i] # if name not in name_list: # name_list.append(name) # name_list.extend([s for s in name_forms if s not in name_list]) # # return name_list # # Path: context/nlp/util.py # def tokenize(text): # """Return tokenized string""" # text = text.replace('@', '__at__').replace('#', '__hash__') # tokens = nltk.word_tokenize(text) # tokens = [t.replace('__at__', '@').replace('__hash__', '#') # for t in tokens] # return tokens # # def compare_names(namepartsA, namepartsB): # """Takes two name-parts lists (as lists of words) and returns a score.""" # complement = set(namepartsA) ^ set(namepartsB) # intersection = set(namepartsA) & set(namepartsB) # score = float(len(intersection))/(len(intersection)+len(complement)) # return score # # def name_parts(names, flat=False): # """Return list of words within a name""" # parts = [] # for name in names: # n = ALNUM_PAT.findall(name) # if flat: # parts.extend(n) # else: # parts.append(n) # return parts # # ALNUM_PAT = re.compile(r'[A-Za-z0-9]+') which might include code, classes, or functions. Output only the next line.
twitter_name_parts = name_parts([obj['name'] for obj in twitter_objs])
Next line prediction: <|code_start|> class GangliaPlugin(IManagerDeviceHook, IOperationsPlugin): CONFIG_PATH = "/etc/ganglia" CREDS_DIR = CONFIG_PATH + "/.creds" GMOND_CFG_MASTER_FILE = "/etc/ganglia/gmetad.conf" VERIFY_COMMAND = "sudo /usr/sbin/gmetad -V" RELOAD_COMMAND = "sudo service gmetad reload" OPSMGR_CONF = "/etc/opsmgr/opsmgr.conf" GANGLIA_SECTION = "GANGLIA" GANGLIA_SERVER = "server" GANGLIA_USERID = "userid" GANGLIA_SSHKEY = "sshkey" @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def get_application_url(): pluginApp = None if os.path.exists(GangliaPlugin.OPSMGR_CONF): try: parser = configparser.ConfigParser() parser.read(GangliaPlugin.OPSMGR_CONF, encoding='utf-8') web_protcol = parser.get(GangliaPlugin.GANGLIA_SECTION, "web_protocol").strip('"') web_proxy = parser.get(GangliaPlugin.GANGLIA_SECTION, "web_proxy").strip('"') web_port = parser.get(GangliaPlugin.GANGLIA_SECTION, "web_port").strip('"') web_path = parser.get(GangliaPlugin.GANGLIA_SECTION, "web_path").strip('"') <|code_end|> . Use current file imports: (import os import paramiko from backports import configparser from opsmgr.inventory.interfaces.IManagerDeviceHook import IManagerDeviceHook from opsmgr.inventory.interfaces.IOperationsPlugin import IOperationsPlugin from opsmgr.inventory import plugins from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit) and context including class names, function names, or small code snippets from other files: # Path: opsmgr/inventory/interfaces/IOperationsPlugin.py # class IOperationsPlugin(object): # __metaclass__ = ABCMeta # # @staticmethod # @abstractmethod # def get_application_url(): # pass # # @staticmethod # @abstractmethod # def get_plugins_status(): # pass # # Path: opsmgr/inventory/plugins.py # I_OPERATIONS_PLUGINS = "opsmgr.inventory.interfaces.IOperationsPlugin" # class PluginApplication(): # def __init__(self, name, function, protocol, host, port, path): # def get_name(self): # def get_function(self): # def get_protocol(self): # def get_host(self): # def get_port(self): # def get_path(self): # def get_operations_plugins(): # def get_plugins_status(): # def _load_operations_plugins(): # # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
pluginApp = plugins.PluginApplication("ganglia", "monitoring", web_protcol,
Given the following code snippet before the placeholder: <|code_start|> GangliaPlugin._remove_config_files(address) GangliaPlugin._reload_gmetad() @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def change_device_post_save(device, old_device_info): new_address = device.address old_address = old_device_info["ip-address"] if new_address != old_address: GangliaPlugin._change_config_files(old_address) GangliaPlugin._reload_gmetad() @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def get_status(): return (None, None) @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def _reload_gmetad(): """ Reload the gmetad server from within the ganglia container """ try: client = GangliaPlugin._connect() # Validate the gmetad config is good (_stdin, stdout, _stderr) = client.exec_command(GangliaPlugin.VERIFY_COMMAND) rc = stdout.channel.recv_exit_status() output = stdout.read().decode() if rc != 0: <|code_end|> , predict the next line using imports from the current file: import os import paramiko from backports import configparser from opsmgr.inventory.interfaces.IManagerDeviceHook import IManagerDeviceHook from opsmgr.inventory.interfaces.IOperationsPlugin import IOperationsPlugin from opsmgr.inventory import plugins from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit and context including class names, function names, and sometimes code from other files: # Path: opsmgr/inventory/interfaces/IOperationsPlugin.py # class IOperationsPlugin(object): # __metaclass__ = ABCMeta # # @staticmethod # @abstractmethod # def get_application_url(): # pass # # @staticmethod # @abstractmethod # def get_plugins_status(): # pass # # Path: opsmgr/inventory/plugins.py # I_OPERATIONS_PLUGINS = "opsmgr.inventory.interfaces.IOperationsPlugin" # class PluginApplication(): # def __init__(self, name, function, protocol, host, port, path): # def get_name(self): # def get_function(self): # def get_protocol(self): # def get_host(self): # def get_port(self): # def get_path(self): # def get_operations_plugins(): # def get_plugins_status(): # def _load_operations_plugins(): # # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
raise exceptions.OpsException("Validation of the gmetad configuration failed:\n"
Given snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class GangliaPlugin(IManagerDeviceHook, IOperationsPlugin): CONFIG_PATH = "/etc/ganglia" CREDS_DIR = CONFIG_PATH + "/.creds" GMOND_CFG_MASTER_FILE = "/etc/ganglia/gmetad.conf" VERIFY_COMMAND = "sudo /usr/sbin/gmetad -V" RELOAD_COMMAND = "sudo service gmetad reload" OPSMGR_CONF = "/etc/opsmgr/opsmgr.conf" GANGLIA_SECTION = "GANGLIA" GANGLIA_SERVER = "server" GANGLIA_USERID = "userid" GANGLIA_SSHKEY = "sshkey" @staticmethod <|code_end|> , continue by predicting the next line. Consider current file imports: import os import paramiko from backports import configparser from opsmgr.inventory.interfaces.IManagerDeviceHook import IManagerDeviceHook from opsmgr.inventory.interfaces.IOperationsPlugin import IOperationsPlugin from opsmgr.inventory import plugins from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit and context: # Path: opsmgr/inventory/interfaces/IOperationsPlugin.py # class IOperationsPlugin(object): # __metaclass__ = ABCMeta # # @staticmethod # @abstractmethod # def get_application_url(): # pass # # @staticmethod # @abstractmethod # def get_plugins_status(): # pass # # Path: opsmgr/inventory/plugins.py # I_OPERATIONS_PLUGINS = "opsmgr.inventory.interfaces.IOperationsPlugin" # class PluginApplication(): # def __init__(self, name, function, protocol, host, port, path): # def get_name(self): # def get_function(self): # def get_protocol(self): # def get_host(self): # def get_port(self): # def get_path(self): # def get_operations_plugins(): # def get_plugins_status(): # def _load_operations_plugins(): # # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f which might include code, classes, or functions. Output only the next line.
@entry_exit(exclude_index=[], exclude_name=[])
Given snippet: <|code_start|> @staticmethod def get_type(): return "LenovoRackSwitch" @staticmethod def get_web_url(host): return "https://" + host @staticmethod def get_capabilities(): return [constants.MONITORING_CAPABLE] @entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"]) def connect(self, host, userid, password=None, ssh_key_string=None): _method_ = "RackSwitchPlugin.connect" self.host = host self.userid = userid self.password = password try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False, look_for_keys=False) if not self._is_rack_switch(): <|code_end|> , continue by predicting the next line. Consider current file imports: import logging import socket import time import paramiko from StringIO import StringIO from io import StringIO from opsmgr.common import constants from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit from opsmgr.inventory.interfaces import IManagerDevicePlugin and context: # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f which might include code, classes, or functions. Output only the next line.
raise exceptions.DeviceException(
Given the code snippet: <|code_start|> SERIAL_NUM_TAG = "Switch Serial" MTM_TAG = "MTM Value" ENABLE_COMMAND = "enable\n" PASSWORD_CHANGE_COMMAND = "password\n" PASSWORD_CHANGED_MESSAGE = "Password changed and applied" def __init__(self): self.client = None self.host = None self.userid = None self.password = None self.ssh_key_string = None self.machine_type_model = "" self.serial_number = "" self.version = "" @staticmethod def get_type(): return "LenovoRackSwitch" @staticmethod def get_web_url(host): return "https://" + host @staticmethod def get_capabilities(): return [constants.MONITORING_CAPABLE] <|code_end|> , generate the next line using the imports in this file: import logging import socket import time import paramiko from StringIO import StringIO from io import StringIO from opsmgr.common import constants from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit from opsmgr.inventory.interfaces import IManagerDevicePlugin and context (functions, classes, or occasionally code) from other files: # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
@entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"])
Continue the code snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class ELKPlugin(IOperationsPlugin): OPSMGR_CONF = "/etc/opsmgr/opsmgr.conf" ELK_SECTION = "ELK" @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def get_application_url(): pluginApp = None if os.path.exists(ELKPlugin.OPSMGR_CONF): try: parser = configparser.ConfigParser() parser.read(ELKPlugin.OPSMGR_CONF, encoding='utf-8') web_protcol = parser.get(ELKPlugin.ELK_SECTION, "web_protocol") web_proxy = parser.get(ELKPlugin.ELK_SECTION, "web_proxy") web_port = parser.get(ELKPlugin.ELK_SECTION, "web_port") application = "ELK" capability = "logging" <|code_end|> . Use current file imports: import os from backports import configparser from opsmgr.inventory.interfaces.IOperationsPlugin import IOperationsPlugin from opsmgr.inventory import plugins from opsmgr.common.utils import entry_exit and context (classes, functions, or code) from other files: # Path: opsmgr/inventory/interfaces/IOperationsPlugin.py # class IOperationsPlugin(object): # __metaclass__ = ABCMeta # # @staticmethod # @abstractmethod # def get_application_url(): # pass # # @staticmethod # @abstractmethod # def get_plugins_status(): # pass # # Path: opsmgr/inventory/plugins.py # I_OPERATIONS_PLUGINS = "opsmgr.inventory.interfaces.IOperationsPlugin" # class PluginApplication(): # def __init__(self, name, function, protocol, host, port, path): # def get_name(self): # def get_function(self): # def get_protocol(self): # def get_host(self): # def get_port(self): # def get_path(self): # def get_operations_plugins(): # def get_plugins_status(): # def _load_operations_plugins(): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
pluginApp = plugins.PluginApplication(application, capability, web_protcol,
Next line prediction: <|code_start|># Copyright 2017, IBM US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class ELKPlugin(IOperationsPlugin): OPSMGR_CONF = "/etc/opsmgr/opsmgr.conf" ELK_SECTION = "ELK" @staticmethod <|code_end|> . Use current file imports: (import os from backports import configparser from opsmgr.inventory.interfaces.IOperationsPlugin import IOperationsPlugin from opsmgr.inventory import plugins from opsmgr.common.utils import entry_exit) and context including class names, function names, or small code snippets from other files: # Path: opsmgr/inventory/interfaces/IOperationsPlugin.py # class IOperationsPlugin(object): # __metaclass__ = ABCMeta # # @staticmethod # @abstractmethod # def get_application_url(): # pass # # @staticmethod # @abstractmethod # def get_plugins_status(): # pass # # Path: opsmgr/inventory/plugins.py # I_OPERATIONS_PLUGINS = "opsmgr.inventory.interfaces.IOperationsPlugin" # class PluginApplication(): # def __init__(self, name, function, protocol, host, port, path): # def get_name(self): # def get_function(self): # def get_protocol(self): # def get_host(self): # def get_port(self): # def get_path(self): # def get_operations_plugins(): # def get_plugins_status(): # def _load_operations_plugins(): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
@entry_exit(exclude_index=[], exclude_name=[])
Given the following code snippet before the placeholder: <|code_start|> self.password = "" @staticmethod def get_type(): return "Redhat Enterprise Linux" @staticmethod def get_web_url(host): return None @staticmethod def get_capabilities(): return [constants.LOGGING_CAPABLE, constants.MONITORING_CAPABLE] @entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"]) def connect(self, host, userid, password=None, ssh_key_string=None): _method_ = "RhelPlugin.connect" self.userid = userid self.password = password try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False) if not self._is_guest_rhel(): <|code_end|> , predict the next line using imports from the current file: import logging import socket import time import paramiko from StringIO import StringIO from io import StringIO from opsmgr.common import constants from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit from opsmgr.inventory.interfaces import IManagerDevicePlugin and context including class names, function names, and sometimes code from other files: # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
raise exceptions.InvalidDeviceException(
Next line prediction: <|code_start|> RHEL_RELEASE_FILE = "/etc/redhat-release" RELEASE_TAG = "Red Hat Enterprise" class RhelPlugin(IManagerDevicePlugin.IManagerDevicePlugin): PASSWORD_CHANGE_COMMAND = "passwd\n" PASSWORD_CHANGED_MESSAGE = "all authentication tokens updated successfully" def __init__(self): self.client = None self.machine_type_model = "" self.serial_number = "" self.userid = "" self.password = "" @staticmethod def get_type(): return "Redhat Enterprise Linux" @staticmethod def get_web_url(host): return None @staticmethod def get_capabilities(): return [constants.LOGGING_CAPABLE, constants.MONITORING_CAPABLE] <|code_end|> . Use current file imports: (import logging import socket import time import paramiko from StringIO import StringIO from io import StringIO from opsmgr.common import constants from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit from opsmgr.inventory.interfaces import IManagerDevicePlugin) and context including class names, function names, or small code snippets from other files: # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
@entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"])
Predict the next line after this snippet: <|code_start|># Copyright 2016, IBM US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. I_DISCOVERY_PLUGIN = "opsmgr.discovery.interfaces.IDiscoveryPlugin" @entry_exit(exclude_index=[], exclude_name=[]) def _load_plugins(): """ Find the discovery provider plugins and return them as dictonary[name]=plugin class """ <|code_end|> using the current file's imports: import logging from opsmgr.common.utils import entry_exit, load_plugin_by_namespace and any relevant context from other files: # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f # # def load_plugin_by_namespace(namespace): # plugins = {} # extensions = extension.ExtensionManager(namespace=namespace) # # for ext in extensions: # plugins[ext.name] = ext.plugin() # return plugins . Output only the next line.
return load_plugin_by_namespace(I_DISCOVERY_PLUGIN)
Predict the next line after this snippet: <|code_start|> rack_id = None session = persistent_mgr.create_database_session() rack = persistent_mgr.get_rack_by_label(session, rack_label) if rack: rack_id = rack.rack_id session.close() return rack_id def _get_racktag_text_id(tag_name): racktag_id = { 'rackid': _('id'), 'label': _('label'), 'mgrRackId': _('manager rack'), 'role': _('role'), 'data-center': _('data center'), 'room': _('room'), 'row': _('row'), 'notes': _('notes'), } if tag_name in racktag_id: return racktag_id[tag_name] return tag_name def _load_inventory_rack_plugins(): """ Find the inventory rack plugins and return them as dictonary[name]=plugin class """ <|code_end|> using the current file's imports: import gettext import logging from opsmgr.inventory import persistent_mgr, resource_mgr from opsmgr.common.utils import entry_exit, push_message, load_plugin_by_namespace from opsmgr.inventory.data_model import Rack and any relevant context from other files: # Path: opsmgr/inventory/resource_mgr.py # I_MANAGER_DEVICE_PLUGIN = "opsmgr.inventory.interfaces.IManagerDevicePlugin" # I_MANAGER_DEVICE_HOOK = "opsmgr.inventory.interfaces.IManagerDeviceHook" # I_MANAGER_RACK_HOOK = "opsmgr.inventory.interfaces.IManagerRackHook" # def add_resource(label, device_type, address, userid, password, rackid='', rack_location='', # ssh_key=None, offline=False): # def change_resource_password(label=None, deviceid=None, old_password=None, new_password=None): # def change_resource_properties(label=None, deviceid=None, new_label=None, # userid=None, password=None, address=None, # rackid=None, rack_location=None, ssh_key=None): # def list_resources(labels=None, isbriefly=False, device_types=None, deviceids=None, # list_device_id=False, is_detail=False, racks=None): # def remove_resource(labels=None, all_devices=False, deviceids=None): # def list_resource_types(): # def get_labels_message(items): # def get_resource_id_by_label(resource_label): # def add_resource_roles(resource_label=None, resource_id=None, roles=None, additional_data=None): # def validate(address, userid, password, device_type, ssh_key=None): # def _validate(address, userid, password, device_type, ssh_key=None): # def _get_devicetag_text_id(tag_name): # def _change_device_key(device, address, userid, ssh_key_string, password): # def _change_device_userpass(device, address, userid, password): # def _load_device_plugins(): # def _load_inventory_device_plugins(): # def _check_device_exist(session, address): # def _check_device_exist_by_props(session, device_type, mtm, serialnum): # def validate_address(address): # def validate_label(label): # def _check_address(address): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f # # def push_message(message, new_message): # if new_message is not None and len(new_message) > 0: # if message: # message = message + '\n' + new_message # else: # message = new_message # return message # # def load_plugin_by_namespace(namespace): # plugins = {} # extensions = extension.ExtensionManager(namespace=namespace) # # for ext in extensions: # plugins[ext.name] = ext.plugin() # return plugins # # Path: opsmgr/inventory/data_model.py # class Rack(Base): # __tablename__ = "rack" # rack_id = Column(Integer, primary_key=True) # # # user defined label for rack # label = Column(String(255), nullable=False, unique=True) # # data_center = Column(String(255)) # room = Column(String(255)) # row = Column(String(255)) # notes = Column(Text()) # # resources = relationship("Resource", back_populates="rack") # # def to_dict_obj(self): # result = {} # result["rackid"] = self.rack_id # result["label"] = self.label # result["room"] = self.room # result["row"] = self.row # result["data-center"] = self.data_center # result["notes"] = self.notes # return result # # def __repr__(self, *args, **kwargs): # _dict = self.to_dict_obj() # return str(_dict) . Output only the next line.
return load_plugin_by_namespace(I_MANAGER_RACK_HOOK)
Continue the code snippet: <|code_start|>@entry_exit(exclude_index=[], exclude_name=[]) def add_rack(label, data_center='', room='', row='', notes=''): """add rack to the list of racks in the configuration managed Args: label: label for rack data_center: data center location (free form) room: Room in the data center of the rack (free form) row: Row in the room of the rack (free form) notes: freeform notes associated with this rack to describe its use, mgmt, etc. Returns: RC: integer return code Message: string with message associated with return code """ _method_ = 'rack_mgr.add_rack' label = label.strip() message = None session = persistent_mgr.create_database_session() # get existing rack info for next set of checks racks_info = persistent_mgr.get_all_racks(session) for rack in racks_info: if rack.label == label: message = _( "The rack label (%s) conflicts with a rack label in the configuration file.") \ % label return 101, message <|code_end|> . Use current file imports: import gettext import logging from opsmgr.inventory import persistent_mgr, resource_mgr from opsmgr.common.utils import entry_exit, push_message, load_plugin_by_namespace from opsmgr.inventory.data_model import Rack and context (classes, functions, or code) from other files: # Path: opsmgr/inventory/resource_mgr.py # I_MANAGER_DEVICE_PLUGIN = "opsmgr.inventory.interfaces.IManagerDevicePlugin" # I_MANAGER_DEVICE_HOOK = "opsmgr.inventory.interfaces.IManagerDeviceHook" # I_MANAGER_RACK_HOOK = "opsmgr.inventory.interfaces.IManagerRackHook" # def add_resource(label, device_type, address, userid, password, rackid='', rack_location='', # ssh_key=None, offline=False): # def change_resource_password(label=None, deviceid=None, old_password=None, new_password=None): # def change_resource_properties(label=None, deviceid=None, new_label=None, # userid=None, password=None, address=None, # rackid=None, rack_location=None, ssh_key=None): # def list_resources(labels=None, isbriefly=False, device_types=None, deviceids=None, # list_device_id=False, is_detail=False, racks=None): # def remove_resource(labels=None, all_devices=False, deviceids=None): # def list_resource_types(): # def get_labels_message(items): # def get_resource_id_by_label(resource_label): # def add_resource_roles(resource_label=None, resource_id=None, roles=None, additional_data=None): # def validate(address, userid, password, device_type, ssh_key=None): # def _validate(address, userid, password, device_type, ssh_key=None): # def _get_devicetag_text_id(tag_name): # def _change_device_key(device, address, userid, ssh_key_string, password): # def _change_device_userpass(device, address, userid, password): # def _load_device_plugins(): # def _load_inventory_device_plugins(): # def _check_device_exist(session, address): # def _check_device_exist_by_props(session, device_type, mtm, serialnum): # def validate_address(address): # def validate_label(label): # def _check_address(address): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f # # def push_message(message, new_message): # if new_message is not None and len(new_message) > 0: # if message: # message = message + '\n' + new_message # else: # message = new_message # return message # # def load_plugin_by_namespace(namespace): # plugins = {} # extensions = extension.ExtensionManager(namespace=namespace) # # for ext in extensions: # plugins[ext.name] = ext.plugin() # return plugins # # Path: opsmgr/inventory/data_model.py # class Rack(Base): # __tablename__ = "rack" # rack_id = Column(Integer, primary_key=True) # # # user defined label for rack # label = Column(String(255), nullable=False, unique=True) # # data_center = Column(String(255)) # room = Column(String(255)) # row = Column(String(255)) # notes = Column(Text()) # # resources = relationship("Resource", back_populates="rack") # # def to_dict_obj(self): # result = {} # result["rackid"] = self.rack_id # result["label"] = self.label # result["room"] = self.room # result["row"] = self.row # result["data-center"] = self.data_center # result["notes"] = self.notes # return result # # def __repr__(self, *args, **kwargs): # _dict = self.to_dict_obj() # return str(_dict) . Output only the next line.
rack_info = Rack()
Next line prediction: <|code_start|> @staticmethod def remove_device_pre_save(device): pass @staticmethod def change_device_pre_save(device, old_device_info): pass @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def add_device_post_save(device): if device.resource_type == "Ubuntu": address = device.address userid = device.userid key = device.key if key: key_string = key.value if key.password is not None: password = persistent_mgr.decrypt_data(key.password) else: password = None else: key_string = None password = persistent_mgr.decrypt_data(device.password) client = UlyssesDevicePlugin._connect(address, userid, password, key_string) roles = [] command = "cat " + UlyssesDevicePlugin.ROLE_FILE (_stdin, stdout, _stderr) = client.exec_command(command) for line in stdout.read().decode().splitlines(): roles.append(line.strip()) <|code_end|> . Use current file imports: ( from StringIO import StringIO from io import StringIO from opsmgr.inventory.interfaces.IManagerDeviceHook import IManagerDeviceHook from opsmgr.inventory import resource_mgr, persistent_mgr from opsmgr.common.utils import entry_exit import paramiko) and context including class names, function names, or small code snippets from other files: # Path: opsmgr/inventory/resource_mgr.py # I_MANAGER_DEVICE_PLUGIN = "opsmgr.inventory.interfaces.IManagerDevicePlugin" # I_MANAGER_DEVICE_HOOK = "opsmgr.inventory.interfaces.IManagerDeviceHook" # I_MANAGER_RACK_HOOK = "opsmgr.inventory.interfaces.IManagerRackHook" # def add_resource(label, device_type, address, userid, password, rackid='', rack_location='', # ssh_key=None, offline=False): # def change_resource_password(label=None, deviceid=None, old_password=None, new_password=None): # def change_resource_properties(label=None, deviceid=None, new_label=None, # userid=None, password=None, address=None, # rackid=None, rack_location=None, ssh_key=None): # def list_resources(labels=None, isbriefly=False, device_types=None, deviceids=None, # list_device_id=False, is_detail=False, racks=None): # def remove_resource(labels=None, all_devices=False, deviceids=None): # def list_resource_types(): # def get_labels_message(items): # def get_resource_id_by_label(resource_label): # def add_resource_roles(resource_label=None, resource_id=None, roles=None, additional_data=None): # def validate(address, userid, password, device_type, ssh_key=None): # def _validate(address, userid, password, device_type, ssh_key=None): # def _get_devicetag_text_id(tag_name): # def _change_device_key(device, address, userid, ssh_key_string, password): # def _change_device_userpass(device, address, userid, password): # def _load_device_plugins(): # def _load_inventory_device_plugins(): # def _check_device_exist(session, address): # def _check_device_exist_by_props(session, device_type, mtm, serialnum): # def validate_address(address): # def validate_label(label): # def _check_address(address): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
resource_mgr.add_resource_roles(device.resource_id, roles)
Here is a snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: # python 2.7 except ImportError: # python 3.4 class UlyssesDevicePlugin(IManagerDeviceHook): ROLE_FILE = "/etc/roles" @staticmethod def add_device_pre_save(device): pass @staticmethod def remove_device_pre_save(device): pass @staticmethod def change_device_pre_save(device, old_device_info): pass @staticmethod <|code_end|> . Write the next line using the current file imports: from StringIO import StringIO from io import StringIO from opsmgr.inventory.interfaces.IManagerDeviceHook import IManagerDeviceHook from opsmgr.inventory import resource_mgr, persistent_mgr from opsmgr.common.utils import entry_exit import paramiko and context from other files: # Path: opsmgr/inventory/resource_mgr.py # I_MANAGER_DEVICE_PLUGIN = "opsmgr.inventory.interfaces.IManagerDevicePlugin" # I_MANAGER_DEVICE_HOOK = "opsmgr.inventory.interfaces.IManagerDeviceHook" # I_MANAGER_RACK_HOOK = "opsmgr.inventory.interfaces.IManagerRackHook" # def add_resource(label, device_type, address, userid, password, rackid='', rack_location='', # ssh_key=None, offline=False): # def change_resource_password(label=None, deviceid=None, old_password=None, new_password=None): # def change_resource_properties(label=None, deviceid=None, new_label=None, # userid=None, password=None, address=None, # rackid=None, rack_location=None, ssh_key=None): # def list_resources(labels=None, isbriefly=False, device_types=None, deviceids=None, # list_device_id=False, is_detail=False, racks=None): # def remove_resource(labels=None, all_devices=False, deviceids=None): # def list_resource_types(): # def get_labels_message(items): # def get_resource_id_by_label(resource_label): # def add_resource_roles(resource_label=None, resource_id=None, roles=None, additional_data=None): # def validate(address, userid, password, device_type, ssh_key=None): # def _validate(address, userid, password, device_type, ssh_key=None): # def _get_devicetag_text_id(tag_name): # def _change_device_key(device, address, userid, ssh_key_string, password): # def _change_device_userpass(device, address, userid, password): # def _load_device_plugins(): # def _load_inventory_device_plugins(): # def _check_device_exist(session, address): # def _check_device_exist_by_props(session, device_type, mtm, serialnum): # def validate_address(address): # def validate_label(label): # def _check_address(address): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f , which may include functions, classes, or code. Output only the next line.
@entry_exit(exclude_index=[], exclude_name=[])
Next line prediction: <|code_start|> self.serial_number = "" @staticmethod def get_type(): return "MLNX-OS" @staticmethod def get_web_url(host): return "https://" + host @staticmethod def get_capabilities(): return [constants.MONITORING_CAPABLE] @entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"]) def connect(self, host, userid, password=None, ssh_key_string=None): _method_ = "MLNXOSPlugin.connect" self.host = host self.userid = userid try: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if ssh_key_string: private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password) self.client.connect(host, username=userid, pkey=private_key, timeout=30, allow_agent=False) else: self.client.connect(host, username=userid, password=password, timeout=30, allow_agent=False) if not self._is_mellanox_switch(): <|code_end|> . Use current file imports: (import logging import socket import time import paramiko from StringIO import StringIO from io import StringIO from opsmgr.common import constants from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit from opsmgr.inventory.interfaces import IManagerDevicePlugin) and context including class names, function names, or small code snippets from other files: # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
raise exceptions.InvalidDeviceException(
Based on the snippet: <|code_start|> class MLNXOSPlugin(IManagerDevicePlugin.IManagerDevicePlugin): SHOW_INVENTORY_COMMAND = "show inventory\n" CHASSIS_INFORMATION = "CHASSIS" GET_VERSION_COMMAND = "show version | include \"Product release:\"\n" VERSION_TAG = "Product release" ENABLE_COMMAND = "enable\n" CONFIGURE_TERMINAL_COMMAND = "configure terminal\n" def __init__(self): self.client = None self.host = None self.userid = None self.machine_type_model = "" self.serial_number = "" @staticmethod def get_type(): return "MLNX-OS" @staticmethod def get_web_url(host): return "https://" + host @staticmethod def get_capabilities(): return [constants.MONITORING_CAPABLE] <|code_end|> , predict the immediate next line with the help of imports: import logging import socket import time import paramiko from StringIO import StringIO from io import StringIO from opsmgr.common import constants from opsmgr.common import exceptions from opsmgr.common.utils import entry_exit from opsmgr.inventory.interfaces import IManagerDevicePlugin and context (classes, functions, sometimes code) from other files: # Path: opsmgr/common/exceptions.py # class OpsException(Exception): # class ConnectionException(OpsException): # class AuthenticationException(OpsException): # class DeviceException(OpsException): # class InvalidDeviceException(DeviceException): # class ProviderException(OpsException): # # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f . Output only the next line.
@entry_exit(exclude_index=[0, 3, 4], exclude_name=["self", "password", "ssh_key_string"])
Here is a snippet: <|code_start|> class PluginApplication(): def __init__(self, name, function, protocol, host, port, path): self.name = name self.function = function self.protocol = protocol self.host = host self.port = port self.path = path def get_name(self): return self.name def get_function(self): return self.function def get_protocol(self): return self.protocol def get_host(self): return self.host def get_port(self): return self.port def get_path(self): return self.path @staticmethod <|code_end|> . Write the next line using the current file imports: from opsmgr.common.utils import entry_exit, load_plugin_by_namespace and context from other files: # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f # # def load_plugin_by_namespace(namespace): # plugins = {} # extensions = extension.ExtensionManager(namespace=namespace) # # for ext in extensions: # plugins[ext.name] = ext.plugin() # return plugins , which may include functions, classes, or code. Output only the next line.
@entry_exit(exclude_index=[], exclude_name=[])
Given snippet: <|code_start|> plugins = PluginApplication._load_operations_plugins() for _plugin_name, plugin_class in plugins.items(): plugin_app = plugin_class.get_application_url() if plugin_app is not None: plugin_apps.append(plugin_app) return plugin_apps @staticmethod @entry_exit(exclude_index=[], exclude_name=[]) def get_plugins_status(): """ Returns two list of Strings for critical and warning messages from all plugins on the localhost. """ critical_messages = [] warning_messages = [] plugins = PluginApplication._load_operations_plugins() for _plugin_name, plugin_class in plugins.items(): (crit, warn) = plugin_class.get_status() if crit is not None: critical_messages.extend(crit) if warn is not None: warning_messages.extend(warn) return (critical_messages, warning_messages) @staticmethod def _load_operations_plugins(): """ Find the operations plugins and return them as a dictonary[name]=plugin class """ <|code_end|> , continue by predicting the next line. Consider current file imports: from opsmgr.common.utils import entry_exit, load_plugin_by_namespace and context: # Path: opsmgr/common/utils.py # def entry_exit(exclude_index=None, exclude_name=None, log_name=None, level=logging.INFO): # """ # it's a decorator that to add entry and exit log for a function # # input: # excludeIndex -- the index of params that you don't want to be record # excludeName -- the name of dictionary params that you don't wnat to be record # log_name -- name of the log to write the logging to. # level -- the logging level to log the entry/exit with. default is INFO level # """ # # def f(func): # @functools.wraps(func) # def wrapper(*args, **kwargs): # # args_for_print = [] # tmp_index = 0 # arg_len = len(args) # while tmp_index < arg_len: # if tmp_index not in exclude_index: # args_for_print.append(args[tmp_index]) # tmp_index += 1 # # kwargs_for_print = {} # for a in kwargs: # if a in exclude_name: # continue # else: # kwargs_for_print[a] = kwargs[a] # # logging.getLogger(log_name).log(level, # "%s::Entry params %s %s", func.__name__, "{}".format( # args_for_print), "{}".format(kwargs_for_print)) # result = func(*args, **kwargs) # logging.getLogger(log_name).log(level, # "%s::Exit %s ", func.__name__, "{}".format(result)) # return result # return wrapper # return f # # def load_plugin_by_namespace(namespace): # plugins = {} # extensions = extension.ExtensionManager(namespace=namespace) # # for ext in extensions: # plugins[ext.name] = ext.plugin() # return plugins which might include code, classes, or functions. Output only the next line.
return load_plugin_by_namespace(I_OPERATIONS_PLUGINS)
Given snippet: <|code_start|> if len(result_dict['racks']) > 0: the_rack = rack.Rack(result_dict['racks'][0]) counter = 0 rack_meta_data.append(RackProperty(counter, "Label", the_rack.name)) counter += 1 rack_meta_data.append(RackProperty(counter, "Data Center", the_rack.data_center)) counter += 1 rack_meta_data.append(RackProperty(counter, "Room", the_rack.room)) counter += 1 rack_meta_data.append(RackProperty(counter, "Row", the_rack.row)) counter += 1 rack_meta_data.append(RackProperty(counter, "Notes", the_rack.notes)) return rack_meta_data def retrieve_application_links(self, request): __method__ = 'tabs.retrieve_application_links' app_link_data = {} # Retrieve the applications' link information <|code_end|> , continue by predicting the next line. Consider current file imports: from django.utils.translation import ugettext_lazy as _ from horizon import messages from horizon import tabs from operational_mgmt.inventory import tables from operational_mgmt import rack from operational_mgmt import resource from opsmgr.inventory.plugins import PluginApplication import logging import opsmgr.inventory.rack_mgr as rack_mgr import opsmgr.inventory.resource_mgr as resource_mgr and context: # Path: opsmgr/inventory/plugins.py # class PluginApplication(): # # def __init__(self, name, function, protocol, host, port, path): # self.name = name # self.function = function # self.protocol = protocol # self.host = host # self.port = port # self.path = path # # def get_name(self): # return self.name # # def get_function(self): # return self.function # # def get_protocol(self): # return self.protocol # # def get_host(self): # return self.host # # def get_port(self): # return self.port # # def get_path(self): # return self.path # # @staticmethod # @entry_exit(exclude_index=[], exclude_name=[]) # def get_operations_plugins(): # """ Returns a List of PluginApplication classes so the url for an installed application # can be constructed. For plugins installed on the localhost, it is recommened to not use # the host field here, but use the host or ip the user specified in the url. # """ # plugin_apps = [] # plugins = PluginApplication._load_operations_plugins() # for _plugin_name, plugin_class in plugins.items(): # plugin_app = plugin_class.get_application_url() # if plugin_app is not None: # plugin_apps.append(plugin_app) # return plugin_apps # # @staticmethod # @entry_exit(exclude_index=[], exclude_name=[]) # def get_plugins_status(): # """ Returns two list of Strings for critical and warning messages from # all plugins on the localhost. # """ # critical_messages = [] # warning_messages = [] # plugins = PluginApplication._load_operations_plugins() # for _plugin_name, plugin_class in plugins.items(): # (crit, warn) = plugin_class.get_status() # if crit is not None: # critical_messages.extend(crit) # if warn is not None: # warning_messages.extend(warn) # return (critical_messages, warning_messages) # # @staticmethod # def _load_operations_plugins(): # """ # Find the operations plugins and return them as a # dictonary[name]=plugin class # """ # return load_plugin_by_namespace(I_OPERATIONS_PLUGINS) which might include code, classes, or functions. Output only the next line.
applications = PluginApplication.get_operations_plugins()
Given the code snippet: <|code_start|> @login_required def logout(request): if request.method == "POST": django.contrib.auth.logout(request) return redirect('/') @login_required def index(request): admins = django.contrib.auth.models.User.objects.filter(is_staff=True) context = { 'username': request.user.username, <|code_end|> , generate the next line using the imports in this file: import json import re import django.contrib.auth from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from .models import Round, Puzzle, to_json_value and context (functions, classes, or occasionally code) from other files: # Path: herring/puzzles/models.py # class Round(models.Model,JSONMixin): # # shell model for defining rounds # number = models.IntegerField(default=1) # name = models.CharField(max_length=200) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # def __str__(self): # return 'R' + str(self.number) # # class Meta: # ordering = ['number', 'id'] # class Json: # include_fields = ['id', 'name', 'number', 'puzzle_set', 'hunt_url'] # # class Puzzle(models.Model,JSONMixin): # # class for all puzzles, including metas # parent = models.ForeignKey(Round) # name = models.CharField(max_length=200) # slug = AutoSlugField( # populate_from=puzzle_to_slug, # unique=True, # db_index=True # ) # number = models.IntegerField(**optional) # answer = models.CharField(max_length=200, default='', **optional) # note = models.CharField(max_length=200, default='', **optional) # tags = models.CharField(max_length=200, default='', **optional) # is_meta = models.BooleanField(default=False) # url = models.CharField(max_length=1000, default='', **optional) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # tracker = FieldTracker() # # class Meta: # ordering = ['parent', '-is_meta', 'number', 'id'] # # class Json: # include_fields = ['id', 'name', 'number', 'answer', 'note', 'tags', 'is_meta', 'url', 'hunt_url', 'slug'] # # def identifier(self): # child_type = 'P' # if self.is_meta: # child_type = 'M' # num = str(self.number) if self.number is not None else 'x' # return str(self.parent) + child_type + num # # def __str__(self): # return '#%s %s' % (self.slug, self.name) # # def is_answered(self): # return bool(self.answer) # # def to_json_value(field): # if isinstance(field, str): # return field # if isinstance(field, int): # return field # if isinstance(field, dict): # return { key: to_json_value(value) for key, value in field.items() } # if isinstance(field, (list, models.query.QuerySet)): # return [to_json_value(item) for item in field] # if isinstance(field, models.manager.Manager): # return [to_json_value(item) for item in field.all()] # if isinstance(field, JSONMixin): # return field.to_json() . Output only the next line.
'rounds': Round.objects.all(),
Given the following code snippet before the placeholder: <|code_start|> 'admins': admins, } return render(request, 'puzzles/index.html', context) @login_required def get_resources(request): return render(request, 'puzzles/resources.html', {}) @login_required def get_puzzles(request): data = { 'rounds': Round.objects.all() } print("Serializing puzzle data.") return JsonResponse(to_json_value(data)) @login_required def one_puzzle(request, puzzle_id): if request.method == "POST": return update_puzzle(request, puzzle_id) else: return get_one_puzzle(request, puzzle_id) def to_channel(title): return re.sub(r'\W+', '_', title.lower()) def get_one_puzzle(request, puzzle_id): <|code_end|> , predict the next line using imports from the current file: import json import re import django.contrib.auth from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from .models import Round, Puzzle, to_json_value and context including class names, function names, and sometimes code from other files: # Path: herring/puzzles/models.py # class Round(models.Model,JSONMixin): # # shell model for defining rounds # number = models.IntegerField(default=1) # name = models.CharField(max_length=200) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # def __str__(self): # return 'R' + str(self.number) # # class Meta: # ordering = ['number', 'id'] # class Json: # include_fields = ['id', 'name', 'number', 'puzzle_set', 'hunt_url'] # # class Puzzle(models.Model,JSONMixin): # # class for all puzzles, including metas # parent = models.ForeignKey(Round) # name = models.CharField(max_length=200) # slug = AutoSlugField( # populate_from=puzzle_to_slug, # unique=True, # db_index=True # ) # number = models.IntegerField(**optional) # answer = models.CharField(max_length=200, default='', **optional) # note = models.CharField(max_length=200, default='', **optional) # tags = models.CharField(max_length=200, default='', **optional) # is_meta = models.BooleanField(default=False) # url = models.CharField(max_length=1000, default='', **optional) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # tracker = FieldTracker() # # class Meta: # ordering = ['parent', '-is_meta', 'number', 'id'] # # class Json: # include_fields = ['id', 'name', 'number', 'answer', 'note', 'tags', 'is_meta', 'url', 'hunt_url', 'slug'] # # def identifier(self): # child_type = 'P' # if self.is_meta: # child_type = 'M' # num = str(self.number) if self.number is not None else 'x' # return str(self.parent) + child_type + num # # def __str__(self): # return '#%s %s' % (self.slug, self.name) # # def is_answered(self): # return bool(self.answer) # # def to_json_value(field): # if isinstance(field, str): # return field # if isinstance(field, int): # return field # if isinstance(field, dict): # return { key: to_json_value(value) for key, value in field.items() } # if isinstance(field, (list, models.query.QuerySet)): # return [to_json_value(item) for item in field] # if isinstance(field, models.manager.Manager): # return [to_json_value(item) for item in field.all()] # if isinstance(field, JSONMixin): # return field.to_json() . Output only the next line.
puzzle = get_object_or_404(Puzzle, pk=puzzle_id)
Predict the next line for this snippet: <|code_start|> @login_required def logout(request): if request.method == "POST": django.contrib.auth.logout(request) return redirect('/') @login_required def index(request): admins = django.contrib.auth.models.User.objects.filter(is_staff=True) context = { 'username': request.user.username, 'rounds': Round.objects.all(), 'channel': 'general_chat', 'admins': admins, } return render(request, 'puzzles/index.html', context) @login_required def get_resources(request): return render(request, 'puzzles/resources.html', {}) @login_required def get_puzzles(request): data = { 'rounds': Round.objects.all() } print("Serializing puzzle data.") <|code_end|> with the help of current file imports: import json import re import django.contrib.auth from django.shortcuts import render, get_object_or_404, redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required from .models import Round, Puzzle, to_json_value and context from other files: # Path: herring/puzzles/models.py # class Round(models.Model,JSONMixin): # # shell model for defining rounds # number = models.IntegerField(default=1) # name = models.CharField(max_length=200) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # def __str__(self): # return 'R' + str(self.number) # # class Meta: # ordering = ['number', 'id'] # class Json: # include_fields = ['id', 'name', 'number', 'puzzle_set', 'hunt_url'] # # class Puzzle(models.Model,JSONMixin): # # class for all puzzles, including metas # parent = models.ForeignKey(Round) # name = models.CharField(max_length=200) # slug = AutoSlugField( # populate_from=puzzle_to_slug, # unique=True, # db_index=True # ) # number = models.IntegerField(**optional) # answer = models.CharField(max_length=200, default='', **optional) # note = models.CharField(max_length=200, default='', **optional) # tags = models.CharField(max_length=200, default='', **optional) # is_meta = models.BooleanField(default=False) # url = models.CharField(max_length=1000, default='', **optional) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # tracker = FieldTracker() # # class Meta: # ordering = ['parent', '-is_meta', 'number', 'id'] # # class Json: # include_fields = ['id', 'name', 'number', 'answer', 'note', 'tags', 'is_meta', 'url', 'hunt_url', 'slug'] # # def identifier(self): # child_type = 'P' # if self.is_meta: # child_type = 'M' # num = str(self.number) if self.number is not None else 'x' # return str(self.parent) + child_type + num # # def __str__(self): # return '#%s %s' % (self.slug, self.name) # # def is_answered(self): # return bool(self.answer) # # def to_json_value(field): # if isinstance(field, str): # return field # if isinstance(field, int): # return field # if isinstance(field, dict): # return { key: to_json_value(value) for key, value in field.items() } # if isinstance(field, (list, models.query.QuerySet)): # return [to_json_value(item) for item in field] # if isinstance(field, models.manager.Manager): # return [to_json_value(item) for item in field.all()] # if isinstance(field, JSONMixin): # return field.to_json() , which may contain function names, class names, or code. Output only the next line.
return JsonResponse(to_json_value(data))
Given the following code snippet before the placeholder: <|code_start|> class PuzzleInline(admin.TabularInline): model = Puzzle extra = 1 exclude = ('answer', 'note', 'tags', 'url') class RoundAdmin(admin.ModelAdmin): inlines = [PuzzleInline] list_display = ('__str__', 'name',) search_fields = ['name'] class PuzzleAdmin(admin.ModelAdmin): exclude = ('answer', 'note', 'tags', 'url') search_fields = ['name'] class UserProfileAdmin(admin.ModelAdmin): pass <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from .models import Round, Puzzle, UserProfile and context including class names, function names, and sometimes code from other files: # Path: herring/puzzles/models.py # class Round(models.Model,JSONMixin): # # shell model for defining rounds # number = models.IntegerField(default=1) # name = models.CharField(max_length=200) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # def __str__(self): # return 'R' + str(self.number) # # class Meta: # ordering = ['number', 'id'] # class Json: # include_fields = ['id', 'name', 'number', 'puzzle_set', 'hunt_url'] # # class Puzzle(models.Model,JSONMixin): # # class for all puzzles, including metas # parent = models.ForeignKey(Round) # name = models.CharField(max_length=200) # slug = AutoSlugField( # populate_from=puzzle_to_slug, # unique=True, # db_index=True # ) # number = models.IntegerField(**optional) # answer = models.CharField(max_length=200, default='', **optional) # note = models.CharField(max_length=200, default='', **optional) # tags = models.CharField(max_length=200, default='', **optional) # is_meta = models.BooleanField(default=False) # url = models.CharField(max_length=1000, default='', **optional) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # tracker = FieldTracker() # # class Meta: # ordering = ['parent', '-is_meta', 'number', 'id'] # # class Json: # include_fields = ['id', 'name', 'number', 'answer', 'note', 'tags', 'is_meta', 'url', 'hunt_url', 'slug'] # # def identifier(self): # child_type = 'P' # if self.is_meta: # child_type = 'M' # num = str(self.number) if self.number is not None else 'x' # return str(self.parent) + child_type + num # # def __str__(self): # return '#%s %s' % (self.slug, self.name) # # def is_answered(self): # return bool(self.answer) # # class UserProfile(models.Model): # user = models.OneToOneField( # settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # related_name='profile', # ) # avatar_url = models.CharField(max_length=200) # # def __str__(self): # return "profile for " + self.user.__str__() . Output only the next line.
admin.site.register(Round, RoundAdmin)
Here is a snippet: <|code_start|> class PuzzleInline(admin.TabularInline): model = Puzzle extra = 1 exclude = ('answer', 'note', 'tags', 'url') class RoundAdmin(admin.ModelAdmin): inlines = [PuzzleInline] list_display = ('__str__', 'name',) search_fields = ['name'] class PuzzleAdmin(admin.ModelAdmin): exclude = ('answer', 'note', 'tags', 'url') search_fields = ['name'] class UserProfileAdmin(admin.ModelAdmin): pass admin.site.register(Round, RoundAdmin) admin.site.register(Puzzle, PuzzleAdmin) <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from .models import Round, Puzzle, UserProfile and context from other files: # Path: herring/puzzles/models.py # class Round(models.Model,JSONMixin): # # shell model for defining rounds # number = models.IntegerField(default=1) # name = models.CharField(max_length=200) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # def __str__(self): # return 'R' + str(self.number) # # class Meta: # ordering = ['number', 'id'] # class Json: # include_fields = ['id', 'name', 'number', 'puzzle_set', 'hunt_url'] # # class Puzzle(models.Model,JSONMixin): # # class for all puzzles, including metas # parent = models.ForeignKey(Round) # name = models.CharField(max_length=200) # slug = AutoSlugField( # populate_from=puzzle_to_slug, # unique=True, # db_index=True # ) # number = models.IntegerField(**optional) # answer = models.CharField(max_length=200, default='', **optional) # note = models.CharField(max_length=200, default='', **optional) # tags = models.CharField(max_length=200, default='', **optional) # is_meta = models.BooleanField(default=False) # url = models.CharField(max_length=1000, default='', **optional) # hunt_url = models.CharField(max_length=1000, default='', **optional) # # tracker = FieldTracker() # # class Meta: # ordering = ['parent', '-is_meta', 'number', 'id'] # # class Json: # include_fields = ['id', 'name', 'number', 'answer', 'note', 'tags', 'is_meta', 'url', 'hunt_url', 'slug'] # # def identifier(self): # child_type = 'P' # if self.is_meta: # child_type = 'M' # num = str(self.number) if self.number is not None else 'x' # return str(self.parent) + child_type + num # # def __str__(self): # return '#%s %s' % (self.slug, self.name) # # def is_answered(self): # return bool(self.answer) # # class UserProfile(models.Model): # user = models.OneToOneField( # settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # related_name='profile', # ) # avatar_url = models.CharField(max_length=200) # # def __str__(self): # return "profile for " + self.user.__str__() , which may include functions, classes, or code. Output only the next line.
admin.site.register(UserProfile, UserProfileAdmin)
Predict the next line after this snippet: <|code_start|> @type word: unicode @return: True if word exists else False @rtype: Boolean """ if not word: return True if word.isdigit(): return True for c in word: if c in string.punctuation: return True # test if the word is previouslly spelled # can get True or False if word in self.worddict: test = self.worddict.get(word, False) else: # if the word is not spelled word = araby.strip_tatweel(word) self.stemmer.segment(word) # extract the affix stem = self.stemmer.get_stem() affix = u"-".join([self.stemmer.get_prefix(), self.stemmer.get_suffix()]) # lookup in the database test = self.database.lookup(word, stem, affix) self.worddict[word] = test return test def known_edits2(self, word): <|code_end|> using the current file's imports: import re import operator import os import sys import string import tashaphyne.stemming import pyarabic.araby as araby from .spelltools import edits1 from . import stem_const from . import spelltools from . import spelldb and any relevant context from other files: # Path: support/yaraspell/spelltools.py # def edits1(word): # splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] # deletes = [a + b[1:] for a, b in splits if b] # transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] # replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] # inserts = [a + c + b for a, b in splits for c in alphabet] # return set(deletes + transposes + replaces + inserts) . Output only the next line.
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if self.lookup(e2))
Here is a snippet: <|code_start|> @pytest.fixture def jasmine_config(): return FakeConfig( src_dir='src', spec_dir='spec', ) def test_defaults(jasmine_config): <|code_end|> . Write the next line using the current file imports: import pytest import urllib from jasmine.url_builder import JasmineUrlBuilder from test.helpers.fake_config import FakeConfig and context from other files: # Path: jasmine/url_builder.py # class JasmineUrlBuilder(object): # # def __init__(self, jasmine_config): # self.jasmine_config = jasmine_config # # def build_url(self, port, seed=None): # netloc = "localhost:{0}".format(port) # query_string = self._build_query_params(seed=seed) # jasmine_url = urllib.parse.urlunparse(('http', netloc, "", "", query_string, "")) # return jasmine_url # # def _build_query_params(self, seed): # query_params = { # "throwFailures": self.jasmine_config.stop_spec_on_expectation_failure(), # "failFast": self.jasmine_config.stop_on_spec_failure(), # "random": self.jasmine_config.random(), # "seed": seed # } # query_params = self._remove_empty_params(query_params) # return urllib.parse.urlencode(query_params) # # def _remove_empty_params(self, query_params): # return dict(((k, str(v).lower()) for k, v in query_params.items() if k == "random" or v)) # # Path: test/helpers/fake_config.py # class FakeConfig(object): # def __init__( # self, # src_dir=None, # spec_dir=None, # stylesheet_urls=None, # script_urls=None, # stop_spec_on_expectation_failure=False, # stop_on_spec_failure=False, # random=True # ): # self._src_dir = src_dir # self._spec_dir = spec_dir # self._stylesheet_urls = stylesheet_urls # self._script_urls = script_urls # self._stop_spec_on_expectation_failure = stop_spec_on_expectation_failure # self._stop_on_spec_failure = stop_on_spec_failure # self._random = random # # self.reload_call_count = 0 # # def src_dir(self): # return self._src_dir # # def spec_dir(self): # return self._spec_dir # # def stylesheet_urls(self): # return self._stylesheet_urls # # def script_urls(self): # return self._script_urls # # def stop_spec_on_expectation_failure(self): # return self._stop_spec_on_expectation_failure # # def stop_on_spec_failure(self): # return self._stop_on_spec_failure # # def random(self): # return self._random # # def reload(self): # self.reload_call_count += 1 , which may include functions, classes, or code. Output only the next line.
url = JasmineUrlBuilder(jasmine_config=jasmine_config).build_url(port=80)
Here is a snippet: <|code_start|> class Parser(object): RESULT_FIELDS = { 'status': 'status', 'fullName': 'full_name', 'failedExpectations': 'failed_expectations', 'deprecationWarnings': 'deprecation_warnings', 'id': 'runnable_id', 'description': 'description', 'pendingReason': 'pending_reason' } def parse(self, items): <|code_end|> . Write the next line using the current file imports: from jasmine.result_list import ResultList and context from other files: # Path: jasmine/result_list.py # class ResultList(list): # # def add_result(self, result): # self.append(Result(**result)) # # def passed(self): # return self._filter_status('passed') # # def failed(self): # return self._filter_status('failed') # # def pending(self): # return self._filter_status('pending') # # def enabled(self): # return [result for result in self if result.status != 'disabled'] # # def _filter_status(self, status): # return [result for result in self if result.status == status] # # def __add__(self, other): # return ResultList(list.__add__(self, other)) , which may include functions, classes, or code. Output only the next line.
result_list = ResultList()
Given the following code snippet before the placeholder: <|code_start|> # fix py26 relpath from root bug http://bugs.python.org/issue5117 return [ relpath[3:] if relpath.startswith("../") else relpath for relpath in relpaths ] def _make_absolute(self, path, relative_to): return ( path if path.startswith('http') else os.path.abspath( os.path.join(self.project_path, relative_to, path) ) ) def _expland_globs(self, path): return ( [path] if path.startswith('http') else self._glob_paths([path]) ) def _make_relative(self, path, relative_to): return ( path if path.startswith('http') else os.path.relpath(path, relative_to) ) def _glob_paths(self, paths): files = [] for src_glob in paths: <|code_end|> , predict the next line using imports from the current file: import os from yaml import load, Loader from jasmine_core import Core from jasmine.utils import iglob and context including class names, function names, and sometimes code from other files: # Path: jasmine/utils.py # def iglob(path_glob): # """Extended globbing function that supports ** and {opt1,opt2,opt3}.""" # if _CHECK_RECURSIVE_GLOB.search(path_glob): # msg = """invalid glob %r: recursive glob "**" must be used alone""" # raise ValueError(msg % path_glob) # if _CHECK_MISMATCH_SET.search(path_glob): # msg = """invalid glob %r: mismatching set marker '{' or '}'""" # raise ValueError(msg % path_glob) # return _iglob(path_glob) . Output only the next line.
files.extend([os.path.abspath(x) for x in iglob(src_glob)])
Given snippet: <|code_start|> "vendor/test.js": '', "vendor/pants.coffee": '', "vendor_spec/pantsSpec.js": '', "main.css": '', } for k in files: parent = os.path.dirname(k) if parent and not os.path.exists(parent): os.makedirs(parent) with open(k, 'w') as f: f.write(files[k]) @contextmanager def pushd(dest): src = os.getcwd() os.chdir(dest) try: yield finally: os.chdir(src) @contextmanager def in_temp_dir(): with tempfile.TemporaryDirectory() as root: with pushd(root): yield def test_src_files(): with in_temp_dir(): create_files() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import tempfile import pkg_resources from contextlib import contextmanager from jasmine.config import Config and context: # Path: jasmine/config.py # class Config(object): # def __init__(self, yaml_file, project_path=None): # self.yaml_file = yaml_file # self.project_path = project_path or os.getcwd() # self._load() # # def script_urls(self): # core_js_files = Core.js_files() # if 'node_boot.js' in core_js_files: # core_js_files.remove('node_boot.js') # return [ # "/__jasmine__/{0}".format(core_js) for core_js in core_js_files # ] + [ # self._prefix_src_underscored(src_file) for src_file in self.src_files() # ] + [ # "/__spec__/{0}".format(helper) for helper in self.helpers() # ] + [ # "/__spec__/{0}".format(spec_file) for spec_file in self.spec_files() # ] # # def stylesheet_urls(self): # return [ # "/__jasmine__/{0}".format(core_css) for core_css in Core.css_files() # ] + [ # "/__src__/{0}".format(css_file) for css_file in self.stylesheets() # ] # # def reload(self): # self._load() # # def src_files(self): # return self._glob_filelist('src_files', self.src_dir()) # # def stylesheets(self): # return self._glob_filelist('stylesheets', self.src_dir()) # # def helpers(self): # default_helpers = os.path.join(self.project_path, self.spec_dir(), # 'helpers/**/*.js') # # return self._glob_filelist('helpers', self.spec_dir(), # default=[default_helpers]) # # def spec_files(self): # default_spec = os.path.join(self.project_path, self.spec_dir(), # "**/*[sS]pec.js") # # return self._glob_filelist('spec_files', self.spec_dir(), # default=[default_spec]) # # def src_dir(self): # return self._yaml.get("src_dir") or self.project_path # # def spec_dir(self): # return self._yaml.get("spec_dir") or 'spec/javascripts' # # def stop_spec_on_expectation_failure(self): # return self._yaml.get("stop_spec_on_expectation_failure") is True # # def stop_on_spec_failure(self): # return self._yaml.get("stop_on_spec_failure") is True # # def random(self): # return self._yaml.get("random", True) is not False # # def _prefix_src_underscored(self, path): # return ( # path if path.startswith('http') else "/__src__/{0}".format(path) # ) # # def _uniq(self, items, idfun=None): # # order preserving # # if idfun is None: # def idfun(x): # return x # seen = {} # result = [] # for item in items: # marker = idfun(item) # # in old Python versions: # # if seen.has_key(marker) # # but in new ones: # if marker in seen: # continue # # seen[marker] = 1 # result.append(item) # return result # # def _glob_filelist(self, filelist, relative_to, default=None): # default = default or [] # paths = self._yaml.get(filelist) or default # # paths = [self._make_absolute(path, relative_to) for path in paths] # paths = [self._expland_globs(path) for path in paths] # paths = sum(paths, []) # relpaths = [self._make_relative(path, relative_to) for path in paths] # # # fix py26 relpath from root bug http://bugs.python.org/issue5117 # return [ # relpath[3:] if relpath.startswith("../") else relpath # for relpath in relpaths # ] # # def _make_absolute(self, path, relative_to): # return ( # path if path.startswith('http') # else os.path.abspath( # os.path.join(self.project_path, relative_to, path) # ) # ) # # def _expland_globs(self, path): # return ( # [path] if path.startswith('http') # else self._glob_paths([path]) # ) # # def _make_relative(self, path, relative_to): # return ( # path if path.startswith('http') # else os.path.relpath(path, relative_to) # ) # # def _glob_paths(self, paths): # files = [] # # for src_glob in paths: # files.extend([os.path.abspath(x) for x in iglob(src_glob)]) # # return list(self._uniq(files)) # # def _extract_urls(self, filelist): # local_files = [x for x in filelist if 'http' not in x] # urls = [x for x in filelist if 'http' in x] # # return local_files, urls # # def _load(self): # with open(self.yaml_file, 'rU') as f: # self._yaml = load(f, Loader=Loader) or {} which might include code, classes, or functions. Output only the next line.
config = Config("jasmine.yml")
Given snippet: <|code_start|> def test_result(): status = 'status' full_name = 'fullName' failed_expectations = 'failedExpectations' runnable_id = 'id' description = 'description' pending_reason = 'pendingReason' deprecation_warnings = 'deprecationWarnings' <|code_end|> , continue by predicting the next line. Consider current file imports: from jasmine.result import Result and context: # Path: jasmine/result.py # class Result(): # def __init__( # self, # status=None, # full_name=None, # failed_expectations=None, # deprecation_warnings=None, # runnable_id=None, # description=None, # pending_reason=None # ): # if failed_expectations is None: # failed_expectations = {} # # self._status = status # self._full_name = full_name # self._failed_expectations = failed_expectations # self._deprecation_warnings = deprecation_warnings # self._runnable_id = runnable_id # self._description = description # self._pending_reason = pending_reason # # @property # def status(self): # return self._status # # @property # def full_name(self): # return self._full_name # # @property # def failed_expectations(self): # return self._failed_expectations # # @property # def deprecation_warnings(self): # return self._deprecation_warnings # # @property # def runnable_id(self): # return self._runnable_id # # @property # def description(self): # return self._description # # @property # def pending_reason(self): # return self._pending_reason which might include code, classes, or functions. Output only the next line.
result = Result(
Given the code snippet: <|code_start|> help_text=_("Custom attribute"), default="", blank=True, ) name = models.CharField( _("name"), max_length=200, help_text=_("Meta attribute name"), ) value = models.CharField( _("value"), max_length=2000, help_text=_("Meta attribute value"), ) class Meta: verbose_name = _("Page meta info (language-dependent)") verbose_name_plural = _("Page meta info (language-dependent)") def __str__(self): if self.page: return _("Attribute {0} for {1}").format(self.name, self.page) if self.title: return _("Attribute {0} for {1}").format(self.name, self.title) # Cache cleanup when deleting pages / editing page extensions @receiver(pre_delete, sender=Page) def cleanup_page(sender, instance, **kwargs): for language in instance.get_languages(): <|code_end|> , generate the next line using the imports in this file: from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from cms.models import Page, Title from django.conf import settings from django.core.cache import cache from django.db import models from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from filer.fields.file import FilerFileField from meta import settings as meta_settings from .utils import get_cache_key, get_metatags from aldryn_snake.template_api import registry and context (functions, classes, or occasionally code) from other files: # Path: djangocms_page_meta/utils.py # def get_cache_key(page, language): # """ # Create the cache key for the current page and language # """ # from cms.cache import _get_cache_key # # try: # site_id = page.node.site_id # except AttributeError: # CMS_3_4 # site_id = page.site_id # return _get_cache_key("page_meta", page, language, site_id) # # def get_metatags(request): # language = get_language_from_request(request, check_path=True) # meta = get_page_meta(request.current_page, language) # return mark_safe( # render_to_string(request=request, template_name="djangocms_page_meta/meta.html", context={"meta": meta}) # ) . Output only the next line.
key = get_cache_key(instance, language)
Given snippet: <|code_start|># Cache cleanup when deleting pages / editing page extensions @receiver(pre_delete, sender=Page) def cleanup_page(sender, instance, **kwargs): for language in instance.get_languages(): key = get_cache_key(instance, language) cache.delete(key) @receiver(pre_delete, sender=Title) def cleanup_title(sender, instance, **kwargs): key = get_cache_key(instance.page, instance.language) cache.delete(key) @receiver(post_save, sender=PageMeta) @receiver(pre_delete, sender=PageMeta) def cleanup_pagemeta(sender, instance, **kwargs): for language in instance.extended_object.get_languages(): key = get_cache_key(instance.extended_object, language) cache.delete(key) @receiver(post_save, sender=TitleMeta) @receiver(pre_delete, sender=TitleMeta) def cleanup_titlemeta(sender, instance, **kwargs): key = get_cache_key(instance.extended_object.page, instance.extended_object.language) cache.delete(key) if registry: <|code_end|> , continue by predicting the next line. Consider current file imports: from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from cms.models import Page, Title from django.conf import settings from django.core.cache import cache from django.db import models from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.utils.translation import ugettext_lazy as _ from filer.fields.file import FilerFileField from meta import settings as meta_settings from .utils import get_cache_key, get_metatags from aldryn_snake.template_api import registry and context: # Path: djangocms_page_meta/utils.py # def get_cache_key(page, language): # """ # Create the cache key for the current page and language # """ # from cms.cache import _get_cache_key # # try: # site_id = page.node.site_id # except AttributeError: # CMS_3_4 # site_id = page.site_id # return _get_cache_key("page_meta", page, language, site_id) # # def get_metatags(request): # language = get_language_from_request(request, check_path=True) # meta = get_page_meta(request.current_page, language) # return mark_safe( # render_to_string(request=request, template_name="djangocms_page_meta/meta.html", context={"meta": meta}) # ) which might include code, classes, or functions. Output only the next line.
registry.add_to_head(get_metatags)
Using the snippet: <|code_start|> class TestRunner(unittest.TestCase): def setUp(self): self.file = tempfile.NamedTemporaryFile() def tearDown(self): self.file.close() def _default_options( self, tagged=False, ner=False, parsed=False, lemmatized=False ): options = MagicMock() options.tagged = tagged options.tagging_model = self.file.name options.ud_tagging_model = self.file.name options.ner = ner options.ner_model = self.file.name options.parsed = parsed options.parsing_model = self.file.name options.lemmatized = lemmatized options.lemmatization_model = self.file.name return options @patch("swe_pipeline.cleanup") @patch("swe_pipeline.tempfile") @patch("swe_pipeline.process_file") def test_empty_options(self, process_file_mock, *args): options = self._default_options() <|code_end|> , determine the next line of code. You have imports: from swe_pipeline import run_pipeline from unittest.mock import patch, MagicMock import tempfile import unittest and context (class names, function names, or code) available: # Path: swe_pipeline.py # def run_pipeline(options, args): # models = { # "suc_ne_tagger": None, # "suc_tagger": None, # "ud_tagger": None, # "lemmatizer": None, # } # if options.tagged or options.ner or options.parsed: # models["suc_tagger"] = SucTagger(options.tagging_model) # # if options.lemmatized: # models["ud_tagger"] = UDTagger(options.ud_tagging_model) # # if options.ner: # models["suc_ne_tagger"] = SucNETagger(options.ner_model) # # # Set up the working directory # tmp_dir = tempfile.mkdtemp("-stb-pipeline") # if options.parsed: # shutil.copy( # os.path.join(SCRIPT_DIR, options.parsing_model + ".mco"), # tmp_dir # ) # # if options.lemmatized: # models["lemmatizer"] = SUCLemmatizer() # models["lemmatizer"].load(options.lemmatization_model) # # # Process each input file # for filename in args: # process_file( # options, # filename, # tmp_dir, # models, # (True if options.non_capitalized else None) # ) # # cleanup(options, tmp_dir) . Output only the next line.
run_pipeline(options, [])
Given the following code snippet before the placeholder: <|code_start|> class TestUtils(unittest.TestCase): def test_write_to_file(self): file = MagicMock() <|code_end|> , predict the next line using imports from the current file: import os import sys import unittest from swe_pipeline import write_to_file, write_to_output, cleanup, output_filename from textwrap import dedent from unittest.mock import call, patch, MagicMock, mock_open and context including class names, function names, and sometimes code from other files: # Path: swe_pipeline.py # def write_to_file(file, lines): # for line in lines: # print(line, file=file) # print(file=file) # # def write_to_output(filename_mapping): # for should_copy, filename, output_dir in filename_mapping: # if should_copy: # shutil.copy(filename, output_dir) # # def cleanup(options, tmp_dir): # if not options.no_delete: # shutil.rmtree(tmp_dir) # else: # print("Leaving working directory as is: %s" % tmp_dir, file=sys.stderr) # # def output_filename(tmp_dir, filename, suffix): # directory, _ = os.path.splitext(filename) # basename = os.path.basename(directory) # return os.path.join(tmp_dir, "%s.%s" % (basename, suffix)) . Output only the next line.
write_to_file(file, ["first line", "second line"])
Using the snippet: <|code_start|> class TestUtils(unittest.TestCase): def test_write_to_file(self): file = MagicMock() write_to_file(file, ["first line", "second line"]) data = "".join([call[0][0] for call in file.write.call_args_list]) self.assertEqual(data, dedent(""" first line second line """).lstrip()) @patch("swe_pipeline.shutil") def test_write_to_output(self, shutil_mock): <|code_end|> , determine the next line of code. You have imports: import os import sys import unittest from swe_pipeline import write_to_file, write_to_output, cleanup, output_filename from textwrap import dedent from unittest.mock import call, patch, MagicMock, mock_open and context (class names, function names, or code) available: # Path: swe_pipeline.py # def write_to_file(file, lines): # for line in lines: # print(line, file=file) # print(file=file) # # def write_to_output(filename_mapping): # for should_copy, filename, output_dir in filename_mapping: # if should_copy: # shutil.copy(filename, output_dir) # # def cleanup(options, tmp_dir): # if not options.no_delete: # shutil.rmtree(tmp_dir) # else: # print("Leaving working directory as is: %s" % tmp_dir, file=sys.stderr) # # def output_filename(tmp_dir, filename, suffix): # directory, _ = os.path.splitext(filename) # basename = os.path.basename(directory) # return os.path.join(tmp_dir, "%s.%s" % (basename, suffix)) . Output only the next line.
write_to_output([
Based on the snippet: <|code_start|> class TestUtils(unittest.TestCase): def test_write_to_file(self): file = MagicMock() write_to_file(file, ["first line", "second line"]) data = "".join([call[0][0] for call in file.write.call_args_list]) self.assertEqual(data, dedent(""" first line second line """).lstrip()) @patch("swe_pipeline.shutil") def test_write_to_output(self, shutil_mock): write_to_output([ (True, "file1", "/tmp1"), (False, "file2", "/tmp2"), (True, "file3", "/tmp3"), ]) self.assertEqual( shutil_mock.copy.call_args_list, [call('file1', '/tmp1'), call('file3', '/tmp3')] ) @patch("swe_pipeline.shutil") def test_cleanup_delete(self, shutil_mock): options = MagicMock() options.no_delete = False <|code_end|> , predict the immediate next line with the help of imports: import os import sys import unittest from swe_pipeline import write_to_file, write_to_output, cleanup, output_filename from textwrap import dedent from unittest.mock import call, patch, MagicMock, mock_open and context (classes, functions, sometimes code) from other files: # Path: swe_pipeline.py # def write_to_file(file, lines): # for line in lines: # print(line, file=file) # print(file=file) # # def write_to_output(filename_mapping): # for should_copy, filename, output_dir in filename_mapping: # if should_copy: # shutil.copy(filename, output_dir) # # def cleanup(options, tmp_dir): # if not options.no_delete: # shutil.rmtree(tmp_dir) # else: # print("Leaving working directory as is: %s" % tmp_dir, file=sys.stderr) # # def output_filename(tmp_dir, filename, suffix): # directory, _ = os.path.splitext(filename) # basename = os.path.basename(directory) # return os.path.join(tmp_dir, "%s.%s" % (basename, suffix)) . Output only the next line.
cleanup(options, "/tmp")
Using the snippet: <|code_start|> (True, "file1", "/tmp1"), (False, "file2", "/tmp2"), (True, "file3", "/tmp3"), ]) self.assertEqual( shutil_mock.copy.call_args_list, [call('file1', '/tmp1'), call('file3', '/tmp3')] ) @patch("swe_pipeline.shutil") def test_cleanup_delete(self, shutil_mock): options = MagicMock() options.no_delete = False cleanup(options, "/tmp") self.assertEqual( shutil_mock.rmtree.call_args_list, [call('/tmp')] ) @patch("swe_pipeline.shutil") def test_cleanup_without_delete(self, shutil_mock): options = MagicMock() options.no_delete = True with open(os.devnull, 'w') as sys.stderr: cleanup(options, "/tmp") self.assertEqual(shutil_mock.rmtree.call_args_list, []) def test_output_filename(self): self.assertEqual( <|code_end|> , determine the next line of code. You have imports: import os import sys import unittest from swe_pipeline import write_to_file, write_to_output, cleanup, output_filename from textwrap import dedent from unittest.mock import call, patch, MagicMock, mock_open and context (class names, function names, or code) available: # Path: swe_pipeline.py # def write_to_file(file, lines): # for line in lines: # print(line, file=file) # print(file=file) # # def write_to_output(filename_mapping): # for should_copy, filename, output_dir in filename_mapping: # if should_copy: # shutil.copy(filename, output_dir) # # def cleanup(options, tmp_dir): # if not options.no_delete: # shutil.rmtree(tmp_dir) # else: # print("Leaving working directory as is: %s" % tmp_dir, file=sys.stderr) # # def output_filename(tmp_dir, filename, suffix): # directory, _ = os.path.splitext(filename) # basename = os.path.basename(directory) # return os.path.join(tmp_dir, "%s.%s" % (basename, suffix)) . Output only the next line.
output_filename("/tmp", "file", "txt"),
Using the snippet: <|code_start|> options.tagged = tagged options.ner = ner options.parsed = parsed options.lemmatized = lemmatized options.skip_tokenization = skip_tokenization return options def _default_models( self, suc_ne_tagger=None, suc_tagger=None, ud_tagger=None, lemmatizer=None ): return { "suc_ne_tagger": suc_ne_tagger, "suc_tagger": suc_tagger, "ud_tagger": ud_tagger, "lemmatizer": lemmatizer, } @patch("swe_pipeline.build_sentences") def test_tagging(self, build_sentences_mock): options = self._default_options(tagged=True) sentence = ["Hej", "mitt", "namn", "är"] tags = ["IN", "PS|NEU|SIN|DEF", "NN|NEU|SIN|IND|NOM", "VB|PRS|AKT"] tagger = MagicMock() tagger.tag.return_value = tags models = self._default_models(suc_tagger=tagger) self.assertEqual( <|code_end|> , determine the next line of code. You have imports: from swe_pipeline import run_tagging_and_lemmatization from unittest.mock import patch, MagicMock import unittest and context (class names, function names, or code) available: # Path: swe_pipeline.py # def run_tagging_and_lemmatization(options, sentence, models): # lemmas = [] # ud_tags_list = [] # suc_tags_list = models["suc_tagger"].tag(sentence) # suc_ne_list = [] # # if options.lemmatized: # lemmas = [ # models["lemmatizer"].predict(token, tag) # for token, tag in zip(sentence, suc_tags_list) # ] # ud_tags_list = models["ud_tagger"].tag(sentence, lemmas, suc_tags_list) # # if options.ner: # suc_ne_list = models["suc_ne_tagger"].tag( # list(zip(sentence, lemmas, suc_tags_list)) # ) # # return lemmas, ud_tags_list, suc_tags_list, suc_ne_list . Output only the next line.
run_tagging_and_lemmatization(options, sentence, models),
Continue the code snippet: <|code_start|> options.tagged = tagged options.ner = ner options.parsed = parsed options.lemmatized = lemmatized return options def _default_models( self, suc_ne_tagger=None, suc_tagger=None, ud_tagger=None, lemmatizer=None ): return { "suc_ne_tagger": suc_ne_tagger, "suc_tagger": suc_tagger, "ud_tagger": ud_tagger, "lemmatizer": lemmatizer, } @patch("swe_pipeline.write_to_output") @patch("swe_pipeline.open", mock_open(), create=True) @patch("swe_pipeline.parse") @patch("swe_pipeline.run_tagging_and_lemmatization") @patch("swe_pipeline.run_tokenization") def test_empty_options( self, run_tokenization_mock, run_tagging_mock, parse_mock, open_mock, *args ): options = self._default_options() models = self._default_models() with open(os.devnull, 'w') as sys.stderr: <|code_end|> . Use current file imports: import os import sys import unittest from swe_pipeline import process_file from textwrap import dedent from unittest.mock import patch, MagicMock, mock_open and context (classes, functions, or code) from other files: # Path: swe_pipeline.py # def process_file(options, filename, tmp_dir, models, non_capitalized=None): # print("Processing %s..." % filename, file=sys.stderr) # # tokenized_filename = output_filename(tmp_dir, filename, "tok") # tagged_filename = output_filename(tmp_dir, filename, "tag") # ner_filename = output_filename(tmp_dir, filename, "ne") # # sentences = run_tokenization(options, filename, # non_capitalized=non_capitalized) # annotated_sentences = [] # # with open(tokenized_filename, "w", encoding="utf-8") as tokenized, \ # open(tagged_filename, "w", encoding="utf-8") as tagged, \ # open(ner_filename, "w", encoding="utf-8") as ner: # # # Run only one pass over sentences for writing to both files # for sentence in sentences: # write_to_file(tokenized, sentence) # # if options.tagged or options.parsed or options.ner: # lemmas, ud_tags_list, suc_tags_list, suc_ne_list = \ # run_tagging_and_lemmatization(options, sentence, models) # # annotated_sentences.append( # zip(sentence, lemmas, ud_tags_list, suc_tags_list) # ) # # ud_tag_list = [ # ud_tags[:ud_tags.find("|")] # for ud_tags in ud_tags_list # ] # # if lemmas and ud_tags_list: # line_tokens = sentence, suc_tags_list, ud_tag_list, lemmas # else: # line_tokens = sentence, suc_tags_list # # lines = ["\t".join(line) for line in zip(*line_tokens)] # # write_to_file(tagged, lines) # # if options.ner: # ner_lines = [ # "\t".join(line) # for line in zip(sentence, suc_ne_list) # ] # # write_to_file(ner, ner_lines) # # parsed_filename = "" # if options.parsed: # parsed_filename = parse( # options, filename, annotated_sentences, tmp_dir # ) # # write_to_output([ # (options.tokenized, tokenized_filename, options.output_dir), # (options.tagged, tagged_filename, options.output_dir), # (options.parsed, parsed_filename, options.output_dir), # (options.ner, ner_filename, options.output_dir), # ]) # # print("done.", file=sys.stderr) . Output only the next line.
process_file(options, "file.txt", "", models)
Using the snippet: <|code_start|> class TestParse(unittest.TestCase): def _default_options(self): options = MagicMock() options.malt = "/dummy/maltparser.jar" options.parsing_model = "/dummy/maltmodel.mco" return options @patch("swe_pipeline.tagged_to_tagged_conll") @patch("swe_pipeline.Popen") def test_run_parser(self, popen_mock, *args): options = self._default_options() popen_mock().wait.return_value = 0 data = [zip( ["Hej", "mitt", "namn", "är"], ["hej", "min", "namn", "vara"], [ "INTJ|_", "DET|Definite=Def|Gender=Neut|Number=Sing|Poss=Yes", "NOUN|Case=Nom|Definite=Ind|Gender=Neut|Number=Sing", "AUX|Mood=Ind|Tense=Pres|VerbForm=Fin|Voice=Act", ], ["IN", "PS|NEU|SIN|DEF", "NN|NEU|SIN|IND|NOM", "VB|PRS|AKT"], )] open_mock = mock_open() with patch("swe_pipeline.open", open_mock, create=True): self.assertEqual( <|code_end|> , determine the next line of code. You have imports: from swe_pipeline import parse from unittest.mock import patch, MagicMock, mock_open import unittest and context (class names, function names, or code) available: # Path: swe_pipeline.py # def parse(options, filename, annotated_sentences, tmp_dir): # tagged_conll_filename = output_filename(tmp_dir, filename, "tag.conll") # parsed_filename = output_filename(tmp_dir, filename, "conll") # log_filename = output_filename(tmp_dir, filename, "log") # # # The parser command line is dependent on the input and # # output files, so we build that one for each data file # parser_cmdline = [ # "java", # "-Xmx2000m", # "-jar", os.path.expanduser(options.malt), # "-m", "parse", # "-i", tagged_conll_filename, # "-o", parsed_filename, # "-w", tmp_dir, # "-c", os.path.basename(options.parsing_model) # ] # # # Conversion from .tag file to tagged.conll (input format for the parser) # tagged_conll_file = open(tagged_conll_filename, "w", encoding="utf-8") # tagged_to_tagged_conll(annotated_sentences, tagged_conll_file) # tagged_conll_file.close() # # # Run the parser # with open(log_filename, "w", encoding="utf-8") as log_file: # returncode = Popen( # parser_cmdline, stdout=log_file, stderr=log_file # ).wait() # # if returncode: # sys.exit("Parsing failed! See log file: %s" % log_filename) # # return parsed_filename . Output only the next line.
parse(options, "file.txt", data, "/tmp"),
Next line prediction: <|code_start|> for idx, hash_name in enumerate(pi_hashes): f.write(' pi_hashes[%d] = %s;\n' % (idx, hash_name)) f.write(''' field_buf += n_fields; field_len += n_fields; pi_hashes += %d; } return 0; } #define N_INVARIANTS %d #define N_FEATURES %d ''' % (len(pi_hashes), len(pi_hashes), len(self.terms))) f.write(''' static void extract_features( const label *history, label tag, size_t i, size_t n_items, const partial_hash_t *pi_hashes, feat_hash_t *feature_hashes) { ''') pi_hashes_idx = { s: i for i, s in enumerate(pi_hashes) } for idx,cons in enumerate(self.terms): form_cons = [con for con in cons if isinstance(con, Form)] <|code_end|> . Use current file imports: (import sys import hashlib, math from collections import defaultdict from tagset import Tag) and context including class names, function names, or small code snippets from other files: # Path: tagset.py # class Tag: # def __init__(self, field, position, tagset): # self.field = field # self.position = position # self.tagset = tagset # tagset.tag_fields.add(field) # # def c_value(self): # if self.position == 0: # return 'tag' # else: # return '((i>=%d)? history[i-%d] : %s)' % ( # -self.position, -self.position, self.tagset.c_n_tags) . Output only the next line.
tag_cons = [con for con in cons if isinstance(con, Tag)]
Given snippet: <|code_start|> class WCLexicon: def __init__(self, name, items, config): config.wclexicons.append(self) self.items = items self.lower = False self.name = name self.config = config self.c_size = '%s_size' % name self.c_table = name def make_table(self): n_items = len(self.items) size = 1 << (ceil(log2(n_items) + 0.5)) table = [None] * size if self.lower: <|code_end|> , continue by predicting the next line. Consider current file imports: from math import ceil, log2 from taglexicon import hash32trans, hash64trans from fasthash import hash32, hash64 from form import Lookup and context: # Path: taglexicon.py # def hash32trans(s): # return fasthash.hashlongs32(tuple(ord(c) for c in s)) # # def hash64trans(s): # return fasthash.hashlongs64(tuple(ord(c) for c in s)) # # Path: form.py # class Lookup(Form): # def __init__(self, parent, wclexicon): # self.parent = parent # self.wclexicon = wclexicon # # def get_wclexicon(self): # return self.wclexicon which might include code, classes, or functions. Output only the next line.
fun = (lambda s: hash32trans(s.lower())) \
Next line prediction: <|code_start|> class WCLexicon: def __init__(self, name, items, config): config.wclexicons.append(self) self.items = items self.lower = False self.name = name self.config = config self.c_size = '%s_size' % name self.c_table = name def make_table(self): n_items = len(self.items) size = 1 << (ceil(log2(n_items) + 0.5)) table = [None] * size if self.lower: fun = (lambda s: hash32trans(s.lower())) \ if self.config.lexicon_hash_bits == 32 \ <|code_end|> . Use current file imports: (from math import ceil, log2 from taglexicon import hash32trans, hash64trans from fasthash import hash32, hash64 from form import Lookup) and context including class names, function names, or small code snippets from other files: # Path: taglexicon.py # def hash32trans(s): # return fasthash.hashlongs32(tuple(ord(c) for c in s)) # # def hash64trans(s): # return fasthash.hashlongs64(tuple(ord(c) for c in s)) # # Path: form.py # class Lookup(Form): # def __init__(self, parent, wclexicon): # self.parent = parent # self.wclexicon = wclexicon # # def get_wclexicon(self): # return self.wclexicon . Output only the next line.
else (lambda s: hash64trans(s.lower()))
Here is a snippet: <|code_start|> self.config = config self.c_size = '%s_size' % name self.c_table = name def make_table(self): n_items = len(self.items) size = 1 << (ceil(log2(n_items) + 0.5)) table = [None] * size if self.lower: fun = (lambda s: hash32trans(s.lower())) \ if self.config.lexicon_hash_bits == 32 \ else (lambda s: hash64trans(s.lower())) else: fun = (lambda s: hash32(1, s.encode('utf-8'))) \ if self.config.lexicon_hash_bits == 32 \ else (lambda s: hash64(1, s.encode('utf-8'))) for key, value in self.items: key_hash = fun(key) i = key_hash % size while not table[i] is None: if table[i][0] == key_hash: break i = (i + 1) % size if table[i] is None: table[i] = (key_hash, value+1) return table def lookup(self, form): if 'normalize' in form.get_translations(): self.lower = True <|code_end|> . Write the next line using the current file imports: from math import ceil, log2 from taglexicon import hash32trans, hash64trans from fasthash import hash32, hash64 from form import Lookup and context from other files: # Path: taglexicon.py # def hash32trans(s): # return fasthash.hashlongs32(tuple(ord(c) for c in s)) # # def hash64trans(s): # return fasthash.hashlongs64(tuple(ord(c) for c in s)) # # Path: form.py # class Lookup(Form): # def __init__(self, parent, wclexicon): # self.parent = parent # self.wclexicon = wclexicon # # def get_wclexicon(self): # return self.wclexicon , which may include functions, classes, or code. Output only the next line.
return Lookup(form, self)
Using the snippet: <|code_start|> class TestRunTokenization(unittest.TestCase): def _default_options( self, tagged=False, ner=False, parsed=False, lemmatized=False, skip_tokenization=False ): options = MagicMock() options.tagged = tagged options.ner = ner options.parsed = parsed options.lemmatized = lemmatized options.skip_tokenization = skip_tokenization return options @patch("swe_pipeline.build_sentences") def test_empty_options(self, build_sentences_mock): options = self._default_options() build_sentences_mock.return_value = [] open_mock = mock_open() with patch("swe_pipeline.open", open_mock, create=True): <|code_end|> , determine the next line of code. You have imports: from swe_pipeline import run_tokenization from textwrap import dedent from unittest.mock import patch, MagicMock, mock_open import unittest and context (class names, function names, or code) available: # Path: swe_pipeline.py # def run_tokenization(options, filename, non_capitalized=None): # with (gzip.open(filename, "rt", encoding="utf-8") # if filename.endswith(".gz") # else open(filename, "r", encoding="utf-8")) as input_file: # data = input_file.read() # # if options.skip_tokenization: # sentences = [ # sentence.split('\n') # for sentence in data.split('\n\n') # if sentence.strip() # ] # elif options.skip_segmentation: # sentences = [ # build_sentences(line, segment=False) # for line in data.split('\n') # if line.strip() # ] # else: # if non_capitalized is None: # n_capitalized = len(re.findall(r'[\.!?] +[A-ZÅÄÖ]', data)) # n_non_capitalized = len(re.findall(r'[\.!?] +[a-zåäö]', data)) # non_capitalized = n_non_capitalized > 5*n_capitalized # sentences = build_sentences(data, non_capitalized=non_capitalized) # # sentences = list(filter(bool, # [[token for token in sentence if len(token) <= MAX_TOKEN] # for sentence in sentences])) # return sentences . Output only the next line.
self.assertEqual(run_tokenization(options, "file.txt"), [])
Given the following code snippet before the placeholder: <|code_start|> class CardForm(forms.Form): name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False) value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560) long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False) active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True) class FeedForm(forms.Form): <|code_end|> , predict the next line using imports from the current file: from django import forms from app.models import Player and context including class names, function names, and sometimes code from other files: # Path: app/models.py # class Player(models.Model): # id = models.AutoField(primary_key=True) # user = models.OneToOneField(User, verbose_name="User", help_text="The user of this player.") # team = models.ForeignKey(Team, # verbose_name="Team", # help_text="The team this player belongs to.", # related_name="player") # # @property # def points_acquired(self): # s = self.captured_card.filter(active=True).aggregate(models.Sum('value')) # if s['value__sum'] is None: # return 0 # return s['value__sum'] # # def __str__(self): # return (str(self.user.get_full_name()) + " (" + # str(self.user.get_username()) + "), " + self.team.name) . Output only the next line.
player = forms.ModelChoiceField(Player.objects.all(), label="玩家")
Predict the next line for this snippet: <|code_start|> class FastSendForm(forms.Form): message = forms.CharField(max_length=255, label="訊息", help_text="悄悄話", required=False) point = forms.IntegerField(label="價值", help_text="點數卡的價值", initial=1) <|code_end|> with the help of current file imports: from django import forms from app.models import Player and context from other files: # Path: app/models.py # class Player(models.Model): # id = models.AutoField(primary_key=True) # user = models.OneToOneField(User, verbose_name="User", help_text="The user of this player.") # team = models.ForeignKey(Team, # verbose_name="Team", # help_text="The team this player belongs to.", # related_name="player") # # @property # def points_acquired(self): # s = self.captured_card.filter(active=True).aggregate(models.Sum('value')) # if s['value__sum'] is None: # return 0 # return s['value__sum'] # # def __str__(self): # return (str(self.user.get_full_name()) + " (" + # str(self.user.get_username()) + "), " + self.team.name) , which may contain function names, class names, or code. Output only the next line.
player = forms.ModelChoiceField(Player.objects.all(), label="玩家")
Using the snippet: <|code_start|>@login_required def card(request, id=None): if request.user.is_authenticated(): try: card = Card.objects.get(cid=id) except ObjectDoesNotExist: return CardNotFound(request) if not card.retrieved and not request.user.has_perm('app.read_card'): return render( request, "submit.html", { "success": False, "content": "尚未被領取的卡片,我才不會告訴你內容呢", "title": "未開封的卡片"}, status=404) else: retriever = card.capturer host = request.META['HTTP_HOST'] allow_edit = request.user.has_perm('app.change_card') allow_feed = request.user.has_perm('app.feed_card') return render(request, "card/card.html", locals()) @login_required def edit(request, id=None): if request.user.has_perm('app.change_card'): try: card = Card.objects.get(cid=id) except ObjectDoesNotExist: return CardNotFound(request) if not request.POST: <|code_end|> , determine the next line of code. You have imports: from app.card.forms import CardForm, FeedForm from app.models import Card, History from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.db import transaction and context (class names, function names, or code) available: # Path: app/card/forms.py # class CardForm(forms.Form): # name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False) # value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560) # long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False) # active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True) # # class FeedForm(forms.Form): # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) . Output only the next line.
form = CardForm(
Using the snippet: <|code_start|> "next_page": reverse('view card', args=[card.cid]), }) else: return render(request, "submit.html", { "success": False, "title": "產生卡片失敗", "content": "要不要去戳戳系統管理員呢?" "(如果是POST奇怪的資料,可能會收到彈力繩喔ˊ_>ˋ)" }) else: raise PermissionDenied @login_required def feed(request, id=None): if request.user.has_perm('app.feed_card'): try: card = Card.objects.get(cid=id) except ObjectDoesNotExist: return CardNotFound(request) if card.retrieved: return render( request, "submit.html", { "success": False, "title": "卡片已被捕獲", "content": "這張卡片已經被使用過囉,何不換張卡片呢?", }) else: if request.method == 'GET': <|code_end|> , determine the next line of code. You have imports: from app.card.forms import CardForm, FeedForm from app.models import Card, History from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.db import transaction and context (class names, function names, or code) available: # Path: app/card/forms.py # class CardForm(forms.Form): # name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False) # value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560) # long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False) # active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True) # # class FeedForm(forms.Form): # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) . Output only the next line.
form = FeedForm()
Predict the next line for this snippet: <|code_start|> def CardNotFound(request): return render( request, "submit.html", { "success": False, "content": "不在系統中的卡片,可能是被註銷了,請戳戳工作人員吧", "title": "不認識的卡片"}, status=404) @login_required def card(request, id=None): if request.user.is_authenticated(): try: <|code_end|> with the help of current file imports: from app.card.forms import CardForm, FeedForm from app.models import Card, History from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.db import transaction and context from other files: # Path: app/card/forms.py # class CardForm(forms.Form): # name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False) # value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560) # long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False) # active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True) # # class FeedForm(forms.Form): # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) , which may contain function names, class names, or code. Output only the next line.
card = Card.objects.get(cid=id)
Given snippet: <|code_start|> if request.user.has_perm('app.change_card'): try: card = Card.objects.get(cid=id) except ObjectDoesNotExist: return CardNotFound(request) if not request.POST: form = CardForm( {"name": card.name, "value": card.value, "long_desc": card.long_desc, "active": card.active, "retrieved": card.retrieved}) return render(request, "card/edit.html", locals()) else: form = CardForm(request.POST) if form.is_valid(): action = 2 if card.active is not form.cleaned_data["active"]: if form.cleaned_data["active"]: action = 4 else: action = 3 with transaction.atomic(): card.name = form.cleaned_data["name"] card.value = form.cleaned_data["value"] card.long_desc = form.cleaned_data["long_desc"] card.active = form.cleaned_data["active"] card.save() <|code_end|> , continue by predicting the next line. Consider current file imports: from app.card.forms import CardForm, FeedForm from app.models import Card, History from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.shortcuts import render, redirect from django.core.urlresolvers import reverse from django.db import transaction and context: # Path: app/card/forms.py # class CardForm(forms.Form): # name = forms.CharField(max_length=32, label="名字", help_text="點數卡的名子", required=False) # value = forms.IntegerField(label="值", help_text="點數卡的數值", initial="64", max_value=2560, min_value=-2560) # long_desc = forms.CharField(max_length=200, widget=forms.Textarea(), label="說明", required=False) # active = forms.BooleanField(label="開通", help_text="該點數卡是否可用", required=False, initial=True) # # class FeedForm(forms.Form): # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) which might include code, classes, or functions. Output only the next line.
record = History(action=action, user=request.user, card=card)
Using the snippet: <|code_start|> @login_required def dashboard(request): if request.user.has_perm('app.master'): # only game master can view this page <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.core.exceptions import PermissionDenied from django.db import transaction, models from app import models as data from app.staff.forms import FastSendForm from app.models import Card, History and context (class names, function names, or code) available: # Path: app/models.py # class Team(models.Model): # class Player(models.Model): # class Card(models.Model): # class Meta: # class History(models.Model): # class Meta: # def points(self): # def __str__(self): # def points_acquired(self): # def __str__(self): # def random(): # def __str__(self): # def action_explain(self): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # Path: app/staff/forms.py # class FastSendForm(forms.Form): # message = forms.CharField(max_length=255, label="訊息", help_text="悄悄話", required=False) # point = forms.IntegerField(label="價值", help_text="點數卡的價值", initial=1) # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) . Output only the next line.
players = data.Player.objects.all()
Predict the next line after this snippet: <|code_start|> return render( request, "submit.html", { "success": False, "title": "發送卡片失敗", "content": "要不要去戳戳系統管理員呢?" "(如果是POST奇怪的資料,可能會收到彈力繩喔ˊ_>ˋ)" }) with transaction.atomic(): card = Card() present = request.user.first_name if present == "": present = '祝福' card.name = "來自 %s 的%s" % (request.user.last_name, present) card.value = denomination[tt] card.active = True card.retrieved = False card.issuer = request.user card.save() record = History(action=1, user=request.user, card=card) record.save() return redirect('view card', card.cid) else: return render(request, 'staff/lite.html', locals()) @login_required def gift(request): if not request.user.has_perm('app.master'): raise PermissionDenied if request.method == 'GET': <|code_end|> using the current file's imports: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.core.exceptions import PermissionDenied from django.db import transaction, models from app import models as data from app.staff.forms import FastSendForm from app.models import Card, History and any relevant context from other files: # Path: app/models.py # class Team(models.Model): # class Player(models.Model): # class Card(models.Model): # class Meta: # class History(models.Model): # class Meta: # def points(self): # def __str__(self): # def points_acquired(self): # def __str__(self): # def random(): # def __str__(self): # def action_explain(self): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # Path: app/staff/forms.py # class FastSendForm(forms.Form): # message = forms.CharField(max_length=255, label="訊息", help_text="悄悄話", required=False) # point = forms.IntegerField(label="價值", help_text="點數卡的價值", initial=1) # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) . Output only the next line.
return render(request, 'staff/gift.html', {"form": FastSendForm()})
Here is a snippet: <|code_start|> @login_required def dashboard(request): if request.user.has_perm('app.master'): # only game master can view this page players = data.Player.objects.all() <|code_end|> . Write the next line using the current file imports: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.core.exceptions import PermissionDenied from django.db import transaction, models from app import models as data from app.staff.forms import FastSendForm from app.models import Card, History and context from other files: # Path: app/models.py # class Team(models.Model): # class Player(models.Model): # class Card(models.Model): # class Meta: # class History(models.Model): # class Meta: # def points(self): # def __str__(self): # def points_acquired(self): # def __str__(self): # def random(): # def __str__(self): # def action_explain(self): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # Path: app/staff/forms.py # class FastSendForm(forms.Form): # message = forms.CharField(max_length=255, label="訊息", help_text="悄悄話", required=False) # point = forms.IntegerField(label="價值", help_text="點數卡的價值", initial=1) # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) , which may include functions, classes, or code. Output only the next line.
cards = data.Card.objects.all()
Predict the next line after this snippet: <|code_start|> @login_required def dashboard(request): if request.user.has_perm('app.master'): # only game master can view this page players = data.Player.objects.all() cards = data.Card.objects.all() teams = data.Team.objects.all() <|code_end|> using the current file's imports: from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.core.exceptions import PermissionDenied from django.db import transaction, models from app import models as data from app.staff.forms import FastSendForm from app.models import Card, History and any relevant context from other files: # Path: app/models.py # class Team(models.Model): # class Player(models.Model): # class Card(models.Model): # class Meta: # class History(models.Model): # class Meta: # def points(self): # def __str__(self): # def points_acquired(self): # def __str__(self): # def random(): # def __str__(self): # def action_explain(self): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # Path: app/staff/forms.py # class FastSendForm(forms.Form): # message = forms.CharField(max_length=255, label="訊息", help_text="悄悄話", required=False) # point = forms.IntegerField(label="價值", help_text="點數卡的價值", initial=1) # player = forms.ModelChoiceField(Player.objects.all(), label="玩家") # # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) . Output only the next line.
history_entries = data.History.objects.all().order_by('-date')[:30]
Predict the next line after this snippet: <|code_start|> class CardCoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s: %d point" % (obj.name, obj.value) class FeedForm(forms.Form): <|code_end|> using the current file's imports: from django import forms from app.models import Card and any relevant context from other files: # Path: app/models.py # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) . Output only the next line.
card = CardCoiceField(Card.objects.filter(active=True, retrieved=False), label="Card")
Predict the next line for this snippet: <|code_start|> def player(request, id=None): if not request.user.is_authenticated(): return redirect("login", id) else: if request.user.is_staff: return redirect('home') if not id == request.user.username: # rediect logged-in user to /player/<username> return redirect('player data', request.user.username) else: user = request.user sorted_players = list(user.player.team.player.all()) sorted_players.sort(key=lambda x: x.points_acquired, reverse=True) <|code_end|> with the help of current file imports: from app.models import History from app.player.forms import FeedForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect, render from django.db import transaction and context from other files: # Path: app/models.py # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) # # Path: app/player/forms.py # class FeedForm(forms.Form): # card = CardCoiceField(Card.objects.filter(active=True, retrieved=False), label="Card") , which may contain function names, class names, or code. Output only the next line.
this_records = History.objects.filter(user=user)
Predict the next line after this snippet: <|code_start|> return redirect('player data', request.user.username) else: user = request.user sorted_players = list(user.player.team.player.all()) sorted_players.sort(key=lambda x: x.points_acquired, reverse=True) this_records = History.objects.filter(user=user) records = [] for player_i in user.player.team.player.all(): records = records + list(History.objects.filter(user=player_i.user)) for i in sorted_players: if user.player.team.points == 0: i.weight = 0 else: i.weight = i.points_acquired / user.player.team.points * 100 return render(request, 'player/player.html', locals()) @login_required def feed(request, id=None): if request.user.has_perm('app.feed_card'): try: user = User.objects.get(username=id) except ObjectDoesNotExist: return render( request, "submit.html", { "content": "你是找誰?", "title": "錯誤!"}, status=404) else: if not request.POST: <|code_end|> using the current file's imports: from app.models import History from app.player.forms import FeedForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect, render from django.db import transaction and any relevant context from other files: # Path: app/models.py # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) # # Path: app/player/forms.py # class FeedForm(forms.Form): # card = CardCoiceField(Card.objects.filter(active=True, retrieved=False), label="Card") . Output only the next line.
form = FeedForm()
Using the snippet: <|code_start|> admin.site.register(Player) admin.site.register(Card) admin.site.register(Team) <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from .models import Player, Card, Team, History and context (class names, function names, or code) available: # Path: app/models.py # class Player(models.Model): # id = models.AutoField(primary_key=True) # user = models.OneToOneField(User, verbose_name="User", help_text="The user of this player.") # team = models.ForeignKey(Team, # verbose_name="Team", # help_text="The team this player belongs to.", # related_name="player") # # @property # def points_acquired(self): # s = self.captured_card.filter(active=True).aggregate(models.Sum('value')) # if s['value__sum'] is None: # return 0 # return s['value__sum'] # # def __str__(self): # return (str(self.user.get_full_name()) + " (" + # str(self.user.get_username()) + "), " + self.team.name) # # class Card(models.Model): # def random(): # return str(get_random_string(16)) # cid = models.CharField(max_length=16, # primary_key=True, # default=random, # verbose_name="Card ID", # help_text="The unique ID for the points card.") # value = models.IntegerField(default="1", # verbose_name="Value", # help_text="The value of the points card.") # active = models.BooleanField(default=True, verbose_name="Active?") # retrieved = models.BooleanField(default=False, verbose_name="Retrieved") # name = models.CharField( # max_length=32, # verbose_name="Name", # help_text="Name of the card.", # blank=True) # long_desc = models.TextField(verbose_name="Descriptions", # help_text="Long descriptions about the card.", # blank=True) # issuer = models.ForeignKey(User, related_name="issued_card") # capturer = models.ForeignKey(Player, related_name="captured_card", null=True, blank=True) # # def __str__(self): # if self.active and not self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "active, " + str(self.value) + " points.") # elif not self.active and self.retrieved: # return (str(self.name) + " (" + str(self.cid) + "), " # "retrieved by " + str(self.capturer) + ", " + str(self.value) + " points.") # else: # return (str(self.name) + " (" + str(self.cid) + "), " # "inactive, " + str(self.value) + " points.") # # class Meta: # permissions = ( # ('read_card', 'can view card detail message'), # ('get_card', 'can capture card'), # ('toggle_card', 'can active/inactive card'), # ('gen_card', 'can generate card within limit'), # ('feed_card', 'can directly send card to someone'), # ('view_cardlist', 'can list all card'), # # ('master', 'game master'), # ('worker', 'normal staff'), # ) # # class Team(models.Model): # tid = models.AutoField(primary_key=True) # name = models.CharField(max_length=100, # verbose_name="Name", # help_text="Name of the team.") # # @property # def points(self): # s = 0 # for player in self.player.all(): # s += player.points_acquired # return s # # def __str__(self): # return str(self.name) + " (" + str(self.tid) + ")" # # class History(models.Model): # ACTION_CODE = { # 1: "建立卡片", # 2: "編輯卡片", # 3: "關閉卡片", # 4: "啟動卡片", # 10: "獲得卡片", # 0xfeed: "餵食卡片", # } # # no = models.AutoField(primary_key=True) # action = models.IntegerField(choices=list(ACTION_CODE.items())) # user = models.ForeignKey(User) # card = models.ForeignKey(Card) # comment = models.CharField(max_length=255) # date = models.DateTimeField(auto_now_add=True) # # @property # def action_explain(self): # return History.ACTION_CODE[self.action] # # class Meta: # permissions = ( # ('view_history', 'can view history'), # ) . Output only the next line.
admin.site.register(History)
Given the following code snippet before the placeholder: <|code_start|>User = get_user_model() class LikedMixin(object): def get_liked_id(self, obj): request = self.context['request'] if request.user.is_authenticated: try: content_type = self.get_content_type(obj) return Like.objects.get(content_type=content_type, user=request.user, object_id=obj.pk).pk except Like.DoesNotExist: pass return None class FollowedMixin(object): def get_follow_id(self, obj): # Indicate whether or not the logged in user is following a given object (e.g., another user) # Provide the id of the follow object so it can be deleted to unfollow the object if self.context['request'].user.is_authenticated: try: content_type = self.get_content_type(obj) return self.context['request'].user.following.get(content_type=content_type, object_id=obj.pk).pk except Follow.DoesNotExist: pass return None class TagSerializer(serializers.ModelSerializer): class Meta: <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer and context including class names, function names, and sometimes code from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) . Output only the next line.
model = Tag
Next line prediction: <|code_start|> if request.user.is_authenticated: try: content_type = self.get_content_type(obj) return Like.objects.get(content_type=content_type, user=request.user, object_id=obj.pk).pk except Like.DoesNotExist: pass return None class FollowedMixin(object): def get_follow_id(self, obj): # Indicate whether or not the logged in user is following a given object (e.g., another user) # Provide the id of the follow object so it can be deleted to unfollow the object if self.context['request'].user.is_authenticated: try: content_type = self.get_content_type(obj) return self.context['request'].user.following.get(content_type=content_type, object_id=obj.pk).pk except Follow.DoesNotExist: pass return None class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'id') class CommentSerializer(serializers.ModelSerializer): class Meta: <|code_end|> . Use current file imports: (from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer) and context including class names, function names, or small code snippets from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) . Output only the next line.
model = Comment
Predict the next line after this snippet: <|code_start|> User = get_user_model() class LikedMixin(object): def get_liked_id(self, obj): request = self.context['request'] if request.user.is_authenticated: try: content_type = self.get_content_type(obj) return Like.objects.get(content_type=content_type, user=request.user, object_id=obj.pk).pk except Like.DoesNotExist: pass return None class FollowedMixin(object): def get_follow_id(self, obj): # Indicate whether or not the logged in user is following a given object (e.g., another user) # Provide the id of the follow object so it can be deleted to unfollow the object if self.context['request'].user.is_authenticated: try: content_type = self.get_content_type(obj) return self.context['request'].user.following.get(content_type=content_type, object_id=obj.pk).pk <|code_end|> using the current file's imports: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer and any relevant context from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) . Output only the next line.
except Follow.DoesNotExist:
Given the following code snippet before the placeholder: <|code_start|> class Meta: model = Follow fields = ['id', 'follower', 'following', 'created', 'content_type', 'object_id'] def get_user_follow(self, obj): user = User.objects.get(pk=obj.object_id) serializer = UserSerializer(user, context={'request': self.context.get('request')}) return serializer.data class ShareSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Share fields = '__all__' class LikeSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Like fields = '__all__' class FlagSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) class Meta: <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer and context including class names, function names, and sometimes code from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) . Output only the next line.
model = Flag
Here is a snippet: <|code_start|> class Meta: model = Comment exclude = ('related_tags',) def __init__(self, *args, **kwargs): """ The `user` field is added here to help with recursive import issues mentioned in rest_user.serializers """ super(CommentSerializer, self).__init__(*args, **kwargs) self.fields["user"] = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) class FollowSerializer(serializers.ModelSerializer): follower = UserSerializer(read_only=True, source="user") following = serializers.SerializerMethodField('get_user_follow') class Meta: model = Follow fields = ['id', 'follower', 'following', 'created', 'content_type', 'object_id'] def get_user_follow(self, obj): user = User.objects.get(pk=obj.object_id) serializer = UserSerializer(user, context={'request': self.context.get('request')}) return serializer.data class ShareSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) class Meta: <|code_end|> . Write the next line using the current file imports: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer and context from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) , which may include functions, classes, or code. Output only the next line.
model = Share
Next line prediction: <|code_start|> User = get_user_model() class LikedMixin(object): def get_liked_id(self, obj): request = self.context['request'] if request.user.is_authenticated: try: content_type = self.get_content_type(obj) <|code_end|> . Use current file imports: (from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer) and context including class names, function names, or small code snippets from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) . Output only the next line.
return Like.objects.get(content_type=content_type, user=request.user, object_id=obj.pk).pk
Given the following code snippet before the placeholder: <|code_start|> class FollowedMixin(object): def get_follow_id(self, obj): # Indicate whether or not the logged in user is following a given object (e.g., another user) # Provide the id of the follow object so it can be deleted to unfollow the object if self.context['request'].user.is_authenticated: try: content_type = self.get_content_type(obj) return self.context['request'].user.following.get(content_type=content_type, object_id=obj.pk).pk except Follow.DoesNotExist: pass return None class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'id') class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment exclude = ('related_tags',) def __init__(self, *args, **kwargs): """ The `user` field is added here to help with recursive import issues mentioned in rest_user.serializers """ super(CommentSerializer, self).__init__(*args, **kwargs) <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_social_network.models import Tag, Comment, Follow, Flag, Share, Like from yak.rest_user.serializers import UserSerializer and context including class names, function names, and sometimes code from other files: # Path: yak/rest_social_network/models.py # class Tag(CoreModel): # name = models.CharField(max_length=75, unique=True) # # class Meta: # ordering = ['-created'] # # def identifier(self): # return "#{}".format(self.name) # # def type(self): # return "tag" # # def __unicode__(self): # return "{}".format(self.name) # # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] # # class Follow(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="following", on_delete=models.CASCADE) # # @property # def object_type(self): # return self.content_type.name # # @property # def name(self): # # object must be registered with FollowableModel # return self.content_object.identifier() # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # ordering = ['created'] # # class Flag(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="flags", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # class Share(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField() # content_object = GenericForeignKey() # shared_with = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='shared_with') # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="shares", on_delete=models.CASCADE) # # class Like(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="likes", on_delete=models.CASCADE) # # class Meta: # unique_together = (("user", "content_type", "object_id"),) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) . Output only the next line.
self.fields["user"] = UserSerializer(read_only=True, default=serializers.CurrentUserDefault())
Here is a snippet: <|code_start|> return "{0}".format(message) @property def name(self): return "{}".format(self.notification_type) def __unicode__(self): return "{}: {}".format(self.user, self.notification_type) class Meta: ordering = ['-created'] @task def create_notification(receiver, reporter, content_object, notification_type, template_override=None, reply_to=None, deep_link=None): # If the receiver of this notification is the same as the reporter or # if the user has blocked this type, then don't create if receiver == reporter: return notification = Notification.objects.create(user=receiver, reporter=reporter, content_object=content_object, notification_type=notification_type, template_override=template_override, deep_link=deep_link) notification.save() notification_setting = NotificationSetting.objects.get(notification_type=notification_type, user=receiver) <|code_end|> . Write the next line using the current file imports: from collections import defaultdict from caching.base import CachingMixin, CachingManager from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.db import models from django.template.loader import render_to_string from celery.task import task from yak.rest_core.models import CoreModel from yak.settings import yak_settings from .utils import send_push_notification from .utils import send_email_notification and context from other files: # Path: yak/rest_core/models.py # class CoreModel(models.Model): # created = models.DateTimeField(auto_now_add=True, null=True) # # def __repr__(self): # return '<{}:{} {}>'.format(self.__class__.__name__, self.pk, str(self)) # # class Meta: # abstract = True # # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) , which may include functions, classes, or code. Output only the next line.
if notification_setting.allow_push and yak_settings.ALLOW_PUSH:
Here is a snippet: <|code_start|> class PushwooshTokenSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, default=serializers.CurrentUserDefault()) hwid = serializers.CharField(write_only=True) language = serializers.CharField(write_only=True) platform = serializers.CharField(write_only=True) class Meta: <|code_end|> . Write the next line using the current file imports: from rest_framework import serializers from yak.rest_notifications.models import NotificationSetting, Notification, PushwooshToken, NotificationType from yak.rest_user.serializers import UserSerializer from yak.settings import yak_settings and context from other files: # Path: yak/rest_notifications/models.py # class NotificationSetting(CoreModel): # notification_type = models.ForeignKey(NotificationType, related_name="user_settings", on_delete=models.CASCADE) # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notification_settings', on_delete=models.CASCADE) # allow_push = models.BooleanField(default=True) # allow_email = models.BooleanField(default=True) # # class Meta: # unique_together = ('notification_type', 'user') # ordering = ['-created'] # # def __unicode__(self): # return "{}: {}".format(self.user, self.notification_type) # # def name(self): # return "{}: {}".format(self.user, self.notification_type) # # class Notification(CoreModel): # PUSH = "push" # EMAIL = "email" # # notification_type = models.ForeignKey(NotificationType, related_name="notifications", on_delete=models.CASCADE) # template_override = models.CharField(max_length=100, blank=True, null=True) # deep_link = models.CharField(max_length=100, blank=True, null=True) # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="notifications_received", null=True, blank=True, # on_delete=models.CASCADE) # reporter = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="notifications_sent", null=True, blank=True, # on_delete=models.CASCADE) # # # The object that the notification is about, not the social model related to it # # E.g., if you Like a Post, the content_object for the notification is the Post, not the Like # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # def message(self, location): # """ # Takes our configured notifications and creates a message # replacing the appropriate variables from the content object # """ # # data = defaultdict(str) # # get the domain from Site # data['domain'] = Site.objects.get_current().domain # # if self.content_object: # data['identifier'] = self.content_object.identifier() # if self.reporter: # data['reporter'] = self.reporter.identifier() # # if hasattr(self.content_object, 'extra_notification_params'): # data.update(self.content_object.extra_notification_params()) # # configured_template_name = "{}.html".format(self.notification_type.slug) # template_name = self.template_override if self.template_override else configured_template_name # return render_to_string("notifications/{}/{}".format(location, template_name), data) # # def email_message(self): # return self.message(Notification.EMAIL) # # def push_message(self): # message = self.message(Notification.PUSH) # if self.reporter: # return "{0} {1}".format(self.reporter, message) # else: # return "{0}".format(message) # # @property # def name(self): # return "{}".format(self.notification_type) # # def __unicode__(self): # return "{}: {}".format(self.user, self.notification_type) # # class Meta: # ordering = ['-created'] # # class PushwooshToken(CoreModel): # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="pushwoosh_tokens", on_delete=models.CASCADE) # token = models.CharField(max_length=255) # # class NotificationType(CachingMixin, CoreModel): # name = models.CharField(max_length=32) # slug = models.SlugField(unique=True) # description = models.CharField(max_length=255) # is_active = models.BooleanField(default=True) # # objects = CachingManager() # # def __unicode__(self): # return "{}".format(self.name) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) # # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) , which may include functions, classes, or code. Output only the next line.
model = PushwooshToken
Next line prediction: <|code_start|> def submit_to_pushwoosh(request_data): url = 'https://cp.pushwoosh.com/json/1.3/createMessage' response = requests.post(url, data=request_data, headers=PushwooshClient.headers) return response.json() def send_pushwoosh_notification(receiver, message, deep_link=None): notification_data = { 'content': message, 'send_date': constants.SEND_DATE_NOW, 'devices': [token.token for token in receiver.pushwoosh_tokens.all()], 'ios_badges': '+1' } if deep_link is not None: notification_data['minimize_link'] = 0 notification_data['link'] = deep_link request = {'request': { 'notifications': [notification_data], <|code_end|> . Use current file imports: (import json import requests from django.conf import settings from django.core.mail import EmailMultiAlternatives from django.utils.html import strip_tags from django.utils.module_loading import import_string from pypushwoosh import constants from pypushwoosh.client import PushwooshClient from yak.settings import yak_settings) and context including class names, function names, or small code snippets from other files: # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) . Output only the next line.
'auth': yak_settings.PUSHWOOSH_AUTH_TOKEN,
Here is a snippet: <|code_start|> User = get_user_model() class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): class Meta: model = User fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', 'about', 'user_following_count', 'user_followers_count', 'follow_id') follow_id = serializers.SerializerMethodField() class PostSerializer(YAKModelSerializer, LikedMixin): user = ProjectUserSerializer(read_only=True, default=serializers.CurrentUserDefault()) liked_id = serializers.SerializerMethodField() class Meta: <|code_end|> . Write the next line using the current file imports: from django.contrib.auth import get_user_model from rest_framework import serializers from test_project.test_app.models import Post from yak.rest_core.serializers import YAKModelSerializer from yak.rest_social_network.serializers import LikedMixin, FollowedMixin from yak.rest_user.serializers import AuthSerializerMixin and context from other files: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # Path: yak/rest_core/serializers.py # class YAKModelSerializer(serializers.ModelSerializer): # # def __init__(self, *args, **kwargs): # super(YAKModelSerializer, self).__init__(*args, **kwargs) # self.fields['content_type'] = serializers.SerializerMethodField() # # def get_content_type(self, obj): # return ContentType.objects.get_for_model(obj).pk # # Path: yak/rest_social_network/serializers.py # class LikedMixin(object): # def get_liked_id(self, obj): # request = self.context['request'] # if request.user.is_authenticated: # try: # content_type = self.get_content_type(obj) # return Like.objects.get(content_type=content_type, user=request.user, object_id=obj.pk).pk # except Like.DoesNotExist: # pass # return None # # class FollowedMixin(object): # def get_follow_id(self, obj): # # Indicate whether or not the logged in user is following a given object (e.g., another user) # # Provide the id of the follow object so it can be deleted to unfollow the object # if self.context['request'].user.is_authenticated: # try: # content_type = self.get_content_type(obj) # return self.context['request'].user.following.get(content_type=content_type, object_id=obj.pk).pk # except Follow.DoesNotExist: # pass # return None # # Path: yak/rest_user/serializers.py # class AuthSerializerMixin(object): # def create(self, validated_data): # if validated_data.get("username", None): # validated_data["username"] = validated_data["username"].lower() # if validated_data.get("email", None): # validated_data["email"] = validated_data["email"].lower() # if validated_data.get("password", None): # validated_data["password"] = make_password(validated_data["password"]) # # return super(AuthSerializerMixin, self).create(validated_data) # # def update(self, instance, validated_data): # if validated_data.get("username", None): # validated_data["username"] = validated_data["username"].lower() # if validated_data.get("email", None): # validated_data["email"] = validated_data["email"].lower() # if validated_data.get("password", None): # validated_data["password"] = make_password(validated_data["password"]) # # return super(AuthSerializerMixin, self).update(instance, validated_data) # # def validate_username(self, value): # username = self.context['request'].user.username if self.context['request'].user.is_authenticated else None # if value and value != username and User.objects.filter(username__iexact=value).exists(): # raise serializers.ValidationError("That username is taken") # return value # # def validate_email(self, value): # email = self.context['request'].user.email if self.context['request'].user.is_authenticated else None # if value and value != email and User.objects.filter(email__iexact=value).exists(): # raise serializers.ValidationError("An account already exists with that email") # return value # # def validate_password(self, value): # value = base64.decodebytes(bytes(value, 'utf8')).decode() # if len(value) < 6: # raise serializers.ValidationError("Password must be at least 6 characters") # return value , which may include functions, classes, or code. Output only the next line.
model = Post
Given the code snippet: <|code_start|> User = get_user_model() class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): class Meta: model = User fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', 'about', 'user_following_count', 'user_followers_count', 'follow_id') follow_id = serializers.SerializerMethodField() <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth import get_user_model from rest_framework import serializers from test_project.test_app.models import Post from yak.rest_core.serializers import YAKModelSerializer from yak.rest_social_network.serializers import LikedMixin, FollowedMixin from yak.rest_user.serializers import AuthSerializerMixin and context (functions, classes, or occasionally code) from other files: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # Path: yak/rest_core/serializers.py # class YAKModelSerializer(serializers.ModelSerializer): # # def __init__(self, *args, **kwargs): # super(YAKModelSerializer, self).__init__(*args, **kwargs) # self.fields['content_type'] = serializers.SerializerMethodField() # # def get_content_type(self, obj): # return ContentType.objects.get_for_model(obj).pk # # Path: yak/rest_social_network/serializers.py # class LikedMixin(object): # def get_liked_id(self, obj): # request = self.context['request'] # if request.user.is_authenticated: # try: # content_type = self.get_content_type(obj) # return Like.objects.get(content_type=content_type, user=request.user, object_id=obj.pk).pk # except Like.DoesNotExist: # pass # return None # # class FollowedMixin(object): # def get_follow_id(self, obj): # # Indicate whether or not the logged in user is following a given object (e.g., another user) # # Provide the id of the follow object so it can be deleted to unfollow the object # if self.context['request'].user.is_authenticated: # try: # content_type = self.get_content_type(obj) # return self.context['request'].user.following.get(content_type=content_type, object_id=obj.pk).pk # except Follow.DoesNotExist: # pass # return None # # Path: yak/rest_user/serializers.py # class AuthSerializerMixin(object): # def create(self, validated_data): # if validated_data.get("username", None): # validated_data["username"] = validated_data["username"].lower() # if validated_data.get("email", None): # validated_data["email"] = validated_data["email"].lower() # if validated_data.get("password", None): # validated_data["password"] = make_password(validated_data["password"]) # # return super(AuthSerializerMixin, self).create(validated_data) # # def update(self, instance, validated_data): # if validated_data.get("username", None): # validated_data["username"] = validated_data["username"].lower() # if validated_data.get("email", None): # validated_data["email"] = validated_data["email"].lower() # if validated_data.get("password", None): # validated_data["password"] = make_password(validated_data["password"]) # # return super(AuthSerializerMixin, self).update(instance, validated_data) # # def validate_username(self, value): # username = self.context['request'].user.username if self.context['request'].user.is_authenticated else None # if value and value != username and User.objects.filter(username__iexact=value).exists(): # raise serializers.ValidationError("That username is taken") # return value # # def validate_email(self, value): # email = self.context['request'].user.email if self.context['request'].user.is_authenticated else None # if value and value != email and User.objects.filter(email__iexact=value).exists(): # raise serializers.ValidationError("An account already exists with that email") # return value # # def validate_password(self, value): # value = base64.decodebytes(bytes(value, 'utf8')).decode() # if len(value) < 6: # raise serializers.ValidationError("Password must be at least 6 characters") # return value . Output only the next line.
class PostSerializer(YAKModelSerializer, LikedMixin):
Predict the next line after this snippet: <|code_start|> router = routers.DefaultRouter() router.register(r'notification_settings', NotificationSettingViewSet, base_name='notification_settings') router.register(r'follows', NotificationFollowViewSet, base_name='follows') router.register(r'likes', NotificationLikeViewSet, base_name='likes') router.register(r'shares', NotificationShareViewSet, base_name='shares') router.register(r'comments', NotificationCommentViewSet, base_name='comments') urlpatterns = [ url(r'^', include(router.urls)), <|code_end|> using the current file's imports: from django.conf.urls import url, include from rest_framework import routers from yak.rest_notifications.views import NotificationSettingViewSet, NotificationView, \ NotificationFollowViewSet, NotificationLikeViewSet, NotificationShareViewSet, NotificationCommentViewSet, \ PushwooshTokenView and any relevant context from other files: # Path: yak/rest_notifications/views.py # class NotificationSettingViewSet(mixins.UpdateModelMixin, # mixins.ListModelMixin, # GenericViewSet): # queryset = NotificationSetting.objects.all() # serializer_class = NotificationSettingSerializer # permission_classes = (IsOwner,) # # def perform_update(self, serializer): # serializer.save(user=self.request.user) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # def put(self, request, *args, **kwargs): # queryset = self.get_queryset() # serializer = self.get_serializer(queryset, data=request.data, many=True, partial=True) # # serializer.is_valid(raise_exception=True) # serializer.save() # return Response(serializer.data, status=status.HTTP_200_OK) # # class NotificationView(generics.ListAPIView): # queryset = Notification.objects.all() # serializer_class = NotificationSerializer # permission_classes = (IsOwner,) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # class NotificationFollowViewSet(FollowViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="follow") # create_notification(obj.content_object, obj.user, obj.content_object, notification_type) # # class NotificationLikeViewSet(LikeViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="like") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class NotificationShareViewSet(ShareViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="share") # for receiver in obj.shared_with.all(): # create_notification(receiver, obj.user, obj.content_object, notification_type) # # class NotificationCommentViewSet(CommentViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="comment") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class PushwooshTokenView(generics.CreateAPIView): # queryset = PushwooshToken.objects.all() # serializer_class = PushwooshTokenSerializer # permission_classes = (IsOwner,) # # def perform_create(self, serializer): # hwid = serializer.validated_data.pop("hwid") # language = serializer.validated_data.pop("language") # platform = serializer.validated_data.pop("platform") # # platform_code = constants.PLATFORM_IOS # if platform == 'android': # platform_code = constants.PLATFORM_ANDROID # # push_client = client.PushwooshClient() # command = RegisterDeviceCommand(yak_settings.PUSHWOOSH_APP_CODE, hwid, platform_code, # serializer.validated_data["token"], language) # response = push_client.invoke(command) # # if response["status_code"] != 200: # raise AuthenticationFailed("Authentication with notification service failed") # # serializer.save(user=self.request.user) . Output only the next line.
url(r'^notifications/$', NotificationView.as_view(), name="notifications"),
Predict the next line after this snippet: <|code_start|> router = routers.DefaultRouter() router.register(r'notification_settings', NotificationSettingViewSet, base_name='notification_settings') router.register(r'follows', NotificationFollowViewSet, base_name='follows') <|code_end|> using the current file's imports: from django.conf.urls import url, include from rest_framework import routers from yak.rest_notifications.views import NotificationSettingViewSet, NotificationView, \ NotificationFollowViewSet, NotificationLikeViewSet, NotificationShareViewSet, NotificationCommentViewSet, \ PushwooshTokenView and any relevant context from other files: # Path: yak/rest_notifications/views.py # class NotificationSettingViewSet(mixins.UpdateModelMixin, # mixins.ListModelMixin, # GenericViewSet): # queryset = NotificationSetting.objects.all() # serializer_class = NotificationSettingSerializer # permission_classes = (IsOwner,) # # def perform_update(self, serializer): # serializer.save(user=self.request.user) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # def put(self, request, *args, **kwargs): # queryset = self.get_queryset() # serializer = self.get_serializer(queryset, data=request.data, many=True, partial=True) # # serializer.is_valid(raise_exception=True) # serializer.save() # return Response(serializer.data, status=status.HTTP_200_OK) # # class NotificationView(generics.ListAPIView): # queryset = Notification.objects.all() # serializer_class = NotificationSerializer # permission_classes = (IsOwner,) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # class NotificationFollowViewSet(FollowViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="follow") # create_notification(obj.content_object, obj.user, obj.content_object, notification_type) # # class NotificationLikeViewSet(LikeViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="like") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class NotificationShareViewSet(ShareViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="share") # for receiver in obj.shared_with.all(): # create_notification(receiver, obj.user, obj.content_object, notification_type) # # class NotificationCommentViewSet(CommentViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="comment") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class PushwooshTokenView(generics.CreateAPIView): # queryset = PushwooshToken.objects.all() # serializer_class = PushwooshTokenSerializer # permission_classes = (IsOwner,) # # def perform_create(self, serializer): # hwid = serializer.validated_data.pop("hwid") # language = serializer.validated_data.pop("language") # platform = serializer.validated_data.pop("platform") # # platform_code = constants.PLATFORM_IOS # if platform == 'android': # platform_code = constants.PLATFORM_ANDROID # # push_client = client.PushwooshClient() # command = RegisterDeviceCommand(yak_settings.PUSHWOOSH_APP_CODE, hwid, platform_code, # serializer.validated_data["token"], language) # response = push_client.invoke(command) # # if response["status_code"] != 200: # raise AuthenticationFailed("Authentication with notification service failed") # # serializer.save(user=self.request.user) . Output only the next line.
router.register(r'likes', NotificationLikeViewSet, base_name='likes')
Next line prediction: <|code_start|> router = routers.DefaultRouter() router.register(r'notification_settings', NotificationSettingViewSet, base_name='notification_settings') router.register(r'follows', NotificationFollowViewSet, base_name='follows') router.register(r'likes', NotificationLikeViewSet, base_name='likes') <|code_end|> . Use current file imports: (from django.conf.urls import url, include from rest_framework import routers from yak.rest_notifications.views import NotificationSettingViewSet, NotificationView, \ NotificationFollowViewSet, NotificationLikeViewSet, NotificationShareViewSet, NotificationCommentViewSet, \ PushwooshTokenView) and context including class names, function names, or small code snippets from other files: # Path: yak/rest_notifications/views.py # class NotificationSettingViewSet(mixins.UpdateModelMixin, # mixins.ListModelMixin, # GenericViewSet): # queryset = NotificationSetting.objects.all() # serializer_class = NotificationSettingSerializer # permission_classes = (IsOwner,) # # def perform_update(self, serializer): # serializer.save(user=self.request.user) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # def put(self, request, *args, **kwargs): # queryset = self.get_queryset() # serializer = self.get_serializer(queryset, data=request.data, many=True, partial=True) # # serializer.is_valid(raise_exception=True) # serializer.save() # return Response(serializer.data, status=status.HTTP_200_OK) # # class NotificationView(generics.ListAPIView): # queryset = Notification.objects.all() # serializer_class = NotificationSerializer # permission_classes = (IsOwner,) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # class NotificationFollowViewSet(FollowViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="follow") # create_notification(obj.content_object, obj.user, obj.content_object, notification_type) # # class NotificationLikeViewSet(LikeViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="like") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class NotificationShareViewSet(ShareViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="share") # for receiver in obj.shared_with.all(): # create_notification(receiver, obj.user, obj.content_object, notification_type) # # class NotificationCommentViewSet(CommentViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="comment") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class PushwooshTokenView(generics.CreateAPIView): # queryset = PushwooshToken.objects.all() # serializer_class = PushwooshTokenSerializer # permission_classes = (IsOwner,) # # def perform_create(self, serializer): # hwid = serializer.validated_data.pop("hwid") # language = serializer.validated_data.pop("language") # platform = serializer.validated_data.pop("platform") # # platform_code = constants.PLATFORM_IOS # if platform == 'android': # platform_code = constants.PLATFORM_ANDROID # # push_client = client.PushwooshClient() # command = RegisterDeviceCommand(yak_settings.PUSHWOOSH_APP_CODE, hwid, platform_code, # serializer.validated_data["token"], language) # response = push_client.invoke(command) # # if response["status_code"] != 200: # raise AuthenticationFailed("Authentication with notification service failed") # # serializer.save(user=self.request.user) . Output only the next line.
router.register(r'shares', NotificationShareViewSet, base_name='shares')
Here is a snippet: <|code_start|> router = routers.DefaultRouter() router.register(r'notification_settings', NotificationSettingViewSet, base_name='notification_settings') router.register(r'follows', NotificationFollowViewSet, base_name='follows') router.register(r'likes', NotificationLikeViewSet, base_name='likes') router.register(r'shares', NotificationShareViewSet, base_name='shares') <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url, include from rest_framework import routers from yak.rest_notifications.views import NotificationSettingViewSet, NotificationView, \ NotificationFollowViewSet, NotificationLikeViewSet, NotificationShareViewSet, NotificationCommentViewSet, \ PushwooshTokenView and context from other files: # Path: yak/rest_notifications/views.py # class NotificationSettingViewSet(mixins.UpdateModelMixin, # mixins.ListModelMixin, # GenericViewSet): # queryset = NotificationSetting.objects.all() # serializer_class = NotificationSettingSerializer # permission_classes = (IsOwner,) # # def perform_update(self, serializer): # serializer.save(user=self.request.user) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # def put(self, request, *args, **kwargs): # queryset = self.get_queryset() # serializer = self.get_serializer(queryset, data=request.data, many=True, partial=True) # # serializer.is_valid(raise_exception=True) # serializer.save() # return Response(serializer.data, status=status.HTTP_200_OK) # # class NotificationView(generics.ListAPIView): # queryset = Notification.objects.all() # serializer_class = NotificationSerializer # permission_classes = (IsOwner,) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # class NotificationFollowViewSet(FollowViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="follow") # create_notification(obj.content_object, obj.user, obj.content_object, notification_type) # # class NotificationLikeViewSet(LikeViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="like") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class NotificationShareViewSet(ShareViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="share") # for receiver in obj.shared_with.all(): # create_notification(receiver, obj.user, obj.content_object, notification_type) # # class NotificationCommentViewSet(CommentViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="comment") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class PushwooshTokenView(generics.CreateAPIView): # queryset = PushwooshToken.objects.all() # serializer_class = PushwooshTokenSerializer # permission_classes = (IsOwner,) # # def perform_create(self, serializer): # hwid = serializer.validated_data.pop("hwid") # language = serializer.validated_data.pop("language") # platform = serializer.validated_data.pop("platform") # # platform_code = constants.PLATFORM_IOS # if platform == 'android': # platform_code = constants.PLATFORM_ANDROID # # push_client = client.PushwooshClient() # command = RegisterDeviceCommand(yak_settings.PUSHWOOSH_APP_CODE, hwid, platform_code, # serializer.validated_data["token"], language) # response = push_client.invoke(command) # # if response["status_code"] != 200: # raise AuthenticationFailed("Authentication with notification service failed") # # serializer.save(user=self.request.user) , which may include functions, classes, or code. Output only the next line.
router.register(r'comments', NotificationCommentViewSet, base_name='comments')
Continue the code snippet: <|code_start|> router = routers.DefaultRouter() router.register(r'notification_settings', NotificationSettingViewSet, base_name='notification_settings') router.register(r'follows', NotificationFollowViewSet, base_name='follows') router.register(r'likes', NotificationLikeViewSet, base_name='likes') router.register(r'shares', NotificationShareViewSet, base_name='shares') router.register(r'comments', NotificationCommentViewSet, base_name='comments') urlpatterns = [ url(r'^', include(router.urls)), url(r'^notifications/$', NotificationView.as_view(), name="notifications"), <|code_end|> . Use current file imports: from django.conf.urls import url, include from rest_framework import routers from yak.rest_notifications.views import NotificationSettingViewSet, NotificationView, \ NotificationFollowViewSet, NotificationLikeViewSet, NotificationShareViewSet, NotificationCommentViewSet, \ PushwooshTokenView and context (classes, functions, or code) from other files: # Path: yak/rest_notifications/views.py # class NotificationSettingViewSet(mixins.UpdateModelMixin, # mixins.ListModelMixin, # GenericViewSet): # queryset = NotificationSetting.objects.all() # serializer_class = NotificationSettingSerializer # permission_classes = (IsOwner,) # # def perform_update(self, serializer): # serializer.save(user=self.request.user) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # def put(self, request, *args, **kwargs): # queryset = self.get_queryset() # serializer = self.get_serializer(queryset, data=request.data, many=True, partial=True) # # serializer.is_valid(raise_exception=True) # serializer.save() # return Response(serializer.data, status=status.HTTP_200_OK) # # class NotificationView(generics.ListAPIView): # queryset = Notification.objects.all() # serializer_class = NotificationSerializer # permission_classes = (IsOwner,) # # def get_queryset(self): # return self.queryset.filter(user=self.request.user) # # class NotificationFollowViewSet(FollowViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="follow") # create_notification(obj.content_object, obj.user, obj.content_object, notification_type) # # class NotificationLikeViewSet(LikeViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="like") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class NotificationShareViewSet(ShareViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="share") # for receiver in obj.shared_with.all(): # create_notification(receiver, obj.user, obj.content_object, notification_type) # # class NotificationCommentViewSet(CommentViewSet): # def perform_create(self, serializer): # obj = serializer.save(user=self.request.user) # notification_type = NotificationType.objects.get(slug="comment") # create_notification(obj.content_object.user, obj.user, obj.content_object, notification_type) # # class PushwooshTokenView(generics.CreateAPIView): # queryset = PushwooshToken.objects.all() # serializer_class = PushwooshTokenSerializer # permission_classes = (IsOwner,) # # def perform_create(self, serializer): # hwid = serializer.validated_data.pop("hwid") # language = serializer.validated_data.pop("language") # platform = serializer.validated_data.pop("platform") # # platform_code = constants.PLATFORM_IOS # if platform == 'android': # platform_code = constants.PLATFORM_ANDROID # # push_client = client.PushwooshClient() # command = RegisterDeviceCommand(yak_settings.PUSHWOOSH_APP_CODE, hwid, platform_code, # serializer.validated_data["token"], language) # response = push_client.invoke(command) # # if response["status_code"] != 200: # raise AuthenticationFailed("Authentication with notification service failed") # # serializer.save(user=self.request.user) . Output only the next line.
url(r'^pushwoosh_token/$', PushwooshTokenView.as_view(), name="pushwoosh_token"),
Based on the snippet: <|code_start|> def assertHttpApplicationError(self, resp): """ Ensures the response is returning a HTTP 500. """ return self.assertEqual(resp.status_code, 500, resp) def assertHttpNotImplemented(self, resp): """ Ensures the response is returning a HTTP 501. """ return self.assertEqual(resp.status_code, 501, resp) def assertValidJSONResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/json``) """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/json')) class SchemaTestCase(APITestCaseWithAssertions): def setUp(self): super(SchemaTestCase, self).setUp() # Parse schema objects for use later self.schema_objects = {} <|code_end|> , predict the immediate next line with the help of imports: import json import sys from flake8.api.legacy import get_style_guide from rest_framework.test import APITestCase from django.conf import settings from yak.settings import yak_settings from django.test import TestCase and context (classes, functions, sometimes code) from other files: # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) . Output only the next line.
with open(yak_settings.API_SCHEMA) as file:
Continue the code snippet: <|code_start|> class FollowableModel(metaclass=abc.ABCMeta): """ Abstract class that used as interface This class makes sure that child classes have my_method implemented """ @abc.abstractmethod def identifier(self): return @abc.abstractmethod def type(self): return <|code_end|> . Use current file imports: import abc import re from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericRelation, GenericForeignKey from django.contrib.sites.models import Site from django.utils.baseconv import base62 from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models.signals import post_save from yak.rest_core.models import CoreModel from yak.rest_notifications.models import NotificationType from yak.rest_user.models import AbstractYeti from yak.settings import yak_settings from yak.rest_notifications.models import create_notification and context (classes, functions, or code) from other files: # Path: yak/rest_core/models.py # class CoreModel(models.Model): # created = models.DateTimeField(auto_now_add=True, null=True) # # def __repr__(self): # return '<{}:{} {}>'.format(self.__class__.__name__, self.pk, str(self)) # # class Meta: # abstract = True # # Path: yak/rest_notifications/models.py # class NotificationType(CachingMixin, CoreModel): # name = models.CharField(max_length=32) # slug = models.SlugField(unique=True) # description = models.CharField(max_length=255) # is_active = models.BooleanField(default=True) # # objects = CachingManager() # # def __unicode__(self): # return "{}".format(self.name) # # Path: yak/rest_user/models.py # class AbstractYeti(AbstractBaseUser, PermissionsMixin): # username = models.CharField(_('username'), max_length=30, unique=True, # help_text=_('Required. 30 characters or fewer. Letters, digits and ' # '@/./+/-/_ only.'), # validators=[ # validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid') # ]) # # Field name should be `fullname` instead of `full_name` for python-social-auth # fullname = models.CharField(max_length=80, blank=True, null=True) # email = models.EmailField(blank=True, null=True, unique=True) # about = models.TextField(blank=True, null=True) # is_active = models.BooleanField(_('active'), default=True, # help_text=_('Designates whether this user should be treated as ' # 'active. Unselect this instead of deleting accounts.')) # is_admin = models.BooleanField(default=False) # is_staff = models.BooleanField(_('staff status'), default=False, # help_text=_('Designates whether the user can log into this admin ' # 'site.')) # date_joined = models.DateTimeField(_('date joined'), default=timezone.now) # # SIZES = { # 'thumbnail': {'height': 60, 'width': 60}, # 'small_photo': {'height': 120, 'width': 120}, # 'large_photo': {'height': 300, 'width': 300} # } # original_file_name = "original_photo" # # original_photo = models.ImageField(upload_to="user_photos/original/", blank=True, null=True) # small_photo = models.ImageField(upload_to="user_photos/small/", blank=True, null=True) # large_photo = models.ImageField(upload_to="user_photos/large/", blank=True, null=True) # thumbnail = models.ImageField(upload_to="user_photos/thumbnail/", blank=True, null=True) # # objects = UserManager() # # USERNAME_FIELD = 'username' # # Used for `createsuperuser` command and nowhere else. Include any fields that cannot be blank # REQUIRED_FIELDS = ['email'] # # class Meta: # abstract = True # # def __unicode__(self): # return "{}".format(self.username) # # def save(self, force_insert=False, force_update=False, using=None, # update_fields=None): # self.username = self.username.lower() # # if self.email: # self.email = self.email.lower().strip() # Remove leading or trailing white space # if self.email == "": # Allows unique=True to work without forcing email presence in forms # self.email = None # super(AbstractYeti, self).save(force_insert, force_update, using, update_fields) # # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) . Output only the next line.
class Tag(CoreModel):
Given snippet: <|code_start|> # If we're using version 0.8.0 or higher if oauth_toolkit_version[0] >= 0 and oauth_toolkit_version[1] >= 8: return obj.oauth2_provider_application.first() else: return obj.oauth2_provider_application.first() def get_client_id(self, obj): return self.get_application(obj).client_id def get_client_secret(self, obj): return self.get_application(obj).client_secret class SignUpSerializer(AuthSerializerMixin, LoginSerializer): password = serializers.CharField(max_length=128, write_only=True, error_messages={'required': 'Password required'}) username = serializers.CharField( error_messages={'required': 'Username required'}, max_length=30, validators=[RegexValidator(), UniqueValidator(queryset=User.objects.all(), message="Username taken")]) email = serializers.EmailField( allow_blank=True, allow_null=True, max_length=75, required=False, validators=[UniqueValidator(queryset=User.objects.all(), message="Email address taken")]) class Meta(LoginSerializer.Meta): fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') <|code_end|> , continue by predicting the next line. Consider current file imports: import base64 import oauth2_provider from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.core.validators import RegexValidator from rest_framework import serializers from rest_framework.validators import UniqueValidator from yak.rest_core.serializers import YAKModelSerializer from yak.rest_core.utils import get_package_version from yak.settings import yak_settings and context: # Path: yak/rest_core/serializers.py # class YAKModelSerializer(serializers.ModelSerializer): # # def __init__(self, *args, **kwargs): # super(YAKModelSerializer, self).__init__(*args, **kwargs) # self.fields['content_type'] = serializers.SerializerMethodField() # # def get_content_type(self, obj): # return ContentType.objects.get_for_model(obj).pk # # Path: yak/rest_core/utils.py # def get_package_version(package): # """ # Return the version number of a Python package as a list of integers # e.g., 1.7.2 will return [1, 7, 2] # """ # return [int(num) for num in package.__version__.split('.')] # # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) which might include code, classes, or functions. Output only the next line.
class UserSerializer(AuthSerializerMixin, YAKModelSerializer):
Given the code snippet: <|code_start|> def get_client_id(self, obj): return self.get_application(obj).client_id def get_client_secret(self, obj): return self.get_application(obj).client_secret class SignUpSerializer(AuthSerializerMixin, LoginSerializer): password = serializers.CharField(max_length=128, write_only=True, error_messages={'required': 'Password required'}) username = serializers.CharField( error_messages={'required': 'Username required'}, max_length=30, validators=[RegexValidator(), UniqueValidator(queryset=User.objects.all(), message="Username taken")]) email = serializers.EmailField( allow_blank=True, allow_null=True, max_length=75, required=False, validators=[UniqueValidator(queryset=User.objects.all(), message="Email address taken")]) class Meta(LoginSerializer.Meta): fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') class UserSerializer(AuthSerializerMixin, YAKModelSerializer): def __new__(cls, *args, **kwargs): """ Can't just inherit in the class definition due to lots of import issues """ <|code_end|> , generate the next line using the imports in this file: import base64 import oauth2_provider from django.contrib.auth import get_user_model from django.contrib.auth.hashers import make_password from django.core.validators import RegexValidator from rest_framework import serializers from rest_framework.validators import UniqueValidator from yak.rest_core.serializers import YAKModelSerializer from yak.rest_core.utils import get_package_version from yak.settings import yak_settings and context (functions, classes, or occasionally code) from other files: # Path: yak/rest_core/serializers.py # class YAKModelSerializer(serializers.ModelSerializer): # # def __init__(self, *args, **kwargs): # super(YAKModelSerializer, self).__init__(*args, **kwargs) # self.fields['content_type'] = serializers.SerializerMethodField() # # def get_content_type(self, obj): # return ContentType.objects.get_for_model(obj).pk # # Path: yak/rest_core/utils.py # def get_package_version(package): # """ # Return the version number of a Python package as a list of integers # e.g., 1.7.2 will return [1, 7, 2] # """ # return [int(num) for num in package.__version__.split('.')] # # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) . Output only the next line.
return yak_settings.USER_SERIALIZER(*args, **kwargs)
Predict the next line after this snippet: <|code_start|> __author__ = 'rudolphmutter' User = get_user_model() class Command(BaseCommand): args = '' help = 'Creates missing notification settings for existing users' def handle(self, *args, **options): for user in User.objects.all(): for notification_type in NotificationType.objects.all(): <|code_end|> using the current file's imports: from django.contrib.auth import get_user_model from django.core.management import BaseCommand from yak.rest_notifications.models import NotificationSetting, NotificationType and any relevant context from other files: # Path: yak/rest_notifications/models.py # class NotificationSetting(CoreModel): # notification_type = models.ForeignKey(NotificationType, related_name="user_settings", on_delete=models.CASCADE) # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notification_settings', on_delete=models.CASCADE) # allow_push = models.BooleanField(default=True) # allow_email = models.BooleanField(default=True) # # class Meta: # unique_together = ('notification_type', 'user') # ordering = ['-created'] # # def __unicode__(self): # return "{}: {}".format(self.user, self.notification_type) # # def name(self): # return "{}: {}".format(self.user, self.notification_type) # # class NotificationType(CachingMixin, CoreModel): # name = models.CharField(max_length=32) # slug = models.SlugField(unique=True) # description = models.CharField(max_length=255) # is_active = models.BooleanField(default=True) # # objects = CachingManager() # # def __unicode__(self): # return "{}".format(self.name) . Output only the next line.
NotificationSetting.objects.get_or_create(notification_type=notification_type, user=user)
Using the snippet: <|code_start|> __author__ = 'rudolphmutter' User = get_user_model() class Command(BaseCommand): args = '' help = 'Creates missing notification settings for existing users' def handle(self, *args, **options): for user in User.objects.all(): <|code_end|> , determine the next line of code. You have imports: from django.contrib.auth import get_user_model from django.core.management import BaseCommand from yak.rest_notifications.models import NotificationSetting, NotificationType and context (class names, function names, or code) available: # Path: yak/rest_notifications/models.py # class NotificationSetting(CoreModel): # notification_type = models.ForeignKey(NotificationType, related_name="user_settings", on_delete=models.CASCADE) # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notification_settings', on_delete=models.CASCADE) # allow_push = models.BooleanField(default=True) # allow_email = models.BooleanField(default=True) # # class Meta: # unique_together = ('notification_type', 'user') # ordering = ['-created'] # # def __unicode__(self): # return "{}: {}".format(self.user, self.notification_type) # # def name(self): # return "{}: {}".format(self.user, self.notification_type) # # class NotificationType(CachingMixin, CoreModel): # name = models.CharField(max_length=32) # slug = models.SlugField(unique=True) # description = models.CharField(max_length=255) # is_active = models.BooleanField(default=True) # # objects = CachingManager() # # def __unicode__(self): # return "{}".format(self.name) . Output only the next line.
for notification_type in NotificationType.objects.all():
Using the snippet: <|code_start|> class ProjectUserViewSet(SocialUserViewSet): serializer_class = ProjectUserSerializer class PostViewSet(viewsets.ModelViewSet, SocialShareMixin): serializer_class = PostSerializer <|code_end|> , determine the next line of code. You have imports: from rest_framework import viewsets from test_project.test_app.models import Post, Article from yak.rest_social_auth.views import SocialShareMixin from yak.rest_social_network.views import SocialUserViewSet from test_project.test_app.api.serializers import ProjectUserSerializer, PostSerializer, ArticleSerializer and context (class names, function names, or code) available: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # class Article(CoreModel): # title = models.CharField(max_length=60) # body = models.TextField() # thumbnail = models.ImageField(upload_to="article_photos/thumbnail/", blank=True, null=True) # likes = GenericRelation(Like) # notifications = GenericRelation(Notification) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def identifier(self): # return "{}".format(self.title) # # Path: yak/rest_social_auth/views.py # class SocialShareMixin(object): # # @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) # def social_share(self, request, pk): # try: # user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) # social_obj = self.get_object() # post_social_media(user_social_auth, social_obj) # return Response({'status': 'success'}) # except UserSocialAuth.DoesNotExist: # raise AuthenticationFailed("User is not authenticated with {}".format(request.data['provider'])) # # Path: yak/rest_social_network/views.py # class SocialUserViewSet(UserViewSet): # serializer_class = UserSerializer # # @detail_route(methods=['get']) # def following(self, request, pk): # requested_user = User.objects.get(pk=pk) # following = requested_user.user_following() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(following) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(following, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # @detail_route(methods=['get']) # def followers(self, request, pk): # requested_user = User.objects.get(pk=pk) # followers = requested_user.user_followers() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(followers) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(followers, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # Path: test_project/test_app/api/serializers.py # class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): # class Meta: # model = User # fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', # 'about', 'user_following_count', 'user_followers_count', 'follow_id') # # follow_id = serializers.SerializerMethodField() # # class PostSerializer(YAKModelSerializer, LikedMixin): # user = ProjectUserSerializer(read_only=True, default=serializers.CurrentUserDefault()) # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'user', 'title', 'description', 'thumbnail', 'liked_id') # # class ArticleSerializer(YAKModelSerializer, LikedMixin): # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'title', 'thumbnail', 'liked_id') . Output only the next line.
queryset = Post.objects.all()
Given the following code snippet before the placeholder: <|code_start|> class ProjectUserViewSet(SocialUserViewSet): serializer_class = ProjectUserSerializer class PostViewSet(viewsets.ModelViewSet, SocialShareMixin): serializer_class = PostSerializer queryset = Post.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer <|code_end|> , predict the next line using imports from the current file: from rest_framework import viewsets from test_project.test_app.models import Post, Article from yak.rest_social_auth.views import SocialShareMixin from yak.rest_social_network.views import SocialUserViewSet from test_project.test_app.api.serializers import ProjectUserSerializer, PostSerializer, ArticleSerializer and context including class names, function names, and sometimes code from other files: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # class Article(CoreModel): # title = models.CharField(max_length=60) # body = models.TextField() # thumbnail = models.ImageField(upload_to="article_photos/thumbnail/", blank=True, null=True) # likes = GenericRelation(Like) # notifications = GenericRelation(Notification) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def identifier(self): # return "{}".format(self.title) # # Path: yak/rest_social_auth/views.py # class SocialShareMixin(object): # # @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) # def social_share(self, request, pk): # try: # user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) # social_obj = self.get_object() # post_social_media(user_social_auth, social_obj) # return Response({'status': 'success'}) # except UserSocialAuth.DoesNotExist: # raise AuthenticationFailed("User is not authenticated with {}".format(request.data['provider'])) # # Path: yak/rest_social_network/views.py # class SocialUserViewSet(UserViewSet): # serializer_class = UserSerializer # # @detail_route(methods=['get']) # def following(self, request, pk): # requested_user = User.objects.get(pk=pk) # following = requested_user.user_following() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(following) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(following, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # @detail_route(methods=['get']) # def followers(self, request, pk): # requested_user = User.objects.get(pk=pk) # followers = requested_user.user_followers() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(followers) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(followers, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # Path: test_project/test_app/api/serializers.py # class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): # class Meta: # model = User # fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', # 'about', 'user_following_count', 'user_followers_count', 'follow_id') # # follow_id = serializers.SerializerMethodField() # # class PostSerializer(YAKModelSerializer, LikedMixin): # user = ProjectUserSerializer(read_only=True, default=serializers.CurrentUserDefault()) # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'user', 'title', 'description', 'thumbnail', 'liked_id') # # class ArticleSerializer(YAKModelSerializer, LikedMixin): # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'title', 'thumbnail', 'liked_id') . Output only the next line.
queryset = Article.objects.all()
Predict the next line for this snippet: <|code_start|> class ProjectUserViewSet(SocialUserViewSet): serializer_class = ProjectUserSerializer class PostViewSet(viewsets.ModelViewSet, SocialShareMixin): <|code_end|> with the help of current file imports: from rest_framework import viewsets from test_project.test_app.models import Post, Article from yak.rest_social_auth.views import SocialShareMixin from yak.rest_social_network.views import SocialUserViewSet from test_project.test_app.api.serializers import ProjectUserSerializer, PostSerializer, ArticleSerializer and context from other files: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # class Article(CoreModel): # title = models.CharField(max_length=60) # body = models.TextField() # thumbnail = models.ImageField(upload_to="article_photos/thumbnail/", blank=True, null=True) # likes = GenericRelation(Like) # notifications = GenericRelation(Notification) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def identifier(self): # return "{}".format(self.title) # # Path: yak/rest_social_auth/views.py # class SocialShareMixin(object): # # @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) # def social_share(self, request, pk): # try: # user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) # social_obj = self.get_object() # post_social_media(user_social_auth, social_obj) # return Response({'status': 'success'}) # except UserSocialAuth.DoesNotExist: # raise AuthenticationFailed("User is not authenticated with {}".format(request.data['provider'])) # # Path: yak/rest_social_network/views.py # class SocialUserViewSet(UserViewSet): # serializer_class = UserSerializer # # @detail_route(methods=['get']) # def following(self, request, pk): # requested_user = User.objects.get(pk=pk) # following = requested_user.user_following() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(following) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(following, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # @detail_route(methods=['get']) # def followers(self, request, pk): # requested_user = User.objects.get(pk=pk) # followers = requested_user.user_followers() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(followers) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(followers, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # Path: test_project/test_app/api/serializers.py # class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): # class Meta: # model = User # fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', # 'about', 'user_following_count', 'user_followers_count', 'follow_id') # # follow_id = serializers.SerializerMethodField() # # class PostSerializer(YAKModelSerializer, LikedMixin): # user = ProjectUserSerializer(read_only=True, default=serializers.CurrentUserDefault()) # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'user', 'title', 'description', 'thumbnail', 'liked_id') # # class ArticleSerializer(YAKModelSerializer, LikedMixin): # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'title', 'thumbnail', 'liked_id') , which may contain function names, class names, or code. Output only the next line.
serializer_class = PostSerializer
Using the snippet: <|code_start|> class ProjectUserViewSet(SocialUserViewSet): serializer_class = ProjectUserSerializer class PostViewSet(viewsets.ModelViewSet, SocialShareMixin): serializer_class = PostSerializer queryset = Post.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) class ArticleViewSet(viewsets.ModelViewSet): <|code_end|> , determine the next line of code. You have imports: from rest_framework import viewsets from test_project.test_app.models import Post, Article from yak.rest_social_auth.views import SocialShareMixin from yak.rest_social_network.views import SocialUserViewSet from test_project.test_app.api.serializers import ProjectUserSerializer, PostSerializer, ArticleSerializer and context (class names, function names, or code) available: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # class Article(CoreModel): # title = models.CharField(max_length=60) # body = models.TextField() # thumbnail = models.ImageField(upload_to="article_photos/thumbnail/", blank=True, null=True) # likes = GenericRelation(Like) # notifications = GenericRelation(Notification) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def identifier(self): # return "{}".format(self.title) # # Path: yak/rest_social_auth/views.py # class SocialShareMixin(object): # # @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) # def social_share(self, request, pk): # try: # user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) # social_obj = self.get_object() # post_social_media(user_social_auth, social_obj) # return Response({'status': 'success'}) # except UserSocialAuth.DoesNotExist: # raise AuthenticationFailed("User is not authenticated with {}".format(request.data['provider'])) # # Path: yak/rest_social_network/views.py # class SocialUserViewSet(UserViewSet): # serializer_class = UserSerializer # # @detail_route(methods=['get']) # def following(self, request, pk): # requested_user = User.objects.get(pk=pk) # following = requested_user.user_following() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(following) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(following, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # @detail_route(methods=['get']) # def followers(self, request, pk): # requested_user = User.objects.get(pk=pk) # followers = requested_user.user_followers() # # if drf_version[0] >= 3 and drf_version[1] < 1: # result_page = self.paginate_queryset(followers) # else: # paginator = FollowViewSet().paginator # result_page = paginator.paginate_queryset(followers, request) # # serializer = FollowSerializer(instance=result_page, many=True, context={'request': request}) # return Response(serializer.data) # # Path: test_project/test_app/api/serializers.py # class ProjectUserSerializer(FollowedMixin, AuthSerializerMixin, YAKModelSerializer): # class Meta: # model = User # fields = ('email', 'id', 'username', 'fullname', 'thumbnail', 'original_photo', 'small_photo', 'large_photo', # 'about', 'user_following_count', 'user_followers_count', 'follow_id') # # follow_id = serializers.SerializerMethodField() # # class PostSerializer(YAKModelSerializer, LikedMixin): # user = ProjectUserSerializer(read_only=True, default=serializers.CurrentUserDefault()) # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'user', 'title', 'description', 'thumbnail', 'liked_id') # # class ArticleSerializer(YAKModelSerializer, LikedMixin): # liked_id = serializers.SerializerMethodField() # # class Meta: # model = Post # fields = ('id', 'title', 'thumbnail', 'liked_id') . Output only the next line.
serializer_class = ArticleSerializer
Given the code snippet: <|code_start|> class Facebook(ExtraActionsAbstractMixin, ExtraDataAbstractMixin, FacebookOAuth2): @staticmethod def save_extra_data(response, user): if 'email' in response: user.email = response['email'] # TODO: better placement of Location model. What do we do with Twitter or other locations? # if 'location' in response: # if not user.location: # Location.objects.create(name=response["location"]["name"], facebook_id=response["location"]["id"]) # else: # location = user.location # location.name = response['location']['name'] # location.facebook_id = response['location']['id'] if 'bio' in response: user.about = response['bio'] user.save() @staticmethod def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): image_url = "https://graph.facebook.com/{}/picture?width=1000&height=1000".format(uid) return image_url @staticmethod def post(user_social_auth, social_obj): graph = facebook.GraphAPI(user_social_auth.extra_data['access_token']) <|code_end|> , generate the next line using the imports in this file: from django.contrib.auth import get_user_model from social_core.backends.facebook import FacebookOAuth2 from yak.rest_social_auth.backends.base import ExtraDataAbstractMixin, ExtraActionsAbstractMixin from yak.settings import yak_settings import facebook and context (functions, classes, or occasionally code) from other files: # Path: yak/rest_social_auth/backends/base.py # class ExtraDataAbstractMixin(object, metaclass=abc.ABCMeta): # """ # Ensure that backends define these methods. Used in pipeline to save extra data on the user model. # """ # # @abc.abstractmethod # def save_extra_data(response, user): # return # # @abc.abstractmethod # def get_profile_image(strategy, details, response, uid, user, social, is_new=False, *args, **kwargs): # return # # class ExtraActionsAbstractMixin(object, metaclass=abc.ABCMeta): # # @abc.abstractmethod # def post(user_social_auth, social_obj): # return # # @abc.abstractmethod # def get_friends(user_social_auth): # return # # Path: yak/settings.py # def perform_import(val, setting_name): # def __getattr__(self, attr): # class YAKAPISettings(APISettings): # USER_SETTINGS = getattr(settings, 'YAK', None) # DEFAULTS = { # 'USER_APP_LABEL': 'test_app', # 'USER_MODEL': 'user', # 'USER_SERIALIZER': "test_app.api.serializers.UserSerializer", # 'API_SCHEMA': 'api-schema-1.0.json', # 'SOCIAL_MODEL': "test_app.models.Post", # 'ALLOW_EMAIL': True, # 'ALLOW_PUSH': True, # 'EMAIL_NOTIFICATION_SUBJECT': 'Test Project Notification', # 'PUSHWOOSH_AUTH_TOKEN': "", # 'PUSHWOOSH_APP_CODE': "", # 'PUSH_NOTIFICATION_HANDLER': "yak.rest_notifications.utils.send_pushwoosh_notification", # 'SOCIAL_SHARE_DELAY': 60, # 'USE_FACEBOOK_OG': False, # 'FACEBOOK_OG_NAMESPACE': "", # 'SERIALIZER_MAPPING': {}, # 'FLAKE8_CONFIG': None, # } # IMPORT_STRINGS = ( # "USER_SERIALIZER", # "SOCIAL_MODEL", # "SERIALIZER_MAPPING", # ) . Output only the next line.
if yak_settings.USE_FACEBOOK_OG:
Next line prediction: <|code_start|> status=status.HTTP_400_BAD_REQUEST) if user and user.is_active: # if the access token was set to an empty string, then save the access token from the request auth_created = user.social_auth.get(provider=provider) if not auth_created.extra_data['access_token']: auth_created.extra_data['access_token'] = token auth_created.save() # Allow client to send up password to complete auth flow if not authed_user and 'password' in request.data: password = base64.decodestring(request.data['password']) user.set_password(password) user.save() # Set instance since we are not calling `serializer.save()` serializer.instance = user headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: return Response({"errors": "Error with social authentication"}, status=status.HTTP_400_BAD_REQUEST) class SocialShareMixin(object): @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) def social_share(self, request, pk): try: user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) social_obj = self.get_object() <|code_end|> . Use current file imports: (import base64 from django.conf import settings from django.contrib.auth import get_user_model from rest_framework import status, generics from rest_framework.decorators import detail_route from rest_framework.exceptions import AuthenticationFailed from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from social_django.utils import load_strategy from social_django.models import UserSocialAuth from social_django.utils import load_backend from social_core.backends.oauth import BaseOAuth1, BaseOAuth2 from social_core.backends.utils import get_backend from social_core.exceptions import AuthAlreadyAssociated from yak.rest_social_auth.serializers import SocialSignUpSerializer from yak.rest_social_auth.utils import post_social_media from yak.rest_user.serializers import UserSerializer from yak.rest_user.views import SignUp) and context including class names, function names, or small code snippets from other files: # Path: yak/rest_social_auth/serializers.py # class SocialSignUpSerializer(AuthSerializerMixin, LoginSerializer): # fullname = serializers.CharField(read_only=True) # username = serializers.CharField(read_only=True) # email = serializers.EmailField(read_only=True) # # class Meta: # model = User # fields = ('fullname', 'username', 'email') # write_only_fields = ('access_token', 'access_token_secret') # # Path: yak/rest_social_auth/utils.py # @task # def post_social_media(user_social_auth, social_obj): # backend = get_backend(settings.AUTHENTICATION_BACKENDS, user_social_auth.provider) # backend.post(user_social_auth, social_obj) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) # # Path: yak/rest_user/views.py # class SignUp(generics.CreateAPIView): # queryset = User.objects.all() # serializer_class = SignUpSerializer # permission_classes = (IsAuthenticatedOrCreate,) . Output only the next line.
post_social_media(user_social_auth, social_obj)
Next line prediction: <|code_start|> # Allow client to send up password to complete auth flow if not authed_user and 'password' in request.data: password = base64.decodestring(request.data['password']) user.set_password(password) user.save() # Set instance since we are not calling `serializer.save()` serializer.instance = user headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) else: return Response({"errors": "Error with social authentication"}, status=status.HTTP_400_BAD_REQUEST) class SocialShareMixin(object): @detail_route(methods=['post'], permission_classes=[IsAuthenticated]) def social_share(self, request, pk): try: user_social_auth = UserSocialAuth.objects.get(user=request.user, provider=request.data['provider']) social_obj = self.get_object() post_social_media(user_social_auth, social_obj) return Response({'status': 'success'}) except UserSocialAuth.DoesNotExist: raise AuthenticationFailed("User is not authenticated with {}".format(request.data['provider'])) class SocialFriends(generics.ListAPIView): queryset = User.objects.all() <|code_end|> . Use current file imports: (import base64 from django.conf import settings from django.contrib.auth import get_user_model from rest_framework import status, generics from rest_framework.decorators import detail_route from rest_framework.exceptions import AuthenticationFailed from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from social_django.utils import load_strategy from social_django.models import UserSocialAuth from social_django.utils import load_backend from social_core.backends.oauth import BaseOAuth1, BaseOAuth2 from social_core.backends.utils import get_backend from social_core.exceptions import AuthAlreadyAssociated from yak.rest_social_auth.serializers import SocialSignUpSerializer from yak.rest_social_auth.utils import post_social_media from yak.rest_user.serializers import UserSerializer from yak.rest_user.views import SignUp) and context including class names, function names, or small code snippets from other files: # Path: yak/rest_social_auth/serializers.py # class SocialSignUpSerializer(AuthSerializerMixin, LoginSerializer): # fullname = serializers.CharField(read_only=True) # username = serializers.CharField(read_only=True) # email = serializers.EmailField(read_only=True) # # class Meta: # model = User # fields = ('fullname', 'username', 'email') # write_only_fields = ('access_token', 'access_token_secret') # # Path: yak/rest_social_auth/utils.py # @task # def post_social_media(user_social_auth, social_obj): # backend = get_backend(settings.AUTHENTICATION_BACKENDS, user_social_auth.provider) # backend.post(user_social_auth, social_obj) # # Path: yak/rest_user/serializers.py # class UserSerializer(AuthSerializerMixin, YAKModelSerializer): # # def __new__(cls, *args, **kwargs): # """ # Can't just inherit in the class definition due to lots of import issues # """ # return yak_settings.USER_SERIALIZER(*args, **kwargs) # # Path: yak/rest_user/views.py # class SignUp(generics.CreateAPIView): # queryset = User.objects.all() # serializer_class = SignUpSerializer # permission_classes = (IsAuthenticatedOrCreate,) . Output only the next line.
serializer_class = UserSerializer
Using the snippet: <|code_start|> class Meta: model = User email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n)) username = factory.Sequence(lambda n: 'person{0}'.format(n)) @staticmethod def get_test_application(): application, created = Application.objects.get_or_create( client_type=Application.CLIENT_PUBLIC, name="Test App", authorization_grant_type=Application.GRANT_PASSWORD, ) return application @classmethod def _create(cls, model_class, *args, **kwargs): user = super(UserFactory, cls)._create(model_class, *args, **kwargs) application = cls.get_test_application() AccessToken.objects.create( user=user, application=application, token='token{}'.format(user.id), expires=now() + datetime.timedelta(days=1) ) return user class PostFactory(factory.DjangoModelFactory): class Meta: <|code_end|> , determine the next line of code. You have imports: import factory import datetime from test_project.test_app.models import Post from django.utils.timezone import now from oauth2_provider.models import AccessToken, Application from django.contrib.auth import get_user_model from yak.rest_social_network.models import Comment and context (class names, function names, or code) available: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # Path: yak/rest_social_network/models.py # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] . Output only the next line.
model = Post
Here is a snippet: <|code_start|> client_type=Application.CLIENT_PUBLIC, name="Test App", authorization_grant_type=Application.GRANT_PASSWORD, ) return application @classmethod def _create(cls, model_class, *args, **kwargs): user = super(UserFactory, cls)._create(model_class, *args, **kwargs) application = cls.get_test_application() AccessToken.objects.create( user=user, application=application, token='token{}'.format(user.id), expires=now() + datetime.timedelta(days=1) ) return user class PostFactory(factory.DjangoModelFactory): class Meta: model = Post user = factory.SubFactory(UserFactory) title = "Factory-farmed post" description = "I love Yeti App Kit!" class CommentFactory(factory.DjangoModelFactory): class Meta: <|code_end|> . Write the next line using the current file imports: import factory import datetime from test_project.test_app.models import Post from django.utils.timezone import now from oauth2_provider.models import AccessToken, Application from django.contrib.auth import get_user_model from yak.rest_social_network.models import Comment and context from other files: # Path: test_project/test_app/models.py # class Post(BaseSocialModel): # user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) # title = models.CharField(max_length=100, null=True, blank=True) # description = models.TextField(blank=True, null=True) # thumbnail = models.ImageField(upload_to="post_photos/thumbnail/", blank=True, null=True) # # TAG_FIELD = 'description' # # likes = GenericRelation(Like) # flags = GenericRelation(Flag) # shares = GenericRelation(Share) # related_tags = models.ManyToManyField(Tag, blank=True) # comments = GenericRelation(Comment) # notifications = GenericRelation(Notification) # # def likes_count(self): # return self.likes.count() # # def comments_count(self): # return self.comments.count() # # def identifier(self): # return "{}".format(self.title) # # def __unicode__(self): # return "{}".format(self.title) if self.title else "Untitled" # # def url(self): # current_site = Site.objects.get_current() # return "http://{0}/{1}/{2}/".format(current_site.domain, "post", base62.encode(self.pk)) # # def facebook_og_info(self): # return {'action': 'post', 'object': 'cut', 'url': self.url()} # # def create_social_message(self, provider): # message = "{} published by {} on Test Project".format(self.title, self.user.username) # # # TODO: Sending of messages to post on social media is broken and convoluted at this point, need to refactor # if provider == "twitter": # return "{}".format(message.encode('utf-8')) # else: # return "{} {}".format(message.encode('utf-8'), self.url()) # # Path: yak/rest_social_network/models.py # class Comment(CoreModel): # content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # object_id = models.PositiveIntegerField(db_index=True) # content_object = GenericForeignKey() # # TAG_FIELD = 'description' # related_tags = models.ManyToManyField(Tag, blank=True) # # description = models.TextField() # user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="comments", on_delete=models.CASCADE) # # class Meta: # ordering = ['created'] , which may include functions, classes, or code. Output only the next line.
model = Comment