<commit_before>require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
//var mongo = require('mongoskin');
//var db = mongo.db(config.connectionString, { native_parser: true });

var mongoose = require('mongoose');
var chatMessage;
var hotelList;
var restaurant;
var event;
var ContactForm;
var FeedbackForm;
var db = mongoose.connection;

db.on('error', console.error);
db.once('open', function() {

    var chatSchema = new mongoose.Schema({
        username: { type: String }
        , message: String
    });
   var hotelSchema = new mongoose.Schema({
       Name: String,
       Location: {type: String},
        Address: { type: String },
        Description : { type: String },
        Rating : { type: String },
        Price : { type: String }
   });
     var restaurantSchema = new mongoose.Schema({
        Name: String,
        Location: String,
        Address:  String,
        Description: String,
        Timings: String,
        Contact: String
    });
    var eventSchema = new mongoose.Schema({
        Name: String,
        Location: String,
        Venue:  String,
        Description: String,
        Timings: String
    });
    var ContactSchema = new mongoose.Schema({
        Email : String,
        Subject : String,
        Message: String

    });
    var FeedbackSchema = new mongoose.Schema({
        name : String,
        email : String,
        phone: String,
        feedback: String

    });

// Compile a 'chat' model using the chatSchema as the structure.
// Mongoose also creates a MongoDB collection called 'chat' for these documents.
    chatMessage = mongoose.model('chat', chatSchema);
    hotelList = mongoose.model('hotels', hotelSchema);
    restaurant = mongoose.model('restaurants', restaurantSchema);
    event = mongoose.model('events', eventSchema);
    ContactForm = mongoose.model('contact', ContactSchema);
    FeedbackForm = mongoose.model('feedback', FeedbackSchema);
});

mongoose.connect('mongodb://localhost:27017/TripOn');

var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

//require('./app/chat')(io);
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
app.use(express.static(path.join(__dirname, 'public')));

// use JWT auth to secure the api
app.use('/api', expressJwt({ secret: config.secret }).unless({ path: ['/api/users/authenticate', '/api/users/register'] }));

// routes
app.use('/login', require('./controllers/login.controller'));
app.use('/register', require('./controllers/register.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/api/users', require('./controllers/api/users.controller'));
app.use('/forgetPassword', require('./controllers/forgetPassword.controller'));
app.use('/home', require('./controllers/home.controller'));
app.use('/contact', require('./controllers/contact.controller'));
app.use('/event_view', require('./controllers/event_view.controller'));
app.use('/event_view1', require('./controllers/event_view1.controller'));
//var Hotels = require('./models/hotels');

// make '/app' default route
app.get('/', function (req, res) {
    return res.redirect('/app');
});

// make '/app' default route
app.get('/hotels', function (req, res) {
    hotelList.find()
        .then(function (hotels) {
            if (hotels) {
                res.send(hotels);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.get('/hotels/:address', function (req, res) {
    hotelList.find( { $or: [ { "Address": { "$regex": req.params.address, "$options": "i" } },{ "Location": { "$regex": req.params.address, "$options": "i" } }]})
        .then(function (hotels) {
            if (hotels) {
                res.send(hotels);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
                res.status(400).send(err);
        });

});

app.post('/hotels', function (req, res) {
    var hotel = new hotelList({
        Name:  req.body.Name,
        Location: req.body.Location,
        Address: req.body.Address,
        Description : req.body.Description,
        Rating : req.body.Rating,
        pricePerDay : req.body.pricePerDay
    });
    hotel.save(function(err, thor) {
        if (err){
            return res.send("error");
        }else{
            console.log('hotel created');
            return res.send("success");
        }
    });
});

app.get('/Events', function (req, res) {
    event.find()
        .then(function (events) {
            if (events) {
                res.send(events);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.get('/Events/:address', function (req, res) {
    event.find({ "Location": { "$regex": req.params.address, "$options": "i" }})
        .then(function (events) {
            if (events) {
                res.send(events);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.post('/Events', function (req, res) {
    console.log(req);
    var eventObj = new event({
        Name: req.body.name,
        Location: req.body.location,
        Venue:  req.body.venue,
        Description: req.body.description,
        Timings: req.body.timings
    });
    eventObj.save(function(err) {
        if (err){
            return res.send("error");
        }else{
            console.log('events created');
            return res.send("success");
        }

    });
});
app.get('/Restaurants', function (req, res) {
    restaurant.find()
        .then(function (restaurants) {
            if (restaurants) {
                res.send(restaurants);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.get('/Restaurants/:address', function (req, res) {
    restaurant.find( { $or: [ { "Address": { "$regex": req.params.address, "$options": "i" } },{ "Location": { "$regex": req.params.address, "$options": "i" } }]})
        .then(function (restaurants) {
            if (restaurants) {
                res.send(restaurants);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.post('/Restaurants', function (req, res) {
    console.log(req);
    var restaurantObj = new restaurant({
        Name: req.body.name,
        Location: req.body.location,
        Address:  req.body.address,
        Description: req.body.description,
        Timings: req.body.timings,
        Contact: req.body.contact
    });
    restaurantObj.save(function(err) {
        if (err){
            return res.send("error");
        }else{
            console.log('restauarant created');
            return res.send("success");
        }

    });
});

// start server
/*var server = app.listen(3000, function () {
 console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
 });
 */

var server = http.listen(3000, function(){
    console.log('Server listening at http://' + server.address().address + ':' + server.address().port);

});
var fisrtTimeConnection = true;
var listOfOnlinePeople = [];
io.on('connection', function(socket){
    socket.on('chat message', function(data){
        io.emit('chat message', data);
        var chat = new chatMessage({
            username:  data.name
            , message: data.msg
        });

        chat.save(function(err, thor) {
            if (err) return console.error(err);
        });
    });

    socket.on('get All Chat', function(){
        chatMessage.find(function (err, chats) {
            if (err) return console.error(err);
            io.emit('get All Chat', chats);
        });
    });

    socket.on("typing", function(data) {
        io.emit("isTyping", data);
    });
    socket.on("disconnect", function() {
        socket.leave(socket.room);
        console.log(socket.id + ' disconnected');
        var id = socket.id;
        for(var i = 0; i < listOfOnlinePeople.length; i++) {
            if(listOfOnlinePeople[i].socketId == id) {
                listOfOnlinePeople.splice(i, 1);
                io.emit("getOnlinePeople",{"listOfOnlinePeople" : listOfOnlinePeople});
                break;
            }
        }
    });
    socket.on("joinserver", function(data) {
        //console.log('disconnect');
        console.log(socket.id + " : "+data.uname);
        // if(!data.isVisited) {
        listOfOnlinePeople.push({"socketId": socket.id, "username": data.uname});
        // }
        io.emit("getOnlinePeople",{"listOfOnlinePeople" : listOfOnlinePeople});
    });

    socket.on('subscribe', function(data) {
        console.log('joining room', data.roomId);
        socket.room = data.roomId;
        socket.join(data.roomId);
        //rooms.push({"roomName" : data.roomId,"socketId": socket.id});
        var socketId;
        for(var i = 0; i < listOfOnlinePeople.length; i++) {
            if(listOfOnlinePeople[i].username == data.toUser) {
                socketId = listOfOnlinePeople[i].socketId;
                io.sockets.connected[socketId].emit('join room to chat', {"roomName" : data.roomId ,"fromUser" : data.name});
                //rooms.push({"roomName" : data.roomId,"socketId": socketId});
                break;
            }
        }

    });
    socket.on('add me in room', function(data) {
        socket.room = data.roomName;
        console.log("adding toUser");
        socket.join(data.roomName);
    });
    socket.on('send private message', function(data) {
        var roomId  = data.room;
        console.log("room found");
        io.to(roomId).emit('conversation private post', {
            "message": data.message,
            "fromUser": data.name,
            "toUser": data.toUser
        });
    });

});

///////////////////////////////////////////////save contact form///////////////////////////////////////////////////

app.post('/contact', function (req, res) {
    console.log('testing2');
    var email = req.param('Email');
    console.log('guestname: ' + email);
    var subject = req.param('Subject');
    console.log('title: ' + subject);
    var msg = req.param('Message');
    console.log('desciption: ' + msg);

//save db
    var contact = new ContactForm({
        Email : email,
        Subject :subject,
        Message: msg

    });
    contact.save(function(err, thor) {
        if (err) return console.error(err);

        res.render('contact',{Message:'Thank you for contacting us...!'});

    });

});
///////////////////////////////////////////////save contact form///////////////////////////////////////////////////

app.post('/feedback', function (req, res) {

    var name = req.param('name');
    console.log('guestname: ' + name);
    var email = req.param('email');
    console.log('title: ' + email);
    var phone = req.param('phone');
    console.log('desciption: ' + phone);
    var message = req.param('message');
    console.log('desciption: ' + message);

//save db
    var feedback = new FeedbackForm({
        name : name,
        email :email,
        phone: phone,
        feedback:message
    });
    feedback.save(function(err, thor) {
        if (err) return console.error(err);

        res.render('feedback',{Message:'Thank you for giving us feedback...!'});

    });

});<commit_msg>feedback data insert into database<commit_after>require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
//var mongo = require('mongoskin');
//var db = mongo.db(config.connectionString, { native_parser: true });

var mongoose = require('mongoose');
var chatMessage;
var hotelList;
var restaurant;
var feedback;
var event;
var ContactForm;
var FeedbackForm;
var db = mongoose.connection;

db.on('error', console.error);
db.once('open', function() {

    var chatSchema = new mongoose.Schema({
        username: { type: String }
        , message: String
    });
   var hotelSchema = new mongoose.Schema({
       Name: String,
       Location: {type: String},
        Address: { type: String },
        Description : { type: String },
        Rating : { type: String },
        Price : { type: String }
   });
    var feedbackSchema = new mongoose.Schema({
        Name: String,
        Email: {type: String},
        Phone: { type: String },
        message: { type: String }
    });
     var restaurantSchema = new mongoose.Schema({
        Name: String,
        Location: String,
        Address:  String,
        Description: String,
        Timings: String,
        Contact: String
    });
    var eventSchema = new mongoose.Schema({
        Name: String,
        Location: String,
        Venue:  String,
        Description: String,
        Timings: String
    });
    var ContactSchema = new mongoose.Schema({
        Email : String,
        Subject : String,
        Message: String

    });

// Compile a 'chat' model using the chatSchema as the structure.
// Mongoose also creates a MongoDB collection called 'chat' for these documents.
    chatMessage = mongoose.model('chat', chatSchema);
    hotelList = mongoose.model('hotels', hotelSchema);
    restaurant = mongoose.model('restaurants', restaurantSchema);
    event = mongoose.model('events', eventSchema);
    ContactForm = mongoose.model('contact', ContactSchema);
    feedback = mongoose.model('feedbacks',feedbackSchema);
});

mongoose.connect('mongodb://localhost:27017/TripOn');

var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');

//require('./app/chat')(io);
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
app.use(express.static(path.join(__dirname, 'public')));

// use JWT auth to secure the api
app.use('/api', expressJwt({ secret: config.secret }).unless({ path: ['/api/users/authenticate', '/api/users/register'] }));

// routes
app.use('/login', require('./controllers/login.controller'));
app.use('/register', require('./controllers/register.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/api/users', require('./controllers/api/users.controller'));
app.use('/forgetPassword', require('./controllers/forgetPassword.controller'));
app.use('/home', require('./controllers/home.controller'));
app.use('/contact', require('./controllers/contact.controller'));
app.use('/event_view', require('./controllers/event_view.controller'));
app.use('/event_view1', require('./controllers/event_view1.controller'));
//var Hotels = require('./models/hotels');

// make '/app' default route
app.get('/', function (req, res) {
    return res.redirect('/app');
});

// make '/app' default route
app.get('/hotels', function (req, res) {
    hotelList.find()
        .then(function (hotels) {
            if (hotels) {
                res.send(hotels);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.get('/hotels/:address', function (req, res) {
    hotelList.find( { $or: [ { "Address": { "$regex": req.params.address, "$options": "i" } },{ "Location": { "$regex": req.params.address, "$options": "i" } }]})
        .then(function (hotels) {
            if (hotels) {
                res.send(hotels);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
                res.status(400).send(err);
        });

});

app.post('/hotels', function (req, res) {
    var hotel = new hotelList({
        Name:  req.body.Name,
        Location: req.body.Location,
        Address: req.body.Address,
        Description : req.body.Description,
        Rating : req.body.Rating,
        pricePerDay : req.body.pricePerDay
    });
    hotel.save(function(err, thor) {
        if (err){
            return res.send("error");
        }else{
            console.log('hotel created');
            return res.send("success");
        }
    });
});

app.get('/Events', function (req, res) {
    event.find()
        .then(function (events) {
            if (events) {
                res.send(events);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.get('/viewFeedbacks', function (req, res) {
    feedback.find()
        .then(function (feedbacks) {
            if (feedbacks) {
                res.send(feedbacks);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.post('/Feedbacks', function (req, res) {
    var feedback1 = new feedback({
        Name:  req.body.name,
        Email: req.body.email,
        Phone: req.body.phone,
        message: req.body.message
    });
    feedback1.save(function(err, thor) {
        if (err){
            return res.send("error");
        }else{
            console.log('Feedback added');
            return res.send("success");
        }
    });
});

app.get('/Events/:address', function (req, res) {
    event.find({ "Location": { "$regex": req.params.address, "$options": "i" }})
        .then(function (events) {
            if (events) {
                res.send(events);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.post('/Events', function (req, res) {
    console.log(req);
    var eventObj = new event({
        Name: req.body.name,
        Location: req.body.location,
        Venue:  req.body.venue,
        Description: req.body.description,
        Timings: req.body.timings
    });
    eventObj.save(function(err) {
        if (err){
            return res.send("error");
        }else{
            console.log('events created');
            return res.send("success");
        }

    });
});
app.get('/Restaurants', function (req, res) {
    restaurant.find()
        .then(function (restaurants) {
            if (restaurants) {
                res.send(restaurants);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.get('/Restaurants/:address', function (req, res) {
    restaurant.find( { $or: [ { "Address": { "$regex": req.params.address, "$options": "i" } },{ "Location": { "$regex": req.params.address, "$options": "i" } }]})
        .then(function (restaurants) {
            if (restaurants) {
                res.send(restaurants);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });

});

app.post('/Restaurants', function (req, res) {
    console.log(req);
    var restaurantObj = new restaurant({
        Name: req.body.name,
        Location: req.body.location,
        Address:  req.body.address,
        Description: req.body.description,
        Timings: req.body.timings,
        Contact: req.body.contact
    });
    restaurantObj.save(function(err) {
        if (err){
            return res.send("error");
        }else{
            console.log('restauarant created');
            return res.send("success");
        }

    });
});

// start server
/*var server = app.listen(3000, function () {
 console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
 });
 */

var server = http.listen(3000, function(){
    console.log('Server listening at http://' + server.address().address + ':' + server.address().port);

});
var fisrtTimeConnection = true;
var listOfOnlinePeople = [];
io.on('connection', function(socket){
    socket.on('chat message', function(data){
        io.emit('chat message', data);
        var chat = new chatMessage({
            username:  data.name
            , message: data.msg
        });

        chat.save(function(err, thor) {
            if (err) return console.error(err);
        });
    });

    socket.on('get All Chat', function(){
        chatMessage.find(function (err, chats) {
            if (err) return console.error(err);
            io.emit('get All Chat', chats);
        });
    });

    socket.on("typing", function(data) {
        io.emit("isTyping", data);
    });
    socket.on("disconnect", function() {
        socket.leave(socket.room);
        console.log(socket.id + ' disconnected');
        var id = socket.id;
        for(var i = 0; i < listOfOnlinePeople.length; i++) {
            if(listOfOnlinePeople[i].socketId == id) {
                listOfOnlinePeople.splice(i, 1);
                io.emit("getOnlinePeople",{"listOfOnlinePeople" : listOfOnlinePeople});
                break;
            }
        }
    });
    socket.on("joinserver", function(data) {
        //console.log('disconnect');
        console.log(socket.id + " : "+data.uname);
        // if(!data.isVisited) {
        listOfOnlinePeople.push({"socketId": socket.id, "username": data.uname});
        // }
        io.emit("getOnlinePeople",{"listOfOnlinePeople" : listOfOnlinePeople});
    });

    socket.on('subscribe', function(data) {
        console.log('joining room', data.roomId);
        socket.room = data.roomId;
        socket.join(data.roomId);
        //rooms.push({"roomName" : data.roomId,"socketId": socket.id});
        var socketId;
        for(var i = 0; i < listOfOnlinePeople.length; i++) {
            if(listOfOnlinePeople[i].username == data.toUser) {
                socketId = listOfOnlinePeople[i].socketId;
                io.sockets.connected[socketId].emit('join room to chat', {"roomName" : data.roomId ,"fromUser" : data.name});
                //rooms.push({"roomName" : data.roomId,"socketId": socketId});
                break;
            }
        }

    });
    socket.on('add me in room', function(data) {
        socket.room = data.roomName;
        console.log("adding toUser");
        socket.join(data.roomName);
    });
    socket.on('send private message', function(data) {
        var roomId  = data.room;
        console.log("room found");
        io.to(roomId).emit('conversation private post', {
            "message": data.message,
            "fromUser": data.name,
            "toUser": data.toUser
        });
    });

});

///////////////////////////////////////////////save contact form///////////////////////////////////////////////////

app.post('/contact', function (req, res) {
    console.log('testing2');
    var email = req.param('Email');
    console.log('guestname: ' + email);
    var subject = req.param('Subject');
    console.log('title: ' + subject);
    var msg = req.param('Message');
    console.log('desciption: ' + msg);

//save db
    var contact = new ContactForm({
        Email : email,
        Subject :subject,
        Message: msg

    });
    contact.save(function(err, thor) {
        if (err) return console.error(err);

        res.render('contact',{Message:'Thank you for contacting us...!'});

    });

});
///////////////////////////////////////////////save contact form///////////////////////////////////////////////////

app.post('/feedback', function (req, res) {

    var name = req.param('name');
    console.log('guestname: ' + name);
    var email = req.param('email');
    console.log('title: ' + email);
    var phone = req.param('phone');
    console.log('desciption: ' + phone);
    var message = req.param('message');
    console.log('desciption: ' + message);

//save db
    var feedback = new FeedbackForm({
        name : name,
        email :email,
        phone: phone,
        feedback:message
    });
    feedback.save(function(err, thor) {
        if (err) return console.error(err);

        res.render('feedback',{Message:'Thank you for giving us feedback...!'});

    });

});<|endoftext|>


<commit_before>/**
 * jQuery DFP v1.0.8
 * http://github.com/coop182/jquery.dfp.js
 *
 * Copyright 2013 Matt Cooper
 * Released under the MIT license
 */
(function ($, window) {

    "use strict";

    // Save Scope
    var dfpScript = this;

    // DFP account ID
    var dfpID = '';

    // Count of ads
    var count = 0;

    // Count of rendered ads
    var rendered = 0;

    // Default DFP jQuery selector
    var dfpSelector = '.adunit';

    // Keep track of if we've already tried to load gpt.js before
    var dfpIsLoaded = false;

    /**
     * Init function sets required params and loads Google's DFP script
     * @param  String id       The DFP account ID
     * @param  String selector The adunit selector
     * @param  Object options  Custom options to apply
     */
    var init = function (id, selector, options) {

        dfpID = id || dfpID;
        dfpSelector = selector || dfpSelector;
        options = options || {};
        dfpLoader();
        $(function () { createAds(options); });

    };

    /**
     * Main function to find and create all Ads
     * @param Object options Custom options to apply
     */
    var createAds = function (options) {

        // Array to Store AdUnits
        var adUnitArray = [];

        // Default DFP options
        var URLTargets = getURLTargets();

        var dfpOptions = {
            'setTargeting': {
                'inURL': URLTargets.inURL,
                'URLIs': URLTargets.URLIs,
                'Query': URLTargets.Query,
                'Domain': window.location.host
            },
            'enableSingleRequest': true,
            'collapseEmptyDivs': 'original'
        };

        // Make sure the default setTargeting is not lost in the object merge
        if (typeof options.setTargeting !== 'undefined' && typeof dfpOptions.setTargeting !== 'undefined') {
            options.setTargeting = $.extend(options.setTargeting, dfpOptions.setTargeting);
        }

        // Merge options objects
        dfpOptions = $.extend(dfpOptions, options);

        // Loops through on page Ad units and gets ads for them.
        $(dfpSelector).each(function () {

            var adUnit = this;

            count++;

            // adUnit name
            var adUnitName = getName(adUnit);

            // adUnit id - this will use an existing id or an auto generated one.
            var adUnitID = getID(adUnit, adUnitName, count);

            // get dimensions of the adUnit
            var dimensions = getDimensions(adUnit);

            // get existing content
            var $existingContent = $(adUnit).html();

            // wipe html clean ready for ad and set the default display class.
            $(adUnit).html('').addClass('display-none');

            // Store AdUnits
            adUnitArray.push(adUnitID);

            // Push commands to DFP to create ads
            window.googletag.cmd.push(function () {

                // Create the ad - out of page or normal
                var googleAdUnit;
                if (typeof $(adUnit).data('outofpage') !== 'undefined') {
                    googleAdUnit = window.googletag.defineOutOfPageSlot('/' + dfpID + '/' + adUnitName, adUnitID).addService(window.googletag.pubads());
                } else {
                    googleAdUnit = window.googletag.defineSlot('/' + dfpID + '/' + adUnitName, dimensions, adUnitID).addService(window.googletag.pubads());
                }

                // Sets custom targeting for just THIS ad unit if it has been specified
                if (typeof $(adUnit).data("targeting") === 'object') {
                    $.each($(adUnit).data("targeting"), function (k, v) {
                        googleAdUnit.setTargeting(k, v);
                    });
                }

                // The following hijacks an internal google method to check if the div has been
                // collapsed after the ad has been attempted to be loaded.
                googleAdUnit.oldRenderEnded = googleAdUnit.renderEnded;
                googleAdUnit.renderEnded = function () {

                    rendered++;

                    var display = $(adUnit).css('display');

                    // if the div has been collapsed but there was existing content expand the
                    // div and reinsert the existing content.
                    if (display === 'none' && $.trim($existingContent).length > 0 && dfpOptions.collapseEmptyDivs === 'original') {
                        $(adUnit).show().html($existingContent);
                        display = 'block display-original';
                    }

                    $(adUnit).removeClass('display-none').addClass('display-' + display);

                    googleAdUnit.oldRenderEnded();

                    // Excute afterEachAdLoaded callback if provided
                    if (typeof dfpOptions.afterEachAdLoaded === 'function') {
                        dfpOptions.afterEachAdLoaded.call(this, adUnit);
                    }

                    // Excute afterAllAdsLoaded callback if provided
                    if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) {
                        dfpOptions.afterAllAdsLoaded.call(this, $(dfpSelector));
                    }

                };

            });

        });

        // Push DFP config options
        window.googletag.cmd.push(function () {

            if (dfpOptions.enableSingleRequest === true) {
                window.googletag.pubads().enableSingleRequest();
            }
            $.each(dfpOptions.setTargeting, function (k, v) {
                window.googletag.pubads().setTargeting(k, v);
            });
            if (dfpOptions.collapseEmptyDivs === true || dfpOptions.collapseEmptyDivs === 'original') {
                window.googletag.pubads().collapseEmptyDivs();
            }
            window.googletag.enableServices();

        });

        // Display each ad
        $.each(adUnitArray, function (k, v) {

            window.googletag.cmd.push(function () { window.googletag.display(v); });

        });

    };

    /**
     * Create an array of paths so that we can target DFP ads to Page URI's
     * @return Array an array of URL parts that can be targeted.
     */
    var getURLTargets = function () {

        // Get the paths for targeting against
        var paths = window.location.pathname.replace(/\/$/, '');
        var patt = new RegExp('\/([^\/]*)', 'ig');
        var pathsMatches = paths.match(patt);
        var targetPaths = ['/'];
        var longestpath = '';
        if (paths !== '/' && pathsMatches !== null) {
            var target = '';
            var size = pathsMatches.length;
            if (size > 0) {
                for (var i = 0; i < size; i++) {
                    target = pathsMatches[i];
                    targetPaths.push(target);
                    for (var j = i + 1; j < size; j++) {
                        target += pathsMatches[j];
                        targetPaths.push(target);
                    }
                    if (i === 0) {
                        targetPaths.splice(-1, 1);
                        longestpath = target;
                    }
                }
            }
            targetPaths.push(longestpath);
        }

        targetPaths = targetPaths.reverse();

        // Get the query params for targeting against
        var url = window.location.toString().replace(/\=/ig, ':').match(/\?(.+)$/);
        var params = RegExp.$1.split("&");

        return {
            'inURL': targetPaths,
            'URLIs': targetPaths[0],
            'Query': params
        };

    };

    /**
     * Get the id of the adUnit div or generate a unique one.
     * @param  Object adUnit     The adunit to work with
     * @param  String adUnitName The name of the adunit
     * @param  Integer count     The current count of adunit, for uniqueness
     * @return String             The ID of the adunit or a unique autogenerated ID
     */
    var getID = function (adUnit, adUnitName, count) {

        var id = adUnit.id;
        if (id === '')
        {
            id = adUnit.id = adUnitName + '-auto-gen-id-' + count;
        }

        return id;

    };

    /**
     * Get the name of the Ad unit, either use the div id or
     * check for the optional attribute data-adunit
     * @param  Object adUnit The adunit to work with
     * @return String        The name of the adunit, will be the same as inside DFP
     */
    var getName = function (adUnit) {

        var name = adUnit.id;
        if (typeof $(adUnit).data('adunit') !== 'undefined') {

            name = $(adUnit).data('adunit');

        }

        return name;

    };

    /**
     * Get the dimensions of the ad unit using the container div dimensions or
     * check for the optional attribute data-dimensions
     * @param  Object adUnit The adunit to work with
     * @return Array         The dimensions of the adunit (width, height)
     */
    var getDimensions = function (adUnit) {

        var dimensions = [],
            $adUnit = $(adUnit),
            dimensionsData = $adUnit.data('dimensions');

        // Check if data-dimensions are specified. If they aren't, use the dimensions of the ad unit div.
        if (typeof dimensionsData !== 'undefined') {

            var dimensionGroups = dimensionsData.split(',');

            $.each(dimensionGroups, function (k, v) {

                var dimensionSet = v.split('x');
                dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]);

            });

        } else {

            dimensions.push([$adUnit.width(), $adUnit.height()]);

        }

        return dimensions;

    };

    /**
     * Call the google DFP script - there is a little bit of error detection in here to detect
     * if the dfp script has failed to load either through an error or it being blocked by an ad
     * blocker... if it does not load we execute a dummy script to replace the real DFP.
     */
    var dfpLoader = function () {

        // make sure we don't load gpt.js multiple times
        dfpIsLoaded = dfpIsLoaded || $('script[src*="googletagservices.com/tag/js/gpt.js"]').length;
        if (dfpIsLoaded) {
            return;
        }

        window.googletag = window.googletag || {};
        window.googletag.cmd = window.googletag.cmd || [];

        var gads = document.createElement('script');
        gads.async = true;
        gads.type = 'text/javascript';

        // Adblock blocks the load of Ad scripts... so we check for that
        gads.onerror = function () {
            dfpBlocked();
        };

        var useSSL = 'https:' === document.location.protocol;
        gads.src = (useSSL ? 'https:' : 'http:') +
        '//www.googletagservices.com/tag/js/gpt.js';
        var node = document.getElementsByTagName('script')[0];
        node.parentNode.insertBefore(gads, node);

        // Adblock plus seems to hide blocked scripts... so we check for that
        if (gads.style.display === 'none') {
            dfpBlocked();
        }

    };

    /**
     * This function gets called if DFP has been blocked by an adblocker
     * it implements a dummy version of the dfp object and allows the script to excute its callbacks
     * regardless of whether DFP is actually loaded or not... it is basically only useful for situations
     * where you are laying DFP over existing content and need to init things like slide shows after the loading
     * is completed.
     */
    var dfpBlocked = function () {

        // Get the stored dfp commands
        var commands = window.googletag.cmd;

        // SetTimeout is a bit dirty but the script does not execute in the correct order without it
        setTimeout(function () {

            // overwrite the dfp object - replacing the command array with a function and defining missing functions
            window.googletag = {
                cmd: {
                    push: function (callback) {
                        callback.call(dfpScript);
                    }
                },
                ads: [],
                pubads: function () { return this; },
                enableSingleRequest: function () { return this; },
                setTargeting: function () { return this; },
                collapseEmptyDivs: function () { return this; },
                enableServices: function () { return this; },
                defineSlot: function (name, dimensions, id) {
                    window.googletag.ads.push(id);
                    window.googletag.ads[id] = {
                        renderEnded: function () {},
                        addService: function () { return this; }
                    };
                    return window.googletag.ads[id];
                },
                defineOutOfPageSlot: function (name, id) {
                    window.googletag.ads.push(id);
                    window.googletag.ads[id] = {
                        renderEnded: function () {},
                        addService: function () { return this; }
                    };
                    return window.googletag.ads[id];
                },
                display: function (id) {
                    window.googletag.ads[id].renderEnded.call(dfpScript);
                    return this;
                }

            };

            // Execute any stored commands
            $.each(commands, function (k, v) {
                window.googletag.cmd.push(v);
            });

        }, 50);

    };

    /**
     * Add function to the jQuery namespace
     * @param  String id      (Optional) The DFP account ID
     * @param  Object options (Optional) Custom options to apply
     */
    $.dfp = $.fn.dfp = function (id, options) {

        options = options || {};

        if (typeof id === 'undefined') {
            id = dfpID;
        }

        if (typeof id === 'object') {
            options = id;
            id = options.dfpID || dfpID;
        }

        var selector = this;

        if (typeof this === 'function') {
            selector = dfpSelector;
        }

        init(id, selector, options);

    };

})(window.jQuery, window);
<commit_msg>add ability to monkey patch window.googletag<commit_after>/**
 * jQuery DFP v1.0.8
 * http://github.com/coop182/jquery.dfp.js
 *
 * Copyright 2013 Matt Cooper
 * Released under the MIT license
 */
(function ($, window) {

    "use strict";

    // Save Scope
    var dfpScript = this;

    // DFP account ID
    var dfpID = '';

    // Count of ads
    var count = 0;

    // Count of rendered ads
    var rendered = 0;

    // Default DFP jQuery selector
    var dfpSelector = '.adunit';

    // Keep track of if we've already tried to load gpt.js before
    var dfpIsLoaded = false;

    /**
     * Init function sets required params and loads Google's DFP script
     * @param  String id       The DFP account ID
     * @param  String selector The adunit selector
     * @param  Object options  Custom options to apply
     */
    var init = function (id, selector, options) {

        dfpID = id || dfpID;
        dfpSelector = selector || dfpSelector;
        options = options || {};
        dfpLoader();
        $(function () { createAds(options); });

    };

    /**
     * Main function to find and create all Ads
     * @param Object options Custom options to apply
     */
    var createAds = function (options) {

        // Array to Store AdUnits
        var adUnitArray = [];

        // Default DFP options
        var URLTargets = getURLTargets();

        var dfpOptions = {
            'setTargeting': {
                'inURL': URLTargets.inURL,
                'URLIs': URLTargets.URLIs,
                'Query': URLTargets.Query,
                'Domain': window.location.host
            },
            'enableSingleRequest': true,
            'collapseEmptyDivs': 'original'
        };

        // Make sure the default setTargeting is not lost in the object merge
        if (typeof options.setTargeting !== 'undefined' && typeof dfpOptions.setTargeting !== 'undefined') {
            options.setTargeting = $.extend(options.setTargeting, dfpOptions.setTargeting);
        }

        // Merge options objects
        dfpOptions = $.extend(dfpOptions, options);

        // If a custom googletag is specified, use it.
        if (dfpOptions.googletag) {
            window.googletag.cmd.push(function () {
                $.extend(window.googletag, dfpOptions.googletag);
            });
        }

        // Loops through on page Ad units and gets ads for them.
        $(dfpSelector).each(function () {

            var adUnit = this;

            count++;

            // adUnit name
            var adUnitName = getName(adUnit);

            // adUnit id - this will use an existing id or an auto generated one.
            var adUnitID = getID(adUnit, adUnitName, count);

            // get dimensions of the adUnit
            var dimensions = getDimensions(adUnit);

            // get existing content
            var $existingContent = $(adUnit).html();

            // wipe html clean ready for ad and set the default display class.
            $(adUnit).html('').addClass('display-none');

            // Store AdUnits
            adUnitArray.push(adUnitID);

            // Push commands to DFP to create ads
            window.googletag.cmd.push(function () {

                // Create the ad - out of page or normal
                var googleAdUnit;
                if (typeof $(adUnit).data('outofpage') !== 'undefined') {
                    googleAdUnit = window.googletag.defineOutOfPageSlot('/' + dfpID + '/' + adUnitName, adUnitID).addService(window.googletag.pubads());
                } else {
                    googleAdUnit = window.googletag.defineSlot('/' + dfpID + '/' + adUnitName, dimensions, adUnitID).addService(window.googletag.pubads());
                }

                // Sets custom targeting for just THIS ad unit if it has been specified
                if (typeof $(adUnit).data("targeting") === 'object') {
                    $.each($(adUnit).data("targeting"), function (k, v) {
                        googleAdUnit.setTargeting(k, v);
                    });
                }

                // The following hijacks an internal google method to check if the div has been
                // collapsed after the ad has been attempted to be loaded.
                googleAdUnit.oldRenderEnded = googleAdUnit.renderEnded;
                googleAdUnit.renderEnded = function () {

                    rendered++;

                    var display = $(adUnit).css('display');

                    // if the div has been collapsed but there was existing content expand the
                    // div and reinsert the existing content.
                    if (display === 'none' && $.trim($existingContent).length > 0 && dfpOptions.collapseEmptyDivs === 'original') {
                        $(adUnit).show().html($existingContent);
                        display = 'block display-original';
                    }

                    $(adUnit).removeClass('display-none').addClass('display-' + display);

                    googleAdUnit.oldRenderEnded();

                    // Excute afterEachAdLoaded callback if provided
                    if (typeof dfpOptions.afterEachAdLoaded === 'function') {
                        dfpOptions.afterEachAdLoaded.call(this, adUnit);
                    }

                    // Excute afterAllAdsLoaded callback if provided
                    if (typeof dfpOptions.afterAllAdsLoaded === 'function' && rendered === count) {
                        dfpOptions.afterAllAdsLoaded.call(this, $(dfpSelector));
                    }

                };

            });

        });

        // Push DFP config options
        window.googletag.cmd.push(function () {

            if (dfpOptions.enableSingleRequest === true) {
                window.googletag.pubads().enableSingleRequest();
            }
            $.each(dfpOptions.setTargeting, function (k, v) {
                window.googletag.pubads().setTargeting(k, v);
            });
            if (dfpOptions.collapseEmptyDivs === true || dfpOptions.collapseEmptyDivs === 'original') {
                window.googletag.pubads().collapseEmptyDivs();
            }
            window.googletag.enableServices();

        });

        // Display each ad
        $.each(adUnitArray, function (k, v) {

            window.googletag.cmd.push(function () { window.googletag.display(v); });

        });

    };

    /**
     * Create an array of paths so that we can target DFP ads to Page URI's
     * @return Array an array of URL parts that can be targeted.
     */
    var getURLTargets = function () {

        // Get the paths for targeting against
        var paths = window.location.pathname.replace(/\/$/, '');
        var patt = new RegExp('\/([^\/]*)', 'ig');
        var pathsMatches = paths.match(patt);
        var targetPaths = ['/'];
        var longestpath = '';
        if (paths !== '/' && pathsMatches !== null) {
            var target = '';
            var size = pathsMatches.length;
            if (size > 0) {
                for (var i = 0; i < size; i++) {
                    target = pathsMatches[i];
                    targetPaths.push(target);
                    for (var j = i + 1; j < size; j++) {
                        target += pathsMatches[j];
                        targetPaths.push(target);
                    }
                    if (i === 0) {
                        targetPaths.splice(-1, 1);
                        longestpath = target;
                    }
                }
            }
            targetPaths.push(longestpath);
        }

        targetPaths = targetPaths.reverse();

        // Get the query params for targeting against
        var url = window.location.toString().replace(/\=/ig, ':').match(/\?(.+)$/);
        var params = RegExp.$1.split("&");

        return {
            'inURL': targetPaths,
            'URLIs': targetPaths[0],
            'Query': params
        };

    };

    /**
     * Get the id of the adUnit div or generate a unique one.
     * @param  Object adUnit     The adunit to work with
     * @param  String adUnitName The name of the adunit
     * @param  Integer count     The current count of adunit, for uniqueness
     * @return String             The ID of the adunit or a unique autogenerated ID
     */
    var getID = function (adUnit, adUnitName, count) {

        var id = adUnit.id;
        if (id === '')
        {
            id = adUnit.id = adUnitName + '-auto-gen-id-' + count;
        }

        return id;

    };

    /**
     * Get the name of the Ad unit, either use the div id or
     * check for the optional attribute data-adunit
     * @param  Object adUnit The adunit to work with
     * @return String        The name of the adunit, will be the same as inside DFP
     */
    var getName = function (adUnit) {

        var name = adUnit.id;
        if (typeof $(adUnit).data('adunit') !== 'undefined') {

            name = $(adUnit).data('adunit');

        }

        return name;

    };

    /**
     * Get the dimensions of the ad unit using the container div dimensions or
     * check for the optional attribute data-dimensions
     * @param  Object adUnit The adunit to work with
     * @return Array         The dimensions of the adunit (width, height)
     */
    var getDimensions = function (adUnit) {

        var dimensions = [],
            $adUnit = $(adUnit),
            dimensionsData = $adUnit.data('dimensions');

        // Check if data-dimensions are specified. If they aren't, use the dimensions of the ad unit div.
        if (typeof dimensionsData !== 'undefined') {

            var dimensionGroups = dimensionsData.split(',');

            $.each(dimensionGroups, function (k, v) {

                var dimensionSet = v.split('x');
                dimensions.push([parseInt(dimensionSet[0], 10), parseInt(dimensionSet[1], 10)]);

            });

        } else {

            dimensions.push([$adUnit.width(), $adUnit.height()]);

        }

        return dimensions;

    };

    /**
     * Call the google DFP script - there is a little bit of error detection in here to detect
     * if the dfp script has failed to load either through an error or it being blocked by an ad
     * blocker... if it does not load we execute a dummy script to replace the real DFP.
     */
    var dfpLoader = function () {

        // make sure we don't load gpt.js multiple times
        dfpIsLoaded = dfpIsLoaded || $('script[src*="googletagservices.com/tag/js/gpt.js"]').length;
        if (dfpIsLoaded) {
            return;
        }

        window.googletag = window.googletag || {};
        window.googletag.cmd = window.googletag.cmd || [];

        var gads = document.createElement('script');
        gads.async = true;
        gads.type = 'text/javascript';

        // Adblock blocks the load of Ad scripts... so we check for that
        gads.onerror = function () {
            dfpBlocked();
        };

        var useSSL = 'https:' === document.location.protocol;
        gads.src = (useSSL ? 'https:' : 'http:') +
        '//www.googletagservices.com/tag/js/gpt.js';
        var node = document.getElementsByTagName('script')[0];
        node.parentNode.insertBefore(gads, node);

        // Adblock plus seems to hide blocked scripts... so we check for that
        if (gads.style.display === 'none') {
            dfpBlocked();
        }

    };

    /**
     * This function gets called if DFP has been blocked by an adblocker
     * it implements a dummy version of the dfp object and allows the script to excute its callbacks
     * regardless of whether DFP is actually loaded or not... it is basically only useful for situations
     * where you are laying DFP over existing content and need to init things like slide shows after the loading
     * is completed.
     */
    var dfpBlocked = function () {

        // Get the stored dfp commands
        var commands = window.googletag.cmd;

        // SetTimeout is a bit dirty but the script does not execute in the correct order without it
        setTimeout(function () {

            // overwrite the dfp object - replacing the command array with a function and defining missing functions
            window.googletag = {
                cmd: {
                    push: function (callback) {
                        callback.call(dfpScript);
                    }
                },
                ads: [],
                pubads: function () { return this; },
                enableSingleRequest: function () { return this; },
                setTargeting: function () { return this; },
                collapseEmptyDivs: function () { return this; },
                enableServices: function () { return this; },
                defineSlot: function (name, dimensions, id) {
                    window.googletag.ads.push(id);
                    window.googletag.ads[id] = {
                        renderEnded: function () {},
                        addService: function () { return this; }
                    };
                    return window.googletag.ads[id];
                },
                defineOutOfPageSlot: function (name, id) {
                    window.googletag.ads.push(id);
                    window.googletag.ads[id] = {
                        renderEnded: function () {},
                        addService: function () { return this; }
                    };
                    return window.googletag.ads[id];
                },
                display: function (id) {
                    window.googletag.ads[id].renderEnded.call(dfpScript);
                    return this;
                }

            };

            // Execute any stored commands
            $.each(commands, function (k, v) {
                window.googletag.cmd.push(v);
            });

        }, 50);

    };

    /**
     * Add function to the jQuery namespace
     * @param  String id      (Optional) The DFP account ID
     * @param  Object options (Optional) Custom options to apply
     */
    $.dfp = $.fn.dfp = function (id, options) {

        options = options || {};

        if (typeof id === 'undefined') {
            id = dfpID;
        }

        if (typeof id === 'object') {
            options = id;
            id = options.dfpID || dfpID;
        }

        var selector = this;

        if (typeof this === 'function') {
            selector = dfpSelector;
        }

        init(id, selector, options);

    };

})(window.jQuery, window);
<|endoftext|>


<commit_before>/*
  postcss-inrule (v1.1.0)
  github.com/salsita/postcss-inrule
  2016 | MIT
  ============================== */

var postcss = require('postcss'),
    assign = require('object-assign');

// Get index of inRule tags
function getTagIndex(string, tag) {
  var tags = string.match('^' + tag + '+');
  return tags && tags[0].length || 0;
}

// Lil' Shavy™
function getShavedClone(clone) {
  var element, current, first = true;
  // Find current element and remove its props
  clone.walkAtRules('in', function (inRule) {
    if (first) {
      first = false;
      current = element = inRule.parent;
      element.removeAll();
    }
  });
  // Clean all parent props that don't lead to current element
  while (current.parent) {
    current.parent.each(function (node) {
      node !== current && node.remove();
    });
    current = current.parent;
  }
  return element;
}

// Process modifications on clone
function processModifications(clone, params, options, inRule) {
  for (var param of params) {
    var appendIndex = getTagIndex(param, options.tagAppend),
        insertIndex = getTagIndex(param, options.tagInsert),
        replaceIndex = getTagIndex(param, options.tagReplace),
        currentIndex = Math.max(appendIndex, insertIndex, replaceIndex),
        modifier = param.slice(currentIndex, param.length),
        current = clone,
        modified = false,
        nodeCount = 0;
    while (current.parent && !modified) {
      var selectors = current.parent.selectors;
      current.type !== 'rule' && nodeCount--;
      if (selectors) {
        nodeCount++;
        if (nodeCount >= currentIndex && clone.parent.type !== 'root') {
          // Append
          if (appendIndex > 0) {
            current.parent.selectors = selectors.map(function (selector) {
              return selector + modifier;
            });
          // Insert
          } else if (insertIndex > 0) {
            current.parent.selectors = selectors.map(function (selector) {
              return selector + ' ' + modifier;
            });
          // Replace
          } else if (replaceIndex > 0) {
            current.parent.selectors = [modifier];
          } else {
            throw inRule.error('No valid tag found', { word: param });
          }
          modified = true;
        }
      }
      current = current.parent;
    }
    if (!modified) {
      throw inRule.error('No parent to modify found', { word: param });
    }
  }
  return clone;
}

module.exports = postcss.plugin('postcss-inrule', function (options) {
  return function (css) {

    // improve tagIndex regex
    // remove immediate at-rules that have no decls from original node

    // Options
    options = options || {};
    var defaultOptions = {
      tagAppend: '<',
      tagInsert: '\\^',
      tagReplace: '@'
    };
    options = assign({
      tagAppend: options.tagAppend || defaultOptions.tagAppend,
      tagInsert: options.tagInsert || defaultOptions.tagInsert,
      tagReplace: options.tagReplace || defaultOptions.tagReplace
    }, options);

    // Process @in at-rules
    css.walkAtRules('in', function (inRule) {

      // Clone a prop-less tree clone for every ',' param
      for (var params of inRule.params.split(',')) {
        var clone = getShavedClone(inRule.root().clone());

        // Process modifications and append new rule to root
        params = postcss.list.space(params);
        processModifications(clone, params, options, inRule);
        if (inRule.nodes.length > 0) {
          clone.append(inRule.nodes);
        } else {
          throw inRule.error('No declarations or other children', { word: inRule });
        }
        css.append(clone.root());
      }
      // Remove empty nodes from original tree
      while (!inRule.parent.nodes.some(function (node){
        return node.type ===  'decl';
      }) && inRule.parent.type !== 'root') { inRule = inRule.parent; }
      // Remove original @in rule and all children
      inRule.removeAll().remove();
    });
  };
});
<commit_msg>better nodeIndex<commit_after>/*
  postcss-inrule (v1.1.0)
  github.com/salsita/postcss-inrule
  2016 | MIT
  ============================== */

var postcss = require('postcss'),
    assign = require('object-assign');

// Get index of inRule tags
function getTagIndex(string, tag) {
  var tags = string.match('^' + tag + '+');
  return tags && tags[0].length || 0;
}

// Lil' Shavy™
function getShavedClone(clone) {
  var element, current, first = true;
  // Find current element and remove its props
  clone.walkAtRules('in', function (inRule) {
    if (first) {
      first = false;
      current = element = inRule.parent;
      element.removeAll();
    }
  });
  // Clean all parent props that don't lead to current element
  while (current.parent) {
    current.parent.each(function (node) {
      node !== current && node.remove();
    });
    current = current.parent;
  }
  return element;
}

// Process modifications on clone
function processModifications(clone, params, options, inRule) {
  for (var param of params) {
    var current = clone,
        appendIndex = getTagIndex(param, options.tagAppend),
        insertIndex = getTagIndex(param, options.tagInsert),
        replaceIndex = getTagIndex(param, options.tagReplace),
        currentIndex = Math.max(appendIndex, insertIndex, replaceIndex),
        nodeIndex = current.type !== 'rule' ? -1 : 0,
        modifier = param.slice(currentIndex, param.length),
        modified = false;
    while (current.parent && !modified) {
      var selectors = current.parent.selectors;
      if (selectors) {
        nodeIndex++;
        if (nodeIndex >= currentIndex && clone.parent.type !== 'root') {
          // Append
          if (appendIndex > 0) {
            current.parent.selectors = selectors.map(function (selector) {
              return selector + modifier;
            });
          // Insert
          } else if (insertIndex > 0) {
            current.parent.selectors = selectors.map(function (selector) {
              return selector + ' ' + modifier;
            });
          // Replace
          } else if (replaceIndex > 0) {
            current.parent.selectors = [modifier];
          } else {
            throw inRule.error('No valid tag found', { word: param });
          }
          modified = true;
        }
      }
      current = current.parent;
    }
    if (!modified) {
      throw inRule.error('No parent to modify found', { word: param });
    }
  }
  return clone;
}

module.exports = postcss.plugin('postcss-inrule', function (options) {
  return function (css) {

    // improve tagIndex regex
    // remove immediate at-rules that have no decls from original node

    // Options
    options = options || {};
    var defaultOptions = {
      tagAppend: '<',
      tagInsert: '\\^',
      tagReplace: '@'
    };
    options = assign({
      tagAppend: options.tagAppend || defaultOptions.tagAppend,
      tagInsert: options.tagInsert || defaultOptions.tagInsert,
      tagReplace: options.tagReplace || defaultOptions.tagReplace
    }, options);

    // Process @in at-rules
    css.walkAtRules('in', function (inRule) {

      // Clone a prop-less tree clone for every ',' param
      for (var params of inRule.params.split(',')) {
        var clone = getShavedClone(inRule.root().clone());

        // Process modifications and append new rule to root
        params = postcss.list.space(params);
        processModifications(clone, params, options, inRule);
        if (inRule.nodes.length > 0) {
          clone.append(inRule.nodes);
        } else {
          throw inRule.error('No declarations or other children', { word: inRule });
        }
        css.append(clone.root());
      }
      // Remove empty parent nodes from original tree
      while (!inRule.parent.nodes.some(function (node){
        return node.type ===  'decl';
      }) && inRule.parent.type !== 'root') { inRule = inRule.parent; }
      // Remove original @in rule and all children
      inRule.removeAll().remove();
    });
  };
});
<|endoftext|>


<commit_before>/* eslint-disable no-trailing-spaces */
/* eslint-disable valid-jsdoc */
/* eslint-disable quotes */
/* eslint-disable max-len */

class RecordingProcessor extends AudioWorkletProcessor {
  constructor(options) {
    super();

    this.port.onmessage = (event) => {
      if (
        event.data.setRecording === false ||
        event.data.setRecording === true
      ) {
        this.isRecording = event.data.setRecording;
      }
    };

    this._liveSampleBuffer = new Float32Array(new SharedArrayBuffer(512));

    if (options && options.processorOptions.recordingBuffer) {
      this._recordingBuffer = (options.processorOptions.recordingBuffer);
      this.sampleRate = options.processorOptions.sampleRate;
    }

    this.recordingLength = 0;
    this.publishedRecordingLength = 0;
    this.isRecording = false;

    this.port.postMessage({
      message: 'PROCESSOR_INIT',
      liveSampleBuffer: this._liveSampleBuffer,
    });
  }

  process(inputs, outputs, params) {
    for (let input = 0; input < 1; input++) {
      const numberOfChannels = inputs[input].length;
      // Channel
      for (let channel = 0; channel < numberOfChannels; channel++) {
        // Sample
        for (let sample = 0; sample < inputs[input][channel].length; sample++) {
          const currentSample = inputs[input][channel][sample];

          this._liveSampleBuffer[sample] = currentSample;

          // Handle recording
          outputs[input][channel][sample] = currentSample;

          // Copy data to recording buffer interleaved
          if (this.isRecording) {
            const currentIndex =
                this.recordingLength +
                (sample * numberOfChannels) +
                channel;

            if (currentIndex < this._recordingBuffer.length) {
              this._recordingBuffer[currentIndex] =
                  currentSample;
            }
          }
        }
      }
    }

    // TODO think about this bound
    if (this.isRecording && this.recordingLength < this._recordingBuffer.length) {
      this.recordingLength+=128;

      // Only post a recordingLength update every 1/4 second
      if (this.recordingLength - this.publishedRecordingLength > this.sampleRate / 60) {
        this.publishedRecordingLength = this.recordingLength;

        this.port.postMessage({
          message: 'UPDATE_RECORDING_LENGTH',
          recordingLength: this.recordingLength,
        });
      }
    }

    if (this.recordingLength >= this._recordingBuffer.length) {
      console.log("length reached");
    }

    return true;
  }
}

registerProcessor('recording-processor', RecordingProcessor);
<commit_msg>fix nit on processor<commit_after>/* eslint-disable no-trailing-spaces */
/* eslint-disable valid-jsdoc */
/* eslint-disable quotes */
/* eslint-disable max-len */

class RecordingProcessor extends AudioWorkletProcessor {
  constructor(options) {
    super();

    this.port.onmessage = (event) => {
      if (
        event.data.setRecording === false ||
        event.data.setRecording === true
      ) {
        this.isRecording = event.data.setRecording;
      }
    };

    this._liveSampleBuffer = new Float32Array(new SharedArrayBuffer(512));

    if (options && options.processorOptions.recordingBuffer) {
      this._recordingBuffer = (options.processorOptions.recordingBuffer);
      this.sampleRate = options.processorOptions.sampleRate;
    }

    this.recordingLength = 0;
    this.publishedRecordingLength = 0;
    this.isRecording = false;

    this.port.postMessage({
      message: 'PROCESSOR_INIT',
      liveSampleBuffer: this._liveSampleBuffer,
    });
  }

  process(inputs, outputs, params) {
    for (let input = 0; input < 1; input++) {
      const numberOfChannels = inputs[input].length;

      // Channel
      for (let channel = 0; channel < numberOfChannels; channel++) {
        const channelOffset = this.recordingLength + channel;

        // Sample
        for (let sample = 0; sample < inputs[input][channel].length; sample++) {
          const currentSample = inputs[input][channel][sample];

          this._liveSampleBuffer[sample] = currentSample;

          // Handle recording
          outputs[input][channel][sample] = currentSample;

          // Copy data to recording buffer interleaved
          if (this.isRecording) {
            const currentIndex = channelOffset +
                (sample * numberOfChannels);

            if (currentIndex < this._recordingBuffer.length) {
              this._recordingBuffer[currentIndex] =
                  currentSample;
            }
          }
        }
      }
    }

    // TODO think about this bound
    if (this.isRecording && this.recordingLength < this._recordingBuffer.length) {
      this.recordingLength+=128;

      // Only post a recordingLength update every 1/4 second
      if (this.recordingLength - this.publishedRecordingLength > this.sampleRate / 60) {
        this.publishedRecordingLength = this.recordingLength;

        this.port.postMessage({
          message: 'UPDATE_RECORDING_LENGTH',
          recordingLength: this.recordingLength,
        });
      }
    }

    if (this.recordingLength >= this._recordingBuffer.length) {
      console.log("length reached");
    }

    return true;
  }
}

registerProcessor('recording-processor', RecordingProcessor);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  /* @ngInject */
  angular
    .module('app.controllers', ['app.services'])
    .controller('WeekListCtrl', WeekListCtrl)
    .controller('WeekDetailCtrl', WeekDetailCtrl)
    .controller('WeekDeleteCtrl', WeekDeleteCtrl)
    .controller('DayDetailCtrl', DayDetailCtrl)
    .controller('MainCtrl', MainCtrl);

  /* @ngInject */
  function WeekListCtrl (Week, $scope, Page) {
    Page.setTitle('Weeks');
    this.weeks = Week.query();
  }

  /* @ngInject */
  function WeekDetailCtrl ($routeParams, Week, Days, DayToggleWr, $scope, Page) {
    Page.setTitle('Week');
    this.week = Week.get({ id: $routeParams.id });
    this.days = Days.query({ id: $routeParams.id });
    $scope.togglewr = function(dayId, position) {
      (DayToggleWr.toggleWr({ id: dayId }))
        .$promise
          .then(function(data) {
            $scope.weekdetail.week = data;
            $scope.weekdetail.days[position].well_registered = !$scope.weekdetail.days[position].well_registered;
          })
          .catch(function(response) {
            console.log(response);
          });
    };

  }

  /* @ngInject */
  function WeekDeleteCtrl ($routeParams, Week) {
    Week.remove({ id: $routeParams.id });
  }

  /* @ngInject */
  function DayDetailCtrl ($routeParams, Day, Ods, $scope, Page) {
    Page.setTitle('Day');
    this.day = Day.get({ id: $routeParams.id });
    this.ods = Ods.query({ id: $routeParams.id });
  }

  /* @ngInject */
  function MainCtrl ($scope, Page) {
    $scope.Page = Page;
  }

})();
<commit_msg>adds toggle_o/d functions<commit_after>(function () {
  'use strict';

  /* @ngInject */
  angular
    .module('app.controllers', ['app.services'])
    .controller('WeekListCtrl', WeekListCtrl)
    .controller('WeekDetailCtrl', WeekDetailCtrl)
    .controller('WeekDeleteCtrl', WeekDeleteCtrl)
    .controller('DayDetailCtrl', DayDetailCtrl)
    .controller('MainCtrl', MainCtrl);

  /* @ngInject */
  function WeekListCtrl (Week, $scope, Page) {
    Page.setTitle('Weeks');
    this.weeks = Week.query();
  }

  /* @ngInject */
  function WeekDetailCtrl ($routeParams, Week, Days, DayToggleWr, $scope, Page) {
    Page.setTitle('Week');
    this.week = Week.get({ id: $routeParams.id });
    this.days = Days.query({ id: $routeParams.id });
    $scope.togglewr = function(dayId, position) {
      (DayToggleWr.toggleWr({ id: dayId }))
        .$promise
          .then(function(data) {
            $scope.weekdetail.week = data;
            $scope.weekdetail.days[position].well_registered = !$scope.weekdetail.days[position].well_registered;
          })
          .catch(function(response) {
            console.log(response);
          });
    };

  }

  /* @ngInject */
  function WeekDeleteCtrl ($routeParams, Week) {
    Week.remove({ id: $routeParams.id });
  }

  /* @ngInject */
  function DayDetailCtrl ($routeParams, Day, Ods, OdToggleO, OdToggleD, $scope, Page) {
    Page.setTitle('Day');
    this.day = Day.get({ id: $routeParams.id });
    this.ods = Ods.query({ id: $routeParams.id });
    $scope.toggle_o = function(odId, position) {
      (OdToggleO.toggle_o({ id: odId }))
        .$promise
          .then(function(data) {
            $scope.daydetail.ods[position].o = !$scope.daydetail.ods[position].o;
          })
          .catch(function(response) {
            console.log(response);
          });
    };
    $scope.toggle_d = function(odId, position) {
      (OdToggleD.toggle_d({ id: odId }))
        .$promise
          .then(function(data) {
            $scope.daydetail.ods[position].d = !$scope.daydetail.ods[position].d;
          })
          .catch(function(response) {
            console.log(response);
          });
    };
  }

  /* @ngInject */
  function MainCtrl ($scope, Page) {
    $scope.Page = Page;
  }

})();
<|endoftext|>


<commit_before>'use strict';

exports.decorateConfig = config => Object.assign({}, config, {
  backgroundColor: '#1F2D3D',
  foregroundColor: '#E0E6ED',
  borderColor:     '#273444',
  cursorColor:     '#1FEEFF',
  cursorShape: 'BLOCK',
  fontFamily: 'SF Mono, Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

  colors: {
    black:        '#1F2D3D',
    red:          '#FF49DB',
    green:        '#13CE66',
    yellow:       '#FFC82C',
    blue:         '#1FB6FF',
    magenta:      '#7E5BEF',
    cyan:         '#1FEEFF',
    white:        '#E5E9F2',
    lightBlack:   '#8492A6',
    lightRed:     '#FF7CE5',
    lightGreen:   '#29EB7F',
    lightYellow:  '#FFD55F',
    lightBlue:    '#85D7FF',
    lightMagenta: '#A389F4',
    lightCyan:    '#1FEEFF',
    lightWhite:   '#F9FAFC'
  },
  css: `
    ${config.css}

    /* Hide title when only one tab */
    .tabs_title {
      display: none !important;
    }

    .tab_active:before {
      border-color: #13CE66;
    }

    .term_fit:not(.term_term) {
      opacity: 0.6;
    }

    .term_fit.term_active {
      opacity: 1;
      transition: opacity 0.12s ease-in-out;
      will-change: opacity;
    }

    .tab_tab::before {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 2px;
      background-color: #13CE66;
      transform: scaleX(0);
    }

    .tab_first {
      border-left-color: transparent !important;
    }

    .tab_tab:not(.tab_active) {
      color: #8492A6;
    }

    .tab_tab.tab_active::before {
      transform: scaleX(1);
      transition: all 200ms cubic-bezier(0.0, 0.0, 0.2, 1);
    }
  `
});
<commit_msg>remove block cursor & font. leave choice to user...<commit_after>'use strict';

exports.decorateConfig = config => Object.assign({}, config, {
  backgroundColor: '#1F2D3D',
  foregroundColor: '#E0E6ED',
  borderColor:     '#273444',
  cursorColor:     '#1FEEFF',

  colors: {
    black:        '#1F2D3D',
    red:          '#FF49DB',
    green:        '#13CE66',
    yellow:       '#FFC82C',
    blue:         '#1FB6FF',
    magenta:      '#7E5BEF',
    cyan:         '#1FEEFF',
    white:        '#E5E9F2',
    lightBlack:   '#8492A6',
    lightRed:     '#FF7CE5',
    lightGreen:   '#29EB7F',
    lightYellow:  '#FFD55F',
    lightBlue:    '#85D7FF',
    lightMagenta: '#A389F4',
    lightCyan:    '#1FEEFF',
    lightWhite:   '#F9FAFC'
  },
  css: `
    ${config.css}

    /* Hide title when only one tab */
    .tabs_title {
      display: none !important;
    }

    .tab_active:before {
      border-color: #13CE66;
    }

    .term_fit:not(.term_term) {
      opacity: 0.6;
    }

    .term_fit.term_active {
      opacity: 1;
      transition: opacity 0.12s ease-in-out;
      will-change: opacity;
    }

    .tab_tab::before {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 2px;
      background-color: #13CE66;
      transform: scaleX(0);
    }

    .tab_first {
      border-left-color: transparent !important;
    }

    .tab_tab:not(.tab_active) {
      color: #8492A6;
    }

    .tab_tab.tab_active::before {
      transform: scaleX(1);
      transition: all 200ms cubic-bezier(0.0, 0.0, 0.2, 1);
    }
  `
});
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

// Provides control sap.ui.core.CustomData.
sap.ui.define(['jquery.sap.global', './Element', './library'],
	function(jQuery, Element, library) {
	"use strict";

	/**
	 * Constructor for a new CustomData.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * Contains a single key/value pair of custom data attached to an Element. See method data().
	 * @extends sap.ui.core.Element
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @name sap.ui.core.CustomData
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var CustomData = Element.extend("sap.ui.core.CustomData", /** @lends sap.ui.core.CustomData.prototype */ { metadata : {

		library : "sap.ui.core",
		properties : {

			/**
			 * The key of the data in this CustomData object.
			 * When the data is just stored, it can be any string, but when it is to be written to HTML (writeToDom == true) then it must also be a valid HTML attribute name (it must conform to the sap.ui.core.ID type and may contain no colon) to avoid collisions, it also may not start with "sap-ui". When written to HTML, the key is prefixed with "data-".
			 * If any restriction is violated, a warning will be logged and nothing will be written to the DOM.
			 */
			key : {type : "string", group : "Data", defaultValue : null},

			/**
			 * The data stored in this CustomData object.
			 * When the data is just stored, it can be any JS type, but when it is to be written to HTML (writeToDom == true) then it must be a string.
			 * If this restriction is violated, a warning will be logged and nothing will be written to the DOM.
			 */
			value : {type : "any", group : "Data", defaultValue : null},

			/**
			 * If set to "true" and the value is of type "string" and the key conforms to the documented restrictions, this custom data is written to the HTML root element of the control as a "data-*" attribute.
			 * If the key is "abc" and the value is "cde", the HTML will look as follows:
			 * <SomeTag ... data-abc="cde" ... >
			 * Thus the application can provide stable attributes by data binding which can be used for styling or identification purposes.
			 * ATTENTION: use carefully to not create huge attributes or a large number of them.
			 * @since 1.9.0
			 */
			writeToDom : {type : "boolean", group : "Data", defaultValue : false}
		}
	}});

	CustomData.prototype.setValue = function(oValue) {
		this.setProperty("value", oValue, true);

		var oControl = this.getParent();
		if (oControl && oControl.getDomRef()) {
			var oCheckResult = this._checkWriteToDom(oControl);
			if (oCheckResult) {
				// update DOM directly
				oControl.$().attr(oCheckResult.key, oCheckResult.value);
			}
		}
		return this;
	};

	CustomData.prototype._checkWriteToDom = function(oRelated) {
		if (!this.getWriteToDom()) {
			return null;
		}

		var key = this.getKey();
		var value = this.getValue();

		if (typeof value != "string") {
			jQuery.sap.log.error("CustomData with key " + key + " should be written to HTML of " + oRelated + " but the value is not a string.");
			return null;
		}

		if (!(sap.ui.core.ID.isValid(key)) || (key.indexOf(":") != -1)) {
			jQuery.sap.log.error("CustomData with key " + key + " should be written to HTML of " + oRelated + " but the key is not valid (must be a valid sap.ui.core.ID without any colon).");
			return null;
		}

		if (key != jQuery.sap._FASTNAVIGATIONKEY && key.indexOf("sap-ui") == 0) {
			jQuery.sap.log.error("CustomData with key " + key + " should be written to HTML of " + oRelated + " but the key is not valid (may not start with 'sap-ui').");
			return null;
		}

		var result = {key: "data-" + key, value: value};

		if (key == jQuery.sap._FASTNAVIGATIONKEY) {
			result.value = (value && (value.trim().toLowerCase() == "x" || value.trim().toLowerCase() == "true")) ? "true" : "false";
		}

		return result;
	};

	return CustomData;

}, /* bExport= */ true);
<commit_msg>[INTERNAL] CustomData: IE8 doesn't support String.trim()<commit_after>/*!
 * ${copyright}
 */

// Provides control sap.ui.core.CustomData.
sap.ui.define(['jquery.sap.global', './Element', './library'],
	function(jQuery, Element, library) {
	"use strict";

	/**
	 * Constructor for a new CustomData.
	 *
	 * @param {string} [sId] id for the new control, generated automatically if no id is given
	 * @param {object} [mSettings] initial settings for the new control
	 *
	 * @class
	 * Contains a single key/value pair of custom data attached to an Element. See method data().
	 * @extends sap.ui.core.Element
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @name sap.ui.core.CustomData
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var CustomData = Element.extend("sap.ui.core.CustomData", /** @lends sap.ui.core.CustomData.prototype */ { metadata : {

		library : "sap.ui.core",
		properties : {

			/**
			 * The key of the data in this CustomData object.
			 * When the data is just stored, it can be any string, but when it is to be written to HTML (writeToDom == true) then it must also be a valid HTML attribute name (it must conform to the sap.ui.core.ID type and may contain no colon) to avoid collisions, it also may not start with "sap-ui". When written to HTML, the key is prefixed with "data-".
			 * If any restriction is violated, a warning will be logged and nothing will be written to the DOM.
			 */
			key : {type : "string", group : "Data", defaultValue : null},

			/**
			 * The data stored in this CustomData object.
			 * When the data is just stored, it can be any JS type, but when it is to be written to HTML (writeToDom == true) then it must be a string.
			 * If this restriction is violated, a warning will be logged and nothing will be written to the DOM.
			 */
			value : {type : "any", group : "Data", defaultValue : null},

			/**
			 * If set to "true" and the value is of type "string" and the key conforms to the documented restrictions, this custom data is written to the HTML root element of the control as a "data-*" attribute.
			 * If the key is "abc" and the value is "cde", the HTML will look as follows:
			 * <SomeTag ... data-abc="cde" ... >
			 * Thus the application can provide stable attributes by data binding which can be used for styling or identification purposes.
			 * ATTENTION: use carefully to not create huge attributes or a large number of them.
			 * @since 1.9.0
			 */
			writeToDom : {type : "boolean", group : "Data", defaultValue : false}
		}
	}});

	CustomData.prototype.setValue = function(oValue) {
		this.setProperty("value", oValue, true);

		var oControl = this.getParent();
		if (oControl && oControl.getDomRef()) {
			var oCheckResult = this._checkWriteToDom(oControl);
			if (oCheckResult) {
				// update DOM directly
				oControl.$().attr(oCheckResult.key, oCheckResult.value);
			}
		}
		return this;
	};

	CustomData.prototype._checkWriteToDom = function(oRelated) {
		if (!this.getWriteToDom()) {
			return null;
		}

		var key = this.getKey();
		var value = this.getValue();

		if (typeof value != "string") {
			jQuery.sap.log.error("CustomData with key " + key + " should be written to HTML of " + oRelated + " but the value is not a string.");
			return null;
		}

		if (!(sap.ui.core.ID.isValid(key)) || (key.indexOf(":") != -1)) {
			jQuery.sap.log.error("CustomData with key " + key + " should be written to HTML of " + oRelated + " but the key is not valid (must be a valid sap.ui.core.ID without any colon).");
			return null;
		}

		if (key == jQuery.sap._FASTNAVIGATIONKEY) {
			value = /^\s*(x|true)\s*$/i.test(value) ? "true" : "false"; // normalize values
		} else if (key.indexOf("sap-ui") == 0) {
			jQuery.sap.log.error("CustomData with key " + key + " should be written to HTML of " + oRelated + " but the key is not valid (may not start with 'sap-ui').");
			return null;
		}

		return {key: "data-" + key, value: value};

	};

	return CustomData;

}, /* bExport= */ true);
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var parser = require('./routes/parser');
var http = require('http');
var path = require('path');
var fs = require('fs');
// var request = require('superagent');
var token = process.env.APPSETTING_readability_key || require(__dirname + '/config.js').token;
var params;
var caracolDB = require('./database/dbsetup.js').caracolDB;

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);

app.get('/users', user.list);
app.get('/app/:u/:t/*', function(req, res){
  params = {
    url: decodeURI(req.params.u),
    token: token
  };
  fs.readFile('./client/app.js', function(error, data){
    if (error) {
      console.log(error);
    } else {
      res.end(data);
    }
  });
    //query db to see if favorited
});

<<<<<<< HEAD
app.options('/*', function(req, res){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.send(200, res.header);
});

app.post('/uri', function(req, res){
  console.log('post received', req.body);
=======
app.post('/uri', function(req, res){
  console.log("post received",req.body);
>>>>>>> post request route
  params = {
    url: req.body.uri,
    token: token
  };
  res.header("Access-Control-Allow-Origin", "*");
  res.end(parser.parser(params, function(response){
    //write data to db if it isn't already there
    console.log('response', response.body);
  }));
});
//new get request
//datestamp from visited bookmarklet
//weighting upvote/downvote

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>refactor uri route<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var parser = require('./routes/parser');
var http = require('http');
var path = require('path');
var fs = require('fs');
// var request = require('superagent');
var token = process.env.APPSETTING_readability_key || require(__dirname + '/config.js').token;
var params;
var caracolDB = require('./database/dbsetup.js').caracolDB;

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);

app.get('/users', user.list);
app.get('/app/:u/:t/*', function(req, res){
  params = {
    url: decodeURI(req.params.u),
    token: token
  };
  fs.readFile('./client/app.js', function(error, data){
    if (error) {
      console.log(error);
    } else {
      res.end(data);
    }
  });
    //query db to see if favorited
});

app.options('/*', function(req, res){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.send(200, res.header);
});

app.post('/uri', function(req, res){
  console.log('post received', req.body);
  params = {
    url: req.body.uri,
    token: token
  };
  res.header("Access-Control-Allow-Origin", "*");
  res.end(parser.parser(params, function(response){
    //write data to db if it isn't already there
    console.log('response', response.body);
  }));
});
//new get request
//datestamp from visited bookmarklet
//weighting upvote/downvote

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>