<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.13.0');
		this.setClientTag('node:20-12-31');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.13.0');
		this.setClientTag('node:21-01-01');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.7.0');
		this.setClientTag('node:20-07-24');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.7.0');
		this.setClientTag('node:20-07-25');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:17-07-10');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:17-07-11');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.13.0');
		this.setClientTag('node:22-09-03');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('18.13.0');
		this.setClientTag('node:22-09-04');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>usePlugin("@nomiclabs/buidler-truffle5");

module.exports = {
  solc: { version: "0.5.5" },
  networks: {
    'development': {
      gas: 7000000
    }
  },
  mocha: {
    reporter: 'eth-gas-reporter',
  }
};<commit_msg>Add url to buidler config<commit_after>usePlugin("@nomiclabs/buidler-truffle5");

module.exports = {
  solc: { version: "0.5.5" },
  networks: {
    development: {
      gas: 7000000,
      url: "http://localhost:8545"
    }
  },
  mocha: {
    reporter: "eth-gas-reporter"
  }
};
<|endoftext|>


<commit_before>var keystone = require('keystone'),
    Types = keystone.Field.Types;

// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
    autokey: { path: 'key', from: 'slug', unique: true },
    defaultSort: '-date'
});

// Create fields
InternalNotes.add( 'Target', {
    target: { type: Types.Select, label: 'target', options: 'child, family, social worker', initial: true },
    child: { type: Types.Relationship, label: 'child', ref: 'Child', dependsOn: { target: 'child' }, initial: true },
    family: { type: Types.Relationship, label: 'family', ref: 'Family', dependsOn: { target: 'family' }, filters: { isActive: true }, initial: true },
    socialWorker: { type: Types.Relationship, label: 'social worker', ref: 'Social Worker', dependsOn: { target: 'social worker' }, filters: { isActive: true }, initial: true }

}, 'Note Details', {

    date: { type: Types.Date, label: 'note date', format: 'MM/DD/YYYY', default: Date.now, required: true, noedit: true },
    employee: { type: Types.Relationship, label: 'note creator', ref: 'Admin', filters: { isActive: true }, required: true, noedit: true, initial: true },
    note: { type: Types.Textarea, label: 'note', required: true, initial: true }

});

// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date|10%, child|10%, family|10%, socialWorker|10% note|60%';
InternalNotes.register();<commit_msg>fixes internal notes default column display<commit_after>var keystone = require('keystone'),
    Types = keystone.Field.Types;

// Create model. Additional options allow menu name to be used what auto-generating URLs
var InternalNotes = new keystone.List('Internal Note', {
    autokey: { path: 'key', from: 'slug', unique: true },
    defaultSort: '-date'
});

// Create fields
InternalNotes.add( 'Target', {
    target: { type: Types.Select, label: 'target', options: 'child, family, social worker', initial: true },
    child: { type: Types.Relationship, label: 'child', ref: 'Child', dependsOn: { target: 'child' }, initial: true },
    family: { type: Types.Relationship, label: 'family', ref: 'Family', dependsOn: { target: 'family' }, filters: { isActive: true }, initial: true },
    socialWorker: { type: Types.Relationship, label: 'social worker', ref: 'Social Worker', dependsOn: { target: 'social worker' }, filters: { isActive: true }, initial: true }

}, 'Note Details', {

    date: { type: Types.Date, label: 'note date', format: 'MM/DD/YYYY', default: Date.now, required: true, noedit: true },
    employee: { type: Types.Relationship, label: 'note creator', ref: 'Admin', filters: { isActive: true }, required: true, noedit: true, initial: true },
    note: { type: Types.Textarea, label: 'note', required: true, initial: true }

});

// Define default columns in the admin interface and register the model
InternalNotes.defaultColumns = 'date|10%, child|10%, family|10%, socialWorker|10%, note|50%';
InternalNotes.register();<|endoftext|>


<commit_before>var keystone = require('keystone');
var transform = require('model-transform');

var PostCategory = new keystone.List('PostCategory', {
	autokey: { from: 'name', path: 'key', unique: true },
	sortable: true,
});

PostCategory.add({
	name: { type: String, required: true },
});

PostCategory.relationship({ ref: 'Post', path: 'categories' });

transform.toJSON(PostCategory);
PostCategory.register();
<commit_msg>Fixing PostCategories Relationship<commit_after>var keystone = require('keystone');
var transform = require('model-transform');

var PostCategory = new keystone.List('PostCategory', {
	autokey: { from: 'name', path: 'key', unique: true },
	sortable: true,
});

PostCategory.add({
	name: { type: String, required: true },
});

PostCategory.relationship({ ref: 'Post', refPath: 'categories' });

transform.toJSON(PostCategory);
PostCategory.register();
<|endoftext|>


<commit_before>/**
 * Created by Administrator on 2015/8/31.
 */
var url = require('url');
var settings = require("./settings");
//数据库操作对象
var DbOpt = require("../Dbopt");

//管理员对象
var AdminUser = require("../AdminUser");
//管理员用户组对象
var AdminGroup = require("../AdminGroup");
// 文档对象
var Content = require("../Content");
//数据操作日志
var DataOptionLog = require("../DataOptionLog");
//文章类别对象
var ContentCategory = require("../ContentCategory");
//文章标签对象
var ContentTags = require("../ContentTags");
//文章模板对象
var ContentTemplate = require("../ContentTemplate");
var TemplateItems = require("../TemplateItems");
//文章留言对象
var Message = require("../Message");
//注册用户对象
var User = require("../User");
//广告对象
var Ads = require("../Ads");
//文件对象
var Files = require("../Files");
//系统日志对象
var SystemOptionLog = require("../SystemOptionLog");
//消息对象
var Notify = require("../Notify");
var UserNotify = require("../UserNotify");
var shortid = require('shortid');
//数据校验
var validator = require("validator");
var system = require('../../util/system');
var request = require('request');

var config = require('../../config');
var express = require('express');

var qiniu = require('qiniu');
var app = express();

app.get('/uptoken', function(req, res, next) {
    var token = uptoken.token();
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        console.log(token);
        console.log(".....................");
        res.json({
            uptoken: token
        });
    }
});

qiniu.conf.ACCESS_KEY = config.ACCESS_KEY;
qiniu.conf.SECRET_KEY = config.SECRET_KEY;

var uptoken = new qiniu.rs.PutPolicy(config.Bucket_Name);

var adminFunc = {

    siteInfos : function (description) {

        return {
            title : settings.SITETITLE,
            description : description,
            version : settings.SITEVERSION
        }
    },

    getMessageList : function(){
        return Message.find({}).limit(10).sort({'date' : -1}).populate('author').populate('replyAuthor').populate('adminAuthor').exec();
    },

    getClienIp : function(req){

        return req.headers['x-forwarded-for'] ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress;

    },

    setMainInfos : function(req, res){
        return res.json({
            adminUserCount : AdminUser.count({}),
            regUsersCount : User.count({}),
            contentsCount : Content.count({}),
            msgCount : Message.count({}),
            msgList : this.getMessageList(),
            regUsers : User.find({}).limit(15).sort({'date' : -1})
        })
    },

    setPageInfoTest : function(req,res,module,currentLink){

        var searchKey = '';
        //area是为了独立查询一个表其中的部分数据而设立的参数
        var area = '';
        if(req.url){
            var params = url.parse(req.url,true);
            searchKey = params.query.searchKey;
            area = req.query.area;
        }

            var token = uptoken.token();
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        console.log(token);
        console.log(".....................");
        res.json({
            uptoken: token
        });
    }

        return {
            domain: config.Domain,
            uptoken_url: config.Uptoken_Url,
            siteInfo : this.siteInfos(module[1]),
            bigCategory : module[0],
            searchKey : searchKey,
            area : area,
            currentLink : currentLink
        }

    },

    setPageInfo : function(req,res,module,currentLink){

        var searchKey = '';
        //area是为了独立查询一个表其中的部分数据而设立的参数
        var area = '';
        if(req.url){
            var params = url.parse(req.url,true);
            searchKey = params.query.searchKey;
            area = req.query.area;
        }

        return {
            domain: config.Domain,
            uptoken_url: config.Uptoken_Url,
            siteInfo : this.siteInfos(module[1]),
            bigCategory : module[0],
            searchKey : searchKey,
            area : area,
            currentLink : currentLink,
            layout : 'manage/public/adminTemp'
        }

    },

    setDataForInfo : function(infoType,infoContent){

        return {
            siteInfo : this.siteInfos('系统操作提示'),
            bigCategory : 'noticePage',
            infoType : infoType,
            infoContent : infoContent,
            area : '',
            layout: 'manage/public/adminTemp'
        }

    },

    setQueryByArea : function(req,keyPr,targetObj,area){
        var newKeyPr = keyPr;
        if(targetObj == UserNotify){
            if(area && area == 'systemNotice'){
                newKeyPr = {'systemUser' : req.session.adminUserInfo._id };
            }
        }else if(targetObj == Notify){
            if(area && area == 'announce'){
                newKeyPr = {'type' : '1' };
            }
        }
        return newKeyPr;
    },

    getAdminNotices : function (req,res,callBack) {

        UserNotify.find({'systemUser':req.session.adminUserInfo._id,'isRead':false})
            .populate('user').populate('notify').exec(function(err,docs){
            if(err){
                res.end(err);
            }else{
                var regNoticeArr = [];
                var msgNoticeArr = [];
                if(docs.length >0){
                    for(var i=0;i<docs.length;i++){
                        var item = docs[i];
                        if(item.notify && item.notify.action == 'reg'){
                            regNoticeArr.push(item)
                        }else if(item.notify && item.notify.action == 'msg'){
                            msgNoticeArr.push(item)
                        }
                    }
                };
                var noticeObj = {
                    regNotices : regNoticeArr,
                    msgNotices : msgNoticeArr,
                    totalCount : regNoticeArr.length + msgNoticeArr.length
                };
                callBack(noticeObj);
            }
        });

    },

    delNotifiesById : function(req,res,nid){
        if(shortid.isValid(nid)){
            Notify.delOneNotify(res,nid,function(){
                var notifyQuery = {'notify': { $regex: new RegExp(nid, 'i') }};
                UserNotify.remove(notifyQuery,function(err){
                    if(err){
                        res.end(err);
                    }
                });
            });
        }else{
            res.end(settings.system_illegal_param);
        }

    },

    getTargetObj : function(currentPage){
        var targetObj;
        if(currentPage.indexOf(settings.ADMINUSERLIST[0]) >=0 ){
            targetObj = AdminUser;
        }else if(currentPage.indexOf(settings.ADMINGROUPLIST[0]) >=0 ){
            targetObj = AdminGroup;
        }else if(currentPage.indexOf(settings.ADSLIST[0]) >=0 ){
            targetObj = Ads;
        }else if(currentPage.indexOf(settings.FILESLIST[0]) >=0 ){
            targetObj = Files;
        }else if(currentPage.indexOf(settings.BACKUPDATA[0]) >=0 ){
            targetObj = DataOptionLog;
        }else if(currentPage.indexOf(settings.SYSTEMLOGS[0]) >=0 ){
            targetObj = SystemOptionLog;
        }else if(currentPage.indexOf(settings.CONTENTLIST[0]) >=0 ){
            targetObj = Content;
        }else if(currentPage.indexOf(settings.CONTENTCATEGORYS[0]) >=0 ){
            targetObj = ContentCategory;
        }else if(currentPage.indexOf(settings.CONTENTTAGS[0]) >=0 ){
            targetObj = ContentTags;
        }else if(currentPage.indexOf(settings.CONTENTTEMPS[0]) >=0 ){
            targetObj = ContentTemplate;
        }else if(currentPage.indexOf(settings.CONTENTTEMPITEMS[0]) >=0 ){
            targetObj = TemplateItems;
        }else if(currentPage.indexOf(settings.MESSAGEMANAGE[0]) >=0 ){
            targetObj = Message;
        }else if(currentPage.indexOf(settings.REGUSERSLIST[0]) >=0 ){
            targetObj = User;
        }else if(currentPage.indexOf(settings.SYSTEMNOTICE[0]) >=0 ){
            targetObj = Notify;
        }else if(currentPage.indexOf(settings.USERNOTICE[0]) >=0 ){
            targetObj = UserNotify;
        }else if(currentPage.indexOf(settings.SYSTEMBACKSTAGENOTICE[0]) >=0 ){
            targetObj = UserNotify;
        }else{
            targetObj = Content;
        }

        return targetObj
    },

    checkAdminPower : function(req,key){
        var power = false;
        var uPower = req.session.adminPower;
        if(uPower){
            var newPowers = eval(uPower);
            for(var i=0;i<newPowers.length;i++) {
                var checkedId = newPowers[i].split(':')[0];
                if(checkedId == key && newPowers[i].split(':')[1]){
                    power = true;
                    break;
                }
            }
        }
        return power;
    },

    renderToManagePage : function(req,res,url,pageKey){

        if(this.checkAdminPower(req,pageKey[0] + '_view')){
            res.render(url, this.setPageInfo(req,res,pageKey,'/admin/'+url));
        }else{
            res.render("manage/public/notice", this.setDataForInfo('danger','对不起，您无权操作 <strong>'+pageKey[1]+'</strong> 模块！'));
        }
    },

    checkTempInfo : function(tempInfoData,forderName,callBack){

        var name = tempInfoData.name;
        var alias = tempInfoData.alias;
        var version = tempInfoData.version;
        var sImg = tempInfoData.sImg;
        var author = tempInfoData.author;
        var comment = tempInfoData.comment;
        var errors;

        if(forderName !== alias){
            errors = '模板名称跟文件夹名称不统一';
        }

        if(!validator.isLength(name,4,15)){
            errors = '模板名称必须为4-15个字符';
        }

        if(!validator.isEn(alias)){
            errors = '模板关键字必须为英文字符';
        }

        if(!validator.isLength(alias,4,15)){
            errors = '模板关键字必须为4-15个字符';
        }

        if(!validator.isLength(version,2,15)){
            errors = '版本号必须为2-15个字符';
        }

        if(!validator.isLength(author,4,15)){
            errors = '作者名称必须为4-15个字符';
        }

        if(!validator.isLength(comment,4,40)){
            errors = '模板描述必须为4-30个字符';
        }

        if(errors){
            callBack(errors);
        }else{
            var query=ContentTemplate.find().or([{'name' : name},{alias : alias}]);
            query.exec(function(err,temp){
                if(err){
                    res.end(err);
                }else{
                    if(temp.length > 0){
                        errors = "模板名称或key已存在，请修改后重试！";
                    }else{
                        errors = 'success';
                    }
                    callBack(errors);
                }

            });
        }
    },

    authDoraCMS : function(req,res,callBack){
        var params = {
          domain : req.headers.host,
          ipAddress : adminFunc.getClienIp(req)
        };
        if(req.session.adminUserInfo && !req.session.adminUserInfo.auth){
            request.post({url: settings.DORACMSAPI + '/system/checkSystemInfo', form: params}, function(err,httpResponse,body){
                if (!err && httpResponse.statusCode == 200) {
                    if(body == 'success'){
                        AdminUser.update({'_id':req.session.adminUserInfo._id},{$set : {auth : true}},function(err){
                            if(err){
                                console.log(err);
                            }
                            callBack();
                        })
                    }
                }else{
                    callBack();
                }
            })
        }else{
            callBack();
        }
    },

    setTempParentId : function(arr,key){
        for(var i=0;i<arr.length;i++){
            var pathObj = arr[i];
            pathObj.pId = key;
        }
        return arr;
    }

};

var uptoken = new qiniu.rs.PutPolicy(config.Bucket_Name);

module.exports = adminFunc;
<commit_msg>debug<commit_after>/**
 * Created by Administrator on 2015/8/31.
 */
var url = require('url');
var settings = require("./settings");
//数据库操作对象
var DbOpt = require("../Dbopt");

//管理员对象
var AdminUser = require("../AdminUser");
//管理员用户组对象
var AdminGroup = require("../AdminGroup");
// 文档对象
var Content = require("../Content");
//数据操作日志
var DataOptionLog = require("../DataOptionLog");
//文章类别对象
var ContentCategory = require("../ContentCategory");
//文章标签对象
var ContentTags = require("../ContentTags");
//文章模板对象
var ContentTemplate = require("../ContentTemplate");
var TemplateItems = require("../TemplateItems");
//文章留言对象
var Message = require("../Message");
//注册用户对象
var User = require("../User");
//广告对象
var Ads = require("../Ads");
//文件对象
var Files = require("../Files");
//系统日志对象
var SystemOptionLog = require("../SystemOptionLog");
//消息对象
var Notify = require("../Notify");
var UserNotify = require("../UserNotify");
var shortid = require('shortid');
//数据校验
var validator = require("validator");
var system = require('../../util/system');
var request = require('request');

var config = require('../../config');
var express = require('express');

var qiniu = require('qiniu');
var app = express();

app.get('/uptoken', function(req, res, next) {
    var token = uptoken.token();
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        console.log(token);
        console.log(".....................");
        res.json({
            uptoken: token
        });
    }
});

qiniu.conf.ACCESS_KEY = config.ACCESS_KEY;
qiniu.conf.SECRET_KEY = config.SECRET_KEY;

var uptoken = new qiniu.rs.PutPolicy(config.Bucket_Name);

var adminFunc = {

    siteInfos : function (description) {

        return {
            title : settings.SITETITLE,
            description : description,
            version : settings.SITEVERSION
        }
    },

    getMessageList : function(){
        return Message.find({}).limit(10).sort({'date' : -1}).populate('author').populate('replyAuthor').populate('adminAuthor').exec();
    },

    getClienIp : function(req){

        return req.headers['x-forwarded-for'] ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress;

    },

    setMainInfos : function(req, res){
        return res.json({
            adminUserCount : AdminUser.count({}),
            regUsersCount : User.count({}),
            contentsCount : Content.count({}),
            msgCount : Message.count({}),
            msgList : this.getMessageList(),
            regUsers : User.find({}).limit(15).sort({'date' : -1})
        })
    },

    setPageInfoTest : function(req,res,module,currentLink){

        var searchKey = '';
        //area是为了独立查询一个表其中的部分数据而设立的参数
        var area = '';
        if(req.url){
            var params = url.parse(req.url,true);
            searchKey = params.query.searchKey;
            area = req.query.area;
        }

            var token = uptoken.token();
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        console.log(token);
        console.log("...+++..................");
    }

        return {
            uptoken: token,
            domain: config.Domain,
            uptoken_url: config.Uptoken_Url,
            siteInfo : this.siteInfos(module[1]),
            bigCategory : module[0],
            searchKey : searchKey,
            area : area,
            currentLink : currentLink
        }

    },

    setPageInfo : function(req,res,module,currentLink){

        var searchKey = '';
        //area是为了独立查询一个表其中的部分数据而设立的参数
        var area = '';
        if(req.url){
            var params = url.parse(req.url,true);
            searchKey = params.query.searchKey;
            area = req.query.area;
        }

        return {
            domain: config.Domain,
            uptoken_url: config.Uptoken_Url,
            siteInfo : this.siteInfos(module[1]),
            bigCategory : module[0],
            searchKey : searchKey,
            area : area,
            currentLink : currentLink,
            layout : 'manage/public/adminTemp'
        }

    },

    setDataForInfo : function(infoType,infoContent){

        return {
            siteInfo : this.siteInfos('系统操作提示'),
            bigCategory : 'noticePage',
            infoType : infoType,
            infoContent : infoContent,
            area : '',
            layout: 'manage/public/adminTemp'
        }

    },

    setQueryByArea : function(req,keyPr,targetObj,area){
        var newKeyPr = keyPr;
        if(targetObj == UserNotify){
            if(area && area == 'systemNotice'){
                newKeyPr = {'systemUser' : req.session.adminUserInfo._id };
            }
        }else if(targetObj == Notify){
            if(area && area == 'announce'){
                newKeyPr = {'type' : '1' };
            }
        }
        return newKeyPr;
    },

    getAdminNotices : function (req,res,callBack) {

        UserNotify.find({'systemUser':req.session.adminUserInfo._id,'isRead':false})
            .populate('user').populate('notify').exec(function(err,docs){
            if(err){
                res.end(err);
            }else{
                var regNoticeArr = [];
                var msgNoticeArr = [];
                if(docs.length >0){
                    for(var i=0;i<docs.length;i++){
                        var item = docs[i];
                        if(item.notify && item.notify.action == 'reg'){
                            regNoticeArr.push(item)
                        }else if(item.notify && item.notify.action == 'msg'){
                            msgNoticeArr.push(item)
                        }
                    }
                };
                var noticeObj = {
                    regNotices : regNoticeArr,
                    msgNotices : msgNoticeArr,
                    totalCount : regNoticeArr.length + msgNoticeArr.length
                };
                callBack(noticeObj);
            }
        });

    },

    delNotifiesById : function(req,res,nid){
        if(shortid.isValid(nid)){
            Notify.delOneNotify(res,nid,function(){
                var notifyQuery = {'notify': { $regex: new RegExp(nid, 'i') }};
                UserNotify.remove(notifyQuery,function(err){
                    if(err){
                        res.end(err);
                    }
                });
            });
        }else{
            res.end(settings.system_illegal_param);
        }

    },

    getTargetObj : function(currentPage){
        var targetObj;
        if(currentPage.indexOf(settings.ADMINUSERLIST[0]) >=0 ){
            targetObj = AdminUser;
        }else if(currentPage.indexOf(settings.ADMINGROUPLIST[0]) >=0 ){
            targetObj = AdminGroup;
        }else if(currentPage.indexOf(settings.ADSLIST[0]) >=0 ){
            targetObj = Ads;
        }else if(currentPage.indexOf(settings.FILESLIST[0]) >=0 ){
            targetObj = Files;
        }else if(currentPage.indexOf(settings.BACKUPDATA[0]) >=0 ){
            targetObj = DataOptionLog;
        }else if(currentPage.indexOf(settings.SYSTEMLOGS[0]) >=0 ){
            targetObj = SystemOptionLog;
        }else if(currentPage.indexOf(settings.CONTENTLIST[0]) >=0 ){
            targetObj = Content;
        }else if(currentPage.indexOf(settings.CONTENTCATEGORYS[0]) >=0 ){
            targetObj = ContentCategory;
        }else if(currentPage.indexOf(settings.CONTENTTAGS[0]) >=0 ){
            targetObj = ContentTags;
        }else if(currentPage.indexOf(settings.CONTENTTEMPS[0]) >=0 ){
            targetObj = ContentTemplate;
        }else if(currentPage.indexOf(settings.CONTENTTEMPITEMS[0]) >=0 ){
            targetObj = TemplateItems;
        }else if(currentPage.indexOf(settings.MESSAGEMANAGE[0]) >=0 ){
            targetObj = Message;
        }else if(currentPage.indexOf(settings.REGUSERSLIST[0]) >=0 ){
            targetObj = User;
        }else if(currentPage.indexOf(settings.SYSTEMNOTICE[0]) >=0 ){
            targetObj = Notify;
        }else if(currentPage.indexOf(settings.USERNOTICE[0]) >=0 ){
            targetObj = UserNotify;
        }else if(currentPage.indexOf(settings.SYSTEMBACKSTAGENOTICE[0]) >=0 ){
            targetObj = UserNotify;
        }else{
            targetObj = Content;
        }

        return targetObj
    },

    checkAdminPower : function(req,key){
        var power = false;
        var uPower = req.session.adminPower;
        if(uPower){
            var newPowers = eval(uPower);
            for(var i=0;i<newPowers.length;i++) {
                var checkedId = newPowers[i].split(':')[0];
                if(checkedId == key && newPowers[i].split(':')[1]){
                    power = true;
                    break;
                }
            }
        }
        return power;
    },

    renderToManagePage : function(req,res,url,pageKey){

        if(this.checkAdminPower(req,pageKey[0] + '_view')){
            res.render(url, this.setPageInfo(req,res,pageKey,'/admin/'+url));
        }else{
            res.render("manage/public/notice", this.setDataForInfo('danger','对不起，您无权操作 <strong>'+pageKey[1]+'</strong> 模块！'));
        }
    },

    checkTempInfo : function(tempInfoData,forderName,callBack){

        var name = tempInfoData.name;
        var alias = tempInfoData.alias;
        var version = tempInfoData.version;
        var sImg = tempInfoData.sImg;
        var author = tempInfoData.author;
        var comment = tempInfoData.comment;
        var errors;

        if(forderName !== alias){
            errors = '模板名称跟文件夹名称不统一';
        }

        if(!validator.isLength(name,4,15)){
            errors = '模板名称必须为4-15个字符';
        }

        if(!validator.isEn(alias)){
            errors = '模板关键字必须为英文字符';
        }

        if(!validator.isLength(alias,4,15)){
            errors = '模板关键字必须为4-15个字符';
        }

        if(!validator.isLength(version,2,15)){
            errors = '版本号必须为2-15个字符';
        }

        if(!validator.isLength(author,4,15)){
            errors = '作者名称必须为4-15个字符';
        }

        if(!validator.isLength(comment,4,40)){
            errors = '模板描述必须为4-30个字符';
        }

        if(errors){
            callBack(errors);
        }else{
            var query=ContentTemplate.find().or([{'name' : name},{alias : alias}]);
            query.exec(function(err,temp){
                if(err){
                    res.end(err);
                }else{
                    if(temp.length > 0){
                        errors = "模板名称或key已存在，请修改后重试！";
                    }else{
                        errors = 'success';
                    }
                    callBack(errors);
                }

            });
        }
    },

    authDoraCMS : function(req,res,callBack){
        var params = {
          domain : req.headers.host,
          ipAddress : adminFunc.getClienIp(req)
        };
        if(req.session.adminUserInfo && !req.session.adminUserInfo.auth){
            request.post({url: settings.DORACMSAPI + '/system/checkSystemInfo', form: params}, function(err,httpResponse,body){
                if (!err && httpResponse.statusCode == 200) {
                    if(body == 'success'){
                        AdminUser.update({'_id':req.session.adminUserInfo._id},{$set : {auth : true}},function(err){
                            if(err){
                                console.log(err);
                            }
                            callBack();
                        })
                    }
                }else{
                    callBack();
                }
            })
        }else{
            callBack();
        }
    },

    setTempParentId : function(arr,key){
        for(var i=0;i<arr.length;i++){
            var pathObj = arr[i];
            pathObj.pId = key;
        }
        return arr;
    }

};

var uptoken = new qiniu.rs.PutPolicy(config.Bucket_Name);

module.exports = adminFunc;
<|endoftext|>


<commit_before>'use strict';

var CimentariusBookshelf = require('./cimentarius');
var Promise = require('bluebird');
var _ = require('lodash');

var Site = CimentariusBookshelf.Model.extend(
    // Instance Methods
    {
        tableName: 'site',
        particles: function () {
            return this.hasMany('Pages');
        },
        // Initialize
        initialize: function () {
            // Destroying Hook for Removing Category Entries In The Through Table
            this.on('destroying', function () {
                console.log('destroying');
                console.log(this);
//                return CimentariusBookshelf.knex('category_page').where('page_id', '=', this.get('id')).delete();
            });
        },
        /*
         *
         */
        getPreference: function (name) {
            switch(name) {
                case 'default_page_template':
                    return 'default';
                case 'template_pack':
                    return 'default';

            }
        },
        /**
         * Fetch A Page With Particles In Order
         */
        fetchWithOrderedPages: function () {
            // Fetch With Particles Ordered By Position
            return this.fetch({
                withRelated: [
                    {
                        'pages': function (qb) {
                            qb.orderBy('position', 'ASC');
                        }
                    }
                ]
            });
        },
        /**
         * Load Ordered Particles Into Existing Page Model
         * @returns {*}
         */
        loadOrderedPages: function () {
            return this.load([
                {
                    'pages': function (qb) {
                        qb.orderBy('position', 'ASC');
                    }
                }
            ]);
        },

//        /*
//         function to locate the handling page for public requests.
//         */
//        function find_requested($request) {
//    $page = $this;
//    $found = true;
//    for($i=0, $limit = count($request); $i<$limit; $i++) {
//        if($request[$i]) {
//            $next = $page->ChildWithURL($request[$i]);
//            if(!$next || !$page->publiclyVisible()) {
//                $found = false;
//                break;
//            }
//            $page = $next;
//            if($page->service) {
//                break;
//            }
//        }
//    }
//    return array(&$page, $found);
//}
        /**
         * Update Search Field From Children Particles
         * Gets Child Particle Search Content, Then Joins It All
         * Adds to Model
         */
        updateSearchField: function () {
            // TET
            var _this = this;
            // Query
            return CimentariusBookshelf.knex('particle').select('search_field').where('page_id', _this.get('id')).then(function (results) {
                return Promise.resolve(_.pluck(results, 'search_field').join(' '));
            }).then(function (searchFieldResults) {
                // Set On Page
                _this.set('search_field', searchFieldResults);
                // Save
                return _this.save();
            });
        },
        /**
         * Get Parent Model Class
         * @returns {*}
         */
        getParentModelClass: function () {
            return getParentModelTypes()[this.get('parent_type')];
        },
        /**
         * Get Parent Collection Class
         * @returns {*}
         */
        getParentCollectionClass: function () {
            return getParentCollectionTypes()[this.get('parent_type')];
        }
    },
    // Static Methods
    {
        /**
         * Get Parent Model Class
         * @returns {*}
         */
        getParentModelClass: function (parentType) {
            return getParentModelTypes()[parentType];
        },
        /**
         * Get Parent Collection Class
         * @returns {*}
         */
        getParentCollectionClass: function (parentType) {
            return getParentCollectionTypes()[parentType];
        }
    });

var Sites = CimentariusBookshelf.Collection.extend({
    model: Site
});

module.exports = {
    Site: CimentariusBookshelf.model('Site', Site),
    Sites: CimentariusBookshelf.collection('Sites', Sites)
//    Form: pageForm
};<commit_msg>Specific -> Generic<commit_after>'use strict';

var CimentariusBookshelf = require('./cimentarius');
var Promise = require('bluebird');
var _ = require('lodash');

var Site = CimentariusBookshelf.Model.extend(
    // Instance Methods
    {
        tableName: 'site',
        particles: function () {
            return this.hasMany('Pages');
        },
        // Initialize
        initialize: function () {
            // Destroying Hook for Removing Category Entries In The Through Table
            this.on('destroying', function () {
                console.log('destroying');
                console.log(this);
//                return CimentariusBookshelf.knex('category_page').where('page_id', '=', this.get('id')).delete();
            });
        },
        /*
         *
         */
        getPreference: function (name) {
            switch(name) {
                case 'default_page_template':
                    return 'default';
                case 'template_pack':
                    return 'default';

            }
        },
        /**
         * Fetch A Page With Particles In Order
         */
        fetchWithOrderedPages: function () {
            // Fetch With Particles Ordered By Position
            return this.fetch({
                withRelated: [
                    {
                        'pages': function (qb) {
                            qb.orderBy('position', 'ASC');
                        }
                    }
                ]
            });
        },
        /**
         * Load Ordered Particles Into Existing Page Model
         * @returns {*}
         */
        loadOrderedPages: function () {
            return this.load([
                {
                    'pages': function (qb) {
                        qb.orderBy('position', 'ASC');
                    }
                }
            ]);
        },

//        /*
//         function to locate the handling page for public requests.
//         */
//        function find_requested($request) {
//    $page = $this;
//    $found = true;
//    for($i=0, $limit = count($request); $i<$limit; $i++) {
//        if($request[$i]) {
//            $next = $page->ChildWithURL($request[$i]);
//            if(!$next || !$page->publiclyVisible()) {
//                $found = false;
//                break;
//            }
//            $page = $next;
//            if($page->service) {
//                break;
//            }
//        }
//    }
//    return array(&$page, $found);
//}
        /**
         * Update Search Field From Children Particles
         * Gets Child Particle Search Content, Then Joins It All
         * Adds to Model
         */
        updateSearchField: function () {
            // TET
            var _this = this;
            // Query
            return CimentariusBookshelf.knex('particle').select('search_field').where('page_id', _this.get('id')).then(function (results) {
                return Promise.resolve(_.pluck(results, 'search_field').join(' '));
            }).then(function (searchFieldResults) {
                // Set On Page
                _this.set('search_field', searchFieldResults);
                // Save
                return _this.save();
            });
        },
        /**
         * Get Parent Model Class
         * @returns {*}
         */
        getParentModelClass: function () {
            return getParentModelTypes()[this.get('parent_type')];
        },
        /**
         * Get Parent Collection Class
         * @returns {*}
         */
        getParentCollectionClass: function () {
            return getParentCollectionTypes()[this.get('parent_type')];
        }
    },
    // Static Methods
    {
        /**
         * Get Parent Model Class
         * @returns {*}
         */
        getParentModelClass: function (parentType) {
            return getParentModelTypes()[parentType];
        },
        /**
         * Get Parent Collection Class
         * @returns {*}
         */
        getParentCollectionClass: function (parentType) {
            return getParentCollectionTypes()[parentType];
        }
    });

var Sites = CimentariusBookshelf.Collection.extend({
    model: Site
});

module.exports = {
    model: CimentariusBookshelf.model('Site', Site),
    collection: CimentariusBookshelf.collection('Sites', Sites)
//    Form: pageForm
};<|endoftext|>


<commit_before>var mongoose = require('mongoose');

var schema = new mongoose.Schema({
	person: {
		firstName: { type: String, required: true, trim: true },
		lastName: { type: String/*, required: true*/, trim: true }
	},
	location: {
		street: { type: String, required: true, trim: true },
		zipCode: { type: String/*, required: true*/, trim: true },
		city: { type: String, required: true, trim: true },
		sublocality1: { type: String, trim: true },
		sublocality2: { type: String, trim: true },
		coordinates: {
			longitude: { type: Number, required: true },
			latitude: { type: Number, required: true }
		},
	},
	laidAt : {
		year: { type: Number, min: 1992 },
		month: { type: Number, min: 0, max: 11 },
		date: { type: Number, min: 0, max: 31 }
	},
	description: { type: String, trim: true },
	imageUrl: { type: String, trim: true },
	source: {
		url: { type: String, trim: true, required: true },
		name: { type: String, trim: true, required: true },
		retrievedAt: { type: Date, required: true }
	},
	createdAt: { type: Date },
	updatedAt: { type: Date }
});

schema.virtual('id').get(function(){
    return this._id;
});

schema.set('toJSON', { transform: function (doc, ret, options) {
	ret.id = doc._id;
  delete ret._id;
	delete ret.__v;
}});

schema.methods.toGeoJSON = function() {
	return {
		"type": "Feature",
		"geometry": {
			"type": "Point",
			"coordinates": [this.location.longitude, this.location.latitude]
		}
	};
}

schema.statics.findExactMatch = function(source, stolperstein, callback) {
	this.findOne({
		"source.url": source.url,
		"source.name": source.name,
//		"source.retrievedAt": source.retrievedAt,
		"person.firstName": stolperstein.person.firstName,
		"person.lastName": stolperstein.person.lastName,
		"location.street": stolperstein.location.street,
		"location.city": stolperstein.location.city,
		"location.zipCode": stolperstein.location.zipCode,
		"location.coordinates.latitude": stolperstein.location.coordinates.latitude,
		"location.coordinates.longitude": stolperstein.location.coordinates.longitude,
		"description": stolperstein.description
	}, callback);
}

// Automatically maintain created and updated dates
schema.pre('save', function (next) {
	// This overwrites model data for createdAt and updatedAt
	if (this.isNew) {
		this.createdAt = this.updatedAt = new Date;
	} else {
		this.updatedAt = new Date;
	}
	next();
});

exports.Stolperstein = mongoose.model('Stolperstein', schema, 'stolpersteine');
exports.StolpersteinSchema = schema;<commit_msg>Removed createdAt and updatedAt attributes<commit_after>var mongoose = require('mongoose');

var schema = new mongoose.Schema({
	person: {
		firstName: { type: String, required: true, trim: true },
		lastName: { type: String/*, required: true*/, trim: true }
	},
	location: {
		street: { type: String, required: true, trim: true },
		zipCode: { type: String/*, required: true*/, trim: true },
		city: { type: String, required: true, trim: true },
		sublocality1: { type: String, trim: true },
		sublocality2: { type: String, trim: true },
		coordinates: {
			longitude: { type: Number, required: true },
			latitude: { type: Number, required: true }
		},
	},
	laidAt : {
		year: { type: Number, min: 1992 },
		month: { type: Number, min: 0, max: 11 },
		date: { type: Number, min: 0, max: 31 }
	},
	description: { type: String, trim: true },
	imageUrl: { type: String, trim: true },
	source: {
		url: { type: String, trim: true, required: true },
		name: { type: String, trim: true, required: true },
		retrievedAt: { type: Date, required: true }
	}
});

schema.virtual('id').get(function(){
    return this._id;
});

schema.set('toJSON', { transform: function (doc, ret, options) {
	ret.id = doc._id;
  delete ret._id;
	delete ret.__v;
}});

schema.methods.toGeoJSON = function() {
	return {
		"type": "Feature",
		"geometry": {
			"type": "Point",
			"coordinates": [this.location.longitude, this.location.latitude]
		}
	};
}

schema.statics.findExactMatch = function(source, stolperstein, callback) {
	this.findOne({
		"source.url": source.url,
		"source.name": source.name,
//		"source.retrievedAt": source.retrievedAt,
		"person.firstName": stolperstein.person.firstName,
		"person.lastName": stolperstein.person.lastName,
		"location.street": stolperstein.location.street,
		"location.city": stolperstein.location.city,
		"location.zipCode": stolperstein.location.zipCode,
		"location.coordinates.latitude": stolperstein.location.coordinates.latitude,
		"location.coordinates.longitude": stolperstein.location.coordinates.longitude,
		"description": stolperstein.description
	}, callback);
}

exports.Stolperstein = mongoose.model('Stolperstein', schema, 'stolpersteine');
exports.StolpersteinSchema = schema;<|endoftext|>


<commit_before>import has from 'has'
import tmatch from 'tmatch'
import isRegExp from 'is-regex'
import assert from './assert'
import { isSpy } from './SpyUtils'
import {
  isA,
  isFunction,
  isArray,
  isEqual,
  isObject,
  functionThrows,
  arrayContains,
  objectContains,
  stringContains
} from './TestUtils'

const addErrorInfo = (actual, expected, callback) => {
  try {
    callback()
  } catch (error) {
    // These attributes are consumed by Mocha to produce a diff output.
    error.actual = actual
    error.expected = expected
    error.showDiff = true
    throw error
  }
}

/**
 * An Expectation is a wrapper around an assertion that allows it to be written
 * in a more natural style, without the need to remember the order of arguments.
 * This helps prevent you from making mistakes when writing tests.
 */
class Expectation {
  constructor(actual) {
    this.actual = actual

    if (isFunction(actual)) {
      this.context = null
      this.args = []
    }
  }

  toExist(message) {
    assert(
      this.actual,
      (message || 'Expected %s to exist'),
      this.actual
    )

    return this
  }

  toNotExist(message) {
    assert(
      !this.actual,
      (message || 'Expected %s to not exist'),
      this.actual
    )

    return this
  }

  toBe(value, message) {
    assert(
      this.actual === value,
      (message || 'Expected %s to be %s'),
      this.actual,
      value
    )

    return this
  }

  toNotBe(value, message) {
    assert(
      this.actual !== value,
      (message || 'Expected %s to not be %s'),
      this.actual,
      value
    )

    return this
  }

  toEqual(value, message) {
    addErrorInfo(this.actual, value, () => {
      assert(
        isEqual(this.actual, value),
        (message || 'Expected %s to equal %s'),
        this.actual,
        value
      )
    })

    return this
  }

  toNotEqual(value, message) {
    addErrorInfo(this.actual, value, () => {
      assert(
        !isEqual(this.actual, value),
        (message || 'Expected %s to not equal %s'),
        this.actual,
        value
      )
    })

    return this
  }

  toThrow(value, message) {
    assert(
      isFunction(this.actual),
      'The "actual" argument in expect(actual).toThrow() must be a function, %s was given',
      this.actual
    )

    assert(
      functionThrows(this.actual, this.context, this.args, value),
      (message || 'Expected %s to throw %s'),
      this.actual,
      value || 'an error'
    )

    return this
  }

  toNotThrow(value, message) {
    assert(
      isFunction(this.actual),
      'The "actual" argument in expect(actual).toNotThrow() must be a function, %s was given',
      this.actual
    )

    assert(
      !functionThrows(this.actual, this.context, this.args, value),
      (message || 'Expected %s to not throw %s'),
      this.actual,
      value || 'an error'
    )

    return this
  }

  toBeA(value, message) {
    assert(
      isFunction(value) || typeof value === 'string',
      'The "value" argument in toBeA(value) must be a function or a string'
    )

    assert(
      isA(this.actual, value),
      (message || 'Expected %s to be a %s'),
      this.actual,
      value
    )

    return this
  }

  toNotBeA(value, message) {
    assert(
      isFunction(value) || typeof value === 'string',
      'The "value" argument in toNotBeA(value) must be a function or a string'
    )

    assert(
      !isA(this.actual, value),
      (message || 'Expected %s to be a %s'),
      this.actual,
      value
    )

    return this
  }

  toMatch(pattern, message) {
    let matches = false

    if (typeof this.actual === 'string') {
      assert(
        isRegExp(pattern),
        'The "pattern" argument in expect(string).toMatch(pattern) must be a RegExp'
      )

      matches = pattern.test(this.actual)
    } else if (isObject(this.actual)) {
      matches = tmatch(this.actual, pattern)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toMatch() must be a string or an object'
      )
    }

    assert(
      matches,
      (message || 'Expected %s to match %s'),
      this.actual,
      pattern
    )

    return this
  }

  toNotMatch(pattern, message) {
    let matches = false

    if (typeof this.actual === 'string') {
      assert(
        isRegExp(pattern),
        'The "pattern" argument in expect(string).toNotMatch(pattern) must be a RegExp'
      )

      matches = pattern.test(this.actual)
    } else if (isObject(this.actual)) {
      matches = tmatch(this.actual, pattern)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toNotMatch() must be a string or an object'
      )
    }

    assert(
      !matches,
      (message || 'Expected %s to not match %s'),
      this.actual,
      pattern
    )

    return this
  }

  toBeLessThan(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeLessThan() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeLessThan(value) must be a number'
    )

    assert(
      this.actual < value,
      (message || 'Expected %s to be less than %s'),
      this.actual,
      value
    )

    return this
  }

  toBeLessThanOrEqualTo(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeLessThanOrEqualTo() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeLessThanOrEqualTo(value) must be a number'
    )

    assert(
      this.actual <= value,
      (message || 'Expected %s to be less than or equal to %s'),
      this.actual,
      value
    )

    return this
  }

  toBeGreaterThan(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeGreaterThan() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeGreaterThan(value) must be a number'
    )

    assert(
      this.actual > value,
      (message || 'Expected %s to be greater than %s'),
      this.actual,
      value
    )

    return this
  }

  toBeGreaterThanOrEqualTo(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeGreaterThanOrEqualTo() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeGreaterThanOrEqualTo(value) must be a number'
    )

    assert(
      this.actual >= value,
      (message || 'Expected %s to be greater than or equal to %s'),
      this.actual,
      value
    )

    return this
  }

  toInclude(value, compareValues, message) {
    if (typeof compareValues === 'string') {
      message = compareValues
      compareValues = null
    }

    if (compareValues == null)
      compareValues = isEqual

    let contains = false

    if (isArray(this.actual)) {
      contains = arrayContains(this.actual, value, compareValues)
    } else if (isObject(this.actual)) {
      contains = objectContains(this.actual, value, compareValues)
    } else if (typeof this.actual === 'string') {
      contains = stringContains(this.actual, value)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toInclude() must be an array, object, or a string'
      )
    }

    assert(
      contains,
      message || 'Expected %s to include %s',
      this.actual,
      value
    )

    return this
  }

  toExclude(value, compareValues, message) {
    if (typeof compareValues === 'string') {
      message = compareValues
      compareValues = null
    }

    if (compareValues == null)
      compareValues = isEqual

    let contains = false

    if (isArray(this.actual)) {
      contains = arrayContains(this.actual, value, compareValues)
    } else if (isObject(this.actual)) {
      contains = objectContains(this.actual, value, compareValues)
    } else if (typeof this.actual === 'string') {
      contains = stringContains(this.actual, value)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toExclude() must be an array, object, or a string'
      )
    }

    assert(
      !contains,
      message || 'Expected %s to exclude %s',
      this.actual,
      value
    )

    return this
  }

  toIncludeKeys(keys, comparator, message) {
    if (typeof comparator === 'string') {
      message = comparator
      comparator = null
    }

    if (comparator == null)
      comparator = has

    assert(
      typeof this.actual === 'object',
      'The "actual" argument in expect(actual).toIncludeKeys() must be an object, not %s',
      typeof this.actual
    )

    const contains = keys.every(key => comparator(this.actual, key))

    assert(
      contains,
      message || 'Expected %s to include key(s) %s',
      this.actual,
      keys.join(', ')
    )

    return this
  }

  toIncludeKey(key, ...args) {
    return this.toIncludeKeys([ key ], ...args)
  }

  toExcludeKeys(keys, comparator, message) {
    if (typeof comparator === 'string') {
      message = comparator
      comparator = null
    }

    if (comparator == null)
      comparator = has

    assert(
      typeof this.actual === 'object',
      'The "actual" argument in expect(actual).toExcludeKeys() must be an object, not %s',
      typeof this.actual
    )

    const contains = keys.every(key => comparator(this.actual, key))

    assert(
      !contains,
      message || 'Expected %s to exclude key(s) %s',
      this.actual,
      keys.join(', ')
    )

    return this
  }

  toExcludeKey(key, ...args) {
    return this.toExcludeKeys([ key ], ...args)
  }

  toHaveBeenCalled(message) {
    const spy = this.actual

    assert(
      isSpy(spy),
      'The "actual" argument in expect(actual).toHaveBeenCalled() must be a spy'
    )

    assert(
      spy.calls.length > 0,
      (message || 'spy was not called')
    )

    return this
  }

  toHaveBeenCalledWith(...expectedArgs) {
    const spy = this.actual

    assert(
      isSpy(spy),
      'The "actual" argument in expect(actual).toHaveBeenCalledWith() must be a spy'
    )

    assert(
      spy.calls.some(call => isEqual(call.arguments, expectedArgs)),
      'spy was never called with %s',
      expectedArgs
    )

    return this
  }

  toNotHaveBeenCalled(message) {
    const spy = this.actual

    assert(
      isSpy(spy),
      'The "actual" argument in expect(actual).toNotHaveBeenCalled() must be a spy'
    )

    assert(
      spy.calls.length === 0,
      (message || 'spy was not supposed to be called')
    )

    return this
  }
}

const deprecate = (fn, message) => {
  let alreadyWarned = false

  return function (...args) {
    if (!alreadyWarned) {
      alreadyWarned = true
      console.warn(message)
    }

    return fn.apply(this, args)
  }
}

Expectation.prototype.withContext = deprecate(function (context) {
  assert(
    isFunction(this.actual),
    'The "actual" argument in expect(actual).withContext() must be a function'
  )

  this.context = context

  return this
}, `
withContext is deprecated; use a closure instead.

  expect(fn).withContext(context).toThrow()

becomes

  expect(() => fn.call(context)).toThrow()
`)

Expectation.prototype.withArgs = deprecate(function (...args) {
  assert(
    isFunction(this.actual),
    'The "actual" argument in expect(actual).withArgs() must be a function'
  )

  if (args.length)
    this.args = this.args.concat(...args)

  return this
}, `
withArgs is deprecated; use a closure instead.

  expect(fn).withArgs(a, b, c).toThrow()

becomes

  expect(() => fn(a, b, c)).toThrow()
`)

const aliases = {
  toBeAn: 'toBeA',
  toNotBeAn: 'toNotBeA',
  toBeTruthy: 'toExist',
  toBeFalsy: 'toNotExist',
  toBeFewerThan: 'toBeLessThan',
  toBeMoreThan: 'toBeGreaterThan',
  toContain: 'toInclude',
  toNotContain: 'toExclude',
  toNotInclude: 'toExclude',
  toContainKeys: 'toIncludeKeys',
  toNotContainKeys: 'toExcludeKeys',
  toNotIncludeKeys: 'toExcludeKeys',
  toContainKey: 'toIncludeKey',
  toNotContainKey: 'toExcludeKey',
  toNotIncludeKey: 'toExcludeKey'
}

for (const alias in aliases)
  if (aliases.hasOwnProperty(alias))
    Expectation.prototype[alias] = Expectation.prototype[aliases[alias]]

export default Expectation
<commit_msg>Only include diff when objects are not equal<commit_after>import has from 'has'
import tmatch from 'tmatch'
import isRegExp from 'is-regex'
import assert from './assert'
import { isSpy } from './SpyUtils'
import {
  isA,
  isFunction,
  isArray,
  isEqual,
  isObject,
  functionThrows,
  arrayContains,
  objectContains,
  stringContains
} from './TestUtils'

/**
 * An Expectation is a wrapper around an assertion that allows it to be written
 * in a more natural style, without the need to remember the order of arguments.
 * This helps prevent you from making mistakes when writing tests.
 */
class Expectation {
  constructor(actual) {
    this.actual = actual

    if (isFunction(actual)) {
      this.context = null
      this.args = []
    }
  }

  toExist(message) {
    assert(
      this.actual,
      (message || 'Expected %s to exist'),
      this.actual
    )

    return this
  }

  toNotExist(message) {
    assert(
      !this.actual,
      (message || 'Expected %s to not exist'),
      this.actual
    )

    return this
  }

  toBe(value, message) {
    assert(
      this.actual === value,
      (message || 'Expected %s to be %s'),
      this.actual,
      value
    )

    return this
  }

  toNotBe(value, message) {
    assert(
      this.actual !== value,
      (message || 'Expected %s to not be %s'),
      this.actual,
      value
    )

    return this
  }

  toEqual(value, message) {
    try {
      assert(
        isEqual(this.actual, value),
        (message || 'Expected %s to equal %s'),
        this.actual,
        value
      )
    } catch (error) {
      // These attributes are consumed by Mocha to produce a diff output.
      error.actual = this.actual
      error.expected = value
      error.showDiff = true
      throw error
    }

    return this
  }

  toNotEqual(value, message) {
    assert(
      !isEqual(this.actual, value),
      (message || 'Expected %s to not equal %s'),
      this.actual,
      value
    )

    return this
  }

  toThrow(value, message) {
    assert(
      isFunction(this.actual),
      'The "actual" argument in expect(actual).toThrow() must be a function, %s was given',
      this.actual
    )

    assert(
      functionThrows(this.actual, this.context, this.args, value),
      (message || 'Expected %s to throw %s'),
      this.actual,
      value || 'an error'
    )

    return this
  }

  toNotThrow(value, message) {
    assert(
      isFunction(this.actual),
      'The "actual" argument in expect(actual).toNotThrow() must be a function, %s was given',
      this.actual
    )

    assert(
      !functionThrows(this.actual, this.context, this.args, value),
      (message || 'Expected %s to not throw %s'),
      this.actual,
      value || 'an error'
    )

    return this
  }

  toBeA(value, message) {
    assert(
      isFunction(value) || typeof value === 'string',
      'The "value" argument in toBeA(value) must be a function or a string'
    )

    assert(
      isA(this.actual, value),
      (message || 'Expected %s to be a %s'),
      this.actual,
      value
    )

    return this
  }

  toNotBeA(value, message) {
    assert(
      isFunction(value) || typeof value === 'string',
      'The "value" argument in toNotBeA(value) must be a function or a string'
    )

    assert(
      !isA(this.actual, value),
      (message || 'Expected %s to be a %s'),
      this.actual,
      value
    )

    return this
  }

  toMatch(pattern, message) {
    let matches = false

    if (typeof this.actual === 'string') {
      assert(
        isRegExp(pattern),
        'The "pattern" argument in expect(string).toMatch(pattern) must be a RegExp'
      )

      matches = pattern.test(this.actual)
    } else if (isObject(this.actual)) {
      matches = tmatch(this.actual, pattern)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toMatch() must be a string or an object'
      )
    }

    assert(
      matches,
      (message || 'Expected %s to match %s'),
      this.actual,
      pattern
    )

    return this
  }

  toNotMatch(pattern, message) {
    let matches = false

    if (typeof this.actual === 'string') {
      assert(
        isRegExp(pattern),
        'The "pattern" argument in expect(string).toNotMatch(pattern) must be a RegExp'
      )

      matches = pattern.test(this.actual)
    } else if (isObject(this.actual)) {
      matches = tmatch(this.actual, pattern)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toNotMatch() must be a string or an object'
      )
    }

    assert(
      !matches,
      (message || 'Expected %s to not match %s'),
      this.actual,
      pattern
    )

    return this
  }

  toBeLessThan(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeLessThan() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeLessThan(value) must be a number'
    )

    assert(
      this.actual < value,
      (message || 'Expected %s to be less than %s'),
      this.actual,
      value
    )

    return this
  }

  toBeLessThanOrEqualTo(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeLessThanOrEqualTo() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeLessThanOrEqualTo(value) must be a number'
    )

    assert(
      this.actual <= value,
      (message || 'Expected %s to be less than or equal to %s'),
      this.actual,
      value
    )

    return this
  }

  toBeGreaterThan(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeGreaterThan() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeGreaterThan(value) must be a number'
    )

    assert(
      this.actual > value,
      (message || 'Expected %s to be greater than %s'),
      this.actual,
      value
    )

    return this
  }

  toBeGreaterThanOrEqualTo(value, message) {
    assert(
      typeof this.actual === 'number',
      'The "actual" argument in expect(actual).toBeGreaterThanOrEqualTo() must be a number'
    )

    assert(
      typeof value === 'number',
      'The "value" argument in toBeGreaterThanOrEqualTo(value) must be a number'
    )

    assert(
      this.actual >= value,
      (message || 'Expected %s to be greater than or equal to %s'),
      this.actual,
      value
    )

    return this
  }

  toInclude(value, compareValues, message) {
    if (typeof compareValues === 'string') {
      message = compareValues
      compareValues = null
    }

    if (compareValues == null)
      compareValues = isEqual

    let contains = false

    if (isArray(this.actual)) {
      contains = arrayContains(this.actual, value, compareValues)
    } else if (isObject(this.actual)) {
      contains = objectContains(this.actual, value, compareValues)
    } else if (typeof this.actual === 'string') {
      contains = stringContains(this.actual, value)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toInclude() must be an array, object, or a string'
      )
    }

    assert(
      contains,
      message || 'Expected %s to include %s',
      this.actual,
      value
    )

    return this
  }

  toExclude(value, compareValues, message) {
    if (typeof compareValues === 'string') {
      message = compareValues
      compareValues = null
    }

    if (compareValues == null)
      compareValues = isEqual

    let contains = false

    if (isArray(this.actual)) {
      contains = arrayContains(this.actual, value, compareValues)
    } else if (isObject(this.actual)) {
      contains = objectContains(this.actual, value, compareValues)
    } else if (typeof this.actual === 'string') {
      contains = stringContains(this.actual, value)
    } else {
      assert(
        false,
        'The "actual" argument in expect(actual).toExclude() must be an array, object, or a string'
      )
    }

    assert(
      !contains,
      message || 'Expected %s to exclude %s',
      this.actual,
      value
    )

    return this
  }

  toIncludeKeys(keys, comparator, message) {
    if (typeof comparator === 'string') {
      message = comparator
      comparator = null
    }

    if (comparator == null)
      comparator = has

    assert(
      typeof this.actual === 'object',
      'The "actual" argument in expect(actual).toIncludeKeys() must be an object, not %s',
      typeof this.actual
    )

    const contains = keys.every(key => comparator(this.actual, key))

    assert(
      contains,
      message || 'Expected %s to include key(s) %s',
      this.actual,
      keys.join(', ')
    )

    return this
  }

  toIncludeKey(key, ...args) {
    return this.toIncludeKeys([ key ], ...args)
  }

  toExcludeKeys(keys, comparator, message) {
    if (typeof comparator === 'string') {
      message = comparator
      comparator = null
    }

    if (comparator == null)
      comparator = has

    assert(
      typeof this.actual === 'object',
      'The "actual" argument in expect(actual).toExcludeKeys() must be an object, not %s',
      typeof this.actual
    )

    const contains = keys.every(key => comparator(this.actual, key))

    assert(
      !contains,
      message || 'Expected %s to exclude key(s) %s',
      this.actual,
      keys.join(', ')
    )

    return this
  }

  toExcludeKey(key, ...args) {
    return this.toExcludeKeys([ key ], ...args)
  }

  toHaveBeenCalled(message) {
    const spy = this.actual

    assert(
      isSpy(spy),
      'The "actual" argument in expect(actual).toHaveBeenCalled() must be a spy'
    )

    assert(
      spy.calls.length > 0,
      (message || 'spy was not called')
    )

    return this
  }

  toHaveBeenCalledWith(...expectedArgs) {
    const spy = this.actual

    assert(
      isSpy(spy),
      'The "actual" argument in expect(actual).toHaveBeenCalledWith() must be a spy'
    )

    assert(
      spy.calls.some(call => isEqual(call.arguments, expectedArgs)),
      'spy was never called with %s',
      expectedArgs
    )

    return this
  }

  toNotHaveBeenCalled(message) {
    const spy = this.actual

    assert(
      isSpy(spy),
      'The "actual" argument in expect(actual).toNotHaveBeenCalled() must be a spy'
    )

    assert(
      spy.calls.length === 0,
      (message || 'spy was not supposed to be called')
    )

    return this
  }
}

const deprecate = (fn, message) => {
  let alreadyWarned = false

  return function (...args) {
    if (!alreadyWarned) {
      alreadyWarned = true
      console.warn(message)
    }

    return fn.apply(this, args)
  }
}

Expectation.prototype.withContext = deprecate(function (context) {
  assert(
    isFunction(this.actual),
    'The "actual" argument in expect(actual).withContext() must be a function'
  )

  this.context = context

  return this
}, `
withContext is deprecated; use a closure instead.

  expect(fn).withContext(context).toThrow()

becomes

  expect(() => fn.call(context)).toThrow()
`)

Expectation.prototype.withArgs = deprecate(function (...args) {
  assert(
    isFunction(this.actual),
    'The "actual" argument in expect(actual).withArgs() must be a function'
  )

  if (args.length)
    this.args = this.args.concat(...args)

  return this
}, `
withArgs is deprecated; use a closure instead.

  expect(fn).withArgs(a, b, c).toThrow()

becomes

  expect(() => fn(a, b, c)).toThrow()
`)

const aliases = {
  toBeAn: 'toBeA',
  toNotBeAn: 'toNotBeA',
  toBeTruthy: 'toExist',
  toBeFalsy: 'toNotExist',
  toBeFewerThan: 'toBeLessThan',
  toBeMoreThan: 'toBeGreaterThan',
  toContain: 'toInclude',
  toNotContain: 'toExclude',
  toNotInclude: 'toExclude',
  toContainKeys: 'toIncludeKeys',
  toNotContainKeys: 'toExcludeKeys',
  toNotIncludeKeys: 'toExcludeKeys',
  toContainKey: 'toIncludeKey',
  toNotContainKey: 'toExcludeKey',
  toNotIncludeKey: 'toExcludeKey'
}

for (const alias in aliases)
  if (aliases.hasOwnProperty(alias))
    Expectation.prototype[alias] = Expectation.prototype[aliases[alias]]

export default Expectation
<|endoftext|>


<commit_before>// connections.js v. 0.1 part of the Application Frame

$('new')({
    name :'connections',
    object : {
        classes : {
            Socket : function(type, url){
                this._type= type;
                this._url= url;
                this._lastMessage= null;
                this._open= false;
                this._xhr= new $$.XMLHttpRequest();
            }
        },

        statics : {
            UPSTREAM_NORMAL : 0,
            DOWNSTREAM_NORMAL : 1
        }
    },
    _init : function(me){
        me.classes.Socket.prototype= {
            get url(){
                return this._url;
            },

            get lastMessage(){
                return this._lastMessage;
            },

            get open(){
                return this._open;
            },

            push : function(message){
                var me= this;
                return new $$.Promise(function(setVaule, setError){
                    me._xhr.open('POST', this._url, true);
                    me.send(message);
                    me._xhr.onreadystatechange= function(e){
                        if(e.readyState == 4){
                            if(e.status == 200){
                                setVaule(e);
                            }else{
                                setError(e);
                            }
                        me._lastMessage= e.statusText;
                        }
                    };
                });
            }
        };
    }
});
<commit_msg>stabilizing of Socket<commit_after>// connections.js v. 0.1 part of the Application Frame

$('new')({
    name :'connections',
    object : {
        classes : {
            Socket : function(type, url){
                this._type= type;
                this._url= url;
                this._lastMessage= null;
                this._open= false;
            }
        }
    },
    _init : function(me){
        var { Promise } = $('classes');
        me.classes.Socket.prototype= {
            get url(){
                return this._url;
            },

            get lastMessage(){
                return this._lastMessage;
            },

            get open(){
                return this._open;
            },

            push : function(message){
                var self= this;
                var xhr= new $$.XMLHttpRequest();
                return new Promise(function(setValue, setError){
                    xhr.onreadystatechange= function(){
                        if(this.readyState == 4){
                            if(this.status == 200){
                                setValue(this.responseText);
                            }else{
                                setError({status : this.status, statusText : this.statusText});
                            }
                        self._lastMessage= this.statusText;
                        }
                    };
                    if(self._type == me.classes.Socket.HTTP_POST){
                        xhr.open('POST', self._url, true);
                        xhr.send(message);
                    }else if(self._type == me.classes.Socket.HTTP_GET){
                        xhr.open('GET', self._url + '?' + message, true);
                        xhr.send();
                    }
                });
            }
        };
    me.classes.Socket.HTTP_GET= 'http_get';
    me.classes.Socket.HTTP_POST= 'http_post';
    me.classes.Socket.HTTP= 'http_post';
    }
});
<|endoftext|>


<commit_before>// PiscoBot Script

var commandDescription = {
  name: '',
  author: '',
  trigger: '',
  version: 1.0,
  description: '',
  module: ''
};

global.botHelp.push(commandDescription);

var _ = require('underscore');

function modifyPoints(bot, message, value) {
  var userMatcher = /<@([A-Z0-9]*)>/g;
  var usersMatched = message.text.match(userMatcher);
  var userIDs = [];
  for(var rawUser of usersMatched) {
    var trimmedID = rawUser.replace(/(<|@|>)/g, '');
    userIDs.push(trimmedID);
  }
  if(!_.isEmpty(userIDs)) {
    for(var userID of userIDs) {
      global.piscobot.storage.users.get(userID, function(err, user) {
        if(!err) {
          if(!user) {
            user = { id: userID };
            user.points = 0;
          }
          user.points += value;
          global.piscobot.storage.users.save(user);
        }
      });
    }
  }
}

global.piscobot.hears(
  [':poop:', ':hankey:', ':shit:', ':pisco:', ':tropical_drink:'],
  ['ambient'],
  function(bot, message) {
    var add = [':pisco:', ':tropical_drink:'];
    var remove = [':poop:', ':hankey:', ':shit:'];
    if(_.contains(add, message.match[0])) {
      modifyPoints(bot, message, +1);
    } else if(_.contains(remove, message.match[0])) {
      modifyPoints(bot, message, -1);
    }
  }
);
<commit_msg>Add a description to the Points command<commit_after>// PiscoBot Script

var commandDescription = {
  name: 'Points',
  author: 'Daniel Gallegos [@that_taco_guy]',
  trigger: ':pisco:/:poop:',
  version: 1.0,
  description: 'Give or take away points from other users.',
  module: 'Core'
};

global.botHelp.push(commandDescription);

var _ = require('underscore');

function modifyPoints(bot, message, value) {
  var userMatcher = /<@([A-Z0-9]*)>/g;
  var usersMatched = message.text.match(userMatcher);
  var userIDs = [];
  for(var rawUser of usersMatched) {
    var trimmedID = rawUser.replace(/(<|@|>)/g, '');
    userIDs.push(trimmedID);
  }
  if(!_.isEmpty(userIDs)) {
    for(var userID of userIDs) {
      global.piscobot.storage.users.get(userID, function(err, user) {
        if(!err) {
          if(!user) {
            user = { id: userID };
            user.points = 0;
          }
          user.points += value;
          global.piscobot.storage.users.save(user);
        }
      });
    }
  }
}

global.piscobot.hears(
  [':poop:', ':hankey:', ':shit:', ':pisco:', ':tropical_drink:'],
  ['ambient'],
  function(bot, message) {
    var add = [':pisco:', ':tropical_drink:'];
    var remove = [':poop:', ':hankey:', ':shit:'];
    if(_.contains(add, message.match[0])) {
      modifyPoints(bot, message, +1);
    } else if(_.contains(remove, message.match[0])) {
      modifyPoints(bot, message, -1);
    }
  }
);
<|endoftext|>


<commit_before>// m16_001 #508 % 510
//
casper.test.begin('m16_001 #508 and 510 handle missing key bib_format', 1, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/787084';
var ENTITY=SERVER+USECASE;
casper.echo(ENTITY);
	casper.start(ENTITY, function() {
    test.assertTextExists('Adante pastoral','retrieved a title, it matched');
    }).run(function() {
        test.done();
    });
});
<commit_msg>edited title match<commit_after>// m16_001 #508 % 510
//
casper.test.begin('m16_001 #508 and 510 handle missing key bib_format', 1, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/787084';
var ENTITY=SERVER+USECASE;
casper.echo(ENTITY);
	casper.start(ENTITY, function() {
    test.assertTextExists('Andante pastoral','retrieved a title, it matched');
    }).run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>// m27_001 #640
//
casper.test.begin('m27_001 #640 hathi trust online', 3, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/7269114';
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('Hathi Trust' , '');
	test.assertTextExists('Record 000124204' , '');
	test.assertTextExists('Treasure island' , '');
    }).run(function() {
        test.done();
    });
});
<commit_msg>updated test message<commit_after>// m27_001 #640
//
casper.test.begin('m27_001 #640 hathi trust online', 3, function suite(test) {
casper.echo("Test environment: "+SERVER);
var USECASE='/item/7269114';
var ENTITY=SERVER+USECASE;
	casper.start(ENTITY, function() {
	test.assertTextExists('Hathi Trust' , 'found Hathi Trust holding');
	test.assertTextExists('Record 000124204' , 'match Hathi record number');
	test.assertTextExists('Treasure island' , 'matched title');
    }).run(function() {
        test.done();
    });
});
<|endoftext|>


<commit_before>include('helma/webapp/response');
include('helma/jsdoc');
require('core/array');

var log = require('helma/logging').getLogger(module.id);

exports.index = function index(req, module) {
    var repo = new ScriptRepository(require.paths.peek());
    if (module && module != "/") {
        var res = repo.getScriptResource(module);
        var jsdoc = parseResource(res);
        // log.info("export()ed symbols: " + exported);
        return new SkinnedResponse(getResource('./skins/module.html'), {
            title: "Module " + res.moduleName,
            jsdoc: jsdoc
        });
    } else {
        var modules = repo.getScriptResources(true).sort(function(a, b) {
            return a.relativePath > b.relativePath ? 1 : -1;
        });
        return new SkinnedResponse(getResource('./skins/index.html'), {
            title: "API Documentation",
            modules: modules
        });
    }
}

<commit_msg>Exclude test suite from jsdoc<commit_after>include('helma/webapp/response');
include('helma/jsdoc');
require('core/array');

var log = require('helma/logging').getLogger(module.id);

exports.index = function index(req, module) {
    var repo = new ScriptRepository(require.paths.peek());
    if (module && module != "/") {
        var res = repo.getScriptResource(module);
        var jsdoc = parseResource(res);
        // log.info("export()ed symbols: " + exported);
        return new SkinnedResponse(getResource('./skins/module.html'), {
            title: "Module " + res.moduleName,
            jsdoc: jsdoc
        });
    } else {
        var modules = repo.getScriptResources(true).filter(function(r) {
            return r.relativePath.indexOf('test') != 0;
        }).sort(function(a, b) {
            return a.relativePath > b.relativePath ? 1 : -1;
        });
        return new SkinnedResponse(getResource('./skins/index.html'), {
            title: "API Documentation",
            modules: modules
        });
    }
}

<|endoftext|>