<commit_before>var express = require('express'),
    path    = require('path'),
    exec    = require('child_process').exec,
    i18n    = require('i18n-abide'),
    _       = require('underscore'),
    backboneio = require('backbone.io'),
    mbc = require('mbc-common'),
    conf = mbc.config.Caspa,
    search_options = mbc.config.Search,
    collections = mbc.config.Common.Collections,
    moment = require('moment'),
    App = require("mbc-common/models/App"),
    maxage = 365 * 24 * 60 * 60 * 1000,
    uuid = require('node-uuid'),
    logger = mbc.logger().addLogger('caspa_server')
 ;

var loggerStream = {
    write: function(message, encoding) {
        logger.info(message);
    }
};

/* make sure at runtime that we atempt to get the dirs we need */
for (d in conf.Dirs) {
    /* HACK: but I'm not going to waist time writing mkdir -p */
    exec ('mkdir -p ' + conf.Dirs[d], function (error, stdout, stderr) {
        if (error !== null) {
            logger.error('exec error: ' + error);
        }
    });
}

var app = express();

app.configure(function () {
    app.use(i18n.abide({
        supported_languages: ['en-US', 'es', 'db-LB', 'it-CH'],
        default_lang: 'es',
        debug_lang: 'it-CH',
        translation_directory: 'locale'
    }));
    app.set('port', process.env.PORT || 3000);
    app.set('views', conf.Dirs.views);
    app.set('view engine', 'jade');
    app.use(express.logger({ stream: loggerStream, format: 'dev' }));
    app.use(express.compress());
/*    app.use('/uploads', upload({
        tmpDir:    conf.Dirs.uploads + '/incoming',
        uploadDir: conf.Dirs.upolads,
        uploadUrl: '/uploads/',
        safeFileTypes: /\.(webm|mkv|mov|mp4|avi|ogg)$/i,
    }));*/
    app.use(express.bodyParser({
            uploadDir: conf.Dirs.uploads,
            maxFieldsSize: 10 * 1024 * 1024
    }));
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.cookieSession({ secret: 'your secret here', cookie: { maxAge: maxage }}));
    app.use(require('less-middleware')({
        src:  conf.Dirs.styles,
        dest: conf.Dirs.pub,
        compress: true}
    ));
    app.use(express.static(conf.Dirs.pub, {maxAge: maxage}));
    app.use('/models', express.static(conf.Dirs.models, {maxAge: maxage}));
    app.use('/lib',    express.static(conf.Dirs.vendor, {maxAge: maxage}));
    app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.set('io.loglevel', 100);
  app.set('minify', false);
});

app.configure('production', function(){
  app.use(express.errorHandler());
  app.set('io.loglevel', 1);
  app.set('minify', true);
});

var appModel = require('./routes')(app);
//var media = require('./routes/media')(app);

// Override mongoStore read method with custom
var searchWrapper = require('./searchWrapper.js');

function debug_backend (backend) {
    backend.use(function(req, res, next) {
        logger.debug('Backend: ', req.backend);
        logger.debug('Method: ', req.method);
        logger.debug('Channel: ', req.channel);
        logger.debug('Options: ', JSON.stringify(req.options));
        logger.debug('Model: ', JSON.stringify(req.model));
        next();
    });
}

function id_middleware(req, res, next) {
    if( req.method == 'create' && req.model._id === undefined) {
        req.model._id = uuid.v1();
    }
    next();
}

var db = mbc.db();

var publisher = mbc.pubsub();
var listener = mbc.pubsub();

var appbackend = backboneio.createBackend();
var transformbackend = backboneio.createBackend();
var mediabackend = backboneio.createBackend();
var piecebackend = backboneio.createBackend();
var listbackend = backboneio.createBackend();
var schedbackend = backboneio.createBackend();
var statusbackend = backboneio.createBackend();
var framebackend = backboneio.createBackend();
var mostomessagesbackend = backboneio.createBackend();

var backends = [ appbackend, transformbackend, mediabackend, piecebackend, listbackend, schedbackend, statusbackend, framebackend, mostomessagesbackend ];
_(backends).each (debug_backend);

appbackend.use(backboneio.middleware.configStore());

transformbackend.use(id_middleware);
transformbackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Transforms, { search: search_options.Transforms })));

mediabackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Medias, { search: search_options.Medias })));

piecebackend.use(id_middleware);
piecebackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Pieces, { search: search_options.Pieces })));

listbackend.use(id_middleware);
listbackend.use(searchWrapper(backboneio.middleware.mongoStore (db, collections.Lists, { search: search_options.Lists })));

schedbackend.use(id_middleware);
schedbackend.use(function (req, res, next) {
    publisher.publishJSON([req.backend, req.method].join('.'), { model: req.model });
    next();
});
schedbackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Scheds, { search: search_options.Scheds })));

listener.on('JSONmessage', function(chan, status) {

    if( chan != "mostoStatus" ) // we can ignore this message
        return;

    // This receives messages from mosto and propagates the message through
    //  backbone.io
    var emit = _.after(6, function() {
        logger.info('emitting', status);
        statusbackend.emit('updated', status)
    });
    ['previous', 'current', 'next'].forEach(function(pos) {
        db.collection(collections.Scheds).findEach({ _id: status.show[pos]._id }, function(err, res) {
            if( res ) {
                status.show[pos] = {
                    name: res.title,
                    _id: res._id,
                };
            }
            emit();
        });
        //db.collection('lists').findEach({ "models._id": status.piece[pos]._id }, function(err, res) {
        db.collection(collections.Pieces).findById(status.piece[pos]._id, function(err, piece) {
            if( err ) {
                // we still want to call emit() even if there was a DB error
                logger.error(err);
            }

            if( piece ) {
                /*
                var piece = _.chain(res.models).filter(function(p) {
                    return p._id == status.piece[pos]._id;
                }).value();
                console.log("[mosto status] filtered pieces", piece)
                if( !piece ) {
                    var message = "[mosto status] error: this shouldn't be empty";
                    console.log(message);
                    return new Error(message);
                }
                if( piece.length != 1 ) {
                    var message = "[mosto status] error: there must only be one!";
                    console.log(message)
                    return new Error(message);
                }

                piece = piece[0];
                */
                status.piece[pos] = piece;
                // default name to id
                if( !status.piece[pos].name ) {
                    var file = piece.file;
                    status.piece[pos].name = path.basename(file).replace(path.extname(file), '');
                }
            }
            emit();
        });
    });
});
listener.subscribe('mostoStatus');
statusbackend.use(backboneio.middleware.mongoStore(db, collections.Status, { search: search_options.Status }));

listener.on('JSONmessage', function(chan, msg) {
    if( !(chan == 'mostoStatus.progress' ) )
        return;

    var status = new App.ProgressStatus(msg);
    framebackend.emit('updated', status);
});
listener.subscribe('mostoStatus.progress');
framebackend.use(backboneio.middleware.memoryStore(db, 'progress', {}));

// there should probably be two backends or two collections or both, or something, one for
// one-time momentary messages like warnings and such to be dismissed by the frontend,
// and another one for "sticky" messages like long-lived status problems, like if melted died
// or the DB has a problem
listener.on('JSONpmessage', function(pattern, chan, msg) {
    switch( chan ) {
        case "mostoMessage.emit":
            return mostomessagesbackend.emit('created', msg.model);
        case "mostoMessage.create":
            return mostomessagesbackend.emit('created', msg.model);
        case "mostoMessage.delete":
            return mostomessagesbackend.emit('deleted', msg.model);
    }
});
listener.psubscribe('mostoMessage*');
mostomessagesbackend.use(backboneio.middleware.mongoStore(db, collections.Mostomessages, { search: search_options.Mostomessages }));

_(backends).each (function(backend) {
    logger.info("Debugging backend: ", backend);
});

var io = backboneio.listen(app.listen(app.get('port'), function(){
    logger.info("Express server listening on port " + app.get('port') + " in mode " + app.settings.env);
}), { appbackend: appbackend,
      transformbackend: transformbackend,
      mediabackend: mediabackend,
      piecebackend: piecebackend,
      listbackend:  listbackend,
      schedbackend: schedbackend,
      statusbackend: statusbackend,
      framebackend: framebackend,
      mostomessagesbackend: mostomessagesbackend
    });

io.configure('production', function(){
    io.enable('browser client minification');  // send minified client
    io.enable('browser client etag');          // apply etag caching logic based on version number
    io.enable('browser client gzip');          // gzip the file
});

io.set('logger', logger); // Log socket.io with custom logger

var utils = require('./utils');

if (process.env.MBC_SCRAPE) {
    setTimeout(function () {
        utils.scrape_files (conf.Dirs.scrape, function (model) {
            db.collection(collections.Medias).insert(model, {safe:true}, function(err, result) {
                if (err) {
                    logger.error('error','An error has occurred' + err);
                } else {
                    mediabackend.emit('created', model);
                }
            });
        });
    }, 300);
} else {
    logger.info ("not scrapping");
}
<commit_msg>Settings to Deploy on Heroku<commit_after>var express = require('express'),
    path    = require('path'),
    exec    = require('child_process').exec,
    i18n    = require('i18n-abide'),
    _       = require('underscore'),
    backboneio = require('backbone.io'),
    mbc = require('mbc-common'),
    conf = mbc.config.Caspa,
    search_options = mbc.config.Search,
    collections = mbc.config.Common.Collections,
    moment = require('moment'),
    App = require("mbc-common/models/App"),
    maxage = 365 * 24 * 60 * 60 * 1000,
    uuid = require('node-uuid'),
    logger = mbc.logger().addLogger('caspa_server')
 ;

var loggerStream = {
    write: function(message, encoding) {
        logger.info(message);
    }
};

/* make sure at runtime that we atempt to get the dirs we need */
for (d in conf.Dirs) {
    /* HACK: but I'm not going to waist time writing mkdir -p */
    exec ('mkdir -p ' + conf.Dirs[d], function (error, stdout, stderr) {
        if (error !== null) {
            logger.error('exec error: ' + error);
        }
    });
}

var app = express();

app.configure(function () {
    app.use(i18n.abide({
        supported_languages: ['en-US', 'es', 'db-LB', 'it-CH'],
        default_lang: 'es',
        debug_lang: 'it-CH',
        translation_directory: 'locale'
    }));
    app.set('port', process.env.PORT || 3000);
    app.set('views', conf.Dirs.views);
    app.set('view engine', 'jade');
    app.use(express.logger({ stream: loggerStream, format: 'dev' }));
    app.use(express.compress());
/*    app.use('/uploads', upload({
        tmpDir:    conf.Dirs.uploads + '/incoming',
        uploadDir: conf.Dirs.upolads,
        uploadUrl: '/uploads/',
        safeFileTypes: /\.(webm|mkv|mov|mp4|avi|ogg)$/i,
    }));*/
    app.use(express.bodyParser({
            uploadDir: conf.Dirs.uploads,
            maxFieldsSize: 10 * 1024 * 1024
    }));
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.cookieSession({ secret: 'your secret here', cookie: { maxAge: maxage }}));
    app.use(require('less-middleware')({
        src:  conf.Dirs.styles,
        dest: conf.Dirs.pub,
        compress: true}
    ));
    app.use(express.static(conf.Dirs.pub, {maxAge: maxage}));
    app.use('/models', express.static(conf.Dirs.models, {maxAge: maxage}));
    app.use('/lib',    express.static(conf.Dirs.vendor, {maxAge: maxage}));
    app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.set('io.loglevel', 100);
  app.set('minify', false);
});

app.configure('production', function(){
  app.use(express.errorHandler());
  app.set('io.loglevel', 1);
  app.set('minify', true);
});

var appModel = require('./routes')(app);
//var media = require('./routes/media')(app);

// Override mongoStore read method with custom
var searchWrapper = require('./searchWrapper.js');

function debug_backend (backend) {
    backend.use(function(req, res, next) {
        logger.debug('Backend: ', req.backend);
        logger.debug('Method: ', req.method);
        logger.debug('Channel: ', req.channel);
        logger.debug('Options: ', JSON.stringify(req.options));
        logger.debug('Model: ', JSON.stringify(req.model));
        next();
    });
}

function id_middleware(req, res, next) {
    if( req.method == 'create' && req.model._id === undefined) {
        req.model._id = uuid.v1();
    }
    next();
}

var db = mbc.db();

var publisher = mbc.pubsub();
var listener = mbc.pubsub();

var appbackend = backboneio.createBackend();
var transformbackend = backboneio.createBackend();
var mediabackend = backboneio.createBackend();
var piecebackend = backboneio.createBackend();
var listbackend = backboneio.createBackend();
var schedbackend = backboneio.createBackend();
var statusbackend = backboneio.createBackend();
var framebackend = backboneio.createBackend();
var mostomessagesbackend = backboneio.createBackend();

var backends = [ appbackend, transformbackend, mediabackend, piecebackend, listbackend, schedbackend, statusbackend, framebackend, mostomessagesbackend ];
_(backends).each (debug_backend);

appbackend.use(backboneio.middleware.configStore());

transformbackend.use(id_middleware);
transformbackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Transforms, { search: search_options.Transforms })));

mediabackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Medias, { search: search_options.Medias })));

piecebackend.use(id_middleware);
piecebackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Pieces, { search: search_options.Pieces })));

listbackend.use(id_middleware);
listbackend.use(searchWrapper(backboneio.middleware.mongoStore (db, collections.Lists, { search: search_options.Lists })));

schedbackend.use(id_middleware);
schedbackend.use(function (req, res, next) {
    publisher.publishJSON([req.backend, req.method].join('.'), { model: req.model });
    next();
});
schedbackend.use(searchWrapper(backboneio.middleware.mongoStore(db, collections.Scheds, { search: search_options.Scheds })));

listener.on('JSONmessage', function(chan, status) {

    if( chan != "mostoStatus" ) // we can ignore this message
        return;

    // This receives messages from mosto and propagates the message through
    //  backbone.io
    var emit = _.after(6, function() {
        logger.info('emitting', status);
        statusbackend.emit('updated', status)
    });
    ['previous', 'current', 'next'].forEach(function(pos) {
        db.collection(collections.Scheds).findEach({ _id: status.show[pos]._id }, function(err, res) {
            if( res ) {
                status.show[pos] = {
                    name: res.title,
                    _id: res._id,
                };
            }
            emit();
        });
        //db.collection('lists').findEach({ "models._id": status.piece[pos]._id }, function(err, res) {
        db.collection(collections.Pieces).findById(status.piece[pos]._id, function(err, piece) {
            if( err ) {
                // we still want to call emit() even if there was a DB error
                logger.error(err);
            }

            if( piece ) {
                /*
                var piece = _.chain(res.models).filter(function(p) {
                    return p._id == status.piece[pos]._id;
                }).value();
                console.log("[mosto status] filtered pieces", piece)
                if( !piece ) {
                    var message = "[mosto status] error: this shouldn't be empty";
                    console.log(message);
                    return new Error(message);
                }
                if( piece.length != 1 ) {
                    var message = "[mosto status] error: there must only be one!";
                    console.log(message)
                    return new Error(message);
                }

                piece = piece[0];
                */
                status.piece[pos] = piece;
                // default name to id
                if( !status.piece[pos].name ) {
                    var file = piece.file;
                    status.piece[pos].name = path.basename(file).replace(path.extname(file), '');
                }
            }
            emit();
        });
    });
});
listener.subscribe('mostoStatus');
statusbackend.use(backboneio.middleware.mongoStore(db, collections.Status, { search: search_options.Status }));

listener.on('JSONmessage', function(chan, msg) {
    if( !(chan == 'mostoStatus.progress' ) )
        return;

    var status = new App.ProgressStatus(msg);
    framebackend.emit('updated', status);
});
listener.subscribe('mostoStatus.progress');
framebackend.use(backboneio.middleware.memoryStore(db, 'progress', {}));

// there should probably be two backends or two collections or both, or something, one for
// one-time momentary messages like warnings and such to be dismissed by the frontend,
// and another one for "sticky" messages like long-lived status problems, like if melted died
// or the DB has a problem
listener.on('JSONpmessage', function(pattern, chan, msg) {
    switch( chan ) {
        case "mostoMessage.emit":
            return mostomessagesbackend.emit('created', msg.model);
        case "mostoMessage.create":
            return mostomessagesbackend.emit('created', msg.model);
        case "mostoMessage.delete":
            return mostomessagesbackend.emit('deleted', msg.model);
    }
});
listener.psubscribe('mostoMessage*');
mostomessagesbackend.use(backboneio.middleware.mongoStore(db, collections.Mostomessages, { search: search_options.Mostomessages }));

_(backends).each (function(backend) {
    logger.info("Debugging backend: ", backend);
});

var io = backboneio.listen(app.listen(app.get('port'), function(){
    logger.info("Express server listening on port " + app.get('port') + " in mode " + app.settings.env);
}), { appbackend: appbackend,
      transformbackend: transformbackend,
      mediabackend: mediabackend,
      piecebackend: piecebackend,
      listbackend:  listbackend,
      schedbackend: schedbackend,
      statusbackend: statusbackend,
      framebackend: framebackend,
      mostomessagesbackend: mostomessagesbackend
    });

io.configure('production', function(){
    io.enable('browser client minification');  // send minified client
    io.enable('browser client etag');          // apply etag caching logic based on version number
    io.enable('browser client gzip');          // gzip the file
});

if (process.env.HEROKU) {
    io.configure(function () {
        io.set("transports", ["xhr-polling"]);
        io.set("polling duration", 10);
    });
}

io.set('logger', logger); // Log socket.io with custom logger

var utils = require('./utils');

if (process.env.MBC_SCRAPE) {
    setTimeout(function () {
        utils.scrape_files (conf.Dirs.scrape, function (model) {
            db.collection(collections.Medias).insert(model, {safe:true}, function(err, result) {
                if (err) {
                    logger.error('error','An error has occurred' + err);
                } else {
                    mediabackend.emit('created', model);
                }
            });
        });
    }, 300);
} else {
    logger.info ("not scrapping");
}
<|endoftext|>


<commit_before>var fs = require('fs');
var cheerio = require('cheerio');
var file = process.argv[2];

fs.readFile(file, function processTemplates (err, contents) {
  $ = cheerio.load(contents, {
          xmlMode: true
        });

  //function to replace element, keeping innerHtml & attributes
  function replaceEl (selector, newTag) {
    selector.each(function(){
      var myAttr = $(this).attr();
      var myHtml = $(this).html();
      $(this).replaceWith(function(){
          return $(newTag).html(myHtml).attr(myAttr);
      });
    });
  }

  //selections
  var ems = $("span[class='spanitaliccharactersital']");
  var strongs = $("span[class='spanboldfacecharactersbf']");
  var sups = $("span[class='spansuperscriptcharacterssup']");
  var subs = $("span[class='spansubscriptcharacterssub']");
  var scitals = $("span[class='spansmcapitalscital']");
  var scbolds = $("span[class='spansmcapboldscbold']");
  var italbems = $("span[class='spanbolditalbem']");
  //call replaceEl to replace selected span elements with formatting tags
  replaceEl (ems, "");
  replaceEl (strongs, "");
  replaceEl (sups, "");
  replaceEl (subs, "");
  //these two spans require nested tags, wrapping existing span (wth appropriate class) with new tag
  scitals.each(function(){
    $(this).wrap("");
  });
  scbolds.each(function(){
    $(this).wrap("");
  });
  //this span requires an element be replaced and wrapped, same function as above + this.wrap
  italbems.each(function(){
    var myAttr = $(this).attr();
    var myHtml = $(this).html();
    $(this).wrap("");
    $(this).replaceWith(function(){
        return $("").html(myHtml).attr(myAttr);
    });
  });

  // support for inline images
  $('span.spanillustrationholderilli').each(function () {
    var mytext = $(this).text().trim();
    var el = $('');
    $(this).empty();
    $(this).append(el);
  });

  var output = $.html();
    fs.writeFile(file, output, function(err) {
	    if(err) {
	        return console.log(err);
	    }

      console.log("Processing instructions have been evaluated!");
	});
});<commit_msg>removing inline design notes<commit_after>var fs = require('fs');
var cheerio = require('cheerio');
var file = process.argv[2];

fs.readFile(file, function processTemplates (err, contents) {
  $ = cheerio.load(contents, {
          xmlMode: true
        });

  //function to replace element, keeping innerHtml & attributes
  function replaceEl (selector, newTag) {
    selector.each(function(){
      var myAttr = $(this).attr();
      var myHtml = $(this).html();
      $(this).replaceWith(function(){
          return $(newTag).html(myHtml).attr(myAttr);
      });
    });
  }

  //selections
  var ems = $("span[class='spanitaliccharactersital']");
  var strongs = $("span[class='spanboldfacecharactersbf']");
  var sups = $("span[class='spansuperscriptcharacterssup']");
  var subs = $("span[class='spansubscriptcharacterssub']");
  var scitals = $("span[class='spansmcapitalscital']");
  var scbolds = $("span[class='spansmcapboldscbold']");
  var italbems = $("span[class='spanbolditalbem']");
  //call replaceEl to replace selected span elements with formatting tags
  replaceEl (ems, "");
  replaceEl (strongs, "");
  replaceEl (sups, "");
  replaceEl (subs, "");
  //these two spans require nested tags, wrapping existing span (wth appropriate class) with new tag
  scitals.each(function(){
    $(this).wrap("");
  });
  scbolds.each(function(){
    $(this).wrap("");
  });
  //this span requires an element be replaced and wrapped, same function as above + this.wrap
  italbems.each(function(){
    var myAttr = $(this).attr();
    var myHtml = $(this).html();
    $(this).wrap("");
    $(this).replaceWith(function(){
        return $("").html(myHtml).attr(myAttr);
    });
  });

  // support for inline images
  $('span.spanillustrationholderilli').each(function () {
    var mytext = $(this).text().trim();
    var el = $('');
    $(this).empty();
    $(this).append(el);
  });

  // remove inline design notes
  $('span.spandesignnotedni').remove();

  var output = $.html();
    fs.writeFile(file, output, function(err) {
	    if(err) {
	        return console.log(err);
	    }

      console.log("Processing instructions have been evaluated!");
	});
});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Button,
    ScrollView,
    Image
} from 'react-native';
import SendButton from './send-button';
import Device from 'react-native-device-detection';
import ChatBox from './chat-box';

export default class Home extends Component {

    constructor() {

        super();

        this.state = {

            message: '',
            messageStore: [],
        }

    }
    render() {
        return (
            <Image source={require('../assets/images/background-image.jpg')} style={styles.container}>
                <ScrollView style={styles.messageContainer}>

                    {this.chatCreator()}
                </ScrollView>
                <View style={styles.inputContainer}>
                    <View style={styles.input} >
                        <TextInput ref='message' numberOfLines={5} multiline={true} style={{ padding: 10 }}
                            underlineColorAndroid='rgba(0,0,0,0)' placeholder="Type Your Message Here...."
                            onChangeText={(message) => this.setState({ message })}>
                        </TextInput>

                    </View>
                    <View style={styles.buttonContainer}>
                        <SendButton onPress={this.onSendButton.bind(this)} />
                    </View>
                </ View>

            </Image>
        );
    }

    onSendButton() {

        this.setState({

            messageStore: this.state.messageStore.concat(this.state.message),
        })

    }

    chatCreator() {

        return this.state.messageStore.map((message, index) => {

            return (
                <ChatBox msg={message} />

            );
        });

    }
}

styles = StyleSheet.create({
    container: {
        flex: 1,
        resizeMode: 'cover',
        width: Device.width,

    },
    inputContainer: {
        flex: 0.2,
        marginBottom: 10,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        width: Device.width,
        marginLeft: 7,
        marginTop: 10,
    },
    input: {
        flex: 0.9,
        height: 50,
        backgroundColor: '#FFF',
        borderColor: 'skyblue',
        borderWidth: 1,
        borderTopLeftRadius: 15,
        borderBottomLeftRadius: 15,
        borderBottomRightRadius: 15,
        width: 300,
    },
    messageContainer: {
        flex: 0.8,
    },
    buttonContainer: {

        flex: 0.2,
    }
});<commit_msg>blank message prevention<commit_after>import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    View,
    TextInput,
    Button,
    ScrollView,
    Image
} from 'react-native';
import SendButton from './send-button';
import Device from 'react-native-device-detection';
import ChatBox from './chat-box';

export default class Home extends Component {

    constructor() {

        super();

        this.state = {

            message: '',
            messageStore: [],
        }

    }
    render() {
        return (
            <Image source={require('../assets/images/background-image.jpg')} style={styles.container}>
                <ScrollView style={styles.messageContainer}>

                    {this.chatCreator()}
                </ScrollView>
                <View style={styles.inputContainer}>
                    <View style={styles.input} >
                        <TextInput ref='message' numberOfLines={5} multiline={true} style={{ padding: 10 }}
                            underlineColorAndroid='rgba(0,0,0,0)' placeholder="Type Your Message Here...."
                            onChangeText={(message) => this.setState({ message })}>
                        </TextInput>

                    </View>
                    <View style={styles.buttonContainer}>
                        <SendButton onPress={this.onSendButton.bind(this)} />
                    </View>
                </ View>

            </Image>
        );
    }

    onSendButton() {

        this.setState({

            messageStore: this.state.messageStore.concat(this.state.message),
        })

    }

    chatCreator() {

        return this.state.messageStore.map((message, index) => {
            if (message != '') {
                return (<ChatBox msg={message} />);
            }
        });

    }
}

styles = StyleSheet.create({
    container: {
        flex: 1,
        resizeMode: 'cover',
        width: Device.width,

    },
    inputContainer: {
        flex: 0.2,
        marginBottom: 10,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        width: Device.width,
        marginLeft: 7,
        marginTop: 10,
    },
    input: {
        flex: 0.9,
        height: 50,
        backgroundColor: '#FFF',
        borderColor: 'skyblue',
        borderWidth: 1,
        borderTopLeftRadius: 15,
        borderBottomLeftRadius: 15,
        borderBottomRightRadius: 15,
        width: 300,
    },
    messageContainer: {
        flex: 0.8,
    },
    buttonContainer: {

        flex: 0.2,
    }
});<|endoftext|>


<commit_before>jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
    return this.each(function() {
        var select = this;

        $(textbox).bind('change keyup', function() {
            //var options = $(select).empty().data('options');
            var search = $(this).val().trim();
            var regex = new RegExp(search, "gi");
            var shown = [];
            $(select).find("label").each(function() {
                // child = <input type='checkbox .../>
                var child = $(this);
                /*
                if (child.hasClass("toggle-parent-label")) {
                	return;
                }
                */
                var childText = child.find("input").attr("value");
                if (childText && childText.match(regex) !== null) {
                    child.show();
                    var parent = child.find("input").attr("parent");
                    if (parent && shown.indexOf(parent) < 0) {
                        shown.push(parent);
                    }
                } else {
                    child.hide();
                }
            });
            // make sure parents are shown even if they text doesn't match
            $.each(shown, function() {
                $(".toggle-parent-label[key='" + this + "']").show();
            });
        });
    });
};
jQuery.fn.multiselect = function() {
    $(this).each(function() {
        var checkboxes = $(this).find(".toggle-checkbox-item");
        checkboxes.each(function() {
            var checkbox = $(this);
            // Highlight pre-selected checkboxes
            if (checkbox.attr("checked")) checkbox.parent().addClass("multiselect-on");
            // Highlight checkboxes that the user selects
            checkbox.click(function() {
                if (checkbox.attr("checked")) checkbox.parent().addClass("multiselect-on");
                else checkbox.parent().removeClass("multiselect-on");
            });
        });
    });
};

function toggleVisibleReports(checked, selector) {
    $(selector).find("input[type='checkbox']:visible").prop('checked', checked);
}

// regular functions
function split(val) {
    return val.split(/,\s*/);
}

$(document).ready(function() {

	// initialize the cohort type ahead, constructs the suggestion engine
    var bloodhoundCohorts = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 20,
        // use /data/sample-cohorts.json just to start off
        prefetch: '/data/sample-cohorts.json',
    });
    bloodhoundCohorts.initialize();

    // initialize bootstrap data toggle
    $("body").tooltip({ selector: '[data-toggle=tooltip]' });

    // typeahead cohort listener
    $('#cohorts-typeahead .typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'cohorts',
        displayKey: 'value',
        source: bloodhoundCohorts.ttAdapter(),
        templates: {
            empty: [
                '
',
                'Unable to find any cohorts that match the current query',
                '
'
            ].join('\n'),
            suggestion: Handlebars.compile('
{{name}} – {{description}}
')
        }
    });

    // on select a cohort
    $("#cohorts-typeahead").bind('typeahead:selected', function(obj, datum, name) {
        $("#cohorts").val(datum.name);

        $(".page-one").slideUp("fast", function() {
        	// set page data
        	angular.element($('#cohort-explorer-main')).scope().showCohort(datum);

        	// show div
            $("#cohort-explorer-main").slideDown("slow");
        });

    });

    // go back listener on cohort explorer
    $("#cohort-explorer-back").click(function() {
    	$("#cohort-explorer-main").slideUp("fast", function() {
            $(".page-one").slideDown('fast'), function() {
                setTimeout(function(){
                	$("#cohorts-typeahead").focus();
                }, 3000);
            }
        });
    });

    // set up auto checkbox filters
    //setup select/clear filters events
    $(".auto-filter-check-list-select").click(function() {
        toggleVisibleReports(true, ".multiselect[filter-key='" + $(this).attr("filter-key") + "']");
        return false;
    });
    $(".auto-filter-check-list-clear").click(function() {
        toggleVisibleReports(false, ".multiselect[filter-key='" + $(this).attr("filter-key") + "']");
        return false;
    });
    // trigger parent click
    $(".toggle-parent-label").click(function() {
    	  var checked = $(this).prop("checked");
          $("input[parent='" + $(this).val() + "']:visible").prop("checked", checked);
    });

    // add event listeners to show multiselect divs
    $(".auto-filter-check-list-input")
	    .focus(function() {
	    	var key = $(this).attr("filter-key");
	    	$(".multiselect-wrapper[filter-key='" + key + "']").slideDown("slow");
	    }).blur(function() {
	    	var key = $(this).attr("filter-key");
	    	$(".multiselect-wrapper[filter-key='" + key + "']").slideUp("slow");
	    });

    // focus on input box
    setTimeout(function(){
    	$("#cohorts-typeahead").focus();
    }, 3000);
});

// init multiselect w/ checkboxes
$(function() {
    $(".multiselect").multiselect();
});
// init filters
$(function() {
	$(".multiselect").each(function() {
		var filterKey = $(this).attr("filter-key");
		$(this).filterByText($(".auto-filter-check-list-input[filter-key='" + filterKey + "']"), true);
	});
});<commit_msg>still allow filter clicking if on same filter, but hide other filters<commit_after>var activeFilter = undefined;
jQuery.fn.filterByText = function(textbox, selectSingleMatch) {
    return this.each(function() {
        var select = this;

        $(textbox).bind('change keyup', function() {
            //var options = $(select).empty().data('options');
            var search = $(this).val().trim();
            var regex = new RegExp(search, "gi");
            var shown = [];
            $(select).find("label").each(function() {
                // child = <input type='checkbox .../>
                var child = $(this);
                /*
                if (child.hasClass("toggle-parent-label")) {
                	return;
                }
                */
                var childText = child.find("input").attr("value");
                if (childText && childText.match(regex) !== null) {
                    child.show();
                    var parent = child.find("input").attr("parent");
                    if (parent && shown.indexOf(parent) < 0) {
                        shown.push(parent);
                    }
                } else {
                    child.hide();
                }
            });
            // make sure parents are shown even if they text doesn't match
            $.each(shown, function() {
                $(".toggle-parent-label[key='" + this + "']").show();
            });
        });
    });
};
jQuery.fn.multiselect = function() {
    $(this).each(function() {
        var checkboxes = $(this).find(".toggle-checkbox-item");
        checkboxes.each(function() {
            var checkbox = $(this);
            // Highlight pre-selected checkboxes
            if (checkbox.attr("checked")) checkbox.parent().addClass("multiselect-on");
            // Highlight checkboxes that the user selects
            checkbox.click(function() {
                if (checkbox.attr("checked")) checkbox.parent().addClass("multiselect-on");
                else checkbox.parent().removeClass("multiselect-on");
            });
        });
    });
};

function toggleVisibleReports(checked, selector) {
    $(selector).find("input[type='checkbox']:visible").prop('checked', checked);
}

// regular functions
function split(val) {
    return val.split(/,\s*/);
}

$(document).ready(function() {

	// initialize the cohort type ahead, constructs the suggestion engine
    var bloodhoundCohorts = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 20,
        // use /data/sample-cohorts.json just to start off
        prefetch: '/data/sample-cohorts.json',
    });
    bloodhoundCohorts.initialize();

    // initialize bootstrap data toggle
    $("body").tooltip({ selector: '[data-toggle=tooltip]' });

    // typeahead cohort listener
    $('#cohorts-typeahead .typeahead').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'cohorts',
        displayKey: 'value',
        source: bloodhoundCohorts.ttAdapter(),
        templates: {
            empty: [
                '
',
                'Unable to find any cohorts that match the current query',
                '
'
            ].join('\n'),
            suggestion: Handlebars.compile('
{{name}} – {{description}}
')
        }
    });

    // on select a cohort
    $("#cohorts-typeahead").bind('typeahead:selected', function(obj, datum, name) {
        $("#cohorts").val(datum.name);

        $(".page-one").slideUp("fast", function() {
        	// set page data
        	angular.element($('#cohort-explorer-main')).scope().showCohort(datum);

        	// show div
            $("#cohort-explorer-main").slideDown("slow");
        });

    });

    // go back listener on cohort explorer
    $("#cohort-explorer-back").click(function() {
    	$("#cohort-explorer-main").slideUp("fast", function() {
            $(".page-one").slideDown('fast'), function() {
                setTimeout(function(){
                	$("#cohorts-typeahead").focus();
                }, 3000);
            }
        });
    });

    // set up auto checkbox filters
    //setup select/clear filters events
    $(".auto-filter-check-list-select").click(function() {
        toggleVisibleReports(true, ".multiselect[filter-key='" + $(this).attr("filter-key") + "']");
        return false;
    });
    $(".auto-filter-check-list-clear").click(function() {
        toggleVisibleReports(false, ".multiselect[filter-key='" + $(this).attr("filter-key") + "']");
        return false;
    });
    // trigger parent click
    $(".toggle-parent-label").click(function() {
    	  var checked = $(this).prop("checked");
          $("input[parent='" + $(this).val() + "']:visible").prop("checked", checked);
    });

    // add event listeners to show multiselect divs
    $(".auto-filter-check-list-input")
	    .focus(function() {
	    	// hide all then show active
	    	activeFilter = $(this).attr("filter-key");
	    	// hide up other active filters
	    	$(".multiselect-wrapper[filter-key!='" + activeFilter + "']:visible").slideUp("slow");
	    	// show current active filters
	    	$(".multiselect-wrapper[filter-key='" + activeFilter + "']").slideDown("slow");

	    });

    $("body").click(function(e) {
    	// if click outside the active filter, then hide that div
    	var hideFilter = true;
    	var click = $(e.target);
    	// look at self
    	if (click.attr("filter-key") && click.attr("filter-key") === activeFilter) {
    		hideFilter = false;
    	}
    	// look at parents
    	var clickParentFilter = (click.parents(".multiselect-wrapper").attr("filter-key"));
		if (clickParentFilter && clickParentFilter === activeFilter) {
			hideFilter = false;
		}

    	if (hideFilter) {
    		if (activeFilter) {
    			$(".multiselect-wrapper[filter-key='" + activeFilter + "']").slideUp("slow");
    			activeFilter = undefined;
    		}
    	}
    })

    // focus on input box
    setTimeout(function(){
    	$("#cohorts-typeahead").focus();
    }, 3000);
});

// init multiselect w/ checkboxes
$(function() {
    $(".multiselect").multiselect();
});
// init filters
$(function() {
	$(".multiselect").each(function() {
		var filterKey = $(this).attr("filter-key");
		$(this).filterByText($(".auto-filter-check-list-input[filter-key='" + filterKey + "']"), true);
	});
});<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('templateStore', [
  'ngRoute',
  'ngCart',
  'templateStore.view1',
  'templateStore.view2',
  'templateStore.templates'
]).
config(['$routeProvider', function($routeProvider) {
  // $routeProvider.otherwise({redirectTo: '/templates'});?
}]);
<commit_msg>create shopping cart<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('templateStore', [
  'ngRoute',
  'ngCart',
  'templateStore.view1',
  'templateStore.view2',
  'templateStore.templates'
]).
config(['$routeProvider', function($routeProvider) {

	$routeProvider
  .when('/templates', {
    templateUrl: 'templates/templates.html',
    controller: 'TemplatesCtrl'
  })
  .when('/template/ngCart/cart', {
    templateUrl: 'template/ngCart/cart',
    controller: 'TemplatesCtrl'
  }).otherwise({redirectTo: '/templates'});
}]);
<|endoftext|>


<commit_before>var openttd = require("./openttd/openttd");

function OpenTTDPlugin(bot) {
	var self = this;
	self.name = "openttd";
	self.help = "OpenTTD plugin";
	self.depend = ["cmd", "bits", "util"];

	self.defServer = null;
	self.defPort = 3979;

	self.channels = [];
	self.pRet = null;
	self.interval = null;

	self.load = function(data) {
		if (data) {
			self.defServer = data.defServer;
			self.defPort = data.defPort;
			self.channels = data.channels || [];
		}
	};

	self.enable = function() {
		self.interval = setInterval(self.refresh, 60 * 1000);
		self.refresh();
	};

	self.disable = function() {
		clearInterval(self.interval);
		self.interval = null;
	};

	self.save = function() {
		return {defServer: self.defServer, defPort: self.defPort, channels: self.channels};
	};

	self.refresh = function() {
		openttd.query(self.defServer, self.defPort, function(ret) {
			if (self.pRet && self.pRet[1].numClient != ret[1].numClient) {
				var prefix = ret[1].name + " \x02(" + self.defServer + ":" + self.defPort + ")\x02";

				var bits = [];
				bits.push(["map", ret[1].map.name + " \x02(" + ret[1].map.width + "×" + ret[1].map.height + ")\x02"]);
				bits.push(["date", ret[1].curDate.toISOString().replace(/^([\d-]+)T.*/, "$1")]);
				bits.push(["companies", ret[1].numCompany + "/" + ret[1].maxCompany]);
				bits.push(["clients", ret[1].numClient + "/" + ret[1].maxClient]);

				var str = bot.plugins.bits.format(prefix, bits);

				self.channels.forEach(function(channel) {
					bot.say(channel, str);
				});
			}

			self.pRet = ret;
		});
	};

	self.events = {
		"cmd#openttd": function(nick, to, args) {
			var server = args[1] || self.defServer;
			var port = args[2] || self.defPort;
			openttd.query(server, port, function(ret) {
				var prefix = ret[1].name + " \x02(" + server + ":" + port + ")\x02";

				var bits = [];
				bits.push(["map", ret[1].map.name + " \x02(" + ret[1].map.width + "×" + ret[1].map.height + ")\x02"]);
				bits.push(["date", ret[1].curDate.toISOString().replace(/^([\d-]+)T.*/, "$1")]);
				bits.push(["companies", ret[1].numCompany + "/" + ret[1].maxCompany]);
				bits.push(["clients", ret[1].numClient + "/" + ret[1].maxClient]);

				bot.say(to, bot.plugins.bits.format(prefix, bits));
			});
		},

		"cmd#openttdrank": function(nick, to, args) {
			var server = args[1] || self.defServer;
			var port = args[2] || self.defPort;
			openttd.query(server, port, function(ret) {
				var prefix = ret[1].name + " ranking";

				var bits = [];
				var companies = ret[3].companies;
				companies.sort(function(lhs, rhs) {
					return rhs.performance - lhs.performance;
				});

				companies.forEach(function(company) {
					bits.push([company.name + " \x02(" + company.performance + ")\x02", "£" + bot.plugins.util.thSeps(company.value)]);
				});

				bot.say(to, bot.plugins.bits.format(prefix, bits));
			});
		},

		"cmd#openttdcomp": function(nick, to, args) {
			var comp = args[1];
			var server = args[2] || self.defServer;
			var port = args[3] || self.defPort;
			openttd.query(server, port, function(ret) {
				var companies = ret[3].companies;

				var i;
				for (i = 0; i < companies.length && companies[i].id != comp && companies[i].name.toLowerCase().indexOf(comp.toLowerCase()) < 0; i++); // maybe unneccessary find
				if (i == companies.length) // not found
					return;

				var company = companies[i];

				var prefix = company.name + " on " + ret[1].name;
				var bits = [];

				bits.push(["start year", company.startYear]);
				bits.push(["value", "£" + bot.plugins.util.thSeps(company.value)]);
				bits.push(["money", "£" + bot.plugins.util.thSeps(company.money)]);
				bits.push(["income", "£" + bot.plugins.util.thSeps(company.income)]);
				bits.push(["performance", company.performance]);

				/*bits.push(["vehicles", Object.keys(company.vehicles).map(function(type) {
					return type + ": " + company.vehicles[type];
				}).join(", ")]);
				bits.push(["stations", Object.keys(company.stations).map(function(type) {
					return type + ": " + company.stations[type];
				}).join(", ")]);*/

				bits.push(["type", "vehicles (stations)"]);
				for (var type in company.vehicles) {
					bits.push([type, company.vehicles[type] + " (" + company.stations[type] + ")"]);
				}

				bot.say(to, bot.plugins.bits.format(prefix, bits));
			});
		}
	};
}

module.exports = OpenTTDPlugin;
<commit_msg>openttd: extra ticker conditions<commit_after>var openttd = require("./openttd/openttd");

function OpenTTDPlugin(bot) {
	var self = this;
	self.name = "openttd";
	self.help = "OpenTTD plugin";
	self.depend = ["cmd", "bits", "util"];

	self.defServer = null;
	self.defPort = 3979;

	self.channels = [];
	self.pRet = null;
	self.interval = null;

	self.load = function(data) {
		if (data) {
			self.defServer = data.defServer;
			self.defPort = data.defPort;
			self.channels = data.channels || [];
		}
	};

	self.enable = function() {
		self.interval = setInterval(self.refresh, 60 * 1000);
		self.refresh();
	};

	self.disable = function() {
		clearInterval(self.interval);
		self.interval = null;
	};

	self.save = function() {
		return {defServer: self.defServer, defPort: self.defPort, channels: self.channels};
	};

	self.refresh = function() {
		openttd.query(self.defServer, self.defPort, function(ret) {
			if (self.pRet &&
				(self.pRet[1].numClient != ret[1].numClient ||
				 self.pRet[1].numCompany != ret[1].numCompany ||
				 self.pRet[1].map.name != ret[1].map.name)) {
				var prefix = ret[1].name + " \x02(" + self.defServer + ":" + self.defPort + ")\x02";

				var bits = [];
				bits.push(["map", ret[1].map.name + " \x02(" + ret[1].map.width + "×" + ret[1].map.height + ")\x02"]);
				bits.push(["date", ret[1].curDate.toISOString().replace(/^([\d-]+)T.*/, "$1")]);
				bits.push(["companies", ret[1].numCompany + "/" + ret[1].maxCompany]);
				bits.push(["clients", ret[1].numClient + "/" + ret[1].maxClient]);

				var str = bot.plugins.bits.format(prefix, bits);

				self.channels.forEach(function(channel) {
					bot.say(channel, str);
				});
			}

			self.pRet = ret;
		});
	};

	self.events = {
		"cmd#openttd": function(nick, to, args) {
			var server = args[1] || self.defServer;
			var port = args[2] || self.defPort;
			openttd.query(server, port, function(ret) {
				var prefix = ret[1].name + " \x02(" + server + ":" + port + ")\x02";

				var bits = [];
				bits.push(["map", ret[1].map.name + " \x02(" + ret[1].map.width + "×" + ret[1].map.height + ")\x02"]);
				bits.push(["date", ret[1].curDate.toISOString().replace(/^([\d-]+)T.*/, "$1")]);
				bits.push(["companies", ret[1].numCompany + "/" + ret[1].maxCompany]);
				bits.push(["clients", ret[1].numClient + "/" + ret[1].maxClient]);

				bot.say(to, bot.plugins.bits.format(prefix, bits));
			});
		},

		"cmd#openttdrank": function(nick, to, args) {
			var server = args[1] || self.defServer;
			var port = args[2] || self.defPort;
			openttd.query(server, port, function(ret) {
				var prefix = ret[1].name + " ranking";

				var bits = [];
				var companies = ret[3].companies;
				companies.sort(function(lhs, rhs) {
					return rhs.performance - lhs.performance;
				});

				companies.forEach(function(company) {
					bits.push([company.name + " \x02(" + company.performance + ")\x02", "£" + bot.plugins.util.thSeps(company.value)]);
				});

				bot.say(to, bot.plugins.bits.format(prefix, bits));
			});
		},

		"cmd#openttdcomp": function(nick, to, args) {
			var comp = args[1];
			var server = args[2] || self.defServer;
			var port = args[3] || self.defPort;
			openttd.query(server, port, function(ret) {
				var companies = ret[3].companies;

				var i;
				for (i = 0; i < companies.length && companies[i].id != comp && companies[i].name.toLowerCase().indexOf(comp.toLowerCase()) < 0; i++); // maybe unneccessary find
				if (i == companies.length) // not found
					return;

				var company = companies[i];

				var prefix = company.name + " on " + ret[1].name;
				var bits = [];

				bits.push(["start year", company.startYear]);
				bits.push(["value", "£" + bot.plugins.util.thSeps(company.value)]);
				bits.push(["money", "£" + bot.plugins.util.thSeps(company.money)]);
				bits.push(["income", "£" + bot.plugins.util.thSeps(company.income)]);
				bits.push(["performance", company.performance]);

				/*bits.push(["vehicles", Object.keys(company.vehicles).map(function(type) {
					return type + ": " + company.vehicles[type];
				}).join(", ")]);
				bits.push(["stations", Object.keys(company.stations).map(function(type) {
					return type + ": " + company.stations[type];
				}).join(", ")]);*/

				bits.push(["type", "vehicles (stations)"]);
				for (var type in company.vehicles) {
					bits.push([type, company.vehicles[type] + " (" + company.stations[type] + ")"]);
				}

				bot.say(to, bot.plugins.bits.format(prefix, bits));
			});
		}
	};
}

module.exports = OpenTTDPlugin;
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');

var app = express();
require('dotenv').load();
require('./app/config/passport')(passport);

mongoose.connect(process.env.MONGO_URI);

app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
app.use('/common', express.static(process.cwd() + '/app/common'));

app.use(session({
	secret: 'secretClementine',
	resave: false,
	saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});<commit_msg>edit server<commit_after>'use strict';

var express = require('express');
var routes = require('./app/routes/index.js');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');

var app = express();
require('dotenv').load();
//require('./app/config/passport')(passport);

//mongoose.connect(process.env.MONGO_URI);

//app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
//app.use('/public', express.static(process.cwd() + '/public'));
//app.use('/common', express.static(process.cwd() + '/app/common'));

//app.use(session({
//	secret: 'secretClementine',
//	resave: false,
//	saveUninitialized: true
//}));

//app.use(passport.initialize());
//app.use(passport.session());

//routes(app, passport);

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});<|endoftext|>


<commit_before>var editor = ace.edit('game-rb-editor');
editor.setTheme('ace/theme/monokai');
editor.getSession().setFoldStyle('manual');
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setUseWrapMode(true);
editor.setDisplayIndentGuides(false);
editor.setHighlightActiveLine(true);
editor.setShowPrintMargin(false);
editor.setShowInvisibles(true);

var addToTerminal = function(value, type) {
    if (type === 'output' && value.indexOf('()') > -1) return;
    var classes = 'outputs outputs-' + type;
    value = value.replace(/&/g, '&')
                 .replace(/>/g, '>')
                 .replace(/</g, '<')
                 .replace(/"/g, '"')
                 .replace(/'/g, ''')
                 .replace(/\n/g, '
');
    terminalOutputs.innerHTML += '
' + value + '
';
    terminalInput.scrollIntoView();
};

var handleterminalInput = function(event) {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.preventDefault();
        socket.emit('terminalInput', { input: terminalInput.value });
        addToTerminal(terminalInput.value, 'input');
        terminalInput.value = '';
    }
};

var handleFileLoad = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileLoad', { input: currentFileContent });
    addToTerminal('Loading game...', 'status');
};

var handleFileSave = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileSave', { fileContent: currentFileContent });
    addToTerminal('Saving game code...', 'status');
};

var socket = io('http://localhost:8888/ruby'),
    terminal = document.getElementById('terminal'),
    terminalOutputs = document.getElementById('terminal-outputs'),
    terminalInput = document.getElementById('terminal-input'),
    sourceActionSave = document.getElementById('source-action-save'),
    sourceActionLoad = document.getElementById('source-action-load');

terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);

socket.on('connect', function() {
    addToTerminal('Server connected', 'status');
    terminalInput.addEventListener('keypress', handleterminalInput, false);
    sourceActionSave.addEventListener('click', handleFileSave, false );
    sourceActionLoad.addEventListener('click', handleFileLoad, false);
});

socket.on('disconnect', function() {
    addToTerminal('Server disconnected', 'error');
    terminalInput.removeEventListener('keypress', handleterminalInput, false);
    sourceActionSave.removeEventListener('click', handleFileSave, false );
    sourceActionLoad.removeEventListener('click', handleFileLoad, false);
});

socket.on('ready', function(data) {
    addToTerminal(data.output, 'status');
    editor.setValue(data.fileContent);
    editor.gotoLine(0);
});

socket.on('terminalOutput', function(data) {
    if (data.output.indexOf('Error') > -1) addToTerminal(data.output, 'error');
    else addToTerminal(data.output, 'output');
});

socket.on('terminalError', function(data) {
    addToTerminal(data.output, 'error');
});

socket.on('fileSaved', function(data) {
    addToTerminal(data.output, 'status');
});

socket.on('fileLoaded', function(data) {
    addToTerminal(data.output, 'status');
});
<commit_msg>Remove error checker, it is flawed<commit_after>var editor = ace.edit('game-rb-editor');
editor.setTheme('ace/theme/monokai');
editor.getSession().setFoldStyle('manual');
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.getSession().setUseWrapMode(true);
editor.setDisplayIndentGuides(false);
editor.setHighlightActiveLine(true);
editor.setShowPrintMargin(false);
editor.setShowInvisibles(true);

var addToTerminal = function(value, type) {
    if (type === 'output' && value.indexOf('()') > -1) return;
    var classes = 'outputs outputs-' + type;
    value = value.replace(/&/g, '&')
                 .replace(/>/g, '>')
                 .replace(/</g, '<')
                 .replace(/"/g, '"')
                 .replace(/'/g, ''')
                 .replace(/\n/g, '
');
    terminalOutputs.innerHTML += '
' + value + '
';
    terminalInput.scrollIntoView();
};

var handleterminalInput = function(event) {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.preventDefault();
        socket.emit('terminalInput', { input: terminalInput.value });
        addToTerminal(terminalInput.value, 'input');
        terminalInput.value = '';
    }
};

var handleFileLoad = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileLoad', { input: currentFileContent });
    addToTerminal('Loading game...', 'status');
};

var handleFileSave = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileSave', { fileContent: currentFileContent });
    addToTerminal('Saving game code...', 'status');
};

var socket = io('http://localhost:8888/ruby'),
    terminal = document.getElementById('terminal'),
    terminalOutputs = document.getElementById('terminal-outputs'),
    terminalInput = document.getElementById('terminal-input'),
    sourceActionSave = document.getElementById('source-action-save'),
    sourceActionLoad = document.getElementById('source-action-load');

terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);

socket.on('connect', function() {
    addToTerminal('Server connected', 'status');
    terminalInput.addEventListener('keypress', handleterminalInput, false);
    sourceActionSave.addEventListener('click', handleFileSave, false );
    sourceActionLoad.addEventListener('click', handleFileLoad, false);
});

socket.on('disconnect', function() {
    addToTerminal('Server disconnected', 'error');
    terminalInput.removeEventListener('keypress', handleterminalInput, false);
    sourceActionSave.removeEventListener('click', handleFileSave, false );
    sourceActionLoad.removeEventListener('click', handleFileLoad, false);
});

socket.on('ready', function(data) {
    addToTerminal(data.output, 'status');
    editor.setValue(data.fileContent);
    editor.gotoLine(0);
});

socket.on('terminalOutput', function(data) {
    //if (data.output.indexOf('Error') > -1 || data.output.indexOf('undefined') > -1)
    //    addToTerminal(data.output, 'error');
    //else addToTerminal(data.output, 'output');
    addToTerminal(data.output, 'output');
});

socket.on('terminalError', function(data) {
    addToTerminal(data.output, 'error');
});

socket.on('fileSaved', function(data) {
    addToTerminal(data.output, 'status');
});

socket.on('fileLoaded', function(data) {
    addToTerminal(data.output, 'status');
});
<|endoftext|>


<commit_before>var express = require('express');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var logger = require('./common/logging.js').logger;
var config = require('config');
var passport = require('passport');
var GitHubStrategy = require('passport-github').Strategy;
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
var request = require('request');

// set up db connection
var db = require('./app/models/db');

// Passport session setup
passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

// use GitHubStrategy with Passport
passport.use(new GitHubStrategy({
        clientID: (process.env.GH_CLIENT_ID || config.github.clientID),
        clientSecret: (process.env.GH_CLIENT_SECRET || config.github.clientSecret),
        callbackURL: config.github.callbackURL
    },
    function(accessToken, refreshToken, extProfile, done) {
        passportStrategySetup(extProfile, done);
    }
));

// use LinkedInStrategy with Passport
passport.use(new LinkedInStrategy({
    clientID: (process.env.LI_CLIENT_ID || config.linkedin.clientID),
    clientSecret: (process.env.LI_CLIENT_SECRET || config.linkedin.clientSecret),
    callbackURL: config.linkedin.callbackURL,
    scope: ['r_fullprofile'],
    state: true
}, function(accessToken, refreshToken, extProfile, done) {
        passportStrategySetup(extProfile, done);
    }
));

function passportStrategySetup(extProfile, done) {
    logger.info("logged in as " + extProfile.displayName + " from " + extProfile.provider);

    db.Account.findOne({'identities.identifier': extProfile.id})
        .populate('identities.origin profiles')
        .exec(function (err, account){
            if (err) {
                logger.error(err);
            }

            if (account) {
                var originExists = false;
                for (var i = 0; i < account.identities.length; i++) {
                    if (account.identities[i].origin.name == extProfile.provider) {
                        originExists = true;
                        break;
                    }
                }

                if (!originExists) {
                    db.addIdentity(account, extProfile, function (err, updatedAcct) {
                        return done(null, updatedAcct);
                    });
                }
                else {
                    return done(null, account);
                }

            } else {

                db.createAccount(extProfile, function (err, updatedAcct) {
                    return done(null, updatedAcct);
                });

            }

        });
}

var app = express();

app.set('port', (config.http.port || 5000));

app.use(session({
    secret: config.http.session.secret,
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ url: config.mongodb.sessionStoreUrl })
}));

// initialize passport and use passport.session() to support persistent login sessions
app.use(passport.initialize());
app.use(passport.session());

app.use(bodyParser.json());

// ===== Static file for all files in public =====
app.use(express.static(__dirname + '/public', {"maxage": config.http.static.maxage}));

// ===== Low level conf for client side ======
app.get("/config",
    function (req, res) {
        res.send(config.ui);
    }
);

// ===== authentication page routing ======

// GET /auth/github
// use passport.authenticate() as route middleware to authenticate the request
app.get('/auth/github',
    passport.authenticate('github'),
    function(req, res) {
    //the request will be redirected to github for auth, so this function will not be called
});

// GET /auth/github/callback
// use passport.authenticate() as route middleware to authenticate the request
// if auth fails, the user will be redirected back to the login page
// otherwise, the primary route function will be called which will redirect the user to the home page
app.get('/auth/github/callback',
    passport.authenticate('github', {
        scope: ['user', 'repo'],
        failureRedirect: '/#/login'
    }),
    function(req, res) {
        loginCallbackHandler(req, res);
    });

// GET /auth/linkedin
// use passport.authenticate() as route middleware to authenticate the request
app.get('/auth/linkedin',
    passport.authenticate('linkedin'),
    function(req, res) {
        //the request will be redirected to linkedin for auth, so this function will not be called
    });

// GET /auth/linkedin/callback
// use passport.authenticate() as route middleware to authenticate the request
// if auth fails, the user will be redirected back to the login page
// otherwise, the primary route function will be called which will redirect the user to the home page
app.get('/auth/linkedin/callback',
    passport.authenticate('linkedin', {
        failureRedirect: '/#/login'
    }),
    function(req, res) {
        loginCallbackHandler(req, res);
    });

function loginCallbackHandler(req, res) {
    db.Profile.findById(req.user.profiles[0])
        .exec(function (err, profile){
            if (err) {
                logger.error(err);
                res.send(500);
            }

            if (profile) {
                res.cookie('user', JSON.stringify({
                    'displayName': profile.name.value
                }));
                res.redirect('/#/account?id=' + req.user.identities[0].identifier);
            }
        });
}

// ===== logout routing ======

app.post('/logout', function(req, res) {
    req.logOut();
    res.send(200);
});

// ===== account page routing ======

app.get('/account/:id', ensureAuthenticated, function(req, res) {
    db.getAccount({'identities.identifier': req.params.id}, res);
})

app.post('/account/:id', ensureAuthenticated, function(req, res) {
    var acctData = req.body;

    db.Account.findById(acctData._id)
        .populate('identities.origin profiles')
        .exec(function (err, account) {
            if (err) {
                logger.error(err);
            }

            if (account) {
                account.profiles[0].visible = acctData.profiles[0].visible;
                account.profiles[0].contactPreferences.notifyMeOfAllUpdates = acctData.profiles[0].contactPreferences.notifyMeOfAllUpdates;
                account.profiles[0].save(function (err) {
                    if (err) {
                        logger.error(err);
                    }

                    res.json(account);

                });
            }
        });

});

app.get('/resources', function(req, res) {
    request('http://' + config.bcdc.host + '/api/3/action/package_search?q=tags:' + config.bcdc.tagToSearch, function (error, response, body) {
      var resourcesJson = { 'resources': [] }
      if (!error && response.statusCode == 200) {
        var json = JSON.parse(body);
        resourcesJson['resources'] = json.result.results;
      }

      else if(error) {
        logger.info('Error while fetching BCDC content (error code %s): %s', response.statusCode, body);
      }

      res.send(resourcesJson);
    });
});

app.listen(app.get('port'), function() {
    logger.info("Node app is running on port " + app.get('port'));
});

// simple route middleware to ensure user is authenticated
// use this route middleware on any resource that needs to be protected
// if the request is authenticated the request will proceed
function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.send(401);
    }
}<commit_msg>update res.send to res.sendStatus in cases where we are returning a status (fix deprecation warning)<commit_after>var express = require('express');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var logger = require('./common/logging.js').logger;
var config = require('config');
var passport = require('passport');
var GitHubStrategy = require('passport-github').Strategy;
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;
var request = require('request');

// set up db connection
var db = require('./app/models/db');

// Passport session setup
passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

// use GitHubStrategy with Passport
passport.use(new GitHubStrategy({
        clientID: (process.env.GH_CLIENT_ID || config.github.clientID),
        clientSecret: (process.env.GH_CLIENT_SECRET || config.github.clientSecret),
        callbackURL: config.github.callbackURL
    },
    function(accessToken, refreshToken, extProfile, done) {
        passportStrategySetup(extProfile, done);
    }
));

// use LinkedInStrategy with Passport
passport.use(new LinkedInStrategy({
    clientID: (process.env.LI_CLIENT_ID || config.linkedin.clientID),
    clientSecret: (process.env.LI_CLIENT_SECRET || config.linkedin.clientSecret),
    callbackURL: config.linkedin.callbackURL,
    scope: ['r_fullprofile'],
    state: true
}, function(accessToken, refreshToken, extProfile, done) {
        passportStrategySetup(extProfile, done);
    }
));

function passportStrategySetup(extProfile, done) {
    logger.info("logged in as " + extProfile.displayName + " from " + extProfile.provider);

    db.Account.findOne({'identities.identifier': extProfile.id})
        .populate('identities.origin profiles')
        .exec(function (err, account){
            if (err) {
                logger.error(err);
            }

            if (account) {
                var originExists = false;
                for (var i = 0; i < account.identities.length; i++) {
                    if (account.identities[i].origin.name == extProfile.provider) {
                        originExists = true;
                        break;
                    }
                }

                if (!originExists) {
                    db.addIdentity(account, extProfile, function (err, updatedAcct) {
                        return done(null, updatedAcct);
                    });
                }
                else {
                    return done(null, account);
                }

            } else {

                db.createAccount(extProfile, function (err, updatedAcct) {
                    return done(null, updatedAcct);
                });

            }

        });
}

var app = express();

app.set('port', (config.http.port || 5000));

app.use(session({
    secret: config.http.session.secret,
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ url: config.mongodb.sessionStoreUrl })
}));

// initialize passport and use passport.session() to support persistent login sessions
app.use(passport.initialize());
app.use(passport.session());

app.use(bodyParser.json());

// ===== Static file for all files in public =====
app.use(express.static(__dirname + '/public', {"maxage": config.http.static.maxage}));

// ===== Low level conf for client side ======
app.get("/config",
    function (req, res) {
        res.send(config.ui);
    }
);

// ===== authentication page routing ======

// GET /auth/github
// use passport.authenticate() as route middleware to authenticate the request
app.get('/auth/github',
    passport.authenticate('github'),
    function(req, res) {
    //the request will be redirected to github for auth, so this function will not be called
});

// GET /auth/github/callback
// use passport.authenticate() as route middleware to authenticate the request
// if auth fails, the user will be redirected back to the login page
// otherwise, the primary route function will be called which will redirect the user to the home page
app.get('/auth/github/callback',
    passport.authenticate('github', {
        scope: ['user', 'repo'],
        failureRedirect: '/#/login'
    }),
    function(req, res) {
        loginCallbackHandler(req, res);
    });

// GET /auth/linkedin
// use passport.authenticate() as route middleware to authenticate the request
app.get('/auth/linkedin',
    passport.authenticate('linkedin'),
    function(req, res) {
        //the request will be redirected to linkedin for auth, so this function will not be called
    });

// GET /auth/linkedin/callback
// use passport.authenticate() as route middleware to authenticate the request
// if auth fails, the user will be redirected back to the login page
// otherwise, the primary route function will be called which will redirect the user to the home page
app.get('/auth/linkedin/callback',
    passport.authenticate('linkedin', {
        failureRedirect: '/#/login'
    }),
    function(req, res) {
        loginCallbackHandler(req, res);
    });

function loginCallbackHandler(req, res) {
    db.Profile.findById(req.user.profiles[0])
        .exec(function (err, profile){
            if (err) {
                logger.error(err);
                res.sendStatus(500);
            }

            if (profile) {
                res.cookie('user', JSON.stringify({
                    'displayName': profile.name.value
                }));
                res.redirect('/#/account?id=' + req.user.identities[0].identifier);
            }
        });
}

// ===== logout routing ======

app.post('/logout', function(req, res) {
    req.logOut();
    res.sendStatus(200);
});

// ===== account page routing ======

app.get('/account/:id', ensureAuthenticated, function(req, res) {
    db.getAccount({'identities.identifier': req.params.id}, res);
})

app.post('/account/:id', ensureAuthenticated, function(req, res) {
    var acctData = req.body;

    db.Account.findById(acctData._id)
        .populate('identities.origin profiles')
        .exec(function (err, account) {
            if (err) {
                logger.error(err);
            }

            if (account) {
                account.profiles[0].visible = acctData.profiles[0].visible;
                account.profiles[0].contactPreferences.notifyMeOfAllUpdates = acctData.profiles[0].contactPreferences.notifyMeOfAllUpdates;
                account.profiles[0].save(function (err) {
                    if (err) {
                        logger.error(err);
                    }

                    res.json(account);

                });
            }
        });

});

app.get('/resources', function(req, res) {
    request('http://' + config.bcdc.host + '/api/3/action/package_search?q=tags:' + config.bcdc.tagToSearch, function (error, response, body) {
      var resourcesJson = { 'resources': [] }
      if (!error && response.statusCode == 200) {
        var json = JSON.parse(body);
        resourcesJson['resources'] = json.result.results;
      }

      else if(error) {
        logger.info('Error while fetching BCDC content (error code %s): %s', response.statusCode, body);
      }

      res.send(resourcesJson);
    });
});

app.listen(app.get('port'), function() {
    logger.info("Node app is running on port " + app.get('port'));
});

// simple route middleware to ensure user is authenticated
// use this route middleware on any resource that needs to be protected
// if the request is authenticated the request will proceed
function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } else {
        res.sendStatus(401);
    }
}<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('101100111001101...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {

            return bot.say('Wenn Andreas gerade online ist, sieht er dieses Gespräch und kann beitreten.')
                .then(() => 'vorname');
        }
    },

    vorname: {
        prompt: (bot) => bot.say('Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {

            var vorname = message.text;
            Smooch.updateUser({ givenName: vorname });

            return bot.setProp('vorname', vorname)
                .then(() => bot.say(`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {
        prompt: (bot) => bot.say('Und mit Nachnamen?'),
        receive: (bot, message) => {

            var nachname = message.text;
            Smooch.updateUser({ surname: nachname });

            return bot.setProp('nachname', nachname)
                .then(() => bot.say(`${nachname}, danke.`))
                .then(() => bot.say('Schreiben Sie hier eine Nachricht an Andreas. Oder unterhalten Sie sich mit mir, indem Sie --bot schreiben!'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            var wollen = message.text;
            var befehl = wollen;
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

         // System
            if (befehl == "--BOT")          { bot.say('Ich bin sozusagen Andreas\' Assistent. Er hat mir vieles beigebracht, was Sie durch Schreiben der mit -- beginnenden Wörter abrufen können.'); }
            if (befehl == "--BOT")          { bot.say('Wollen Sie etwas über seine --Person erfahren, hören, was es --Neues bei ihm gibt oder auf anderem Wege --Kontakt  aufnehmen?'); }
            if (befehl == "--ABBRECHEN")    { bot.say('Text: Abbruch.'); }

         // Über mich
            if (befehl == "--PERSON")       { bot.say('Text: Person; Links: --Lebenslauf, --Foto.'); }
            if (befehl == "--LEBENSLAUF")   { bot.say('Text: Lebenslauf. %[Lebenslauf öffnen](http://sefzig.net/link/Lebenslauf/)'); }
            if (befehl == "--FOTO")         { bot.say('Text mit http://sefzig.net/text/seiten/SefzignetStartseite/dateien/SefzignetStartseiteFotoLogos.png Bild.'); }
            if (befehl == "--NEUES")        { bot.say('Text: Neues.'); }

         // Kontakt
            if (befehl == "--KONTAKT")      { bot.say('Text: Kontakt mit Webseite; Links: --Twitter, --Slackteam, --Xing. %[Kontakt-Seite öffnen](http://sefzig.net/link/Kontakt/)'); }
            if (befehl == "--SLACKTEAM")    { bot.say('Text: Offenes Slack-Team. %[Offenes Slack-Team](http://sefzig.net/link/Slack/)'); }
            if (befehl == "--XING")         { bot.say('Andreas ist Mitglied bei Xing: %[Xing-Profil ansehen](http://sefzig.net/link/Xing/)'); }
            if (befehl == "--TWITTER")      { bot.say('Andreas ist auf Twitter: %[Twitter-Profil öffnen](http://sefzig.net/link/Twitter/)'); }

         // Vorlage
            if (befehl == "--VORLAGE")      { bot.say('Text: Vorlage.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {

            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>Tests<commit_after>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('101100111001101...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {

            return bot.say('Wenn Andreas gerade online ist, sieht er dieses Gespräch und kann beitreten.')
                .then(() => 'vorname');
        }
    },

    vorname: {
        prompt: (bot) => bot.say('Wie heissen Sie mit Vornamen?'),
        receive: (bot, message) => {

            var vorname = message.text;

            Smooch.updateUser({ givenName: vorname });

            return bot.setProp('vorname', vorname)
                .then(() => bot.say(`${vorname}, prima.`))
                .then(() => 'nachname');
        }
    },

    nachname: {
        prompt: (bot) => bot.say('Und mit Nachnamen?'),
        receive: (bot, message) => {

            var nachname = message.text;

            Smooch.updateUser({ surname: nachname });

            return bot.setProp('nachname', nachname)
                .then(() => bot.say(`${nachname}, danke.`))
                .then(() => bot.say('Schreiben Sie hier eine Nachricht an Andreas. Oder unterhalten Sie sich mit mir, indem Sie --bot schreiben!'))
                .then(() => 'register');
        }
    },

    register: {
        receive: (bot, message) => {

            var wollen = message.text;
            var befehl = wollen;
            befehl = befehl.trim();
            befehl = befehl.toUpperCase();

         // System
            if (befehl == "--BOT")          { bot.say('Ich bin sozusagen Andreas\' Assistent. Er hat mir vieles beigebracht, was Sie durch Schreiben der mit -- beginnenden Wörter abrufen können.'); }
            if (befehl == "--BOT")          { bot.say('Wollen Sie etwas über seine --Person erfahren, hören, was es --Neues bei ihm gibt oder auf anderem Wege --Kontakt  aufnehmen?'); }
            if (befehl == "--ABBRECHEN")    { bot.say('Text: Abbruch.'); }

         // Über mich
            if (befehl == "--PERSON")       { bot.say('Text: Person; Links: --Lebenslauf, --Foto.'); }
            if (befehl == "--LEBENSLAUF")   { bot.say('Text: Lebenslauf. %[Lebenslauf öffnen](http://sefzig.net/link/Lebenslauf/)'); }
            if (befehl == "--FOTO")         { bot.say('Text mit http://sefzig.net/text/seiten/SefzignetStartseite/dateien/SefzignetStartseiteFotoLogos.png Bild.'); }
            if (befehl == "--NEUES")        { bot.say('Text: Neues.'); }

         // Kontakt
            if (befehl == "--KONTAKT")      { bot.say('Text: Kontakt mit Webseite; Links: --Twitter, --Slackteam, --Xing. %[Kontakt-Seite öffnen](http://sefzig.net/link/Kontakt/)'); }
            if (befehl == "--SLACKTEAM")    { bot.say('Text: Offenes Slack-Team. %[Offenes Slack-Team](http://sefzig.net/link/Slack/)'); }
            if (befehl == "--XING")         { bot.say('Andreas ist Mitglied bei Xing: %[Xing-Profil ansehen](http://sefzig.net/link/Xing/)'); }
            if (befehl == "--TWITTER")      { bot.say('Andreas ist auf Twitter: %[Twitter-Profil öffnen](http://sefzig.net/link/Twitter/)'); }

         // Vorlage
            if (befehl == "--VORLAGE")      { bot.say('Text: Vorlage.'); }

            return bot.setProp('wollen', wollen)
                .then(() => 'register');
        }
    },

    finish: {
        receive: (bot, message) => {

            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */
import 'babel-polyfill';

/* eslint-disable import/no-unresolved */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved */

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: selectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

const render = (translatedMessages) => {
  ReactDOM.render(
    <Provider store={store}>
      <LanguageProvider messages={translatedMessages}>
        <Router
          history={history}
          routes={rootRoute}
          render={
            // Scroll to top when going to a new page, imitating default browser
            // behaviour
            applyRouterMiddleware(useScroll())
          }
        />
      </LanguageProvider>
    </Provider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(System.import('intl'));
  }))
    .then(() => Promise.all([
      System.import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
<commit_msg>Added Material UI Theme<commit_after>/**
 * app.js
 *
 * This is the entry file for the application, only setup and boilerplate
 * code.
 */
import 'babel-polyfill';

/* eslint-disable import/no-unresolved */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved */

// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import configureStore from './store';

// Import i18n messages
import { translationMessages } from './i18n';

// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';

// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: selectLocationState(),
});

// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
  component: App,
  childRoutes: createRoutes(store),
};

const render = (translatedMessages) => {
  ReactDOM.render(
    <MuiThemeProvider>
      <Provider store={store}>
        <LanguageProvider messages={translatedMessages}>
          <Router
            history={history}
            routes={rootRoute}
            render={
              // Scroll to top when going to a new page, imitating default browser
              // behaviour
              applyRouterMiddleware(useScroll())
            }
          />
        </LanguageProvider>
      </Provider>
    </MuiThemeProvider>,
    document.getElementById('app')
  );
};

// Hot reloadable translation json files
if (module.hot) {
  // modules.hot.accept does not accept dynamic dependencies,
  // have to be constants at compile-time
  module.hot.accept('./i18n', () => {
    render(translationMessages);
  });
}

// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
  (new Promise((resolve) => {
    resolve(System.import('intl'));
  }))
    .then(() => Promise.all([
      System.import('intl/locale-data/jsonp/de.js'),
    ]))
    .then(() => render(translationMessages))
    .catch((err) => {
      throw err;
    });
} else {
  render(translationMessages);
}

// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
<|endoftext|>


<commit_before>'use strict';

var Hapi = require('hapi');
var routes = require('./routes');
var config = require('./config');
var server = new Hapi.Server();

server.connection({
  port:config.SERVER_PORT,
  routes:{cors:true}
});

server.route(routes);

function startServer() {
  server.start(function() {
    console.log('Server running at:', server.info.uri);
  });
}

function stopServer() {
  server.stop(function() {
    console.log('Server stopped');
  });
}

module.exports.start = startServer;

module.exports.stop =  stopServer;
<commit_msg>Change CORS settings to credentials:true<commit_after>'use strict';

var Hapi = require('hapi');
var routes = require('./routes');
var config = require('./config');
var server = new Hapi.Server();

server.connection({
  port:config.SERVER_PORT,
  routes:{cors:{credentials:true}}
});

server.route(routes);

function startServer() {
  server.start(function() {
    console.log('Server running at:', server.info.uri);
  });
}

function stopServer() {
  server.stop(function() {
    console.log('Server stopped');
  });
}

module.exports.start = startServer;

module.exports.stop =  stopServer;
<|endoftext|>