<commit_before>from sqlalchemy import (
    Column,
    Integer,
    Text,
    String,
    Boolean,
    Table,
    ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
from slugify import slugify
from .auth import pwd_context

SASession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))


class Model(object):
    def save(self):
        SASession.add(self)

    @classmethod
    def query(cls, **kwargs):
        return SASession.query(cls, **kwargs)

    def delete(self):
        SASession.delete(self)

    @classmethod
    def create_from_dict(cls, data):
        record = cls.__call__()
        record.update_from_dict(data)
        return record

    def to_dict(self):
        return dict([(c.name, getattr(self, c.name)) for c in
                     self.__mapper__.columns])

    def update_from_dict(self, data):
        [setattr(self, key, data.get(key)) for key in data]

    def show_url(self, request):
        return request.route_url(
            'site', traverse=(self.__tablename__, self.id))

    def update_url(self, request):
        return request.route_url(
            'site', traverse=(self.__tablename__, self.id, 'edit'))

    def delete_url(self, request):
        return request.route_url(
            'site', traverse=(self.__tablename__, self.id, 'delete'))


Base = declarative_base(cls=Model)

user_group = Table(
    'user_groups', Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id')),
    Column('group_id', Integer, ForeignKey('groups.id')),
)


def generate_slug(column, value, unique_query):
    i = 0
    base_slug = slugify(value)
    slug = base_slug
    while unique_query.filter(column == slug).count() > 0:
        i += 1
        slug = "{0}-{1}".format(base_slug, i)
    return slug


def set_slug(mapper, connection, target):
    target_column = mapper.class_.slug_target_column()
    source_column = mapper.class_.slug_source_column()
    slug = generate_slug(
        target_column, target.__getattribute__(
            source_column.name), target.slug_unique_query())
    target.__setattr__(target_column.name, slug)


class Slugable(object):
    def slug_unique_query(self):
        raise NotImplementedError

    @classmethod
    def slug_target_column(cls):
        return cls.slug

    @classmethod
    def slug_source_column(cls):
        return cls.name


def group_finder(user_id, request):
    try:
        # todo: join with groups
        user = BaseUser.query().filter(BaseUser.id == user_id).one()
    except NoResultFound:
        return None
    else:
        groups = ['g:{0}'.format(g.name) for g in user.groups]
        groups.append('u:{0}'.format(user_id))
        return groups


class BaseUser(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    account_id = Column(String(100), unique=True, nullable=False)
    password = Column(String(255), nullable=False)
    is_active = Column(Boolean(), nullable=False, default=False)
    groups = relationship('Group', secondary=user_group, backref='users')

    def check_password(self):
        raise NotImplementedError()

    def update_url(self, request):
        return request.route_url('site', traverse=('users', self.id, 'edit'))

    def delete_url(self, request):
        return request.route_url('site', traverse=('users', self.id, 'delete'))

    def to_dict(self):
        data = super(BaseUser, self).to_dict()
        # password can only be set, not edited
        data['password'] = None
        data['group_names'] = self.group_names
        return data

    def update_from_dict(self, data):
        # if password is blank, remove its key from data
        has_password = 'password' in data
        if has_password and not data['password']:
            del data['password']
        elif has_password:<commit_msg>fixed Groups relationship to refer to group table as BaseGroup<commit_after>from sqlalchemy import (
    Column,
    Integer,
    Text,
    String,
    Boolean,
    Table,
    ForeignKey,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship,
)
from zope.sqlalchemy import ZopeTransactionExtension
from slugify import slugify
from .auth import pwd_context

SASession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))


class Model(object):
    def save(self):
        SASession.add(self)

    @classmethod
    def query(cls, **kwargs):
        return SASession.query(cls, **kwargs)

    def delete(self):
        SASession.delete(self)

    @classmethod
    def create_from_dict(cls, data):
        record = cls.__call__()
        record.update_from_dict(data)
        return record

    def to_dict(self):
        return dict([(c.name, getattr(self, c.name)) for c in
                     self.__mapper__.columns])

    def update_from_dict(self, data):
        [setattr(self, key, data.get(key)) for key in data]

    def show_url(self, request):
        return request.route_url(
            'site', traverse=(self.__tablename__, self.id))

    def update_url(self, request):
        return request.route_url(
            'site', traverse=(self.__tablename__, self.id, 'edit'))

    def delete_url(self, request):
        return request.route_url(
            'site', traverse=(self.__tablename__, self.id, 'delete'))


Base = declarative_base(cls=Model)

user_group = Table(
    'user_groups', Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id')),
    Column('group_id', Integer, ForeignKey('groups.id')),
)


def generate_slug(column, value, unique_query):
    i = 0
    base_slug = slugify(value)
    slug = base_slug
    while unique_query.filter(column == slug).count() > 0:
        i += 1
        slug = "{0}-{1}".format(base_slug, i)
    return slug


def set_slug(mapper, connection, target):
    target_column = mapper.class_.slug_target_column()
    source_column = mapper.class_.slug_source_column()
    slug = generate_slug(
        target_column, target.__getattribute__(
            source_column.name), target.slug_unique_query())
    target.__setattr__(target_column.name, slug)


class Slugable(object):
    def slug_unique_query(self):
        raise NotImplementedError

    @classmethod
    def slug_target_column(cls):
        return cls.slug

    @classmethod
    def slug_source_column(cls):
        return cls.name


def group_finder(user_id, request):
    try:
        # todo: join with groups
        user = BaseUser.query().filter(BaseUser.id == user_id).one()
    except NoResultFound:
        return None
    else:
        groups = ['g:{0}'.format(g.name) for g in user.groups]
        groups.append('u:{0}'.format(user_id))
        return groups


class BaseUser(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    account_id = Column(String(100), unique=True, nullable=False)
    password = Column(String(255), nullable=False)
    is_active = Column(Boolean(), nullable=False, default=False)
    groups = relationship('BaseGroup', secondary=user_group, backref='users')

    def check_password(self):
        raise NotImplementedError()

    def update_url(self, request):
        return request.route_url('site', traverse=('users', self.id, 'edit'))

    def delete_url(self, request):
        return request.route_url('site', traverse=('users', self.id, 'delete'))

    def to_dict(self):
        data = super(BaseUser, self).to_dict()
        # password can only be set, not edited
        data['password'] = <PASSWORD>
        data['group_names'] = self.group_names
        return data

    def update_from_dict(self, data):
        # if password is blank, remove its key from data
        has_password = 'password' in data
        if has_password and not data['password']:
            del data['password']
        elif has_password:
{'fraction_non_alphanumeric': 0.11263770268597599, 'fraction_numerical': 0.003218220076742171, 'mean_word_length': 3.1182466870540266, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5731821', 'n_tokens_mistral': 2522, 'n_tokens_neox': 2446, 'n_words': 574}