Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given snippet: <|code_start|>class CSVStorage(FileStorageBase): name = 'csv' extension = 'csv' def load_accounts(self): filename = self.get_accounts_filename() if not os.path.exists(filename): return [] with codecs.open(filename) as f: return map(self._csv_row_to_account, unicodecsv.reader(f)) def load_transactions(self, filename): if not os.path.exists(filename): return [] with codecs.open(filename) as f: return map(self._csv_row_to_transaction, unicodecsv.reader(f)) def save_accounts(self, accounts): with codecs.open(self.get_accounts_filename(), 'w') as f: writer = unicodecsv.writer(f) for acc in accounts: writer.writerow(acc) def save_transactions(self, transactions, filename): with codecs.open(filename, 'w') as f: writer = unicodecsv.writer(f) for tx in transactions: writer.writerow(self._transaction_to_csv_row(tx)) def _csv_row_to_account(self, row): <|code_end|> , continue by predicting the next line. Consider current file imports: import os, json, inspect, unicodecsv, codecs, datetime, re from .data import Account, Transaction, period_to_months, filter_transactions_period and context: # Path: budgettracker/data.py # class Account(namedtuple('Account', ['id', 'title', 'amount'])): # @classmethod # def from_dict(cls, dct): # return cls(**dct) # # def update(self, **kwargs): # return Account(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'title': self.title, # 'amount': self.amount # } # # class Transaction(namedtuple('Transaction', ['id', 'label', 'date', 'amount', 'account', 'categories', 'goal'])): # @classmethod # def from_dict(cls, dct): # return cls( # id=dct['id'], # label=dct['label'], # date=datetime.datetime.strptime(dct['date'], "%Y-%m-%d").date(), # amount=float(dct['amount']), # account=dct['account'], # categories=dct.get('categories') or [], # goal=dct.get('goal') # ) # # def update(self, **kwargs): # return Transaction(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'label': self.label, # 'date': self.date.isoformat(), # 'amount': self.amount, # 'account': self.account, # 'categories': self.categories, # 'goal': self.goal # } # # def to_str(self, famount): # return u"%s - %s = %s%s%s" % (self.date.isoformat(), self.label, famount(self.amount), # ' #%s' % ', #'.join(self.categories) if self.categories else '', # ' [%s%s]' % (famount(self.goal)) if self.goal else '') # # def __unicode__(self): # return self.to_str() # # def period_to_months(start_date, end_date): # dates = [start_date.replace(day=1)] # end_date = end_date.replace(day=1) - monthdelta(1) # while dates[-1] < end_date: # dates.append(dates[-1] + monthdelta(1)) # return dates # # def filter_transactions_period(transactions, start_date=None, end_date=None): # if not start_date and not end_date: # return transactions # return filter( # lambda tx: (not start_date or tx.date >= start_date) and (not end_date or tx.date < end_date), # transactions) which might include code, classes, or functions. Output only the next line.
return Account(row[0], row[1], float(row[2]))
Using the snippet: <|code_start|> def load_accounts(self): filename = self.get_accounts_filename() if not os.path.exists(filename): return [] with codecs.open(filename) as f: return map(self._csv_row_to_account, unicodecsv.reader(f)) def load_transactions(self, filename): if not os.path.exists(filename): return [] with codecs.open(filename) as f: return map(self._csv_row_to_transaction, unicodecsv.reader(f)) def save_accounts(self, accounts): with codecs.open(self.get_accounts_filename(), 'w') as f: writer = unicodecsv.writer(f) for acc in accounts: writer.writerow(acc) def save_transactions(self, transactions, filename): with codecs.open(filename, 'w') as f: writer = unicodecsv.writer(f) for tx in transactions: writer.writerow(self._transaction_to_csv_row(tx)) def _csv_row_to_account(self, row): return Account(row[0], row[1], float(row[2])) def _csv_row_to_transaction(self, row): <|code_end|> , determine the next line of code. You have imports: import os, json, inspect, unicodecsv, codecs, datetime, re from .data import Account, Transaction, period_to_months, filter_transactions_period and context (class names, function names, or code) available: # Path: budgettracker/data.py # class Account(namedtuple('Account', ['id', 'title', 'amount'])): # @classmethod # def from_dict(cls, dct): # return cls(**dct) # # def update(self, **kwargs): # return Account(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'title': self.title, # 'amount': self.amount # } # # class Transaction(namedtuple('Transaction', ['id', 'label', 'date', 'amount', 'account', 'categories', 'goal'])): # @classmethod # def from_dict(cls, dct): # return cls( # id=dct['id'], # label=dct['label'], # date=datetime.datetime.strptime(dct['date'], "%Y-%m-%d").date(), # amount=float(dct['amount']), # account=dct['account'], # categories=dct.get('categories') or [], # goal=dct.get('goal') # ) # # def update(self, **kwargs): # return Transaction(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'label': self.label, # 'date': self.date.isoformat(), # 'amount': self.amount, # 'account': self.account, # 'categories': self.categories, # 'goal': self.goal # } # # def to_str(self, famount): # return u"%s - %s = %s%s%s" % (self.date.isoformat(), self.label, famount(self.amount), # ' #%s' % ', #'.join(self.categories) if self.categories else '', # ' [%s%s]' % (famount(self.goal)) if self.goal else '') # # def __unicode__(self): # return self.to_str() # # def period_to_months(start_date, end_date): # dates = [start_date.replace(day=1)] # end_date = end_date.replace(day=1) - monthdelta(1) # while dates[-1] < end_date: # dates.append(dates[-1] + monthdelta(1)) # return dates # # def filter_transactions_period(transactions, start_date=None, end_date=None): # if not start_date and not end_date: # return transactions # return filter( # lambda tx: (not start_date or tx.date >= start_date) and (not end_date or tx.date < end_date), # transactions) . Output only the next line.
return Transaction(row[0], row[1], datetime.datetime.strptime(row[2], "%Y-%m-%d").date(),
Based on the snippet: <|code_start|> def get_storage(name): for o in globals().values(): if inspect.isclass(o) and issubclass(o, StorageBase) and o is not StorageBase and o.name == name: return o class StorageBase(object): def __init__(self, config): self.config = config def load_accounts(self): raise NotImplementedError def save_accounts(self, accounts): raise NotImplementedError def load_monthly_transactions(self, date): raise NotImplementedError def save_monthly_transactions(self, date, transactions): raise NotImplementedError def load_period_transactions(self, start_date, end_date): transactions = [] <|code_end|> , predict the immediate next line with the help of imports: import os, json, inspect, unicodecsv, codecs, datetime, re from .data import Account, Transaction, period_to_months, filter_transactions_period and context (classes, functions, sometimes code) from other files: # Path: budgettracker/data.py # class Account(namedtuple('Account', ['id', 'title', 'amount'])): # @classmethod # def from_dict(cls, dct): # return cls(**dct) # # def update(self, **kwargs): # return Account(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'title': self.title, # 'amount': self.amount # } # # class Transaction(namedtuple('Transaction', ['id', 'label', 'date', 'amount', 'account', 'categories', 'goal'])): # @classmethod # def from_dict(cls, dct): # return cls( # id=dct['id'], # label=dct['label'], # date=datetime.datetime.strptime(dct['date'], "%Y-%m-%d").date(), # amount=float(dct['amount']), # account=dct['account'], # categories=dct.get('categories') or [], # goal=dct.get('goal') # ) # # def update(self, **kwargs): # return Transaction(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'label': self.label, # 'date': self.date.isoformat(), # 'amount': self.amount, # 'account': self.account, # 'categories': self.categories, # 'goal': self.goal # } # # def to_str(self, famount): # return u"%s - %s = %s%s%s" % (self.date.isoformat(), self.label, famount(self.amount), # ' #%s' % ', #'.join(self.categories) if self.categories else '', # ' [%s%s]' % (famount(self.goal)) if self.goal else '') # # def __unicode__(self): # return self.to_str() # # def period_to_months(start_date, end_date): # dates = [start_date.replace(day=1)] # end_date = end_date.replace(day=1) - monthdelta(1) # while dates[-1] < end_date: # dates.append(dates[-1] + monthdelta(1)) # return dates # # def filter_transactions_period(transactions, start_date=None, end_date=None): # if not start_date and not end_date: # return transactions # return filter( # lambda tx: (not start_date or tx.date >= start_date) and (not end_date or tx.date < end_date), # transactions) . Output only the next line.
for date in period_to_months(start_date, end_date):
Given the following code snippet before the placeholder: <|code_start|> def get_storage(name): for o in globals().values(): if inspect.isclass(o) and issubclass(o, StorageBase) and o is not StorageBase and o.name == name: return o class StorageBase(object): def __init__(self, config): self.config = config def load_accounts(self): raise NotImplementedError def save_accounts(self, accounts): raise NotImplementedError def load_monthly_transactions(self, date): raise NotImplementedError def save_monthly_transactions(self, date, transactions): raise NotImplementedError def load_period_transactions(self, start_date, end_date): transactions = [] for date in period_to_months(start_date, end_date): transactions.extend(self.load_monthly_transactions(date)) <|code_end|> , predict the next line using imports from the current file: import os, json, inspect, unicodecsv, codecs, datetime, re from .data import Account, Transaction, period_to_months, filter_transactions_period and context including class names, function names, and sometimes code from other files: # Path: budgettracker/data.py # class Account(namedtuple('Account', ['id', 'title', 'amount'])): # @classmethod # def from_dict(cls, dct): # return cls(**dct) # # def update(self, **kwargs): # return Account(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'title': self.title, # 'amount': self.amount # } # # class Transaction(namedtuple('Transaction', ['id', 'label', 'date', 'amount', 'account', 'categories', 'goal'])): # @classmethod # def from_dict(cls, dct): # return cls( # id=dct['id'], # label=dct['label'], # date=datetime.datetime.strptime(dct['date'], "%Y-%m-%d").date(), # amount=float(dct['amount']), # account=dct['account'], # categories=dct.get('categories') or [], # goal=dct.get('goal') # ) # # def update(self, **kwargs): # return Transaction(**dict(self._asdict(), **kwargs)) # # def to_dict(self): # return { # 'id': self.id, # 'label': self.label, # 'date': self.date.isoformat(), # 'amount': self.amount, # 'account': self.account, # 'categories': self.categories, # 'goal': self.goal # } # # def to_str(self, famount): # return u"%s - %s = %s%s%s" % (self.date.isoformat(), self.label, famount(self.amount), # ' #%s' % ', #'.join(self.categories) if self.categories else '', # ' [%s%s]' % (famount(self.goal)) if self.goal else '') # # def __unicode__(self): # return self.to_str() # # def period_to_months(start_date, end_date): # dates = [start_date.replace(day=1)] # end_date = end_date.replace(day=1) - monthdelta(1) # while dates[-1] < end_date: # dates.append(dates[-1] + monthdelta(1)) # return dates # # def filter_transactions_period(transactions, start_date=None, end_date=None): # if not start_date and not end_date: # return transactions # return filter( # lambda tx: (not start_date or tx.date >= start_date) and (not end_date or tx.date < end_date), # transactions) . Output only the next line.
return filter_transactions_period(transactions, start_date, end_date)
Based on the snippet: <|code_start|> class Command(BaseCommand): help = "Create set of new pastes" args = "[how many]" def handle(self, how_many=100, **options): for i in range(int(how_many)): <|code_end|> , predict the immediate next line with the help of imports: from django.core.management.base import BaseCommand from apps.wklej.models import Wklejka from wklej.populate import wklejka and context (classes, functions, sometimes code) from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) . Output only the next line.
w = Wklejka(**wklejka())
Based on the snippet: <|code_start|> def get_txt(self, obj): url = obj.get_txt_url() response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertEquals(response._headers['content-type'], ('Content-Type', 'text/plain; charset=utf-8')) def get_dl(self, obj): url = obj.get_download_url() response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertEquals( response._headers['content-type'], ('Content-Type', 'application/x-force-download') ) def get_del(self, obj): self.client.login(username='joe', password='doe') url = obj.get_del_url() response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "delete.html") def post_del(self, obj): self.client.login(username='joe', password='doe') url = obj.get_del_url() response = self.client.post(url, {"yes": "true"}) self.assertEquals(response.status_code, 302) <|code_end|> , predict the immediate next line with the help of imports: from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User from apps.wklej.models import Wklejka from apps.userstuff.models import UserProfile and context (classes, functions, sometimes code) from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt . Output only the next line.
new_obj = Wklejka.objects.get(pk=obj.id)
Based on the snippet: <|code_start|> def test_private_url(self): w = Wklejka(is_private=True, hash="foobar", user=self.user) w.save() self.get(w) self.get_txt(w) self.get_dl(w) self.get_del(w) self.post_del(w) def test_banned_lexer(self): w = Wklejka(syntax="raw") w.save() self.get(w) def test_re(self): w = Wklejka() w.save() url = reverse("reply", kwargs={"id": w.id}) response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "homepage.html") def test_own(self): url = reverse("own") self.client.login(username='joe', password='doe') response = self.client.get(url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "wklej/list.html") def test_salt(self): <|code_end|> , predict the immediate next line with the help of imports: from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User from apps.wklej.models import Wklejka from apps.userstuff.models import UserProfile and context (classes, functions, sometimes code) from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt . Output only the next line.
userprofile = UserProfile(user=self.user)
Here is a snippet: <|code_start|> class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) display_name = models.CharField(max_length=30) current_salt = models.CharField(max_length=50) def __unicode__(self): return self.user.username def username(self): return self.user.username def get_wklejki(self): return self.user.wklejka_set def generate_new_salt(self): <|code_end|> . Write the next line using the current file imports: from django.db import models from django.contrib.auth.models import User from helpers.helpers import generate_salt and context from other files: # Path: helpers/helpers.py # def generate_salt(): # salt = ''.join([choice(SALT_LEVEL) for i in range(50)]) # return salt , which may include functions, classes, or code. Output only the next line.
new_salt = generate_salt()
Predict the next line after this snippet: <|code_start|> class WklejkaTestCase(TestCase): def test_author(self): user = User(username="joedoe") <|code_end|> using the current file's imports: from apps.wklej.models import Wklejka from django.contrib.auth.models import User from django.test import TestCase and any relevant context from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) . Output only the next line.
self.wklejka = Wklejka(
Predict the next line after this snippet: <|code_start|>#coding: utf-8 def single(request, id=0, hash=''): """ This is very important view because it displays a single paste. It's actually the most viewed view ever """ if id: <|code_end|> using the current file's imports: from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from wklej.forms import RotateSyntaxForm from wklej.forms import WklejkaForm from apps.wklej.models import Wklejka, BANNED_LEXERS and any relevant context from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # BANNED_LEXERS = [ # 'antlr-objc', # 'raw', # 'c-objdump', # 'opa', # ] . Output only the next line.
w = get_object_or_404(Wklejka, pk=id, is_private=False)
Continue the code snippet: <|code_start|>#coding: utf-8 def single(request, id=0, hash=''): """ This is very important view because it displays a single paste. It's actually the most viewed view ever """ if id: w = get_object_or_404(Wklejka, pk=id, is_private=False) elif hash: w = get_object_or_404(Wklejka, hash=hash, is_private=True) hl = request.GET.get('hl', w.syntax) or w.guessed_syntax or 'python' <|code_end|> . Use current file imports: from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.http import HttpResponse from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from wklej.forms import RotateSyntaxForm from wklej.forms import WklejkaForm from apps.wklej.models import Wklejka, BANNED_LEXERS and context (classes, functions, or code) from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # BANNED_LEXERS = [ # 'antlr-objc', # 'raw', # 'c-objdump', # 'opa', # ] . Output only the next line.
if hl in BANNED_LEXERS:
Based on the snippet: <|code_start|>dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Py 2.5 # model def rpc_handler(request): """ the actual handler: if you setup your urls.py properly, all calls to the xml-rpc service should be routed through here. If post data is defined, it assumes it's XML-RPC and tries to process as such Empty post assumes you're viewing from a browser and tells you about the service. """ response = HttpResponse() if len(request.POST): response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) else: response.write("<b>This is an XML-RPC Service.</b><br>") #methods = dispatcher.system_listMethods() response['Content-length'] = str(len(response.content)) return response def dodaj_wpis(tresc, syntax, autor="Anonim"): """ Pozwala zdalnie dodawac wpisy do wkleja. """ <|code_end|> , predict the immediate next line with the help of imports: import sha import random from SimpleXMLRPCServer import SimpleXMLRPCDispatcher from django.http import HttpResponse from apps.wklej.models import Wklejka from apps.userstuff.models import UserProfile and context (classes, functions, sometimes code) from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt . Output only the next line.
w = Wklejka(nickname=autor, body=tresc, syntax=syntax)
Next line prediction: <|code_start|> """ Pozwala zdalnie dodawac wpisy do wkleja. """ w = Wklejka(nickname=autor, body=tresc, syntax=syntax) w.save() return w.get_absolute_url() def dodaj_prywatny_wpis(tresc, syntax, autor="Anonim"): """ Pozwala zdalnie dodawać prywatne wpisy do wkleja """ w = Wklejka(nickname=autor, body=tresc, syntax=syntax, is_private=True) w.save() salt = sha.new(str(random.random())).hexdigest()[:10] hash = sha.new(salt).hexdigest()[:10] w.hash = hash w.save() return w.get_absolute_url() def auth_dodaj_wpis(tresc, syntax, salt): """ Pozwala zdalnei dodawac wpisy do konta """ try: <|code_end|> . Use current file imports: (import sha import random from SimpleXMLRPCServer import SimpleXMLRPCDispatcher from django.http import HttpResponse from apps.wklej.models import Wklejka from apps.userstuff.models import UserProfile) and context including class names, function names, or small code snippets from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt . Output only the next line.
p = UserProfile.objects.get(current_salt=salt)
Using the snippet: <|code_start|>#coding: utf-8 class WklejAdmin(admin.ModelAdmin): list_display = ['user', 'nickname', 'syntax', 'is_private'] search_fields = ['user', 'nickname', 'comment', 'body', 'ip'] list_filter = ['is_private', 'is_deleted', 'is_spam'] raw_id_fields = ['parent', ] <|code_end|> , determine the next line of code. You have imports: from apps.wklej.models import Wklejka from django.contrib import admin and context (class names, function names, or code) available: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) . Output only the next line.
admin.site.register(Wklejka, WklejAdmin)
Given snippet: <|code_start|>#-*- coding: utf-8 -*- class WklejkaForm(forms.ModelForm): nickname = forms.CharField(required=False) class Meta: <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from apps.wklej.models import Wklejka from lib.antispam import check_for_link_spam from recaptcha_app.fields import ReCaptchaField from apps.wklej.models import LEXERS from django.conf import settings and context: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: lib/antispam.py # def check_for_link_spam(code): # """It's spam if more than 30% of the text are links.""" # spans = [x.span() for x in _link_re.finditer(code)] # if len(spans) > MAX_LINK_PERCENTAGE: # return True # return (sum(starmap(sub, spans)) * -100) / (len(code) or 1) \ # > MAX_LINK_PERCENTAGE # # Path: apps/wklej/models.py # LEXERS = [ # ('python', "Python"), # ('perl', "Perl"), # ('ruby', "Ruby"), # ('c', 'C'), # ('bash', "Bash"), # ('java', "Java"), # ('html+django', "Html+Django"), # ('xml', "XML"), # ('mysql', "MySQL"), # ('cpp', "C++"), # ('js', 'JavaScript'), # ] + sorted([ # (x[1][0], x[0]) for x in all_lexers if x[1][0] not in BANNED_LEXERS # ]) which might include code, classes, or functions. Output only the next line.
model = Wklejka
Next line prediction: <|code_start|>#-*- coding: utf-8 -*- class WklejkaForm(forms.ModelForm): nickname = forms.CharField(required=False) class Meta: model = Wklejka fields = '__all__' def clean_nickname(self): if len(self.cleaned_data['nickname']) == 0: self.cleaned_data['nickname'] = 'Anonim' elif len(self.cleaned_data['nickname']) > 30: self.cleaned_data['nickname'] = self.cleaned_data['nickname'][:29] return self.cleaned_data['nickname'] def clean_body(self): <|code_end|> . Use current file imports: (from django import forms from apps.wklej.models import Wklejka from lib.antispam import check_for_link_spam from recaptcha_app.fields import ReCaptchaField from apps.wklej.models import LEXERS from django.conf import settings) and context including class names, function names, or small code snippets from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: lib/antispam.py # def check_for_link_spam(code): # """It's spam if more than 30% of the text are links.""" # spans = [x.span() for x in _link_re.finditer(code)] # if len(spans) > MAX_LINK_PERCENTAGE: # return True # return (sum(starmap(sub, spans)) * -100) / (len(code) or 1) \ # > MAX_LINK_PERCENTAGE # # Path: apps/wklej/models.py # LEXERS = [ # ('python', "Python"), # ('perl', "Perl"), # ('ruby', "Ruby"), # ('c', 'C'), # ('bash', "Bash"), # ('java', "Java"), # ('html+django', "Html+Django"), # ('xml', "XML"), # ('mysql', "MySQL"), # ('cpp', "C++"), # ('js', 'JavaScript'), # ] + sorted([ # (x[1][0], x[0]) for x in all_lexers if x[1][0] not in BANNED_LEXERS # ]) . Output only the next line.
if settings.USE_CAPTCHA and check_for_link_spam(self.cleaned_data['body']):
Next line prediction: <|code_start|> return self.cleaned_data['nickname'] def clean_body(self): if settings.USE_CAPTCHA and check_for_link_spam(self.cleaned_data['body']): raise forms.ValidationError("This paste looks like spam.") return self.cleaned_data['body'] # TODO: FIXME: Do this with inheritance class WklejkaCaptchaForm(forms.ModelForm): recaptcha = ReCaptchaField() has_captcha = forms.CharField(widget=forms.HiddenInput, required=False) nickname = forms.CharField(required=False) class Meta: model = Wklejka fields = '__all__' def clean_nickname(self): if len(self.cleaned_data['nickname']) == 0: self.cleaned_data['nickname'] = 'Anonim' elif len(self.cleaned_data['nickname']) > 30: self.cleaned_data['nickname'] = self.cleaned_data['autor'][:29] return self.cleaned_data['nickname'] ### To change syntax hilight on "single" page. class RotateSyntaxForm(forms.Form): hl = forms.CharField(max_length=100, label="syntax ", <|code_end|> . Use current file imports: (from django import forms from apps.wklej.models import Wklejka from lib.antispam import check_for_link_spam from recaptcha_app.fields import ReCaptchaField from apps.wklej.models import LEXERS from django.conf import settings) and context including class names, function names, or small code snippets from other files: # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) # # Path: lib/antispam.py # def check_for_link_spam(code): # """It's spam if more than 30% of the text are links.""" # spans = [x.span() for x in _link_re.finditer(code)] # if len(spans) > MAX_LINK_PERCENTAGE: # return True # return (sum(starmap(sub, spans)) * -100) / (len(code) or 1) \ # > MAX_LINK_PERCENTAGE # # Path: apps/wklej/models.py # LEXERS = [ # ('python', "Python"), # ('perl', "Perl"), # ('ruby', "Ruby"), # ('c', 'C'), # ('bash', "Bash"), # ('java', "Java"), # ('html+django', "Html+Django"), # ('xml', "XML"), # ('mysql', "MySQL"), # ('cpp', "C++"), # ('js', 'JavaScript'), # ] + sorted([ # (x[1][0], x[0]) for x in all_lexers if x[1][0] not in BANNED_LEXERS # ]) . Output only the next line.
widget=forms.Select(choices=LEXERS))
Given the code snippet: <|code_start|>#-*- coding: utf-8 -*- def homepage(request): """ This view is responsible for displaying form on the homepage. This is actualy all what it's doing. it displays, validate, and submits new paste into database. """ if not request.method == 'POST': # if it's not a POST request, i just display pure homepage.html # with empty form. When user has cookie with previously used highlight # he recieves form with initial syntax if 'highlight' in request.COOKIES: syntax = request.COOKIES['highlight'] <|code_end|> , generate the next line using the imports in this file: from django.http import HttpResponseRedirect from django.conf import settings from django.template.response import TemplateResponse from pygments.lexers import guess_lexer from apps.wklej.forms import WklejkaForm, WklejkaCaptchaForm import hashlib import random and context (functions, classes, or occasionally code) from other files: # Path: apps/wklej/forms.py # class WklejkaForm(forms.ModelForm): # nickname = forms.CharField(required=False) # # class Meta: # model = Wklejka # fields = '__all__' # # def clean_nickname(self): # if len(self.cleaned_data['nickname']) == 0: # self.cleaned_data['nickname'] = 'Anonim' # elif len(self.cleaned_data['nickname']) > 30: # self.cleaned_data['nickname'] = self.cleaned_data['nickname'][:29] # # return self.cleaned_data['nickname'] # # def clean_body(self): # if settings.USE_CAPTCHA and check_for_link_spam(self.cleaned_data['body']): # raise forms.ValidationError("This paste looks like spam.") # return self.cleaned_data['body'] # # class WklejkaCaptchaForm(forms.ModelForm): # recaptcha = ReCaptchaField() # has_captcha = forms.CharField(widget=forms.HiddenInput, required=False) # nickname = forms.CharField(required=False) # # class Meta: # model = Wklejka # fields = '__all__' # # def clean_nickname(self): # if len(self.cleaned_data['nickname']) == 0: # self.cleaned_data['nickname'] = 'Anonim' # elif len(self.cleaned_data['nickname']) > 30: # self.cleaned_data['nickname'] = self.cleaned_data['autor'][:29] # # return self.cleaned_data['nickname'] . Output only the next line.
form = WklejkaForm(initial={'syntax': syntax})
Predict the next line after this snippet: <|code_start|>#-*- coding: utf-8 -*- def homepage(request): """ This view is responsible for displaying form on the homepage. This is actualy all what it's doing. it displays, validate, and submits new paste into database. """ if not request.method == 'POST': # if it's not a POST request, i just display pure homepage.html # with empty form. When user has cookie with previously used highlight # he recieves form with initial syntax if 'highlight' in request.COOKIES: syntax = request.COOKIES['highlight'] form = WklejkaForm(initial={'syntax': syntax}) else: form = WklejkaForm() return TemplateResponse(request, 'homepage.html', {'form': form}) ### now i can focus on processing a POST request for new paste. try: if request.POST.get('has_captcha', '') and settings.USE_CAPTCHA: <|code_end|> using the current file's imports: from django.http import HttpResponseRedirect from django.conf import settings from django.template.response import TemplateResponse from pygments.lexers import guess_lexer from apps.wklej.forms import WklejkaForm, WklejkaCaptchaForm import hashlib import random and any relevant context from other files: # Path: apps/wklej/forms.py # class WklejkaForm(forms.ModelForm): # nickname = forms.CharField(required=False) # # class Meta: # model = Wklejka # fields = '__all__' # # def clean_nickname(self): # if len(self.cleaned_data['nickname']) == 0: # self.cleaned_data['nickname'] = 'Anonim' # elif len(self.cleaned_data['nickname']) > 30: # self.cleaned_data['nickname'] = self.cleaned_data['nickname'][:29] # # return self.cleaned_data['nickname'] # # def clean_body(self): # if settings.USE_CAPTCHA and check_for_link_spam(self.cleaned_data['body']): # raise forms.ValidationError("This paste looks like spam.") # return self.cleaned_data['body'] # # class WklejkaCaptchaForm(forms.ModelForm): # recaptcha = ReCaptchaField() # has_captcha = forms.CharField(widget=forms.HiddenInput, required=False) # nickname = forms.CharField(required=False) # # class Meta: # model = Wklejka # fields = '__all__' # # def clean_nickname(self): # if len(self.cleaned_data['nickname']) == 0: # self.cleaned_data['nickname'] = 'Anonim' # elif len(self.cleaned_data['nickname']) > 30: # self.cleaned_data['nickname'] = self.cleaned_data['autor'][:29] # # return self.cleaned_data['nickname'] . Output only the next line.
form = WklejkaCaptchaForm(request.POST)
Next line prediction: <|code_start|> class UserProfileTest(TestCase): def setUp(self): self.user = User(username="foobar") self.user.save() self.wklejka = Wklejka(user=self.user, body="foobarbaz").save() <|code_end|> . Use current file imports: (from apps.userstuff.models import UserProfile from apps.wklej.models import Wklejka from django.contrib.auth.models import User from django.test import TestCase) and context including class names, function names, or small code snippets from other files: # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt # # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) . Output only the next line.
self.userprofile = UserProfile(user=self.user)
Given the code snippet: <|code_start|> class UserProfileTest(TestCase): def setUp(self): self.user = User(username="foobar") self.user.save() <|code_end|> , generate the next line using the imports in this file: from apps.userstuff.models import UserProfile from apps.wklej.models import Wklejka from django.contrib.auth.models import User from django.test import TestCase and context (functions, classes, or occasionally code) from other files: # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt # # Path: apps/wklej/models.py # class Wklejka(models.Model): # """ # This model represents a single paste, both for anonymous and authenticated # pasters. # """ # # nickname = models.CharField(max_length=30, null=True) # user = models.ForeignKey(User, blank=True, null=True) # body = models.TextField() # pub_date = models.DateTimeField(auto_now_add=True) # mod_date = models.DateTimeField(auto_now=True) # hash = models.CharField(max_length=45, blank=True) # # # syntax # syntax = models.CharField(max_length=30, choices=LEXERS, # blank=True, null=True) # guessed_syntax = models.CharField(max_length=30, blank=True, null=True) # # # inheritance: # parent = models.ForeignKey('self', blank=True, null=True) # # # flags: # is_private = models.BooleanField(default=False) # is_deleted = models.BooleanField(default=False) # is_spam = models.BooleanField(default=False) # # # new: # comment = models.TextField(blank=True, null=True) # wherefrom = models.CharField(max_length=100, blank=True, null=True) # ip = models.CharField(max_length=20, blank=True, null=True) # # class Meta: # verbose_name = "Wklejka" # verbose_name_plural = "Wklejki" # ordering = ['-pub_date'] # db_table = 'wklej_wklejka' # # def __unicode__(self): # return "%s at %s" % (self.author, str(self.pub_date)) # # @property # def author(self): # return self.user if self.user else self.nickname # # @property # def is_public(self): # return not self.is_private # # @property # def hl(self): # return self.syntax or self.guessed_syntax # # def get_absolute_url(self): # if self.is_private: # return self.get_hash_url() # return self.get_id_url() # # def get_id_url(self): # return reverse('single', kwargs={'id': self.id}) # # def get_hash_url(self): # return reverse('single', kwargs={"hash": self.hash}) # # def get_del_url(self): # if self.is_private: # return reverse('delete', kwargs={"hash": self.hash}) # return reverse('delete', kwargs={"id": self.id}) # # def get_txt_url(self): # if self.is_private: # return reverse('txt', kwargs={"hash": self.hash}) # return reverse('txt', kwargs={"id": self.id}) # # def get_download_url(self): # if self.is_private: # return reverse('download', kwargs={"hash": self.hash}) # return reverse('download', kwargs={"id": self.id}) # # def is_parent(self): # if self.wklejka_set.all(): # return True # return False # # def children(self): # return self.wklejka_set.all() # # def children_count(self): # return self.children().count() # # def is_child(self): # if self.parent: # return True # return False # # def get_10_lines(self): # return "\n".join(self.body.splitlines()[:10]) . Output only the next line.
self.wklejka = Wklejka(user=self.user, body="foobarbaz").save()
Predict the next line after this snippet: <|code_start|> ### single paste: url(r'^id/(?P<id>\d+)/$', 'wklej.views.single', name="single"), # and it's txt version: url(r'^id/(?P<id>\d+)/txt/$', 'wklej.views.txt', name="txt"), # and it's downloadable: url(r'^id/(?P<id>\d+)/dl/$', 'wklej.views.download', name="download"), # responses url(r'^id/(?P<id>\d+)/re/$', 'wklej.views.re', name="reply"), # deletion url(r'^id/(?P<id>\d+)/delete/$', 'wklej.views.delete', name="delete"), ### single private paste: url(r'^hash/(?P<hash>\w+)/$', 'wklej.views.single', name="single"), # and it's txt version: url(r'^hash/(?P<hash>\w+)/txt/$', 'wklej.views.txt', name="txt"), # and it's downloadable: url(r'^hash/(?P<hash>\w+)/dl/$', 'wklej.views.download', name="download"), # and it's downloadable: url(r'^hash/(?P<hash>\w+)/delete/$', 'wklej.views.delete', name="delete"), ### list url(r'^own/$', 'apps.wklej.views.own', name="own"), #(r'^wklejki/$', 'wklej.views.wklejki'), #url(r'^tag/(?P<tag>\w+)/$', 'wklej.views.with_tag', name="with_tag"), ### registartion stuff url(r'^accounts/register/$', RegistrationView.as_view(), <|code_end|> using the current file's imports: from django.conf.urls import patterns, url, include from django.conf import settings from django.contrib import admin from django.views.generic import RedirectView, TemplateView from registration.views import RegistrationView from apps.userstuff.models import UserProfile from apps.wklej.xmlrpc import rpc_handler and any relevant context from other files: # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt # # Path: apps/wklej/xmlrpc.py # def rpc_handler(request): # """ # the actual handler: # if you setup your urls.py properly, all calls to the xml-rpc service # should be routed through here. # If post data is defined, it assumes it's XML-RPC and tries to process as # such Empty post assumes you're viewing from a browser and tells you about # the service. # """ # # response = HttpResponse() # if len(request.POST): # response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) # else: # response.write("<b>This is an XML-RPC Service.</b><br>") # #methods = dispatcher.system_listMethods() # response['Content-length'] = str(len(response.content)) # return response . Output only the next line.
{'profile_callback': UserProfile.objects.create},
Using the snippet: <|code_start|> 'django.contrib.auth.views.password_reset', {"template_name": 'registration/password_reset_form.html'}, name="password_reset"), url(r'^reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name': 'registration/password_reset_confirm.html'}, name="password_reset_confirm"), url(r'^reset/done/$', 'django.contrib.auth.views.password_reset_done', {"template_name": 'registration/password_reset_done.html'}, name="password_reset_done"), url(r'^reset/complete/$', 'django.contrib.auth.views.password_reset_complete', {"template_name": 'registration/password_reset_complete.html'}, name="password_reset_complete"), url(r'^own/password/$', 'django.contrib.auth.views.password_change', {"template_name": 'registration/password_change_form.html'}, name="password_change"), url(r'^own/password/done/$', 'django.contrib.auth.views.password_change_done', {"template_name": 'registration/password_change_done.html'}, name="password_change_done"), ## API: <|code_end|> , determine the next line of code. You have imports: from django.conf.urls import patterns, url, include from django.conf import settings from django.contrib import admin from django.views.generic import RedirectView, TemplateView from registration.views import RegistrationView from apps.userstuff.models import UserProfile from apps.wklej.xmlrpc import rpc_handler and context (class names, function names, or code) available: # Path: apps/userstuff/models.py # class UserProfile(models.Model): # user = models.ForeignKey(User, unique=True) # display_name = models.CharField(max_length=30) # current_salt = models.CharField(max_length=50) # # def __unicode__(self): # return self.user.username # # def username(self): # return self.user.username # # def get_wklejki(self): # return self.user.wklejka_set # # def generate_new_salt(self): # new_salt = generate_salt() # self.current_salt = new_salt # self.save() # return new_salt # # Path: apps/wklej/xmlrpc.py # def rpc_handler(request): # """ # the actual handler: # if you setup your urls.py properly, all calls to the xml-rpc service # should be routed through here. # If post data is defined, it assumes it's XML-RPC and tries to process as # such Empty post assumes you're viewing from a browser and tells you about # the service. # """ # # response = HttpResponse() # if len(request.POST): # response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) # else: # response.write("<b>This is an XML-RPC Service.</b><br>") # #methods = dispatcher.system_listMethods() # response['Content-length'] = str(len(response.content)) # return response . Output only the next line.
(r'^xmlrpc/$', rpc_handler),
Given the code snippet: <|code_start|> ''' connection = pika.BlockingConnection(pika.ConnectionParameters( host=host)) channel = connection.channel() channel.exchange_declare(exchange=exchange_info[0], exchange_type=exchange_info[1]) channel.basic_publish(exchange=exchange_info[0], routing_key=routing, body=message) connection.close() def lifecycle_event_handler(sender, **kwargs): ''' This handler will send a message to a message queue with information about the lifecycle event. The mesage will only be sent if the settings.PUBLISH_LIFECYCLE flag is set to True. ''' host = settings.AMQP_HOST exchange_info = ('openethics_events', 'fanout') signal = kwargs['signal'] <|code_end|> , generate the next line using the imports in this file: from ethicsapplication.signals import application_created from review.signals import application_accepted_by_reviewer,\ application_rejected_by_reviewer from django.conf import settings import pika import json and context (functions, classes, or occasionally code) from other files: # Path: ethicsapplication/signals.py # # Path: review/signals.py . Output only the next line.
if signal == application_created:
Here is a snippet: <|code_start|> connection = pika.BlockingConnection(pika.ConnectionParameters( host=host)) channel = connection.channel() channel.exchange_declare(exchange=exchange_info[0], exchange_type=exchange_info[1]) channel.basic_publish(exchange=exchange_info[0], routing_key=routing, body=message) connection.close() def lifecycle_event_handler(sender, **kwargs): ''' This handler will send a message to a message queue with information about the lifecycle event. The mesage will only be sent if the settings.PUBLISH_LIFECYCLE flag is set to True. ''' host = settings.AMQP_HOST exchange_info = ('openethics_events', 'fanout') signal = kwargs['signal'] if signal == application_created: event_type = 'created' <|code_end|> . Write the next line using the current file imports: from ethicsapplication.signals import application_created from review.signals import application_accepted_by_reviewer,\ application_rejected_by_reviewer from django.conf import settings import pika import json and context from other files: # Path: ethicsapplication/signals.py # # Path: review/signals.py , which may include functions, classes, or code. Output only the next line.
elif signal == application_accepted_by_reviewer:
Using the snippet: <|code_start|> host=host)) channel = connection.channel() channel.exchange_declare(exchange=exchange_info[0], exchange_type=exchange_info[1]) channel.basic_publish(exchange=exchange_info[0], routing_key=routing, body=message) connection.close() def lifecycle_event_handler(sender, **kwargs): ''' This handler will send a message to a message queue with information about the lifecycle event. The mesage will only be sent if the settings.PUBLISH_LIFECYCLE flag is set to True. ''' host = settings.AMQP_HOST exchange_info = ('openethics_events', 'fanout') signal = kwargs['signal'] if signal == application_created: event_type = 'created' elif signal == application_accepted_by_reviewer: event_type = 'accepted' <|code_end|> , determine the next line of code. You have imports: from ethicsapplication.signals import application_created from review.signals import application_accepted_by_reviewer,\ application_rejected_by_reviewer from django.conf import settings import pika import json and context (class names, function names, or code) available: # Path: ethicsapplication/signals.py # # Path: review/signals.py . Output only the next line.
elif signal == application_rejected_by_reviewer:
Here is a snippet: <|code_start|> class CommitteeTestCase(TestCase): def test_fields(self): ''' This model requires a committee member and the optional count should default to 0. ''' <|code_end|> . Write the next line using the current file imports: from django.test import TestCase from django.db.utils import IntegrityError from review.models import Committee, CommitteeManager from django.contrib.auth.models import User and context from other files: # Path: review/models.py # class Committee(models.Model): # ''' # This model represents the review committee. # It consists of a foreign key to users for the members # of the committee, and a count which maintains the number of # applications each committee member has reviewed. # ''' # member = models.ForeignKey(User) # count = models.IntegerField(max_length=3, default=0) # # objects = CommitteeManager() # # def __unicode__(self): # return '%s count: %s' % (self.member, self.count) # # class CommitteeManager(models.Manager): # ''' # The deafult manager for the Committee model # ''' # # def get_next_free_reviewer(self): # ''' # This function should return the committe member who has the smallest # application count. If there are two members with the same count then the # user with the highest pk is returned. If there are no committee members # then this function will return None # # ''' # query_set = super(CommitteeManager, self).get_query_set().order_by('count', '-id') # # if len(query_set) > 0: # member = query_set[0].member # return member # else: # return None , which may include functions, classes, or code. Output only the next line.
self.assertRaises(IntegrityError, Committee.objects.create)
Predict the next line after this snippet: <|code_start|> class CommitteeTestCase(TestCase): def test_fields(self): ''' This model requires a committee member and the optional count should default to 0. ''' self.assertRaises(IntegrityError, Committee.objects.create) committee = Committee.objects.create(member=User.objects.create_user('username', 'email@me.com', 'password')) self.assertEquals(committee.count, 0) def test_default_manager(self): ''' The committee model should have an instance of CommitteeManager as its deafult manager ''' <|code_end|> using the current file's imports: from django.test import TestCase from django.db.utils import IntegrityError from review.models import Committee, CommitteeManager from django.contrib.auth.models import User and any relevant context from other files: # Path: review/models.py # class Committee(models.Model): # ''' # This model represents the review committee. # It consists of a foreign key to users for the members # of the committee, and a count which maintains the number of # applications each committee member has reviewed. # ''' # member = models.ForeignKey(User) # count = models.IntegerField(max_length=3, default=0) # # objects = CommitteeManager() # # def __unicode__(self): # return '%s count: %s' % (self.member, self.count) # # class CommitteeManager(models.Manager): # ''' # The deafult manager for the Committee model # ''' # # def get_next_free_reviewer(self): # ''' # This function should return the committe member who has the smallest # application count. If there are two members with the same count then the # user with the highest pk is returned. If there are no committee members # then this function will return None # # ''' # query_set = super(CommitteeManager, self).get_query_set().order_by('count', '-id') # # if len(query_set) > 0: # member = query_set[0].member # return member # else: # return None . Output only the next line.
self.assertIsInstance(Committee.objects, CommitteeManager)
Continue the code snippet: <|code_start|>''' This will test the forms code for the ethicsapplication application Created on Jul 25, 2012 @author: jasonmarshall ''' class FormsTest(TestCase): def test_EthicsApplication_form_title(self): ''' Check that the form provdes a field that cannot be blank for the application title ''' <|code_end|> . Use current file imports: from django.test import TestCase from ethicsapplication.forms import EthicsApplicationForm and context (classes, functions, or code) from other files: # Path: ethicsapplication/forms.py # class EthicsApplicationForm(ModelForm): # class Meta: # model = EthicsApplication # exclude = ('principle_investigator','application_form', 'active', 'checklist') . Output only the next line.
form = EthicsApplicationForm()
Here is a snippet: <|code_start|> class FullApplicationChecklistLinkTestCase(TestCase): def test_fields(self): ''' This model should specify the following fields: checklist_question - ForeignKey(Question) included_group - ForeignKey (QuestionGroup) order - Integer all of which are required for creation ''' test_question = Question.objects.create(label='test', field_type='charfield') test_question_group = QuestionGroup.objects.create(name='test') <|code_end|> . Write the next line using the current file imports: from django.test import TestCase from applicationform.models import FullApplicationChecklistLink,\ FullApplicationChecklistLinkManager from questionnaire.models import QuestionGroup, Question from django.db.utils import IntegrityError and context from other files: # Path: applicationform/models.py # class FullApplicationChecklistLink(models.Model): # ''' # This model encapsulates the link between a checklist question # and one of more QuestionGroups that will be added to the # ethics application_form if that question is answered yes. # ''' # # checklist_question = models.ForeignKey(Question, related_name='checklist_question') # included_group = models.ForeignKey(QuestionGroup, related_name='included_group') # order = models.IntegerField() # objects = FullApplicationChecklistLinkManager() # # class FullApplicationChecklistLinkManager(models.Manager): # # def get_ordered_groups_for_question(self, the_question): # ''' # Returns all of the Groups that are linked to a particular # checklist_question, in order. # ''' # # return [link.included_group for link in super(FullApplicationChecklistLinkManager, self). # get_query_set().filter(checklist_question=the_question).order_by('order')] , which may include functions, classes, or code. Output only the next line.
self.assertRaises(IntegrityError, FullApplicationChecklistLink.objects.create)
Next line prediction: <|code_start|> class FullApplicationChecklistLinkTestCase(TestCase): def test_fields(self): ''' This model should specify the following fields: checklist_question - ForeignKey(Question) included_group - ForeignKey (QuestionGroup) order - Integer all of which are required for creation ''' test_question = Question.objects.create(label='test', field_type='charfield') test_question_group = QuestionGroup.objects.create(name='test') self.assertRaises(IntegrityError, FullApplicationChecklistLink.objects.create) self.assertRaises(IntegrityError, FullApplicationChecklistLink.objects.create, checklist_question=test_question) self.assertRaises(IntegrityError, FullApplicationChecklistLink.objects.create, checklist_question=test_question, included_group=test_question_group) self.assertTrue( FullApplicationChecklistLink.objects.create(checklist_question=test_question, included_group=test_question_group, order=1) ) def test_default_manager(self): ''' This model should have an instance of FullApplicationChecklistLinkManager as the default manager available through the ''objects'' field. ''' <|code_end|> . Use current file imports: (from django.test import TestCase from applicationform.models import FullApplicationChecklistLink,\ FullApplicationChecklistLinkManager from questionnaire.models import QuestionGroup, Question from django.db.utils import IntegrityError) and context including class names, function names, or small code snippets from other files: # Path: applicationform/models.py # class FullApplicationChecklistLink(models.Model): # ''' # This model encapsulates the link between a checklist question # and one of more QuestionGroups that will be added to the # ethics application_form if that question is answered yes. # ''' # # checklist_question = models.ForeignKey(Question, related_name='checklist_question') # included_group = models.ForeignKey(QuestionGroup, related_name='included_group') # order = models.IntegerField() # objects = FullApplicationChecklistLinkManager() # # class FullApplicationChecklistLinkManager(models.Manager): # # def get_ordered_groups_for_question(self, the_question): # ''' # Returns all of the Groups that are linked to a particular # checklist_question, in order. # ''' # # return [link.included_group for link in super(FullApplicationChecklistLinkManager, self). # get_query_set().filter(checklist_question=the_question).order_by('order')] . Output only the next line.
self.assertIsInstance(FullApplicationChecklistLink.objects, FullApplicationChecklistLinkManager)
Given the following code snippet before the placeholder: <|code_start|> It is thisobject that will be manipulated by the workflow engine. ''' title = models.CharField(max_length=255, default=None) #default=None stops null strings which effectively makes it mandatory principle_investigator = models.ForeignKey(User ,related_name='pi') application_form = models.ForeignKey(Questionnaire, related_name='application_form', blank=True, null=True) checklist = models.ForeignKey(Questionnaire, related_name='checklist_questionnaire', blank=True, null=True) #TODO test the new checklist attribute objects = EthicsApplicationManager() __original_principle_investigator = None __original_id = None def __init__(self, *args, **kwargs): super(EthicsApplication, self).__init__(*args, **kwargs) #save the orginal values of the pi and the id so we can detect if they have changed without having to ask the db self.__original_principle_investigator = kwargs.get('principle_investigator', None) self.__original_id = self.id def save(self, force_insert=False, force_update=False, using=None): super(EthicsApplication, self).save(force_insert, force_update, using) if(self.__original_id != self.id): #this is a new application that has been changed (or somehow the id has changed?!) self._add_to_workflow() self._add_to_principle_investigator_role() self.__original_id = self.id <|code_end|> , predict the next line using imports from the current file: from django.db import models from django.contrib.auth.models import User from questionnaire.models import AnswerSet, Questionnaire from django.db.models.manager import Manager from workflows.utils import set_workflow from django.conf import settings from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from workflows.models import Workflow, State from permissions.models import Role from permissions.utils import remove_local_role, add_local_role, get_object_for_principle_as_role from workflows.utils import get_state from ethicsapplication.signals import application_created and context including class names, function names, and sometimes code from other files: # Path: ethicsapplication/signals.py . Output only the next line.
application_created.send(sender=self, application=self)
Next line prediction: <|code_start|># copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """This file contains common views.""" bp_common = Blueprint('common', __name__) @bp_common.route('/_uploads/<path:filename>') def serve_file(filename): """Serve the given uploaded file. Args: filename (str): Relative file path. """ <|code_end|> . Use current file imports: (import os from flask import Blueprint, current_app, make_response, send_from_directory from werkzeug.utils import secure_filename from akamatsu.models import FileUpload) and context including class names, function names, or small code snippets from other files: # Path: akamatsu/models.py # class FileUpload(BaseModel): # """Model for static file uploads. # # Attributes: # id (int): Unique ID of the record. # path (str): Path to the file relative to the uploads directory. # description (str): Optional description of the file. # uploaded_at (datetime): UTC datetime in which the file was uploaded. # """ # __tablename__ = 'uploads' # # id = db.Column(db.Integer, primary_key=True) # # path = db.Column(db.String(255), nullable=False, unique=True) # description = db.Column(db.String(256), nullable=True) # mime = db.Column(db.String(128), nullable=False) # uploaded_at = db.Column( # db.DateTime, # nullable=False, # default=datetime.datetime.utcnow() # ) # # # @classmethod # def get_by_path(cls, path): # """Get instance by path. # # Returns: # Instance or `None` if not found. # """ # return cls.query.filter_by(path=path).first() . Output only the next line.
fupload = FileUpload.get_by_path(filename)
Given the code snippet: <|code_start|># Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """This file contains unauthenticated page views.""" bp_pages = Blueprint('pages', __name__) @bp_pages.route('/') def root(): """Load the root page.""" page = ( <|code_end|> , generate the next line using the imports in this file: from flask import Blueprint, abort, redirect, render_template, url_for from akamatsu.models import Page and context (functions, classes, or occasionally code) from other files: # Path: akamatsu/models.py # class Page(BaseModel): # """Model for dynamic pages. # # Pages may be written in markdown (default) or in html. Security should # be taken into consideration when writing html. # # The `<head>` can be extended (e.g. to add some custom JS scripts) when # writing pages in html. # # Pages can "ghost" other pages, meaning that accessing a ghost page will # redirect to the page being ghosted. # # Attributes: # id (int): Unique page ID. # ghosted_id (int): ID of the page the browser will be redirected to # when accessing this page. If set to `None`, this page will not be # a ghost page. # title (str): Title of the page. # mini (str): Optional text to show at the top of the page. # route (str): Route to this page. Must be unique. # custom_head (str): Add custom html to the `<head>` of the template. # content (str): Main content of the page. This can be written in markdown # or html. # is_published (bool): Whether the page is published. # comments_enabled (bool): Whether comments are enabled for this page. # last_updated (datetime): UTC datetime in which the page was last edited. # """ # __tablename__ = 'pages' # # id = db.Column(db.Integer, primary_key=True) # # ghosted_id = db.Column( # db.Integer, # db.ForeignKey('pages.id', onupdate='CASCADE', ondelete='CASCADE'), # nullable=True # ) # title = db.Column(db.String(255), nullable=False) # mini = db.Column(db.String(50), nullable=False) # route = db.Column(db.String(255), nullable=False, unique=True) # custom_head = db.Column(db.Text, nullable=True) # content = db.Column(db.Text, nullable=False) # is_published = db.Column(db.Boolean, default=False) # comments_enabled = db.Column(db.Boolean, default=False) # last_updated = db.Column(db.DateTime) # # # Relationships # ghosts = db.relationship( # 'Page', # cascade='all', # backref=db.backref('ghosted', remote_side='Page.id'), # collection_class=set # ) # # def __str__(self): # return self.title . Output only the next line.
Page.query
Predict the next line for this snippet: <|code_start|>""" class test_branchScale_ExpCM(unittest.TestCase): """Tests `branchScale` of `ExpCM_empirical_phi` model.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_branchScale(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) # define model, only free parameter is mu for testing simulations nsites = 50 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) kappa = 4.2 omega = 0.4 beta = 1.5 mu = 0.3 if self.MODEL == phydmslib.models.ExpCM: <|code_end|> with the help of current file imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo import pyvolve from phydmslib.constants import N_NT, N_AA, AA_TO_INDEX and context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} , which may contain function names, class names, or code. Output only the next line.
phi = numpy.random.dirichlet([7] * N_NT)
Here is a snippet: <|code_start|>"""Tests branch scaling. Makes sure we can correctly re-scale branch lengths into units of substitutions per site. Written by Jesse Bloom. """ class test_branchScale_ExpCM(unittest.TestCase): """Tests `branchScale` of `ExpCM_empirical_phi` model.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_branchScale(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) # define model, only free parameter is mu for testing simulations nsites = 50 prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> . Write the next line using the current file imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo import pyvolve from phydmslib.constants import N_NT, N_AA, AA_TO_INDEX and context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} , which may include functions, classes, or code. Output only the next line.
rprefs = numpy.random.dirichlet([1] * N_AA)
Here is a snippet: <|code_start|>"""Tests branch scaling. Makes sure we can correctly re-scale branch lengths into units of substitutions per site. Written by Jesse Bloom. """ class test_branchScale_ExpCM(unittest.TestCase): """Tests `branchScale` of `ExpCM_empirical_phi` model.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_branchScale(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) # define model, only free parameter is mu for testing simulations nsites = 50 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> . Write the next line using the current file imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo import pyvolve from phydmslib.constants import N_NT, N_AA, AA_TO_INDEX and context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} , which may include functions, classes, or code. Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Continue the code snippet: <|code_start|> # create initial ExpCM g = numpy.random.dirichlet([3] * N_NT) omega = 0.7 kappa = 2.5 beta = 1.2 self.expcm = (phydmslib.models .ExpCM_empirical_phi(self.prefs, g=g, omega=omega, kappa=kappa, beta=beta)) self.assertTrue(numpy.allclose(g, self.expcm.g)) # now check ExpCM attributes / derivates, updating several times for _update in range(2): self.params = {'omega': random.uniform(0.1, 2), 'kappa': random.uniform(0.5, 10), 'beta': random.uniform(0.5, 5), 'mu': random.uniform(0.05, 5.0), } self.expcm.updateParams(self.params) self.assertTrue(numpy.allclose(g, self.expcm.g)) self.check_empirical_phi() self.check_dQxy_dbeta() self.check_dprx_dbeta() self.check_ExpCM_attributes() self.check_ExpCM_derivatives() self.check_ExpCM_matrix_exponentials() def check_empirical_phi(self): """Check that `phi` gives right `g`, and has right derivative.""" nt_freqs = [0] * N_NT for r in range(self.nsites): <|code_end|> . Use current file imports: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import (N_CODON, N_NT, CODON_NT_COUNT, AA_TO_INDEX, N_AA) and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
for x in range(N_CODON):
Given the following code snippet before the placeholder: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi` class. Written by Jesse Bloom. """ class testExpCM_empirical_phi(unittest.TestCase): """Tests ``ExpCM`` with empirical phi.""" def test_ExpCM_empirical_phi(self): """Initialize `ExpCM_empirical_phi`, test, update, test again.""" # create preferences random.seed(1) numpy.random.seed(1) self.nsites = 7 self.prefs = [] minpref = 0.01 for _r in range(self.nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) # create initial ExpCM <|code_end|> , predict the next line using imports from the current file: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import (N_CODON, N_NT, CODON_NT_COUNT, AA_TO_INDEX, N_AA) and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
g = numpy.random.dirichlet([3] * N_NT)
Predict the next line for this snippet: <|code_start|> omega = 0.7 kappa = 2.5 beta = 1.2 self.expcm = (phydmslib.models .ExpCM_empirical_phi(self.prefs, g=g, omega=omega, kappa=kappa, beta=beta)) self.assertTrue(numpy.allclose(g, self.expcm.g)) # now check ExpCM attributes / derivates, updating several times for _update in range(2): self.params = {'omega': random.uniform(0.1, 2), 'kappa': random.uniform(0.5, 10), 'beta': random.uniform(0.5, 5), 'mu': random.uniform(0.05, 5.0), } self.expcm.updateParams(self.params) self.assertTrue(numpy.allclose(g, self.expcm.g)) self.check_empirical_phi() self.check_dQxy_dbeta() self.check_dprx_dbeta() self.check_ExpCM_attributes() self.check_ExpCM_derivatives() self.check_ExpCM_matrix_exponentials() def check_empirical_phi(self): """Check that `phi` gives right `g`, and has right derivative.""" nt_freqs = [0] * N_NT for r in range(self.nsites): for x in range(N_CODON): for w in range(N_NT): <|code_end|> with the help of current file imports: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import (N_CODON, N_NT, CODON_NT_COUNT, AA_TO_INDEX, N_AA) and context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) , which may contain function names, class names, or code. Output only the next line.
nt_freqs[w] += self.expcm.prx[r][x] * CODON_NT_COUNT[w][x]
Given snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi` class. Written by Jesse Bloom. """ class testExpCM_empirical_phi(unittest.TestCase): """Tests ``ExpCM`` with empirical phi.""" def test_ExpCM_empirical_phi(self): """Initialize `ExpCM_empirical_phi`, test, update, test again.""" # create preferences random.seed(1) numpy.random.seed(1) self.nsites = 7 self.prefs = [] minpref = 0.01 for _r in range(self.nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> , continue by predicting the next line. Consider current file imports: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import (N_CODON, N_NT, CODON_NT_COUNT, AA_TO_INDEX, N_AA) and context: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) which might include code, classes, or functions. Output only the next line.
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|>"""Tests `phydmslib.models.ExpCM_empirical_phi` class. Written by Jesse Bloom. """ class testExpCM_empirical_phi(unittest.TestCase): """Tests ``ExpCM`` with empirical phi.""" def test_ExpCM_empirical_phi(self): """Initialize `ExpCM_empirical_phi`, test, update, test again.""" # create preferences random.seed(1) numpy.random.seed(1) self.nsites = 7 self.prefs = [] minpref = 0.01 for _r in range(self.nsites): <|code_end|> using the current file's imports: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import (N_CODON, N_NT, CODON_NT_COUNT, AA_TO_INDEX, N_AA) and any relevant context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Here is a snippet: <|code_start|> [pirAy, random.uniform(0.01, 0.5)], [omega, random.uniform(0.1, 2.0)]] self.assertTrue(abs(values[1][1] - values[2][1]) > diffpref, "choose another random number seed as pirAx and " "pirAy are too close.") self.assertTrue(numpy.allclose(float(dFrxy_dpirAx.subs(values)), float(sympy.diff(Frxy, pirAx).subs(values)))) self.assertTrue(numpy.allclose(float(dFrxy_dpirAy.subs(values)), float(sympy.diff(Frxy, pirAy).subs(values)))) values[2][1] = values[1][1] * (1 + diffpref) self.assertTrue(numpy.allclose(float(dFrxy_dpirAx_equal.subs( values)), float(sympy.diff(Frxy, pirAx).subs(values)))) self.assertTrue(numpy.allclose(float(dFrxy_dpirAy_equal.subs( values)), float(sympy.diff(Frxy, pirAy).subs(values)))) expcm_fitprefs = copy.deepcopy(self.expcm_fitprefs) for r in range(expcm_fitprefs.nsites): for x in range(N_CODON): for y in range(N_CODON): if x == y: continue values = {} values[beta] = expcm_fitprefs.beta values[omega] = expcm_fitprefs.omega values[pirAx] = expcm_fitprefs.pi_codon[r][x] values[pirAy] = expcm_fitprefs.pi_codon[r][y] Qxy = expcm_fitprefs.Qxy[x][y] # check Prxy values if values[pirAx] == values[pirAy]: <|code_end|> . Write the next line using the current file imports: import random import unittest import copy import numpy import scipy.optimize import sympy import phydmslib.models from phydmslib.constants import CODON_TO_AA, N_CODON, N_AA, AA_TO_INDEX, N_NT and context from other files: # Path: phydmslib/constants.py # CODON_TO_AA = [] # # N_CODON = len(CODON_TO_INDEX) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) , which may include functions, classes, or code. Output only the next line.
if CODON_TO_AA[x] == CODON_TO_AA[y]:
Given the code snippet: <|code_start|> (1 - (pirAx / pirAy)**beta)) dFrxy_dpirAx = ((-omega * beta / pirAx) * ((pirAx / pirAy)**beta * (sympy.ln((pirAx / pirAy)**beta) - 1) + 1) / ((1 - (pirAx / pirAy)**beta)**2)) dFrxy_dpirAx_equal = -omega * beta / (2 * pirAx) dFrxy_dpirAy = ((omega * beta / pirAy) * ((pirAx / pirAy)**beta * (sympy.ln((pirAx / pirAy)**beta) - 1) + 1) / ((1 - (pirAx / pirAy)**beta)**2)) dFrxy_dpirAy_equal = omega * beta / (2 * pirAy) diffpref = 1.0e-5 for _itest in range(5): values = [[beta, 1], [pirAx, random.uniform(0.01, 0.5)], [pirAy, random.uniform(0.01, 0.5)], [omega, random.uniform(0.1, 2.0)]] self.assertTrue(abs(values[1][1] - values[2][1]) > diffpref, "choose another random number seed as pirAx and " "pirAy are too close.") self.assertTrue(numpy.allclose(float(dFrxy_dpirAx.subs(values)), float(sympy.diff(Frxy, pirAx).subs(values)))) self.assertTrue(numpy.allclose(float(dFrxy_dpirAy.subs(values)), float(sympy.diff(Frxy, pirAy).subs(values)))) values[2][1] = values[1][1] * (1 + diffpref) self.assertTrue(numpy.allclose(float(dFrxy_dpirAx_equal.subs( values)), float(sympy.diff(Frxy, pirAx).subs(values)))) self.assertTrue(numpy.allclose(float(dFrxy_dpirAy_equal.subs( values)), float(sympy.diff(Frxy, pirAy).subs(values)))) expcm_fitprefs = copy.deepcopy(self.expcm_fitprefs) for r in range(expcm_fitprefs.nsites): <|code_end|> , generate the next line using the imports in this file: import random import unittest import copy import numpy import scipy.optimize import sympy import phydmslib.models from phydmslib.constants import CODON_TO_AA, N_CODON, N_AA, AA_TO_INDEX, N_NT and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # CODON_TO_AA = [] # # N_CODON = len(CODON_TO_INDEX) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
for x in range(N_CODON):
Given the following code snippet before the placeholder: <|code_start|> (self .assertTrue((numpy .allclose(float(dFrxy_dpirAx_equal .subs(values.items()) ), (-expcm_fitprefs .tildeFrxy[r][x][y]) / values[pirAx])))) self.assertTrue(numpy.allclose( float(dFrxy_dpirAy_equal .subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAy])) else: self.assertTrue(numpy.allclose( float(dFrxy_dpirAx.subs(values.items())), -expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAx])) self.assertTrue(numpy.allclose( float(dFrxy_dpirAy.subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAy])) def setUp(self): """Set up for tests.""" numpy.random.seed(1) random.seed(1) nsites = 1 minpref = 0.001 self.prefs = [] for _r in range(nsites): <|code_end|> , predict the next line using imports from the current file: import random import unittest import copy import numpy import scipy.optimize import sympy import phydmslib.models from phydmslib.constants import CODON_TO_AA, N_CODON, N_AA, AA_TO_INDEX, N_NT and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # CODON_TO_AA = [] # # N_CODON = len(CODON_TO_INDEX) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
rprefs = numpy.random.dirichlet([0.7] * N_AA)
Given the following code snippet before the placeholder: <|code_start|> ), (-expcm_fitprefs .tildeFrxy[r][x][y]) / values[pirAx])))) self.assertTrue(numpy.allclose( float(dFrxy_dpirAy_equal .subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAy])) else: self.assertTrue(numpy.allclose( float(dFrxy_dpirAx.subs(values.items())), -expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAx])) self.assertTrue(numpy.allclose( float(dFrxy_dpirAy.subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAy])) def setUp(self): """Set up for tests.""" numpy.random.seed(1) random.seed(1) nsites = 1 minpref = 0.001 self.prefs = [] for _r in range(nsites): rprefs = numpy.random.dirichlet([0.7] * N_AA) rprefs[rprefs < minpref] = minpref rprefs[0] = rprefs[1] + 1.0e-8 # near equal prefs handled OK rprefs /= rprefs.sum() <|code_end|> , predict the next line using imports from the current file: import random import unittest import copy import numpy import scipy.optimize import sympy import phydmslib.models from phydmslib.constants import CODON_TO_AA, N_CODON, N_AA, AA_TO_INDEX, N_NT and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # CODON_TO_AA = [] # # N_CODON = len(CODON_TO_INDEX) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Given snippet: <|code_start|> self.assertTrue(numpy.allclose( float(dFrxy_dpirAy_equal .subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAy])) else: self.assertTrue(numpy.allclose( float(dFrxy_dpirAx.subs(values.items())), -expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAx])) self.assertTrue(numpy.allclose( float(dFrxy_dpirAy.subs(values.items())), expcm_fitprefs.tildeFrxy[r][x][y] / values[pirAy])) def setUp(self): """Set up for tests.""" numpy.random.seed(1) random.seed(1) nsites = 1 minpref = 0.001 self.prefs = [] for _r in range(nsites): rprefs = numpy.random.dirichlet([0.7] * N_AA) rprefs[rprefs < minpref] = minpref rprefs[0] = rprefs[1] + 1.0e-8 # near equal prefs handled OK rprefs /= rprefs.sum() self.prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) self.expcm_fitprefs = self.MODEL(self.prefs, prior=None, kappa=3.0, omega=0.3, <|code_end|> , continue by predicting the next line. Consider current file imports: import random import unittest import copy import numpy import scipy.optimize import sympy import phydmslib.models from phydmslib.constants import CODON_TO_AA, N_CODON, N_AA, AA_TO_INDEX, N_NT and context: # Path: phydmslib/constants.py # CODON_TO_AA = [] # # N_CODON = len(CODON_TO_INDEX) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) which might include code, classes, or functions. Output only the next line.
phi=numpy.random.dirichlet([5] * N_NT)
Here is a snippet: <|code_start|> """Test that `TreeLikelihood` initializes properly.""" tl = (phydmslib.treelikelihood .TreeLikelihood(self.tree, self.alignment, self.model, underflowfreq=self.underflowfreq, dparamscurrent=False, dtcurrent=True)) self.assertEqual(tl.dloglik_dt.shape, tl.t.shape) def test_dM_dt(self): """Tests model `dM` with respect to `t`.""" numpy.random.seed(1) random.seed(1) tl = (phydmslib.treelikelihood .TreeLikelihood(self.tree, self.alignment, self.model, underflowfreq=self.underflowfreq, dparamscurrent=False, dtcurrent=True)) def func(t, k, r, x, y): return tl._M(k, t[0], None)[r][x][y] def dfunc(t, k, r, x, y): return tl._dM(k, t[0], 't', None)[r][x][y] for r in range(self.nsites): k = random.choice(tl._catindices) <|code_end|> . Write the next line using the current file imports: import os import unittest import random import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import N_CODON, N_NT, AA_TO_INDEX, N_AA and context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) , which may include functions, classes, or code. Output only the next line.
x = random.randint(0, N_CODON - 1)
Given snippet: <|code_start|> class test_BrLenDerivatives_ExpCM(unittest.TestCase): """`TreeLikelihood` branch length derivatives for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM DISTRIBUTIONMODEL = None def setUp(self): """Set up parameters for test.""" random.seed(1) numpy.random.seed(1) self.underflowfreq = 1 # define tree self.newick = ('((node1:0.2,node2:0.3)node4:0.3,node3:0.5)node5:0.04;') tempfile = '_temp.tree' with open(tempfile, 'w') as f: f.write(self.newick) self.tree = Bio.Phylo.read(tempfile, 'newick') os.remove(tempfile) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 50 self.nseqs = self.tree.count_terminals() <|code_end|> , continue by predicting the next line. Consider current file imports: import os import unittest import random import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import N_CODON, N_NT, AA_TO_INDEX, N_AA and context: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) which might include code, classes, or functions. Output only the next line.
e_pw = numpy.ndarray((3, N_NT), dtype='float')
Here is a snippet: <|code_start|> os.remove(tempfile) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 50 self.nseqs = self.tree.count_terminals() e_pw = numpy.ndarray((3, N_NT), dtype='float') e_pw.fill(0.25) yngkp_m0 = phydmslib.models.YNGKP_M0(e_pw, self.nsites) partitions = phydmslib.simulate.pyvolvePartitions(yngkp_m0) alignment = '_temp_simulatedalignment.fasta' info = '_temp_info.txt' rates = '_temp_ratefile.txt' evolver = pyvolve.Evolver(partitions=partitions, tree=pyvolvetree) evolver(seqfile=alignment, infofile=info, ratefile=rates) self.alignment = [(s.description, str(s.seq)) for s in Bio.SeqIO.parse( alignment, 'fasta')] for f in [alignment, info, rates]: os.remove(f) assert len(self.alignment[0][1]) == self.nsites * 3 assert len(self.alignment) == self.nseqs # define model prefs = [] minpref = 0.02 g = numpy.random.dirichlet([10] * N_NT) for _r in range(self.nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> . Write the next line using the current file imports: import os import unittest import random import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import N_CODON, N_NT, AA_TO_INDEX, N_AA and context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) , which may include functions, classes, or code. Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Continue the code snippet: <|code_start|> with open(tempfile, 'w') as f: f.write(self.newick) self.tree = Bio.Phylo.read(tempfile, 'newick') os.remove(tempfile) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 50 self.nseqs = self.tree.count_terminals() e_pw = numpy.ndarray((3, N_NT), dtype='float') e_pw.fill(0.25) yngkp_m0 = phydmslib.models.YNGKP_M0(e_pw, self.nsites) partitions = phydmslib.simulate.pyvolvePartitions(yngkp_m0) alignment = '_temp_simulatedalignment.fasta' info = '_temp_info.txt' rates = '_temp_ratefile.txt' evolver = pyvolve.Evolver(partitions=partitions, tree=pyvolvetree) evolver(seqfile=alignment, infofile=info, ratefile=rates) self.alignment = [(s.description, str(s.seq)) for s in Bio.SeqIO.parse( alignment, 'fasta')] for f in [alignment, info, rates]: os.remove(f) assert len(self.alignment[0][1]) == self.nsites * 3 assert len(self.alignment) == self.nseqs # define model prefs = [] minpref = 0.02 g = numpy.random.dirichlet([10] * N_NT) for _r in range(self.nsites): <|code_end|> . Use current file imports: import os import unittest import random import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import N_CODON, N_NT, AA_TO_INDEX, N_AA and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Given snippet: <|code_start|>"""Tests ``--diffprefsbysite`` option to ``phydms`` on simulated data. Written by Jesse Bloom. """ matplotlib.use('pdf') class test_DiffPrefsBySiteExpCM(unittest.TestCase): """Tests ``--diffprefsbysite`` to ``phydms`` for `ExpCM`.""" gammaomega_arg = [] def setUp(self): """Set up test.""" random.seed(1) numpy.random.seed(1) self.tree = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_tree.newick')) self.align = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_alignment.fasta')) self.prefs = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_prefs.tsv')) self.nsites = len(phydmslib.file_io .ReadCodonAlignment(self.align, True)[0][1]) // 3 prefs = phydmslib.file_io.readPrefs(self.prefs, minpref=0.005) <|code_end|> , continue by predicting the next line. Consider current file imports: import os import unittest import subprocess import random import pandas import scipy.stats import phydmslib.file_io import phydmslib.models import phydmslib.simulate import matplotlib import matplotlib.pyplot as plt import pyvolve import numpy from phydmslib.constants import INDEX_TO_AA, N_AA, AA_TO_INDEX and context: # Path: phydmslib/constants.py # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} which might include code, classes, or functions. Output only the next line.
aas = [INDEX_TO_AA[a] for a in range(N_AA)]
Next line prediction: <|code_start|>"""Tests ``--diffprefsbysite`` option to ``phydms`` on simulated data. Written by Jesse Bloom. """ matplotlib.use('pdf') class test_DiffPrefsBySiteExpCM(unittest.TestCase): """Tests ``--diffprefsbysite`` to ``phydms`` for `ExpCM`.""" gammaomega_arg = [] def setUp(self): """Set up test.""" random.seed(1) numpy.random.seed(1) self.tree = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_tree.newick')) self.align = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_alignment.fasta')) self.prefs = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_prefs.tsv')) self.nsites = len(phydmslib.file_io .ReadCodonAlignment(self.align, True)[0][1]) // 3 prefs = phydmslib.file_io.readPrefs(self.prefs, minpref=0.005) <|code_end|> . Use current file imports: (import os import unittest import subprocess import random import pandas import scipy.stats import phydmslib.file_io import phydmslib.models import phydmslib.simulate import matplotlib import matplotlib.pyplot as plt import pyvolve import numpy from phydmslib.constants import INDEX_TO_AA, N_AA, AA_TO_INDEX) and context including class names, function names, or small code snippets from other files: # Path: phydmslib/constants.py # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} . Output only the next line.
aas = [INDEX_TO_AA[a] for a in range(N_AA)]
Using the snippet: <|code_start|> matplotlib.use('pdf') class test_DiffPrefsBySiteExpCM(unittest.TestCase): """Tests ``--diffprefsbysite`` to ``phydms`` for `ExpCM`.""" gammaomega_arg = [] def setUp(self): """Set up test.""" random.seed(1) numpy.random.seed(1) self.tree = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_tree.newick')) self.align = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_alignment.fasta')) self.prefs = os.path.abspath(os.path.join(os.path.dirname(__file__), './NP_data/NP_prefs.tsv')) self.nsites = len(phydmslib.file_io .ReadCodonAlignment(self.align, True)[0][1]) // 3 prefs = phydmslib.file_io.readPrefs(self.prefs, minpref=0.005) aas = [INDEX_TO_AA[a] for a in range(N_AA)] self.shuffledsites = random.sample(sorted(prefs.keys()), 10) self.targetaas = {r: random.choice(aas) for r in self.shuffledsites} prefs = [prefs[r] for r in sorted(prefs.keys())] hipref = 0.9 lowpref = (1.0 - hipref) / (N_AA - 1) for r in self.shuffledsites: rprefs = [lowpref] * N_AA <|code_end|> , determine the next line of code. You have imports: import os import unittest import subprocess import random import pandas import scipy.stats import phydmslib.file_io import phydmslib.models import phydmslib.simulate import matplotlib import matplotlib.pyplot as plt import pyvolve import numpy from phydmslib.constants import INDEX_TO_AA, N_AA, AA_TO_INDEX and context (class names, function names, or code) available: # Path: phydmslib/constants.py # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} . Output only the next line.
rprefs[AA_TO_INDEX[self.targetaas[r]]] = hipref
Using the snippet: <|code_start|> J. Kyte & R. F. Doolittle: "A simple method for displaying the hydropathic character of a protein." J Mol Biol, 157, 105-132 More positive values indicate higher hydrophobicity, while more negative values indicate lower hydrophobicity. The returned variable is the 3-tuple *(cmap, mapping_d, mapper)*: * *cmap* is a ``pylab`` *LinearSegmentedColorMap* object. * *mapping_d* is a dictionary keyed by the one-letter amino-acid codes. The values are the colors in CSS2 format (e.g. #FF0000 for red) for that amino acid. The value for a stop codon (denoted by a ``*`` character) is black (#000000). * *mapper* is the actual *pylab.cm.ScalarMappable* object. The optional argument *maptype* should specify a valid ``pylab`` color map. The optional calling argument *reverse* specifies that we set up the color map so that the most hydrophobic residue comes first (in the Kyte-Doolittle scale the most hydrophobic comes last as it has the largest value). This option is *True* by default as it seems more intuitive to have charged residues red and hydrophobic ones blue. """ d = {'A': 1.8, 'C': 2.5, 'D': -3.5, 'E': -3.5, 'F': 2.8, 'G': -0.4, 'H': -3.2, 'I': 4.5, 'K': -3.9, 'L': 3.8, 'M': 1.9, 'N': -3.5, 'P': -1.6, 'Q': -3.5, 'R': -4.5, 'S': -0.8, 'T': -0.7, 'V': 4.2, 'W': -0.9, 'Y': -1.3} <|code_end|> , determine the next line of code. You have imports: import collections import os import tempfile import string import math import shutil import natsort import numpy import matplotlib import pylab import PyPDF2 import weblogolib # weblogo library import weblogolib.colorscheme # weblogo library import corebio.matrix # weblogo library import corebio.utils # weblogo library import doctest from phydmslib.constants import AA_TO_INDEX, NT_TO_INDEX and context (class names, function names, or code) available: # Path: phydmslib/constants.py # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()} . Output only the next line.
aas = sorted(AA_TO_INDEX.keys())
Using the snippet: <|code_start|> 'kd'(Kyte-Doolittle hydrophobicity scale, default), 'mw' (molecular weight), 'functionalgroup' (functional groups: small, nucleophilic, hydrophobic, aromatic, basic, acidic, and amide), 'charge' (charge at neutral pH), and 'singlecolor'. If 'charge' is used, then the argument for *custom_cmap* will no longer be meaningful, since 'charge' uses its own blue/black/red colormapping. Similarly, 'functionalgroup' uses its own colormapping. * *noseparator* is only meaningful if *datatype* is 'diffsel' or 'diffprefs'. If it set to *True*, then we do **not** a black horizontal line to separate positive and negative values. * *underlay* if `True` then make an underlay rather than an overlay. * *scalebar*: show a scale bar. If `False`, no scale bar shown. Otherwise should be a 2-tuple of `(scalebarlen, scalebarlabel)`. Currently only works when data is `diffsel`. """ assert datatype in ['prefs', 'diffprefs', 'diffsel'], ("Invalid datatype " "{0}" .format(datatype)) # check data, and get characters assert sites, "No sites specified" assert set(sites) == set(data.keys()), ("Not a match between " "sites and the keys of data") characters = list(data[sites[0]].keys()) aas = sorted(AA_TO_INDEX.keys()) <|code_end|> , determine the next line of code. You have imports: import collections import os import tempfile import string import math import shutil import natsort import numpy import matplotlib import pylab import PyPDF2 import weblogolib # weblogo library import weblogolib.colorscheme # weblogo library import corebio.matrix # weblogo library import corebio.utils # weblogo library import doctest from phydmslib.constants import AA_TO_INDEX, NT_TO_INDEX and context (class names, function names, or code) available: # Path: phydmslib/constants.py # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()} . Output only the next line.
if set(characters) == set(NT_TO_INDEX.keys()):
Given the following code snippet before the placeholder: <|code_start|> # re-set to old value, make sure return to original values tl.paramsarray = copy.deepcopy(paramsarray) self.assertTrue(numpy.allclose(logl, tl.loglik)) for (param, value) in modelparams.items(): self.assertTrue(numpy.allclose(value, getattr(tl.model, param))) def test_Likelihood(self): """Tests likelihood.""" random.seed(1) numpy.random.seed(1) if self.DISTRIBUTIONMODEL: return # test doesn't work for DistributionModel mus = [0.5, 1.5] partials_by_mu = {} siteloglik_by_mu = {} loglik_by_mu = {} for mu in mus: model = copy.deepcopy(self.model) model.updateParams({"mu": mu}) tl = phydmslib.treelikelihood.TreeLikelihood(self.tree, self.alignment, model) # Here we are doing the multiplication hand-coded for the # tree defined in `setUp`. This calculation would be wrong # if the tree in `setUp` were to be changed. M = {} for (node, t) in self.brlen.items(): M[node] = model.M(t / model.branchScale) # compute partials at root node <|code_end|> , predict the next line using imports from the current file: import os import re import math import unittest import random import copy import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA, CODON_TO_INDEX) and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) # # CODON_TO_INDEX = {} . Output only the next line.
partials = numpy.zeros(shape=(self.nsites, N_CODON))
Here is a snippet: <|code_start|> # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM DISTRIBUTIONMODEL = None def setUp(self): """Set up parameters for test.""" random.seed(1) numpy.random.seed(1) # define tree self.newick = "((node1:0.2,node2:0.3)node4:0.3,node3:0.5)node5:0.04;" tempfile = "_temp.tree" with open(tempfile, "w") as f: f.write(self.newick) self.tree = Bio.Phylo.read(tempfile, "newick") os.remove(tempfile) self.brlen = {} for (name, brlen) in re.findall( r"(?P<name>node\d):(?P<brlen>\d+\.\d+)", self.newick ): if name != self.tree.root.name: i = name[-1] # node number self.brlen[int(i)] = float(brlen) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 60 self.nseqs = self.tree.count_terminals() <|code_end|> . Write the next line using the current file imports: import os import re import math import unittest import random import copy import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA, CODON_TO_INDEX) and context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) # # CODON_TO_INDEX = {} , which may include functions, classes, or code. Output only the next line.
e_pw = numpy.ndarray((3, N_NT), dtype="float")
Given the code snippet: <|code_start|> info = "_temp_info.txt" rates = "_temp_ratefile.txt" evolver = pyvolve.Evolver(partitions=partitions, tree=pyvolvetree) evolver(seqfile=alignment, infofile=info, ratefile=rates) self.alignment = [(s.description, str(s.seq)) for s in Bio.SeqIO.parse(alignment, "fasta")] for f in [alignment, info, rates]: os.remove(f) assert len(self.alignment[0][1]) == self.nsites * 3 assert len(self.alignment) == self.nseqs self.codons = {} # indexed by node, site, gives codon index for node in self.tree.get_terminals(): node = node.name i = int(node[-1]) self.codons[i] = {} seq = [seq for (head, seq) in self.alignment if node == head][0] for r in range(self.nsites): codon = seq[3 * r: 3 * r + 3] self.codons[i][r] = CODON_TO_INDEX[codon] # define model prefs = [] minpref = 0.02 g = numpy.random.dirichlet([5] * N_NT) g[g < 0.1] = 0.1 g /= g.sum() for _r in range(self.nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> , generate the next line using the imports in this file: import os import re import math import unittest import random import copy import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA, CODON_TO_INDEX) and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) # # CODON_TO_INDEX = {} . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|> yngkp_m0 = phydmslib.models.YNGKP_M0(e_pw, self.nsites) partitions = phydmslib.simulate.pyvolvePartitions(yngkp_m0) alignment = "_temp_simulatedalignment.fasta" info = "_temp_info.txt" rates = "_temp_ratefile.txt" evolver = pyvolve.Evolver(partitions=partitions, tree=pyvolvetree) evolver(seqfile=alignment, infofile=info, ratefile=rates) self.alignment = [(s.description, str(s.seq)) for s in Bio.SeqIO.parse(alignment, "fasta")] for f in [alignment, info, rates]: os.remove(f) assert len(self.alignment[0][1]) == self.nsites * 3 assert len(self.alignment) == self.nseqs self.codons = {} # indexed by node, site, gives codon index for node in self.tree.get_terminals(): node = node.name i = int(node[-1]) self.codons[i] = {} seq = [seq for (head, seq) in self.alignment if node == head][0] for r in range(self.nsites): codon = seq[3 * r: 3 * r + 3] self.codons[i][r] = CODON_TO_INDEX[codon] # define model prefs = [] minpref = 0.02 g = numpy.random.dirichlet([5] * N_NT) g[g < 0.1] = 0.1 g /= g.sum() for _r in range(self.nsites): <|code_end|> using the current file's imports: import os import re import math import unittest import random import copy import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA, CODON_TO_INDEX) and any relevant context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) # # CODON_TO_INDEX = {} . Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Here is a snippet: <|code_start|> i = name[-1] # node number self.brlen[int(i)] = float(brlen) # simulate alignment with pyvolve pyvolvetree = pyvolve.read_tree(tree=self.newick) self.nsites = 60 self.nseqs = self.tree.count_terminals() e_pw = numpy.ndarray((3, N_NT), dtype="float") e_pw.fill(0.25) yngkp_m0 = phydmslib.models.YNGKP_M0(e_pw, self.nsites) partitions = phydmslib.simulate.pyvolvePartitions(yngkp_m0) alignment = "_temp_simulatedalignment.fasta" info = "_temp_info.txt" rates = "_temp_ratefile.txt" evolver = pyvolve.Evolver(partitions=partitions, tree=pyvolvetree) evolver(seqfile=alignment, infofile=info, ratefile=rates) self.alignment = [(s.description, str(s.seq)) for s in Bio.SeqIO.parse(alignment, "fasta")] for f in [alignment, info, rates]: os.remove(f) assert len(self.alignment[0][1]) == self.nsites * 3 assert len(self.alignment) == self.nseqs self.codons = {} # indexed by node, site, gives codon index for node in self.tree.get_terminals(): node = node.name i = int(node[-1]) self.codons[i] = {} seq = [seq for (head, seq) in self.alignment if node == head][0] for r in range(self.nsites): codon = seq[3 * r: 3 * r + 3] <|code_end|> . Write the next line using the current file imports: import os import re import math import unittest import random import copy import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve from phydmslib.constants import (N_CODON, N_NT, AA_TO_INDEX, N_AA, CODON_TO_INDEX) and context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) # # CODON_TO_INDEX = {} , which may include functions, classes, or code. Output only the next line.
self.codons[i][r] = CODON_TO_INDEX[codon]
Here is a snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedBetaModel` class. Written by Jesse Bloom and Sarah Hilton. """ class test_GammaBeta_ExpCM(unittest.TestCase): """Test gamma distributed beta for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments BASEMODEL = phydmslib.models.ExpCM def test_GammaDistributedBeta(self): """Initialize, test values, update, test again.""" random.seed(1) numpy.random.seed(1) nsites = 10 # create preference set prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> . Write the next line using the current file imports: import random import unittest import numpy import scipy.optimize import phydmslib.models from phydmslib.constants import N_AA, N_NT, AA_TO_INDEX and context from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} , which may include functions, classes, or code. Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Here is a snippet: <|code_start|> Written by Jesse Bloom and Sarah Hilton. """ class test_GammaBeta_ExpCM(unittest.TestCase): """Test gamma distributed beta for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments BASEMODEL = phydmslib.models.ExpCM def test_GammaDistributedBeta(self): """Initialize, test values, update, test again.""" random.seed(1) numpy.random.seed(1) nsites = 10 # create preference set prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) if self.BASEMODEL == phydmslib.models.ExpCM: <|code_end|> . Write the next line using the current file imports: import random import unittest import numpy import scipy.optimize import phydmslib.models from phydmslib.constants import N_AA, N_NT, AA_TO_INDEX and context from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} , which may include functions, classes, or code. Output only the next line.
paramvalues = {"eta": numpy.random.dirichlet([5] * (N_NT - 1)),
Next line prediction: <|code_start|>"""Tests `phydmslib.models.GammaDistributedBetaModel` class. Written by Jesse Bloom and Sarah Hilton. """ class test_GammaBeta_ExpCM(unittest.TestCase): """Test gamma distributed beta for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments BASEMODEL = phydmslib.models.ExpCM def test_GammaDistributedBeta(self): """Initialize, test values, update, test again.""" random.seed(1) numpy.random.seed(1) nsites = 10 # create preference set prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> . Use current file imports: (import random import unittest import numpy import scipy.optimize import phydmslib.models from phydmslib.constants import N_AA, N_NT, AA_TO_INDEX) and context including class names, function names, or small code snippets from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Based on the snippet: <|code_start|> class test_simulateAlignment_ExpCM(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_simulateAlignment(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) alignmentPrefix = "test" # define model nsites = 1000 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) kappa = 4.2 omega = 0.4 beta = 1.5 mu = 0.3 if self.MODEL == phydmslib.models.ExpCM: <|code_end|> , predict the immediate next line with the help of imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo from phydmslib.constants import N_NT, AA_TO_INDEX, N_AA and context (classes, functions, sometimes code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
phi = numpy.random.dirichlet([7] * N_NT)
Predict the next line after this snippet: <|code_start|> Makes sure we can correctly simulate an alignment given a model and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_simulateAlignment(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) alignmentPrefix = "test" # define model nsites = 1000 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> using the current file's imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo from phydmslib.constants import N_NT, AA_TO_INDEX, N_AA and any relevant context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Next line prediction: <|code_start|>"""Tests alignment simulation. Makes sure we can correctly simulate an alignment given a model and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_simulateAlignment(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) alignmentPrefix = "test" # define model nsites = 1000 prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> . Use current file imports: (import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo from phydmslib.constants import N_NT, AA_TO_INDEX, N_AA) and context including class names, function names, or small code snippets from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
rprefs = numpy.random.dirichlet([1] * N_AA)
Using the snippet: <|code_start|>"""Tests the calculation of spielmanwr, following Spielman and Wilke, 2015. Written by Jesse Bloom and Sarah Hilton. """ class testExpCM_spielmanwr(unittest.TestCase): """Test the calculation of `spielmanwr` using the model `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 <|code_end|> , determine the next line of code. You have imports: import random import unittest import numpy import phydmslib.models from phydmslib.constants import (N_NT, N_AA, AA_TO_INDEX, N_CODON, CODON_SINGLEMUT, CODON_NONSYN) and context (class names, function names, or code) available: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_CODON = len(CODON_TO_INDEX) # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') . Output only the next line.
g = numpy.random.dirichlet([5] * N_NT)
Continue the code snippet: <|code_start|>"""Tests the calculation of spielmanwr, following Spielman and Wilke, 2015. Written by Jesse Bloom and Sarah Hilton. """ class testExpCM_spielmanwr(unittest.TestCase): """Test the calculation of `spielmanwr` using the model `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> . Use current file imports: import random import unittest import numpy import phydmslib.models from phydmslib.constants import (N_NT, N_AA, AA_TO_INDEX, N_CODON, CODON_SINGLEMUT, CODON_NONSYN) and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_CODON = len(CODON_TO_INDEX) # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') . Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Next line prediction: <|code_start|>"""Tests the calculation of spielmanwr, following Spielman and Wilke, 2015. Written by Jesse Bloom and Sarah Hilton. """ class testExpCM_spielmanwr(unittest.TestCase): """Test the calculation of `spielmanwr` using the model `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> . Use current file imports: (import random import unittest import numpy import phydmslib.models from phydmslib.constants import (N_NT, N_AA, AA_TO_INDEX, N_CODON, CODON_SINGLEMUT, CODON_NONSYN)) and context including class names, function names, or small code snippets from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_CODON = len(CODON_TO_INDEX) # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|> # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) if self.MODEL == phydmslib.models.ExpCM: self.model = phydmslib.models.ExpCM(prefs) elif self.MODEL == phydmslib.models.ExpCM_empirical_phi: self.model = phydmslib.models.ExpCM_empirical_phi(prefs, g) else: raise ValueError("Invalid MODEL: {0}".format(self.MODEL)) # test `_spielman_wr` calculation wr = [] for n in range(self.model.nsites): numerator = 0 denominator = 0 <|code_end|> using the current file's imports: import random import unittest import numpy import phydmslib.models from phydmslib.constants import (N_NT, N_AA, AA_TO_INDEX, N_CODON, CODON_SINGLEMUT, CODON_NONSYN) and any relevant context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_CODON = len(CODON_TO_INDEX) # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') . Output only the next line.
for x in range(N_CODON):
Predict the next line after this snippet: <|code_start|> def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) if self.MODEL == phydmslib.models.ExpCM: self.model = phydmslib.models.ExpCM(prefs) elif self.MODEL == phydmslib.models.ExpCM_empirical_phi: self.model = phydmslib.models.ExpCM_empirical_phi(prefs, g) else: raise ValueError("Invalid MODEL: {0}".format(self.MODEL)) # test `_spielman_wr` calculation wr = [] for n in range(self.model.nsites): numerator = 0 denominator = 0 for x in range(N_CODON): for y in range(N_CODON): <|code_end|> using the current file's imports: import random import unittest import numpy import phydmslib.models from phydmslib.constants import (N_NT, N_AA, AA_TO_INDEX, N_CODON, CODON_SINGLEMUT, CODON_NONSYN) and any relevant context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_CODON = len(CODON_TO_INDEX) # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') . Output only the next line.
if CODON_SINGLEMUT[x][y] and CODON_NONSYN[x][y]:
Based on the snippet: <|code_start|> def testExpCM_spielmanwr(self): """Test the `ExpCM` function `_spielman_wr`.""" # create models random.seed(1) numpy.random.seed(1) nsites = 10 g = numpy.random.dirichlet([5] * N_NT) prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) if self.MODEL == phydmslib.models.ExpCM: self.model = phydmslib.models.ExpCM(prefs) elif self.MODEL == phydmslib.models.ExpCM_empirical_phi: self.model = phydmslib.models.ExpCM_empirical_phi(prefs, g) else: raise ValueError("Invalid MODEL: {0}".format(self.MODEL)) # test `_spielman_wr` calculation wr = [] for n in range(self.model.nsites): numerator = 0 denominator = 0 for x in range(N_CODON): for y in range(N_CODON): <|code_end|> , predict the immediate next line with the help of imports: import random import unittest import numpy import phydmslib.models from phydmslib.constants import (N_NT, N_AA, AA_TO_INDEX, N_CODON, CODON_SINGLEMUT, CODON_NONSYN) and context (classes, functions, sometimes code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_CODON = len(CODON_TO_INDEX) # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') . Output only the next line.
if CODON_SINGLEMUT[x][y] and CODON_NONSYN[x][y]:
Based on the snippet: <|code_start|>""" class test_simulateRandomSeed_ExpCM(unittest.TestCase): """Tests `simulate.simulateAlignment` module with different seeds.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_simulateAlignmentRandomSeed(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) # define model nsites = 200 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) kappa = 4.2 omega = 0.4 beta = 1.5 mu = 0.3 if self.MODEL == phydmslib.models.ExpCM: <|code_end|> , predict the immediate next line with the help of imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo import glob from phydmslib.constants import N_NT, N_AA, AA_TO_INDEX and context (classes, functions, sometimes code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} . Output only the next line.
phi = numpy.random.dirichlet([7] * N_NT)
Continue the code snippet: <|code_start|>"""Tests random number seeding in aligment simulation. Makes sure the random numbering seeding gives reproducible results. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateRandomSeed_ExpCM(unittest.TestCase): """Tests `simulate.simulateAlignment` module with different seeds.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_simulateAlignmentRandomSeed(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) # define model nsites = 200 prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> . Use current file imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo import glob from phydmslib.constants import N_NT, N_AA, AA_TO_INDEX and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} . Output only the next line.
rprefs = numpy.random.dirichlet([1] * N_AA)
Based on the snippet: <|code_start|>"""Tests random number seeding in aligment simulation. Makes sure the random numbering seeding gives reproducible results. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateRandomSeed_ExpCM(unittest.TestCase): """Tests `simulate.simulateAlignment` module with different seeds.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi def test_simulateAlignmentRandomSeed(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) # define model nsites = 200 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> , predict the immediate next line with the help of imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo import glob from phydmslib.constants import N_NT, N_AA, AA_TO_INDEX and context (classes, functions, sometimes code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Predict the next line after this snippet: <|code_start|> "--brlen", "scale"]) omegabysitefile = simulateprefix + "_omegabysite.txt" omegas = pandas.read_csv(omegabysitefile, sep="\t", comment="#") divpressureomegas = omegas[omegas["site"].isin(divpressuresites)] self.assertTrue(len(divpressureomegas) == len(divpressuresites)) self.assertTrue( (divpressureomegas["omega"].values > 2).all(), "Not all divpressure sites have omega > 2:\n{0}" .format(divpressureomegas)) self.assertTrue( (divpressureomegas["P"].values < 0.08).all(), "Not all divpressure sites have P < 0.08:\n{0}" .format(divpressureomegas)) nspurious = len( omegas[ (omegas["omega"] > 2) & (omegas["P"] < 0.05) & (~omegas["site"].isin(divpressuresites))]) self.assertTrue(nspurious <= 1, "{0} spurious sites".format(nspurious)) for f in ["custom_matrix_frequencies.txt"]: if os.path.isfile(f): os.remove(f) class test_OmegaBySiteYNGKP(test_OmegaBySiteExpCM): """Tests ``--omegabysite`` to ``phydms`` for `YNGKP_M0`.""" def initializeModel(self): """Init model.""" <|code_end|> using the current file's imports: import os import unittest import subprocess import random import pandas import phydmslib.file_io import phydmslib.models import phydmslib.simulate import pyvolve import numpy from phydmslib.constants import N_NT and any relevant context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) . Output only the next line.
e_pw = numpy.full((3, N_NT), 1.0 / N_NT, dtype="float")
Here is a snippet: <|code_start|>"""Tests `phydmslib.models.YNGKP_M0` class. Written by Jesse Bloom. Edited by Sarah Hilton Uses `sympy` to make sure attributes and derivatives of attributes are correct for `YNGKP_M0` implemented in `phydmslib.models`. """ class testYNGKP_M0(unittest.TestCase): """Test YNGKP M0.""" def test_YNGKP_M0(self): """Initialize `YNGKP_M0`, test values, update, test again.""" # create alignment numpy.random.seed(1) random.seed(1) <|code_end|> . Write the next line using the current file imports: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import N_NT, N_CODON and context from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_CODON = len(CODON_TO_INDEX) , which may include functions, classes, or code. Output only the next line.
self.e_pa = numpy.random.uniform(0.12, 1.0, size=(3, N_NT))
Continue the code snippet: <|code_start|> omega = 0.4 kappa = 2.5 self.YNGKP_M0 = phydmslib.models.YNGKP_M0( self.e_pa, self.nsites, omega=omega, kappa=kappa) self.assertTrue(numpy.allclose(omega, self.YNGKP_M0.omega)) self.assertTrue(numpy.allclose(kappa, self.YNGKP_M0.kappa)) self.assertTrue( numpy.allclose( numpy.repeat(1.0, self.nsites), self.YNGKP_M0.stationarystate.sum(axis=1))) # now check YNGKP_M0 attributes / derivates, updating several times for _update in range(2): self.params = { "omega": random.uniform(0.1, 2), "kappa": random.uniform(0.5, 10), "mu": random.uniform(0.05, 5.0)} self.YNGKP_M0.updateParams(self.params) self.check_YNGKP_M0_attributes() self.check_YNGKP_M0_derivatives() self.check_YNGKP_M0_matrix_exponentials() def check_YNGKP_M0_attributes(self): """Make sure `YNGKP_M0` has the expected attribute values.""" self.assertEqual(self.nsites, self.YNGKP_M0.nsites) # make sure Prxy has rows summing to zero self.assertFalse(numpy.isnan(self.YNGKP_M0.Pxy).any()) self.assertFalse(numpy.isinf(self.YNGKP_M0.Pxy).any()) <|code_end|> . Use current file imports: import random import unittest import numpy import scipy.linalg import scipy.optimize import phydmslib.models from phydmslib.constants import N_NT, N_CODON and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # N_NT = len(INDEX_TO_NT) # # N_CODON = len(CODON_TO_INDEX) . Output only the next line.
diag = numpy.eye(N_CODON, dtype="bool")
Next line prediction: <|code_start|> divsites = [] assert all((1 <= r <= model.nsites for r in divsites)) partitions = [] for r in range(model.nsites): matrix = numpy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumerate(codons): ntdiffs = [(x[j], y[j]) for j in range(3) if x[j] != y[j]] if len(ntdiffs) == 1: (xnt, ynt) = ntdiffs[0] qxy = 1.0 if (xnt in purines) == (ynt in purines): qxy *= model.kappa (xaa, yaa) = (codon_dict[x], codon_dict[y]) fxy = 1.0 if xaa != yaa: if type(model) ==\ phydmslib.models.ExpCM_empirical_phi_divpressure: fxy *= (model.omega * (1 + model.omega2 * model.deltar[r])) elif r + 1 in divsites: fxy *= divomega else: fxy *= model.omega if type(model) in [phydmslib.models.ExpCM, phydmslib.models.ExpCM_empirical_phi, (phydmslib.models .ExpCM_empirical_phi_divpressure)]: <|code_end|> . Use current file imports: (import os import sys import math import phydmslib.models import pyvolve import numpy import random import Bio.Phylo import doctest from phydmslib.constants import (NT_TO_INDEX, AA_TO_INDEX, ALMOST_ZERO) from tempfile import mkstemp) and context including class names, function names, or small code snippets from other files: # Path: phydmslib/constants.py # NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()} # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # ALMOST_ZERO = 1.0e-6 . Output only the next line.
qxy *= model.phi[NT_TO_INDEX[ynt]]
Given the code snippet: <|code_start|> assert all((1 <= r <= model.nsites for r in divsites)) partitions = [] for r in range(model.nsites): matrix = numpy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumerate(codons): ntdiffs = [(x[j], y[j]) for j in range(3) if x[j] != y[j]] if len(ntdiffs) == 1: (xnt, ynt) = ntdiffs[0] qxy = 1.0 if (xnt in purines) == (ynt in purines): qxy *= model.kappa (xaa, yaa) = (codon_dict[x], codon_dict[y]) fxy = 1.0 if xaa != yaa: if type(model) ==\ phydmslib.models.ExpCM_empirical_phi_divpressure: fxy *= (model.omega * (1 + model.omega2 * model.deltar[r])) elif r + 1 in divsites: fxy *= divomega else: fxy *= model.omega if type(model) in [phydmslib.models.ExpCM, phydmslib.models.ExpCM_empirical_phi, (phydmslib.models .ExpCM_empirical_phi_divpressure)]: qxy *= model.phi[NT_TO_INDEX[ynt]] <|code_end|> , generate the next line using the imports in this file: import os import sys import math import phydmslib.models import pyvolve import numpy import random import Bio.Phylo import doctest from phydmslib.constants import (NT_TO_INDEX, AA_TO_INDEX, ALMOST_ZERO) from tempfile import mkstemp and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()} # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # ALMOST_ZERO = 1.0e-6 . Output only the next line.
pix = model.pi[r][AA_TO_INDEX[xaa]]**model.beta
Given snippet: <|code_start|> partitions = [] for r in range(model.nsites): matrix = numpy.zeros((len(codons), len(codons)), dtype='float') for (xi, x) in enumerate(codons): for (yi, y) in enumerate(codons): ntdiffs = [(x[j], y[j]) for j in range(3) if x[j] != y[j]] if len(ntdiffs) == 1: (xnt, ynt) = ntdiffs[0] qxy = 1.0 if (xnt in purines) == (ynt in purines): qxy *= model.kappa (xaa, yaa) = (codon_dict[x], codon_dict[y]) fxy = 1.0 if xaa != yaa: if type(model) ==\ phydmslib.models.ExpCM_empirical_phi_divpressure: fxy *= (model.omega * (1 + model.omega2 * model.deltar[r])) elif r + 1 in divsites: fxy *= divomega else: fxy *= model.omega if type(model) in [phydmslib.models.ExpCM, phydmslib.models.ExpCM_empirical_phi, (phydmslib.models .ExpCM_empirical_phi_divpressure)]: qxy *= model.phi[NT_TO_INDEX[ynt]] pix = model.pi[r][AA_TO_INDEX[xaa]]**model.beta piy = model.pi[r][AA_TO_INDEX[yaa]]**model.beta <|code_end|> , continue by predicting the next line. Consider current file imports: import os import sys import math import phydmslib.models import pyvolve import numpy import random import Bio.Phylo import doctest from phydmslib.constants import (NT_TO_INDEX, AA_TO_INDEX, ALMOST_ZERO) from tempfile import mkstemp and context: # Path: phydmslib/constants.py # NT_TO_INDEX = {nt: i for (i, nt) in INDEX_TO_NT.items()} # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # ALMOST_ZERO = 1.0e-6 which might include code, classes, or functions. Output only the next line.
if abs(pix - piy) > ALMOST_ZERO:
Given the following code snippet before the placeholder: <|code_start|>"""Tests alignment simulation. Makes sure we can correctly simulate an alignment given an `ExpCM` with divpressure and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM_divselection(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi_divpressure def test_simulateAlignment(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) alignmentPrefix = "test" # define model nsites = 1000 prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> , predict the next line using imports from the current file: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo from phydmslib.constants import N_AA, AA_TO_INDEX, N_NT and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
rprefs = numpy.random.dirichlet([1] * N_AA)
Predict the next line after this snippet: <|code_start|>Makes sure we can correctly simulate an alignment given an `ExpCM` with divpressure and a tree. Written by Sarah Hilton and Jesse Bloom. """ class test_simulateAlignment_ExpCM_divselection(unittest.TestCase): """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi_divpressure def test_simulateAlignment(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) alignmentPrefix = "test" # define model nsites = 1000 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> using the current file's imports: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo from phydmslib.constants import N_AA, AA_TO_INDEX, N_NT and any relevant context from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Given the following code snippet before the placeholder: <|code_start|> """Tests `simulateAlignment` of `simulate.py` module.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM_empirical_phi_divpressure def test_simulateAlignment(self): """Simulate evolution, ensure scaled branches match number of subs.""" numpy.random.seed(1) random.seed(1) alignmentPrefix = "test" # define model nsites = 1000 prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([1] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) kappa = 4.2 omega = 0.4 beta = 1.5 mu = 0.3 omega2 = 1.2 deltar = numpy.array([1 if x in random.sample(range(nsites), 20) else 0 for x in range(nsites)]) if self.MODEL == phydmslib.models.ExpCM_empirical_phi_divpressure: <|code_end|> , predict the next line using imports from the current file: import os import numpy import unittest import random import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import Bio.SeqIO import Bio.Phylo from phydmslib.constants import N_AA, AA_TO_INDEX, N_NT and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
g = numpy.random.dirichlet([7] * N_NT)
Continue the code snippet: <|code_start|> def tfunc(x): """Negative log likelihood when `x` is branch lengths.""" self.t = x return -self.loglik def tdfunc(x): """Negative gradient loglik with respect to branch lengths.""" self.t = x return -self.dloglik_dt def _printResult(opttype, result, i, old, new): """Print summary of optimization result.""" if printfunc is not None: printfunc('Step {0}, optimized {1}.\n' 'Likelihood went from {2} to {3}.\n' 'Max magnitude in Jacobian is {4}.\n' 'Full optimization result:\n{5}\n' .format(i, opttype, old, new, numpy.absolute(result.jac).max(), result)) oldloglik = self.loglik converged = False firstbrlenpass = True options = {'ftol': 1.0e-7} # optimization options params_args = {'method': 'L-BFGS-B', "bounds": self.paramsarraybounds, "options": options } tree_args = {'method': 'L-BFGS-B', <|code_end|> . Use current file imports: import copy import warnings import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import doctest from phydmslib.numutils import broadcastMatrixVectorMultiply from phydmslib.constants import ALMOST_ZERO, CODON_TO_INDEX, N_CODON and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # ALMOST_ZERO = 1.0e-6 # # CODON_TO_INDEX = {} # # N_CODON = len(CODON_TO_INDEX) . Output only the next line.
'bounds': [(ALMOST_ZERO, None)] * len(self.t),
Continue the code snippet: <|code_start|> else: self._dLshape[param] = (len(paramvalue), self.nsites, N_CODON) else: raise ValueError("Cannot handle param: {0}, {1}".format( param, paramvalue)) tipnodes = [] internalnodes = [] self.tips = numpy.zeros((self.ntips, self.nsites), dtype='int') self.gaps = [] self.descendants = [] self._t = numpy.full((self.nnodes - 1,), -1, dtype='float') for node in self._tree.find_clades(order='postorder'): if node.is_terminal(): tipnodes.append(node) else: internalnodes.append(node) for (n, node) in enumerate(tipnodes + internalnodes): if node != self._tree.root: assert n < self.nnodes - 1 self._t[n] = node.branch_length if node.is_terminal(): assert n < self.ntips self.descendants.append([]) seq = alignment_d[node.name] nodegaps = [] for r in range(self.nsites): codon = seq[3 * r:3 * r + 3] if codon == '---': nodegaps.append(r) <|code_end|> . Use current file imports: import copy import warnings import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import doctest from phydmslib.numutils import broadcastMatrixVectorMultiply from phydmslib.constants import ALMOST_ZERO, CODON_TO_INDEX, N_CODON and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # ALMOST_ZERO = 1.0e-6 # # CODON_TO_INDEX = {} # # N_CODON = len(CODON_TO_INDEX) . Output only the next line.
elif codon in CODON_TO_INDEX:
Given the code snippet: <|code_start|> assert all({len(seq) == 3 * self.nsites for (head, seq) in alignment}) assert set({head for (head, seq) in alignment} ) == {clade.name for clade in tree.get_terminals()} self.alignment = copy.deepcopy(alignment) self.nseqs = len(alignment) alignment_d = dict(self.alignment) # For internal storage, branch lengths are in model units rather # than codon substitutions per site. So here adjust them from # codon substitutions per site to model units. assert isinstance(tree, Bio.Phylo.BaseTree.Tree), "invalid tree" self._tree = copy.deepcopy(tree) assert self._tree.count_terminals() == self.nseqs if branchScale is None: branchScale = self.model.branchScale else: assert isinstance(branchScale, float) and branchScale > 0 for node in self._tree.find_clades(): if node != self._tree.root: node.branch_length /= branchScale # index nodes self.name_to_nodeindex = {} self.ninternal = len(self._tree.get_nonterminals()) self.ntips = self._tree.count_terminals() self.nnodes = self.ntips + self.ninternal self.rdescend = [-1] * self.ninternal self.ldescend = [-1] * self.ninternal self.underflowlogscale = numpy.zeros(self.nsites, dtype='float') if self._distributionmodel: <|code_end|> , generate the next line using the imports in this file: import copy import warnings import numpy import scipy.optimize import Bio.Phylo import phydmslib.models import doctest from phydmslib.numutils import broadcastMatrixVectorMultiply from phydmslib.constants import ALMOST_ZERO, CODON_TO_INDEX, N_CODON and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # ALMOST_ZERO = 1.0e-6 # # CODON_TO_INDEX = {} # # N_CODON = len(CODON_TO_INDEX) . Output only the next line.
self._Lshape = (self.model.ncats, self.nsites, N_CODON)
Next line prediction: <|code_start|> """`TreeLikelihood` branch length optimization for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM DISTRIBUTIONMODEL = None def setUp(self): """Set up parameters for test.""" random.seed(1) numpy.random.seed(1) self.underflowfreq = 1 # define tree self.newick = ('((node1:0.2,node2:0.3)node4:0.3,node3:0.5)node5:0.04;') tempfile = '_temp.tree' with open(tempfile, 'w') as f: f.write(self.newick) self.tree = Bio.Phylo.read(tempfile, 'newick') os.remove(tempfile) # amino-acid preferences self.nsites = 50 prefs = [] minpref = 0.02 for _r in range(self.nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> . Use current file imports: (import os import unittest import random import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve import numpy from phydmslib.constants import AA_TO_INDEX, N_AA) and context including class names, function names, or small code snippets from other files: # Path: phydmslib/constants.py # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Based on the snippet: <|code_start|> class test_BrLenOptimize_ExpCM(unittest.TestCase): """`TreeLikelihood` branch length optimization for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments MODEL = phydmslib.models.ExpCM DISTRIBUTIONMODEL = None def setUp(self): """Set up parameters for test.""" random.seed(1) numpy.random.seed(1) self.underflowfreq = 1 # define tree self.newick = ('((node1:0.2,node2:0.3)node4:0.3,node3:0.5)node5:0.04;') tempfile = '_temp.tree' with open(tempfile, 'w') as f: f.write(self.newick) self.tree = Bio.Phylo.read(tempfile, 'newick') os.remove(tempfile) # amino-acid preferences self.nsites = 50 prefs = [] minpref = 0.02 for _r in range(self.nsites): <|code_end|> , predict the immediate next line with the help of imports: import os import unittest import random import Bio.Phylo import phydmslib.models import phydmslib.treelikelihood import phydmslib.simulate import pyvolve import numpy from phydmslib.constants import AA_TO_INDEX, N_AA and context (classes, functions, sometimes code) from other files: # Path: phydmslib/constants.py # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_AA = len(INDEX_TO_AA) . Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Predict the next line for this snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedOmegaModel` class. Written by Jesse Bloom. """ class test_GammaDistributedOmega_ExpCM(unittest.TestCase): """Test gamma distributed omega for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments BASEMODEL = phydmslib.models.ExpCM def test_GammaDistributedOmega(self): """Initialize, test values, update, test again.""" random.seed(1) numpy.random.seed(1) nsites = 10 if self.BASEMODEL == phydmslib.models.ExpCM: prefs = [] minpref = 0.01 for _r in range(nsites): <|code_end|> with the help of current file imports: import random import unittest import numpy import scipy.optimize import phydmslib.models from phydmslib.constants import N_AA, AA_TO_INDEX, N_NT and context from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) , which may contain function names, class names, or code. Output only the next line.
rprefs = numpy.random.dirichlet([0.5] * N_AA)
Given snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedOmegaModel` class. Written by Jesse Bloom. """ class test_GammaDistributedOmega_ExpCM(unittest.TestCase): """Test gamma distributed omega for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments BASEMODEL = phydmslib.models.ExpCM def test_GammaDistributedOmega(self): """Initialize, test values, update, test again.""" random.seed(1) numpy.random.seed(1) nsites = 10 if self.BASEMODEL == phydmslib.models.ExpCM: prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() <|code_end|> , continue by predicting the next line. Consider current file imports: import random import unittest import numpy import scipy.optimize import phydmslib.models from phydmslib.constants import N_AA, AA_TO_INDEX, N_NT and context: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) which might include code, classes, or functions. Output only the next line.
prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs)))
Given the code snippet: <|code_start|>"""Tests `phydmslib.models.GammaDistributedOmegaModel` class. Written by Jesse Bloom. """ class test_GammaDistributedOmega_ExpCM(unittest.TestCase): """Test gamma distributed omega for `ExpCM`.""" # use approach here to run multiple tests: # http://stackoverflow.com/questions/17260469/instantiate-python-unittest-testcase-with-arguments BASEMODEL = phydmslib.models.ExpCM def test_GammaDistributedOmega(self): """Initialize, test values, update, test again.""" random.seed(1) numpy.random.seed(1) nsites = 10 if self.BASEMODEL == phydmslib.models.ExpCM: prefs = [] minpref = 0.01 for _r in range(nsites): rprefs = numpy.random.dirichlet([0.5] * N_AA) rprefs[rprefs < minpref] = minpref rprefs /= rprefs.sum() prefs.append(dict(zip(sorted(AA_TO_INDEX.keys()), rprefs))) <|code_end|> , generate the next line using the imports in this file: import random import unittest import numpy import scipy.optimize import phydmslib.models from phydmslib.constants import N_AA, AA_TO_INDEX, N_NT and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # N_AA = len(INDEX_TO_AA) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # N_NT = len(INDEX_TO_NT) . Output only the next line.
paramvalues = {"eta": numpy.random.dirichlet([5] * (N_NT - 1)),
Given the code snippet: <|code_start|> `kappa`, `omega`, `beta`, `mu`, `phi` Model params described in main class doc string. `freeparams` (list of strings) Specifies free parameters. """ self._nsites = len(prefs) assert self.nsites > 0, "No preferences specified" assert all(map(lambda x: x in self.ALLOWEDPARAMS, freeparams)),\ ("Invalid entry in freeparams\nGot: {0}\nAllowed: {1}" .format(', '.join(freeparams), ', '.join(self.ALLOWEDPARAMS))) self._freeparams = list(freeparams) # `freeparams` is property # put prefs in pi self.pi = numpy.ndarray((self.nsites, N_AA), dtype='float') assert (isinstance(prefs, list) and all((isinstance(x, dict) for x in prefs))),\ "prefs is not a list of dicts" for r in range(self.nsites): assert set(prefs[r].keys()) == set(AA_TO_INDEX.keys()),\ "prefs not keyed by amino acids for site {0}".format(r) assert abs(1 - sum(prefs[r].values())) <= ALMOST_ZERO,\ "prefs don't sum to one for site {0}".format(r) for (a, aa) in INDEX_TO_AA.items(): _checkParam('pi', prefs[r][aa], self.PARAMLIMITS, self.PARAMTYPES) self.pi[r][a] = prefs[r][aa] self.pi[r] /= self.pi[r].sum() # renormalize to sum to one # set up attributes defined solely in terms of preferences <|code_end|> , generate the next line using the imports in this file: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') . Output only the next line.
self.pi_codon = numpy.full((self.nsites, N_CODON), -1, dtype='float')
Continue the code snippet: <|code_start|> def _update_pi_vars(self): """Update variables that depend on `pi`. These are `pi_codon`, `ln_pi_codon`, `piAx_piAy`, `piAx_piAy_beta`, `ln_piAx_piAy_beta`. Update using current `pi` and `beta`. """ with numpy.errstate(divide='raise', under='raise', over='raise', invalid='raise'): for r in range(self.nsites): self.pi_codon[r] = self.pi[r][CODON_TO_AA] # [x][y] is piAy pim = numpy.tile(self.pi_codon[r], (N_CODON, 1)) self.piAx_piAy[r] = pim.transpose() / pim self.ln_pi_codon = numpy.log(self.pi_codon) self.piAx_piAy_beta = self.piAx_piAy**self.beta self.ln_piAx_piAy_beta = numpy.log(self.piAx_piAy_beta) def _update_Frxy(self): """ Update `Frxy` from `piAx_piAy_beta`,`ln_piAx_piAy_beta`, `omega`,`beta`. """ self.Frxy.fill(1.0) self.Frxy_no_omega.fill(1.0) with numpy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): (numpy .copyto(self.Frxy_no_omega, -self.ln_piAx_piAy_beta / (1 - self.piAx_piAy_beta), # noqa: E501 <|code_end|> . Use current file imports: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context (classes, functions, or code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') . Output only the next line.
where=numpy.logical_and(CODON_NONSYN, numpy.fabs(1 - self.piAx_piAy_beta) # noqa: E501
Given the following code snippet before the placeholder: <|code_start|> dM_param[j] = (broadcastMatrixVectorMultiply(self.A, broadcastGetCols(broadcastMatrixMultiply(self.B[param][j] * V, self.Ainv), tips))) # noqa: E501 if gaps is not None: if not paramisvec: dM_param[gaps] = numpy.zeros(N_CODON, dtype='float') else: dM_param[:, gaps] = numpy.zeros(N_CODON, dtype='float') return dM_param def _eta_from_phi(self): """Update `eta` using current `phi`.""" self.eta = numpy.ndarray(N_NT - 1, dtype='float') etaprod = 1.0 for w in range(N_NT - 1): self.eta[w] = 1.0 - self.phi[w] / etaprod etaprod *= self.eta[w] _checkParam('eta', self.eta, self.PARAMLIMITS, self.PARAMTYPES) def _update_phi(self): """Update `phi` using current `eta`.""" etaprod = 1.0 for w in range(N_NT - 1): self.phi[w] = etaprod * (1 - self.eta[w]) etaprod *= self.eta[w] self.phi[N_NT - 1] = etaprod def _update_Qxy(self): """Update `Qxy` using current `kappa` and `phi`.""" for w in range(N_NT): numpy.copyto(self.Qxy, self.phi[w], where=CODON_NT_MUT[w]) <|code_end|> , predict the next line using imports from the current file: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context including class names, function names, and sometimes code from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') . Output only the next line.
self.Qxy[CODON_TRANSITION] *= self.kappa
Given the code snippet: <|code_start|> gene-wide `omega`. Returns: `wr` (list) list of `omega_r` values of length `nsites` Following `Spielman and Wilke, MBE, 32:1097-1108 <https://doi.org/10.1093/molbev/msv003>`_, we can predict the `dN/dS` value for each site `r`, :math:`\\rm{spielman}\\omega_r`, from the `ExpCM`. When `norm` is `False`, the `omega_r` values are defined as :math:`\\rm{spielman}\\omega_r = \\frac{\\sum_x\ \\sum_{y \\in N_x}p_{r,x}P_{r,xy}}\ {\\sum_x \\sum_{y \\in Nx}p_{r,x}Q_{xy}}`, where `r,x,y`, :math:`p_{r,x}`, :math:`P_{r,xy}`, and :math:`Q_{x,y}` have the same definitions as in the main `ExpCM` doc string and :math:`N_{x}`is the set of codons which are non-synonymous to codon `x` and differ from `x` by one nucleotide. When `norm` is `True`, the `omega_r` values above are divided by the ExpCM `omega` value. """ wr = [] for r in range(self.nsites): num = 0 den = 0 for i in range(N_CODON): # indices where single mut and non syn true <|code_end|> , generate the next line using the imports in this file: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') . Output only the next line.
j = numpy.where((CODON_SINGLEMUT[i] * CODON_NONSYN[i]) == 1)[0]
Given the code snippet: <|code_start|> `dprx` (dict) Keyed by strings in `freeparams`, each value is `numpy.ndarray` of floats giving derivative of `prx` with respect to that param, or 0 if if `prx` does not depend on parameter. The shape of each array is `(nsites, N_CODON)` except for *eta*, for which it is `(N_NT - 1, nsites, N_CODON)` with the first index ranging over each element in `eta`. Equivalent to `dstationarystate[param]`. `D` (`numpy.ndarray` floats, shape `(nsites, N_CODON)`) Element `r` is diagonal of :math:`\mathbf{D_r}` diagonal matrix, :math:`\mathbf{P_r} = \mathbf{A_r}^{-1} \mathbf{D_r} \mathbf{A_r}` `A` (`numpy.ndarray` floats, shape `(nsites, N_CODON, N_CODON)`) Element r is :math:`\mathbf{A_r}` matrix. `Ainv` (`numpy.ndarray` floats, shape `(nsites, N_CODON, N_CODON)`) Element r is :math:`\mathbf{A_r}^{-1}` matrix. `B` (dict) Keyed by strings in `freeparams`, each value is `numpy.ndarray` of floats giving `B` matrix for that parameter. The shape is `(nsites, N_CODON, N_CODON)` except for *eta*, for which it is `(N_NT - 1, nsites, N_CODON, N_CODON)` with the first index ranging over each element in `eta`. """ # class variables ALLOWEDPARAMS = ['kappa', 'omega', 'beta', 'eta', 'mu'] _REPORTPARAMS = ['kappa', 'omega', 'beta', 'phi'] _PARAMLIMITS = {'kappa': (0.01, 100.0), 'omega': (1.0e-5, 100.0), 'beta': (1.0e-5, 10), 'eta': (0.01, 0.99), 'phi': (0.001, 0.999), <|code_end|> , generate the next line using the imports in this file: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') . Output only the next line.
'pi': (ALMOST_ZERO, 1),
Given the code snippet: <|code_start|> """Update `B`.""" for param in self.freeparams: if param == 'mu': continue paramval = getattr(self, param) if isinstance(paramval, float): self.B[param] = (broadcastMatrixMultiply(self.Ainv, broadcastMatrixMultiply(self.dPrxy[param], self.A))) else: assert isinstance(paramval, numpy.ndarray)\ and paramval.ndim == 1 for j in range(paramval.shape[0]): self.B[param][j] = (broadcastMatrixMultiply(self.Ainv, broadcastMatrixMultiply(self.dPrxy[param][j], self.A))) # noqa: E501 def _update_dprx(self): """Update `dprx`.""" if 'beta' in self.freeparams: for r in range(self.nsites): self.dprx['beta'][r] = (self.prx[r] * (self.ln_pi_codon[r] - numpy.dot(self.ln_pi_codon[r], self.prx[r]))) if 'eta' in self.freeparams: boolterm = numpy.ndarray(N_CODON, dtype='float') with numpy.errstate(divide='raise', under='raise', over='raise', invalid='raise'): for i in range(N_NT - 1): boolterm.fill(0) for j in range(3): <|code_end|> , generate the next line using the imports in this file: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context (functions, classes, or occasionally code) from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') . Output only the next line.
boolterm += ((i <= CODON_NT_INDEX[j]).astype('float')
Here is a snippet: <|code_start|> return bs @property def nsites(self): """See docs for `Model` abstract base class.""" return self._nsites @property def freeparams(self): """See docs for `Model` abstract base class.""" return self._freeparams @property def mu(self): """See docs for `Model` abstract base class.""" return self._mu @mu.setter def mu(self, value): """Set new `mu` value.""" self._mu = value def _calculate_correctedF3X4(self): """Calculate `phi` based on the empirical `e_pw` values""" def F(phi): phi_reshape = phi.reshape((3, N_NT)) functionList = [] stop_frequency = [] for x in range(N_STOP): <|code_end|> . Write the next line using the current file imports: import copy import six import abc import warnings import numpy import scipy.misc import scipy.optimize import scipy.linalg import scipy.stats import scipy.special import doctest from phydmslib.numutils import (broadcastMatrixMultiply, broadcastMatrixVectorMultiply, broadcastGetCols) from phydmslib.constants import (N_CODON, CODON_NONSYN, CODON_TRANSITION, CODON_SINGLEMUT, ALMOST_ZERO, CODON_NT_INDEX, STOP_CODON_TO_NT_INDICES, N_STOP, N_NT, N_AA, INDEX_TO_NT, CODON_NT_MUT, CODON_NT_COUNT, CODON_TO_AA, INDEX_TO_AA, AA_TO_INDEX, CODON_NT) and context from other files: # Path: phydmslib/constants.py # N_CODON = len(CODON_TO_INDEX) # # CODON_NONSYN = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_TRANSITION = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # CODON_SINGLEMUT = numpy.full((N_CODON, N_CODON), False, dtype='bool') # # ALMOST_ZERO = 1.0e-6 # # CODON_NT_INDEX = numpy.full((3, N_CODON), -1, dtype='int') # # STOP_CODON_TO_NT_INDICES = [] # # N_STOP = 0 # # N_NT = len(INDEX_TO_NT) # # N_AA = len(INDEX_TO_AA) # # INDEX_TO_NT = dict(enumerate('ACGT')) # # CODON_NT_MUT = numpy.full((N_NT, N_CODON, N_CODON), False, dtype='bool') # # CODON_NT_COUNT = numpy.zeros((N_NT, N_CODON), dtype='int') # # CODON_TO_AA = [] # # INDEX_TO_AA = dict(enumerate('ACDEFGHIKLMNPQRSTVWY')) # # AA_TO_INDEX = {aa: i for (i, aa) in INDEX_TO_AA.items()} # # CODON_NT = numpy.full((3, N_NT, N_CODON), False, dtype='bool') , which may include functions, classes, or code. Output only the next line.
codonFrequency = STOP_CODON_TO_NT_INDICES[x] * phi_reshape