<commit_before>import React, { PropTypes } from 'react';
import invariant from 'invariant';
import { provide } from 'react-redux';
import { initializePlugin } from 'mention/plugin';
import { finalizeSetup } from 'mention/actions/mentionActions';
import initializeRedux from 'mention/utils/initializeRedux';
import mentionReducer from 'mention/reducers/mentionReducer';
import TinyMCEDelegate from 'mention/components/TinyMCEDelegate';
import SuggestionList from 'mention/components/SuggestionList';
import MentionsDebugger from 'mention/components/MentionsDebugger';

const store = initializeRedux({
  mention: mentionReducer
});

@provide(store)
export default class Mention {

  static propTypes = {
    dataSource: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.func,
      PropTypes.object
    ]).isRequired,
    delimiter: PropTypes.string,
    transformFn: PropTypes.func
  }

  componentDidMount() {
    const { dataSource, delimiter } = this.props;

    initializePlugin(store, dataSource, delimiter)
      .then(::this._finalizeSetup)
      .catch((error, errorMsg) => {
        console.error(error);
      });
  }

  _finalizeSetup({ editor, resolvedDataSource }) {
    const dataSource = this._transformResponse(resolvedDataSource);
    store.dispatch(finalizeSetup(editor, dataSource));
  }

  _transformResponse(resolvedDataSource) {
    const { transformFn } = this.props;
    const isFunc = typeof transformFn === 'function';

    invariant(isFunc || typeof transformFn === 'undefined',
      'Error initializing plugin: `transformFn` must be a function.'
    );

    invariant(resolvedDataSource instanceof Array,
      'Error applying sort: `transformFn` must return an array.'
    );

    const transformedDataSource = isFunc
      ? transformFn(resolvedDataSource)
      : resolvedDataSource;

    invariant(transformedDataSource instanceof Array,
      'Error transforming response: `transformedDataSource` must be an array.'
    );

    return transformedDataSource;
  }

  render() {
    const { dataSource } = this.props;

    return (

        <SuggestionList />
        <TinyMCEDelegate />
        <MentionsDebugger />

    );
  }
}
<commit_msg>Removed unnecessary invariant<commit_after>import React, { PropTypes } from 'react';
import invariant from 'invariant';
import { provide } from 'react-redux';
import { initializePlugin } from 'mention/plugin';
import { finalizeSetup } from 'mention/actions/mentionActions';
import initializeRedux from 'mention/utils/initializeRedux';
import mentionReducer from 'mention/reducers/mentionReducer';
import TinyMCEDelegate from 'mention/components/TinyMCEDelegate';
import SuggestionList from 'mention/components/SuggestionList';
import MentionsDebugger from 'mention/components/MentionsDebugger';

const store = initializeRedux({
  mention: mentionReducer
});

@provide(store)
export default class Mention {

  static propTypes = {
    dataSource: PropTypes.oneOfType([
      PropTypes.array,
      PropTypes.func,
      PropTypes.object
    ]).isRequired,
    delimiter: PropTypes.string,
    transformFn: PropTypes.func
  }

  componentDidMount() {
    const { dataSource, delimiter } = this.props;

    initializePlugin(store, dataSource, delimiter)
      .then(::this._finalizeSetup)
      .catch((error, errorMsg) => {
        console.error(error);
      });
  }

  _finalizeSetup({ editor, resolvedDataSource }) {
    const dataSource = this._transformResponse(resolvedDataSource);
    store.dispatch(finalizeSetup(editor, dataSource));
  }

  _transformResponse(resolvedDataSource) {
    const { transformFn } = this.props;
    const isFunc = typeof transformFn === 'function';

    invariant(isFunc || typeof transformFn === 'undefined',
      'Error initializing plugin: `transformFn` must be a function.'
    );

    const transformedDataSource = isFunc
      ? transformFn(resolvedDataSource)
      : resolvedDataSource;

    invariant(transformedDataSource instanceof Array,
      'Error transforming response: `transformedDataSource` must be an array.'
    );

    return transformedDataSource;
  }

  render() {
    const { dataSource } = this.props;

    return (

        <SuggestionList />
        <TinyMCEDelegate />
        <MentionsDebugger />

    );
  }
}
<|endoftext|>


<commit_before>import deepClone from 'mout/src/lang/deepClone';

function transformRequest(data) {
  return JSON.stringify(data);
}

const headers = {
  'Content-Type': 'application/json',
};

export default function ({ client, filterQuery, mustContain, busy }) {
  return {

    // get /clusters
    //     Search for clusters with certain properties
    listClusters(params) {
      return busy(client._.get('/clusters', {
        params,
      }));
    },

    // post /clusters
    //     Create a cluster
    createCluster(cluster) {
      return busy(client._.post('/clusters', cluster, {
        transformRequest, headers,
      }));
    },

    // get /clusters/{id}
    //     Get a cluster
    getCluster(id) {
      return busy(client._.get(`/clusters/${id}`));
    },

    // patch /clusters/{id}
    //     Update the cluster
    updateCluster(cluster) {
      const editableCluster = deepClone(cluster),
        expected = ['name', 'type', 'config', '_id'],
        cfiltered = filterQuery(editableCluster, ...expected.slice(0, 3)),
        {
          missingKeys, promise,
        } = mustContain(cluster, ...expected);

      // Remove read only fields if any
      if (editableCluster.config.ssh && editableCluster.config.ssh.user) {
        delete editableCluster.config.ssh.user;
      }
      if (editableCluster.config.host) {
        delete editableCluster.config.host;
      }

      return missingKeys ? promise :
        busy(client._.patch(`/clusters/${cluster._id}`, cfiltered, {
          transformRequest, headers,
        }));
    },

    // delete /clusters/{id}
    //     Delete a cluster and its configuration
    deleteCluster(id) {
      return busy(client._.delete(`/clusters/${id}`));
    },

    // put /clusters/{id}/job/{jobId}/submit
    //     Submit a job to the cluster
    submitJob(clusterId, jobId) {
      console.log('Not implemented yet');
    },

    // get /clusters/{id}/log
    //     Get log entries for cluster
    getClusterLogs(taskId, offset = 0) {
      if (offset) {
        return busy(client._.get(`/clusters/${taskId}/log?offset=${offset}`));
      }
      return busy(client._.get(`/clusters/${taskId}/log`));
    },

    // PUT /clusters/{id}/provision Provision a cluster with ansible
    provisionCluster(id, params) {
      return busy(client._.put(`/clusters/${id}/provision`, params));
    },

    // put /clusters/{id}/start
    //     Start a cluster (ec2 only)
    startCluster(id) {
      return busy(client._.put(`/clusters/${id}/start`));
    },

    // get /clusters/{id}/status
    //     Get the clusters current state
    getClusterStatus(id) {
      return busy(client._.get(`/clusters/${id}/status`));
    },

    // put /clusters/{id}/terminate
    //     Terminate a cluster
    terminateCluster(id) {
      console.log('Not implemented yet');
    },
  };
}
<commit_msg>fix(IO): added two unimplemented cluster endpoints<commit_after>import deepClone from 'mout/src/lang/deepClone';

function transformRequest(data) {
  return JSON.stringify(data);
}

const headers = {
  'Content-Type': 'application/json',
};

export default function ({ client, filterQuery, mustContain, busy }) {
  return {

    // get /clusters
    //     Search for clusters with certain properties
    listClusters(params) {
      return busy(client._.get('/clusters', {
        params,
      }));
    },

    // post /clusters
    //     Create a cluster
    createCluster(cluster) {
      return busy(client._.post('/clusters', cluster, {
        transformRequest, headers,
      }));
    },

    // get /clusters/{id}
    //     Get a cluster
    getCluster(id) {
      return busy(client._.get(`/clusters/${id}`));
    },

    // patch /clusters/{id}
    //     Update the cluster
    updateCluster(cluster) {
      const editableCluster = deepClone(cluster),
        expected = ['name', 'type', 'config', '_id'],
        cfiltered = filterQuery(editableCluster, ...expected.slice(0, 3)),
        {
          missingKeys, promise,
        } = mustContain(cluster, ...expected);

      // Remove read only fields if any
      if (editableCluster.config.ssh && editableCluster.config.ssh.user) {
        delete editableCluster.config.ssh.user;
      }
      if (editableCluster.config.host) {
        delete editableCluster.config.host;
      }

      return missingKeys ? promise :
        busy(client._.patch(`/clusters/${cluster._id}`, cfiltered, {
          transformRequest, headers,
        }));
    },

    // delete /clusters/{id}
    //     Delete a cluster and its configuration
    deleteCluster(id) {
      return busy(client._.delete(`/clusters/${id}`));
    },

    // put /clusters/{id}/job/{jobId}/submit
    //     Submit a job to the cluster
    submitJob(clusterId, jobId) {
      return busy(client._.put(`/clusters/${clusterId}/job/${jobId}/submit`));
    },

    // get /clusters/{id}/log
    //     Get log entries for cluster
    getClusterLogs(taskId, offset = 0) {
      if (offset) {
        return busy(client._.get(`/clusters/${taskId}/log?offset=${offset}`));
      }
      return busy(client._.get(`/clusters/${taskId}/log`));
    },

    // PUT /clusters/{id}/provision Provision a cluster with ansible
    provisionCluster(id, params) {
      return busy(client._.put(`/clusters/${id}/provision`, params));
    },

    // put /clusters/{id}/start
    //     Start a cluster (ec2 only)
    startCluster(id) {
      return busy(client._.put(`/clusters/${id}/start`));
    },

    // get /clusters/{id}/status
    //     Get the clusters current state
    getClusterStatus(id) {
      return busy(client._.get(`/clusters/${id}/status`));
    },

    // put /clusters/{id}/terminate
    //     Terminate a cluster
    terminateCluster(id) {
      return busy(client._.put(`/clusters/${id}/terminate`));
    },
  };
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var shell = require('shelljs');

var command = 'chmod -R 775 dist/prod';

gulp.task('chmod-prod', function(cb) {
	shell.exec(command);
	cb();
});<commit_msg>update chmod<commit_after>var gulp = require('gulp');
var shell = require('shelljs');

var command = 'chmod -R 777 dist/prod';

gulp.task('chmod-prod', function(cb) {
	shell.exec(command);
	cb();
});<|endoftext|>


<commit_before>/**
 * Created by Matt on 24/01/2015.
 */
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    errorHandler = require('./errors'),
    Quiz = mongoose.model('Quiz'),
    _ = require('lodash');

//creating error handler for callback after quiz.update

/**

/**
 * Handling /play:id
 */

exports.createSummary = function(req, res, next){
    console.log('creating summary');
    req.quiz = {
        results: req.quiz.results,
        summary: req.quiz.summary
    };
    next();
};

exports.read = function(req, res) {
    res.jsonp(req.quiz);
};

exports.quizByID = function(req, res, next, id) { Quiz.findById(id).populate('user', 'displayName').exec(function(err, quiz) {
    console.log('quizByID: ' + id);
    if (err) return next(err);
    if (! quiz) return next(new Error('Failed to load Quiz ' + id));
    req.quiz = quiz;
    next();
});
};

exports.workOutAction = function(req, res, next){
    console.log('working out action../');
    var quiz = req.quiz;//working out based on quiz data from DB.
    var user = req.user;//using user data
    if(quiz.users[user._id]){//user exists
        console.log('user exists');
        if(!quiz.users[user._id].session){//no session but user exists
            req.action = 'createSessionInUser';
            console.log('no session but user exists');
            //insert session, start on question 1, res.currentQuestion = 5
        }
        else if(quiz === 5){//session in progress for user
            req.action = 'returnCurrentQuestion';
            console.log('session in progress for user');

        }
    }
    else{//user does not exist, quiz.users.userId === undefined
        req.action = 'createUserAndSession';
        console.log('user does not exist in quiz, inserting user and session 1');
        //creating user and current quiz session in quiz
    }
    next();
};

exports.performAction = function(req, res){
    var quiz = req.quiz;

    /*
        Functions for performing session actions
     */

    var newSession = function(){//constructor function, though using object literal as it does not contain methods
        var shuffleArray = function(array) {//shuffle array using implementation of Fisher-Yates' Knuth Shuffle
            for (var i = array.length - 1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
            return array;
        };
        var appendQuestionCallback = function(question){
            var newQuestion = {//new question definition by object literal
                'title': question.title,
                'timeLimit': question.timeLimit,
                'questionType': question.questionType,
                'pointsAwarded': question.pointsAwarded
            };
            if(req.quiz.users[req.user._id]){//if it defined... ie. does the user exist in the quiz coll yet?
                if(req.quiz.users[req.user._id].completedQuizSessions.length >= question.attemptsBeforeHint ){//nSessions >= nNeededForHint???
                    newQuestion.hint = question.hint;
                }
            }
            else{//user does not exist yet, so it's the first session.
                if(question.attemptsBeforeHint < 1){
                    newQuestion.hint = question.hint;
                }
            }
            if(question.questionType === 'Multiple Choice'){
                question.wrongAnswers.push(question.answer[0]);
                var multipleChoiceOptions = question.wrongAnswers;
                multipleChoiceOptions.push(question.answer[0]);
                newQuestion.answers = shuffleArray(multipleChoiceOptions);//return and assign shuffled answer order so they can't just remember "it's the first answer"
            }
            questions.push(newQuestion);
        };

        //creating questions:
        var questions = [];
        quiz.questions.forEach(appendQuestionCallback);
        if(quiz.settings[0].randomizeOrder){
            questions = shuffleArray(questions);
        }

        return {
            dateStarted: Date.now(),
            questions: questions,
            doneQuestions: []
        };
    };

    var extractUserInfo = function(){//extracts user info from http headers
        return{
            firstName: req.user.firstName,
            lastName: req.user.lastName,
            email: req.user.email,
            username: req.user.username,
            displayName: req.user.displayName
        };
    };

    //Setting up Model.update() parameters
    var conditions = {'_id':req.quiz._id};
    var update = {$set: {}};
    var callback = function(err, doc){
        if(err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
    };

    /*
     Now act on decisions:
     */
    if(req.action === 'createUserAndSession'){
        //TODO
        console.log('creating user and session in quiz');
        var user = {
            completedQuizSessions: [],
            session: newSession(),
            info: extractUserInfo()
        };
        //now update quiz collection
        update.$set['users.' + req.user._id] = user;
        res.jsonp(user.session.questions[0]);
        console.log(conditions,update);
        Quiz.update(conditions, update, {}, callback);

    }
    else if(req.action === 'createSessionInUser'){//then create session in user and update
        console.log('creating session in user (in quiz)');
        console.log(req.user._id);
        console.log(req.quiz.users[req.user._id].completedQuizSessions);
        var userWithSession = {
            session: newSession(),//generate new session
            completedQuizSessions: req.quiz.users[req.user._id].completedQuizSessions,//retain old data
            info: extractUserInfo()//keeps user info updated by updating at the start of a session...
        };
        res.jsonp(userWithSession.session.questions[0]);
        //update quizzes collection
        update.$set['users.' + req.user._id] = userWithSession;
        Quiz.update(conditions, update, {}, callback);
    }
    else{//return current question
        console.log('returning current question');
        res.jsonp(quiz.users[req.user._id].session.questions[0]);
    }
};

exports.respond = function(req, res){
    res.status(200).jsonp(req.questionToSend);
    console.log('after response');
};

/*
   POST RESPONSE FUNCTIONS
 */

exports.handleData = function(req, res, next){
    var quiz = req.quiz;
    console.log(req);
    console.log(quiz.users);

    //extract answer info and move question to doneQuestions
    quiz.users[req.user._id].session.questions[0].userAnswer = req.body.userAnswer;
    quiz.users[req.user._id].session.questions[0].timeSubmitted = Date.now();
    quiz.users[req.user._id].session.doneQuestions.push(quiz.users[req.user._id].session.questions.shift());
    //answer moved to doneQuestions

    //add info for response
    quiz.users[req.user._id].session.questions[0].qNumber = quiz.users[req.user._id].session.doneQuestions.length + 1;
    quiz.users[req.user._id].session.questions[0].nQuestions = quiz.users[req.user._id].session.doneQuestions.length + quiz.users[req.user._id].session.questions.length;
    //info added

    //work out what to do next()
    if(quiz.users[req.user._id].session.questions.length === 0){//check if no q's left
        req.action = 'endSession';
    }
    else{//questions are left, respond with question
        req.action = 'respondWithQuestion';
    }
    next();
};

exports.respondToPost = function(req, res, next){
    var quiz = req.quiz;

    //responding to post
    if(req.action === 'endSession'){
        //setting up return summary...TEMP for now
        req.questionToSend = {
            'questionType': 'quizSummary',
            'score': '100%'
        };
    }
    else{//session still in progress
        //return newQuestion
        req.questionToSend = quiz.users[req.user._id].session.questions[0];
    }
    res.status(200).jsonp({'nextQuestion': req.questionToSend});
    next();
};

exports.updateDB = function(req, res){
    console.log('afterRes');
    var quiz = req.quiz;
    req.editedUser = {//initialise user object for update.
        completedQuizSessions: quiz.users[req.user._id].completedQuizSessions,
        session: quiz.users[req.user._id].session,
        info: quiz.users[req.user._id].info
    };

    if(req.action === 'endSession') {
        //move session to doneSessions, make session = false, ready for db update
        req.editedUser.completedQuizSessions.push(req.editedUser.session);
        req.editedUser.session = false;
    }

    //Setting up Model.update() parameters;
    var conditions = {'_id':req.quiz._id};
    var update = {$set: {}};
    update.$set['users.' + req.user._id] = req.editedUser;

    var errorCallback = function(err, doc){
        if(err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
    };

    Quiz.update(conditions, update, {}, errorCallback);
};

//END POST RESPONSE FUNCTIONS
<commit_msg>code cleanup, changed POST flow to a more logical and easy to read order, added comments, made variable names make more sense, made sure answer is stored in coll<commit_after>/**
 * Created by Matt on 24/01/2015.
 */
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    errorHandler = require('./errors'),
    Quiz = mongoose.model('Quiz'),
    _ = require('lodash');

//creating error handler for callback after quiz.update

/**

/**
 * Handling /play:id
 */

exports.createSummary = function(req, res, next){
    console.log('creating summary');
    req.quiz = {
        results: req.quiz.results,
        summary: req.quiz.summary
    };
    next();
};

exports.read = function(req, res) {
    res.jsonp(req.quiz);
};

exports.quizByID = function(req, res, next, id) { Quiz.findById(id).populate('user', 'displayName').exec(function(err, quiz) {
    console.log('quizByID: ' + id);
    if (err) return next(err);
    if (! quiz) return next(new Error('Failed to load Quiz ' + id));
    req.quiz = quiz;
    next();
});
};

exports.workOutAction = function(req, res, next){
    console.log('working out action../');
    var quiz = req.quiz;//working out based on quiz data from DB.
    var user = req.user;//using user data
    if(quiz.users[user._id]){//user exists
        console.log('user exists');
        if(!quiz.users[user._id].session){//no session but user exists
            req.action = 'createSessionInUser';
            console.log('no session but user exists');
            //insert session, start on question 1, res.currentQuestion = 5
        }
        else if(quiz === 5){//session in progress for user
            req.action = 'returnCurrentQuestion';
            console.log('session in progress for user');

        }
    }
    else{//user does not exist, quiz.users.userId === undefined
        req.action = 'createUserAndSession';
        console.log('user does not exist in quiz, inserting user and session 1');
        //creating user and current quiz session in quiz
    }
    next();
};

exports.performAction = function(req, res){
    var quiz = req.quiz;

    /*
        Functions for performing session actions
     */

    var newSession = function(){//constructor function, though using object literal as it does not contain methods
        var shuffleArray = function(array) {//shuffle array using implementation of Fisher-Yates' Knuth Shuffle
            for (var i = array.length - 1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
            return array;
        };
        var appendQuestionCallback = function(question){
            var newQuestion = {//new question definition by object literal
                'title': question.title,
                'timeLimit': question.timeLimit,
                'questionType': question.questionType,
                'pointsAwarded': question.pointsAwarded
            };
            if(req.quiz.users[req.user._id]){//if it defined... ie. does the user exist in the quiz coll yet?
                if(req.quiz.users[req.user._id].completedQuizSessions.length >= question.attemptsBeforeHint ){//nSessions >= nNeededForHint???
                    newQuestion.hint = question.hint;
                }
            }
            else{//user does not exist yet, so it's the first session.
                if(question.attemptsBeforeHint < 1){
                    newQuestion.hint = question.hint;
                }
            }
            if(question.questionType === 'Multiple Choice'){
                question.wrongAnswers.push(question.answer[0]);
                var multipleChoiceOptions = question.wrongAnswers;
                multipleChoiceOptions.push(question.answer[0]);
                newQuestion.answers = shuffleArray(multipleChoiceOptions);//return and assign shuffled answer order so they can't just remember "it's the first answer"
            }
            questions.push(newQuestion);
        };

        //creating questions:
        var questions = [];
        quiz.questions.forEach(appendQuestionCallback);
        if(quiz.settings[0].randomizeOrder){
            questions = shuffleArray(questions);
        }

        return {
            dateStarted: Date.now(),
            questions: questions,
            doneQuestions: []
        };
    };

    var extractUserInfo = function(){//extracts user info from http headers
        return{
            firstName: req.user.firstName,
            lastName: req.user.lastName,
            email: req.user.email,
            username: req.user.username,
            displayName: req.user.displayName
        };
    };

    //Setting up Model.update() parameters
    var conditions = {'_id':req.quiz._id};
    var update = {$set: {}};
    var callback = function(err, doc){
        if(err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
    };

    /*
     Now act on decisions:
     */
    if(req.action === 'createUserAndSession'){
        //TODO
        console.log('creating user and session in quiz');
        var user = {
            completedQuizSessions: [],
            session: newSession(),
            info: extractUserInfo()
        };
        //now update quiz collection
        update.$set['users.' + req.user._id] = user;
        res.jsonp(user.session.questions[0]);
        console.log(conditions,update);
        Quiz.update(conditions, update, {}, callback);

    }
    else if(req.action === 'createSessionInUser'){//then create session in user and update
        console.log('creating session in user (in quiz)');
        console.log(req.user._id);
        console.log(req.quiz.users[req.user._id].completedQuizSessions);
        var userWithSession = {
            session: newSession(),//generate new session
            completedQuizSessions: req.quiz.users[req.user._id].completedQuizSessions,//retain old data
            info: extractUserInfo()//keeps user info updated by updating at the start of a session...
        };
        res.jsonp(userWithSession.session.questions[0]);
        //update quizzes collection
        update.$set['users.' + req.user._id] = userWithSession;
        Quiz.update(conditions, update, {}, callback);
    }
    else{//return current question
        console.log('returning current question');
        res.jsonp(quiz.users[req.user._id].session.questions[0]);
    }
};

exports.respond = function(req, res){
    res.status(200).jsonp(req.questionToSend);
    console.log('after response');
};

/*
   POST RESPONSE FUNCTIONS
 */

exports.handleData = function(req, res, next){
    var quiz = req.quiz;
    console.log(req);
    console.log(quiz.users);

    //extract answer info and move question to doneQuestions
    quiz.users[req.user._id].session.questions[0].userAnswer = req.body.userAnswer;
    quiz.users[req.user._id].session.questions[0].timeSubmitted = Date.now();
    quiz.users[req.user._id].session.doneQuestions.push(quiz.users[req.user._id].session.questions.shift());
    //answer moved to doneQuestions

    //work out what to do next()
    if(quiz.users[req.user._id].session.questions.length === 0){//check if no q's left
        req.action = 'endSession';
    }
    else{//questions are left, respond with question
        req.action = 'respondWithQuestion';
    }

    //add info for response
    if(req.action !== 'endSession'){
        quiz.users[req.user._id].session.questions[0].qNumber = quiz.users[req.user._id].session.doneQuestions.length + 1;
        quiz.users[req.user._id].session.questions[0].nQuestions = quiz.users[req.user._id].session.doneQuestions.length + quiz.users[req.user._id].session.questions.length;
    }
    //info added

    next();
};

exports.respondToPost = function(req, res, next){
    var quiz = req.quiz;

    //responding to post
    if(req.action === 'endSession'){
        //setting up return summary...TEMP for now
        req.questionToSend = {
            'questionType': 'quizSummary',
            'score': '100%'
        };
    }
    else{//session still in progress
        //return newQuestion
        req.questionToSend = quiz.users[req.user._id].session.questions[0];
    }
    res.status(200).jsonp({'nextQuestion': req.questionToSend});
    next();
};

exports.updateDB = function(req, res){
    console.log('afterRes');
    var quiz = req.quiz;
    req.editedUser = {//initialise user object for update.
        completedQuizSessions: quiz.users[req.user._id].completedQuizSessions,
        session: quiz.users[req.user._id].session,
        info: quiz.users[req.user._id].info
    };

    if(req.action === 'endSession') {
        //move session to doneSessions, make session = false, ready for db update
        req.editedUser.completedQuizSessions.push(req.editedUser.session);
        req.editedUser.session = false;
    }

    //Setting up Model.update() parameters;
    var conditions = {'_id':req.quiz._id};
    var update = {$set: {}};
    update.$set['users.' + req.user._id] = req.editedUser;

    var errorCallback = function(err, doc){
        if(err){
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        }
    };

    Quiz.update(conditions, update, {}, errorCallback);
};

//END POST RESPONSE FUNCTIONS
<|endoftext|>


<commit_before><commit_msg>add note<commit_after><|endoftext|>


<commit_before>module.exports = {
  root: true,
  extends: [
    '../all.js',
  ],
  rules: {
    'flowtype/require-valid-file-annotation': 'off',
  }
};
<commit_msg>Format test file<commit_after>module.exports = {
  root: true,
  extends: ['../all.js'],
  rules: {
    'flowtype/require-valid-file-annotation': 'off',
  },
};
<|endoftext|>


<commit_before><commit_msg>Changing Version<commit_after><|endoftext|>


<commit_before><commit_msg>added provide for FieldType, was causing compile errors.<commit_after>
goog.provide('caffeine.Model.Fieldtype');<|endoftext|>


<commit_before>var Singleton = require('../utils/singleton'),
    Path = require('path'),
    fs = require('fs'),
    _ = require('lodash'),
    logger = require('../utils/logger')('Settings', true);

var Settings = function() {
    this.rootDir = Path.resolve(Path.join(__dirname, '..', '..'));
    this.defaultSettings = {
        mongoUrl: 'mongodb://localhost:27017/giskard',
        adapter: 'shell',
        nicknames: [],
        loggerLevel: 'info',
        httpServerPort: 2727,
        token: null,
        roots: []
    };
    this.envAliases = {
        'PORT': 'httpServerPort',
        'MONGO_URL': 'mongoUrl'
    };

    var fileConf = {},
        preConf = {};
    try {
        var path = Path.resolve(process.env.GISKARDCONF || Path.join(this.rootDir, 'settings.json'));
        if(fs.existsSync(path)) {
            var file = fs.readFileSync(path).toString();
            fileConf = JSON.parse(file);
        }
    } catch(ex) {
        logger.error('Error loading settings file: ');
        logger.error(ex);
        process.exit(1);
    }

    _.merge(preConf, this.defaultSettings, fileConf);
    Object.keys(this.defaultSettings)
        .forEach(k => {
            if(process.env[k]) {
                preConf[k] = process.env[k];
            }
        });

    Object.keys(this.envAliases).forEach(k => {
        if(process.env[k]) {
            preConf[this.envAliases[k]] = process.env[k];
        }
    });

    _.merge(this, preConf);

    // TODO: At this point, iterate preConf and assign readonly properties to `this` scope,
    // using only getters.
};

module.exports = new Singleton(Settings);
<commit_msg>Include default setting value for sentryUri<commit_after>var Singleton = require('../utils/singleton'),
    Path = require('path'),
    fs = require('fs'),
    _ = require('lodash'),
    logger = require('../utils/logger')('Settings', true);

var Settings = function() {
    this.rootDir = Path.resolve(Path.join(__dirname, '..', '..'));
    this.defaultSettings = {
        mongoUrl: 'mongodb://localhost:27017/giskard',
        adapter: 'shell',
        nicknames: [],
        loggerLevel: 'info',
        httpServerPort: 2727,
        token: null,
        roots: [],
        sentryUri: null
    };
    this.envAliases = {
        'PORT': 'httpServerPort',
        'MONGO_URL': 'mongoUrl'
    };

    var fileConf = {},
        preConf = {};
    try {
        var path = Path.resolve(process.env.GISKARDCONF || Path.join(this.rootDir, 'settings.json'));
        if(fs.existsSync(path)) {
            var file = fs.readFileSync(path).toString();
            fileConf = JSON.parse(file);
        }
    } catch(ex) {
        logger.error('Error loading settings file: ');
        logger.error(ex);
        process.exit(1);
    }

    _.merge(preConf, this.defaultSettings, fileConf);
    Object.keys(this.defaultSettings)
        .forEach(k => {
            if(process.env[k]) {
                preConf[k] = process.env[k];
            }
        });

    Object.keys(this.envAliases).forEach(k => {
        if(process.env[k]) {
            preConf[this.envAliases[k]] = process.env[k];
        }
    });

    _.merge(this, preConf);

    // TODO: At this point, iterate preConf and assign readonly properties to `this` scope,
    // using only getters.
};

module.exports = new Singleton(Settings);
<|endoftext|>


<commit_before>var mkmk = mkmk || {};

mkmk.WebLayout = ccui.Layout.extend(/** @lends ccui.Layout# */{
    _usedHeight:0,
    _margin:5,
    _fontColor:cc.color(0,0,0),
    _tableLineColor:cc.color(128,128,128),

    ctor: function () {
        ccui.Layout.prototype.ctor.call(this); // super
        this._usedHeight = this._margin;
    },

    write: function(_string){
        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width,0));
        text.setAnchorPoint(cc.p(0,1));
        text.setPosition(cc.p(0,this.height-this._usedHeight));
        text.setColor(this._fontColor);

        this._usedHeight += text.height + this._margin;
        this.addChild(text);
        return text;
    },

    header : function(_string){
        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width,0));
        text.setAnchorPoint(cc.p(0,1));
        text.setPosition(cc.p(0,this.height-this._usedHeight));
        text.setColor(this._fontColor);

        this._usedHeight += text.height + this._margin;
        this.addChild(text);
        return text;
    },

    footer : function(_string){
        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width,0));
        text.setAnchorPoint(cc.p(0,0));
        text.setPosition(cc.p(this.width/2,0));
        text.setColor(this._fontColor);

        this.addChild(text);
        return text;
    },

    addImage : function(_image, _scaleX, _scaleY){
        var imageView = ccui.ImageView.create(_image);
        var height = imageView.height;
        if( _scaleX || _scaleY ){
            imageView.setScale( _scaleX, _scaleY );
            height *= _scaleY ? _scaleY : _scaleX;
        }
        imageView.setAnchorPoint(cc.p(0.5,1));
        imageView.setPosition(cc.p(this.width/2,this.height-this._usedHeight));

        this._usedHeight += height + this._margin;
        this.addChild(imageView);
        return imageView;
    },

    item : function(_string, _image){
        var iconSize = 40;
        var imageView = ccui.ImageView.create(_image);
        imageView.setScale(iconSize/imageView.width, iconSize/imageView.height);
        imageView.setAnchorPoint(cc.p(0,1));
        imageView.setPosition(cc.p(0,this.height-this._usedHeight));

        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width-iconSize-this._margin,0));
        text.setAnchorPoint(cc.p(0,1));
        text.setPosition(cc.p(iconSize+this._margin,this.height-this._usedHeight));
        text.setColor(this._fontColor);

        this._usedHeight += Math.max(iconSize, text.height) + this._margin;

        this.addChild(imageView);
        this.addChild(text);
    },

    table : function(_2DArray, _colWidths){
        var self = this;
        var drowLine = function(_start, _end){
            var lineWidth = 0.5;
            var lineColor = self._tableLineColor;
            var node = cc.DrawNode.create();
            node.drawSegment(_start,_end, lineWidth, lineColor);
            self.addChild(node);
            self._usedHeight += self._margin;
        };

        var firstPosY = this.height-this._usedHeight;

        drowLine(cc.p(this._margin,firstPosY), cc.p(this.width-this._margin,firstPosY));

        for(var col=0 ; col<_2DArray.length ; col++){
            var curCol = _2DArray[col];
            var posX = this._margin;
            var maxHeight = 0;
            for(var row=0 ; row<curCol.length ; row++){
                var text = new cc.LabelTTF(curCol[row]);
                text.setDimensions(cc.size(_colWidths[row],0));
                text.setAnchorPoint(cc.p(0,1));
                text.setPosition(cc.p(posX, this.height-this._usedHeight));
                text.setColor(this._fontColor);
                posX += _colWidths[row] + this._margin;
                maxHeight = Math.max(maxHeight, text.height );
                this.addChild(text);
            }
            this._usedHeight += maxHeight + this._margin;
            drowLine(cc.p(this._margin,this.height-this._usedHeight), cc.p(this.width-this._margin,this.height-this._usedHeight));
        }

        var posX = this._margin;
        var height = this.height-this._usedHeight+this._margin;
        drowLine(cc.p(posX,firstPosY), cc.p(posX,height));

        for(var i=0 ; i<_colWidths.length ; i++){
            posX += _colWidths[i];
            drowLine(cc.p(posX,firstPosY), cc.p(posX,height));
        }
    },

    brank : function(_height){
        this._usedHeight += _height;
    },

    setPage :function(_page){
        _page.call(this);
    }
});
<commit_msg>説明ページのタイトルの書式を調整<commit_after>var mkmk = mkmk || {};

mkmk.WebLayout = ccui.Layout.extend(/** @lends ccui.Layout# */{
    _usedHeight:0,
    _margin:5,
    _fontColor:cc.color(0,0,0),
    _tableLineColor:cc.color(128,128,128),
    _headerFontColor:cc.color(169, 68, 66),
    _headerUnderLineColor:cc.color(169, 68, 66),

    ctor: function () {
        ccui.Layout.prototype.ctor.call(this); // super
        this._usedHeight = this._margin;
    },

    write: function(_string){
        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width,0));
        text.setAnchorPoint(cc.p(0,1));
        text.setPosition(cc.p(0,this.height-this._usedHeight));
        text.setColor(this._fontColor);

        this._usedHeight += text.height + this._margin;
        this.addChild(text);
        return text;
    },

    header : function(_string){
        var self = this;
        var text = new cc.LabelTTF("◯"+_string);
        text.setDimensions(cc.size(this.width,0));
        text.setAnchorPoint(cc.p(0,1));
        text.setPosition(cc.p(0,this.height-this._usedHeight));
        text.setColor(this._headerFontColor);

        this._usedHeight += text.height;
        this.addChild(text);

        var drowDashLine = function(_startX, _endX, height){
            var lineWidth = 0.5;
            var lineColor = self._headerUnderLineColor;
            var dashWidth = 4;
            var space = 3;

            for(var posX = _startX ; posX < _endX ; posX += dashWidth ){

                var node = cc.DrawNode.create();
                node.drawSegment(cc.p(posX, height) , cc.p(posX+dashWidth, height), lineWidth, lineColor);
                self.addChild(node);
                posX += space;
            }
            self._usedHeight += self._margin;
        };

        drowDashLine(0, this.width, this.height-this._usedHeight);

        return text;
    },

    footer : function(_string){
        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width,0));
        text.setAnchorPoint(cc.p(0,0));
        text.setPosition(cc.p(this.width/2,0));
        text.setColor(this._fontColor);

        this.addChild(text);
        return text;
    },

    addImage : function(_image, _scaleX, _scaleY){
        var imageView = ccui.ImageView.create(_image);
        var height = imageView.height;
        if( _scaleX || _scaleY ){
            imageView.setScale( _scaleX, _scaleY );
            height *= _scaleY ? _scaleY : _scaleX;
        }
        imageView.setAnchorPoint(cc.p(0.5,1));
        imageView.setPosition(cc.p(this.width/2,this.height-this._usedHeight));

        this._usedHeight += height + this._margin;
        this.addChild(imageView);
        return imageView;
    },

    item : function(_string, _image){
        var iconSize = 40;
        var imageView = ccui.ImageView.create(_image);
        imageView.setScale(iconSize/imageView.width, iconSize/imageView.height);
        imageView.setAnchorPoint(cc.p(0,1));
        imageView.setPosition(cc.p(0,this.height-this._usedHeight));

        var text = new cc.LabelTTF(_string);
        text.setDimensions(cc.size(this.width-iconSize-this._margin,0));
        text.setAnchorPoint(cc.p(0,1));
        text.setPosition(cc.p(iconSize+this._margin,this.height-this._usedHeight));
        text.setColor(this._fontColor);

        this._usedHeight += Math.max(iconSize, text.height) + this._margin;

        this.addChild(imageView);
        this.addChild(text);
    },

    table : function(_2DArray, _colWidths){
        var self = this;
        var drowLine = function(_start, _end){
            var lineWidth = 0.5;
            var lineColor = self._tableLineColor;
            var node = cc.DrawNode.create();
            node.drawSegment(_start,_end, lineWidth, lineColor);
            self.addChild(node);
            self._usedHeight += self._margin;
        };

        var firstPosY = this.height-this._usedHeight;

        drowLine(cc.p(this._margin,firstPosY), cc.p(this.width-this._margin,firstPosY));

        for(var col=0 ; col<_2DArray.length ; col++){
            var curCol = _2DArray[col];
            var posX = this._margin;
            var maxHeight = 0;
            for(var row=0 ; row<curCol.length ; row++){
                var text = new cc.LabelTTF(curCol[row]);
                text.setDimensions(cc.size(_colWidths[row],0));
                text.setAnchorPoint(cc.p(0,1));
                text.setPosition(cc.p(posX, this.height-this._usedHeight));
                text.setColor(this._fontColor);
                posX += _colWidths[row] + this._margin;
                maxHeight = Math.max(maxHeight, text.height );
                this.addChild(text);
            }
            this._usedHeight += maxHeight + this._margin;
            drowLine(cc.p(this._margin,this.height-this._usedHeight), cc.p(this.width-this._margin,this.height-this._usedHeight));
        }

        var posX = this._margin;
        var height = this.height-this._usedHeight+this._margin;
        drowLine(cc.p(posX,firstPosY), cc.p(posX,height));

        for(var i=0 ; i<_colWidths.length ; i++){
            posX += _colWidths[i];
            drowLine(cc.p(posX,firstPosY), cc.p(posX,height));
        }
    },

    brank : function(_height){
        this._usedHeight += _height;
    },

    setPage :function(_page){
        _page.call(this);
    }
});
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import {View, StyleSheet, ActivityIndicator} from 'react-native';
import NavigationViewContainer from './navigation/NavigationViewContainer';
import * as snapshotUtil from '../utils/snapshot';
import * as SessionStateActions from '../modules/session/SessionState';
import store from '../redux/store';
import DeveloperMenu from '../components/DeveloperMenu';

const AppView = React.createClass({
  propTypes: {
    isReady: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
  },
  componentDidMount() {
    snapshotUtil.resetSnapshot()
      .then(snapshot => {
        const {dispatch} = this.props;

        if (snapshot) {
          dispatch(SessionStateActions.resetSessionStateFromSnapshot(snapshot));
        } else {
          dispatch(SessionStateActions.initializeSessionState());
        }

        store.subscribe(() => {
          snapshotUtil.saveSnapshot(store.getState());
        });
      });
  },

  render() {
    if (!this.props.isReady) {
      return (
        <View>
          <ActivityIndicator style={styles.centered}/>
        </View>
      );
    }

    return (
      <View style={{flex: 1}}>
        <NavigationViewContainer />
        {__DEV__ && <DeveloperMenu />}
      </View>
    );
  }
});

const styles = StyleSheet.create({
  centered: {
    flex: 1,
    alignSelf: 'center'
  }
});

export default AppView;
<commit_msg>Center the activity indicator shown when app not yet ready (#162)<commit_after>import React, {PropTypes} from 'react';
import {View, StyleSheet, ActivityIndicator} from 'react-native';
import NavigationViewContainer from './navigation/NavigationViewContainer';
import * as snapshotUtil from '../utils/snapshot';
import * as SessionStateActions from '../modules/session/SessionState';
import store from '../redux/store';
import DeveloperMenu from '../components/DeveloperMenu';

const AppView = React.createClass({
  propTypes: {
    isReady: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
  },
  componentDidMount() {
    snapshotUtil.resetSnapshot()
      .then(snapshot => {
        const {dispatch} = this.props;

        if (snapshot) {
          dispatch(SessionStateActions.resetSessionStateFromSnapshot(snapshot));
        } else {
          dispatch(SessionStateActions.initializeSessionState());
        }

        store.subscribe(() => {
          snapshotUtil.saveSnapshot(store.getState());
        });
      });
  },

  render() {
    if (!this.props.isReady) {
      return (
        <View style={{flex: 1}}>
          <ActivityIndicator style={styles.centered}/>
        </View>
      );
    }

    return (
      <View style={{flex: 1}}>
        <NavigationViewContainer />
        {__DEV__ && <DeveloperMenu />}
      </View>
    );
  }
});

const styles = StyleSheet.create({
  centered: {
    flex: 1,
    alignSelf: 'center'
  }
});

export default AppView;
<|endoftext|>


<commit_before>/*
 * Loads the depandancies in order and aggregates exports from various modules
 */

/*
 * Because we are going to attach listeners to these all over the place, have
 * to load soome core modules in specific order. Also avoids nasty circular
 * dependaancy, by placing some of the exports here and not in child modules.
 */
var $ = require('jquery'),
	_ = require('underscore'),
	Backbone = require('backbone');

/*
 * Since the language pack contains functions and we can not simply use those
 * with underscore templates, had to stringify those. Now we convert them back
 * to functions.
 */
exports.lang = window.lang;
['pluralize', 'capitalize', 'ago', 'abbrev_msg'].forEach(function(func) {
	eval('exports.lang[func] = ' + window.lang[func]);
});

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

// Register jquery plugins
require('jquery.cookie');
// Bind jQuery to backbone
Backbone.$ = $;

exports.isMobile = /Android|iP(?:hone|ad|od)|Windows Phone/
	.test(navigator.userAgent);

// Store them here, to avoid requiring modules in the wrong order
exports.send = function() {};
exports.serverTimeOffset = 0;
exports.dispatcher = {};
exports.connSM = new common.FSM('load');
exports.postSM = new common.FSM('none');

// Cached jQuery objects
exports.$doc = $(document);
exports.$threads = $('threads');

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

// Initialise main rendering object
var oneeSama = exports.oneeSama = new common.OneeSama(function(num) {
	// Core post link handler
	var frag;
	if (this.links && num in this.links) {
		var op = this.links[num];
		// FIXME: Threads not done yet
		var model = state.posts.get(num),
			desc = model && model.get('mine') && '(You)';
		frag = this.post_ref(num, op, desc);
	}
	else
		frag = '>>' + num;
	this.callback(frag);
});
oneeSama.full = oneeSama.op = state.page.get('thread');

// The require chain also loads some core dependancies
var Extract = require('./extract');
new Extract();

// Start the client
require('./client');

// Load auxilary modules
require('./history');<commit_msg>Remove done FIXME<commit_after>/*
 * Loads the depandancies in order and aggregates exports from various modules
 */

/*
 * Because we are going to attach listeners to these all over the place, have
 * to load soome core modules in specific order. Also avoids nasty circular
 * dependaancy, by placing some of the exports here and not in child modules.
 */
var $ = require('jquery'),
	_ = require('underscore'),
	Backbone = require('backbone');

/*
 * Since the language pack contains functions and we can not simply use those
 * with underscore templates, had to stringify those. Now we convert them back
 * to functions.
 */
exports.lang = window.lang;
['pluralize', 'capitalize', 'ago', 'abbrev_msg'].forEach(function(func) {
	eval('exports.lang[func] = ' + window.lang[func]);
});

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

// Register jquery plugins
require('jquery.cookie');
// Bind jQuery to backbone
Backbone.$ = $;

exports.isMobile = /Android|iP(?:hone|ad|od)|Windows Phone/
	.test(navigator.userAgent);

// Store them here, to avoid requiring modules in the wrong order
exports.send = function() {};
exports.serverTimeOffset = 0;
exports.dispatcher = {};
exports.connSM = new common.FSM('load');
exports.postSM = new common.FSM('none');
// Read-only boards gets expanded later
exports.readOnly = ['archive'];

// Cached jQuery objects
exports.$doc = $(document);
exports.$threads = $('threads');

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

// Initialise main rendering object
var oneeSama = exports.oneeSama = new common.OneeSama(function(num) {
	// Core post link handler
	var frag;
	if (this.links && num in this.links) {
		var op = this.links[num],
			model = state.posts.get(num),
			desc = model && model.get('mine') && '(You)';
		frag = this.post_ref(num, op, desc);
	}
	else
		frag = '>>' + num;
	this.callback(frag);
});
oneeSama.full = oneeSama.op = state.page.get('thread');

// The require chain also loads some core dependancies
var Extract = require('./extract');
new Extract();

// Start the client
require('./client');

// Load auxilary modules
require('./history');<|endoftext|>


<commit_before>/**
 * Determine if the elements have the specified class
 * @param {string} cls - className
 * @returns {boolean} true or false
 */

	$.fn.hasClass = function(cls) {
		var hasCls;
		this.each(function() {
			hasCls = this.classList.contains(cls);
		});
		return hasCls;
	};

/**
 * Add a class to the current set of elements
 * @param {string} cls - className
 * @returns {object} current instance of Grindstone
 */

	$.fn.addClass = function(cls) {
		this.each(function() {
			if (!$(this).hasClass(cls)) {
				var self = this;
				var classes = cls.split(' ');
				classes.forEach(function(clsName) {
					self.classList.add(clsName);
				});
			}
		});
		return this;
	};

/**
 * Remove a class from the current set of elements
 * @param {string} cls - className
 * @returns {object} current instance of Grindstone
 */

	$.fn.removeClass = function(cls) {
		this.each(function() {
			if ($(this).hasClass(cls)) {
				var self = this;
				var classes = cls.split(' ');
				classes.forEach(function(clsName) {
					self.classList.remove(clsName);
				});
			}
		});
		return this;
	};

/**
 * Toggle the specified class
 * @param {string} cls - className
 * @returns {object} current instance of Grindstone
 */

	$.fn.toggleClass = function(cls) {
		this.each(function() {
			var self = this;
			var classes = cls.split(' ');
			classes.forEach(function(clsName) {
				self.classList.toggle(clsName);
			});
		});
		return this;
	};
<commit_msg>Fix adding and removing multiple classes<commit_after>/**
 * Determine if the elements have the specified class
 * @param {string} cls - className
 * @returns {boolean} true or false
 */

	$.fn.hasClass = function(cls) {
		var hasCls;
		this.each(function() {
			hasCls = this.classList.contains(cls);
		});
		return hasCls;
	};

/**
 * Add a class to the current set of elements
 * @param {string} cls - className
 * @returns {object} current instance of Grindstone
 */

	$.fn.addClass = function(cls) {
		var classes = cls.split(' ');
		this.each(function() {
			var self = this;
			classes.forEach(function(clsName) {
				self.classList.add(clsName);
			});
		});
		return this;
	};

/**
 * Remove a class from the current set of elements
 * @param {string} cls - className
 * @returns {object} current instance of Grindstone
 */

	$.fn.removeClass = function(cls) {
		var classes = cls.split(' ');
		this.each(function() {
			var self = this;
			classes.forEach(function(clsName) {
				self.classList.remove(clsName);
			});
		});
		return this;
	};

/**
 * Toggle the specified class
 * @param {string} cls - className
 * @returns {object} current instance of Grindstone
 */

	$.fn.toggleClass = function(cls) {
		var classes = cls.split(' ');
		this.each(function() {
			var self = this;
			classes.forEach(function(clsName) {
				self.classList.toggle(clsName);
			});
		});
		return this;
	};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016, WikiWeb
*/

import React from "react";
import Loader from 'react-loader';
import { Modal, OverlayTrigger, Popover} from 'react-bootstrap'
import { connect } from 'react-redux'
import { getSearch, resetSearch } from './inputURL/actions'
import _ from 'lodash'

const ENTER_KEY_CODE = 13;

const homepageUrlSearchForm = {
  display: 'block',
  margin: 'auto',
  marginTop: '50px',
  paddingLeft: '20px',
  paddingRight: '20px'
}

const homepageUrlSearchBox = {
  fontSize: '17px',
  outline: 'none',
}

const buttonStyle = {
  padding: 0,
  margin: '12px',
  backgroundColor: 'rgba(255, 255, 255, 0)',
  border: 'none',
  height: 0,
  outline: 'none'
}

class InputURL extends React.Component {

  constructor(){
    super()
    this.state = { searchInput:'' };
    this._onChange = this._onChange.bind(this);
    this._onSubmit = this._onSubmit.bind(this);
    this._onKeyDown = this._onKeyDown.bind(this);
    this._search = this._search.bind(this);
    this._reset = this._reset.bind(this);
    this._submitWithDelay = _.debounce(this._submitWithDelay, 700);
  }

  componentWillMount(nextProps){
    const { setValue, id} = this.props;
    this.uid = id?id:Math.random()*Math.pow(10, 17);
    if (setValue) this._setValue(setValue)
    if (this.props.hasSearchButton) this.urlValidIconStyle = Object.assign(this.urlValidIconStyle,{right:45});
  }

  componentWillReceiveProps(nextProps){
    if (nextProps[this.uid]){
      const { reset } = nextProps[this.uid];
      if (reset) this.setState({searchInput:''})
    }
  }

  makePopover(status, text, title){
   const popover =
      <Popover
        id={this.uid}
        title={title?title:''}>
        {text}
      </Popover>
   return <OverlayTrigger
     trigger="focus"
     placement="top"

     overlay={popover}>
     <button style={buttonStyle} >{status}</button>
   </OverlayTrigger>
  }

  render() {
    const { searchInput } = this.state
    const { dispatch, hasSearchButton, placeholder } = this.props
    const search = this.props[this.uid]
    const statusStyle = {margin: '0'}
    let result = null;
    let node = null;
    let hrefSubmit = "javascript:void(0)";
    let searchDisabled = {};
    let status = null;

    if (search){

      const {isURL, loading, node} = search;

      if (loading) status = (

        <Loader scale={0.55} />

)
      else if (isURL)
        status = this.makePopover(
          ,
          'text',
          'title');
      else if (isURL==false)
        status = this.makePopover(
          ,
          'text',
          'title'),
        searchDisabled = {cursor:'not-allowed'};

      if (node && !node.isConnected)
      hrefSubmit = '/connect?url='+ node.canonicalLink;
      else if (node)
      hrefSubmit = '/node/'+ node._id;

    }
    const searchButton = hasSearchButton?(

    ):null;

    return (

            <input
              onChange={this._onChange}
              onKeyDown={this._onKeyDown}
              value={searchInput}
              type="search"
              placeholder={placeholder}
              className="form-control"
              style={homepageUrlSearchBox} />

              {status}

            {searchButton}

        {result}

    );
  }

  _setValue(setValue){
    this.setState({
      searchInput:setValue
    });
    if (setValue.length>0) this._search(setValue);
  }

  _onChange(e) {
    e.preventDefault()
    this.setState({
      searchInput: e.target.value
    })
    this._submitWithDelay()
  }

  _onKeyDown(e) {
    if (e.keyCode === ENTER_KEY_CODE) {
      this._onSubmit();
    }
  }

  _submitWithDelay(e) {
    this._onSubmit()
  }

  _onSubmit(){
    const {searchInput} = this.state;
    if (searchInput.length > 0){
      this._submitWithDelay.cancel() //cancel the delayed submit.
      this._search(searchInput)
    } else{
      this._reset()
    }
  }

  _search(searchInput) {
    const { dispatch } = this.props;
    if (this.lastSearch !== searchInput){
      this.lastSearch = searchInput;
      dispatch(getSearch(searchInput, this.uid));
    }
  }

  _reset(searchInput) {
    const { dispatch } = this.props;
    dispatch(resetSearch(this.uid));
  }

  urlValidIconStyle = {
    position: 'absolute',
    zIndex: 3,
    right: 0
  }

};

function mapStateToProps(state) {
  const searches = {...state.inputURLResult};
  return searches
}

export default connect(mapStateToProps)(InputURL)
<commit_msg>killing ol file<commit_after><|endoftext|>


<commit_before>(function(T) {
    "use strict";

    function Decoder() {}

    Decoder.prototype.decode = function(src, onloadedmetadata, onloadeddata) {
        if (typeof src === "string") {
            if (/\.wav$/.test(src)) {
                return Decoder.wav_decode(src, onloadedmetadata, onloadeddata);
            } else if (Decoder.ogg_decode && /\.ogg$/.test(src)) {
                return Decoder.ogg_decode(src, onloadedmetadata, onloadeddata);
            } else if (Decoder.mp3_decode && /\.mp3$/.test(src)) {
                return Decoder.mp3_decode(src, onloadedmetadata, onloadeddata);
            }
        }
        if (Decoder.webkit_decode) {
            return Decoder.webkit_decode(src, onloadedmetadata, onloadeddata);
        } else if (Decoder.moz_decode) {
            return Decoder.moz_decode(src, onloadedmetadata, onloadeddata);
        }
        onloadedmetadata(false);
    };
    T.modules.Decoder = Decoder;

    if (T.envtype === "browser") {
        Decoder.getBinaryWithPath = function(path, callback) {
            T.fn.fix_iOS6_1_problem(true);

            var xhr = new XMLHttpRequest();
            xhr.open("GET", path, true);
            xhr.responseType = "arraybuffer";
            xhr.onload = function() {
                if (xhr.status === 200) {
                    if (xhr.response) {
                        callback(new Uint8Array(xhr.response));
                    } else if (xhr.responseBody !== undefined) {
                        var res = VBArray(xhr.responseBody).toArray();
                        var i, imax = res.length;
                        var a = new Array(imax);
                        for (var i = 0; i < imax; ++i) {
                            a[i] = res[i];
                        }
                        callback(new Uint8Array(a));
                    }
                } else {
                    callback(xhr.status + " " + xhr.statusText);
                }
                T.fn.fix_iOS6_1_problem(false);
            };
            xhr.send();
        };
    } else {
        Decoder.getBinaryWithPath = function(path, callback) {
            callback("no support");
        };
    }

    var deinterleave = function(list) {
        var result = new list.constructor(list.length>>1);
        var i, j, jmax = result.length;
        if (list.length % 2) {
            j |= 0;
        }
        for (i = j = 0; j < jmax; ++j, i += 2) {
            result[j] = (list[i] + list[i+1]) * 0.5;
        }
        return result;
    };

    var _24bit_to_32bit = function(uint8) {
        var b0, b1, b2, bb, x;
        var int32 = new Int32Array(uint8.length / 3);
        for (var i = 0, imax = uint8.length, j = 0; i < imax; ) {
            b0 = uint8[i++] ,b1 = uint8[i++], b2 = uint8[i++];
            bb = b0 + (b1 << 8) + (b2 << 16);
            x = (bb & 0x800000) ? -((bb^0xFFFFFF)+1) : bb;
            int32[j++] = x;
        }
        return int32;
    };

    Decoder.wav_decode = function(src, onloadedmetadata, onloadeddata) {
        Decoder.getBinaryWithPath(src, function(data) {
            if (data[0] !== 0x52 || data[1] !== 0x49 ||
                data[2] !== 0x46 || data[3] !== 0x46) { // 'RIFF'
                    // "HeaderError: not exists 'RIFF'"
                    return onloadedmetadata(false);
            }

            var l1 = data[4] + (data[5]<<8) + (data[6]<<16) + (data[7]<<24);
            if (l1 + 8 !== data.length) {
                // "HeaderError: invalid data size"
                return onloadedmetadata(false);
            }

            if (data[ 8] !== 0x57 || data[ 9] !== 0x41 ||
                data[10] !== 0x56 || data[11] !== 0x45) { // 'WAVE'
                    // "HeaderError: not exists 'WAVE'"
                    return onloadedmetadata(false);
            }

            if (data[12] !== 0x66 || data[13] !== 0x6D ||
                data[14] !== 0x74 || data[15] !== 0x20) { // 'fmt '
                    // "HeaderError: not exists 'fmt '"
                    return onloadedmetadata(false);
            }

            // var byteLength = data[16] + (data[17]<<8) + (data[18]<<16) + (data[19]<<24);
            // var linearPCM  = data[20] + (data[21]<<8);
            var channels   = data[22] + (data[23]<<8);
            var samplerate = data[24] + (data[25]<<8) + (data[26]<<16) + (data[27]<<24);
            // var dataSpeed  = data[28] + (data[29]<<8) + (data[30]<<16) + (data[31]<<24);
            // var blockSize  = data[32] + (data[33]<<8);
            var bitSize    = data[34] + (data[35]<<8);

            if (data[36] !== 0x64 || data[37] !== 0x61 ||
                data[38] !== 0x74 || data[39] !== 0x61) { // 'data'
                    // "HeaderError: not exists 'data'"
                    return onloadedmetadata(false);
            }

            var l2 = data[40] + (data[41]<<8) + (data[42]<<16) + (data[43]<<24);
            var duration = ((l2 / channels) >> 1) / samplerate;

            if (l2 > data.length - 44) {
                // "HeaderError: not exists data"
                return onloadedmetadata(false);
            }

            var buffer = new Float32Array((duration * samplerate)|0);

            onloadedmetadata({
                samplerate: samplerate,
                buffer    : buffer,
                duration  : duration
            });

            if (bitSize === 8) {
                data = new Int8Array(data.buffer, 44);
            } else if (bitSize === 16) {
                data = new Int16Array(data.buffer, 44);
            } else if (bitSize === 32) {
                data = new Int32Array(data.buffer, 44);
            } else if (bitSize === 24) {
                data = _24bit_to_32bit(new Uint8Array(data.buffer, 44));
            }

            if (channels === 2) {
                data = deinterleave(data);
            }

            var k = 1 / ((1 << (bitSize-1)) - 1);
            for (var i = 0, imax = buffer.length; i < imax; ++i) {
                buffer[i] = data[i] * k;
            }

            onloadeddata();
        });
    };

    Decoder.webkit_decode = (function() {
        if (typeof webkitAudioContext !== "undefined") {
            var ctx = T.fn._audioContext;
            var _decode = function(data, onloadedmetadata, onloadeddata) {
                var samplerate, duration, buffer;
                if (typeof data === "string") {
                    return onloadeddata(false);
                }

                try {
                    buffer = ctx.createBuffer(data.buffer, true);
                } catch (e) {
                    return onloadedmetadata(false);
                }

                samplerate = ctx.sampleRate;
                buffer     = buffer.getChannelData(0);
                duration   = buffer.length / samplerate;

                onloadedmetadata({
                    samplerate: samplerate,
                    buffer    : buffer,
                    duration  : duration
                });

                onloadeddata();
            };

            return function(src, onloadedmetadata, onloadeddata) {
                /*global File:true */
                if (src instanceof File) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        _decode(new Uint8Array(e.target.result),
                                onloadedmetadata, onloadeddata);
                    };
                    reader.readAsArrayBuffer(src);
                } else {
                    Decoder.getBinaryWithPath(src, function(data) {
                        _decode(data, onloadedmetadata, onloadeddata);
                    });
                }
                /*global File:false */
            };
        }
    })();

    Decoder.moz_decode = (function() {
        if (typeof Audio === "function" && typeof new Audio().mozSetup === "function") {
            return function(src, onloadedmetadata, onloadeddata) {
                var samplerate, duration, buffer;
                var writeIndex = 0;

                var audio = new Audio(src);
                audio.volume = 0.0;
                audio.speed  = 4;
                audio.addEventListener("loadedmetadata", function() {
                    samplerate = audio.mozSampleRate;
                    duration = audio.duration;
                    buffer = new Float32Array((audio.duration * samplerate)|0);
                    if (audio.mozChannels === 2) {
                        audio.addEventListener("MozAudioAvailable", function(e) {
                            var samples = e.frameBuffer;
                            for (var i = 0, imax = samples.length; i < imax; i += 2) {
                                buffer[writeIndex++] = (samples[i] + samples[i+1]) * 0.5;
                            }
                        }, false);
                    } else {
                        audio.addEventListener("MozAudioAvailable", function(e) {
                            var samples = e.frameBuffer;
                            for (var i = 0, imax = samples.length; i < imax; ++i) {
                                buffer[writeIndex++] = samples[i];
                            }
                        }, false);
                    }
                    audio.play();
                    setTimeout(function() {
                        onloadedmetadata({
                            samplerate: samplerate,
                            buffer    : buffer,
                            duration  : duration
                        });
                    }, 1000);
                }, false);
                audio.addEventListener("ended", function() {
                    onloadeddata();
                }, false);
                audio.load();
            };
        }
    })();
})(timbre);
<commit_msg>quite fix<commit_after>(function(T) {
    "use strict";

    function Decoder() {}

    Decoder.prototype.decode = function(src, onloadedmetadata, onloadeddata) {
        if (typeof src === "string") {
            if (/\.wav$/.test(src)) {
                return Decoder.wav_decode(src, onloadedmetadata, onloadeddata);
            } else if (Decoder.ogg_decode && /\.ogg$/.test(src)) {
                return Decoder.ogg_decode(src, onloadedmetadata, onloadeddata);
            } else if (Decoder.mp3_decode && /\.mp3$/.test(src)) {
                return Decoder.mp3_decode(src, onloadedmetadata, onloadeddata);
            }
        }
        if (Decoder.webkit_decode) {
            return Decoder.webkit_decode(src, onloadedmetadata, onloadeddata);
        } else if (Decoder.moz_decode) {
            return Decoder.moz_decode(src, onloadedmetadata, onloadeddata);
        }
        onloadedmetadata(false);
    };
    T.modules.Decoder = Decoder;

    if (T.envtype === "browser") {
        Decoder.getBinaryWithPath = function(path, callback) {
            T.fn.fix_iOS6_1_problem(true);

            var xhr = new XMLHttpRequest();
            xhr.open("GET", path, true);
            xhr.responseType = "arraybuffer";
            xhr.onload = function() {
                if (xhr.status === 200) {
                    if (xhr.response) {
                        callback(new Uint8Array(xhr.response));
                    } else if (xhr.responseBody !== undefined) {
                        /*global VBArray:true */
                        var res = VBArray(xhr.responseBody).toArray();
                        var i, imax = res.length;
                        var a = new Array(imax);
                        for (i = 0; i < imax; ++i) {
                            a[i] = res[i];
                        }
                        callback(new Uint8Array(a));
                        /*global VBArray:false */
                    }
                } else {
                    callback(xhr.status + " " + xhr.statusText);
                }
                T.fn.fix_iOS6_1_problem(false);
            };
            xhr.send();
        };
    } else {
        Decoder.getBinaryWithPath = function(path, callback) {
            callback("no support");
        };
    }

    var deinterleave = function(list) {
        var result = new list.constructor(list.length>>1);
        var i, j, jmax = result.length;
        if (list.length % 2) {
            j |= 0;
        }
        for (i = j = 0; j < jmax; ++j, i += 2) {
            result[j] = (list[i] + list[i+1]) * 0.5;
        }
        return result;
    };

    var _24bit_to_32bit = function(uint8) {
        var b0, b1, b2, bb, x;
        var int32 = new Int32Array(uint8.length / 3);
        for (var i = 0, imax = uint8.length, j = 0; i < imax; ) {
            b0 = uint8[i++] ,b1 = uint8[i++], b2 = uint8[i++];
            bb = b0 + (b1 << 8) + (b2 << 16);
            x = (bb & 0x800000) ? -((bb^0xFFFFFF)+1) : bb;
            int32[j++] = x;
        }
        return int32;
    };

    Decoder.wav_decode = function(src, onloadedmetadata, onloadeddata) {
        Decoder.getBinaryWithPath(src, function(data) {
            if (data[0] !== 0x52 || data[1] !== 0x49 ||
                data[2] !== 0x46 || data[3] !== 0x46) { // 'RIFF'
                    // "HeaderError: not exists 'RIFF'"
                    return onloadedmetadata(false);
            }

            var l1 = data[4] + (data[5]<<8) + (data[6]<<16) + (data[7]<<24);
            if (l1 + 8 !== data.length) {
                // "HeaderError: invalid data size"
                return onloadedmetadata(false);
            }

            if (data[ 8] !== 0x57 || data[ 9] !== 0x41 ||
                data[10] !== 0x56 || data[11] !== 0x45) { // 'WAVE'
                    // "HeaderError: not exists 'WAVE'"
                    return onloadedmetadata(false);
            }

            if (data[12] !== 0x66 || data[13] !== 0x6D ||
                data[14] !== 0x74 || data[15] !== 0x20) { // 'fmt '
                    // "HeaderError: not exists 'fmt '"
                    return onloadedmetadata(false);
            }

            // var byteLength = data[16] + (data[17]<<8) + (data[18]<<16) + (data[19]<<24);
            // var linearPCM  = data[20] + (data[21]<<8);
            var channels   = data[22] + (data[23]<<8);
            var samplerate = data[24] + (data[25]<<8) + (data[26]<<16) + (data[27]<<24);
            // var dataSpeed  = data[28] + (data[29]<<8) + (data[30]<<16) + (data[31]<<24);
            // var blockSize  = data[32] + (data[33]<<8);
            var bitSize    = data[34] + (data[35]<<8);

            if (data[36] !== 0x64 || data[37] !== 0x61 ||
                data[38] !== 0x74 || data[39] !== 0x61) { // 'data'
                    // "HeaderError: not exists 'data'"
                    return onloadedmetadata(false);
            }

            var l2 = data[40] + (data[41]<<8) + (data[42]<<16) + (data[43]<<24);
            var duration = ((l2 / channels) >> 1) / samplerate;

            if (l2 > data.length - 44) {
                // "HeaderError: not exists data"
                return onloadedmetadata(false);
            }

            var buffer = new Float32Array((duration * samplerate)|0);

            onloadedmetadata({
                samplerate: samplerate,
                buffer    : buffer,
                duration  : duration
            });

            if (bitSize === 8) {
                data = new Int8Array(data.buffer, 44);
            } else if (bitSize === 16) {
                data = new Int16Array(data.buffer, 44);
            } else if (bitSize === 32) {
                data = new Int32Array(data.buffer, 44);
            } else if (bitSize === 24) {
                data = _24bit_to_32bit(new Uint8Array(data.buffer, 44));
            }

            if (channels === 2) {
                data = deinterleave(data);
            }

            var k = 1 / ((1 << (bitSize-1)) - 1);
            for (var i = 0, imax = buffer.length; i < imax; ++i) {
                buffer[i] = data[i] * k;
            }

            onloadeddata();
        });
    };

    Decoder.webkit_decode = (function() {
        if (typeof webkitAudioContext !== "undefined") {
            var ctx = T.fn._audioContext;
            var _decode = function(data, onloadedmetadata, onloadeddata) {
                var samplerate, duration, buffer;
                if (typeof data === "string") {
                    return onloadeddata(false);
                }

                try {
                    buffer = ctx.createBuffer(data.buffer, true);
                } catch (e) {
                    return onloadedmetadata(false);
                }

                samplerate = ctx.sampleRate;
                buffer     = buffer.getChannelData(0);
                duration   = buffer.length / samplerate;

                onloadedmetadata({
                    samplerate: samplerate,
                    buffer    : buffer,
                    duration  : duration
                });

                onloadeddata();
            };

            return function(src, onloadedmetadata, onloadeddata) {
                /*global File:true */
                if (src instanceof File) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        _decode(new Uint8Array(e.target.result),
                                onloadedmetadata, onloadeddata);
                    };
                    reader.readAsArrayBuffer(src);
                } else {
                    Decoder.getBinaryWithPath(src, function(data) {
                        _decode(data, onloadedmetadata, onloadeddata);
                    });
                }
                /*global File:false */
            };
        }
    })();

    Decoder.moz_decode = (function() {
        if (typeof Audio === "function" && typeof new Audio().mozSetup === "function") {
            return function(src, onloadedmetadata, onloadeddata) {
                var samplerate, duration, buffer;
                var writeIndex = 0;

                var audio = new Audio(src);
                audio.volume = 0.0;
                audio.speed  = 4;
                audio.addEventListener("loadedmetadata", function() {
                    samplerate = audio.mozSampleRate;
                    duration = audio.duration;
                    buffer = new Float32Array((audio.duration * samplerate)|0);
                    if (audio.mozChannels === 2) {
                        audio.addEventListener("MozAudioAvailable", function(e) {
                            var samples = e.frameBuffer;
                            for (var i = 0, imax = samples.length; i < imax; i += 2) {
                                buffer[writeIndex++] = (samples[i] + samples[i+1]) * 0.5;
                            }
                        }, false);
                    } else {
                        audio.addEventListener("MozAudioAvailable", function(e) {
                            var samples = e.frameBuffer;
                            for (var i = 0, imax = samples.length; i < imax; ++i) {
                                buffer[writeIndex++] = samples[i];
                            }
                        }, false);
                    }
                    audio.play();
                    setTimeout(function() {
                        onloadedmetadata({
                            samplerate: samplerate,
                            buffer    : buffer,
                            duration  : duration
                        });
                    }, 1000);
                }, false);
                audio.addEventListener("ended", function() {
                    onloadeddata();
                }, false);
                audio.load();
            };
        }
    })();
})(timbre);
<|endoftext|>


<commit_before>import Request from 'superagent';
import './../../promises';

/**
 * A helper to make poll an endpoint with a GET request
 *
 * The helper takes the following params
 *
 * - queryOptions:
 * -- url - the url to make the GET request to
 * -- data - any data you wish to pass with the request
 * -- headers - any header you wish to pass with the request
 *
 * - functions: An object containing the custom functions
 * -- conditionMet: Use this to test a desired condition in the response and return a boolean.
 *                  If the condition is true, the callback will be executed.
 * -- conditionNotMetCallback: Called when condition not met and poller will retry
 * -- callback: A callback function to call when the conditionMet returns true
 * -- handleError: a callback function that takes an error and handles it
 * -- terminate: Use this to test a desired condition in the response and return a boolean.
 *               If the condition is true, the polling will end.
 * options:
 * -- interval - the interval after which the request is re-submitted
 * -- retries - number of times to re-submit the request before giving up
 * -- endTime - a time period after which to end the polling
 *
 * ===Example Usage===
 *
 * import Poller from 'carbon/lib/utils/helpers/poller';
 *
 * let queryOptions = {  url: '/foo/bar/1' }
 * let options = { interval: 5000 };
 * let functions = {
 *   conditionMet: function(response) => { return response.body.status === 'complete' };
 *   conditionNotMetCallback: function(response) => { notYetFunction(response) };
 *   callback: function(response) => { doSomethingFancy(reponse) };
 *   handleError: function(err) => { FlashMessage("Failed", err) };
 * }
 *
 * Poller(queryOptions, functions);
 */
export default (queryOptions, functions, options) => {
  if (!setupValid(queryOptions, functions)) {
    return undefined;
  }

  // set default options for unprovided options
  const queryOpts = getQueryOptions(queryOptions);
  const funcs = getFunctions(functions);
  const opts = getOptions(options);

  // pollCount for use if retries option passed
  let pollCount = 1;

  (function poll() {
    const now = Date.now();
    if (pollCount > opts.retries || now > opts.endTime) {
      console.warn('The poller has made too many requests - terminating poll'); // eslint-disable-line no-console
      return;
    }
    Request
      .get(queryOpts.url)
      .query(queryOpts.data)
      .set(queryOpts.headers)
      .end((err, response) => {
        let result;

        if (err) {
          if (funcs.handleError) {
            result = funcs.handleError(err);
          } else {
            result = console.error(err.message); // eslint-disable-line no-console
          }
        } else if (funcs.terminate(response)) {
          result = response;
        } else if (funcs.conditionMet(response)) {
          result = funcs.callback(response);
        } else {
          funcs.conditionNotMetCallback(response);
          pollCount += 1;
          setTimeout(poll, opts.interval);
        }

        return result;
      });
  }());
};

/**
 * Sets default queryOptions
 *
 * @method getQueryOptions
 * @return {Object} queryOptions
 */
function getQueryOptions(queryOptions) {
  return {
    url: queryOptions.url,
    data: queryOptions.data || {},
    headers: queryOptions.headers || {}
  };
}

/**
 * Sets default Options for poller
 *
 * @method getOptions
 * @return {Object} options
 */
function getOptions(options) {
  return {
    interval: options.interval || 3000,
    endTime: Number(new Date()) + options.endTime || Infinity,
    retries: options.retries || Infinity
  };
}

/**
 * Sets default functions for poller
 *
 * @method getFunctions
 * @return {Object} functions
 */
function getFunctions(functions) {
  return {
    callback: functions.callback || null,
    handleError: functions.handleError || null,
    conditionMet: functions.conditionMet || (() => { return false; }),
    conditionNotMetCallback: functions.conditionNotMetCallback || (() => { return false; }),
    terminate: functions.terminate || (() => { return false; })
  };
}

/**
 * Checks that required params are present
 *
 * @method setupValid
 * @return {Boolean}
 */
function setupValid(queryOptions, functions) {
  if (queryOptions === null || typeof queryOptions.url === 'undefined') {
    console.error('You must provide a url to the poller'); // eslint-disable-line no-console
    return false;
  }

  if (typeof functions.conditionMet !== 'undefined' && typeof functions.callback === 'undefined') {
    const msg = 'You must provide a callback function if you are testing a condition with conditionMet';
    console.error(msg); // eslint-disable-line no-console
    return false;
  }
  return true;
}
<commit_msg>Fix consistent-return ESLint rule<commit_after>import Request from 'superagent';
import './../../promises';

/**
 * A helper to make poll an endpoint with a GET request
 *
 * The helper takes the following params
 *
 * - queryOptions:
 * -- url - the url to make the GET request to
 * -- data - any data you wish to pass with the request
 * -- headers - any header you wish to pass with the request
 *
 * - functions: An object containing the custom functions
 * -- conditionMet: Use this to test a desired condition in the response and return a boolean.
 *                  If the condition is true, the callback will be executed.
 * -- conditionNotMetCallback: Called when condition not met and poller will retry
 * -- callback: A callback function to call when the conditionMet returns true
 * -- handleError: a callback function that takes an error and handles it
 * -- terminate: Use this to test a desired condition in the response and return a boolean.
 *               If the condition is true, the polling will end.
 * options:
 * -- interval - the interval after which the request is re-submitted
 * -- retries - number of times to re-submit the request before giving up
 * -- endTime - a time period after which to end the polling
 *
 * ===Example Usage===
 *
 * import Poller from 'carbon/lib/utils/helpers/poller';
 *
 * let queryOptions = {  url: '/foo/bar/1' }
 * let options = { interval: 5000 };
 * let functions = {
 *   conditionMet: function(response) => { return response.body.status === 'complete' };
 *   conditionNotMetCallback: function(response) => { notYetFunction(response) };
 *   callback: function(response) => { doSomethingFancy(reponse) };
 *   handleError: function(err) => { FlashMessage("Failed", err) };
 * }
 *
 * Poller(queryOptions, functions);
 */
export default (queryOptions, functions, options) => {
  if (!setupValid(queryOptions, functions)) {
    return;
  }

  // set default options for unprovided options
  const queryOpts = getQueryOptions(queryOptions);
  const funcs = getFunctions(functions);
  const opts = getOptions(options);

  // pollCount for use if retries option passed
  let pollCount = 1;

  (function poll() {
    const now = Date.now();
    if (pollCount > opts.retries || now > opts.endTime) {
      console.warn('The poller has made too many requests - terminating poll'); // eslint-disable-line no-console
      return;
    }
    Request
      .get(queryOpts.url)
      .query(queryOpts.data)
      .set(queryOpts.headers)
      .end((err, response) => {
        let result;

        if (err) {
          if (funcs.handleError) {
            result = funcs.handleError(err);
          } else {
            result = console.error(err.message); // eslint-disable-line no-console
          }
        } else if (funcs.terminate(response)) {
          result = response;
        } else if (funcs.conditionMet(response)) {
          result = funcs.callback(response);
        } else {
          funcs.conditionNotMetCallback(response);
          pollCount += 1;
          setTimeout(poll, opts.interval);
        }

        return result;
      });
  }());
};

/**
 * Sets default queryOptions
 *
 * @method getQueryOptions
 * @return {Object} queryOptions
 */
function getQueryOptions(queryOptions) {
  return {
    url: queryOptions.url,
    data: queryOptions.data || {},
    headers: queryOptions.headers || {}
  };
}

/**
 * Sets default Options for poller
 *
 * @method getOptions
 * @return {Object} options
 */
function getOptions(options) {
  return {
    interval: options.interval || 3000,
    endTime: Number(new Date()) + options.endTime || Infinity,
    retries: options.retries || Infinity
  };
}

/**
 * Sets default functions for poller
 *
 * @method getFunctions
 * @return {Object} functions
 */
function getFunctions(functions) {
  return {
    callback: functions.callback || null,
    handleError: functions.handleError || null,
    conditionMet: functions.conditionMet || (() => { return false; }),
    conditionNotMetCallback: functions.conditionNotMetCallback || (() => { return false; }),
    terminate: functions.terminate || (() => { return false; })
  };
}

/**
 * Checks that required params are present
 *
 * @method setupValid
 * @return {Boolean}
 */
function setupValid(queryOptions, functions) {
  if (queryOptions === null || typeof queryOptions.url === 'undefined') {
    console.error('You must provide a url to the poller'); // eslint-disable-line no-console
    return false;
  }

  if (typeof functions.conditionMet !== 'undefined' && typeof functions.callback === 'undefined') {
    const msg = 'You must provide a callback function if you are testing a condition with conditionMet';
    console.error(msg); // eslint-disable-line no-console
    return false;
  }
  return true;
}
<|endoftext|>


<commit_before><commit_msg>Add test that shows ordering issue of Suspense inside Fragment<commit_after><|endoftext|>


<commit_before>// NOTE: Do not use any components here,
// as they won't be wrapped in the required providers.
//
// This component also does NOT render on the client-side.

import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'

export default class Page extends PureComponent {
  static propTypes = {
    bundleName: PropTypes.string.isRequired,
    asset: PropTypes.func.isRequired,

    helmet: PropTypes.shape({
      title: PropTypes.shape({
        toComponent: PropTypes.func.isRequired,
      }),
      meta: PropTypes.shape({
        toComponent: PropTypes.func.isRequired,
      }),
      link: PropTypes.shape({
        toComponent: PropTypes.func.isRequired,
      }),
    }).isRequired,
    styles: PropTypes.arrayOf(PropTypes.node).isRequired,
    content: PropTypes.node.isRequired,

    // eslint-disable-next-line react/forbid-prop-types
    state: PropTypes.object.isRequired,

    // eslint-disable-next-line react/forbid-prop-types
    sharifyData: PropTypes.object.isRequired,
  }

  render() {
    const {
      bundleName,
      helmet,
      content,
      state,
      styles,
      asset,
      sharifyData,
    } = this.props

    return (

          {helmet.title.toComponent()}
          {helmet.meta.toComponent()}
          {helmet.link.toComponent()}

          <meta
            name="google-site-verification"
            content="yEDzyeh9dYsQoRw7VJA6X5aVthUCYVTNK6nOUQU1eEE"
          />
          <meta
            name="google-site-verification"
            content="YlzaBIQnBQhN5JFfKeoinJXrTlfdmdtFZ6s8Ez_O8vc"
          />

          <meta
            name="viewport"
            content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0, minimal-ui"
          />
          <meta name="apple-mobile-web-app-capable" content="yes" />
          <meta name="apple-mobile-web-app-status-bar-style" content="black" />

          <link
            rel="apple-touch-icon"
            href={`${sharifyData.IMAGE_PATH}touch-icon-iphone.png`}
          />
          <link
            rel="apple-touch-icon"
            sizes="76x76"
            href={`${sharifyData.IMAGE_PATH}touch-icon-ipad.png`}
          />
          <link
            rel="apple-touch-icon"
            sizes="120x120"
            href={`${sharifyData.IMAGE_PATH}touch-icon-iphone-retina.png`}
          />
          <link
            rel="apple-touch-icon"
            sizes="152x152"
            href={`${sharifyData.IMAGE_PATH}touch-icon-ipad-retina.png`}
          />

          <meta name="apple-itunes-app" content="app-id=1299153149" />
          <link
            rel="mask-icon"
            href={`${sharifyData.IMAGE_PATH}arena-mark.svg`}
            color="black"
          />

          <meta name="twitter:site" content="@aredotna" />

          {sharifyData.USE_CSP && (
            <meta
              httpEquiv="Content-Security-Policy"
              content={`default-src 'self' *.are.na instant.page/1.2.2 arena-avatars.s3.amazonaws.com gravatar.com https://d2hp0ptr16qg89.cloudfront.net https://d2w9rnfcy7mm78.cloudfront.net https://www.google-analytics.com d62qkf7fve5zu.cloudfront.net arena-api-staging.herokuapp.com ${
                sharifyData.CSP_SRCS
              }
              'unsafe-inline'; frame-src *;`}
            />
          )}

          {styles}


<commit_before>var listViewModule = require("ui/list-view");
module.exports = {

	process : function(c) {
		c.comp = new listViewModule.ListView();
		c.comp.src = c.src;
	}
}<commit_msg>init listview<commit_after>var listViewModule = require("ui/list-view");
module.exports = {

	process : function(c) {
		c.comp = new listViewModule.ListView();
		var listView = c.comp;
		listView.items = cat.list;
		listView.on(listViewModule.ListView.itemLoadingEvent, function (args1) {
			if (!args1.view) {
				// Create label if it is not already created.
				args1.view = new labelModule.Label();
				args1.view.height = 44;
			}
			args1.view.cat = cat.list[args1.index];
			args1.view.text = cat.list[args1.index].title;

		});
	}
}<|endoftext|>


<commit_before>var hyphenMatcher = /-([a-z])/gi;

function toUpperCase(match, char, index, str) {
  return char.toUpperCase();
}

export class NameExpression {
  constructor(attribute){
    this.attribute = attribute;
    this.property = attribute.replace(hyphenMatcher, toUpperCase);
    this.discrete = true;
  }

  createBinding(target){
    return new NameBinder(this.property, target);
  }
}

class NameBinder {
  constructor(property, target){
    this.property = property;
    this.target = target.primaryBehavior ? target.primaryBehavior.executionContext : target;
  }

  bind(source){
    if(this.source){
      if(this.source === source){
        return;
      }

      this.unbind();
    }

    this.source = source;
    source[this.property] = this.target;
  }

  unbind(){
    this.source[this.property] = null;
  }
}<commit_msg>feat(name-expression): support explicit ref binding modes<commit_after>var hyphenMatcher = /-([a-z])/gi;

function toUpperCase(match, char, index, str) {
  return char.toUpperCase();
}

export class NameExpression {
  constructor(attribute, value){
    this.attribute = attribute;
    this.property = attribute.replace(hyphenMatcher, toUpperCase);
    this.discrete = true;
    this.mode = (value || 'model').toLowerCase();
  }

  createBinding(target){
    return new NameBinder(this.property, target, this.mode);
  }
}

class NameBinder {
  constructor(property, target, mode){
    this.property = property;

    switch(mode){
      case 'model':
        this.target = target.primaryBehavior ? target.primaryBehavior.executionContext : target;
        break;
      case 'element':
        this.target = target;
        break;
      default:
        throw new Error('Name expressions do not support mode: ' + mode);
    }
  }

  bind(source){
    if(this.source){
      if(this.source === source){
        return;
      }

      this.unbind();
    }

    this.source = source;
    source[this.property] = this.target;
  }

  unbind(){
    this.source[this.property] = null;
  }
}<|endoftext|>