Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class FeatureToggleAttributesAdminInline(admin.TabularInline):
model = FeatureToggleAttribute
extra = 0
min_num = 1
class FeatureToggleAdmin(admin.ModelAdmin):
inlines = [FeatureToggleAttributesAdminInline]
def get_readonly_fields(self, request, obj=None):
readonly_fields = super().get_readonly_fields(request, obj)
if obj:
readonly_fields += ('uid',)
return readonly_fields
<|code_end|>
with the help of current file imports:
from django.contrib import admin
from .models import FeatureToggleAttribute, FeatureToggle
and context from other files:
# Path: feature_toggle/models.py
# class FeatureToggleAttribute(TimeStampedModel):
# feature_toggle = models.ForeignKey(FeatureToggle, related_name='attributes', on_delete=models.CASCADE)
# key = models.CharField(max_length=ATTRIB_KEY_MAX_LENGTH, choices=ATTRIB_CHOICES)
# value = models.TextField(max_length=ATTRIB_VAL_MAX_LENGTH, null=True, blank=True)
#
# class Meta:
# unique_together = ('feature_toggle', 'key')
# managed = False
#
# def __str__(self):
# return "{ft}: {k} - {v}".format(ft=str(self.feature_toggle), k=self.key, v=self.value)
#
# def __unicode__(self):
# return self.__str__()
#
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
, which may contain function names, class names, or code. Output only the next line. | admin.site.register(FeatureToggle, FeatureToggleAdmin) |
Predict the next line for this snippet: <|code_start|>
ENV_CHOICES = django_model_choices_from_iterable(Environments)
ATTRIB_CHOICES = django_model_choices_from_iterable(Attributes)
ATTRIB_KEY_MAX_LENGTH = getattr(settings, 'FEATURE_TOGGLE_ATTRIB_KEY_MAX_LEN', 100)
ATTRIB_VAL_MAX_LENGTH = getattr(settings, 'FEATURE_TOGGLE_ATTRIB_VAL_MAX_LEN', 1000)
class FeatureToggle(TimeStampedModel):
uid = models.CharField(max_length=20)
name = models.CharField(max_length=20)
environment = models.CharField(max_length=50, choices=ENV_CHOICES)
is_active = models.BooleanField(default=True)
start_date_time = models.DateTimeField(auto_now_add=True)
end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
time_bomb = models.BooleanField(default=False)
class Meta:
unique_together = (('name', 'environment'), ('uid',))
managed = True
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if not self.uid:
self.uid = make_meanigful_id(self.name, length=5)
super().save(force_insert, force_update, using, update_fields)
def set_attribute(self, key, value=None, update_if_existing=True):
attrib, created = self.attributes.get_or_create(key=key)
if not created and not update_if_existing:
<|code_end|>
with the help of current file imports:
from django.conf import settings
from django.db import models
from djutil.models import TimeStampedModel
from feature_toggle.exceptions import FeatureToggleAttributeAlreadyExists
from .constants import Environments, Attributes
from .utilities import django_model_choices_from_iterable, make_meanigful_id
and context from other files:
# Path: feature_toggle/exceptions.py
# class FeatureToggleAttributeAlreadyExists(Exception):
# """
# When trying to create a toggle attribute that already exists.
# """
#
# def __init__(self, **kwargs):
# msg = 'FeatureToggleAttribute already exists with data: {d}'.format(d=kwargs)
# super(FeatureToggleAttributeAlreadyExists, self).__init__(self, msg)
#
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/utilities.py
# def django_model_choices_from_iterable(iterable):
# try:
# return tuple((x, x) for x in iterable)
# except TypeError:
# raise ValueError("must be an iterable")
#
# def make_meanigful_id(string, length=10, cast_uppercase=True):
# _short = meaningful_shorten(string, length=int(math.ceil(length * 0.4)))
# _hash = cheap_hash(string + str(time.time()), length=int(math.ceil(length * 0.6)))
# _id = '{s}{h}'.format(s=_short, h=_hash)[:length]
# return _id.upper() if cast_uppercase else _id
, which may contain function names, class names, or code. Output only the next line. | raise FeatureToggleAttributeAlreadyExists(**dict(key=key)) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
ENV_CHOICES = django_model_choices_from_iterable(Environments)
ATTRIB_CHOICES = django_model_choices_from_iterable(Attributes)
ATTRIB_KEY_MAX_LENGTH = getattr(settings, 'FEATURE_TOGGLE_ATTRIB_KEY_MAX_LEN', 100)
ATTRIB_VAL_MAX_LENGTH = getattr(settings, 'FEATURE_TOGGLE_ATTRIB_VAL_MAX_LEN', 1000)
class FeatureToggle(TimeStampedModel):
uid = models.CharField(max_length=20)
name = models.CharField(max_length=20)
environment = models.CharField(max_length=50, choices=ENV_CHOICES)
is_active = models.BooleanField(default=True)
start_date_time = models.DateTimeField(auto_now_add=True)
end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
time_bomb = models.BooleanField(default=False)
class Meta:
unique_together = (('name', 'environment'), ('uid',))
managed = True
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if not self.uid:
<|code_end|>
, determine the next line of code. You have imports:
from django.conf import settings
from django.db import models
from djutil.models import TimeStampedModel
from feature_toggle.exceptions import FeatureToggleAttributeAlreadyExists
from .constants import Environments, Attributes
from .utilities import django_model_choices_from_iterable, make_meanigful_id
and context (class names, function names, or code) available:
# Path: feature_toggle/exceptions.py
# class FeatureToggleAttributeAlreadyExists(Exception):
# """
# When trying to create a toggle attribute that already exists.
# """
#
# def __init__(self, **kwargs):
# msg = 'FeatureToggleAttribute already exists with data: {d}'.format(d=kwargs)
# super(FeatureToggleAttributeAlreadyExists, self).__init__(self, msg)
#
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/utilities.py
# def django_model_choices_from_iterable(iterable):
# try:
# return tuple((x, x) for x in iterable)
# except TypeError:
# raise ValueError("must be an iterable")
#
# def make_meanigful_id(string, length=10, cast_uppercase=True):
# _short = meaningful_shorten(string, length=int(math.ceil(length * 0.4)))
# _hash = cheap_hash(string + str(time.time()), length=int(math.ceil(length * 0.6)))
# _id = '{s}{h}'.format(s=_short, h=_hash)[:length]
# return _id.upper() if cast_uppercase else _id
. Output only the next line. | self.uid = make_meanigful_id(self.name, length=5) |
Continue the code snippet: <|code_start|>
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle):
assert isinstance(toggle, BaseToggle)
tgl = FeatureToggle.objects.create(name=toggle.name)
for key, value in tgl.attributes.items():
tgl.set_attribute(key, value)
@classmethod
def get_model(cls, uid):
try:
return FeatureToggle.objects.get(uid=uid)
except FeatureToggle.DoesNotExist:
msg = 'Feature Toggle for uid: {u} does not exist.'.format(u=uid)
raise FeatureToggleDoesNotExist(msg)
@classmethod
def get_from_name_and_env(cls, name, environment):
<|code_end|>
. Use current file imports:
import logging
from feature_toggle.constants import Environments
from feature_toggle.exceptions import FeatureToggleDoesNotExist
from feature_toggle.toggle import BaseToggle, Toggle
from .models import FeatureToggle
and context (classes, functions, or code) from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
. Output only the next line. | assert environment in Environments |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle):
assert isinstance(toggle, BaseToggle)
tgl = FeatureToggle.objects.create(name=toggle.name)
for key, value in tgl.attributes.items():
tgl.set_attribute(key, value)
@classmethod
def get_model(cls, uid):
try:
return FeatureToggle.objects.get(uid=uid)
except FeatureToggle.DoesNotExist:
msg = 'Feature Toggle for uid: {u} does not exist.'.format(u=uid)
<|code_end|>
, predict the next line using imports from the current file:
import logging
from feature_toggle.constants import Environments
from feature_toggle.exceptions import FeatureToggleDoesNotExist
from feature_toggle.toggle import BaseToggle, Toggle
from .models import FeatureToggle
and context including class names, function names, and sometimes code from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
. Output only the next line. | raise FeatureToggleDoesNotExist(msg) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle):
<|code_end|>
with the help of current file imports:
import logging
from feature_toggle.constants import Environments
from feature_toggle.exceptions import FeatureToggleDoesNotExist
from feature_toggle.toggle import BaseToggle, Toggle
from .models import FeatureToggle
and context from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
, which may contain function names, class names, or code. Output only the next line. | assert isinstance(toggle, BaseToggle) |
Next line prediction: <|code_start|> @classmethod
def create(cls, toggle):
assert isinstance(toggle, BaseToggle)
tgl = FeatureToggle.objects.create(name=toggle.name)
for key, value in tgl.attributes.items():
tgl.set_attribute(key, value)
@classmethod
def get_model(cls, uid):
try:
return FeatureToggle.objects.get(uid=uid)
except FeatureToggle.DoesNotExist:
msg = 'Feature Toggle for uid: {u} does not exist.'.format(u=uid)
raise FeatureToggleDoesNotExist(msg)
@classmethod
def get_from_name_and_env(cls, name, environment):
assert environment in Environments
try:
tgl = FeatureToggle.objects.get(name=name, environment=environment)
except FeatureToggle.DoesNotExist:
msg = 'Feature for name: {n} and env: {e} does not exist.'.format(n=name, e=environment)
raise FeatureToggleDoesNotExist(msg)
return cls.convert(toggle_model=tgl)
@classmethod
def convert(cls, toggle_model):
toggle_attributes = toggle_model.attibutes.all().values('key', 'value')
toggle_attributes = {attrib['key']: attrib['value'] for attrib in toggle_attributes.items()}
<|code_end|>
. Use current file imports:
(import logging
from feature_toggle.constants import Environments
from feature_toggle.exceptions import FeatureToggleDoesNotExist
from feature_toggle.toggle import BaseToggle, Toggle
from .models import FeatureToggle)
and context including class names, function names, or small code snippets from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
. Output only the next line. | tgl = Toggle( |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
logger = logging.getLogger(__name__)
class FeatureToggleService(object):
@classmethod
def get(cls, uid):
tgl = cls.get_model(uid)
return cls.convert(toggle_model=tgl)
@classmethod
def create(cls, toggle):
assert isinstance(toggle, BaseToggle)
<|code_end|>
, determine the next line of code. You have imports:
import logging
from feature_toggle.constants import Environments
from feature_toggle.exceptions import FeatureToggleDoesNotExist
from feature_toggle.toggle import BaseToggle, Toggle
from .models import FeatureToggle
and context (class names, function names, or code) available:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
. Output only the next line. | tgl = FeatureToggle.objects.create(name=toggle.name) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def test_given_basic_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
simple_active_toggle = BaseToggle(
uid=1,
name="test",
<|code_end|>
. Use current file imports:
(import datetime
import pytest
from feature_toggle.constants import Environments
from feature_toggle.toggle import BaseToggle, Toggle, TimeBombToggle
from feature_toggle.utilities import utc_now)
and context including class names, function names, or small code snippets from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# class TimeBombToggle(Toggle):
# """
# This is a time bomb toggle by default.
#
# A time bomb toggle stops working after the end date. Generally toggle's lifetime should be predetermined.
# If not toggles can pollute the code base. A bit of discipline is needed to maintain toggles and time bomb
# helps enforce it.
#
# This toggle will spit a warning if not time bomb and will get disabled if it is a time bomb.
# i.e., `if toggle` will return false even if it is active
# So don't blame the poor toggle now.
#
# """
#
# def __bool__(self):
# active = super().__bool__()
#
# if active:
# return self.start_date_time <= utc_now() <= self.end_date_time
# return active
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
. Output only the next line. | environment=Environments.Local, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
def test_given_basic_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
import pytest
from feature_toggle.constants import Environments
from feature_toggle.toggle import BaseToggle, Toggle, TimeBombToggle
from feature_toggle.utilities import utc_now
and context (classes, functions, sometimes code) from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# class TimeBombToggle(Toggle):
# """
# This is a time bomb toggle by default.
#
# A time bomb toggle stops working after the end date. Generally toggle's lifetime should be predetermined.
# If not toggles can pollute the code base. A bit of discipline is needed to maintain toggles and time bomb
# helps enforce it.
#
# This toggle will spit a warning if not time bomb and will get disabled if it is a time bomb.
# i.e., `if toggle` will return false even if it is active
# So don't blame the poor toggle now.
#
# """
#
# def __bool__(self):
# active = super().__bool__()
#
# if active:
# return self.start_date_time <= utc_now() <= self.end_date_time
# return active
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
. Output only the next line. | simple_active_toggle = BaseToggle( |
Given snippet: <|code_start|> uid=1,
name="test",
environment=Environments.Local,
is_active=False,
)
assert bool(simple_active_toggle) is False
def test_given_basic_toggle_when_given_invalid_environment_then_fails():
"""
test_case_type: negative
test_case_complexity: simple
"""
with pytest.raises(AssertionError):
BaseToggle(
uid=1,
name="test",
environment='Invalid Environment',
is_active=False,
)
def test_given_simple_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
today = utc_now()
some_far_away_date = today + datetime.timedelta(days=9999)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import pytest
from feature_toggle.constants import Environments
from feature_toggle.toggle import BaseToggle, Toggle, TimeBombToggle
from feature_toggle.utilities import utc_now
and context:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# class TimeBombToggle(Toggle):
# """
# This is a time bomb toggle by default.
#
# A time bomb toggle stops working after the end date. Generally toggle's lifetime should be predetermined.
# If not toggles can pollute the code base. A bit of discipline is needed to maintain toggles and time bomb
# helps enforce it.
#
# This toggle will spit a warning if not time bomb and will get disabled if it is a time bomb.
# i.e., `if toggle` will return false even if it is active
# So don't blame the poor toggle now.
#
# """
#
# def __bool__(self):
# active = super().__bool__()
#
# if active:
# return self.start_date_time <= utc_now() <= self.end_date_time
# return active
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
which might include code, classes, or functions. Output only the next line. | simple_active_toggle = Toggle( |
Given the code snippet: <|code_start|> )
def test_given_simple_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
today = utc_now()
some_far_away_date = today + datetime.timedelta(days=9999)
simple_active_toggle = Toggle(
uid=1,
name="test",
environment=Environments.Local,
is_active=True,
start_date_time=today,
end_date_time=some_far_away_date,
)
assert bool(simple_active_toggle) is True
def test_given_time_bomb_active_toggle_when_evaluated_with_future_end_date_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
today = utc_now()
some_far_away_date = today + datetime.timedelta(days=9999)
<|code_end|>
, generate the next line using the imports in this file:
import datetime
import pytest
from feature_toggle.constants import Environments
from feature_toggle.toggle import BaseToggle, Toggle, TimeBombToggle
from feature_toggle.utilities import utc_now
and context (functions, classes, or occasionally code) from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# class TimeBombToggle(Toggle):
# """
# This is a time bomb toggle by default.
#
# A time bomb toggle stops working after the end date. Generally toggle's lifetime should be predetermined.
# If not toggles can pollute the code base. A bit of discipline is needed to maintain toggles and time bomb
# helps enforce it.
#
# This toggle will spit a warning if not time bomb and will get disabled if it is a time bomb.
# i.e., `if toggle` will return false even if it is active
# So don't blame the poor toggle now.
#
# """
#
# def __bool__(self):
# active = super().__bool__()
#
# if active:
# return self.start_date_time <= utc_now() <= self.end_date_time
# return active
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
. Output only the next line. | simple_active_toggle = TimeBombToggle( |
Given snippet: <|code_start|> """
simple_active_toggle = BaseToggle(
uid=1,
name="test",
environment=Environments.Local,
is_active=False,
)
assert bool(simple_active_toggle) is False
def test_given_basic_toggle_when_given_invalid_environment_then_fails():
"""
test_case_type: negative
test_case_complexity: simple
"""
with pytest.raises(AssertionError):
BaseToggle(
uid=1,
name="test",
environment='Invalid Environment',
is_active=False,
)
def test_given_simple_active_toggle_when_evaluated_then_returns_true():
"""
test_case_type: positive
test_case_complexity: simple
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
import pytest
from feature_toggle.constants import Environments
from feature_toggle.toggle import BaseToggle, Toggle, TimeBombToggle
from feature_toggle.utilities import utc_now
and context:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/toggle.py
# class BaseToggle(object):
# """
# Interface for implementing toggle class
# """
#
# class Attributes(object):
# def __init__(self, attribs):
# assert isinstance(attribs, dict)
#
# self.attribs = attribs
#
# def __getattr__(self, item):
# try:
# return self.attribs[item]
# except KeyError:
# raise AttributeError(item)
#
# def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
# self.uid = uid
# self.name = name
# assert environment in Environments
# self.environment = environment
# self.is_active = is_active
#
# if attributes:
# self.attributes = self.Attributes(attributes)
#
# self.kwargs = kwargs
#
# def __bool__(self):
# return bool(self.is_active)
#
# __nonzero__ = __bool__
#
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
#
# class TimeBombToggle(Toggle):
# """
# This is a time bomb toggle by default.
#
# A time bomb toggle stops working after the end date. Generally toggle's lifetime should be predetermined.
# If not toggles can pollute the code base. A bit of discipline is needed to maintain toggles and time bomb
# helps enforce it.
#
# This toggle will spit a warning if not time bomb and will get disabled if it is a time bomb.
# i.e., `if toggle` will return false even if it is active
# So don't blame the poor toggle now.
#
# """
#
# def __bool__(self):
# active = super().__bool__()
#
# if active:
# return self.start_date_time <= utc_now() <= self.end_date_time
# return active
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
which might include code, classes, or functions. Output only the next line. | today = utc_now() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class BaseToggle(object):
"""
Interface for implementing toggle class
"""
class Attributes(object):
def __init__(self, attribs):
assert isinstance(attribs, dict)
self.attribs = attribs
def __getattr__(self, item):
try:
return self.attribs[item]
except KeyError:
raise AttributeError(item)
def __init__(self, uid, name, environment, is_active, attributes=None, **kwargs):
self.uid = uid
self.name = name
<|code_end|>
, determine the next line of code. You have imports:
import datetime
import warnings
from feature_toggle.constants import Environments
from feature_toggle.utilities import utc_now
and context (class names, function names, or code) available:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
. Output only the next line. | assert environment in Environments |
Given the following code snippet before the placeholder: <|code_start|> self.is_active = is_active
if attributes:
self.attributes = self.Attributes(attributes)
self.kwargs = kwargs
def __bool__(self):
return bool(self.is_active)
__nonzero__ = __bool__
class Toggle(BaseToggle):
def __init__(self, uid, name, environment, is_active,
start_date_time, end_date_time,
attributes=None, **kwargs):
assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
self.start_date_time = start_date_time
assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
self.end_date_time = end_date_time
super().__init__(uid, name, environment, is_active, attributes, **kwargs)
def __bool__(self):
active = super().__bool__()
<|code_end|>
, predict the next line using imports from the current file:
import datetime
import warnings
from feature_toggle.constants import Environments
from feature_toggle.utilities import utc_now
and context including class names, function names, and sometimes code from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/utilities.py
# def utc_now():
# return datetime.datetime.now(tz=pytz.utc)
. Output only the next line. | if self.end_date_time and self.end_date_time < utc_now(): |
Given snippet: <|code_start|>
class TestToggleService(TestCase):
@classmethod
def setUpClass(cls):
cls.active_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=True,
)
cls.inactive_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=False,
)
@classmethod
def tearDownClass(cls):
FeatureToggle.objects.all().delete()
def test_when_toggle_in_db_then_get_from_uid(self):
FeatureToggleService.get(uid='test1')
def test_toggle_without_name_and_code(self):
with self.assertRaises(RuntimeError):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import datetime
from django.test import TestCase
from constants import Environments
from feature_toggle import constants
from feature_toggle.exceptions import FeatureToggleDoesNotExist, FeatureToggleAlreadyExists
from feature_toggle.models import FeatureToggle
from feature_toggle.toggle import Toggle
from services import FeatureToggleService
and context:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# class FeatureToggleAlreadyExists(Exception):
# """
# This exception is raised when trying to create a toggle that already exists.
# """
# pass
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
#
# Path: feature_toggle/toggle.py
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
which might include code, classes, or functions. Output only the next line. | Toggle(environment=constants.FeatureToggle.Environment.LOCAL) |
Continue the code snippet: <|code_start|> is_active=True,
)
cls.inactive_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=False,
)
@classmethod
def tearDownClass(cls):
FeatureToggle.objects.all().delete()
def test_when_toggle_in_db_then_get_from_uid(self):
FeatureToggleService.get(uid='test1')
def test_toggle_without_name_and_code(self):
with self.assertRaises(RuntimeError):
Toggle(environment=constants.FeatureToggle.Environment.LOCAL)
def test_toggle_with_invalid_environment(self):
with self.assertRaises(AssertionError):
Toggle(environment='__invalid__', name=self.active_ft_tgl.name, code=self.active_ft_tgl.code)
def test_existing_toggle(self):
ft_tgl = self.active_ft_tgl
tgl = Toggle(environment=ft_tgl.environment, name=ft_tgl.name, code=ft_tgl.code)
self._toggle_equality_test(tgl, ft_tgl)
def test_non_existing_toggle(self):
<|code_end|>
. Use current file imports:
import datetime
from django.test import TestCase
from constants import Environments
from feature_toggle import constants
from feature_toggle.exceptions import FeatureToggleDoesNotExist, FeatureToggleAlreadyExists
from feature_toggle.models import FeatureToggle
from feature_toggle.toggle import Toggle
from services import FeatureToggleService
and context (classes, functions, or code) from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# class FeatureToggleAlreadyExists(Exception):
# """
# This exception is raised when trying to create a toggle that already exists.
# """
# pass
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
#
# Path: feature_toggle/toggle.py
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
. Output only the next line. | with self.assertRaises(FeatureToggleDoesNotExist): |
Based on the snippet: <|code_start|> ft_tgl = self.inactive_ft_tgl
ft_tgl.set_attribute(constants.FeatureToggle.Attributes.END_DATE, tomorrow)
tgl = Toggle(environment=ft_tgl.environment, name=ft_tgl.name, code=ft_tgl.code)
self.assertFalse(tgl.is_enabled())
def test_is_enabled_with_inactive_toggle_with_both_start_and_end_date(self):
yesterday = datetime.date.today() - datetime.timedelta(1)
tomorrow = datetime.date.today() + datetime.timedelta(1)
ft_tgl = self.inactive_ft_tgl
ft_tgl.set_attribute(constants.FeatureToggle.Attributes.START_DATE, yesterday)
ft_tgl.set_attribute(constants.FeatureToggle.Attributes.END_DATE, tomorrow)
tgl = Toggle(environment=ft_tgl.environment, name=ft_tgl.name, code=ft_tgl.code)
self.assertFalse(tgl.is_enabled())
def test_is_attribute_of_a_toggle(self):
time_bomb = '__time_bomb__'
ft_tgl = self.active_ft_tgl
ft_tgl.set_attribute(constants.FeatureToggle.Attributes.TIME_BOMB, time_bomb)
tgl = Toggle(environment=ft_tgl.environment, name=ft_tgl.name, code=ft_tgl.code)
self.assertEqual(getattr(tgl, constants.FeatureToggle.Attributes.TIME_BOMB), time_bomb)
def _toggle_equality_test(self, tgl, ft_tgl):
self.assertEqual(tgl.code, ft_tgl.code)
self.assertEqual(tgl.name, ft_tgl.name)
self.assertEqual(tgl.environment, ft_tgl.environment)
self.assertEqual(tgl.is_active(), ft_tgl.is_active)
def test_creating_existing_toggle(self):
ft_tgl = self.active_ft_tgl
tgl = Toggle(environment=ft_tgl.environment, name=ft_tgl.name, code=ft_tgl.code)
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from django.test import TestCase
from constants import Environments
from feature_toggle import constants
from feature_toggle.exceptions import FeatureToggleDoesNotExist, FeatureToggleAlreadyExists
from feature_toggle.models import FeatureToggle
from feature_toggle.toggle import Toggle
from services import FeatureToggleService
and context (classes, functions, sometimes code) from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# class FeatureToggleAlreadyExists(Exception):
# """
# This exception is raised when trying to create a toggle that already exists.
# """
# pass
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
#
# Path: feature_toggle/toggle.py
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
. Output only the next line. | with self.assertRaises(FeatureToggleAlreadyExists): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
class TestToggleService(TestCase):
@classmethod
def setUpClass(cls):
<|code_end|>
, predict the immediate next line with the help of imports:
import datetime
from django.test import TestCase
from constants import Environments
from feature_toggle import constants
from feature_toggle.exceptions import FeatureToggleDoesNotExist, FeatureToggleAlreadyExists
from feature_toggle.models import FeatureToggle
from feature_toggle.toggle import Toggle
from services import FeatureToggleService
and context (classes, functions, sometimes code) from other files:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# class FeatureToggleAlreadyExists(Exception):
# """
# This exception is raised when trying to create a toggle that already exists.
# """
# pass
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
#
# Path: feature_toggle/toggle.py
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
. Output only the next line. | cls.active_tgl = FeatureToggle.objects.create( |
Using the snippet: <|code_start|>
class TestToggleService(TestCase):
@classmethod
def setUpClass(cls):
cls.active_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=True,
)
cls.inactive_tgl = FeatureToggle.objects.create(
uid='test1',
name='test1',
environment=Environments.Local,
is_active=False,
)
@classmethod
def tearDownClass(cls):
FeatureToggle.objects.all().delete()
def test_when_toggle_in_db_then_get_from_uid(self):
FeatureToggleService.get(uid='test1')
def test_toggle_without_name_and_code(self):
with self.assertRaises(RuntimeError):
<|code_end|>
, determine the next line of code. You have imports:
import datetime
from django.test import TestCase
from constants import Environments
from feature_toggle import constants
from feature_toggle.exceptions import FeatureToggleDoesNotExist, FeatureToggleAlreadyExists
from feature_toggle.models import FeatureToggle
from feature_toggle.toggle import Toggle
from services import FeatureToggleService
and context (class names, function names, or code) available:
# Path: feature_toggle/constants.py
# class Attribute(Container):
# class Environment(Container):
# def __init__(self):
# def __init__(self):
#
# Path: feature_toggle/exceptions.py
# class FeatureToggleDoesNotExist(Exception):
# """
# This exception is to aid consumers in providing an common exception to catch instead of relying on
# model.DoesNotExist.
# """
# pass
#
# class FeatureToggleAlreadyExists(Exception):
# """
# This exception is raised when trying to create a toggle that already exists.
# """
# pass
#
# Path: feature_toggle/models.py
# class FeatureToggle(TimeStampedModel):
# uid = models.CharField(max_length=20)
# name = models.CharField(max_length=20)
# environment = models.CharField(max_length=50, choices=ENV_CHOICES)
# is_active = models.BooleanField(default=True)
# start_date_time = models.DateTimeField(auto_now_add=True)
# end_date_time = models.DateTimeField(auto_now_add=True) # todo: add 3 months from now by default
# time_bomb = models.BooleanField(default=False)
#
# class Meta:
# unique_together = (('name', 'environment'), ('uid',))
# managed = True
#
# def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if not self.uid:
# self.uid = make_meanigful_id(self.name, length=5)
# super().save(force_insert, force_update, using, update_fields)
#
# def set_attribute(self, key, value=None, update_if_existing=True):
# attrib, created = self.attributes.get_or_create(key=key)
# if not created and not update_if_existing:
# raise FeatureToggleAttributeAlreadyExists(**dict(key=key))
#
# attrib.value = value
# attrib.save()
#
# def __str__(self):
# return "{e}: {n}({u})".format(e=self.environment, n=self.name, u=self.uid)
#
# def __unicode__(self):
# return self.__str__()
#
# Path: feature_toggle/toggle.py
# class Toggle(BaseToggle):
#
# def __init__(self, uid, name, environment, is_active,
# start_date_time, end_date_time,
# attributes=None, **kwargs):
# assert isinstance(start_date_time, datetime.datetime) # should be a time stamp
# assert start_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.start_date_time = start_date_time
#
# assert isinstance(end_date_time, datetime.datetime) # should be a time stamp
# assert end_date_time.tzinfo is not None # should have a time zone. otherwise causes confusions
# self.end_date_time = end_date_time
# super().__init__(uid, name, environment, is_active, attributes, **kwargs)
#
# def __bool__(self):
# active = super().__bool__()
#
# if self.end_date_time and self.end_date_time < utc_now():
# # this check because toggles can quickly get overwhelming
# warnings.warn('{t} has expired. Get rid of me and help me attain salvation'.format(t=str(self)))
#
# return active
. Output only the next line. | Toggle(environment=constants.FeatureToggle.Environment.LOCAL) |
Given snippet: <|code_start|>
# %% useful funcs
def coefs2mats(coefs, n=8):
const = coefs[0]
jac = coefs[1:n+1]
hes = np.zeros((n,n))
hes[np.triu_indices(n)] = hes.T[np.triu_indices(n)] = coefs[n+1:]
hes[np.diag_indices(n)] *= 2
return const, jac, hes
# invento ejemplo para testear el fiteo de hiperparabola
# vert = np.random.rand(8) # considero centrado en el origen, no pierdo nada
jac = np.random.rand(8) * 2 -1
hes = np.random.rand(8,8) * 2 - 1
hes = (hes + hes.T) / 2 # lo hago simetrico
deltaX = np.random.rand(10000, 8)
#y = deltaX.dot(jac)
#y += (deltaX.reshape((-1,8,1,1))
# * hes.reshape((1,8,8,1))
# * deltaX.T.reshape((1,1,8,-1))).sum(axis=(1,2)).diagonal() / 2
y = np.array([jac.dot(x) + x.dot(hes).dot(x) / 2 for x in deltaX])
# %% hago el fiteo
ruidoY = np.random.randn(y.shape[0]) * 0.1
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import matplotlib.pyplot as plt
from dev import multipolyfit as mpf
and context:
# Path: dev/multipolyfit.py
# def multipolyfit(xs, y, deg, full=False, model_out=False, powers_out=False):
# """
# Least squares multivariate polynomial fit
# Fit a polynomial like ``y = a**2 + 3a - 2ab + 4b**2 - 1``
# with many covariates a, b, c, ...
# Parameters
# ----------
# xs : array_like, shape (M, k)
# x-coordinates of the k covariates over the M sample points
# y : array_like, shape(M,)
# y-coordinates of the sample points.
# deg : int
# Degree o fthe fitting polynomial
# model_out : bool (defaults to True)
# If True return a callable function
# If False return an array of coefficients
# powers_out : bool (defaults to False)
# Returns the meaning of each of the coefficients in the form of an
# iterator that gives the powers over the inputs and 1
# For example if xs corresponds to the covariates a,b,c then the array
# [1, 2, 1, 0] corresponds to 1**1 * a**2 * b**1 * c**0
# See Also
# --------
# numpy.polyfit
# """
# y = asarray(y).squeeze()
# rows = y.shape[0]
# xs = asarray(xs)
# num_covariates = xs.shape[1]
# xs = hstack((ones((xs.shape[0], 1), dtype=xs.dtype) , xs))
#
# generators = [basis_vector(num_covariates+1, i)
# for i in range(num_covariates+1)]
#
# # All combinations of degrees
# powers = map(sum, itertools.combinations_with_replacement(generators, deg))
# if powers_out:
# exponents = [p for p in dc(powers)]
#
# # Raise data to specified degree pattern, stack in order
# A = hstack(asarray([as_tall((xs**p).prod(1)) for p in powers]))
#
# beta = linalg.lstsq(A, y)[0]
#
# if model_out:
# return mk_model(beta, powers)
#
# if powers_out:
# return beta, exponents
# return beta
which might include code, classes, or functions. Output only the next line. | coefs, exps = mpf.multipolyfit(deltaX, y + ruidoY, 2, powers_out=True) |
Given the code snippet: <|code_start|>rVecsFile = imagesFolder + camera + model + "Rvecs.npy"
imageSelection = np.arange(33) # selecciono con que imagenes trabajar
# load data
imagePoints = np.load(cornersFile)[imageSelection]
n = len(imagePoints) # cantidad de imagenes
chessboardModel = np.load(patternFile)
imgSize = tuple(np.load(imgShapeFile))
# images = glob.glob(imagesFolder+'*.png')
# Parametros de entrada/salida de la calibracion
objpoints = np.array([chessboardModel]*n)
m = chessboardModel.shape[1] # cantidad de puntos
# load model specific data
distCoeffs = np.load(distCoeffsFile)
cameraMatrix = np.load(linearCoeffsFile)
rVecs = np.load(rVecsFile)[imageSelection]
tVecs = np.load(tVecsFile)[imageSelection]
# standar deviation from subpixel epsilon used
std = 1.0
# output file
intrinsicParamsOutFile = imagesFolder + camera + model + "intrinsicParamsML"
intrinsicParamsOutFile = intrinsicParamsOutFile + str(std) + ".npy"
# pongo en forma flat los valores iniciales
<|code_end|>
, generate the next line using the imports in this file:
import numpy as np
import scipy.stats as sts
import matplotlib.pyplot as plt
import corner
import time
import sys
from copy import deepcopy as dc
from dev import bayesLib as bl
from numpy.random import rand as rn
from sklearn.decomposition import PCA
and context (functions, classes, or occasionally code) from other files:
# Path: dev/bayesLib.py
# def int2flat(cameraMatrix, distCoeffs, model):
# def flat2CamMatrix(kFlat, model):
# def flat2int(X, Ns, model):
# def ext2flat(rVec, tVec):
# def flat2ext(X):
# def errorCuadraticoImagen(Xext, Xint, Ns, params, j, mahDist=False):
# def etotalExt(Xext, Xint, Ns, params, j):
# def errorCuadraticoInt(Xint, Ns, XextList, params, mahDist=False):
# def etotalInt(Xint, Ns, XextList, params):
# def __init__(self, Ns, XextList, params, sampleador):
# def nuevo(self, old, oldE):
# def __init__(self, Xint, Ns, params, sampleador, priorExt, W):
# def ePrior(self, Xext):
# def etotalExt(self, Xext):
# def nuevo(self, old, oldE):
# def procJint(Xint, Ns, XextList, params, ret):
# def procHint(Xint, Ns, XextList, params, ret):
# def procJext(Xext, Xint, Ns, params, j, ret):
# def procHext(Xext, Xint, Ns, params, j, ret):
# def jacobianos(Xint, Ns, XextList, params, hessianos=True):
# def varVar2(c, N):
# def varMahal(c1, n, c2, rank=False):
# def trasPerMAt(k,l):
# def varVarN(c, Nsamples):
# X = np.concatenate((kFlat, dFlat))
# X = np.concatenate((rFlat, tFlat))
# S = np.linalg.inv(Cm) # inverse of covariance matrix
# A = vecA.reshape((k,l))
# class metHas:
# class metHasExt:
. Output only the next line. | Xint, Ns = bl.int2flat(cameraMatrix, distCoeffs) |
Given the following code snippet before the placeholder: <|code_start|> ranking = sts.chi2.cdf(mahDist, 3)
return mahDist, ranking
else:
return mahDist
# elimino uno de los componentes que es redundante # y lo multiplico
# mul = np.array([[1],[2],[1]])
ind = [0,1,3]
ciVar = varVar(ci, N)[ind] # * mul
cjVar = varVar(cj, N)[ind] # * mul
ciVar = ciVar.T[ind].T
cjVar = cjVar.T[ind].T
ciFlat = np.reshape(ci, -1)[ind]
cjFlat = np.reshape(cj, -1)[ind]
cFlatDif = ciFlat - cjFlat
A = varVar(ci, N)
ln.svd(A)
ciPres = np.linalg.inv(ciVar)
cjPres = np.linalg.inv(cjVar)
dMahi = cFlatDif.dot(ciPres).dot(cFlatDif)
dMahj = cFlatDif.dot(cjPres).dot(cFlatDif)
varMahal(ci, N, cj)
varMahal(cj, N, ci)
<|code_end|>
, predict the next line using imports from the current file:
import numpy as np
import scipy.stats as sts
import scipy.special as spe
import matplotlib.pyplot as plt
import scipy.linalg as ln
from dev import bayesLib as bl
and context including class names, function names, and sometimes code from other files:
# Path: dev/bayesLib.py
# def int2flat(cameraMatrix, distCoeffs, model):
# def flat2CamMatrix(kFlat, model):
# def flat2int(X, Ns, model):
# def ext2flat(rVec, tVec):
# def flat2ext(X):
# def errorCuadraticoImagen(Xext, Xint, Ns, params, j, mahDist=False):
# def etotalExt(Xext, Xint, Ns, params, j):
# def errorCuadraticoInt(Xint, Ns, XextList, params, mahDist=False):
# def etotalInt(Xint, Ns, XextList, params):
# def __init__(self, Ns, XextList, params, sampleador):
# def nuevo(self, old, oldE):
# def __init__(self, Xint, Ns, params, sampleador, priorExt, W):
# def ePrior(self, Xext):
# def etotalExt(self, Xext):
# def nuevo(self, old, oldE):
# def procJint(Xint, Ns, XextList, params, ret):
# def procHint(Xint, Ns, XextList, params, ret):
# def procJext(Xext, Xint, Ns, params, j, ret):
# def procHext(Xext, Xint, Ns, params, j, ret):
# def jacobianos(Xint, Ns, XextList, params, hessianos=True):
# def varVar2(c, N):
# def varMahal(c1, n, c2, rank=False):
# def trasPerMAt(k,l):
# def varVarN(c, Nsamples):
# X = np.concatenate((kFlat, dFlat))
# X = np.concatenate((rFlat, tFlat))
# S = np.linalg.inv(Cm) # inverse of covariance matrix
# A = vecA.reshape((k,l))
# class metHas:
# class metHasExt:
. Output only the next line. | bl.varMahal(ci, N, cj, rank=True) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
<|code_end|>
, predict the next line using imports from the current file:
from matplotlib.pyplot import plot, imshow, legend, show, figure, gcf, imread
from matplotlib.pyplot import xlabel, ylabel
from cv2 import Rodrigues # , homogr2pose
from numpy import max, zeros, array, sqrt, roots, diag, sum, log
from numpy import sin, cos, cross, ones, concatenate, flipud, dot, isreal
from numpy import linspace, polyval, eye, linalg, mean, prod, vstack
from numpy import ones_like, zeros_like, pi, float64, transpose
from numpy import any as anny
from numpy.linalg import svd, inv, det
from scipy.linalg import norm
from scipy.special import chdtri
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from importlib import reload
from calibration import StereographicCalibration as stereographic
from calibration import UnifiedCalibration as unified
from calibration import RationalCalibration as rational
from calibration import FisheyeCalibration as fisheye
from calibration import PolyCalibration as poly
and context including class names, function names, and sometimes code from other files:
# Path: calibration/StereographicCalibration.py
# def radialDistort(rh, k, quot=False, der=False):
# def radialUndistort(rd, k, quot=False, der=False):
#
# Path: calibration/UnifiedCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False):
# def radialUndistort(rp, k, quot=False):
#
# Path: calibration/RationalCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = np.array([X, Y, np.zeros(shape[1])]).T
# XYZ = np.reshape(XYZ, shape)
# D = zeros((1, 8))
#
# Path: calibration/FisheyeCalibration.py
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# D = zeros((4))
#
# Path: calibration/PolyCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = array([X, Y, zeros(shape[1])]).T
# XYZ = reshape(XYZ, shape)
# D = zeros((1, 5))
. Output only the next line. | reload(unified) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
reload(unified)
<|code_end|>
. Use current file imports:
(from matplotlib.pyplot import plot, imshow, legend, show, figure, gcf, imread
from matplotlib.pyplot import xlabel, ylabel
from cv2 import Rodrigues # , homogr2pose
from numpy import max, zeros, array, sqrt, roots, diag, sum, log
from numpy import sin, cos, cross, ones, concatenate, flipud, dot, isreal
from numpy import linspace, polyval, eye, linalg, mean, prod, vstack
from numpy import ones_like, zeros_like, pi, float64, transpose
from numpy import any as anny
from numpy.linalg import svd, inv, det
from scipy.linalg import norm
from scipy.special import chdtri
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from importlib import reload
from calibration import StereographicCalibration as stereographic
from calibration import UnifiedCalibration as unified
from calibration import RationalCalibration as rational
from calibration import FisheyeCalibration as fisheye
from calibration import PolyCalibration as poly)
and context including class names, function names, or small code snippets from other files:
# Path: calibration/StereographicCalibration.py
# def radialDistort(rh, k, quot=False, der=False):
# def radialUndistort(rd, k, quot=False, der=False):
#
# Path: calibration/UnifiedCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False):
# def radialUndistort(rp, k, quot=False):
#
# Path: calibration/RationalCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = np.array([X, Y, np.zeros(shape[1])]).T
# XYZ = np.reshape(XYZ, shape)
# D = zeros((1, 8))
#
# Path: calibration/FisheyeCalibration.py
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# D = zeros((4))
#
# Path: calibration/PolyCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = array([X, Y, zeros(shape[1])]).T
# XYZ = reshape(XYZ, shape)
# D = zeros((1, 5))
. Output only the next line. | reload(rational) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
reload(unified)
reload(rational)
<|code_end|>
using the current file's imports:
from matplotlib.pyplot import plot, imshow, legend, show, figure, gcf, imread
from matplotlib.pyplot import xlabel, ylabel
from cv2 import Rodrigues # , homogr2pose
from numpy import max, zeros, array, sqrt, roots, diag, sum, log
from numpy import sin, cos, cross, ones, concatenate, flipud, dot, isreal
from numpy import linspace, polyval, eye, linalg, mean, prod, vstack
from numpy import ones_like, zeros_like, pi, float64, transpose
from numpy import any as anny
from numpy.linalg import svd, inv, det
from scipy.linalg import norm
from scipy.special import chdtri
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from importlib import reload
from calibration import StereographicCalibration as stereographic
from calibration import UnifiedCalibration as unified
from calibration import RationalCalibration as rational
from calibration import FisheyeCalibration as fisheye
from calibration import PolyCalibration as poly
and any relevant context from other files:
# Path: calibration/StereographicCalibration.py
# def radialDistort(rh, k, quot=False, der=False):
# def radialUndistort(rd, k, quot=False, der=False):
#
# Path: calibration/UnifiedCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False):
# def radialUndistort(rp, k, quot=False):
#
# Path: calibration/RationalCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = np.array([X, Y, np.zeros(shape[1])]).T
# XYZ = np.reshape(XYZ, shape)
# D = zeros((1, 8))
#
# Path: calibration/FisheyeCalibration.py
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# D = zeros((4))
#
# Path: calibration/PolyCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = array([X, Y, zeros(shape[1])]).T
# XYZ = reshape(XYZ, shape)
# D = zeros((1, 5))
. Output only the next line. | reload(fisheye) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Created on Thu Aug 18 11:47:18 2016
@author: sebalander
"""
# %% IMPORTS
# from copy import deepcopy as dc
reload(stereographic)
reload(unified)
reload(rational)
reload(fisheye)
<|code_end|>
with the help of current file imports:
from matplotlib.pyplot import plot, imshow, legend, show, figure, gcf, imread
from matplotlib.pyplot import xlabel, ylabel
from cv2 import Rodrigues # , homogr2pose
from numpy import max, zeros, array, sqrt, roots, diag, sum, log
from numpy import sin, cos, cross, ones, concatenate, flipud, dot, isreal
from numpy import linspace, polyval, eye, linalg, mean, prod, vstack
from numpy import ones_like, zeros_like, pi, float64, transpose
from numpy import any as anny
from numpy.linalg import svd, inv, det
from scipy.linalg import norm
from scipy.special import chdtri
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
from importlib import reload
from calibration import StereographicCalibration as stereographic
from calibration import UnifiedCalibration as unified
from calibration import RationalCalibration as rational
from calibration import FisheyeCalibration as fisheye
from calibration import PolyCalibration as poly
and context from other files:
# Path: calibration/StereographicCalibration.py
# def radialDistort(rh, k, quot=False, der=False):
# def radialUndistort(rd, k, quot=False, der=False):
#
# Path: calibration/UnifiedCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False):
# def radialUndistort(rp, k, quot=False):
#
# Path: calibration/RationalCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = np.array([X, Y, np.zeros(shape[1])]).T
# XYZ = np.reshape(XYZ, shape)
# D = zeros((1, 8))
#
# Path: calibration/FisheyeCalibration.py
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# D = zeros((4))
#
# Path: calibration/PolyCalibration.py
# def formatParameters(rVec, tVec, linearCoeffs, distCoeffs):
# def setParametersVary(params, flag):
# def retrieveParameters(params):
# def radialDistort(rp, k, quot=False, der=False):
# def radialUndistort(rpp, k, quot=False, der=False):
# def inverseRationalOwn(corners, rotMatrix, tVec, cameraMatrix, distCoeffs):
# def directRationalOwn(objectPoints, rotMatrix, tVec, cameraMatrix, distCoeffs,
# plot=False, img=None, corners=None):
# def calibrateIntrinsic(objpoints, imgpoints, imgSize, K, D,
# flags, criteria):
# X = -(c*e - f*b)/q # check why wrong sign, why must put '-' in front?
# Y = -(f*a - c*d)/q
# XYZ = array([X, Y, zeros(shape[1])]).T
# XYZ = reshape(XYZ, shape)
# D = zeros((1, 5))
, which may contain function names, class names, or code. Output only the next line. | reload(poly) |
Predict the next line for this snippet: <|code_start|> else:
return ee.Image.constant(value)
def makeName(img, pattern, date_pattern=None, extra=None):
""" Make a name with the given pattern. The pattern must contain the
propeties to replace between curly braces. There are 2 special words:
* 'system_date': replace with the date of the image formatted with
`date_pattern`, which defaults to 'yyyyMMdd'
* 'id' or 'ID': the image id. If None, it'll be replaced with 'id'
Pattern example (supposing each image has a property called `city`):
'image from {city} on {system_date}'
You can add extra parameters using keyword `extra`
"""
img = ee.Image(img)
props = img.toDictionary()
props = ee.Dictionary(ee.Algorithms.If(
img.id(),
props.set('id', img.id()).set('ID', img.id()),
props))
props = ee.Dictionary(ee.Algorithms.If(
img.propertyNames().contains('system:time_start'),
props.set('system_date', img.date().format(date_pattern)),
props))
if extra:
extra = ee.Dictionary(extra)
props = props.combine(extra)
<|code_end|>
with the help of current file imports:
import pandas as pd
import ee
import threading
from copy import deepcopy
from .tools import string
from collections import namedtuple
and context from other files:
# Path: geetools/tools/string.py
# def eq(string, to_compare):
# def format(string, replacement):
# def addFormat(st):
# def true():
# def false():
# def formatValues(k, val):
# def true(v):
# def false(v):
# def wrap(kv, ini):
# def _zip(l1, l2):
# def wrap(el):
# def mix(strings):
# def wrap(eelist, aggregate):
, which may contain function names, class names, or code. Output only the next line. | name = string.format(pattern, props) |
Given snippet: <|code_start|># coding=utf-8
ee.Initialize()
l8SR = ee.Image("LANDSAT/LC8_SR/LC82310772014043")
p_l8SR_no_cloud = ee.Geometry.Point([-66.0306, -24.9338])
def test_expressions():
generator = expressions.Expression()
exp_max = generator.max("b('B1')", "b('B2')")
exp_min = generator.min("b('B1')", "b('B2')")
img_max = l8SR.expression(exp_max).select([0], ["max"])
img_min = l8SR.expression(exp_min).select([0], ["min"])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import ee
from geetools.tools.image import getValue
from geetools import expressions
and context:
# Path: geetools/tools/image.py
# def getValue(image, point, scale=None, side="server"):
# """ Return the value of all bands of the image in the specified point
#
# :param img: Image to get the info from
# :type img: ee.Image
# :param point: Point from where to get the info
# :type point: ee.Geometry.Point
# :param scale: The scale to use in the reducer. It defaults to 10 due to the
# minimum scale available in EE (Sentinel 10m)
# :type scale: int
# :param side: 'server' or 'client' side
# :type side: str
# :return: Values of all bands in the ponit
# :rtype: ee.Dictionary or dict
# """
# if scale:
# scale = int(scale)
# else:
# scale = 1
#
# type = point.getInfo()["type"]
# if type != "Point":
# raise ValueError("Point must be ee.Geometry.Point")
#
# result = image.reduceRegion(ee.Reducer.first(), point, scale)
#
# if side == 'server':
# return result
# elif side == 'client':
# return result.getInfo()
# else:
# raise ValueError("side parameter must be 'server' or 'client'")
which might include code, classes, or functions. Output only the next line. | vals_max = getValue(img_max, p_l8SR_no_cloud, 30, 'client') |
Next line prediction: <|code_start|># coding=utf-8
ee.Initialize()
list1 = ee.List([1, 2, 3, 4, 5])
list2 = ee.List([4, 5, 6, 7])
# helper
def assert_equal(obj, compare):
assert obj.getInfo() == compare
def test_list_intersection():
<|code_end|>
. Use current file imports:
(from geetools.tools import ee_list
import ee)
and context including class names, function names, or small code snippets from other files:
# Path: geetools/tools/ee_list.py
# def difference(eelist, to_compare):
# def format(eelist):
# def wrap(el, ini):
# def getFromDict(eelist, values):
# def wrap(el, first):
# def intersection(eelist, intersect):
# def wrap(element, first):
# def removeDuplicates(eelist):
# def wrap(element, init):
# def removeIndex(list, index):
# def allowed():
# def zerof(list):
# def rest(list, index):
# def lastf(list):
# def restf(list, index):
# def replaceDict(eelist, to_replace):
# def wrap(el):
# def sequence(ini, end, step=1):
# def toString(eelist):
# def wrap(el):
# def false(el):
# def zip(eelist):
# def wrap(l, accum):
# def transpose(eelist):
# def wrap(i, acc):
# def wrap2(ll, accum):
. Output only the next line. | intersection = ee_list.intersection(list1, list2) |
Given the following code snippet before the placeholder: <|code_start|># coding=utf-8
ee.Initialize()
l8SR = ee.Image("LANDSAT/LC8_SR/LC82310772014043")
p_l8SR_cloud = ee.Geometry.Point([-65.8109, -25.0185])
p_l8SR_no_cloud = ee.Geometry.Point([-66.0306, -24.9338])
list1 = ee.List([1, 2, 3, 4, 5])
list2 = ee.List([4, 5, 6, 7])
def test_getRegion():
expected = [[0.0,0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0], [0.0, 0.0]]
pol = ee.Geometry.Polygon(expected)
feat = ee.Feature(pol)
<|code_end|>
, predict the next line using imports from the current file:
import ee
from geetools.tools.geometry import getRegion
and context including class names, function names, and sometimes code from other files:
# Path: geetools/tools/geometry.py
# def getRegion(eeobject, bounds=False, error=1):
# """ Gets the region of a given geometry to use in exporting tasks. The
# argument can be a Geometry, Feature or Image
#
# :param eeobject: geometry to get region of
# :type eeobject: ee.Feature, ee.Geometry, ee.Image
# :param error: error parameter of ee.Element.geometry
# :return: region coordinates ready to use in a client-side EE function
# :rtype: json
# """
# def dispatch(geometry):
# info = geometry.getInfo()
# geomtype = info['type']
# if geomtype == 'GeometryCollection':
# geometries = info['geometries']
# region = []
# for geom in geometries:
# this_type = geom['type']
# if this_type in ['Polygon', 'Rectangle']:
# region.append(geom['coordinates'][0])
# elif this_type in ['MultiPolygon']:
# geometries2 = geom['coordinates']
# region.append(unpack(geometries2))
#
# elif geomtype == 'MultiPolygon':
# subregion = info['coordinates']
# region = unpack(subregion)
# else:
# region = info['coordinates']
#
# return region
#
# # Geometry
# if isinstance(eeobject, ee.Geometry):
# geometry = eeobject.bounds() if bounds else eeobject
# region = dispatch(geometry)
# # Feature and Image
# elif isinstance(eeobject, (ee.Feature, ee.Image)):
# geometry = eeobject.geometry(error).bounds() if bounds else eeobject.geometry(error)
# region = dispatch(geometry)
# # FeatureCollection and ImageCollection
# elif isinstance(eeobject, (ee.FeatureCollection, ee.ImageCollection)):
# if bounds:
# geometry = eeobject.geometry(error).bounds()
# else:
# geometry = eeobject.geometry(error).dissolve()
# region = dispatch(geometry)
# # List
# elif isinstance(eeobject, list):
# condition = all([type(item) == list for item in eeobject])
# if condition:
# region = eeobject
# else:
# region = eeobject
#
# return region
. Output only the next line. | region_geom = getRegion(pol) |
Predict the next line after this snippet: <|code_start|>class QueryThread(QThread):
fetching_completed = pyqtSignal(object)
progress_number = pyqtSignal(object)
query_completed = pyqtSignal(object)
combobox_results = pyqtSignal(object)
def __init__(self, parent=None):
QThread.__init__(self, parent)
self.stopped = False
self.mid = None
self.uid = None
self.fid = None
self.cmbid = None
self.ambid = None
self.iid = None
self.parent = self.parent()
self.fetching_completed.connect(self.parent.work_received)
self.combobox_results.connect(self.parent.change_combobox_backgrounds)
self.progress_number.connect(self.parent.set_progress_number)
self.query_completed.connect(self.parent.query_finished)
def check_selection(self):
iteration = iter([self.mid, self.fid, self.uid,
self.cmbid, self.ambid])
return any(iteration) and not any(iteration)
def fetch_recordings(self):
for work in self.works:
<|code_end|>
using the current file's imports:
from ..dunya import makam
from PyQt5.QtCore import QThread, QObject, pyqtSignal
and any relevant context from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_recordings():
# def get_recording(rmbid):
# def get_artists():
# def get_artist(ambid):
# def get_composers():
# def get_composer(cmbid):
# def get_releases():
# def get_release(cmbid):
# def get_works():
# def get_work(wmbid):
# def get_instruments():
# def get_instrument(iid):
# def get_forms():
# def get_form(fid):
# def get_makams():
# def get_makam(mid):
# def get_usuls():
# def get_symbtrs():
# def get_symbtr(uuid):
# def get_usul(uid):
# def get_works_by_query(mid='', uid='', fid='', cmbid='', ambid=''):
# def download_mp3(recordingid, location, slugify=False):
# def download_release(releaseid, location, slugify=False):
# def slugify_tr(value):
. Output only the next line. | w = makam.get_work(work['mbid']) |
Continue the code snippet: <|code_start|> self.comboBox_melodic.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_form.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_rhythm.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_composer.currentIndexChanged.connect(self.set_toolbutton)
self.comboBox_performer.currentIndexChanged.connect(
self.set_toolbutton)
self.comboBox_instrument.currentIndexChanged.connect(
self.set_toolbutton)
def _set_size_attributes(self):
"""Sets the size policies of frame"""
size_policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
size_policy.setHorizontalStretch(0)
size_policy.setVerticalStretch(0)
size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
self.setSizePolicy(size_policy)
self.setCursor(QCursor(Qt.ArrowCursor))
self.setFrameShape(QFrame.StyledPanel)
self.setFrameShadow(QFrame.Raised)
self.setLineWidth(1)
def _set_layout(self, layout):
"""Sets the size policies of layout and initializes the comoboxes and
query button."""
layout.setSizeConstraint(QLayout.SetNoConstraint)
layout.setMargin(MARGIN)
layout.setSpacing(SPACING)
# combo boxes
# melodic structure
<|code_end|>
. Use current file imports:
import os
import platform
from PyQt5.QtWidgets import (QFrame, QGridLayout, QSizePolicy, QLayout,
QHBoxLayout, QToolButton, QSpacerItem)
from PyQt5.QtGui import QCursor, QIcon
from PyQt5.QtCore import Qt, QSize
from .combobox import ComboBox
and context (classes, functions, or code) from other files:
# Path: dunyadesktop_app/widgets/combobox.py
# class ComboBox(QComboBox):
# """Combobox of the attributes."""
# def __init__(self, parent):
# QComboBox.__init__(self, parent)
# self.setEditable(True)
# self.setInsertPolicy(QComboBox.NoInsert)
#
# if platform.system() == 'Linux':
# self.setFixedHeight(23)
# else:
# self.setFixedHeight(25)
#
# self._set_cancel_button()
#
# # signals
# self.currentIndexChanged.connect(self.change_lineedit_status)
# self.cancel_button.clicked.connect(self.reset_attribute_selection)
# self.lineEdit().textEdited.connect(lambda:
# self.cancel_button.setVisible(True))
# self.lineEdit().editingFinished.connect(self.check_lineedit_status)
# self.dialog_filtering = FilteringDialog(self)
# self.dialog_filtering.ok_button_clicked.connect(
# lambda: self.set_selection(self.dialog_filtering.selection))
#
# def _set_cancel_button(self):
# self.cancel_button = QToolButton(self)
# self.cancel_button.setIcon(QIcon(ICON_PATH_CANCEL))
# self.cancel_button.setVisible(False)
#
# def resizeEvent(self, QResizeEvent):
# """Sets the position of cancel button."""
# button_size = self.cancel_button.sizeHint()
# frame_width = self.lineEdit().style().pixelMetric(
# QStyle.PM_DefaultFrameWidth)
# self.cancel_button.move(
# self.rect().right() - BUTTON_POS * frame_width-button_size.width(),
# (self.rect().bottom() - button_size.height() + 1) / 2)
# super(ComboBox, self).resizeEvent(QResizeEvent)
#
# def wheelEvent(self, QWheelEvent):
# """Wheel event of mouse is disabled."""
# pass
#
# def mousePressEvent(self, QMouseEvent):
# """Popups the filtering dialog when the combobox is clicked."""
# self.dialog_filtering.attribute = self.attribute
# self.dialog_filtering.setWindowTitle("")
# self.dialog_filtering.filtering_model.add_items(self.attribute)
# self.dialog_filtering.move(QMouseEvent.globalPos().x(),
# QMouseEvent.globalPos().y())
# self.dialog_filtering.show()
#
# def set_placeholder_text(self, text):
# font = QFont()
# font.setPointSize(FONT_SIZE)
#
# self.lineEdit().setPlaceholderText(text)
# self.lineEdit().setFont(font)
#
# def add_items(self, attribute):
# """Adds the items of given attribute to the combobox"""
# self.attribute = attribute
# for att in self.attribute:
# self.addItem(att['name'])
# self.setCurrentIndex(-1)
#
# def get_attribute_id(self):
# """Returns the id of selected item"""
# index = self.currentIndex()
# if index is not -1:
# try:
# return self.attribute[index]['uuid']
# except:
# return self.attribute[index]['mbid']
# else:
# return ''
#
# def set_selection(self, index):
# """Sets the selected item on the combobox."""
# try:
# index_row = index.row()
# except:
# index_row = index
# self.setCurrentIndex(index_row)
# self.lineEdit().setText(self.attribute[index_row]['name'])
# self.cancel_button.setVisible(True)
#
# def reset_attribute_selection(self):
# """Resets the selection."""
# self.lineEdit().setText('')
# self.setCurrentIndex(-1)
# self.cancel_button.setVisible(False)
#
# def change_lineedit_status(self):
# """Changes the background color of the combobox according to the user
# """
# if self.currentIndex() is not -1:
# self.lineEdit().setReadOnly(True)
# self.change_background("#F3F4E3;")
# else:
# self.lineEdit().setReadOnly(False)
# self.change_background()
#
# def change_background(self, color=''):
# """Changes the background color of the combobox according to the query
# results of """
# pass
#
# def check_lineedit_status(self):
# """Checks the lineedit widget and set the cancel button as
# visible/invisible"""
# if str(u''.join(self.lineEdit().text()).encode('utf-8').strip()) == '':
# self.cancel_button.setVisible(False)
. Output only the next line. | self.comboBox_melodic = ComboBox(self) |
Here is a snippet: <|code_start|> samplerate = 44100.
def __init__(self):
pg.GraphicsLayoutWidget.__init__(self, parent=None)
# Set 0 margin 0 spacing to cover the whole area.
self.centralWidget.setContentsMargins(0, 0, 0, 0)
self.centralWidget.setSpacing(0)
self.section_items = []
def plot_waveform(self, raw_audio):
"""
Plots the given raw audio.
:param raw_audio: (list of numpy array) List of floats.
"""
# add a new plot
self.waveform = self.centralWidget.addPlot()
# hide x and y axis
self.waveform.hideAxis(axis='bottom')
self.waveform.hideAxis(axis='left')
# disable the mouse events and menu events
self.waveform.setMouseEnabled(x=False, y=False)
self.waveform.setMenuEnabled(False)
# downsampling the given plot array
<|code_end|>
. Write the next line using the current file imports:
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QCursor
from .widgetutilities import downsample_plot
import pyqtgraph as pg
import numpy as np
and context from other files:
# Path: dunyadesktop_app/widgets/widgetutilities.py
# def downsample_plot(plot_array, ds_limit):
# # Decide by how much we should downsample
# """
# Downsamples the given pitch array according to the given downsample limit.
#
# :param plot_array: (numpy array) A sequence of pitch values
# [440.4, 442.3, 440.0, ...]
# :param ds_limit: (int) Maximum number of samples to be plotted.
#
# :return: (numpy array) A sequence of pitch values
# """
# size_array = np.size(plot_array)
# ds = int(size_array / ds_limit) + 1
#
# if ds == 1:
# # Small enough to display with no intervention.
# return plot_array
# else:
# # Here convert data into a down-sampled array suitable for
# # visualizing. Must do this piecewise to limit memory usage.
# samples = 1 + (size_array // ds)
# visible = np.zeros(samples * 2, dtype=plot_array.dtype)
# source_ptr = 0
# target_ptr = 0
#
# # read data in chunks of ~1M samples
# chunk_size = (1000000 // ds) * ds
# while source_ptr < size_array - 1:
# chunk = plot_array[source_ptr:min(size_array,
# source_ptr+chunk_size)]
# size_chunk = np.size(chunk)
# source_ptr += size_chunk
# # reshape chunk to be integral multiple of ds
# chunk = chunk[:(size_chunk // ds) * ds].reshape(size_chunk//ds, ds)
#
# # compute max and min
# chunk_max = chunk.max(axis=1)
# chunk_min = chunk.min(axis=1)
#
# # interleave min and max into plot data to preserve
# # envelope shape
# visible[target_ptr:target_ptr + chunk.shape[0] * 2:2] = chunk_min
# visible[1+target_ptr:1+target_ptr+chunk.shape[0] * 2:2] = chunk_max
# target_ptr += chunk.shape[0] * 2
# plot_y = visible[:target_ptr]
# plot_y[-1] = np.nan
# return plot_y
, which may include functions, classes, or code. Output only the next line. | self.visible = downsample_plot(raw_audio, self.limit) |
Next line prediction: <|code_start|>
class FilteringDialog(QDialog):
"""The dialog which pops up when the user clicks the combobox"""
ok_button_clicked = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.attribute = None
self.setFixedSize(200, 300)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)
v_layout = QVBoxLayout(self)
self.filtering_edit = QLineEdit()
<|code_end|>
. Use current file imports:
(from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLineEdit, QDialogButtonBox
from PyQt5.QtCore import pyqtSignal, Qt
from .table import TableView
from .models.filteringmodel import FilteringModel
from .models.proxymodel import SortFilterProxyModel)
and context including class names, function names, or small code snippets from other files:
# Path: dunyadesktop_app/widgets/table.py
# class TableView(QTableView):
# open_dunya_triggered = pyqtSignal(object)
# add_to_collection = pyqtSignal(str, object)
#
# def __init__(self, parent=None):
# QTableView.__init__(self, parent=parent)
#
# # setting the table for no edit and row selection
# self.setEditTriggers(QAbstractItemView.NoEditTriggers)
# self.setSelectionBehavior(QAbstractItemView.SelectRows)
# # self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
# self.setMouseTracking(True)
# self.horizontalHeader().setStretchLastSection(True)
# font = QFont()
# font.setPointSize(13)
# self.horizontalHeader().setFont(font)
#
# # hiding the vertical headers
# self.verticalHeader().hide()
#
# # arranging the artist column for being multi-line
# self.setWordWrap(True)
# self.setTextElideMode(Qt.ElideMiddle)
#
# self._last_index = QPersistentModelIndex()
# self.viewport().installEventFilter(self)
#
# self._set_font()
#
# def _set_font(self):
# """Sets the font of the table"""
# font = QFont()
# font.setPointSize(FONT_SIZE)
# self.setFont(font)
#
# def contextMenuEvent(self, event):
# """Pops up the context menu when the right button is clicked."""
# try:
# index = self._get_current_index
# menu = RCMenu(self)
# menu.popup(QCursor.pos())
#
# self.selected_indexes = menu.return_selected_row_indexes()
# menu.overall_hist_action.triggered.connect(
# self._compute_overall_histograms)
# except UnboundLocalError:
# pass
#
# @property
# def _get_current_index(self):
# """
# Returns the index of clicked item.
#
# :return: (int) Index of clicked item.
# """
# if self.selectionModel().selection().indexes():
# for index in self.selectionModel().selection().indexes():
# row, column = index.row(), index.column()
# self.index = index
# return index
#
# def _compute_overall_histograms(self):
# """
# Computes the overall histograms of selected items in a table.
# """
# coll_widget = self.parent().parent().listView_collections
# coll = str(coll_widget.currentItem().text())
#
# conn, c = database.connect()
# histograms = {}
# for row in self.selected_indexes:
# mbid = str(database.get_nth_row(c, coll, row)[0])
# pd_path = os.path.join(DOCS_PATH, mbid,
# 'audioanalysis--pitch_distribution.json')
# tnc_path = os.path.join(DOCS_PATH, mbid,
# 'audioanalysis--tonic.json')
# vals, bins = load_pd(pd_path)
# tonic = load_tonic(tnc_path)
# histograms[mbid] = [[vals, bins], tonic]
# corpusbasestatistics.compute_overall_histogram(histograms)
#
# def send_rec(self):
# """Emits 'open_dunya_triggered' signal and the current index to open
# the player"""
# self.index = self._get_current_index
# if self.index:
# self.open_dunya_triggered.emit(self.index)
# self.index = None
#
# def get_selected_rows(self):
# """Returns the current selected rows in the table."""
# selected_rows = []
# for item in self.selectionModel().selectedRows():
# if item.row() not in selected_rows:
# selected_rows.append(item)
# return selected_rows
#
# def send_to_db(self, coll):
# """Emits 'add_to_collection' signal to add the selected rows to the
# database"""
# if self.index:
# self.add_to_collection.emit(coll, self.index)
# self.index = None
#
# Path: dunyadesktop_app/widgets/models/filteringmodel.py
# class FilteringModel(QStandardItemModel):
# """This model is contains the attributes"""
# def __init__(self, parent=None):
# QStandardItemModel.__init__(self, parent)
#
# def add_items(self, attribute):
# self.setRowCount(len(attribute))
#
# for row, item in enumerate(attribute):
# name = QStandardItem(item['name'])
# self.setItem(row, 0, name)
#
# Path: dunyadesktop_app/widgets/models/proxymodel.py
# class SortFilterProxyModel(QSortFilterProxyModel):
# """Sort filter model is for filtering the table of query results."""
# def __init__(self, QObject_parent=None):
# QSortFilterProxyModel.__init__(self, QObject_parent)
#
# def filter_table(self, text):
# reg_exp = QRegExp(text, Qt.CaseInsensitive)
# self.setFilterRegExp(reg_exp)
. Output only the next line. | self.table_attribute = TableView() |
Here is a snippet: <|code_start|>
class FilteringDialog(QDialog):
"""The dialog which pops up when the user clicks the combobox"""
ok_button_clicked = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.attribute = None
self.setFixedSize(200, 300)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)
v_layout = QVBoxLayout(self)
self.filtering_edit = QLineEdit()
self.table_attribute = TableView()
self.button_box = QDialogButtonBox(self)
self.button_box.addButton('OK', QDialogButtonBox.AcceptRole)
self.button_box.addButton('Cancel', QDialogButtonBox.RejectRole)
v_layout.addWidget(self.filtering_edit)
v_layout.addWidget(self.table_attribute)
v_layout.addWidget(self.button_box)
self.setLayout(v_layout)
<|code_end|>
. Write the next line using the current file imports:
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLineEdit, QDialogButtonBox
from PyQt5.QtCore import pyqtSignal, Qt
from .table import TableView
from .models.filteringmodel import FilteringModel
from .models.proxymodel import SortFilterProxyModel
and context from other files:
# Path: dunyadesktop_app/widgets/table.py
# class TableView(QTableView):
# open_dunya_triggered = pyqtSignal(object)
# add_to_collection = pyqtSignal(str, object)
#
# def __init__(self, parent=None):
# QTableView.__init__(self, parent=parent)
#
# # setting the table for no edit and row selection
# self.setEditTriggers(QAbstractItemView.NoEditTriggers)
# self.setSelectionBehavior(QAbstractItemView.SelectRows)
# # self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
# self.setMouseTracking(True)
# self.horizontalHeader().setStretchLastSection(True)
# font = QFont()
# font.setPointSize(13)
# self.horizontalHeader().setFont(font)
#
# # hiding the vertical headers
# self.verticalHeader().hide()
#
# # arranging the artist column for being multi-line
# self.setWordWrap(True)
# self.setTextElideMode(Qt.ElideMiddle)
#
# self._last_index = QPersistentModelIndex()
# self.viewport().installEventFilter(self)
#
# self._set_font()
#
# def _set_font(self):
# """Sets the font of the table"""
# font = QFont()
# font.setPointSize(FONT_SIZE)
# self.setFont(font)
#
# def contextMenuEvent(self, event):
# """Pops up the context menu when the right button is clicked."""
# try:
# index = self._get_current_index
# menu = RCMenu(self)
# menu.popup(QCursor.pos())
#
# self.selected_indexes = menu.return_selected_row_indexes()
# menu.overall_hist_action.triggered.connect(
# self._compute_overall_histograms)
# except UnboundLocalError:
# pass
#
# @property
# def _get_current_index(self):
# """
# Returns the index of clicked item.
#
# :return: (int) Index of clicked item.
# """
# if self.selectionModel().selection().indexes():
# for index in self.selectionModel().selection().indexes():
# row, column = index.row(), index.column()
# self.index = index
# return index
#
# def _compute_overall_histograms(self):
# """
# Computes the overall histograms of selected items in a table.
# """
# coll_widget = self.parent().parent().listView_collections
# coll = str(coll_widget.currentItem().text())
#
# conn, c = database.connect()
# histograms = {}
# for row in self.selected_indexes:
# mbid = str(database.get_nth_row(c, coll, row)[0])
# pd_path = os.path.join(DOCS_PATH, mbid,
# 'audioanalysis--pitch_distribution.json')
# tnc_path = os.path.join(DOCS_PATH, mbid,
# 'audioanalysis--tonic.json')
# vals, bins = load_pd(pd_path)
# tonic = load_tonic(tnc_path)
# histograms[mbid] = [[vals, bins], tonic]
# corpusbasestatistics.compute_overall_histogram(histograms)
#
# def send_rec(self):
# """Emits 'open_dunya_triggered' signal and the current index to open
# the player"""
# self.index = self._get_current_index
# if self.index:
# self.open_dunya_triggered.emit(self.index)
# self.index = None
#
# def get_selected_rows(self):
# """Returns the current selected rows in the table."""
# selected_rows = []
# for item in self.selectionModel().selectedRows():
# if item.row() not in selected_rows:
# selected_rows.append(item)
# return selected_rows
#
# def send_to_db(self, coll):
# """Emits 'add_to_collection' signal to add the selected rows to the
# database"""
# if self.index:
# self.add_to_collection.emit(coll, self.index)
# self.index = None
#
# Path: dunyadesktop_app/widgets/models/filteringmodel.py
# class FilteringModel(QStandardItemModel):
# """This model is contains the attributes"""
# def __init__(self, parent=None):
# QStandardItemModel.__init__(self, parent)
#
# def add_items(self, attribute):
# self.setRowCount(len(attribute))
#
# for row, item in enumerate(attribute):
# name = QStandardItem(item['name'])
# self.setItem(row, 0, name)
#
# Path: dunyadesktop_app/widgets/models/proxymodel.py
# class SortFilterProxyModel(QSortFilterProxyModel):
# """Sort filter model is for filtering the table of query results."""
# def __init__(self, QObject_parent=None):
# QSortFilterProxyModel.__init__(self, QObject_parent)
#
# def filter_table(self, text):
# reg_exp = QRegExp(text, Qt.CaseInsensitive)
# self.setFilterRegExp(reg_exp)
, which may include functions, classes, or code. Output only the next line. | self.filtering_model = FilteringModel(self) |
Given the code snippet: <|code_start|>
class FilteringDialog(QDialog):
"""The dialog which pops up when the user clicks the combobox"""
ok_button_clicked = pyqtSignal()
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.attribute = None
self.setFixedSize(200, 300)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)
v_layout = QVBoxLayout(self)
self.filtering_edit = QLineEdit()
self.table_attribute = TableView()
self.button_box = QDialogButtonBox(self)
self.button_box.addButton('OK', QDialogButtonBox.AcceptRole)
self.button_box.addButton('Cancel', QDialogButtonBox.RejectRole)
v_layout.addWidget(self.filtering_edit)
v_layout.addWidget(self.table_attribute)
v_layout.addWidget(self.button_box)
self.setLayout(v_layout)
self.filtering_model = FilteringModel(self)
<|code_end|>
, generate the next line using the imports in this file:
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QLineEdit, QDialogButtonBox
from PyQt5.QtCore import pyqtSignal, Qt
from .table import TableView
from .models.filteringmodel import FilteringModel
from .models.proxymodel import SortFilterProxyModel
and context (functions, classes, or occasionally code) from other files:
# Path: dunyadesktop_app/widgets/table.py
# class TableView(QTableView):
# open_dunya_triggered = pyqtSignal(object)
# add_to_collection = pyqtSignal(str, object)
#
# def __init__(self, parent=None):
# QTableView.__init__(self, parent=parent)
#
# # setting the table for no edit and row selection
# self.setEditTriggers(QAbstractItemView.NoEditTriggers)
# self.setSelectionBehavior(QAbstractItemView.SelectRows)
# # self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
# self.setMouseTracking(True)
# self.horizontalHeader().setStretchLastSection(True)
# font = QFont()
# font.setPointSize(13)
# self.horizontalHeader().setFont(font)
#
# # hiding the vertical headers
# self.verticalHeader().hide()
#
# # arranging the artist column for being multi-line
# self.setWordWrap(True)
# self.setTextElideMode(Qt.ElideMiddle)
#
# self._last_index = QPersistentModelIndex()
# self.viewport().installEventFilter(self)
#
# self._set_font()
#
# def _set_font(self):
# """Sets the font of the table"""
# font = QFont()
# font.setPointSize(FONT_SIZE)
# self.setFont(font)
#
# def contextMenuEvent(self, event):
# """Pops up the context menu when the right button is clicked."""
# try:
# index = self._get_current_index
# menu = RCMenu(self)
# menu.popup(QCursor.pos())
#
# self.selected_indexes = menu.return_selected_row_indexes()
# menu.overall_hist_action.triggered.connect(
# self._compute_overall_histograms)
# except UnboundLocalError:
# pass
#
# @property
# def _get_current_index(self):
# """
# Returns the index of clicked item.
#
# :return: (int) Index of clicked item.
# """
# if self.selectionModel().selection().indexes():
# for index in self.selectionModel().selection().indexes():
# row, column = index.row(), index.column()
# self.index = index
# return index
#
# def _compute_overall_histograms(self):
# """
# Computes the overall histograms of selected items in a table.
# """
# coll_widget = self.parent().parent().listView_collections
# coll = str(coll_widget.currentItem().text())
#
# conn, c = database.connect()
# histograms = {}
# for row in self.selected_indexes:
# mbid = str(database.get_nth_row(c, coll, row)[0])
# pd_path = os.path.join(DOCS_PATH, mbid,
# 'audioanalysis--pitch_distribution.json')
# tnc_path = os.path.join(DOCS_PATH, mbid,
# 'audioanalysis--tonic.json')
# vals, bins = load_pd(pd_path)
# tonic = load_tonic(tnc_path)
# histograms[mbid] = [[vals, bins], tonic]
# corpusbasestatistics.compute_overall_histogram(histograms)
#
# def send_rec(self):
# """Emits 'open_dunya_triggered' signal and the current index to open
# the player"""
# self.index = self._get_current_index
# if self.index:
# self.open_dunya_triggered.emit(self.index)
# self.index = None
#
# def get_selected_rows(self):
# """Returns the current selected rows in the table."""
# selected_rows = []
# for item in self.selectionModel().selectedRows():
# if item.row() not in selected_rows:
# selected_rows.append(item)
# return selected_rows
#
# def send_to_db(self, coll):
# """Emits 'add_to_collection' signal to add the selected rows to the
# database"""
# if self.index:
# self.add_to_collection.emit(coll, self.index)
# self.index = None
#
# Path: dunyadesktop_app/widgets/models/filteringmodel.py
# class FilteringModel(QStandardItemModel):
# """This model is contains the attributes"""
# def __init__(self, parent=None):
# QStandardItemModel.__init__(self, parent)
#
# def add_items(self, attribute):
# self.setRowCount(len(attribute))
#
# for row, item in enumerate(attribute):
# name = QStandardItem(item['name'])
# self.setItem(row, 0, name)
#
# Path: dunyadesktop_app/widgets/models/proxymodel.py
# class SortFilterProxyModel(QSortFilterProxyModel):
# """Sort filter model is for filtering the table of query results."""
# def __init__(self, QObject_parent=None):
# QSortFilterProxyModel.__init__(self, QObject_parent)
#
# def filter_table(self, text):
# reg_exp = QRegExp(text, Qt.CaseInsensitive)
# self.setFilterRegExp(reg_exp)
. Output only the next line. | self.proxy_model = SortFilterProxyModel(self) |
Using the snippet: <|code_start|>
:param pitch_plot: (numpy array or list) List of pitch values. Ex: [234.5, 234,3, 234.0, ...]
:param x_start: (int or float) Time stamp of starting point in seconds.
:param x_end: (int or float) Time stamp of ending point in seconds.
:param hop_size: (int) Hop size in samples. Ex: 128.
"""
if not self.is_pitch_plotted: # if pitch is not plotted yet
self.ratio = 1. / (hop_size / np.float(self.sample_rate))
self.pitch_plot = pitch_plot
# downsample the plot in given time stamps
self.update_plot(start=x_start, stop=x_end, hop_size=hop_size)
# set the flag as true after plot the pitch
self.is_pitch_plotted = True
else:
# downsample the plot in given time stamps
self.update_plot(start=x_start, stop=x_end, hop_size=hop_size)
def update_plot(self, start, stop, hop_size):
"""
Updates the view of the plot region with given time stamps.
:param start: (int or float) Time stamp of starting point in seconds.
:param stop: (int or float) Time stamp of ending point in seconds.
:param hop_size: (int) Hop size in samples. Ex: 128.
"""
# convert the given time stamps into samples to specify the plot array
start = int(start * self.ratio)
stop = int(stop * self.ratio)
<|code_end|>
, determine the next line of code. You have imports:
import pyqtgraph as pg
import numpy as np
from PyQt5.QtCore import pyqtSignal
from .widgetutilities import downsample_plot, cursor_pos_sample, current_pitch
and context (class names, function names, or code) available:
# Path: dunyadesktop_app/widgets/widgetutilities.py
# def downsample_plot(plot_array, ds_limit):
# # Decide by how much we should downsample
# """
# Downsamples the given pitch array according to the given downsample limit.
#
# :param plot_array: (numpy array) A sequence of pitch values
# [440.4, 442.3, 440.0, ...]
# :param ds_limit: (int) Maximum number of samples to be plotted.
#
# :return: (numpy array) A sequence of pitch values
# """
# size_array = np.size(plot_array)
# ds = int(size_array / ds_limit) + 1
#
# if ds == 1:
# # Small enough to display with no intervention.
# return plot_array
# else:
# # Here convert data into a down-sampled array suitable for
# # visualizing. Must do this piecewise to limit memory usage.
# samples = 1 + (size_array // ds)
# visible = np.zeros(samples * 2, dtype=plot_array.dtype)
# source_ptr = 0
# target_ptr = 0
#
# # read data in chunks of ~1M samples
# chunk_size = (1000000 // ds) * ds
# while source_ptr < size_array - 1:
# chunk = plot_array[source_ptr:min(size_array,
# source_ptr+chunk_size)]
# size_chunk = np.size(chunk)
# source_ptr += size_chunk
# # reshape chunk to be integral multiple of ds
# chunk = chunk[:(size_chunk // ds) * ds].reshape(size_chunk//ds, ds)
#
# # compute max and min
# chunk_max = chunk.max(axis=1)
# chunk_min = chunk.min(axis=1)
#
# # interleave min and max into plot data to preserve
# # envelope shape
# visible[target_ptr:target_ptr + chunk.shape[0] * 2:2] = chunk_min
# visible[1+target_ptr:1+target_ptr+chunk.shape[0] * 2:2] = chunk_max
# target_ptr += chunk.shape[0] * 2
# plot_y = visible[:target_ptr]
# plot_y[-1] = np.nan
# return plot_y
#
# def cursor_pos_sample(pos, samplerate, hopsize):
# """
# Returns the current index of sample.
#
# :param pos: (int or float) Playback position in seconds.
# """
# return np.int(pos * samplerate / hopsize)
#
# def current_pitch(sample, pitch_plot):
# """
# Returns the current pitch value in Hz.
# :param sample: (int) Index of sample.
#
# :return: (float) Pitch in Hz.
# """
# return pitch_plot[sample]
. Output only the next line. | plot_y = downsample_plot(self.pitch_plot[start:stop], self.limit) |
Given the following code snippet before the placeholder: <|code_start|>
def add_tonic(self, values):
"""
Adds tonic lines on the pitch plot.
:param values: (list or numpy array) A sequence of tonic values in Hz.
"""
# label options for the tonic values on the tonic line
label_opts = {'position': 0.1, 'color': (200, 200, 100),
'fill': (200, 200, 200, 50), 'movable': True}
if not hasattr(self, 'tonic_lines'):
self.tonic_lines = []
for value in values:
# create infinite line
t_line = pg.InfiniteLine(pos=value, movable=False, angle=0,
label='Tonic=%.2f' % value,
labelOpts=label_opts)
# take tonic lines in a list to remove in the future
self.tonic_lines.append(t_line)
self.zoom_selection.addItem(t_line) # add item to zoom selection
def set_hist_cursor_pos(self, pos):
"""
Sets the position of histogram in y-axis.
:param pos: (int or float) Playback position in seconds.
"""
<|code_end|>
, predict the next line using imports from the current file:
import pyqtgraph as pg
import numpy as np
from PyQt5.QtCore import pyqtSignal
from .widgetutilities import downsample_plot, cursor_pos_sample, current_pitch
and context including class names, function names, and sometimes code from other files:
# Path: dunyadesktop_app/widgets/widgetutilities.py
# def downsample_plot(plot_array, ds_limit):
# # Decide by how much we should downsample
# """
# Downsamples the given pitch array according to the given downsample limit.
#
# :param plot_array: (numpy array) A sequence of pitch values
# [440.4, 442.3, 440.0, ...]
# :param ds_limit: (int) Maximum number of samples to be plotted.
#
# :return: (numpy array) A sequence of pitch values
# """
# size_array = np.size(plot_array)
# ds = int(size_array / ds_limit) + 1
#
# if ds == 1:
# # Small enough to display with no intervention.
# return plot_array
# else:
# # Here convert data into a down-sampled array suitable for
# # visualizing. Must do this piecewise to limit memory usage.
# samples = 1 + (size_array // ds)
# visible = np.zeros(samples * 2, dtype=plot_array.dtype)
# source_ptr = 0
# target_ptr = 0
#
# # read data in chunks of ~1M samples
# chunk_size = (1000000 // ds) * ds
# while source_ptr < size_array - 1:
# chunk = plot_array[source_ptr:min(size_array,
# source_ptr+chunk_size)]
# size_chunk = np.size(chunk)
# source_ptr += size_chunk
# # reshape chunk to be integral multiple of ds
# chunk = chunk[:(size_chunk // ds) * ds].reshape(size_chunk//ds, ds)
#
# # compute max and min
# chunk_max = chunk.max(axis=1)
# chunk_min = chunk.min(axis=1)
#
# # interleave min and max into plot data to preserve
# # envelope shape
# visible[target_ptr:target_ptr + chunk.shape[0] * 2:2] = chunk_min
# visible[1+target_ptr:1+target_ptr+chunk.shape[0] * 2:2] = chunk_max
# target_ptr += chunk.shape[0] * 2
# plot_y = visible[:target_ptr]
# plot_y[-1] = np.nan
# return plot_y
#
# def cursor_pos_sample(pos, samplerate, hopsize):
# """
# Returns the current index of sample.
#
# :param pos: (int or float) Playback position in seconds.
# """
# return np.int(pos * samplerate / hopsize)
#
# def current_pitch(sample, pitch_plot):
# """
# Returns the current pitch value in Hz.
# :param sample: (int) Index of sample.
#
# :return: (float) Pitch in Hz.
# """
# return pitch_plot[sample]
. Output only the next line. | pos_sample = cursor_pos_sample(pos, self.sample_rate, self.hopsize) |
Based on the snippet: <|code_start|> def add_tonic(self, values):
"""
Adds tonic lines on the pitch plot.
:param values: (list or numpy array) A sequence of tonic values in Hz.
"""
# label options for the tonic values on the tonic line
label_opts = {'position': 0.1, 'color': (200, 200, 100),
'fill': (200, 200, 200, 50), 'movable': True}
if not hasattr(self, 'tonic_lines'):
self.tonic_lines = []
for value in values:
# create infinite line
t_line = pg.InfiniteLine(pos=value, movable=False, angle=0,
label='Tonic=%.2f' % value,
labelOpts=label_opts)
# take tonic lines in a list to remove in the future
self.tonic_lines.append(t_line)
self.zoom_selection.addItem(t_line) # add item to zoom selection
def set_hist_cursor_pos(self, pos):
"""
Sets the position of histogram in y-axis.
:param pos: (int or float) Playback position in seconds.
"""
pos_sample = cursor_pos_sample(pos, self.sample_rate, self.hopsize)
<|code_end|>
, predict the immediate next line with the help of imports:
import pyqtgraph as pg
import numpy as np
from PyQt5.QtCore import pyqtSignal
from .widgetutilities import downsample_plot, cursor_pos_sample, current_pitch
and context (classes, functions, sometimes code) from other files:
# Path: dunyadesktop_app/widgets/widgetutilities.py
# def downsample_plot(plot_array, ds_limit):
# # Decide by how much we should downsample
# """
# Downsamples the given pitch array according to the given downsample limit.
#
# :param plot_array: (numpy array) A sequence of pitch values
# [440.4, 442.3, 440.0, ...]
# :param ds_limit: (int) Maximum number of samples to be plotted.
#
# :return: (numpy array) A sequence of pitch values
# """
# size_array = np.size(plot_array)
# ds = int(size_array / ds_limit) + 1
#
# if ds == 1:
# # Small enough to display with no intervention.
# return plot_array
# else:
# # Here convert data into a down-sampled array suitable for
# # visualizing. Must do this piecewise to limit memory usage.
# samples = 1 + (size_array // ds)
# visible = np.zeros(samples * 2, dtype=plot_array.dtype)
# source_ptr = 0
# target_ptr = 0
#
# # read data in chunks of ~1M samples
# chunk_size = (1000000 // ds) * ds
# while source_ptr < size_array - 1:
# chunk = plot_array[source_ptr:min(size_array,
# source_ptr+chunk_size)]
# size_chunk = np.size(chunk)
# source_ptr += size_chunk
# # reshape chunk to be integral multiple of ds
# chunk = chunk[:(size_chunk // ds) * ds].reshape(size_chunk//ds, ds)
#
# # compute max and min
# chunk_max = chunk.max(axis=1)
# chunk_min = chunk.min(axis=1)
#
# # interleave min and max into plot data to preserve
# # envelope shape
# visible[target_ptr:target_ptr + chunk.shape[0] * 2:2] = chunk_min
# visible[1+target_ptr:1+target_ptr+chunk.shape[0] * 2:2] = chunk_max
# target_ptr += chunk.shape[0] * 2
# plot_y = visible[:target_ptr]
# plot_y[-1] = np.nan
# return plot_y
#
# def cursor_pos_sample(pos, samplerate, hopsize):
# """
# Returns the current index of sample.
#
# :param pos: (int or float) Playback position in seconds.
# """
# return np.int(pos * samplerate / hopsize)
#
# def current_pitch(sample, pitch_plot):
# """
# Returns the current pitch value in Hz.
# :param sample: (int) Index of sample.
#
# :return: (float) Pitch in Hz.
# """
# return pitch_plot[sample]
. Output only the next line. | pitch = current_pitch(pos_sample, self.pitch_plot) |
Predict the next line for this snippet: <|code_start|>else:
CSS_PATH = os.path.join(os.path.dirname(__file__), '..', 'ui_files', 'css',
'combobox_mac.css')
BUTTON_POS = 20
FONT_SIZE = 10
ICON_PATH_CANCEL = os.path.join(os.path.dirname(__file__), '..', 'ui_files',
'icons', 'cancel-music.svg')
class ComboBox(QComboBox):
"""Combobox of the attributes."""
def __init__(self, parent):
QComboBox.__init__(self, parent)
self.setEditable(True)
self.setInsertPolicy(QComboBox.NoInsert)
if platform.system() == 'Linux':
self.setFixedHeight(23)
else:
self.setFixedHeight(25)
self._set_cancel_button()
# signals
self.currentIndexChanged.connect(self.change_lineedit_status)
self.cancel_button.clicked.connect(self.reset_attribute_selection)
self.lineEdit().textEdited.connect(lambda:
self.cancel_button.setVisible(True))
self.lineEdit().editingFinished.connect(self.check_lineedit_status)
<|code_end|>
with the help of current file imports:
import os
import platform
from PyQt5.QtWidgets import QComboBox, QToolButton, QStyle
from PyQt5.QtGui import QIcon, QFont
from .filteringdialog import FilteringDialog
and context from other files:
# Path: dunyadesktop_app/widgets/filteringdialog.py
# class FilteringDialog(QDialog):
# """The dialog which pops up when the user clicks the combobox"""
# ok_button_clicked = pyqtSignal()
#
# def __init__(self, parent=None):
# QDialog.__init__(self, parent)
# self.attribute = None
# self.setFixedSize(200, 300)
#
# self.setWindowFlags(Qt.FramelessWindowHint | Qt.Popup)
#
# v_layout = QVBoxLayout(self)
# self.filtering_edit = QLineEdit()
# self.table_attribute = TableView()
#
# self.button_box = QDialogButtonBox(self)
# self.button_box.addButton('OK', QDialogButtonBox.AcceptRole)
# self.button_box.addButton('Cancel', QDialogButtonBox.RejectRole)
#
# v_layout.addWidget(self.filtering_edit)
# v_layout.addWidget(self.table_attribute)
# v_layout.addWidget(self.button_box)
#
# self.setLayout(v_layout)
#
# self.filtering_model = FilteringModel(self)
#
# self.proxy_model = SortFilterProxyModel(self)
# self.proxy_model.setSourceModel(self.filtering_model)
# self.proxy_model.setFilterKeyColumn(-1)
#
# self.table_attribute.horizontalHeader().hide()
# self.table_attribute.setModel(self.proxy_model)
# self.table_attribute.setColumnWidth(0, 28)
#
# self.filtering_edit.setPlaceholderText('Type here to filter...')
# self.selection = -1
#
# self.filtering_edit.textChanged.connect(
# lambda: self.proxy_model.filter_table(self.filtering_edit.text()))
#
# self.button_box.rejected.connect(self.clicked_cancel)
# self.table_attribute.doubleClicked.connect(
# self.get_selected_item_index)
# self.button_box.accepted.connect(self.get_selected_item_index)
#
# def get_selected_item_index(self):
# """Stores the index of the selected item and emits the clicked
# signal."""
# self.filtering_edit.setText('')
# self.selection = self.table_attribute.model().mapToSource(
# self.table_attribute.currentIndex())
# self.close()
# self.ok_button_clicked.emit()
#
# def clicked_cancel(self):
# """Closes the window"""
# self.close()
, which may contain function names, class names, or code. Output only the next line. | self.dialog_filtering = FilteringDialog(self) |
Predict the next line after this snippet: <|code_start|> dir_name = dir_name[:-1] if dir_name[-1] == os.sep else dir_name
# walk all the subdirectories
for (path, dirs, files) in os.walk(dir_name):
for f in files:
has_key = (fnmatch.fnmatch(f, keyword) if match_case else
fnmatch.fnmatch(f.lower(), keyword.lower()))
if has_key and skip_foldername not in path.split(os.sep)[1:]:
try:
folders.append(str(path))
except TypeError: # already unicode
folders.append(path)
try:
names.append(str(f))
except TypeError: # already unicode
names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary according to the keys"""
return sorted(dictionary, key=lambda k: k[key])
def get_attributes():
"""Downloads the attributes"""
<|code_end|>
using the current file's imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and any relevant context from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | makams = get_makams() |
Continue the code snippet: <|code_start|> for (path, dirs, files) in os.walk(dir_name):
for f in files:
has_key = (fnmatch.fnmatch(f, keyword) if match_case else
fnmatch.fnmatch(f.lower(), keyword.lower()))
if has_key and skip_foldername not in path.split(os.sep)[1:]:
try:
folders.append(str(path))
except TypeError: # already unicode
folders.append(path)
try:
names.append(str(f))
except TypeError: # already unicode
names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary according to the keys"""
return sorted(dictionary, key=lambda k: k[key])
def get_attributes():
"""Downloads the attributes"""
makams = get_makams()
makams = sort_dictionary(makams, 'name')
<|code_end|>
. Use current file imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context (classes, functions, or code) from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | forms = get_forms() |
Predict the next line after this snippet: <|code_start|> fnmatch.fnmatch(f.lower(), keyword.lower()))
if has_key and skip_foldername not in path.split(os.sep)[1:]:
try:
folders.append(str(path))
except TypeError: # already unicode
folders.append(path)
try:
names.append(str(f))
except TypeError: # already unicode
names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary according to the keys"""
return sorted(dictionary, key=lambda k: k[key])
def get_attributes():
"""Downloads the attributes"""
makams = get_makams()
makams = sort_dictionary(makams, 'name')
forms = get_forms()
forms = sort_dictionary(forms, 'name')
<|code_end|>
using the current file's imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and any relevant context from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | usuls = get_usuls() |
Given the following code snippet before the placeholder: <|code_start|> folders.append(str(path))
except TypeError: # already unicode
folders.append(path)
try:
names.append(str(f))
except TypeError: # already unicode
names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary according to the keys"""
return sorted(dictionary, key=lambda k: k[key])
def get_attributes():
"""Downloads the attributes"""
makams = get_makams()
makams = sort_dictionary(makams, 'name')
forms = get_forms()
forms = sort_dictionary(forms, 'name')
usuls = get_usuls()
usuls = sort_dictionary(usuls, 'name')
<|code_end|>
, predict the next line using imports from the current file:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context including class names, function names, and sometimes code from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | composers = get_composers() |
Predict the next line for this snippet: <|code_start|> try:
names.append(str(f))
except TypeError: # already unicode
names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary according to the keys"""
return sorted(dictionary, key=lambda k: k[key])
def get_attributes():
"""Downloads the attributes"""
makams = get_makams()
makams = sort_dictionary(makams, 'name')
forms = get_forms()
forms = sort_dictionary(forms, 'name')
usuls = get_usuls()
usuls = sort_dictionary(usuls, 'name')
composers = get_composers()
composers = sort_dictionary(composers, 'name')
<|code_end|>
with the help of current file imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
, which may contain function names, class names, or code. Output only the next line. | performers = get_artists() |
Given the code snippet: <|code_start|> names.append(path)
fullnames.append(os.path.join(path, f))
if verbose:
print("> Found " + str(len(names)) + " files.")
return fullnames, folders, names
def sort_dictionary(dictionary, key):
"""sorts the given dictionary according to the keys"""
return sorted(dictionary, key=lambda k: k[key])
def get_attributes():
"""Downloads the attributes"""
makams = get_makams()
makams = sort_dictionary(makams, 'name')
forms = get_forms()
forms = sort_dictionary(forms, 'name')
usuls = get_usuls()
usuls = sort_dictionary(usuls, 'name')
composers = get_composers()
composers = sort_dictionary(composers, 'name')
performers = get_artists()
performers = sort_dictionary(performers, 'name')
<|code_end|>
, generate the next line using the imports in this file:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context (functions, classes, or occasionally code) from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | instruments = get_instruments() |
Continue the code snippet: <|code_start|> """Downloads the available features from Dunya-backend related with the
given docid"""
FOLDER = os.path.join(os.path.dirname(__file__), '..', 'documents')
step_completed = pyqtSignal(object)
# checking existance of documents folder in culture
if not os.path.exists(FOLDER):
os.makedirs(FOLDER)
def __init__(self, queue, callback, parent=None):
QThread.__init__(self, parent)
self.queue = queue
self.step_completed.connect(callback)
def run(self):
while True:
arg = self.queue.get()
if arg is None:
return
self.download(arg)
def download(self, docid):
if docid:
doc_folder = os.path.join(self.FOLDER, docid)
if not os.path.exists(doc_folder):
os.makedirs(doc_folder)
# feature list
try:
<|code_end|>
. Use current file imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context (classes, functions, or code) from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | features = document(docid)['derivedfiles'] |
Continue the code snippet: <|code_start|> print(docid, 'is not found')
return
try:
m_path = os.path.join(doc_folder, docid + '.mp3')
if not os.path.exists(m_path):
# for now, all tokens have permission to download
# audio files
mp3 = get_mp3(docid)
open(m_path, 'wb').write(mp3)
except:
pass
num_f = 0
download_list = []
if 'audioanalysis' in features:
num_f += len(features['audioanalysis'])
download_list.append('audioanalysis')
if 'jointanalysis' in features:
num_f += len(features['jointanalysis'])
self.download_score(docid)
download_list.append('jointanalysis')
count = 0
for thetype in download_list:
for subtype in features[thetype]:
f_path = os.path.join(doc_folder,
thetype + '--' + subtype + '.json')
if not os.path.exists(f_path):
try:
<|code_end|>
. Use current file imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context (classes, functions, or code) from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | feature = get_document_as_json(docid, thetype, |
Here is a snippet: <|code_start|> def __init__(self, queue, callback, parent=None):
QThread.__init__(self, parent)
self.queue = queue
self.step_completed.connect(callback)
def run(self):
while True:
arg = self.queue.get()
if arg is None:
return
self.download(arg)
def download(self, docid):
if docid:
doc_folder = os.path.join(self.FOLDER, docid)
if not os.path.exists(doc_folder):
os.makedirs(doc_folder)
# feature list
try:
features = document(docid)['derivedfiles']
except HTTPError:
print(docid, 'is not found')
return
try:
m_path = os.path.join(doc_folder, docid + '.mp3')
if not os.path.exists(m_path):
# for now, all tokens have permission to download
# audio files
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context from other files:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
, which may include functions, classes, or code. Output only the next line. | mp3 = get_mp3(docid) |
Using the snippet: <|code_start|> given docid"""
FOLDER = os.path.join(os.path.dirname(__file__), '..', 'documents')
step_completed = pyqtSignal(object)
# checking existance of documents folder in culture
if not os.path.exists(FOLDER):
os.makedirs(FOLDER)
def __init__(self, queue, callback, parent=None):
QThread.__init__(self, parent)
self.queue = queue
self.step_completed.connect(callback)
def run(self):
while True:
arg = self.queue.get()
if arg is None:
return
self.download(arg)
def download(self, docid):
if docid:
doc_folder = os.path.join(self.FOLDER, docid)
if not os.path.exists(doc_folder):
os.makedirs(doc_folder)
# feature list
try:
features = document(docid)['derivedfiles']
<|code_end|>
, determine the next line of code. You have imports:
import sys
import os
import os.path
import json
import fnmatch
import urllib
import urllib.request as urllib
import numpy as np
from ..dunya.makam import (get_makams, get_forms, get_usuls,
get_composers, get_artists, get_instruments)
from ..dunya.docserver import (document, get_document_as_json, get_mp3)
from ..dunya.conn import HTTPError
from PyQt5.QtCore import QObject, QThread, pyqtSignal
and context (class names, function names, or code) available:
# Path: dunyadesktop_app/cultures/dunya/makam.py
# def get_makams():
# """ Get a list of makam makams in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing makam information::
#
# {"uuid": makam uuid,
# "name": Name of the makam
# }
#
# For additional information about each makam use :func:`get_makam`
#
# """
# return conn._get_paged_json("api/makam/makam")
#
# def get_forms():
# """ Get a list of makam forms in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing form information::
#
# {"uuid": form uuid,
# "name": Name of the form
# }
#
# For additional information about each form use :func:`get_form`
#
# """
# return conn._get_paged_json("api/makam/form")
#
# def get_usuls():
# """ Get a list of makam usuls in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing usul information::
#
# {"uuid": usul uuid,
# "name": Name of the usul
# }
#
# For additional information about each usul use :func:`get_usul`
#
# """
# return conn._get_paged_json("api/makam/usul")
#
# def get_composers():
# """ Get a list of makam composers in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing composers information::
#
# {"mbid": Musicbrainz composer id,
# "name": Name of the composer}
#
# For additional information about each composer use :func:`get_composer`
#
# """
# return conn._get_paged_json("api/makam/composer")
#
# def get_artists():
# """ Get a list of makam artists in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing artist information::
#
# {"mbid": Musicbrainz artist id,
# "name": Name of the artist}
#
# For additional information about each artist use :func:`get_artist`
#
# """
# return conn._get_paged_json("api/makam/artist")
#
# def get_instruments():
# """ Get a list of makam instruments in the database.
# This function will automatically page through API results.
#
# returns: A list of dictionaries containing instrument information::
#
# {"id": instrument id,
# "name": Name of the instrument
# }
#
# For additional information about each instrument use :func:`get_instrument`
#
# """
# return conn._get_paged_json("api/makam/instrument")
#
# Path: dunyadesktop_app/cultures/dunya/docserver.py
# def document(recordingid):
# """Get the available source filetypes for a Musicbrainz recording.
#
# :param recordingid: Musicbrainz recording ID
# :returns: a list of filetypes in the database for this recording
#
# """
# path = "document/by-id/%s" % recordingid
# recording = conn._dunya_query_json(path)
# return recording
#
# def get_document_as_json(recordingid, thetype, subtype=None, part=None, version=None):
# """ Get a derived filetype and load it as json.
#
# :param recordingid: Musicbrainz recording ID
# :param derivedtype: the computed filetype
# :param subtype: a subtype if the module has one
# :param part: the file part if the module has one
# :param version: a specific version, otherwise the most recent one will be used
#
# """
#
# doc = file_for_document(recordingid, thetype, subtype, part, version)
# try:
# return json.loads(doc)
# except ValueError:
# return doc
#
# def get_mp3(recordingid):
# return file_for_document(recordingid, "mp3")
#
# Path: dunyadesktop_app/cultures/dunya/conn.py
# class HTTPError(Exception):
# pass
. Output only the next line. | except HTTPError: |
Continue the code snippet: <|code_start|>
admin.site.register(PBSServer)
admin.site.register(PBSQueue)
admin.site.register(PBSJob)
<|code_end|>
. Use current file imports:
from pytorque.models import PBSServer
from pytorque.models import PBSQueue
from pytorque.models import PBSJob
from pytorque.models import PBSUserStat
from django.contrib import admin
and context (classes, functions, or code) from other files:
# Path: pytorque/models.py
# class PBSServer(models.Model):
# time = models.DateTimeField(
# default=datetime.now)#auto_now_add=True sets datetime with creating object, not with every modifying action
#
# name = models.CharField(max_length=100)
# state = models.CharField(max_length=20)
# total_jobs = models.IntegerField()
# running_jobs = models.IntegerField()
# queued_jobs = models.IntegerField()
# pbs_version = models.CharField(max_length=10)
#
# Path: pytorque/models.py
# class PBSQueue(models.Model):
# server = models.ForeignKey(PBSServer)#, blank=True, null=True, on_delete=models.SET_NULL
# time = models.DateTimeField(default=datetime.now)
#
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# type = models.CharField(default='', max_length=20, blank=True, null=True)
# total_jobs = models.IntegerField(default=0)
# running_jobs = models.IntegerField(default=0)
# queued_jobs = models.IntegerField(default=0)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_nodes = models.IntegerField(default=0)
#
# Path: pytorque/models.py
# class PBSJob(models.Model):
# user = models.ForeignKey(User)
# queue = models.ForeignKey(PBSQueue)
# time = models.DateTimeField(default=datetime.now)
#
# jobId = models.CharField(default='', max_length=50, blank=True, null=True)
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# owner = models.CharField(default='', max_length=100, blank=True, null=True)
# state = models.CharField(default='', max_length=10, blank=True, null=True)
# queue_raw = models.CharField(default='', max_length=100, blank=True, null=True)
#
# start_time = models.DateTimeField(default=datetime.now, blank=True, null=True)
# resource_cput = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_mem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_vmem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
#
# Path: pytorque/models.py
# class PBSUserStat(models.Model):
# time = models.DateTimeField(default=datetime.now, auto_now_add=True)
#
# username = models.CharField(default='', max_length=100, blank=True, null=True)
# jobCount = models.IntegerField(default=0, blank=True, null=True)
. Output only the next line. | admin.site.register(PBSUserStat) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class ChartGenerator():
@staticmethod
def getJobStatChart(title, currentTime):
statistics =\
DataPool(
series=
[{'options': {
<|code_end|>
with the help of current file imports:
from datetime import timedelta, datetime
from chartit import DataPool, Chart
from pytorque.models import PBSServer, PBSUserStat
import time
and context from other files:
# Path: pytorque/models.py
# class PBSServer(models.Model):
# time = models.DateTimeField(
# default=datetime.now)#auto_now_add=True sets datetime with creating object, not with every modifying action
#
# name = models.CharField(max_length=100)
# state = models.CharField(max_length=20)
# total_jobs = models.IntegerField()
# running_jobs = models.IntegerField()
# queued_jobs = models.IntegerField()
# pbs_version = models.CharField(max_length=10)
#
# class PBSUserStat(models.Model):
# time = models.DateTimeField(default=datetime.now, auto_now_add=True)
#
# username = models.CharField(default='', max_length=100, blank=True, null=True)
# jobCount = models.IntegerField(default=0, blank=True, null=True)
, which may contain function names, class names, or code. Output only the next line. | 'source': PBSServer.objects.order_by('-time')[:20] }, #filter(time__gte=(currentTime - timedelta(hours=+2)))}, |
Next line prediction: <|code_start|> 'queued_jobs',
'total_jobs']}
])
#Step 2: Create the Chart object
chart = Chart(
datasource=statistics,
series_options=
[{'options': {
'type': 'line',
'stacking': False},
'terms': {
'time': [
'running_jobs',
'queued_jobs',
'total_jobs']
}}],
chart_options=
{'title': {
'text': title},
'xAxis': {
'title': {
'text': 'Time'}}},
x_sortf_mapf_mts=(None, lambda i: datetime.fromtimestamp(i).strftime("%H:%M"), False))
return chart
@staticmethod
def getUserStatChart(title, currentTime):
try:
<|code_end|>
. Use current file imports:
(from datetime import timedelta, datetime
from chartit import DataPool, Chart
from pytorque.models import PBSServer, PBSUserStat
import time)
and context including class names, function names, or small code snippets from other files:
# Path: pytorque/models.py
# class PBSServer(models.Model):
# time = models.DateTimeField(
# default=datetime.now)#auto_now_add=True sets datetime with creating object, not with every modifying action
#
# name = models.CharField(max_length=100)
# state = models.CharField(max_length=20)
# total_jobs = models.IntegerField()
# running_jobs = models.IntegerField()
# queued_jobs = models.IntegerField()
# pbs_version = models.CharField(max_length=10)
#
# class PBSUserStat(models.Model):
# time = models.DateTimeField(default=datetime.now, auto_now_add=True)
#
# username = models.CharField(default='', max_length=100, blank=True, null=True)
# jobCount = models.IntegerField(default=0, blank=True, null=True)
. Output only the next line. | lastUserStatTime = PBSUserStat.objects.latest('time').time |
Using the snippet: <|code_start|> customJob.n_p = TorqueService._splitResourcesList(pbsJob[pbs.ATTR_l]['nodes'])
except KeyError:
pass
try:
customJob.setQueued(TorqueService._listToStr(pbsJob[pbs.ATTR_qtime], '|'))
except KeyError:
pass
try:
customJob.setStarted(TorqueService._listToStr(pbsJob[pbs.ATTR_start_time], '|'))
except KeyError:
pass
try:
customJob.running_time = TorqueService._listToStr(pbsJob[pbs.ATTR_used]['walltime'], '|')
except KeyError:
pass
resultJobs.append(customJob)
except PBSError as pbsErr:
print(pbsErr)
return resultJobs
@staticmethod
def getModelServers():
resultServers = []
pQuery = PBSQuery()
try:
servers = pQuery.get_serverinfo()
for serverName, pbsServer in servers.items():
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime
from PBSQuery import PBSQuery, PBSError
from django.contrib.auth.models import User
from pytorque.models import PBSServer, PBSQueue, PBSJob
import time
import pbs
and context (class names, function names, or code) available:
# Path: pytorque/models.py
# class PBSServer(models.Model):
# time = models.DateTimeField(
# default=datetime.now)#auto_now_add=True sets datetime with creating object, not with every modifying action
#
# name = models.CharField(max_length=100)
# state = models.CharField(max_length=20)
# total_jobs = models.IntegerField()
# running_jobs = models.IntegerField()
# queued_jobs = models.IntegerField()
# pbs_version = models.CharField(max_length=10)
#
# class PBSQueue(models.Model):
# server = models.ForeignKey(PBSServer)#, blank=True, null=True, on_delete=models.SET_NULL
# time = models.DateTimeField(default=datetime.now)
#
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# type = models.CharField(default='', max_length=20, blank=True, null=True)
# total_jobs = models.IntegerField(default=0)
# running_jobs = models.IntegerField(default=0)
# queued_jobs = models.IntegerField(default=0)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_nodes = models.IntegerField(default=0)
#
# class PBSJob(models.Model):
# user = models.ForeignKey(User)
# queue = models.ForeignKey(PBSQueue)
# time = models.DateTimeField(default=datetime.now)
#
# jobId = models.CharField(default='', max_length=50, blank=True, null=True)
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# owner = models.CharField(default='', max_length=100, blank=True, null=True)
# state = models.CharField(default='', max_length=10, blank=True, null=True)
# queue_raw = models.CharField(default='', max_length=100, blank=True, null=True)
#
# start_time = models.DateTimeField(default=datetime.now, blank=True, null=True)
# resource_cput = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_mem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_vmem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
. Output only the next line. | customServer = PBSServer(name=serverName) |
Continue the code snippet: <|code_start|> customServer.total_jobs = TorqueService._listToInt(pbsServer[pbs.ATTR_total])
except KeyError:
pass
try:
customServer.running_jobs = int(TorqueService._strToDict(pbsServer[pbs.ATTR_count][0])['Running'])
except KeyError:
pass
try:
customServer.queued_jobs = int(TorqueService._strToDict(pbsServer[pbs.ATTR_count][0])['Queued'])
except KeyError:
pass
try:
customServer.pbs_version = TorqueService._listToStr(pbsServer[pbs.ATTR_pbsversion], '|')
except KeyError:
pass
resultServers.append(customServer)
except PBSError as pbsErr:
print(pbsErr)
return resultServers
@staticmethod
def getModelQueues(pbsServer):
resultQueues = []
pQuery = PBSQuery()
try:
queues = pQuery.getqueues()
for queueName, pbsQueue in queues.items():
<|code_end|>
. Use current file imports:
from datetime import datetime
from PBSQuery import PBSQuery, PBSError
from django.contrib.auth.models import User
from pytorque.models import PBSServer, PBSQueue, PBSJob
import time
import pbs
and context (classes, functions, or code) from other files:
# Path: pytorque/models.py
# class PBSServer(models.Model):
# time = models.DateTimeField(
# default=datetime.now)#auto_now_add=True sets datetime with creating object, not with every modifying action
#
# name = models.CharField(max_length=100)
# state = models.CharField(max_length=20)
# total_jobs = models.IntegerField()
# running_jobs = models.IntegerField()
# queued_jobs = models.IntegerField()
# pbs_version = models.CharField(max_length=10)
#
# class PBSQueue(models.Model):
# server = models.ForeignKey(PBSServer)#, blank=True, null=True, on_delete=models.SET_NULL
# time = models.DateTimeField(default=datetime.now)
#
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# type = models.CharField(default='', max_length=20, blank=True, null=True)
# total_jobs = models.IntegerField(default=0)
# running_jobs = models.IntegerField(default=0)
# queued_jobs = models.IntegerField(default=0)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_nodes = models.IntegerField(default=0)
#
# class PBSJob(models.Model):
# user = models.ForeignKey(User)
# queue = models.ForeignKey(PBSQueue)
# time = models.DateTimeField(default=datetime.now)
#
# jobId = models.CharField(default='', max_length=50, blank=True, null=True)
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# owner = models.CharField(default='', max_length=100, blank=True, null=True)
# state = models.CharField(default='', max_length=10, blank=True, null=True)
# queue_raw = models.CharField(default='', max_length=100, blank=True, null=True)
#
# start_time = models.DateTimeField(default=datetime.now, blank=True, null=True)
# resource_cput = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_mem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_vmem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
. Output only the next line. | customQueue = PBSQueue(server=pbsServer, name=queueName) |
Given snippet: <|code_start|> pass
try:
customQueue.resource_walltime = TorqueService._listToStr(pbsQueue[pbs.ATTR_rescdflt]['walltime'],
'|')
except KeyError:
pass
try:
customQueue.resource_nodes = TorqueService._listToInt(pbsQueue[pbs.ATTR_rescdflt]['nodes'])
except KeyError:
pass
resultQueues.append(customQueue)
except PBSError as pbsErr:
print(pbsErr)
return resultQueues
@staticmethod
def getModelJobs():
"""
1. get jobs
2. get users
3. map each job to User and Queue
4. save all jobs
"""
resultJobs = []
pQuery = PBSQuery()
try:
jobs = pQuery.getjobs()
for jobName, pbsJob in jobs.items():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from datetime import datetime
from PBSQuery import PBSQuery, PBSError
from django.contrib.auth.models import User
from pytorque.models import PBSServer, PBSQueue, PBSJob
import time
import pbs
and context:
# Path: pytorque/models.py
# class PBSServer(models.Model):
# time = models.DateTimeField(
# default=datetime.now)#auto_now_add=True sets datetime with creating object, not with every modifying action
#
# name = models.CharField(max_length=100)
# state = models.CharField(max_length=20)
# total_jobs = models.IntegerField()
# running_jobs = models.IntegerField()
# queued_jobs = models.IntegerField()
# pbs_version = models.CharField(max_length=10)
#
# class PBSQueue(models.Model):
# server = models.ForeignKey(PBSServer)#, blank=True, null=True, on_delete=models.SET_NULL
# time = models.DateTimeField(default=datetime.now)
#
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# type = models.CharField(default='', max_length=20, blank=True, null=True)
# total_jobs = models.IntegerField(default=0)
# running_jobs = models.IntegerField(default=0)
# queued_jobs = models.IntegerField(default=0)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_nodes = models.IntegerField(default=0)
#
# class PBSJob(models.Model):
# user = models.ForeignKey(User)
# queue = models.ForeignKey(PBSQueue)
# time = models.DateTimeField(default=datetime.now)
#
# jobId = models.CharField(default='', max_length=50, blank=True, null=True)
# name = models.CharField(default='', max_length=100, blank=True, null=True)
# owner = models.CharField(default='', max_length=100, blank=True, null=True)
# state = models.CharField(default='', max_length=10, blank=True, null=True)
# queue_raw = models.CharField(default='', max_length=100, blank=True, null=True)
#
# start_time = models.DateTimeField(default=datetime.now, blank=True, null=True)
# resource_cput = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_mem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_vmem = models.CharField(default='', max_length=20, blank=True, null=True)
# resource_walltime = models.CharField(default='', max_length=20, blank=True, null=True)
which might include code, classes, or functions. Output only the next line. | customJob = PBSJob(jobId=jobName) |
Predict the next line after this snippet: <|code_start|> curr_hidden = [fwd_hidden, bwd_hidden[::-1]]
curr_dim = [dim, dim]
return bricks, hidden_list
class Model():
def __init__(self, config, vocab_size):
question = tensor.imatrix('question')
question_mask = tensor.imatrix('question_mask')
context = tensor.imatrix('context')
context_mask = tensor.imatrix('context_mask')
answer = tensor.imatrix('answer')
answer_mask = tensor.imatrix('answer_mask')
ans_indices = tensor.imatrix('ans_indices') # n_steps * n_samples
ans_indices_mask = tensor.imatrix('ans_indices_mask')
bricks = []
question = question.dimshuffle(1, 0)
question_mask = question_mask.dimshuffle(1, 0)
context = context.dimshuffle(1, 0)
context_mask = context_mask.dimshuffle(1, 0)
answer = answer.dimshuffle(1, 0)
answer_mask = answer_mask.dimshuffle(1, 0)
ans_indices = ans_indices.dimshuffle(1, 0)
ans_indices_mask = ans_indices_mask.dimshuffle(1, 0)
# Embed questions and context
embed = LookupTable(vocab_size, config.embed_size, name='embed')
#embed.weights_init = IsotropicGaussian(0.01)
<|code_end|>
using the current file's imports:
import theano
import numpy
import scipy
from theano import tensor
from blocks.bricks import Tanh, Softmax, Linear, MLP, Identity, Rectifier
from blocks.bricks.lookup import LookupTable
from blocks.bricks.recurrent import LSTM, GatedRecurrent, Bidirectional
from blocks.bricks.attention import SequenceContentAttention
from blocks.bricks.parallel import Fork
from blocks.bricks.sequence_generators import (
SequenceGenerator, Readout, SoftmaxEmitter, LookupFeedback)
from blocks.filter import VariableFilter
from blocks.roles import WEIGHT
from blocks.graph import ComputationGraph, apply_dropout, apply_noise
from blocks.monitoring import aggregation
from blocks.initialization import Orthogonal, IsotropicGaussian, Constant
from utils import init_embedding_table
and any relevant context from other files:
# Path: utils.py
# def init_embedding_table(filename='embeddings/vocab_embeddings.txt', embed_dim=300, vocab_file='squad_rare/vocab.txt'):
# import theano
# vocab = ['<DUMMY>', '<EOA>', '@placeholder', '<UNK>'] + [ w.strip().split()[0] for w in open(vocab_file) ]
# reverse_vocab = {w: i for i, w in enumerate(vocab)}
# word_vecs = read_word_vectors(filename,embed_dim)
# embeddings = numpy.ndarray(shape=(len(vocab), embed_dim),dtype=theano.config.floatX)
# count = 0
# for k,v in word_vecs.iteritems():
# if k.upper() in ['<DUMMY>', '<EOA>', '@placeholder', '<UNK>']:
# k = k.upper()
# # print (count)
# # print (reverse_vocab[k])
# count += 1
# embeddings[reverse_vocab[k],:] = v
#
# return embeddings
. Output only the next line. | embed.weights_init = Constant(init_embedding_table(filename='embeddings/vocab_embeddings.txt')) |
Based on the snippet: <|code_start|> assert 0 <= self.redoIndex <= len(self.redo_chain)
if self.stallNextRedo:
self.stallNextRedo = False
return
if self.processTempChange:
self.processTempChange = False
self.__redo_move(self.tempChange)
self.update_basic_scroll_position()
return
if self.tempChange:
self.__undo_move(self.tempChange)
self.tempChange = None
self.update_basic_scroll_position()
while self.redoIndex < len(self.redo_chain):
changes = self.redo_chain[self.redoIndex]
self.redoIndex += 1
for change in changes:
self.__redo_change(change)
# Stop redoing if we redo a non-trivial action
if not (
(changes[0][0] == "f" or changes[0][0] == "m") and len(changes) == 1
):
self.shouldReparse = True
break
self.update_basic_scroll_position()
def __redo_change(self, change):
if change[0] == "b": # Redo backspace.
self.penRow, self.penCol = self.parser.backspace(self.penRow, self.penCol)
elif change[0] == "bw": # Redo backspace word.
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import re
import app.buffer_file
import app.log
import app.selectable
from app.curses_util import column_width
and context (classes, functions, sometimes code) from other files:
# Path: app/curses_util.py
# def column_width(string):
# """When rendering |string| how many character cells will be used? For ASCII
# characters this will equal len(string). For many Chinese characters and
# emoji the value will be greater than len(string), since many of them use two
# cells.
# """
# if app.config.strict_debug:
# assert isinstance(string, unicode)
# width = 0
# for i in string:
# width += char_width(i, width)
# return width
. Output only the next line. | width = column_width(change[1]) |
Predict the next line for this snippet: <|code_start|># See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
kTestFile = "#bookmarks_test_file_with_unlikely_file_name~"
class BookmarkTestCases(app.fake_curses_testing.FakeCursesTestCase):
def setUp(self):
self.prg = app.ci_program.CiProgram()
self.fakeHost = app.window.ViewWindow(self.prg, None)
self.textBuffer = app.text_buffer.TextBuffer(self.prg)
self.textBuffer.lines = 50
self.lineNumbers = app.window.LineNumbers(self.prg, self.fakeHost)
self.lineNumbers.rows = 30
self.lineNumbers.parent = self.fakeHost
self.fakeHost.lineNumberColumn = self.lineNumbers
self.fakeHost.textBuffer = self.textBuffer
self.fakeHost.scrollRow = self.fakeHost.cursorRow = 0
app.fake_curses_testing.FakeCursesTestCase.set_up(self)
def tearDown(self):
app.fake_curses_testing.FakeCursesTestCase.tear_down(self)
def test_bookmark_comparisons(self):
<|code_end|>
with the help of current file imports:
import os
import sys
import unittest
import app.fake_curses_testing
import app.prefs
import app.text_buffer
import app.window
import mock
from app.bookmark import Bookmark
from app.curses_util import *
and context from other files:
# Path: app/bookmark.py
# class Bookmark(object):
# """
# This bookmark object is used as a marker for different places in a
# text document. Note that because text buffer lines index at 0, all
# references to rows also assume that 0 is the first line.
# """
#
# def __init__(self, beginRow, endRow, data):
# """
# Creates a bookmark located at the specified rows. This will
# automatically cast the passed in rows into integers.
# Args:
# beginRow (int-like): The line that the bookmark starts on (inclusive).
# endRow (int-like): The line that the bookmark ends on (inclusive).
# data (other): This is used to store any information that you would
# like to to associate with this bookmark. It is an empty
# dictionary by default.
# """
# self.__begin = int(beginRow)
# self.__end = int(endRow)
# self.data = data
#
# @property
# def range(self):
# return (self.begin, self.end)
#
# @range.setter
# def range(self, value):
# self.__begin, self.__end = sorted(int(x) for x in value)
#
# @property
# def begin(self):
# return self.__begin
#
# @begin.setter
# def begin(self, value):
# self.__begin, self.__end = sorted(int(x) for x in (value, self.__end))
#
# @property
# def end(self):
# return self.__end
#
# @end.setter
# def end(self, value):
# self.__begin, self.__end = sorted(int(x) for x in (self.__begin, value))
#
# def overlaps(self, bookmark):
# """
# Takes in another bookmark object and returns True if this bookmark
# shares any rows with the passed in bookmark.
# """
# begin1, end1 = self.range
# begin2, end2 = bookmark.range
# return begin1 <= end2 and end1 >= begin2
#
# def __contains__(self, row):
# """
# Args:
# row (int): the row that you want to check.
#
# Returns:
# True if the passed in row is inside the bookmark's range.
# """
# return self.begin <= row <= self.end
#
# def __lt__(self, other):
# assert isinstance(other, Bookmark)
# return self.range < other.range
#
# def __gt__(self, other):
# assert isinstance(other, Bookmark)
# return self.range > other.range
#
# def __eq__(self, other):
# assert isinstance(other, Bookmark)
# return self.range == other.range
#
# def __ne__(self, other):
# assert isinstance(other, Bookmark)
# return self.range != other.range
#
# def __le__(self, other):
# assert isinstance(other, Bookmark)
# return self.range <= other.range
#
# def __ge__(self, other):
# assert isinstance(other, Bookmark)
# return self.range >= other.range
#
# def __hash__(self):
# # NOTE: Any two bookmarks with the same range WILL have the same hash
# # value. self.range can also change, so be careful when using this in a
# # hash table.
# return hash(self.range)
#
# def __repr__(self):
# return repr(self.range)
, which may contain function names, class names, or code. Output only the next line. | b1 = Bookmark(1, 5, {}) |
Next line prediction: <|code_start|>
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'],
'Email address already taken.')
def test_signup_verify_invalid_code(self):
url = reverse('authemail-signup-verify')
params = {
'code': 'XXX',
}
response = self.client.get(url, params)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Unable to verify user.')
def test_signup_and_signup_verify(self):
# Send Signup request
url = reverse('authemail-signup')
payload = {
'email': self.user_visitor_email,
'password': self.user_visitor_pw,
}
response = self.client.post(url, payload)
# Confirm that new user created, but not verified
user = get_user_model().objects.latest('id')
self.assertEqual(user.email, self.user_visitor_email)
self.assertEqual(user.is_verified, False)
# Confirm that signup code created
<|code_end|>
. Use current file imports:
(import re
from datetime import timedelta
from django.core import mail
from django.contrib.auth import get_user_model
from django.test.utils import override_settings
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from authemail.models import SignupCode, PasswordResetCode
from authemail.models import EmailChangeCode)
and context including class names, function names, or small code snippets from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
. Output only the next line. | signup_code = SignupCode.objects.latest('code') |
Given the code snippet: <|code_start|> payload = {
'email': 'XXX@mail.com'
}
response = self.client.post(url, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Password reset not allowed.')
def test_password_reset_user_not_verified_not_allowed(self):
url = reverse('authemail-password-reset')
payload = {
'email': self.user_not_verified_email
}
response = self.client.post(url, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Password reset not allowed.')
def test_password_reset_user_not_active_not_allowed(self):
url = reverse('authemail-password-reset')
payload = {
'email': self.user_not_active_email
}
response = self.client.post(url, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Password reset not allowed.')
def test_password_reset_user_verified_code_created_email_sent(self):
# Create two past reset codes that aren't used
<|code_end|>
, generate the next line using the imports in this file:
import re
from datetime import timedelta
from django.core import mail
from django.contrib.auth import get_user_model
from django.test.utils import override_settings
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from authemail.models import SignupCode, PasswordResetCode
from authemail.models import EmailChangeCode
and context (functions, classes, or occasionally code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
. Output only the next line. | password_reset_code_old1 = PasswordResetCode.objects.create_password_reset_code( |
Continue the code snippet: <|code_start|> url = reverse('authemail-email-change')
for error_dict in error_dicts:
response = self.client.post(url, error_dict['payload'])
self.assertEqual(response.status_code, error_dict['status_code'])
self.assertEqual(response.data[error_dict['error'][0]][0],
error_dict['error'][1])
def test_email_change_user_verified_so_email_taken(self):
# Send Email Change request
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
url = reverse('authemail-email-change')
payload = {
'email': self.user_verified_email,
}
response = self.client.post(url, payload)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Email address already taken.')
def test_email_change_user_not_verified_code_created_and_emails_sent(self):
# Send Email Change request
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
url = reverse('authemail-email-change')
payload = {
'email': self.user_not_verified_email,
}
response = self.client.post(url, payload)
# Confirm that email change code created
<|code_end|>
. Use current file imports:
import re
from datetime import timedelta
from django.core import mail
from django.contrib.auth import get_user_model
from django.test.utils import override_settings
from django.urls import reverse
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from authemail.models import SignupCode, PasswordResetCode
from authemail.models import EmailChangeCode
and context (classes, functions, or code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
. Output only the next line. | email_change_code = EmailChangeCode.objects.latest('code') |
Using the snippet: <|code_start|>
class LandingFrontEnd(TemplateView):
template_name = 'landing.html'
class SignupFrontEnd(FormView):
template_name = 'signup.html'
form_class = SignupForm
success_url = reverse_lazy('signup_email_sent_page')
def form_valid(self, form):
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
<|code_end|>
, determine the next line of code. You have imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context (class names, function names, or code) available:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
. Output only the next line. | account = wrapper.Authemail() |
Here is a snippet: <|code_start|>
class LandingFrontEnd(TemplateView):
template_name = 'landing.html'
class SignupFrontEnd(FormView):
template_name = 'signup.html'
<|code_end|>
. Write the next line using the current file imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context from other files:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
, which may include functions, classes, or code. Output only the next line. | form_class = SignupForm |
Given the code snippet: <|code_start|>
class SignupEmailSentFrontEnd(TemplateView):
template_name = 'signup_email_sent.html'
class SignupVerifyFrontEnd(View):
def get(self, request, format=None):
code = request.GET.get('code', '')
account = wrapper.Authemail()
response = account.signup_verify(code=code)
# Handle other error responses from API
if 'detail' in response:
return HttpResponseRedirect(reverse('signup_not_verified_page'))
return HttpResponseRedirect(reverse('signup_verified_page'))
class SignupVerifiedFrontEnd(TemplateView):
template_name = 'signup_verified.html'
class SignupNotVerifiedFrontEnd(TemplateView):
template_name = 'signup_not_verified.html'
class LoginFrontEnd(FormView):
template_name = 'login.html'
<|code_end|>
, generate the next line using the imports in this file:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context (functions, classes, or occasionally code) from other files:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
. Output only the next line. | form_class = LoginForm |
Based on the snippet: <|code_start|>
def get_context_data(self, **kwargs):
context = super(HomeFrontEnd, self).get_context_data(**kwargs)
token = self.request.session['auth_token']
account = wrapper.Authemail()
account.users_me(token=token)
context['first_name'] = account.first_name
context['last_name'] = account.last_name
context['email'] = account.email
return context
class LogoutFrontEnd(View):
def get(self, request):
token = self.request.session['auth_token']
account = wrapper.Authemail()
account.logout(token=token)
self.request.session.flush()
return HttpResponseRedirect(reverse('landing_page'))
class PasswordResetFrontEnd(FormView):
template_name = 'password_reset.html'
<|code_end|>
, predict the immediate next line with the help of imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context (classes, functions, sometimes code) from other files:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
. Output only the next line. | form_class = PasswordResetForm |
Here is a snippet: <|code_start|> if 'detail' in response:
form.add_error(None, response['detail'])
return self.form_invalid(form)
return super(PasswordResetFrontEnd, self).form_valid(form)
class PasswordResetEmailSentFrontEnd(TemplateView):
template_name = 'password_reset_email_sent.html'
class PasswordResetVerifyFrontEnd(View):
def get(self, request, format=None):
code = request.GET.get('code', '')
account = wrapper.Authemail()
response = account.password_reset_verify(code=code)
# Handle other error responses from API
if 'detail' in response:
return HttpResponseRedirect(
reverse('password_reset_not_verified_page'))
request.session['password_reset_code'] = code
return HttpResponseRedirect(reverse('password_reset_verified_page'))
class PasswordResetVerifiedFrontEnd(FormView):
template_name = 'password_reset_verified.html'
<|code_end|>
. Write the next line using the current file imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context from other files:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
, which may include functions, classes, or code. Output only the next line. | form_class = PasswordResetVerifiedForm |
Given snippet: <|code_start|>class PasswordResetVerifiedFrontEnd(FormView):
template_name = 'password_reset_verified.html'
form_class = PasswordResetVerifiedForm
success_url = reverse_lazy('password_reset_success_page')
def form_valid(self, form):
code = self.request.session['password_reset_code']
password = form.cleaned_data['password']
account = wrapper.Authemail()
response = account.password_reset_verified(code=code, password=password)
# Handle other error responses from API
if 'detail' in response:
form.add_error(None, response['detail'])
return self.form_invalid(form)
return super(PasswordResetVerifiedFrontEnd, self).form_valid(form)
class PasswordResetNotVerifiedFrontEnd(TemplateView):
template_name = 'password_reset_not_verified.html'
class PasswordResetSuccessFrontEnd(TemplateView):
template_name = 'password_reset_success.html'
class EmailChangeFrontEnd(FormView):
template_name = 'email_change.html'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
which might include code, classes, or functions. Output only the next line. | form_class = EmailChangeForm |
Continue the code snippet: <|code_start|> template_name = 'email_change_emails_sent.html'
class EmailChangeVerifyFrontEnd(View):
def get(self, request, format=None):
code = request.GET.get('code', '')
account = wrapper.Authemail()
response = account.email_change_verify(code=code)
# Handle other error responses from API
if 'detail' in response:
return HttpResponseRedirect(
reverse('email_change_not_verified_page'))
request.session['email_change_code'] = code
return HttpResponseRedirect(reverse('email_change_verified_page'))
class EmailChangeVerifiedFrontEnd(TemplateView):
template_name = 'email_change_verified.html'
class EmailChangeNotVerifiedFrontEnd(TemplateView):
template_name = 'email_change_not_verified.html'
class PasswordChangeFrontEnd(FormView):
template_name = 'password_change.html'
<|code_end|>
. Use current file imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context (classes, functions, or code) from other files:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
. Output only the next line. | form_class = PasswordChangeForm |
Here is a snippet: <|code_start|>class EmailChangeNotVerifiedFrontEnd(TemplateView):
template_name = 'email_change_not_verified.html'
class PasswordChangeFrontEnd(FormView):
template_name = 'password_change.html'
form_class = PasswordChangeForm
success_url = reverse_lazy('password_change_success_page')
def form_valid(self, form):
token = self.request.session['auth_token']
password = form.cleaned_data['password']
account = wrapper.Authemail()
response = account.password_change(token=token, password=password)
# Handle other error responses from API
if 'detail' in response:
form.add_error(None, response['detail'])
return self.form_invalid(form)
return super(PasswordChangeFrontEnd, self).form_valid(form)
class PasswordChangeSuccessFrontEnd(TemplateView):
template_name = 'password_change_success.html'
class UsersMeChangeFrontEnd(FormView):
template_name = 'users_me_change.html'
<|code_end|>
. Write the next line using the current file imports:
from django.urls import reverse, reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.views.generic.edit import FormView
from authemail import wrapper
from .forms import SignupForm, LoginForm
from .forms import PasswordResetForm, PasswordResetVerifiedForm
from .forms import EmailChangeForm
from .forms import PasswordChangeForm, UsersMeChangeForm
from . import wrapperplus
and context from other files:
# Path: authemail/wrapper.py
# class API(object):
# class Authemail(API):
# BASE_PATH = ''
# URLS = {}
# BASE_PATH = 'accounts'
# URLS = {
# 'signup': '/signup/',
# 'signup_verify': '/signup/verify/',
# 'login': '/login/',
# 'logout': '/logout/',
# 'password_reset': '/password/reset/',
# 'password_reset_verify': '/password/reset/verify/',
# 'password_reset_verified': '/password/reset/verified/',
# 'email_change': '/email/change/',
# 'email_change_verify': '/email/change/verify/',
# 'password_change': '/password/change/',
# 'users_me': '/users/me/',
# }
# def __init__(self):
# def _get_path(self, key):
# def _get_complete_url(self, path):
# def _request(self, method, path, params=None, payload=None):
# def _GET(self, path, params=None):
# def _POST(self, path, params=None, payload=None):
# def _set_attrs_to_values(self, response={}):
# def signup(self, **kwargs):
# def signup_verify(self, **kwargs):
# def login(self, **kwargs):
# def logout(self, **kwargs):
# def password_reset(self, **kwargs):
# def password_reset_verify(self, **kwargs):
# def password_reset_verified(self, **kwargs):
# def email_change(self, **kwargs):
# def email_change_verify(self, **kwargs):
# def password_change(self, **kwargs):
# def users_me(self, **kwargs):
#
# Path: example_project/example_project/forms.py
# class SignupForm(PasswordConfirmForm):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# email = forms.EmailField(max_length=255)
#
# class LoginForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
# password = forms.CharField(max_length=128)
#
# Path: example_project/example_project/forms.py
# class PasswordResetForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# class PasswordResetVerifiedForm(AddErrorMixin, forms.Form):
# pass
#
# Path: example_project/example_project/forms.py
# class EmailChangeForm(AddErrorMixin, forms.Form):
# email = forms.EmailField(max_length=255)
#
# Path: example_project/example_project/forms.py
# class PasswordChangeForm(PasswordConfirmForm):
# pass
#
# class UsersMeChangeForm(AddErrorMixin, forms.Form):
# first_name = forms.CharField(max_length=30, required=False)
# last_name = forms.CharField(max_length=30, required=False)
# date_of_birth = forms.DateField(required=False)
, which may include functions, classes, or code. Output only the next line. | form_class = UsersMeChangeForm |
Continue the code snippet: <|code_start|>
class Signup(APIView):
permission_classes = (AllowAny,)
serializer_class = SignupSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
email = serializer.data['email']
password = serializer.data['password']
first_name = serializer.data['first_name']
last_name = serializer.data['last_name']
must_validate_email = getattr(settings, "AUTH_EMAIL_VERIFICATION", True)
try:
user = get_user_model().objects.get(email=email)
if user.is_verified:
content = {'detail': _('Email address already taken.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
try:
# Delete old signup codes
<|code_end|>
. Use current file imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context (classes, functions, or code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | signup_code = SignupCode.objects.get(user=user) |
Based on the snippet: <|code_start|> try:
password_reset_code = PasswordResetCode.objects.get(code=code)
password_reset_code.user.set_password(password)
password_reset_code.user.save()
# Delete password reset code just used
password_reset_code.delete()
content = {'success': _('Password reset.')}
return Response(content, status=status.HTTP_200_OK)
except PasswordResetCode.DoesNotExist:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class EmailChange(APIView):
permission_classes = (IsAuthenticated,)
serializer_class = EmailChangeSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
user = request.user
# Delete all unused email change codes
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context (classes, functions, sometimes code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | EmailChangeCode.objects.filter(user=user).delete() |
Predict the next line after this snippet: <|code_start|>
class Logout(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
"""
Remove all auth tokens owned by request.user.
"""
tokens = Token.objects.filter(user=request.user)
for token in tokens:
token.delete()
content = {'success': _('User logged out.')}
return Response(content, status=status.HTTP_200_OK)
class PasswordReset(APIView):
permission_classes = (AllowAny,)
serializer_class = PasswordResetSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
email = serializer.data['email']
try:
user = get_user_model().objects.get(email=email)
# Delete all unused password reset codes
<|code_end|>
using the current file's imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and any relevant context from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | PasswordResetCode.objects.filter(user=user).delete() |
Here is a snippet: <|code_start|> if serializer.is_valid():
email = serializer.data['email']
password = serializer.data['password']
first_name = serializer.data['first_name']
last_name = serializer.data['last_name']
must_validate_email = getattr(settings, "AUTH_EMAIL_VERIFICATION", True)
try:
user = get_user_model().objects.get(email=email)
if user.is_verified:
content = {'detail': _('Email address already taken.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
try:
# Delete old signup codes
signup_code = SignupCode.objects.get(user=user)
signup_code.delete()
except SignupCode.DoesNotExist:
pass
except get_user_model().DoesNotExist:
user = get_user_model().objects.create_user(email=email)
# Set user fields provided
user.set_password(password)
user.first_name = first_name
user.last_name = last_name
if not must_validate_email:
user.is_verified = True
<|code_end|>
. Write the next line using the current file imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
, which may include functions, classes, or code. Output only the next line. | send_multi_format_email('welcome_email', |
Based on the snippet: <|code_start|>
content = {'email': email, 'first_name': first_name,
'last_name': last_name}
return Response(content, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class SignupVerify(APIView):
permission_classes = (AllowAny,)
def get(self, request, format=None):
code = request.GET.get('code', '')
verified = SignupCode.objects.set_user_is_verified(code)
if verified:
try:
signup_code = SignupCode.objects.get(code=code)
signup_code.delete()
except SignupCode.DoesNotExist:
pass
content = {'success': _('Email address verified.')}
return Response(content, status=status.HTTP_200_OK)
else:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
class Login(APIView):
permission_classes = (AllowAny,)
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context (classes, functions, sometimes code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | serializer_class = LoginSerializer |
Predict the next line after this snippet: <|code_start|> else:
content = {'detail':
_('User account not verified.')}
return Response(content, status=status.HTTP_401_UNAUTHORIZED)
else:
content = {'detail':
_('Unable to login with provided credentials.')}
return Response(content, status=status.HTTP_401_UNAUTHORIZED)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class Logout(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
"""
Remove all auth tokens owned by request.user.
"""
tokens = Token.objects.filter(user=request.user)
for token in tokens:
token.delete()
content = {'success': _('User logged out.')}
return Response(content, status=status.HTTP_200_OK)
class PasswordReset(APIView):
permission_classes = (AllowAny,)
<|code_end|>
using the current file's imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and any relevant context from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | serializer_class = PasswordResetSerializer |
Given the code snippet: <|code_start|>
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class PasswordResetVerify(APIView):
permission_classes = (AllowAny,)
def get(self, request, format=None):
code = request.GET.get('code', '')
try:
password_reset_code = PasswordResetCode.objects.get(code=code)
# Delete password reset code if older than expiry period
delta = date.today() - password_reset_code.created_at.date()
if delta.days > PasswordResetCode.objects.get_expiry_period():
password_reset_code.delete()
raise PasswordResetCode.DoesNotExist()
content = {'success': _('Email address verified.')}
return Response(content, status=status.HTTP_200_OK)
except PasswordResetCode.DoesNotExist:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
class PasswordResetVerified(APIView):
permission_classes = (AllowAny,)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context (functions, classes, or occasionally code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | serializer_class = PasswordResetVerifiedSerializer |
Given the code snippet: <|code_start|> serializer_class = PasswordResetVerifiedSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
code = serializer.data['code']
password = serializer.data['password']
try:
password_reset_code = PasswordResetCode.objects.get(code=code)
password_reset_code.user.set_password(password)
password_reset_code.user.save()
# Delete password reset code just used
password_reset_code.delete()
content = {'success': _('Password reset.')}
return Response(content, status=status.HTTP_200_OK)
except PasswordResetCode.DoesNotExist:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class EmailChange(APIView):
permission_classes = (IsAuthenticated,)
<|code_end|>
, generate the next line using the imports in this file:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context (functions, classes, or occasionally code) from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | serializer_class = EmailChangeSerializer |
Given the following code snippet before the placeholder: <|code_start|> if user_with_email.is_verified:
# Delete email change code since won't be used
email_change_code.delete()
content = {'detail': _('Email address already taken.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
else:
# If the account with this email address is not verified,
# delete the account (and signup code) because the email
# address will be used for the user who just verified.
user_with_email.delete()
except get_user_model().DoesNotExist:
pass
# If all is well, change the email address.
email_change_code.user.email = email_change_code.email
email_change_code.user.save()
# Delete email change code just used
email_change_code.delete()
content = {'success': _('Email address changed.')}
return Response(content, status=status.HTTP_200_OK)
except EmailChangeCode.DoesNotExist:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
class PasswordChange(APIView):
permission_classes = (IsAuthenticated,)
<|code_end|>
, predict the next line using imports from the current file:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context including class names, function names, and sometimes code from other files:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | serializer_class = PasswordChangeSerializer |
Using the snippet: <|code_start|> return Response(content, status=status.HTTP_200_OK)
except EmailChangeCode.DoesNotExist:
content = {'detail': _('Unable to verify user.')}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
class PasswordChange(APIView):
permission_classes = (IsAuthenticated,)
serializer_class = PasswordChangeSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
user = request.user
password = serializer.data['password']
user.set_password(password)
user.save()
content = {'success': _('Password changed.')}
return Response(content, status=status.HTTP_200_OK)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class UserMe(APIView):
permission_classes = (IsAuthenticated,)
<|code_end|>
, determine the next line of code. You have imports:
from datetime import date
from django.conf import settings
from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from authemail.models import SignupCode, EmailChangeCode, PasswordResetCode
from authemail.models import send_multi_format_email
from authemail.serializers import SignupSerializer, LoginSerializer
from authemail.serializers import PasswordResetSerializer
from authemail.serializers import PasswordResetVerifiedSerializer
from authemail.serializers import EmailChangeSerializer
from authemail.serializers import PasswordChangeSerializer
from authemail.serializers import UserSerializer
and context (class names, function names, or code) available:
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# Path: authemail/models.py
# def send_multi_format_email(template_prefix, template_ctxt, target_email):
# subject_file = 'authemail/%s_subject.txt' % template_prefix
# txt_file = 'authemail/%s.txt' % template_prefix
# html_file = 'authemail/%s.html' % template_prefix
#
# subject = render_to_string(subject_file).strip()
# from_email = settings.EMAIL_FROM
# to = target_email
# bcc_email = settings.EMAIL_BCC
# text_content = render_to_string(txt_file, template_ctxt)
# html_content = render_to_string(html_file, template_ctxt)
# msg = EmailMultiAlternatives(subject, text_content, from_email, [to],
# bcc=[bcc_email])
# msg.attach_alternative(html_content, 'text/html')
# msg.send()
#
# Path: authemail/serializers.py
# class SignupSerializer(serializers.Serializer):
# """
# Don't require email to be unique so visitor can signup multiple times,
# if misplace verification email. Handle in view.
# """
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
# first_name = serializers.CharField(max_length=30, default='',
# required=False)
# last_name = serializers.CharField(max_length=30, default='',
# required=False)
#
# class LoginSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class PasswordResetSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordResetVerifiedSerializer(serializers.Serializer):
# code = serializers.CharField(max_length=40)
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class EmailChangeSerializer(serializers.Serializer):
# email = serializers.EmailField(max_length=255)
#
# Path: authemail/serializers.py
# class PasswordChangeSerializer(serializers.Serializer):
# password = serializers.CharField(max_length=128)
#
# Path: authemail/serializers.py
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = get_user_model()
# fields = ('email', 'first_name', 'last_name')
. Output only the next line. | serializer_class = UserSerializer |
Predict the next line after this snippet: <|code_start|>
class EmailChangeCodeInline(admin.TabularInline):
model = EmailChangeCode
fieldsets = (
(None, {
'fields': ('code', 'email', 'created_at')
}),
)
readonly_fields = ('code', 'email', 'created_at')
def has_add_permission(self, request, obj=None):
return False
class EmailUserAdmin(UserAdmin):
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal Info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
form = EmailUserChangeForm
<|code_end|>
using the current file's imports:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from authemail.forms import EmailUserCreationForm, EmailUserChangeForm
from authemail.models import SignupCode, PasswordResetCode, EmailChangeCode
and any relevant context from other files:
# Path: authemail/forms.py
# class EmailUserCreationForm(forms.ModelForm):
# """
# A form that creates a user, with no privileges, from the given email and
# password.
# """
# password1 = forms.CharField(label=_('Password'),
# widget=forms.PasswordInput)
# password2 = forms.CharField(label=_('Password confirmation'),
# widget=forms.PasswordInput,
# help_text=_('Enter the same password as '
# 'above, for verification.'))
#
# class Meta:
# model = get_user_model()
# fields = ('email',)
#
# def clean_email(self):
# email = self.cleaned_data.get('email')
# try:
# get_user_model().objects.get(email=email)
# except get_user_model().DoesNotExist:
# return email
# raise forms.ValidationError(_('A user with that email already exists.'))
#
# def clean_password2(self):
# password1 = self.cleaned_data.get('password1')
# password2 = self.cleaned_data.get('password2')
# if password1 and password2 and password1 != password2:
# raise forms.ValidationError(
# _('The two password fields did not match.'))
# return password2
#
# def save(self, commit=True):
# user = super(EmailUserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data['password1'])
# if commit:
# user.save()
# return user
#
# class EmailUserChangeForm(UserChangeForm):
# class Meta:
# model = get_user_model()
# fields = '__all__'
#
# def __init__(self, *args, **kwargs):
# super(EmailUserChangeForm, self).__init__(*args, **kwargs)
# if 'username' in self.fields:
# del self.fields['username']
#
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
. Output only the next line. | add_form = EmailUserCreationForm |
Here is a snippet: <|code_start|> return False
class EmailChangeCodeInline(admin.TabularInline):
model = EmailChangeCode
fieldsets = (
(None, {
'fields': ('code', 'email', 'created_at')
}),
)
readonly_fields = ('code', 'email', 'created_at')
def has_add_permission(self, request, obj=None):
return False
class EmailUserAdmin(UserAdmin):
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal Info'), {'fields': ('first_name', 'last_name')}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from authemail.forms import EmailUserCreationForm, EmailUserChangeForm
from authemail.models import SignupCode, PasswordResetCode, EmailChangeCode
and context from other files:
# Path: authemail/forms.py
# class EmailUserCreationForm(forms.ModelForm):
# """
# A form that creates a user, with no privileges, from the given email and
# password.
# """
# password1 = forms.CharField(label=_('Password'),
# widget=forms.PasswordInput)
# password2 = forms.CharField(label=_('Password confirmation'),
# widget=forms.PasswordInput,
# help_text=_('Enter the same password as '
# 'above, for verification.'))
#
# class Meta:
# model = get_user_model()
# fields = ('email',)
#
# def clean_email(self):
# email = self.cleaned_data.get('email')
# try:
# get_user_model().objects.get(email=email)
# except get_user_model().DoesNotExist:
# return email
# raise forms.ValidationError(_('A user with that email already exists.'))
#
# def clean_password2(self):
# password1 = self.cleaned_data.get('password1')
# password2 = self.cleaned_data.get('password2')
# if password1 and password2 and password1 != password2:
# raise forms.ValidationError(
# _('The two password fields did not match.'))
# return password2
#
# def save(self, commit=True):
# user = super(EmailUserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data['password1'])
# if commit:
# user.save()
# return user
#
# class EmailUserChangeForm(UserChangeForm):
# class Meta:
# model = get_user_model()
# fields = '__all__'
#
# def __init__(self, *args, **kwargs):
# super(EmailUserChangeForm, self).__init__(*args, **kwargs)
# if 'username' in self.fields:
# del self.fields['username']
#
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
, which may include functions, classes, or code. Output only the next line. | form = EmailUserChangeForm |
Here is a snippet: <|code_start|>
class SignupCodeAdmin(admin.ModelAdmin):
list_display = ('code', 'user', 'ipaddr', 'created_at')
ordering = ('-created_at',)
readonly_fields = ('user', 'code', 'ipaddr')
def has_add_permission(self, request, obj=None):
return False
class SignupCodeInline(admin.TabularInline):
<|code_end|>
. Write the next line using the current file imports:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from authemail.forms import EmailUserCreationForm, EmailUserChangeForm
from authemail.models import SignupCode, PasswordResetCode, EmailChangeCode
and context from other files:
# Path: authemail/forms.py
# class EmailUserCreationForm(forms.ModelForm):
# """
# A form that creates a user, with no privileges, from the given email and
# password.
# """
# password1 = forms.CharField(label=_('Password'),
# widget=forms.PasswordInput)
# password2 = forms.CharField(label=_('Password confirmation'),
# widget=forms.PasswordInput,
# help_text=_('Enter the same password as '
# 'above, for verification.'))
#
# class Meta:
# model = get_user_model()
# fields = ('email',)
#
# def clean_email(self):
# email = self.cleaned_data.get('email')
# try:
# get_user_model().objects.get(email=email)
# except get_user_model().DoesNotExist:
# return email
# raise forms.ValidationError(_('A user with that email already exists.'))
#
# def clean_password2(self):
# password1 = self.cleaned_data.get('password1')
# password2 = self.cleaned_data.get('password2')
# if password1 and password2 and password1 != password2:
# raise forms.ValidationError(
# _('The two password fields did not match.'))
# return password2
#
# def save(self, commit=True):
# user = super(EmailUserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data['password1'])
# if commit:
# user.save()
# return user
#
# class EmailUserChangeForm(UserChangeForm):
# class Meta:
# model = get_user_model()
# fields = '__all__'
#
# def __init__(self, *args, **kwargs):
# super(EmailUserChangeForm, self).__init__(*args, **kwargs)
# if 'username' in self.fields:
# del self.fields['username']
#
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
, which may include functions, classes, or code. Output only the next line. | model = SignupCode |
Given the following code snippet before the placeholder: <|code_start|> ordering = ('-created_at',)
readonly_fields = ('user', 'code', 'ipaddr')
def has_add_permission(self, request, obj=None):
return False
class SignupCodeInline(admin.TabularInline):
model = SignupCode
fieldsets = (
(None, {
'fields': ('code', 'ipaddr', 'created_at')
}),
)
readonly_fields = ('code', 'ipaddr', 'created_at')
def has_add_permission(self, request, obj=None):
return False
class PasswordResetCodeAdmin(admin.ModelAdmin):
list_display = ('code', 'user', 'created_at')
ordering = ('-created_at',)
readonly_fields = ('user', 'code')
def has_add_permission(self, request, obj=None):
return False
class PasswordResetCodeInline(admin.TabularInline):
<|code_end|>
, predict the next line using imports from the current file:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from authemail.forms import EmailUserCreationForm, EmailUserChangeForm
from authemail.models import SignupCode, PasswordResetCode, EmailChangeCode
and context including class names, function names, and sometimes code from other files:
# Path: authemail/forms.py
# class EmailUserCreationForm(forms.ModelForm):
# """
# A form that creates a user, with no privileges, from the given email and
# password.
# """
# password1 = forms.CharField(label=_('Password'),
# widget=forms.PasswordInput)
# password2 = forms.CharField(label=_('Password confirmation'),
# widget=forms.PasswordInput,
# help_text=_('Enter the same password as '
# 'above, for verification.'))
#
# class Meta:
# model = get_user_model()
# fields = ('email',)
#
# def clean_email(self):
# email = self.cleaned_data.get('email')
# try:
# get_user_model().objects.get(email=email)
# except get_user_model().DoesNotExist:
# return email
# raise forms.ValidationError(_('A user with that email already exists.'))
#
# def clean_password2(self):
# password1 = self.cleaned_data.get('password1')
# password2 = self.cleaned_data.get('password2')
# if password1 and password2 and password1 != password2:
# raise forms.ValidationError(
# _('The two password fields did not match.'))
# return password2
#
# def save(self, commit=True):
# user = super(EmailUserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data['password1'])
# if commit:
# user.save()
# return user
#
# class EmailUserChangeForm(UserChangeForm):
# class Meta:
# model = get_user_model()
# fields = '__all__'
#
# def __init__(self, *args, **kwargs):
# super(EmailUserChangeForm, self).__init__(*args, **kwargs)
# if 'username' in self.fields:
# del self.fields['username']
#
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
. Output only the next line. | model = PasswordResetCode |
Given snippet: <|code_start|> ordering = ('-created_at',)
readonly_fields = ('user', 'code')
def has_add_permission(self, request, obj=None):
return False
class PasswordResetCodeInline(admin.TabularInline):
model = PasswordResetCode
fieldsets = (
(None, {
'fields': ('code', 'created_at')
}),
)
readonly_fields = ('code', 'created_at')
def has_add_permission(self, request, obj=None):
return False
class EmailChangeCodeAdmin(admin.ModelAdmin):
list_display = ('code', 'user', 'email', 'created_at')
ordering = ('-created_at',)
readonly_fields = ('user', 'code', 'email')
def has_add_permission(self, request, obj=None):
return False
class EmailChangeCodeInline(admin.TabularInline):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from authemail.forms import EmailUserCreationForm, EmailUserChangeForm
from authemail.models import SignupCode, PasswordResetCode, EmailChangeCode
and context:
# Path: authemail/forms.py
# class EmailUserCreationForm(forms.ModelForm):
# """
# A form that creates a user, with no privileges, from the given email and
# password.
# """
# password1 = forms.CharField(label=_('Password'),
# widget=forms.PasswordInput)
# password2 = forms.CharField(label=_('Password confirmation'),
# widget=forms.PasswordInput,
# help_text=_('Enter the same password as '
# 'above, for verification.'))
#
# class Meta:
# model = get_user_model()
# fields = ('email',)
#
# def clean_email(self):
# email = self.cleaned_data.get('email')
# try:
# get_user_model().objects.get(email=email)
# except get_user_model().DoesNotExist:
# return email
# raise forms.ValidationError(_('A user with that email already exists.'))
#
# def clean_password2(self):
# password1 = self.cleaned_data.get('password1')
# password2 = self.cleaned_data.get('password2')
# if password1 and password2 and password1 != password2:
# raise forms.ValidationError(
# _('The two password fields did not match.'))
# return password2
#
# def save(self, commit=True):
# user = super(EmailUserCreationForm, self).save(commit=False)
# user.set_password(self.cleaned_data['password1'])
# if commit:
# user.save()
# return user
#
# class EmailUserChangeForm(UserChangeForm):
# class Meta:
# model = get_user_model()
# fields = '__all__'
#
# def __init__(self, *args, **kwargs):
# super(EmailUserChangeForm, self).__init__(*args, **kwargs)
# if 'username' in self.fields:
# del self.fields['username']
#
# Path: authemail/models.py
# class SignupCode(AbstractBaseCode):
# ipaddr = models.GenericIPAddressField(_('ip address'))
#
# objects = SignupCodeManager()
#
# def send_signup_email(self):
# prefix = 'signup_email'
# self.send_email(prefix)
#
# class PasswordResetCode(AbstractBaseCode):
# objects = PasswordResetCodeManager()
#
# def send_password_reset_email(self):
# prefix = 'password_reset_email'
# self.send_email(prefix)
#
# class EmailChangeCode(AbstractBaseCode):
# email = models.EmailField(_('email address'), max_length=255)
#
# objects = EmailChangeCodeManager()
#
# def send_email_change_emails(self):
# prefix = 'email_change_notify_previous_email'
# self.send_email(prefix)
#
# prefix = 'email_change_confirm_new_email'
# ctxt = {
# 'email': self.email,
# 'code': self.code
# }
#
# send_multi_format_email(prefix, ctxt, target_email=self.email)
which might include code, classes, or functions. Output only the next line. | model = EmailChangeCode |
Predict the next line after this snippet: <|code_start|> 'publisher_category_id': GetCategoryId(rating.category),
'date': rating.date,
'rating': rating.rating,
'url': rating.url,
}
def FeedRatingToUnified(item):
return {
'type': SOURCE_TYPE_FEED,
'publisher_id': item.feed_url,
'publisher_category_id': None,
'date': item.published_date,
'rating': ratings.POSITIVE,
'url': item.url,
}
def GetUnifiedRatings(url, include_source_feed=True, do_not_fetch=False):
page_info_future = GetPageInfoAsync(url, do_not_fetch=do_not_fetch)
# Find user ratings for this url.
user_ratings = [
UserRatingToUnified(rating)
for rating in PageRating.query(
PageRating.url == url).order(-PageRating.date)
if rating.rating != ratings.NEUTRAL
]
# Find feed items for this url.
feed_ratings = [
<|code_end|>
using the current file's imports:
from datetime import datetime
from datetime import timedelta
from urlparse import urlparse
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from recommender import feeds
from recommender import items
from recommender import json_encoder
from recommender import ratings
from recommender import time_periods
from recommender import url_util
import functools
import logging
import math
import pickle
and any relevant context from other files:
# Path: recommender/feeds.py
# MAX_ITEMS_PER_FEED = 0
# CLEAN_UP_ITEMS_PER_UPDATE = 1000
# TIME_BETWEEN_UPDATES = timedelta(minutes=30)
# CACHE_TIME_PERIODS_IN_DAYS = [1, 3, 7, 14, 30, 60, 100000]
# ITEM_ID_CACHE_PREFIX = 'fid:'
# class Feed(ndb.Model):
# class FeedItemId(object):
# class FeedItem(ndb.Model):
# def GetUrl(self):
# def Update(self, canonicalize=None):
# def UpdateAsync(self, canonicalize=None, enable_async=True):
# def _TimeToMillis(t):
# def _MillisToDatetime(ms):
# def __init__(self, feed_url, item_id, published_date):
# def GetBulkItemIdsAsync(feed_urls, since_time):
# def _UpdateCachedItemIds(feed_url, time_period_in_days):
# def GetFeed(url):
# def AddFeed(url, title):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/json_encoder.py
# class Serializable(object):
# class JSONEncoder(json.JSONEncoder):
# def to_dict(self):
# def TimeToMillis(t):
# def default(self, o):
#
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
#
# Path: recommender/time_periods.py
# LAST_VISIT_RESTRICTED = 'LAST_VISIT_RESTRICTED'
# LAST_VISIT = 'LAST_VISIT'
# RECENT = 'RECENT'
# HOUR = 'HOUR'
# DAY = 'DAY'
# WEEK = 'WEEK'
# MONTH = 'MONTH'
# YEAR = 'YEAR'
# ALL = 'ALL'
# ALL_NUMERIC = 0
# YEAR_NUMERIC = 1
# MONTH_NUMERIC = 2
# WEEK_NUMERIC = 3
# DAY_NUMERIC = 4
# HOUR_NUMERIC = 5
# RECENT_NUMERIC = 6
# LAST_VISIT_NUMERIC = 7
# LAST_VISIT_RESTRICTED_NUMERIC = 8
# TIME_PERIODS = [
# {
# 'timedelta': timedelta.max,
# 'name': ALL,
# 'numeric': ALL_NUMERIC
# },
# {
# 'timedelta': timedelta(days=365),
# 'name': YEAR,
# 'numeric': YEAR_NUMERIC
# },
# {
# 'timedelta': timedelta(days=31),
# 'name': MONTH,
# 'numeric': MONTH_NUMERIC
# },
# {
# 'timedelta': timedelta(weeks=1),
# 'name': WEEK,
# 'numeric': WEEK_NUMERIC
# },
# {
# 'timedelta': timedelta(days=1),
# 'name': DAY,
# 'numeric': DAY_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=1),
# 'name': HOUR,
# 'numeric': HOUR_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': RECENT,
# 'numeric': RECENT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT,
# 'numeric': LAST_VISIT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT_RESTRICTED,
# 'numeric': LAST_VISIT_RESTRICTED_NUMERIC
# },
# ]
# def Get(name):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | FeedRatingToUnified(item) for item in feeds.FeedItem.query( |
Given the following code snippet before the placeholder: <|code_start|>
def AddRatingAtTime(user,
url,
rating,
source,
category_id,
time):
# Get existing ratings before we the new rating is added so we can tell who
# this user will be connecting to.
stats = GetRatingStats(url)
# Make sure there is a User placeholder for each user with rating so
# we can run analysis by user.
MaybeAddUser(user)
user_key = UserKey(user)
category = None
# Clamp the rating to [-1, 1] range.
rating = min(rating, 1)
rating = max(rating, -1)
if category_id is not None:
category = CategoryKey(category_id, user)
user_id = user_key.id()
PageRating(
key=ndb.Key(PageRating, url, parent=user_key),
user_id=user_id,
url=url,
rating=rating,
category=category,
source=source,
date=time,
<|code_end|>
, predict the next line using imports from the current file:
from datetime import datetime
from datetime import timedelta
from urlparse import urlparse
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from recommender import feeds
from recommender import items
from recommender import json_encoder
from recommender import ratings
from recommender import time_periods
from recommender import url_util
import functools
import logging
import math
import pickle
and context including class names, function names, and sometimes code from other files:
# Path: recommender/feeds.py
# MAX_ITEMS_PER_FEED = 0
# CLEAN_UP_ITEMS_PER_UPDATE = 1000
# TIME_BETWEEN_UPDATES = timedelta(minutes=30)
# CACHE_TIME_PERIODS_IN_DAYS = [1, 3, 7, 14, 30, 60, 100000]
# ITEM_ID_CACHE_PREFIX = 'fid:'
# class Feed(ndb.Model):
# class FeedItemId(object):
# class FeedItem(ndb.Model):
# def GetUrl(self):
# def Update(self, canonicalize=None):
# def UpdateAsync(self, canonicalize=None, enable_async=True):
# def _TimeToMillis(t):
# def _MillisToDatetime(ms):
# def __init__(self, feed_url, item_id, published_date):
# def GetBulkItemIdsAsync(feed_urls, since_time):
# def _UpdateCachedItemIds(feed_url, time_period_in_days):
# def GetFeed(url):
# def AddFeed(url, title):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/json_encoder.py
# class Serializable(object):
# class JSONEncoder(json.JSONEncoder):
# def to_dict(self):
# def TimeToMillis(t):
# def default(self, o):
#
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
#
# Path: recommender/time_periods.py
# LAST_VISIT_RESTRICTED = 'LAST_VISIT_RESTRICTED'
# LAST_VISIT = 'LAST_VISIT'
# RECENT = 'RECENT'
# HOUR = 'HOUR'
# DAY = 'DAY'
# WEEK = 'WEEK'
# MONTH = 'MONTH'
# YEAR = 'YEAR'
# ALL = 'ALL'
# ALL_NUMERIC = 0
# YEAR_NUMERIC = 1
# MONTH_NUMERIC = 2
# WEEK_NUMERIC = 3
# DAY_NUMERIC = 4
# HOUR_NUMERIC = 5
# RECENT_NUMERIC = 6
# LAST_VISIT_NUMERIC = 7
# LAST_VISIT_RESTRICTED_NUMERIC = 8
# TIME_PERIODS = [
# {
# 'timedelta': timedelta.max,
# 'name': ALL,
# 'numeric': ALL_NUMERIC
# },
# {
# 'timedelta': timedelta(days=365),
# 'name': YEAR,
# 'numeric': YEAR_NUMERIC
# },
# {
# 'timedelta': timedelta(days=31),
# 'name': MONTH,
# 'numeric': MONTH_NUMERIC
# },
# {
# 'timedelta': timedelta(weeks=1),
# 'name': WEEK,
# 'numeric': WEEK_NUMERIC
# },
# {
# 'timedelta': timedelta(days=1),
# 'name': DAY,
# 'numeric': DAY_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=1),
# 'name': HOUR,
# 'numeric': HOUR_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': RECENT,
# 'numeric': RECENT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT,
# 'numeric': LAST_VISIT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT_RESTRICTED,
# 'numeric': LAST_VISIT_RESTRICTED_NUMERIC
# },
# ]
# def Get(name):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | item_id=items.UrlToItemId(url)).put() |
Continue the code snippet: <|code_start|> if hasattr(self, 'category'):
result['category'] = self.category.to_dict()
return result
# Returns the list of urls this object is interested in for conversion to
# json.
def GetPageUrls(self):
return {self.url}
# Saves a url->page info map to be used later in to_dict.
def SavePageInfos(self, page_infos):
self.page_infos = page_infos
# The page that you have in common with others that led to a recommendation.
class RecommendationSourcePage(object):
_EXPORTED_FIELDS = {'url', 'user_count'}
def __init__(self, url):
self.url = url
self.weight = 0
self.user_count = 0
def to_dict(self):
return dict((k, v)
for k, v in self.__dict__.iteritems()
if k in RecommendationSourcePage._EXPORTED_FIELDS)
# User-item recommendation.
<|code_end|>
. Use current file imports:
from datetime import datetime
from datetime import timedelta
from urlparse import urlparse
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from recommender import feeds
from recommender import items
from recommender import json_encoder
from recommender import ratings
from recommender import time_periods
from recommender import url_util
import functools
import logging
import math
import pickle
and context (classes, functions, or code) from other files:
# Path: recommender/feeds.py
# MAX_ITEMS_PER_FEED = 0
# CLEAN_UP_ITEMS_PER_UPDATE = 1000
# TIME_BETWEEN_UPDATES = timedelta(minutes=30)
# CACHE_TIME_PERIODS_IN_DAYS = [1, 3, 7, 14, 30, 60, 100000]
# ITEM_ID_CACHE_PREFIX = 'fid:'
# class Feed(ndb.Model):
# class FeedItemId(object):
# class FeedItem(ndb.Model):
# def GetUrl(self):
# def Update(self, canonicalize=None):
# def UpdateAsync(self, canonicalize=None, enable_async=True):
# def _TimeToMillis(t):
# def _MillisToDatetime(ms):
# def __init__(self, feed_url, item_id, published_date):
# def GetBulkItemIdsAsync(feed_urls, since_time):
# def _UpdateCachedItemIds(feed_url, time_period_in_days):
# def GetFeed(url):
# def AddFeed(url, title):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/json_encoder.py
# class Serializable(object):
# class JSONEncoder(json.JSONEncoder):
# def to_dict(self):
# def TimeToMillis(t):
# def default(self, o):
#
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
#
# Path: recommender/time_periods.py
# LAST_VISIT_RESTRICTED = 'LAST_VISIT_RESTRICTED'
# LAST_VISIT = 'LAST_VISIT'
# RECENT = 'RECENT'
# HOUR = 'HOUR'
# DAY = 'DAY'
# WEEK = 'WEEK'
# MONTH = 'MONTH'
# YEAR = 'YEAR'
# ALL = 'ALL'
# ALL_NUMERIC = 0
# YEAR_NUMERIC = 1
# MONTH_NUMERIC = 2
# WEEK_NUMERIC = 3
# DAY_NUMERIC = 4
# HOUR_NUMERIC = 5
# RECENT_NUMERIC = 6
# LAST_VISIT_NUMERIC = 7
# LAST_VISIT_RESTRICTED_NUMERIC = 8
# TIME_PERIODS = [
# {
# 'timedelta': timedelta.max,
# 'name': ALL,
# 'numeric': ALL_NUMERIC
# },
# {
# 'timedelta': timedelta(days=365),
# 'name': YEAR,
# 'numeric': YEAR_NUMERIC
# },
# {
# 'timedelta': timedelta(days=31),
# 'name': MONTH,
# 'numeric': MONTH_NUMERIC
# },
# {
# 'timedelta': timedelta(weeks=1),
# 'name': WEEK,
# 'numeric': WEEK_NUMERIC
# },
# {
# 'timedelta': timedelta(days=1),
# 'name': DAY,
# 'numeric': DAY_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=1),
# 'name': HOUR,
# 'numeric': HOUR_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': RECENT,
# 'numeric': RECENT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT,
# 'numeric': LAST_VISIT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT_RESTRICTED,
# 'numeric': LAST_VISIT_RESTRICTED_NUMERIC
# },
# ]
# def Get(name):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | class Recommendation(json_encoder.Serializable): |
Given the code snippet: <|code_start|> if publisher_category_id:
publisher_category_id = long(publisher_category_id)
if subscriber_category_id:
subscriber_category_id = long(subscriber_category_id)
if positive:
parts = (str(publisher_id), publisher_category_id, str(subscriber_id),
subscriber_category_id, str(version))
else:
parts = (str(publisher_id), publisher_category_id, str(subscriber_id),
subscriber_category_id, str(version), False)
return ndb.Key(Connection, pickle.dumps(parts))
def UserRatingToUnified(rating):
return {
'type': SOURCE_TYPE_USER,
'publisher_id': rating.key.parent().id(),
'publisher_category_id': GetCategoryId(rating.category),
'date': rating.date,
'rating': rating.rating,
'url': rating.url,
}
def FeedRatingToUnified(item):
return {
'type': SOURCE_TYPE_FEED,
'publisher_id': item.feed_url,
'publisher_category_id': None,
'date': item.published_date,
<|code_end|>
, generate the next line using the imports in this file:
from datetime import datetime
from datetime import timedelta
from urlparse import urlparse
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from recommender import feeds
from recommender import items
from recommender import json_encoder
from recommender import ratings
from recommender import time_periods
from recommender import url_util
import functools
import logging
import math
import pickle
and context (functions, classes, or occasionally code) from other files:
# Path: recommender/feeds.py
# MAX_ITEMS_PER_FEED = 0
# CLEAN_UP_ITEMS_PER_UPDATE = 1000
# TIME_BETWEEN_UPDATES = timedelta(minutes=30)
# CACHE_TIME_PERIODS_IN_DAYS = [1, 3, 7, 14, 30, 60, 100000]
# ITEM_ID_CACHE_PREFIX = 'fid:'
# class Feed(ndb.Model):
# class FeedItemId(object):
# class FeedItem(ndb.Model):
# def GetUrl(self):
# def Update(self, canonicalize=None):
# def UpdateAsync(self, canonicalize=None, enable_async=True):
# def _TimeToMillis(t):
# def _MillisToDatetime(ms):
# def __init__(self, feed_url, item_id, published_date):
# def GetBulkItemIdsAsync(feed_urls, since_time):
# def _UpdateCachedItemIds(feed_url, time_period_in_days):
# def GetFeed(url):
# def AddFeed(url, title):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/json_encoder.py
# class Serializable(object):
# class JSONEncoder(json.JSONEncoder):
# def to_dict(self):
# def TimeToMillis(t):
# def default(self, o):
#
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
#
# Path: recommender/time_periods.py
# LAST_VISIT_RESTRICTED = 'LAST_VISIT_RESTRICTED'
# LAST_VISIT = 'LAST_VISIT'
# RECENT = 'RECENT'
# HOUR = 'HOUR'
# DAY = 'DAY'
# WEEK = 'WEEK'
# MONTH = 'MONTH'
# YEAR = 'YEAR'
# ALL = 'ALL'
# ALL_NUMERIC = 0
# YEAR_NUMERIC = 1
# MONTH_NUMERIC = 2
# WEEK_NUMERIC = 3
# DAY_NUMERIC = 4
# HOUR_NUMERIC = 5
# RECENT_NUMERIC = 6
# LAST_VISIT_NUMERIC = 7
# LAST_VISIT_RESTRICTED_NUMERIC = 8
# TIME_PERIODS = [
# {
# 'timedelta': timedelta.max,
# 'name': ALL,
# 'numeric': ALL_NUMERIC
# },
# {
# 'timedelta': timedelta(days=365),
# 'name': YEAR,
# 'numeric': YEAR_NUMERIC
# },
# {
# 'timedelta': timedelta(days=31),
# 'name': MONTH,
# 'numeric': MONTH_NUMERIC
# },
# {
# 'timedelta': timedelta(weeks=1),
# 'name': WEEK,
# 'numeric': WEEK_NUMERIC
# },
# {
# 'timedelta': timedelta(days=1),
# 'name': DAY,
# 'numeric': DAY_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=1),
# 'name': HOUR,
# 'numeric': HOUR_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': RECENT,
# 'numeric': RECENT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT,
# 'numeric': LAST_VISIT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT_RESTRICTED,
# 'numeric': LAST_VISIT_RESTRICTED_NUMERIC
# },
# ]
# def Get(name):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | 'rating': ratings.POSITIVE, |
Based on the snippet: <|code_start|> date = ndb.DateTimeProperty()
time_period_numeric = ndb.IntegerProperty()
serialized_recommendation = ndb.BlobProperty()
# When False then this past recommendation is not counted as an old
# recommendation.
committed = ndb.BooleanProperty()
# Increasing number, one for each batch of recommendations committed at
# the same time.
session_number = ndb.IntegerProperty()
index_within_page = ndb.IntegerProperty()
# Summary of a session, where a session is a list of PastRecommendations that
# have the same session_number.
# The summary is used to determine how much new recommendations to load
# initially for a new session.
class RecommendationSession(ndb.Model):
user_id = ndb.StringProperty()
time_period_numeric = ndb.IntegerProperty()
# When the session was committed.
date = ndb.DateTimeProperty(auto_now_add=True)
median_weight = ndb.FloatProperty()
min_weight = ndb.FloatProperty()
max_weight = ndb.FloatProperty()
recommendation_count = ndb.IntegerProperty()
# Is called when the user rates the url.
def DeletePastRecommendation(user_id, url):
user_key = UserKey(user_id)
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from datetime import timedelta
from urlparse import urlparse
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from recommender import feeds
from recommender import items
from recommender import json_encoder
from recommender import ratings
from recommender import time_periods
from recommender import url_util
import functools
import logging
import math
import pickle
and context (classes, functions, sometimes code) from other files:
# Path: recommender/feeds.py
# MAX_ITEMS_PER_FEED = 0
# CLEAN_UP_ITEMS_PER_UPDATE = 1000
# TIME_BETWEEN_UPDATES = timedelta(minutes=30)
# CACHE_TIME_PERIODS_IN_DAYS = [1, 3, 7, 14, 30, 60, 100000]
# ITEM_ID_CACHE_PREFIX = 'fid:'
# class Feed(ndb.Model):
# class FeedItemId(object):
# class FeedItem(ndb.Model):
# def GetUrl(self):
# def Update(self, canonicalize=None):
# def UpdateAsync(self, canonicalize=None, enable_async=True):
# def _TimeToMillis(t):
# def _MillisToDatetime(ms):
# def __init__(self, feed_url, item_id, published_date):
# def GetBulkItemIdsAsync(feed_urls, since_time):
# def _UpdateCachedItemIds(feed_url, time_period_in_days):
# def GetFeed(url):
# def AddFeed(url, title):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/json_encoder.py
# class Serializable(object):
# class JSONEncoder(json.JSONEncoder):
# def to_dict(self):
# def TimeToMillis(t):
# def default(self, o):
#
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
#
# Path: recommender/time_periods.py
# LAST_VISIT_RESTRICTED = 'LAST_VISIT_RESTRICTED'
# LAST_VISIT = 'LAST_VISIT'
# RECENT = 'RECENT'
# HOUR = 'HOUR'
# DAY = 'DAY'
# WEEK = 'WEEK'
# MONTH = 'MONTH'
# YEAR = 'YEAR'
# ALL = 'ALL'
# ALL_NUMERIC = 0
# YEAR_NUMERIC = 1
# MONTH_NUMERIC = 2
# WEEK_NUMERIC = 3
# DAY_NUMERIC = 4
# HOUR_NUMERIC = 5
# RECENT_NUMERIC = 6
# LAST_VISIT_NUMERIC = 7
# LAST_VISIT_RESTRICTED_NUMERIC = 8
# TIME_PERIODS = [
# {
# 'timedelta': timedelta.max,
# 'name': ALL,
# 'numeric': ALL_NUMERIC
# },
# {
# 'timedelta': timedelta(days=365),
# 'name': YEAR,
# 'numeric': YEAR_NUMERIC
# },
# {
# 'timedelta': timedelta(days=31),
# 'name': MONTH,
# 'numeric': MONTH_NUMERIC
# },
# {
# 'timedelta': timedelta(weeks=1),
# 'name': WEEK,
# 'numeric': WEEK_NUMERIC
# },
# {
# 'timedelta': timedelta(days=1),
# 'name': DAY,
# 'numeric': DAY_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=1),
# 'name': HOUR,
# 'numeric': HOUR_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': RECENT,
# 'numeric': RECENT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT,
# 'numeric': LAST_VISIT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT_RESTRICTED,
# 'numeric': LAST_VISIT_RESTRICTED_NUMERIC
# },
# ]
# def Get(name):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | for time_period in time_periods.TIME_PERIODS: |
Continue the code snippet: <|code_start|> canonical_url_tasks = [
GetPageInfoAsync(page_info.canonical_url)
for page_info in page_infos
if page_info.url != page_info.canonical_url
]
for task in canonical_url_tasks:
task.get_result()
def _MetadataToPageInfo(m, key, url):
return PageInfo(
key=key,
url=url,
title=m.title,
canonical_url=m.canonical_url,
description=m.description,
feed_url=m.feed_url,
feed_title=m.feed_title,
is_feed=m.is_feed,
estimated_reading_time=m.estimated_reading_time)
@ndb.tasklet
def GetPageInfoAsync(
url,
log_not_found=False,
do_not_fetch=False,
raise_invalid_url=False,
raise_error=False,
get_from_datastore=True):
<|code_end|>
. Use current file imports:
from datetime import datetime
from datetime import timedelta
from urlparse import urlparse
from google.appengine.api import memcache
from google.appengine.ext import deferred
from google.appengine.ext import ndb
from recommender import feeds
from recommender import items
from recommender import json_encoder
from recommender import ratings
from recommender import time_periods
from recommender import url_util
import functools
import logging
import math
import pickle
and context (classes, functions, or code) from other files:
# Path: recommender/feeds.py
# MAX_ITEMS_PER_FEED = 0
# CLEAN_UP_ITEMS_PER_UPDATE = 1000
# TIME_BETWEEN_UPDATES = timedelta(minutes=30)
# CACHE_TIME_PERIODS_IN_DAYS = [1, 3, 7, 14, 30, 60, 100000]
# ITEM_ID_CACHE_PREFIX = 'fid:'
# class Feed(ndb.Model):
# class FeedItemId(object):
# class FeedItem(ndb.Model):
# def GetUrl(self):
# def Update(self, canonicalize=None):
# def UpdateAsync(self, canonicalize=None, enable_async=True):
# def _TimeToMillis(t):
# def _MillisToDatetime(ms):
# def __init__(self, feed_url, item_id, published_date):
# def GetBulkItemIdsAsync(feed_urls, since_time):
# def _UpdateCachedItemIds(feed_url, time_period_in_days):
# def GetFeed(url):
# def AddFeed(url, title):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/json_encoder.py
# class Serializable(object):
# class JSONEncoder(json.JSONEncoder):
# def to_dict(self):
# def TimeToMillis(t):
# def default(self, o):
#
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
#
# Path: recommender/time_periods.py
# LAST_VISIT_RESTRICTED = 'LAST_VISIT_RESTRICTED'
# LAST_VISIT = 'LAST_VISIT'
# RECENT = 'RECENT'
# HOUR = 'HOUR'
# DAY = 'DAY'
# WEEK = 'WEEK'
# MONTH = 'MONTH'
# YEAR = 'YEAR'
# ALL = 'ALL'
# ALL_NUMERIC = 0
# YEAR_NUMERIC = 1
# MONTH_NUMERIC = 2
# WEEK_NUMERIC = 3
# DAY_NUMERIC = 4
# HOUR_NUMERIC = 5
# RECENT_NUMERIC = 6
# LAST_VISIT_NUMERIC = 7
# LAST_VISIT_RESTRICTED_NUMERIC = 8
# TIME_PERIODS = [
# {
# 'timedelta': timedelta.max,
# 'name': ALL,
# 'numeric': ALL_NUMERIC
# },
# {
# 'timedelta': timedelta(days=365),
# 'name': YEAR,
# 'numeric': YEAR_NUMERIC
# },
# {
# 'timedelta': timedelta(days=31),
# 'name': MONTH,
# 'numeric': MONTH_NUMERIC
# },
# {
# 'timedelta': timedelta(weeks=1),
# 'name': WEEK,
# 'numeric': WEEK_NUMERIC
# },
# {
# 'timedelta': timedelta(days=1),
# 'name': DAY,
# 'numeric': DAY_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=1),
# 'name': HOUR,
# 'numeric': HOUR_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': RECENT,
# 'numeric': RECENT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT,
# 'numeric': LAST_VISIT_NUMERIC
# },
# {
# 'timedelta': timedelta(hours=0),
# 'name': LAST_VISIT_RESTRICTED,
# 'numeric': LAST_VISIT_RESTRICTED_NUMERIC
# },
# ]
# def Get(name):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | url = url_util.Normalize(url) |
Using the snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class UrlUtilTest(unittest.TestCase):
def testDeduplicate(self):
self.assertEqual(['https://a.test'],
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from recommender import url_util
and context (class names, function names, or code) available:
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | url_util.DeduplicateUrls( |
Next line prediction: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class ItemsTest(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_datastore_v3_stub()
self.testbed.init_memcache_stub()
def tearDown(self):
self.testbed.deactivate()
def testSerialization(self):
self.assertEqual([1, 2, 3],
<|code_end|>
. Use current file imports:
(import unittest
from recommender import items
from google.appengine.ext import testbed)
and context including class names, function names, or small code snippets from other files:
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
. Output only the next line. | items.ItemIdsFromBytes(items.ItemIdsToBytes([1, 2, 3]))) |
Predict the next line after this snippet: <|code_start|> else:
stream = io.BytesIO(content)
parsed = feedparser.parse(stream)
else:
try:
parsed = feedparser.parse(url, etag=etag, modified=modified_tuple)
except StandardError as e:
logging.warning('Failed to parse feed: %s error: %s', url, e)
# Try to read content ourselves and pass it to the parser:
try:
content, _, _, _ = url_util.GetPageContent(url)
parsed = feedparser.parse(content)
except url_util.Error as e:
logging.warning('Failed to parse feed %s with fallback error: %s',
url, e)
raise ndb.Return([])
if hasattr(parsed, 'modified_parsed') and parsed.modified_parsed:
self.modified = datetime.fromtimestamp(
time.mktime(parsed.modified_parsed))
if hasattr(parsed, 'etag'):
self.etag = parsed.etag
new_items = []
for entry in parsed.entries:
if not hasattr(entry, 'link') or not entry.link:
continue
if hasattr(entry, 'id') and entry.id:
entry_id = entry.id
else:
# Some feeds don't specify the id so we use the link as the id.
entry_id = entry.link
<|code_end|>
using the current file's imports:
from datetime import datetime
from datetime import timedelta
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.ext import db
from google.appengine.ext import ndb
from recommender import feed_util
from recommender import items
from recommender import url_util
from protos import cache_pb2
import io
import logging
import time
import feedparser
and any relevant context from other files:
# Path: recommender/feed_util.py
# def GetEntryDate(entry, min_date=None, max_date=None):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | entry_date = feed_util.GetEntryDate( |
Based on the snippet: <|code_start|> if hasattr(parsed, 'etag'):
self.etag = parsed.etag
new_items = []
for entry in parsed.entries:
if not hasattr(entry, 'link') or not entry.link:
continue
if hasattr(entry, 'id') and entry.id:
entry_id = entry.id
else:
# Some feeds don't specify the id so we use the link as the id.
entry_id = entry.link
entry_date = feed_util.GetEntryDate(
entry, min_date=self.last_updated, max_date=now)
if not entry_date:
entry_date = datetime.now()
title = None
if hasattr(entry, 'title'):
title = entry.title
item = FeedItem.query(FeedItem.feed_url == self.GetUrl(),
FeedItem.id == entry_id).get()
if item is None:
try:
canonical_url = canonicalize(entry.link)
new_item = FeedItem(
id=entry_id,
url=canonical_url,
title=title,
feed_url=self.GetUrl(),
retrieved_date=now,
published_date=entry_date,
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from datetime import timedelta
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.ext import db
from google.appengine.ext import ndb
from recommender import feed_util
from recommender import items
from recommender import url_util
from protos import cache_pb2
import io
import logging
import time
import feedparser
and context (classes, functions, sometimes code) from other files:
# Path: recommender/feed_util.py
# def GetEntryDate(entry, min_date=None, max_date=None):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | item_id=items.UrlToItemId(canonical_url)) |
Using the snippet: <|code_start|> etag = ndb.StringProperty()
last_updated = ndb.DateTimeProperty()
def GetUrl(self):
return self.key.id()
def Update(self, canonicalize=None):
return self.UpdateAsync(
canonicalize=canonicalize, enable_async=False).get_result()
# Updates the list of items in the feed.
# Returns the list of newly added items.
@ndb.tasklet
def UpdateAsync(self, canonicalize=None, enable_async=True):
now = datetime.now()
if canonicalize is None:
canonicalize = lambda url: url
modified_tuple = None
etag = self.etag
if self.modified is not None:
modified_tuple = self.modified.timetuple()
# Don't use etag if we have modified time. Some servers are generating new
# etags when nothing actually changes and modified date stays the same.
etag = None
url = self.GetUrl()
if enable_async:
if url.startswith('feed:http'):
url = url[5:]
elif url.startswith('feed:'):
url = 'http:' + url[5:]
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime
from datetime import timedelta
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.ext import db
from google.appengine.ext import ndb
from recommender import feed_util
from recommender import items
from recommender import url_util
from protos import cache_pb2
import io
import logging
import time
import feedparser
and context (class names, function names, or code) available:
# Path: recommender/feed_util.py
# def GetEntryDate(entry, min_date=None, max_date=None):
#
# Path: recommender/items.py
# class Item(ndb.Model):
# def ItemId(self):
# def UrlToItemId(url):
# def UrlsToItemIds(urls):
# def ItemIdsToUrls(item_ids):
# def ItemIdToUrl(item_id):
# def ItemIdsToBytes(item_ids):
# def ItemIdsFromBytes(string):
#
# Path: recommender/url_util.py
# class PageMetadata(object):
# class Error(Exception):
# class InvalidURLError(Error):
# def DeduplicateUrls(urls):
# def Normalize(url):
# def RemoveUtmParameters(url):
# def Resolve(base_url, url):
# def _GetContentTypeAndCharset(headers):
# def GetPageContent(url):
# def GetPageMetadata(url):
# def FindContent(tree, paths, filter_fn=None):
# def FindFeedUrl(url, tree, path, result):
# URL_FETCH_DEADLINE_SECONDS = 15
# FEED_CONTENT_TYPES = set([
# 'application/atom+xml', 'application/rdf+xml', 'application/rss+xml',
# 'application/x-netcdf', 'application/xml', 'text/xml'
# ])
. Output only the next line. | rpc = urlfetch.create_rpc(deadline=url_util.URL_FETCH_DEADLINE_SECONDS) |
Using the snippet: <|code_start|> FindContent(tree, [{
'path': './/head/link[@rel="canonical"]',
'attribute': 'href'
}, {
'path': './/head/meta[@property="og:url"]',
'attribute': 'content'
}]))
if not result.canonical_url:
result.canonical_url = final_url
result.description = FindContent(tree, [{
'path': './/head/meta[@property="og:description"]',
'attribute': 'content'
}, {
'path': './/head/meta[@name="description"]',
'attribute': 'content'
}, {
'path': './/head/meta[@name="twitter:description"]',
'attribute': 'content'
}])
result.feed_url = None
result.feed_title = None
if not FindFeedUrl(url, tree, './/head/link[@type="application/rss+xml"]',
result):
FindFeedUrl(url, tree, './/head/link[@type="application/atom+xml"]', result)
result.is_feed = False
try:
<|code_end|>
, determine the next line of code. You have imports:
import cgi
import logging
import feedparser
import lxml.etree
import lxml.html
import lxml.html.soupparser
import urlparse
from recommender import reading_time_estimator
from google.appengine.api import urlfetch
and context (class names, function names, or code) available:
# Path: recommender/reading_time_estimator.py
# CHARACTERS_PER_MINUTE = 860
# def Estimate(tree):
# def _IsVisible(element):
# def _CountCharacters(texts):
# def EstimateUrl(url):
. Output only the next line. | result.estimated_reading_time = reading_time_estimator.Estimate(tree) |
Given the following code snippet before the placeholder: <|code_start|> feed. This allows us to avoid doing updates for every single new item.
Args:
publisher: The publisher that recommended the items.
num_items: The number of items the publisher recommended.
"""
for connection in self.connection_store.GetSubscribers(
publisher, positive=POSITIVE):
# We do not decay negative weights because getting out of the negative
# zone should be earned by posting useful content, not just a ton of
# content that the user ignores.
if connection.weight <= 0:
continue
# This could be calculated using the expected prediction.
# w = w - a * (hypothesis(subscriber, item) - 0.5) * rating
# But we simplify.
weight = self.GetDecayedWeight(connection.weight, num_items)
self.connection_store.SetWeight(
connection.user, publisher, POSITIVE, weight, publisher_voted=True)
def RecommendationAdded(self, user, item, rating):
"""Updates connection weights between users.
Args:
user: Who recommended.
item: What was recommended.
rating: {1, 0, -1} - positive, neutral or negative - the rating the user
gave to the item.
"""
<|code_end|>
, predict the next line using imports from the current file:
from abc import ABCMeta
from abc import abstractmethod
from recommender import ratings
import math
and context including class names, function names, and sometimes code from other files:
# Path: recommender/ratings.py
# POSITIVE = 1
# NEGATIVE = -1
# NEUTRAL = 0
# def NumberToRating(value):
. Output only the next line. | if rating == ratings.NEUTRAL: |
Using the snippet: <|code_start|># Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class Recommendation(object):
def __init__(self, user, rating):
self.user = user
self.rating = rating
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from recommender import connection_trainer
and context (class names, function names, or code) available:
# Path: recommender/connection_trainer.py
# NEUTRAL_PREDICTION = 0.5
# POSITIVE = True
# NEGATIVE = False
# def Sigmoid(z):
# def __init__(self, rating, user, weight, num_ratings_ago):
# def __init__(self, user, weight):
# def GetRecommendations(self, item, user, user_rating):
# def GetWeight(self, subscriber, publisher, positive):
# def SetWeight(self,
# subscriber,
# publisher,
# positive,
# weight,
# shared_item=None,
# publisher_voted=False,
# reverted=False):
# def GetSubscribers(self, publisher, positive=True):
# def CanSubscribe(self, user):
# def __init__(self,
# connection_store,
# learning_rate,
# ignore_learning_rate,
# default_contribution=0.1):
# def GetDecayedWeight(self, initial_weight, num_items):
# def DecayConnectionWeightToPublisher(self, publisher, num_items=1):
# def RecommendationAdded(self, user, item, rating):
# class Rating(object):
# class Connection(object):
# class ConnectionStore(object):
# class Trainer(object):
. Output only the next line. | class InMemoryStore(connection_trainer.ConnectionStore): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.