<commit_before>from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from app import db, login_manager

class Employee(UserMixin, db.Model):
    """
    Create an Employee table
    """

    # Ensures table will be named in plural and not in singular
    # as is the name of the model
    __tablename__ = 'employees'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(60), index=True, unique=True)
    username = db.Column(db.String(60), index=True, unique=True)
    first_name = db.Column(db.String(60), index=True)
    last_name = db.Column(db.String(60), index=True)
    password_hash = db.Column(db.String(128))
    department_id = db.Column(db.Integer, db.ForeignKey('vendors.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    is_admin = db.Column(db.Boolean, default=False)

    @property
    def password(self):
        """
        Prevent pasword from being accessed
        """
        raise AttributeError('password is not a readable attribute.')

    @password.setter
    def password(self, password):
        """
        Set password to a hashed password
        """
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        """
        Check if hashed password matches actual password
        """
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<Employee: {}>'.format(self.username)

# Set up user_loader
@login_manager.user_loader
def load_user(user_id):
    return Employee.query.get(int(user_id))

class Vendor(db.Model):
    """
    Create a Vendor table
    """

    __tablename__ = 'vendors'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), unique=True)t
    description = db.Column(db.String(200))
    employees = db.relationship('Employee', backref='vendor',
                                lazy='dynamic')

    def __repr__(self):
        return '<Vendor: {}>'.format(self.name)

class Role(db.Model):
    """
    Create a Role table
    """

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), unique=True)
    description = db.Column(db.String(200))
    employees = db.relationship('Employee', backref='role',
                                lazy='dynamic')

    def __repr__(self):
        return '<Role: {}>'.format(self.name)

class Thing(db.Model):
    """
    Create a Thing table
    for physical objects
    """

    __tablename__ = 'thing'

    id = db.Column(db.Integer, primary_key=True)
    barcode = db.Column(db.String, unique=True)
    name = db.Column(db.String)
    description = db.Column(db.String)
    owner = db.Column(db.String)

    def __repr__(self):
        return '<Item>: {}'.format(self.name)
<commit_msg>Fix Typo<commit_after>from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash

from app import db, login_manager

class Employee(UserMixin, db.Model):
    """
    Create an Employee table
    """

    # Ensures table will be named in plural and not in singular
    # as is the name of the model
    __tablename__ = 'employees'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(60), index=True, unique=True)
    username = db.Column(db.String(60), index=True, unique=True)
    first_name = db.Column(db.String(60), index=True)
    last_name = db.Column(db.String(60), index=True)
    password_hash = db.Column(db.String(128))
    department_id = db.Column(db.Integer, db.ForeignKey('vendors.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    is_admin = db.Column(db.Boolean, default=False)

    @property
    def password(self):
        """
        Prevent pasword from being accessed
        """
        raise AttributeError('password is not a readable attribute.')

    @password.setter
    def password(self, password):
        """
        Set password to a hashed password
        """
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        """
        Check if hashed password matches actual password
        """
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return '<Employee: {}>'.format(self.username)

# Set up user_loader
@login_manager.user_loader
def load_user(user_id):
    return Employee.query.get(int(user_id))

class Vendor(db.Model):
    """
    Create a Vendor table
    """

    __tablename__ = 'vendors'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), unique=True)
    description = db.Column(db.String(200))
    employees = db.relationship('Employee', backref='vendor',
                                lazy='dynamic')

    def __repr__(self):
        return '<Vendor: {}>'.format(self.name)

class Role(db.Model):
    """
    Create a Role table
    """

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(60), unique=True)
    description = db.Column(db.String(200))
    employees = db.relationship('Employee', backref='role',
                                lazy='dynamic')

    def __repr__(self):
        return '<Role: {}>'.format(self.name)

class Thing(db.Model):
    """
    Create a Thing table
    for physical objects
    """

    __tablename__ = 'thing'

    id = db.Column(db.Integer, primary_key=True)
    barcode = db.Column(db.String, unique=True)
    name = db.Column(db.String)
    description = db.Column(db.String)
    owner = db.Column(db.String)

    def __repr__(self):
        return '<Item>: {}'.format(self.name)
<|endoftext|>


<commit_before>"""Leave one out coding"""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from category_encoders.utils import get_obj_cols, convert_input, get_generated_cols
from sklearn.utils.random import check_random_state

__author__ = 'hbghhy'

class LeaveOneOutEncoder(BaseEstimator, TransformerMixin):
    """Leave one out coding for categorical features.

    Parameters
    ----------

    verbose: int
        integer indicating verbosity of output. 0 for none.
    cols: list
        a list of columns to encode, if None, all string columns will be encoded.
    drop_invariant: bool
        boolean for whether or not to drop columns with 0 variance.
    return_df: bool
        boolean for whether to return a pandas DataFrame from transform (otherwise it will be a numpy array).
    impute_missing: bool
        boolean for whether or not to apply the logic for handle_unknown, will be deprecated in the future.
    handle_unknown: str
        options are 'error', 'ignore' and 'impute', defaults to 'impute', which will impute the category -1. Warning: if
        impute is used, an extra column will be added in if the transform matrix has unknown categories.  This can causes
        unexpected changes in dimension in some cases.
    randomized: bool
        adds normal (Gaussian) distribution noise into training data in order to decrease overfitting (testing data are untouched).
    sigma: float
        standard deviation (spread or "width") of the normal distribution.

    Example
    -------
    >>> from category_encoders import *
    >>> import pandas as pd
    >>> from sklearn.datasets import load_boston
    >>> bunch = load_boston()
    >>> y = bunch.target
    >>> X = pd.DataFrame(bunch.data, columns=bunch.feature_names)
    >>> enc = LeaveOneOutEncoder(cols=['CHAS', 'RAD']).fit(X, y)
    >>> numeric_dataset = enc.transform(X)
    >>> print(numeric_dataset.info())
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 506 entries, 0 to 505
    Data columns (total 13 columns):
    CRIM       506 non-null float64
    ZN         506 non-null float64
    INDUS      506 non-null float64
    NOX        506 non-null float64
    RM         506 non-null float64
    AGE        506 non-null float64
    DIS        506 non-null float64
    TAX        506 non-null float64
    PTRATIO    506 non-null float64
    B          506 non-null float64
    LSTAT      506 non-null float64
    CHAS       506 non-null float64
    RAD        506 non-null float64
    dtypes: float64(13)
    memory usage: 51.5 KB
    None

    References
    ----------

    .. [1] Strategies to encode categorical variables with many categories. from
    https://www.kaggle.com/c/caterpillar-tube-pricing/discussion/15748#143154.

    """

    def __init__(self, verbose=0, cols=None, drop_invariant=False, return_df=True, impute_missing=True,
                 handle_unknown='impute', random_state=None, randomized=False, sigma=0.05):
        self.return_df = return_df
        self.drop_invariant = drop_invariant
        self.drop_cols = []
        self.verbose = verbose
        self.static_cols = cols
        self.cols = cols
        self._dim = None
        self.mapping = None
        self.impute_missing = impute_missing
        self.handle_unknown = handle_unknown
        self._mean = None
        self.random_state = random_state
        self.randomized = randomized
        self.sigma = sigma

    def fit(self, X, y, **kwargs):
        """Fit encoder according to X and y.

        Parameters
        ----------

        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.
        y : array-like, shape = [n_samples]
            Target values.

        Returns
        -------

        self : encoder
            Returns self.

        """

        # first check the type
        X = convert_input(X)
        if isinstance(y, pd.DataFrame):
            y = y.iloc[:,0]
        else:
            y = pd.Series(y, name='target')
        if X.shape[0] != y.shape[0]:
            raise ValueError("The length of X is " + str(X.shape[0]) + " but length of y is " + str(y.shape[0]) + ".")

        self._dim = X.shape[1]

        # if columns aren't passed, just use every string column
        if self.static_cols is None:
            self.cols = get_obj_cols(X)

        categories = self.fit_leave_one_out(
            X, y,
            cols=self.cols,
            impute_missing=self.impute_missing,
            handle_unknown=self.handle_unknown
        )
        self.mapping = categories

        if self.drop_invariant:
            self.drop_cols = []
            X_temp = self.transform(X)
            generated_cols = get_generated_cols(X, X_temp, self.cols)
            self.drop_cols = [x for x in generated_cols if X_temp[x].var() <= 10e-5]

        return self

    def transform(self, X, y=None):
        """Perform the transformation to new categorical data.

        Parameters
        ----------

        X : array-like, shape = [n_samples, n_features]
        y : array-like, shape = [n_samples] when transform by leave one out
            None, when transform without target information (such as transform test set)

        Returns
        -------

        p : array, shape = [n_samples, n_numeric + N]
            Transformed values with encoding applied.

        """

        if self._dim is None:
            raise ValueError('Must train encoder before it can be used to transform data.')

        # first check the type
        X = convert_input(X)

        # then make sure that it is the right size
        if X.shape[1] != self._dim:
            raise ValueError('Unexpected input dimension %d, expected %d' % (X.shape[1], self._dim,))

        # if we are encoding the training data, we have to check the target
        if y is not None:
            if isinstance(y, pd.DataFrame):
                y = y.iloc[:, 0]
            else:
                y = pd.Series(y, name='target')
            if X.shape[0] != y.shape[0]:
                raise ValueError("The length of X is " + str(X.shape[0]) + " but length of y is " + str(y.shape[0]) + ".")

        if not self.cols:
            return X
        X = self.transform_leave_one_out(
            X, y,
            mapping=self.mapping,
            impute_missing=self.impute_missing,
            handle_unknown=self.handle_unknown
        )

        if self.drop_invariant:
            for col in self.drop_cols:
                X.drop(col, 1, inplace=True)

        if self.return_df:
            return X
        else:
            return X.values

    def fit_transform(self, X, y=None, **fit_params):
        """
        Encoders that utilize the target must make sure that the training data are transformed with:
             transform(X, y)
        and not with:
            transform(X)
        """
        return self.fit(X, y, **fit_params).transform(X, y)

    def fit_leave_one_out(self, X_in, y, cols=None, impute_missing=True, handle_unknown='impute'):
        X = X_in.copy(deep=True)

        if cols is None:
            cols = X.columns.values

        self._mean = y.mean()
        mapping_out = []

        for col in cols:
            tmp = y.groupby(X[col]).agg(['sum', 'count'])
            tmp['mean'] = tmp['sum'] / tmp['count']
            tmp = tmp.to_dict(orient='index')

            X[str(col) + '_tmp'] = np.nan
            for val in tmp:
                """if the val only appear once ,encoder it as mean of y"""
                if tmp[val]['count'] == 1:
                    X.loc[X[col] == val, str(col) + '_tmp'] = self._mean
                else:
                    X.loc[X[col] == val, str(col) + '_tmp'] = (tmp[val]['sum'] - y.loc[X[col] == val]) / (
                            tmp[val]['count'] - 1)
            del X[col]
            X.rename(columns={str(col) + '_tmp': col}, inplace=True)

            if impute_missing:
                if handle_unknown == 'impute':
                    X[col].fillna(self._mean, inplace=True)

            X[col] = X[col].astype(float).values.reshape(-1, )

            mapping_out.append({'col': col, 'mapping': tmp}, )

        return mapping_out

    def transform_leave_one_out(self, X_in, y, mapping=None, impute_missing=True, handle_unknown='impute'):
        """
        Leave one out encoding uses a single column of floats to represent the means of the target variables.
        """

        X = X_in.copy(deep=True)

        random_state_ = check_random_state(self.random_state)
        for switch in mapping:
            X[str(switch.get('col')) + '_tmp'] = np.nan
            for val in switch.get('mapping'):
                if y is None:
                    X.loc[X[switch.get('col')] == val, str(switch.get('col')) + '_tmp'] = \
                        switch.get('mapping')[val]['mean']
                elif switch.get('mapping')[val]['count'] == 1:
                    X.loc[X[switch.get('col')] == val, str(switch.get('col')) + '_tmp'] = self._mean
                else:
                    X.loc[X[switch.get('col')] == val, str(switch.get('col')) + '_tmp'] = (
                        (switch.get('mapping')[val]['sum'] - y[(X[switch.get('col')] == val).values]) / (
                            switch.get('mapping')[val]['count'] - 1)
                    )
            del X[switch.get('col')]
            X.rename(columns={str(switch.get('col')) + '_tmp': switch.get('col')}, inplace=True)

            if impute_missing:
                if handle_unknown == 'impute':
                    X[switch.get('col')].fillna(self._mean, inplace=True)
                elif handle_unknown == 'error':
                    missing = X[switch.get('col')].isnull()
                    if any(missing):
                        raise ValueError('Unexpected categories found in column %s' % switch.get('col'))

            if self.randomized and y is not None:
                X[switch.get('col')] = (X[switch.get('col')] *
                                        random_state_.normal(1., self.sigma, X[switch.get('col')].shape[0]))

            X[switch.get('col')] = X[switch.get('col')].astype(float).values.reshape(-1, )

        return X
<commit_msg>Convery static_cols into a boolean field use_default_cols to make it clearer whether or not we need to use the dataframe to extract the categorical columns<commit_after>"""Leave one out coding"""
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from category_encoders.utils import get_obj_cols, convert_input, get_generated_cols
from sklearn.utils.random import check_random_state

__author__ = 'hbghhy'

class LeaveOneOutEncoder(BaseEstimator, TransformerMixin):
    """Leave one out coding for categorical features.

    Parameters
    ----------

    verbose: int
        integer indicating verbosity of output. 0 for none.
    cols: list
        a list of columns to encode, if None, all string columns will be encoded.
    drop_invariant: bool
        boolean for whether or not to drop columns with 0 variance.
    return_df: bool
        boolean for whether to return a pandas DataFrame from transform (otherwise it will be a numpy array).
    impute_missing: bool
        boolean for whether or not to apply the logic for handle_unknown, will be deprecated in the future.
    handle_unknown: str
        options are 'error', 'ignore' and 'impute', defaults to 'impute', which will impute the category -1. Warning: if
        impute is used, an extra column will be added in if the transform matrix has unknown categories.  This can causes
        unexpected changes in dimension in some cases.
    randomized: bool
        adds normal (Gaussian) distribution noise into training data in order to decrease overfitting (testing data are untouched).
    sigma: float
        standard deviation (spread or "width") of the normal distribution.

    Example
    -------
    >>> from category_encoders import *
    >>> import pandas as pd
    >>> from sklearn.datasets import load_boston
    >>> bunch = load_boston()
    >>> y = bunch.target
    >>> X = pd.DataFrame(bunch.data, columns=bunch.feature_names)
    >>> enc = LeaveOneOutEncoder(cols=['CHAS', 'RAD']).fit(X, y)
    >>> numeric_dataset = enc.transform(X)
    >>> print(numeric_dataset.info())
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 506 entries, 0 to 505
    Data columns (total 13 columns):
    CRIM       506 non-null float64
    ZN         506 non-null float64
    INDUS      506 non-null float64
    NOX        506 non-null float64
    RM         506 non-null float64
    AGE        506 non-null float64
    DIS        506 non-null float64
    TAX        506 non-null float64
    PTRATIO    506 non-null float64
    B          506 non-null float64
    LSTAT      506 non-null float64
    CHAS       506 non-null float64
    RAD        506 non-null float64
    dtypes: float64(13)
    memory usage: 51.5 KB
    None

    References
    ----------

    .. [1] Strategies to encode categorical variables with many categories. from
    https://www.kaggle.com/c/caterpillar-tube-pricing/discussion/15748#143154.

    """

    def __init__(self, verbose=0, cols=None, drop_invariant=False, return_df=True, impute_missing=True,
                 handle_unknown='impute', random_state=None, randomized=False, sigma=0.05):
        self.return_df = return_df
        self.drop_invariant = drop_invariant
        self.drop_cols = []
        self.verbose = verbose
        self.use_default_cols = cols is None  # important when we call fit() repeatedly
        self.cols = cols
        self._dim = None
        self.mapping = None
        self.impute_missing = impute_missing
        self.handle_unknown = handle_unknown
        self._mean = None
        self.random_state = random_state
        self.randomized = randomized
        self.sigma = sigma

    def fit(self, X, y, **kwargs):
        """Fit encoder according to X and y.

        Parameters
        ----------

        X : array-like, shape = [n_samples, n_features]
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.
        y : array-like, shape = [n_samples]
            Target values.

        Returns
        -------

        self : encoder
            Returns self.

        """

        # first check the type
        X = convert_input(X)
        if isinstance(y, pd.DataFrame):
            y = y.iloc[:,0]
        else:
            y = pd.Series(y, name='target')
        if X.shape[0] != y.shape[0]:
            raise ValueError("The length of X is " + str(X.shape[0]) + " but length of y is " + str(y.shape[0]) + ".")

        self._dim = X.shape[1]

        # if columns aren't passed, just use every string column
        if self.use_default_cols:
            self.cols = get_obj_cols(X)

        categories = self.fit_leave_one_out(
            X, y,
            cols=self.cols,
            impute_missing=self.impute_missing,
            handle_unknown=self.handle_unknown
        )
        self.mapping = categories

        if self.drop_invariant:
            self.drop_cols = []
            X_temp = self.transform(X)
            generated_cols = get_generated_cols(X, X_temp, self.cols)
            self.drop_cols = [x for x in generated_cols if X_temp[x].var() <= 10e-5]

        return self

    def transform(self, X, y=None):
        """Perform the transformation to new categorical data.

        Parameters
        ----------

        X : array-like, shape = [n_samples, n_features]
        y : array-like, shape = [n_samples] when transform by leave one out
            None, when transform without target information (such as transform test set)

        Returns
        -------

        p : array, shape = [n_samples, n_numeric + N]
            Transformed values with encoding applied.

        """

        if self._dim is None:
            raise ValueError('Must train encoder before it can be used to transform data.')

        # first check the type
        X = convert_input(X)

        # then make sure that it is the right size
        if X.shape[1] != self._dim:
            raise ValueError('Unexpected input dimension %d, expected %d' % (X.shape[1], self._dim,))

        # if we are encoding the training data, we have to check the target
        if y is not None:
            if isinstance(y, pd.DataFrame):
                y = y.iloc[:, 0]
            else:
                y = pd.Series(y, name='target')
            if X.shape[0] != y.shape[0]:
                raise ValueError("The length of X is " + str(X.shape[0]) + " but length of y is " + str(y.shape[0]) + ".")

        if not self.cols:
            return X
        X = self.transform_leave_one_out(
            X, y,
            mapping=self.mapping,
            impute_missing=self.impute_missing,
            handle_unknown=self.handle_unknown
        )

        if self.drop_invariant:
            for col in self.drop_cols:
                X.drop(col, 1, inplace=True)

        if self.return_df:
            return X
        else:
            return X.values

    def fit_transform(self, X, y=None, **fit_params):
        """
        Encoders that utilize the target must make sure that the training data are transformed with:
             transform(X, y)
        and not with:
            transform(X)
        """
        return self.fit(X, y, **fit_params).transform(X, y)

    def fit_leave_one_out(self, X_in, y, cols=None, impute_missing=True, handle_unknown='impute'):
        X = X_in.copy(deep=True)

        if cols is None:
            cols = X.columns.values

        self._mean = y.mean()
        mapping_out = []

        for col in cols:
            tmp = y.groupby(X[col]).agg(['sum', 'count'])
            tmp['mean'] = tmp['sum'] / tmp['count']
            tmp = tmp.to_dict(orient='index')

            X[str(col) + '_tmp'] = np.nan
            for val in tmp:
                """if the val only appear once ,encoder it as mean of y"""
                if tmp[val]['count'] == 1:
                    X.loc[X[col] == val, str(col) + '_tmp'] = self._mean
                else:
                    X.loc[X[col] == val, str(col) + '_tmp'] = (tmp[val]['sum'] - y.loc[X[col] == val]) / (
                            tmp[val]['count'] - 1)
            del X[col]
            X.rename(columns={str(col) + '_tmp': col}, inplace=True)

            if impute_missing:
                if handle_unknown == 'impute':
                    X[col].fillna(self._mean, inplace=True)

            X[col] = X[col].astype(float).values.reshape(-1, )

            mapping_out.append({'col': col, 'mapping': tmp}, )

        return mapping_out

    def transform_leave_one_out(self, X_in, y, mapping=None, impute_missing=True, handle_unknown='impute'):
        """
        Leave one out encoding uses a single column of floats to represent the means of the target variables.
        """

        X = X_in.copy(deep=True)

        random_state_ = check_random_state(self.random_state)
        for switch in mapping:
            X[str(switch.get('col')) + '_tmp'] = np.nan
            for val in switch.get('mapping'):
                if y is None:
                    X.loc[X[switch.get('col')] == val, str(switch.get('col')) + '_tmp'] = \
                        switch.get('mapping')[val]['mean']
                elif switch.get('mapping')[val]['count'] == 1:
                    X.loc[X[switch.get('col')] == val, str(switch.get('col')) + '_tmp'] = self._mean
                else:
                    X.loc[X[switch.get('col')] == val, str(switch.get('col')) + '_tmp'] = (
                        (switch.get('mapping')[val]['sum'] - y[(X[switch.get('col')] == val).values]) / (
                            switch.get('mapping')[val]['count'] - 1)
                    )
            del X[switch.get('col')]
            X.rename(columns={str(switch.get('col')) + '_tmp': switch.get('col')}, inplace=True)

            if impute_missing:
                if handle_unknown == 'impute':
                    X[switch.get('col')].fillna(self._mean, inplace=True)
                elif handle_unknown == 'error':
                    missing = X[switch.get('col')].isnull()
                    if any(missing):
                        raise ValueError('Unexpected categories found in column %s' % switch.get('col'))

            if self.randomized and y is not None:
                X[switch.get('col')] = (X[switch.get('col')] *
                                        random_state_.normal(1., self.sigma, X[switch.get('col')].shape[0]))

            X[switch.get('col')] = X[switch.get('col')].astype(float).values.reshape(-1, )

        return X
<|endoftext|>


<commit_before>import app
from app import db
from datetime import datetime, date

class FriendRequest(db.Model):
    __tablename__ = "friend_requests"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    friend_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created = db.Column(db.DateTime, default=datetime.utcnow)
    __table_args__ = (
        db.CheckConstraint("user_id != friend_id"),
    )

class Friend(db.Model):
    __tablename__ = "friends"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    friend_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created = db.Column(db.DateTime, default=datetime.utcnow)
    __table_args__ = (
        db.CheckConstraint("user_id != friend_id"),
    )

class Message(db.Model):
    __tablename__ = "messages"
    id = db.Column(db.Integer, primary_key=True)
    sent_timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    to_user_id = db.Column(db.Integer, nullable=False)
    from_user_id = db.Column(db.Integer, nullable=False)
    title = db.Column(db.String, index=True)
    body = db.Column(db.String, nullable=False, index=True)
    is_read = db.Column(db.Boolean, default=False)
    __table_args__ = (
        db.CheckConstraint("to_user_id != from_user_id"),
    )

    def from_user(self):
        user = User.query.filter_by(id=self.from_user_id).first()
        if user is not None:
            return user
        else:
            return None

    def to_user(self):
        user = User.query.filter_by(id=self.to_user_id).first()
        if user is not None:
            return user
        else:
            return None

    def __repr__(self):
        return "<Message: From: %d, to: %d, title: %r>" % (self.from_user_id, self.to_user_id, self.title)

class Task(db.Model):
    __tablename__ = "task"
    id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    end_timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    description = db.Column(db.String, nullable=False, index=True)
    requester_id = db.Column(db.Integer, nullable=False)
    doer_id = db.Column(db.Integer, nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    __table_args__ = (
        db.CheckConstraint("requester_id != doer_id"),
    )

    def requester(self):
        return db.session.query(User, Task).filter(self.requester_id == User.id).first()

    def doer(self):
        return db.session.query(User, Task).filter(self.doer_id == User.id).first()

    def __repr__(self):
        return "<Task: Requester: %d, doer: %d, '%r'>" % (self.requester_id, self.doer_id, self.description)

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, index=True, unique=True)
    pw_hash = db.Column(db.String, index=True)
    age = db.Column(db.Integer)
    gender = db.Column(db.String(24))
    role = db.Column(db.String(24))
    orientation = db.Column(db.String(24))
    bio = db.Column(db.String)
    email = db.Column(db.String, nullable=False, unique=True)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    user_role = db.Column(db.Integer, default=0)
    is_validated = db.Column(db.Boolean, default=False)
    password_reset_token = db.Column(db.String)
    password_reset_token_expiration = db.Column(db.DateTime)
    users_sending_friend_requests = db.relationship('User',
        secondary="friend_requests",
        primaryjoin=(FriendRequest.friend_id == id),
        secondaryjoin=(FriendRequest.user_id == id),
        backref=db.backref("users_with_pending_friend_requests", lazy="dynamic"),
        lazy="dynamic"
    )
    friends = db.relationship('User',
        secondary="friends",
        primaryjoin=(Friend.user_id == id),
        secondaryjoin=(Friend.friend_id == id),
        lazy="dynamic"
    )
    __table_args__ = (
        db.UniqueConstraint('username'),
        db.UniqueConstraint('email'),
        db.CheckConstraint('age is null or (age >= 18 and age <= 100)')
    )

    def inbox_messages(self):
        return Message.query.filter_by(to_user_id=self.id).order_by(Message.sent_timestamp.desc())

    def outbox_messages(self):
        return Message.query.filter_by(from_user_id=self.id).order_by(Message.sent_timestamp.desc())

    def num_unread_messages(self):
        return Message.query.filter_by(to_user_id=self.id).filter(~Message.is_read).count()

    def age_gender_role(self):
        return " ".join([str(x) if x is not None else "" for x in [self.age, self.gender, self.role]])

    def tasks_todo(self, active=True):
        return [x[1] for x in
                db.session.query(User, Task).filter(User.id == Task.doer_id and Task.is_active == bool(active)).
                    filter(User.id == self.id).all()
                ]

    def tasks_assigned(self, active=True):
        return [x[1] for x in
                    db.session.query(User, Task).filter(User.id == Task.requester_id and Task.is_active == bool(active)).
                        filter(User.id == self.id).all()
                ]

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return "<User '%r'>" % (self.username)
<commit_msg>Model tweaks<commit_after>import app
from app import db
from datetime import datetime, date

class FriendRequest(db.Model):
    __tablename__ = "friend_requests"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    friend_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created = db.Column(db.DateTime, default=datetime.utcnow)
    __table_args__ = (
        db.CheckConstraint("user_id != friend_id"),
    )

class Friend(db.Model):
    __tablename__ = "friends"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    friend_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    created = db.Column(db.DateTime, default=datetime.utcnow)
    __table_args__ = (
        db.CheckConstraint("user_id != friend_id"),
    )

class Message(db.Model):
    __tablename__ = "messages"
    id = db.Column(db.Integer, primary_key=True)
    sent_timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    to_user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    from_user_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    title = db.Column(db.String, index=True)
    body = db.Column(db.String, nullable=False, index=True)
    is_read = db.Column(db.Boolean, default=False)
    __table_args__ = (
        db.CheckConstraint("to_user_id != from_user_id"),
    )

    def from_user(self):
        user = User.query.filter_by(id=self.from_user_id).first()
        if user is not None:
            return user
        else:
            return None

    def to_user(self):
        user = User.query.filter_by(id=self.to_user_id).first()
        if user is not None:
            return user
        else:
            return None

    def __repr__(self):
        return "<Message: From: %d, to: %d, title: %r>" % (self.from_user_id, self.to_user_id, self.title)

class Task(db.Model):
    __tablename__ = "task"
    id = db.Column(db.Integer, primary_key=True)
    created = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    end_timestamp = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    description = db.Column(db.String, nullable=False, index=True)
    requester_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    doer_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    is_active = db.Column(db.Boolean, default=True)
    __table_args__ = (
        db.CheckConstraint("requester_id != doer_id"),
    )

    def requester(self):
        return db.session.query(User, Task).filter(self.requester_id == User.id).first()

    def doer(self):
        return db.session.query(User, Task).filter(self.doer_id == User.id).first()

    def __repr__(self):
        return "<Task: Requester: %d, doer: %d, '%r'>" % (self.requester_id, self.doer_id, self.description)

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String, index=True, unique=True)
    pw_hash = db.Column(db.String, index=True)
    age = db.Column(db.Integer)
    gender = db.Column(db.String(24))
    role = db.Column(db.String(24))
    orientation = db.Column(db.String(24))
    bio = db.Column(db.String)
    email = db.Column(db.String, nullable=False, unique=True)
    created = db.Column(db.DateTime, default=datetime.utcnow)
    user_role = db.Column(db.Integer, default=0)
    is_validated = db.Column(db.Boolean, default=False)
    password_reset_token = db.Column(db.String)
    password_reset_token_expiration = db.Column(db.DateTime)
    users_sending_friend_requests = db.relationship('User',
        secondary="friend_requests",
        primaryjoin=(FriendRequest.friend_id == id),
        secondaryjoin=(FriendRequest.user_id == id),
        backref=db.backref("users_with_pending_friend_requests", lazy="dynamic"),
        lazy="dynamic"
    )
    friends = db.relationship('User',
        secondary="friends",
        primaryjoin=(Friend.user_id == id),
        secondaryjoin=(Friend.friend_id == id),
        lazy="dynamic"
    )
    __table_args__ = (
        db.UniqueConstraint('username'),
        db.UniqueConstraint('email'),
        db.CheckConstraint('age is null or (age >= 18 and age <= 100)')
    )

    def inbox_messages(self):
        return Message.query.filter_by(to_user_id=self.id).order_by(Message.sent_timestamp.desc())

    def outbox_messages(self):
        return Message.query.filter_by(from_user_id=self.id).order_by(Message.sent_timestamp.desc())

    def num_unread_messages(self):
        return Message.query.filter_by(to_user_id=self.id).filter(~Message.is_read).count()

    def age_gender_role(self):
        return " ".join([str(x) if x is not None else "" for x in [self.age, self.gender, self.role]])

    def tasks_todo(self, active=True):
        return [x[1] for x in
                db.session.query(User, Task).filter(User.id == Task.doer_id and Task.is_active == bool(active)).
                    filter(User.id == self.id).all()
                ]

    def tasks_assigned(self, active=True):
        return [x[1] for x in
                    db.session.query(User, Task).filter(User.id == Task.requester_id and Task.is_active == bool(active)).
                        filter(User.id == self.id).all()
                ]

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return unicode(self.id)

    def __repr__(self):
        return "<User '%r'>" % (self.username)
<|endoftext|>


<commit_before>from math import sin

from .modifier import Modifier

class LFOSine(Modifier):
    """
    A positive sine, moving from 0 to 1 * amplitude
    """

    def __init__(self, frequency=0.2, **kwargs):
        super().__init__(**kwargs)
        self.frequency = frequency

    def serialize(self):
        m = super().serialize()
        m["frequency"] = self.frequency
        return m

    def from_dict(self, m, *args, **kwargs):
        super().from_dict(m, *args, **kwargs)
        self.frequency = m["frequency"]

    def calculate(self, t):
        return (sin(t * self.frequency) + 1) * 0.5

    def save(self):
        d = super().save()
        d["frequency"] = self.frequency
        return d

    def load(self, d, i):
        super().load(d, i)
        self.frequency = d["frequency"]
<commit_msg>Makes Basic modifier class<commit_after>from math import sin

from .modifier import Modifier

class Basic(Modifier):
    """
    A basic modulator that just needs a frequency to operate.
    """

    def __init__(self, frequency=0.2, **kwargs):
        super().__init__(**kwargs)
        self.frequency = frequency

    def serialize(self):
        m = super().serialize()
        m["frequency"] = self.frequency
        return m

    def from_dict(self, m, *args, **kwargs):
        super().from_dict(m, *args, **kwargs)
        self.frequency = m["frequency"]

    def save(self):
        d = super().save()
        d["frequency"] = self.frequency
        return d

    def load(self, d, i):
        super().load(d, i)
        self.frequency = d["frequency"]

class LFOSine(Basic):
    """
    A positive sine, moving from 0 to 1 * amplitude
    """

    def calculate(self, t):
        return (sin(t * self.frequency) + 1) * 0.5

<|endoftext|>


<commit_before>from beets.plugins import BeetsPlugin
from beets import ui, config, library

from os import system, fsync
from os.path import isdir, isfile, join, relpath
from tempfile import NamedTemporaryFile

def syncpl(lib, opts, args):
    if args:
        config['syncpl']['dest'] = args[0]

    if not config['syncpl']['dest']:
        raise ui.UserError(u'no destination path specified')

    if not isdir(config['syncpl']['dest'].get()):
        raise ui.UserError(u'invalid destination path')

    if not config['syncpl']['playlists'].get() and \
       not config['syncpl']['queries'].get():
        raise ui.UserError(u'nothing to sync')

    if config['syncpl']['playlists'].get():
        if not config['syncpl']['playlist_dir'].get():
            raise ui.UserError(u'no playlist_dir specified')

        if not isdir(config['syncpl']['playlist_dir'].get()):
            raise ui.UserError(u'invalid playlist_dir')

    items = set()
    paths = set()

    # Retrieve the playlist items to sync
    for playlist in config['syncpl']['playlists'].as_str_seq():
        pl_path = join(config['syncpl']['playlist_dir'].get(), playlist)

        if not isfile(pl_path):
            raise ui.UserError(u'playlist not found: ' + playlist)

        with open(pl_path, 'r') as f:
            for path in f.readlines():
                full_path = join(config['directory'].get(),
                                 path.strip('\n').decode('utf-8'))
                items.update(lib.items(query=u'path:"%s"' % full_path))

        if config['syncpl']['include_playlist']:
            paths.add(playlist.encode('utf-8'))

    # Retrieve the query items to sync
    for query in config['syncpl']['queries'].as_str_seq():
        items.update(lib.items(query=query))

    # Retrieve the track and album art paths
    for item in items:
        paths.add(relpath(item.path, config['directory'].get().encode('utf-8')))

        if item.get_album().artpath:
            paths.add(relpath(item.get_album().artpath,
                              config['directory'].get()))

    # Write the paths to a reference file for rsync
    with NamedTemporaryFile() as tmp:
        tmp.write('\n'.join(paths))
        tmp.flush()
        fsync(tmp.fileno())

        src = join(config['directory'].get(), '')

        if config['syncpl']['playlist_dir']:
            src += ' ' + join(config['syncpl']['playlist_dir'].get(), '')

        system('rsync -amv --include="*/" --include-from=%s --exclude="*" \
                --delete-excluded %s %s' %
                        (tmp.name, src, config['syncpl']['dest'].get()))

class SyncplPlugin(BeetsPlugin):
    def __init__(self):
        super(SyncplPlugin, self).__init__()
        self.config.add({
            u'dest': None,
            u'playlist_dir': None,
            u'include_playlist': True,
            u'playlists': [],
            u'queries': [],
        })

    def commands(self):
        cmd = ui.Subcommand('syncpl', help='sync music files to a folder')
        cmd.func = syncpl
        return [cmd]
<commit_msg>Add --delete and --nodelete option<commit_after>from beets.plugins import BeetsPlugin
from beets import ui, config, library

from os import system, fsync
from os.path import isdir, isfile, join, relpath
from tempfile import NamedTemporaryFile

def syncpl(lib, opts, args):
    config['syncpl'].set_args(opts)

    if args:
        config['syncpl']['dest'] = args[0]

    if not config['syncpl']['dest']:
        raise ui.UserError(u'no destination path specified')

    if not isdir(config['syncpl']['dest'].get()):
        raise ui.UserError(u'invalid destination path')

    if not config['syncpl']['playlists'].get() and \
       not config['syncpl']['queries'].get():
        raise ui.UserError(u'nothing to sync')

    if config['syncpl']['playlists'].get():
        if not config['syncpl']['playlist_dir'].get():
            raise ui.UserError(u'no playlist_dir specified')

        if not isdir(config['syncpl']['playlist_dir'].get()):
            raise ui.UserError(u'invalid playlist_dir')

    items = set()
    paths = set()

    # Retrieve the playlist items to sync
    for playlist in config['syncpl']['playlists'].as_str_seq():
        pl_path = join(config['syncpl']['playlist_dir'].get(), playlist)

        if not isfile(pl_path):
            raise ui.UserError(u'playlist not found: ' + playlist)

        with open(pl_path, 'r') as f:
            for path in f.readlines():
                full_path = join(config['directory'].get(),
                                 path.strip('\n').decode('utf-8'))
                items.update(lib.items(query=u'path:"%s"' % full_path))

        if config['syncpl']['include_playlist']:
            paths.add(playlist.encode('utf-8'))

    # Retrieve the query items to sync
    for query in config['syncpl']['queries'].as_str_seq():
        items.update(lib.items(query=query))

    # Retrieve the track and album art paths
    for item in items:
        paths.add(relpath(item.path, config['directory'].get().encode('utf-8')))

        if item.get_album().artpath:
            paths.add(relpath(item.get_album().artpath,
                              config['directory'].get()))

    # Write the paths to a reference file for rsync
    with NamedTemporaryFile() as tmp:
        tmp.write('\n'.join(paths))
        tmp.flush()
        fsync(tmp.fileno())

        src = join(config['directory'].get(), '')
        options = ''

        if config['syncpl']['playlist_dir']:
            src += ' ' + join(config['syncpl']['playlist_dir'].get(), '')

        if config['syncpl']['delete']:
            options += '--delete-excluded'

        system('rsync -amv --include="*/" --include-from=%s --exclude="*" \
                %s %s %s' % (tmp.name, options, src,
                             config['syncpl']['dest'].get()))

class SyncplPlugin(BeetsPlugin):
    def __init__(self):
        super(SyncplPlugin, self).__init__()
        self.config.add({
            u'dest': None,
            u'playlist_dir': None,
            u'include_playlist': True,
            u'delete': False,
            u'playlists': [],
            u'queries': [],
        })

    def commands(self):
        cmd = ui.Subcommand('syncpl', help='sync music files to a folder')
        cmd.parser.add_option(
            '-d', '--delete', action='store_true', default=None,
            help="delete anything unspecfied in the destination folder")
        cmd.parser.add_option(
            '-D', '--nodelete', action='store_false', dest='delete',
            help="don't delete anything unspecified in the destination folder")
        cmd.func = syncpl
        return [cmd]
<|endoftext|>


<commit_before>"""The main module of the Bayesian API Fuzzer."""

from fastlog import log
from cliargs import cli_parser

def main():
    """Entry point to the Bayesian API Fuzzer."""
    log.setLevel(log.INFO)
    log.info("Setup")
    with log.indent():
        cli_arguments = cli_parser.parse_args()

if __name__ == "__main__":
    # execute only if run as a script
    main()
<commit_msg>HTML generator settings<commit_after>"""The main module of the Bayesian API Fuzzer."""

from fastlog import log
from cliargs import cli_parser

def main():
    """Entry point to the Bayesian API Fuzzer."""
    log.setLevel(log.INFO)
    log.info("Setup")
    with log.indent():
        cli_arguments = cli_parser.parse_args()
        generate_html = cli_arguments.html
        log.info("HTML generator: " + ("enabled" if generate_html else "disabled"))

if __name__ == "__main__":
    # execute only if run as a script
    main()
<|endoftext|>


<commit_before>from flask_login import UserMixin
import spotify
import spotipy
import db_utils
import application as app

class User(UserMixin):
    ''' User class for Flask-Login '''
    def __init__(self, user_id, username=None):
        self.id = int(user_id)
        self.username = username
        self._spotify = None

    @property
    def spotify(self):
        oa_client = spotify.sp_oauth
        # Fetch credentials from database
        if not self._spotify:
            self._spotify = db_utils.spotify_creds_for_user(app.engine,
                                                            self.id)
        # No credentials exist for user
        if self._spotify is None:
            return None
        # Refresh tokens if nescessary
        if oa_client.is_token_expired(self._spotify):
            self._spotify = oa_client.refresh_access_token(self._spotify)
            db_utils.spotify_credentials_upsert(app.engine,
                                                self.id,
                                                self._spotify)
        return spotipy.Spotify(auth=self._spotify)

class Playlist(object):
    ''' Playlist object representation '''
    def __init__(self, playlist_id, title=None, duration=0, count=0):
        self.id = playlist_id
        self.title = title
        self.duration = duration
        self.count = count
<commit_msg>Fix Spotify api object creation<commit_after>from flask_login import UserMixin
import spotify
import spotipy
import db_utils
import application as app

class User(UserMixin):
    ''' User class for Flask-Login '''
    def __init__(self, user_id, username=None):
        self.id = int(user_id)
        self.username = username
        self._spotify = None

    @property
    def spotify(self):
        oa_client = spotify.sp_oauth
        # Fetch credentials from database
        if not self._spotify:
            self._spotify = db_utils.spotify_creds_for_user(app.engine,
                                                            self.id)
        # No credentials exist for user
        if self._spotify is None:
            return None
        # Refresh tokens if nescessary
        if oa_client.is_token_expired(self._spotify):
            self._spotify = oa_client.refresh_access_token(self._spotify)
            db_utils.spotify_credentials_upsert(app.engine,
                                                self.id,
                                                self._spotify)
        return spotipy.Spotify(auth=self._spotify['access_token'])

class Playlist(object):
    ''' Playlist object representation '''
    def __init__(self, playlist_id, title=None, duration=0, count=0):
        self.id = playlist_id
        self.title = title
        self.duration = duration
        self.count = count
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Example of 'static graph' feature by Brian Vogel.
# Requires Chainer v3.
# Note: this code is proof-of-concept only. It does not yet
# implement optimized functions and only supports the
# Linear link/function.

import argparse

import chainer
from chainer.dataset import convert
import chainer.links as L
import numpy as np
from chainer.datasets import get_mnist
from chainer import optimizers
import chainer.links.model.classifier as classifier

from chainer.graph_optimizations.static_graph import static_graph

# todo (vogel)

# For now, please refer to the existing examples that have been optimizaed to use
# this feature:
# MNIST example, CIFAR example, ptb example.

if __name__ == '__main__':

    # todo: consider a modified ptb or char-rnn example in which the LSTM node is written
    # in define-by-run code (for gates, activations, linear layers etc). This
    # would be a good use case for static graph optimizations. For example, if a
    # researcher is experimenting with a novel type of RNN, it would be preferable
    # to be able to write a quick prototype implementation in terms of basic chainer
    # functions using define-by-run code and then simply enable static
    # graph optimizations to get improved runtime performance.
<commit_msg>delete file<commit_after><|endoftext|>


<commit_before>from app import db

class NetDevice(db.Model):
    __tablename__ = 'NetDevice'
    id = db.Column(db.Integer, primary_key=True)
    vendor = db.Column(db.String(16))
    device_type = db.Column(db.String(8))
    serial_number = db.Column(db.String(64))
    management_ip = db.Column(db.String(32))
    device_ports = db.relationship('NetDevicePorts', backref='device', lazy='dynamic')

    @property
    def serialize(self):
        return {
            'id': self.id,
            'vendor': self.vendor,
            'device_type': self.device_type,
            'serial_number': self.serial_number,
            'management_ip': self.management_ip,
        }

class NetDevicePorts(db.Model):
    __tablename__ = 'NetDevicePorts'
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('NetDevice.id'))
    connected_to = db.Column(db.String(64))
    vlan = db.Column(db.Integer)
    ip = db.Column(db.String(32))

class IpAddress(db.Model):
    __tablename__ = 'IpAddress'
    id = db.Column(db.Integer, primary_key=True)
    ip = db.Column(db.String(32))
    network_id = db.Column(db.Integer, db.ForeignKey('Network.id'))

class Network(db.Model):
    __tablename__ = 'Network'
    id = db.Column(db.Integer, primary_key=True)
    subnet = db.Column(db.String(24))
    vlan = db.Column(db.Integer)
    ip_networks = db.relationship('IpAddress', backref='network_ip', lazy='dynamic')
    server_networks = db.relationship('Server', backref='network_server', lazy='dynamic')
    vm_networks = db.relationship('VirtualMachine', backref='network_vms', lazy='dynamic')

class PatchPanel(db.Model):
    __tablename__ = 'PatchPanel'
    patch_id = db.Column(db.String(16), primary_key=True)
    description = db.Column(db.String(64))
    connected_to = db.Column(db.String(64))

class Server(db.Model):
    __tablename__ = 'Server'
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(64))
    serial_number = db.Column(db.String(64))
    rack = db.Column(db.String(64))
    unit = db.Column(db.Integer)
    machine_name = db.Column(db.String(64))
    hostname = db.Column(db.String(64))
    vendor = db.Column(db.String(16))
    operating_system = db.Column(db.String(64))
    storage = db.Column(db.String(64))
    ram = db.Column(db.String(64))
    cpu = db.Column(db.String(64))
    network = db.Column(db.String(64))
    server_vms = db.relationship('VirtualMachine', backref='server', lazy='dynamic')
    network_id = db.Column(db.Integer, db.ForeignKey('Network.id'))

class VirtualMachine(db.Model):
    __tablename__ = 'VirtualMachine'
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(64))
    responsible_person = db.Column(db.String(64))
    machine_name = db.Column(db.String(64))
    hostname = db.Column(db.String(64))
    operating_system = db.Column(db.String(64))
    storage = db.Column(db.String(64))
    ram = db.Column(db.String(64))
    cpu = db.Column(db.String(64))
    network = db.Column(db.String(64))
    server_id = db.Column(db.Integer, db.ForeignKey('Server.id'))
    network_id = db.Column(db.Integer, db.ForeignKey('Network.id'))
<commit_msg>Serializer for NetDevicePorts model<commit_after>from app import db

class NetDevice(db.Model):
    __tablename__ = 'NetDevice'
    id = db.Column(db.Integer, primary_key=True)
    vendor = db.Column(db.String(16))
    device_type = db.Column(db.String(8))
    serial_number = db.Column(db.String(64))
    management_ip = db.Column(db.String(32))
    device_ports = db.relationship('NetDevicePorts', backref='device', lazy='dynamic')

    @property
    def serialize(self):
        return {
            'id': self.id,
            'vendor': self.vendor,
            'device_type': self.device_type,
            'serial_number': self.serial_number,
            'management_ip': self.management_ip,
        }

class NetDevicePorts(db.Model):
    __tablename__ = 'NetDevicePorts'
    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('NetDevice.id'))
    connected_to = db.Column(db.String(64))
    vlan = db.Column(db.Integer)
    ip = db.Column(db.String(32))

    @property
    def serialize(self):
        return {
            'id': self.id,
            'device_id': self.device_id,
            'connected_to': self.connected_to,
            'vlan': self.vlan,
            'ip': self.ip,
        }

class IpAddress(db.Model):
    __tablename__ = 'IpAddress'
    id = db.Column(db.Integer, primary_key=True)
    ip = db.Column(db.String(32))
    network_id = db.Column(db.Integer, db.ForeignKey('Network.id'))

class Network(db.Model):
    __tablename__ = 'Network'
    id = db.Column(db.Integer, primary_key=True)
    subnet = db.Column(db.String(24))
    vlan = db.Column(db.Integer)
    ip_networks = db.relationship('IpAddress', backref='network_ip', lazy='dynamic')
    server_networks = db.relationship('Server', backref='network_server', lazy='dynamic')
    vm_networks = db.relationship('VirtualMachine', backref='network_vms', lazy='dynamic')

class PatchPanel(db.Model):
    __tablename__ = 'PatchPanel'
    patch_id = db.Column(db.String(16), primary_key=True)
    description = db.Column(db.String(64))
    connected_to = db.Column(db.String(64))

class Server(db.Model):
    __tablename__ = 'Server'
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(64))
    serial_number = db.Column(db.String(64))
    rack = db.Column(db.String(64))
    unit = db.Column(db.Integer)
    machine_name = db.Column(db.String(64))
    hostname = db.Column(db.String(64))
    vendor = db.Column(db.String(16))
    operating_system = db.Column(db.String(64))
    storage = db.Column(db.String(64))
    ram = db.Column(db.String(64))
    cpu = db.Column(db.String(64))
    network = db.Column(db.String(64))
    server_vms = db.relationship('VirtualMachine', backref='server', lazy='dynamic')
    network_id = db.Column(db.Integer, db.ForeignKey('Network.id'))

class VirtualMachine(db.Model):
    __tablename__ = 'VirtualMachine'
    id = db.Column(db.Integer, primary_key=True)
    description = db.Column(db.String(64))
    responsible_person = db.Column(db.String(64))
    machine_name = db.Column(db.String(64))
    hostname = db.Column(db.String(64))
    operating_system = db.Column(db.String(64))
    storage = db.Column(db.String(64))
    ram = db.Column(db.String(64))
    cpu = db.Column(db.String(64))
    network = db.Column(db.String(64))
    server_id = db.Column(db.Integer, db.ForeignKey('Server.id'))
    network_id = db.Column(db.Integer, db.ForeignKey('Network.id'))
<|endoftext|>


<commit_before>#!/usr/bin/env python3.6
"""
Write JavaScript code to be pasted into a Google Sheet to draw a calendar.
"""

import csv
import datetime
import itertools
import sys

class BaseCalendar:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.width = 12 * (end - start + 1)

    def column(self, year, month):
        return (year - self.start) * 12 + month - 1

    def bar(self, name, start, end=None, length=None, **kwargs):
        istart = self.column(*start)
        if length is None:
            iend = self.column(*end)
        else:
            iend = istart + length - 1
        if istart >= self.width:
            return  # bar is entirely in the future.
        if iend < 0:
            return  # bar is entirely in the past.
        istart = max(0, istart)
        iend = min(self.width - 1, iend)
        self.rawbar(istart, iend, name, **kwargs)

class GsheetCalendar(BaseCalendar):
    def __init__(self, start, end):
        super().__init__(start, end)
        self.currow = 1
        self.cycling = None
        self.prologue()

    def prologue(self):
        print(f"""\
            function makeBarCalendar() {{
            var sheet = SpreadsheetApp.getActiveSheet();
            sheet.getDataRange().deleteCells(SpreadsheetApp.Dimension.ROWS);
            """)

    def epilog(self):
        print(f"""\
            range = sheet.getDataRange();
            sheet.setColumnWidths(range.getColumn(), range.getWidth(), 12);
            sheet.setRowHeights(range.getRow(), range.getHeight(), 18);
            range.setFontSize(9);

            var keepRows = 10;
            var tooMany = sheet.getMaxRows() - range.getLastRow() - keepRows;
            if (tooMany > 0) {{
                sheet.deleteRows(range.getLastRow() + keepRows + 1, tooMany);
            }}
            var keepCols = 1;
            var tooMany = sheet.getMaxColumns() - range.getLastColumn() - keepCols;
            if (tooMany > 0) {{
                sheet.deleteColumns(range.getLastColumn() + keepCols + 1, tooMany);
            }}

            for (var c = 12; c <= range.getLastColumn(); c += 12) {{
                sheet.getRange(1, c, sheet.getMaxRows(), 1)
                    .setBorder(null, null, null, true, null, null, "black", null);
            }}

            }}
            """)

    def years_months(self):
        yearrow = self.currow
        monthrow = self.currow + 1
        self.currow += 2

        print(f"""\
            sheet.insertColumns(1, {(self.end - self.start + 1) * 12});
            """)

        for year in range(self.start, self.end+1):
            iyear = self.column(year, 1) + 1
            print(f"""\
                sheet.getRange({yearrow}, {iyear}, 1, 12)
                    .merge()
                    .setBorder(null, null, null, true, null, null, "black", null)
                    .setValue("{year}");
                for (m = 0; m < 12; m++) {{
                    sheet.getRange({monthrow}, {iyear}+m).setValue("JFMAMJJASOND"[m]);
                }}
                """);
        print(f"""\
            sheet.getRange({yearrow}, 1, 1, {self.width})
                .setFontWeight("bold")
                .setHorizontalAlignment("center");
            sheet.getRange({monthrow}, 1, 1, {self.width})
                .setHorizontalAlignment("center");
            """);
        print(f"""\
            var rules = sheet.getConditionalFormatRules();
            rules.push(
            SpreadsheetApp.newConditionalFormatRule()
                .whenFormulaSatisfied("=(year(now())-$A$1)*12+1 = column()")
                .setBackground("#E9CECE")
                .setRanges([sheet.getRange({yearrow}, 1, 1, {self.width})])
                .build()
            );
            rules.push(
            SpreadsheetApp.newConditionalFormatRule()
                .whenFormulaSatisfied("=(year(now())-$A$1)*12 + (month(now())) = column()")
                .setBackground("#E9CECE")
                .setRanges([sheet.getRange({monthrow}, 1, 1, {self.width})])
                .build()
            );
            sheet.setConditionalFormatRules(rules);
            """)

    def rawbar(self, istart, iend, name, color=None, text_color=None, current=False):
        formatting = ""
        if color:
            formatting += f""".setBackground({color!r})"""
        if text_color:
            formatting += f""".setFontColor({text_color!r})"""
        if current:
            formatting += f""".setBorder(true, true, true, true, null, null, "black", SpreadsheetApp.BorderStyle.SOLID_MEDIUM)"""
            formatting += f""".setFontWeight("bold")"""
        print(f"""\
            sheet.getRange({self.currow}, {istart + 1}, 1, {iend - istart + 1})
                .merge()
                {formatting}
                .setValue({name!r});
            """)
        self.next_bar()

    def set_cycling(self, cycling):
        if cycling:
            self.top_cycling_row = self.currow
        else:
            self.currow = self.top_cycling_row + self.cycling
        self.cycling = cycling

    def next_bar(self):
        self.currow += 1
        if self.cycling:
            if self.currow >= self.top_cycling_row + self.cycling:
                self.currow = self.top_cycling_row

    def text_line(self, text=""):
        print(f"""\
            sheet.getRange({self.currow}, 1).setValue({text!r})
            """)
        self.currow += 1

    def freeze_here(self):
        print(f"""\
            sheet.setFrozenRows({self.currow - 1});
            """)

    def write(self):
        self.epilog()

# Options
START_YEAR = 2016
END_YEAR = 2024
LTS_ONLY = True

CURRENT = {
    "Open edX": "Ironwood",
    "Python": "2.7",
    "Django": "1.11",
    "Ubuntu": "16.04",
    "Node": "10.x",
    "Mongo": "3.2",
}

cal = GsheetCalendar(START_YEAR, END_YEAR)
cal.years_months()

# Open edX releases
cal.set_cycling(3)
names = [
    ('Aspen', 2014, 10),
    ('Birch', 2015, 2),
    ('Cypress', 2015, 8),
    ('Dogwood', 2016, 2),
    ('Eucalyptus', 2016, 8),
    ('Ficus', 2017, 2),
    ('Ginkgo', 2017, 8),
    ('Hawthorn', 2018, 8),
    ('Ironwood', 2019, 3),
    ('Juniper', 2019, 10),
    ]
future = ['Koa', 'Lilac', 'Maple'] + list('NOPQRSTUVWXYZ')
releases = list(itertools.chain(names, [(name, None, None) for name in future]))
last = (None, None)
for (name, year, month), (_, nextyear, nextmonth) in zip(releases, releases[1:]):
    if year is None:
        year, month = last
        month += 6
        yearplus, month = divmod(month, 12)
        year += yearplus
    if nextyear is None:
        length = 6
    else:
        length = (nextyear * 12 + nextmonth) - (year * 12 + month)
    cal.bar(name, start=(year, month), length=length, color="#fce5cd", current=(name==CURRENT["Open edX"]))
    last = (year, month)

cal.set_cycling(None)
cal.freeze_here()
cal.text_line("(this calendar is part of OEP-10, please don't change it without considering the impact there.)")

# Django releases
django_releases = [
    ('1.8', 2015, 4, True),
    ('1.9', 2016, 1, False),
    ('1.10', 2016, 8, False),
    ('1.11', 2017, 4, True),
    ('2.0', 2018, 1, False),
    ('2.1', 2018, 8, False),
    ('2.2', 2019, 4, True),
    ('3.0', 2020, 1, False),
    ('3.1', 2020, 8, False),
    ('3.2', 2021, 4, True),
    ('4.0', 2022, 1, False),
]
for name, year, month, lts in django_releases:
    if LTS_ONLY and not lts:
        continue
    length = 3*12 if lts else 16
    color = "#44b78b" if lts else "#c9f0df"
    cal.bar(f"Django {name}", start=(year, month), length=length, color=color, current=(name==CURRENT["Django"]))

# Python releases
python_releases = [
    ('2.7', 2010, 7, 2019, 12),
    ('3.5', 2015, 9, 2020, 9),          # https://www.python.org/dev/peps/pep-0478/
    ('3.6', 2016, 12, 2021, 12),        # https://www.python.org/dev/peps/pep-0494/
    ('3.7', 2018, 6, 2023, 6),          # https://www.python.org/dev/peps/pep-0537/
    ('3.8', 2019, 10, 2024, 10),        # https://www.python.org/dev/peps/pep-0569/
    ('3.9', 2020, 10, 2025, 10),        # https://www.python.org/dev/peps/pep-0596/
]
for name, syear, smonth, eyear, emonth in python_releases:
    cal.bar(f"Python {name}", start=(syear, smonth), end=(eyear, emonth), color="#ffd545", current=(name==CURRENT["Python"]))

# Ubuntu releases
for year, month in itertools.product(range(16, 23), [4, 10]):
    name = "{:d}.{:02d}".format(year, month)
    lts = (year % 2 == 0) and (month == 4)
    if LTS_ONLY and not lts:
        continue
    length = 5*12 if lts else 9
    color = "#E95420" if lts else "#F4AA90"     # http://design.ubuntu.com/brand/colour-palette
    cal.bar(f"Ubuntu {name}", (2000+year, month), length=length, color=color, text_color="white", current=(name==CURRENT["Ubuntu"]))

# Node releases: https://github.com/nodejs/Release
node_releases = [
    ('6.x', 2016, 4, 2019, 4),
    ('8.x', 2017, 5, 2019, 12),
    ('10.x', 2018, 4, 2021, 4),
    ('12.x', 2019, 4, 2022, 4),
    ('14.x', 2020, 4, 2023, 4),
]
for name, syear, smonth, eyear, emonth in node_releases:
    cal.bar(f"Node {name}", start=(syear, smonth), end=(eyear, emonth), color="#2f6c1b", text_color="white", current=(name==CURRENT["Node"]))

# Mongo releases: https://www.mongodb.com/support-policy (search for MongoDB Server)
mongo_releases = [
    #('3.0', 2015, 3, 2018, 2),
    ('3.2', 2015, 12, 2018, 9),
    ('3.4', 2016, 11, 2020, 1),
    ('3.6', 2017, 11, 3000, 1),
    ('4.0', 2018, 6, 3000, 1),
    #('4.2', 2019, 8, 3000, 1),
]
for name, syear, smonth, eyear, emonth in mongo_releases:
    cal.bar(f"Mongo {name}", start=(syear, smonth), end=(eyear, emonth), color="#4da65a", current=(name==CURRENT["Mongo"]))

cal.write()
<commit_msg>Draw indefinite ends differently<commit_after>#!/usr/bin/env python3.6
"""
Write JavaScript code to be pasted into a Google Sheet to draw a calendar.
"""

import colorsys
import csv
import datetime
import itertools
import sys

def css_to_rgb(hex):
    assert hex[0] == "#"
    return [int(h, 16)/255 for h in [hex[1:3], hex[3:5], hex[5:7]]]

def rgb_to_css(r, g, b):
    return "#" + "".join(f"{int(v*255):02x}" for v in (r, g, b))

def lighten(css, amount=0.5):
    """Make a CSS color some amount lighter."""
    h, l, s = colorsys.rgb_to_hls(*css_to_rgb(css))
    lighter = colorsys.hls_to_rgb(h, l + (1 - l) * amount, s)
    return rgb_to_css(*lighter)

class BaseCalendar:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.width = 12 * (end - start + 1)

    def column(self, year, month):
        return (year - self.start) * 12 + month - 1

    def bar(self, name, start, end=None, length=None, **kwargs):
        istart = self.column(*start)
        if length is None:
            iend = self.column(*end)
        else:
            iend = istart + length - 1
        if istart >= self.width:
            return  # bar is entirely in the future.
        if iend < 0:
            return  # bar is entirely in the past.
        istart = max(0, istart)
        iend = min(self.width - 1, iend)
        if end and end[0] == 3000:
            kwargs.update(indefinite=True)
        self.rawbar(istart, iend, name, **kwargs)

class GsheetCalendar(BaseCalendar):
    def __init__(self, start, end):
        super().__init__(start, end)
        self.currow = 1
        self.cycling = None
        self.prologue()

    def prologue(self):
        print(f"""\
            function makeBarCalendar() {{
            var sheet = SpreadsheetApp.getActiveSheet();
            sheet.getDataRange().deleteCells(SpreadsheetApp.Dimension.ROWS);
            """)

    def epilog(self):
        print(f"""\
            range = sheet.getDataRange();
            sheet.setColumnWidths(range.getColumn(), range.getWidth(), 12);
            sheet.setRowHeights(range.getRow(), range.getHeight(), 18);
            range.setFontSize(9);

            var keepRows = 10;
            var tooMany = sheet.getMaxRows() - range.getLastRow() - keepRows;
            if (tooMany > 0) {{
                sheet.deleteRows(range.getLastRow() + keepRows + 1, tooMany);
            }}
            var keepCols = 1;
            var tooMany = sheet.getMaxColumns() - range.getLastColumn() - keepCols;
            if (tooMany > 0) {{
                sheet.deleteColumns(range.getLastColumn() + keepCols + 1, tooMany);
            }}

            for (var c = 12; c <= range.getLastColumn(); c += 12) {{
                sheet.getRange(1, c, sheet.getMaxRows(), 1)
                    .setBorder(null, null, null, true, null, null, "black", null);
            }}

            }}
            """)

    def years_months(self):
        yearrow = self.currow
        monthrow = self.currow + 1
        self.currow += 2

        print(f"""\
            sheet.insertColumns(1, {(self.end - self.start + 1) * 12});
            """)

        for year in range(self.start, self.end+1):
            iyear = self.column(year, 1) + 1
            print(f"""\
                sheet.getRange({yearrow}, {iyear}, 1, 12)
                    .merge()
                    .setBorder(null, null, null, true, null, null, "black", null)
                    .setValue("{year}");
                for (m = 0; m < 12; m++) {{
                    sheet.getRange({monthrow}, {iyear}+m).setValue("JFMAMJJASOND"[m]);
                }}
                """);
        print(f"""\
            sheet.getRange({yearrow}, 1, 1, {self.width})
                .setFontWeight("bold")
                .setHorizontalAlignment("center");
            sheet.getRange({monthrow}, 1, 1, {self.width})
                .setHorizontalAlignment("center");
            """);
        print(f"""\
            var rules = sheet.getConditionalFormatRules();
            rules.push(
            SpreadsheetApp.newConditionalFormatRule()
                .whenFormulaSatisfied("=(year(now())-$A$1)*12+1 = column()")
                .setBackground("#E9CECE")
                .setRanges([sheet.getRange({yearrow}, 1, 1, {self.width})])
                .build()
            );
            rules.push(
            SpreadsheetApp.newConditionalFormatRule()
                .whenFormulaSatisfied("=(year(now())-$A$1)*12 + (month(now())) = column()")
                .setBackground("#E9CECE")
                .setRanges([sheet.getRange({monthrow}, 1, 1, {self.width})])
                .build()
            );
            sheet.setConditionalFormatRules(rules);
            """)

    def rawbar(self, istart, iend, name, color=None, text_color=None, current=False, indefinite=False):
        formatting = ""
        if color:
            formatting += f""".setBackground({color!r})"""
        if text_color:
            formatting += f""".setFontColor({text_color!r})"""
        if current:
            formatting += f""".setBorder(true, true, true, true, null, null, "black", SpreadsheetApp.BorderStyle.SOLID_MEDIUM)"""
            formatting += f""".setFontWeight("bold")"""
        if indefinite:
            iend = self.width - 24
        print(f"""\
            sheet.getRange({self.currow}, {istart + 1}, 1, {iend - istart + 1})
                .merge()
                {formatting}
                .setValue({name!r});
            """)
        if indefinite:
            for i in range(4):
                bg = lighten(color, amount=(i+1)/5)
                print(f"""\
                    sheet.getRange({self.currow}, {self.width - 22 + i * 3}, 1, 3)
                        .merge()
                        .setBackground({bg!r});
                    """)
            print(f"""\
                sheet.getRange({self.currow}, {self.width - 10}, 1, 1)
                    .setValue("(indefinite end)");
                """)
        self.next_bar()

    def set_cycling(self, cycling):
        if cycling:
            self.top_cycling_row = self.currow
        else:
            self.currow = self.top_cycling_row + self.cycling
        self.cycling = cycling

    def next_bar(self):
        self.currow += 1
        if self.cycling:
            if self.currow >= self.top_cycling_row + self.cycling:
                self.currow = self.top_cycling_row

    def text_line(self, text=""):
        print(f"""\
            sheet.getRange({self.currow}, 1).setValue({text!r})
            """)
        self.currow += 1

    def freeze_here(self):
        print(f"""\
            sheet.setFrozenRows({self.currow - 1});
            """)

    def write(self):
        self.epilog()

# Options
START_YEAR = 2016
END_YEAR = 2024
LTS_ONLY = True

CURRENT = {
    "Open edX": "Ironwood",
    "Python": "2.7",
    "Django": "1.11",
    "Ubuntu": "16.04",
    "Node": "10.x",
    "Mongo": "3.2",
}

cal = GsheetCalendar(START_YEAR, END_YEAR)
cal.years_months()

# Open edX releases
cal.set_cycling(3)
names = [
    ('Aspen', 2014, 10),
    ('Birch', 2015, 2),
    ('Cypress', 2015, 8),
    ('Dogwood', 2016, 2),
    ('Eucalyptus', 2016, 8),
    ('Ficus', 2017, 2),
    ('Ginkgo', 2017, 8),
    ('Hawthorn', 2018, 8),
    ('Ironwood', 2019, 3),
    ('Juniper', 2019, 10),
    ]
future = ['Koa', 'Lilac', 'Maple'] + list('NOPQRSTUVWXYZ')
releases = list(itertools.chain(names, [(name, None, None) for name in future]))
last = (None, None)
for (name, year, month), (_, nextyear, nextmonth) in zip(releases, releases[1:]):
    if year is None:
        year, month = last
        month += 6
        yearplus, month = divmod(month, 12)
        year += yearplus
    if nextyear is None:
        length = 6
    else:
        length = (nextyear * 12 + nextmonth) - (year * 12 + month)
    cal.bar(name, start=(year, month), length=length, color="#fce5cd", current=(name==CURRENT["Open edX"]))
    last = (year, month)

cal.set_cycling(None)
cal.freeze_here()
cal.text_line("(this calendar is part of OEP-10, please don't change it without considering the impact there.)")

# Django releases
django_releases = [
    ('1.8', 2015, 4, True),
    ('1.9', 2016, 1, False),
    ('1.10', 2016, 8, False),
    ('1.11', 2017, 4, True),
    ('2.0', 2018, 1, False),
    ('2.1', 2018, 8, False),
    ('2.2', 2019, 4, True),
    ('3.0', 2020, 1, False),
    ('3.1', 2020, 8, False),
    ('3.2', 2021, 4, True),
    ('4.0', 2022, 1, False),
]
for name, year, month, lts in django_releases:
    if LTS_ONLY and not lts:
        continue
    length = 3*12 if lts else 16
    color = "#44b78b" if lts else "#c9f0df"
    cal.bar(f"Django {name}", start=(year, month), length=length, color=color, current=(name==CURRENT["Django"]))

# Python releases
python_releases = [
    ('2.7', 2010, 7, 2019, 12),
    ('3.5', 2015, 9, 2020, 9),          # https://www.python.org/dev/peps/pep-0478/
    ('3.6', 2016, 12, 2021, 12),        # https://www.python.org/dev/peps/pep-0494/
    ('3.7', 2018, 6, 2023, 6),          # https://www.python.org/dev/peps/pep-0537/
    ('3.8', 2019, 10, 2024, 10),        # https://www.python.org/dev/peps/pep-0569/
    ('3.9', 2020, 10, 2025, 10),        # https://www.python.org/dev/peps/pep-0596/
]
for name, syear, smonth, eyear, emonth in python_releases:
    cal.bar(f"Python {name}", start=(syear, smonth), end=(eyear, emonth), color="#ffd545", current=(name==CURRENT["Python"]))

# Ubuntu releases
for year, month in itertools.product(range(16, 23), [4, 10]):
    name = "{:d}.{:02d}".format(year, month)
    lts = (year % 2 == 0) and (month == 4)
    if LTS_ONLY and not lts:
        continue
    length = 5*12 if lts else 9
    color = "#E95420" if lts else "#F4AA90"     # http://design.ubuntu.com/brand/colour-palette
    cal.bar(f"Ubuntu {name}", (2000+year, month), length=length, color=color, text_color="white", current=(name==CURRENT["Ubuntu"]))

# Node releases: https://github.com/nodejs/Release
node_releases = [
    ('6.x', 2016, 4, 2019, 4),
    ('8.x', 2017, 5, 2019, 12),
    ('10.x', 2018, 4, 2021, 4),
    ('12.x', 2019, 4, 2022, 4),
    ('14.x', 2020, 4, 2023, 4),
]
for name, syear, smonth, eyear, emonth in node_releases:
    cal.bar(f"Node {name}", start=(syear, smonth), end=(eyear, emonth), color="#2f6c1b", text_color="white", current=(name==CURRENT["Node"]))

# Mongo releases: https://www.mongodb.com/support-policy (search for MongoDB Server)
mongo_releases = [
    #('3.0', 2015, 3, 2018, 2),
    ('3.2', 2015, 12, 2018, 9),
    ('3.4', 2016, 11, 2020, 1),
    ('3.6', 2017, 11, 3000, 1),
    ('4.0', 2018, 6, 3000, 1),
    #('4.2', 2019, 8, 3000, 1),
]
for name, syear, smonth, eyear, emonth in mongo_releases:
    cal.bar(f"Mongo {name}", start=(syear, smonth), end=(eyear, emonth), color="#4da65a", current=(name==CURRENT["Mongo"]))

cal.write()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

from __future__ import unicode_literals

"""Module: barcode.ean

:Provided barcodes: EAN-13, EAN-8, JAN
"""

from barcode.base import Barcode
from barcode.charsets import ean as _ean
from barcode.errors import *

# Python 3
try:
    reduce
except NameError:
    from functools import reduce

# EAN13 Specs (all sizes in mm)
SIZES = dict(SC0=0.27, SC1=0.297, SC2=0.33, SC3=0.363, SC4=0.396, SC5=0.445,
             SC6=0.495, SC7=0.544, SC8=0.61, SC9=0.66)

class EuropeanArticleNumber13(Barcode):
    """Initializes EAN13 object.

    :parameters:
        ean : String
            The ean number as string.
        writer : barcode.writer Instance
            The writer to render the barcode (default: SVGWriter).
    """

    name = 'EAN-13'

    digits = 12

    def __init__(self, ean, writer=None):
        ean = ean[:self.digits]
        if not ean.isdigit():
            raise IllegalCharacterError('EAN code can only contain numbers.')
        self.ean = ean
        self.ean = '{0}{1}'.format(ean, self.calculate_checksum())
        self.writer = writer or Barcode.default_writer()

    def __unicode__(self):
        return self.ean

    __str__ = __unicode__

    def get_fullcode(self):
        return self.ean

    def calculate_checksum(self):
        """Calculates the checksum for EAN13-Code.

        :returns: The checksum for `self.ean`.
        :rtype: Integer
        """
        sum_ = lambda x, y: int(x) + int(y)
        evensum = reduce(sum_, self.ean[::2])
        oddsum = reduce(sum_, self.ean[1::2])
        return (10 - ((evensum + oddsum * 3) % 10)) % 10

    def build(self):
        """Builds the barcode pattern from `self.ean`.

        :returns: The pattern as string
        :rtype: String
        """
        code = _ean.EDGE[:]
        pattern = _ean.LEFT_PATTERN[int(self.ean[0])]
        for i, number in enumerate(self.ean[1:7]):
            code += _ean.CODES[pattern[i]][int(number)]
        code += _ean.MIDDLE
        for number in self.ean[7:]:
            code += _ean.CODES['C'][int(number)]
        code += _ean.EDGE
        return [code]

    def to_ascii(self):
        """Returns an ascii representation of the barcode.

        :rtype: String
        """
        code = self.build()
        for i, line in enumerate(code):
            code[i] = line.replace('1', '|').replace('0', ' ')
        return '\n'.join(code)

    def render(self, writer_options=None):
        options = dict(module_width=SIZES['SC2'])
        options.update(writer_options or {})
        return Barcode.render(self, options)

class JapanArticleNumber(EuropeanArticleNumber13):
    """Initializes JAN barcode.

    :parameters:
        jan : String
            The jan number as string.
        writer : barcode.writer Instance
            The writer to render the barcode (default: SVGWriter).
    """

    name = 'JAN'

    valid_country_codes = list(range(450, 460)) + list(range(490, 500))

    def __init__(self, jan, writer=None):
        if int(jan[:3]) not in JapanArticleNumber.valid_country_codes:
            raise WrongCountryCodeError("Country code isn't between 450-460 "
                                        "or 490-500.")
        EuropeanArticleNumber13.__init__(self, jan, writer)

class EuropeanArticleNumber8(EuropeanArticleNumber13):
    """Represents an EAN-8 barcode. See EAN13's __init__ for details.

    :parameters:
        ean : String
            The ean number as string.
        writer : barcode.writer Instance
            The writer to render the barcode (default: SVGWriter).
    """

    name = 'EAN-8'

    digits = 7

    def __init__(self, ean, writer=None):
        EuropeanArticleNumber13.__init__(self, ean, writer)

    def calculate_checksum(self):
        """Calculates the checksum for EAN8-Code.

        :returns: The checksum for `self.ean`.
        :rtype: Integer
        """
        sum_ = lambda x, y: int(x) + int(y)
        evensum = reduce(sum_, self.ean[::2])
        oddsum = reduce(sum_, self.ean[1::2])
        return 10 - ((evensum * 3 + oddsum) % 10)

    def build(self):
        """Builds the barcode pattern from `self.ean`.

        :returns: The pattern as string
        :rtype: String
        """
        code = _ean.EDGE[:]
        for number in self.ean[:4]:
            code += _ean.CODES['A'][int(number)]
        code += _ean.MIDDLE
        for number in self.ean[4:]:
            code += _ean.CODES['C'][int(number)]
        code += _ean.EDGE
        return [code]

# Shortcuts
EAN13 = EuropeanArticleNumber13
EAN8 = EuropeanArticleNumber8
JAN = JapanArticleNumber
<commit_msg>Fixed a bug in calculating checksum for EAN-8 barcodes.<commit_after># -*- coding: utf-8 -*-

from __future__ import unicode_literals

"""Module: barcode.ean

:Provided barcodes: EAN-13, EAN-8, JAN
"""

from barcode.base import Barcode
from barcode.charsets import ean as _ean
from barcode.errors import *

# Python 3
try:
    reduce
except NameError:
    from functools import reduce

# EAN13 Specs (all sizes in mm)
SIZES = dict(SC0=0.27, SC1=0.297, SC2=0.33, SC3=0.363, SC4=0.396, SC5=0.445,
             SC6=0.495, SC7=0.544, SC8=0.61, SC9=0.66)

class EuropeanArticleNumber13(Barcode):
    """Initializes EAN13 object.

    :parameters:
        ean : String
            The ean number as string.
        writer : barcode.writer Instance
            The writer to render the barcode (default: SVGWriter).
    """

    name = 'EAN-13'

    digits = 12

    def __init__(self, ean, writer=None):
        ean = ean[:self.digits]
        if not ean.isdigit():
            raise IllegalCharacterError('EAN code can only contain numbers.')
        self.ean = ean
        self.ean = '{0}{1}'.format(ean, self.calculate_checksum())
        self.writer = writer or Barcode.default_writer()

    def __unicode__(self):
        return self.ean

    __str__ = __unicode__

    def get_fullcode(self):
        return self.ean

    def calculate_checksum(self):
        """Calculates the checksum for EAN13-Code.

        :returns: The checksum for `self.ean`.
        :rtype: Integer
        """
        sum_ = lambda x, y: int(x) + int(y)
        evensum = reduce(sum_, self.ean[::2])
        oddsum = reduce(sum_, self.ean[1::2])
        return (10 - ((evensum + oddsum * 3) % 10)) % 10

    def build(self):
        """Builds the barcode pattern from `self.ean`.

        :returns: The pattern as string
        :rtype: String
        """
        code = _ean.EDGE[:]
        pattern = _ean.LEFT_PATTERN[int(self.ean[0])]
        for i, number in enumerate(self.ean[1:7]):
            code += _ean.CODES[pattern[i]][int(number)]
        code += _ean.MIDDLE
        for number in self.ean[7:]:
            code += _ean.CODES['C'][int(number)]
        code += _ean.EDGE
        return [code]

    def to_ascii(self):
        """Returns an ascii representation of the barcode.

        :rtype: String
        """
        code = self.build()
        for i, line in enumerate(code):
            code[i] = line.replace('1', '|').replace('0', ' ')
        return '\n'.join(code)

    def render(self, writer_options=None):
        options = dict(module_width=SIZES['SC2'])
        options.update(writer_options or {})
        return Barcode.render(self, options)

class JapanArticleNumber(EuropeanArticleNumber13):
    """Initializes JAN barcode.

    :parameters:
        jan : String
            The jan number as string.
        writer : barcode.writer Instance
            The writer to render the barcode (default: SVGWriter).
    """

    name = 'JAN'

    valid_country_codes = list(range(450, 460)) + list(range(490, 500))

    def __init__(self, jan, writer=None):
        if int(jan[:3]) not in JapanArticleNumber.valid_country_codes:
            raise WrongCountryCodeError("Country code isn't between 450-460 "
                                        "or 490-500.")
        EuropeanArticleNumber13.__init__(self, jan, writer)

class EuropeanArticleNumber8(EuropeanArticleNumber13):
    """Represents an EAN-8 barcode. See EAN13's __init__ for details.

    :parameters:
        ean : String
            The ean number as string.
        writer : barcode.writer Instance
            The writer to render the barcode (default: SVGWriter).
    """

    name = 'EAN-8'

    digits = 7

    def __init__(self, ean, writer=None):
        EuropeanArticleNumber13.__init__(self, ean, writer)

    def calculate_checksum(self):
        """Calculates the checksum for EAN8-Code.

        :returns: The checksum for `self.ean`.
        :rtype: Integer
        """
        sum_ = lambda x, y: int(x) + int(y)
        evensum = reduce(sum_, self.ean[::2])
        oddsum = reduce(sum_, self.ean[1::2])
        return (10 - ((evensum * 3 + oddsum) % 10)) % 10

    def build(self):
        """Builds the barcode pattern from `self.ean`.

        :returns: The pattern as string
        :rtype: String
        """
        code = _ean.EDGE[:]
        for number in self.ean[:4]:
            code += _ean.CODES['A'][int(number)]
        code += _ean.MIDDLE
        for number in self.ean[4:]:
            code += _ean.CODES['C'][int(number)]
        code += _ean.EDGE
        return [code]

# Shortcuts
EAN13 = EuropeanArticleNumber13
EAN8 = EuropeanArticleNumber8
JAN = JapanArticleNumber
<|endoftext|>


<commit_before>import tensorflow as tf
from pathlib import Path

import os
import random

from tf_trainer.common import dataset_input
from tf_trainer.common import types
from typing import List, Dict, Tuple

tf.app.flags.DEFINE_string('train_path', None,
                           'Path to the training data TFRecord file.')
tf.app.flags.DEFINE_string('dev_path', None,
                           'Path to the training data TFRecord file.')
tf.app.flags.DEFINE_string('episode_size', None,
                           'Path to the training data TFRecord file.')

class EpisodicTFRecordInput(dataset_input.DatasetInput):

  def __init__(self, train_dir, validate_dir) -> None:
    self.train_dir = train_dir
    self.validate_dir = validate_dir

  def train_input_fn(self) -> types.FeatureAndLabelTensors:
    all_episodes = self._get_randomized_episodes(self.train_dir)
    all_texts = [ep[0] for ep in all_episodes]
    all_domains = [ep[1] for ep in all_episodes]
    all_labels = [ep[2] for ep in all_episodes]
    ds = tf.data.Dataset.from_tensor_slices((all_texts, all_domains,
                                             all_labels))
    self.episode_batches_itr = ds.make_one_shot_iterator()
    return self.episode_batches_itr.get_next()

  def validate_input_fn(self) -> types.FeatureAndLabelTensors:
    pass

  def _get_randomized_episodes(self, directory: str):
    """Retrieves a list of domain specific datasets.

    Given a directory of TFRecord files, each holding data for a given domain,
    with file name "[domain].tfrecord", returns an iterator of datasets, each
    corresponding to the data for a single domain.
    """

    tfrecord_files = tf.gfile.Glob(os.path.join(directory, '*.tfrecord'))
    episodes = []
    for file_no, tfrecord_file in enumerate(tfrecord_files):
      print(f'PROCESSING FILE {file_no}: {tfrecord_file}')
      episodes.append(self._dataset_from_tfrecord_file(tfrecord_file))
    random.shuffle(episodes)
    return episodes

  def _dataset_from_tfrecord_file(
      self,
      tfrecord_file: str) -> Tuple[List[tf.Tensor], List[str], List[tf.Tensor]]:
    # The domain happens to be the stem for this dataset.
    domain = Path(tfrecord_file).stem

    def _read_tf_example(record):
      parsed = tf.parse_single_example(
          record, {
              'text': tf.FixedLenFeature([], tf.string),
              'label': tf.FixedLenFeature([], tf.int64)
          })  # type: Dict[str, types.Tensor]

      return {
          'text': parsed['text'],
          'domain': domain,
          'label': parsed['label'],
      }

    examples = list(tf.python_io.tf_record_iterator(tfrecord_file))
    random.shuffle(examples)

    datapoints = [_read_tf_example(example) for example in examples]
    texts = [dp['text'] for dp in datapoints]
    domains = [dp['domain'] for dp in datapoints]
    labels = [dp['label'] for dp in datapoints]
    return (texts, domains, labels)
<commit_msg>Fix syntax (python 3.5 compatible)<commit_after>import tensorflow as tf
from pathlib import Path

import os
import random

from tf_trainer.common import dataset_input
from tf_trainer.common import types
from typing import List, Dict, Tuple

tf.app.flags.DEFINE_string('train_path', None,
                           'Path to the training data TFRecord file.')
tf.app.flags.DEFINE_string('dev_path', None,
                           'Path to the training data TFRecord file.')
tf.app.flags.DEFINE_string('episode_size', None,
                           'Path to the training data TFRecord file.')

class EpisodicTFRecordInput(dataset_input.DatasetInput):

  def __init__(self, train_dir, validate_dir) -> None:
    self.train_dir = train_dir
    self.validate_dir = validate_dir

  def train_input_fn(self) -> types.FeatureAndLabelTensors:
    all_episodes = self._get_randomized_episodes(self.train_dir)
    all_texts = [ep[0] for ep in all_episodes]
    all_domains = [ep[1] for ep in all_episodes]
    all_labels = [ep[2] for ep in all_episodes]
    ds = tf.data.Dataset.from_tensor_slices((all_texts, all_domains,
                                             all_labels))
    self.episode_batches_itr = ds.make_one_shot_iterator()
    return self.episode_batches_itr.get_next()

  def validate_input_fn(self) -> types.FeatureAndLabelTensors:
    pass

  def _get_randomized_episodes(self, directory: str):
    """Retrieves a list of domain specific datasets.

    Given a directory of TFRecord files, each holding data for a given domain,
    with file name "[domain].tfrecord", returns an iterator of datasets, each
    corresponding to the data for a single domain.
    """

    tfrecord_files = tf.gfile.Glob(os.path.join(directory, '*.tfrecord'))
    episodes = []
    for file_no, tfrecord_file in enumerate(tfrecord_files):
      print('PROCESSING FILE {}: {}'.format(file_no, tfrecord_file))
      episodes.append(self._dataset_from_tfrecord_file(tfrecord_file))
    random.shuffle(episodes)
    return episodes

  def _dataset_from_tfrecord_file(
      self,
      tfrecord_file: str) -> Tuple[List[tf.Tensor], List[str], List[tf.Tensor]]:
    # The domain happens to be the stem for this dataset.
    domain = Path(tfrecord_file).stem

    def _read_tf_example(record):
      parsed = tf.parse_single_example(
          record, {
              'text': tf.FixedLenFeature([], tf.string),
              'label': tf.FixedLenFeature([], tf.int64)
          })  # type: Dict[str, types.Tensor]

      return {
          'text': parsed['text'],
          'domain': domain,
          'label': parsed['label'],
      }

    examples = list(tf.python_io.tf_record_iterator(tfrecord_file))
    random.shuffle(examples)

    datapoints = [_read_tf_example(example) for example in examples]
    texts = [dp['text'] for dp in datapoints]
    domains = [dp['domain'] for dp in datapoints]
    labels = [dp['label'] for dp in datapoints]
    return (texts, domains, labels)
<|endoftext|>


<commit_before>from app import db

ROLE_USER = 0
ROLE_ADMIN = 1

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    nickname = db.Column(db.String(64), index = True, unique = True)
    email = db.Column(db.String(120), index = True, unique = True)
    role = db.Column(db.SmallInteger, default = ROLE_USER)
    posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')

    def __repr__(self):
        return '<User %r>' % (self.nickname)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user_id'))

    def __repr__(self):
        return '<Post %r>' % (self.body)
<commit_msg>Fixed errant character in Post class<commit_after>from app import db

ROLE_USER = 0
ROLE_ADMIN = 1

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    nickname = db.Column(db.String(64), index = True, unique = True)
    email = db.Column(db.String(120), index = True, unique = True)
    role = db.Column(db.SmallInteger, default = ROLE_USER)
    posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')

    def __repr__(self):
        return '<User %r>' % (self.nickname)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    body = db.Column(db.String(140))
    timestamp = db.Column(db.DateTime)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '<Post %r>' % (self.body)
<|endoftext|>