<commit_before>import React, { PropTypes } from 'react';

import { connect } from 'react-redux';

import moment from 'moment';

import Agenda from '../../components/03-organisms/Agenda';
import Calendar from '../../components/01-atoms/Calendar';
import Messages from '../../components/02-molecules/Messages';
import ReservationList from '../../components/02-molecules/ReservationList';

import MeetingCancel from '../../components/02-molecules/MeetingCancel';
import MeetingForm from '../MeetingForm';

import styles from './styles.scss';

import isMeetingOnDate from '../../utils/isMeetingOnDate';

import {
  meetingsFetchStart,
  populateMeetingCreateForm,
  populateMeetingEditForm,
  logout,
 } from '../../actions';

export class DashboardContainer extends React.Component {
  componentDidMount() {
    // This fetches meetings. It should happen whenever `selectedDate` is updated.
    this.props.requestRooms();
  }

  leftPaneContent() {
    if (this.props.isEditingMeeting) { return <MeetingForm />; }
    if (this.props.isCreatingMeeting) { return <MeetingForm />; }
    if (this.props.isCancellingMeeting) { return (<MeetingCancel />); }
    return (<Calendar selectedDate={this.props.selectedDate} />);
  }

  render() {
    const {
      messages,
      user,
      agenda,
    } = this.props;

    return (

            { this.leftPaneContent() }
            <Messages messages={messages} />
            <ReservationList
              roomMeetings={agenda}
              handleEditClick={this.props.populateMeetingEditForm}
            />

            Hello

              { user.name }!

            Log Out

          <Agenda
            agenda={agenda}
            populateMeetingCreateForm={this.props.populateMeetingCreateForm}
          />

    );
  }
}

DashboardContainer.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string.isRequired,
  }),
  agenda: PropTypes.arrayOf(PropTypes.object),
  isEditingMeeting: PropTypes.bool,
  isCreatingMeeting: PropTypes.bool.isRequired,
  isCancellingMeeting: PropTypes.bool,
  selectedDate: PropTypes.shape({}).isRequired,
  messages: PropTypes.arrayOf(PropTypes.string),
  requestRooms: PropTypes.func,
  populateMeetingCreateForm: PropTypes.func.isRequired,
  populateMeetingEditForm: PropTypes.func.isRequired,
  logout: PropTypes.func.isRequired,
};

const mapMeeting = (room, user, date, requestedMeeting) => {
  const meetings = room.meetings
  .filter(meeting => isMeetingOnDate(meeting, date))
  .map(meeting => {
    const start = moment(meeting.start);
    const end = moment(meeting.end);
    const duration = end.diff(start, 'minutes') / 60;

    return {
      id: meeting.id,
      start,
      end,
      duration,
      participants: meeting.participants,
      owner: meeting.owner,
      title: meeting.title,
      room: room.room,
      // TODO: Change this to reflect actual meeting ownership
      // See commented line below
      isOwnedByUser: meeting.owner.name === 'Comes from the session!!!',
      // isOwnedByUser: meeting.owner && (user.email === meeting.owner.email),
      isSelected: requestedMeeting && meeting.id === requestedMeeting.id,
    };
  });

  return {
    room: room.room,
    meetings,
  };
};

const mapStateToProps = state => ({
  user: state.user,
  agenda: state.app.meetings.map(room => mapMeeting(room, state.user, state.app.selectedDate)),
  rooms: state.app.meetings.map(rm => mapMeeting(rm, state.user, state.app.selectedDate, state.app.requestedMeeting)),
  isCreatingMeeting: state.app.isCreatingMeeting,
  isEditingMeeting: state.app.isEditingMeeting,
  isCancellingMeeting: state.app.isCancellingMeeting,
  meetingEditForm: state.app.meetingEditForm,
  messages: state.app.messages,
  selectedDate: state.app.selectedDate,
  requestedMeeting: state.app.requestedMeeting,
});

const mapDispatchToProps = dispatch => ({
  requestRooms: () => {
    // Why does `requestRooms` fetch Meetings?
    // TODO: Fetch meetings for selectedDate.
    dispatch(meetingsFetchStart());
  },
  populateMeetingCreateForm: (room, meeting) => {
    dispatch(populateMeetingCreateForm(room, meeting));
  },
  populateMeetingEditForm: meeting => {
    dispatch(populateMeetingEditForm(meeting));
  },
  logout: () => {
    dispatch(logout());
  },
});

const connected = connect(
  mapStateToProps,
  mapDispatchToProps,
)(DashboardContainer);

export default connected;
<commit_msg>fixed line length lint error<commit_after>import React, { PropTypes } from 'react';

import { connect } from 'react-redux';

import moment from 'moment';

import Agenda from '../../components/03-organisms/Agenda';
import Calendar from '../../components/01-atoms/Calendar';
import Messages from '../../components/02-molecules/Messages';
import ReservationList from '../../components/02-molecules/ReservationList';

import MeetingCancel from '../../components/02-molecules/MeetingCancel';
import MeetingForm from '../MeetingForm';

import styles from './styles.scss';

import isMeetingOnDate from '../../utils/isMeetingOnDate';

import {
  meetingsFetchStart,
  populateMeetingCreateForm,
  populateMeetingEditForm,
  logout,
 } from '../../actions';

export class DashboardContainer extends React.Component {
  componentDidMount() {
    // This fetches meetings. It should happen whenever `selectedDate` is updated.
    this.props.requestRooms();
  }

  leftPaneContent() {
    if (this.props.isEditingMeeting) { return <MeetingForm />; }
    if (this.props.isCreatingMeeting) { return <MeetingForm />; }
    if (this.props.isCancellingMeeting) { return (<MeetingCancel />); }
    return (<Calendar selectedDate={this.props.selectedDate} />);
  }

  render() {
    const {
      messages,
      user,
      agenda,
    } = this.props;

    return (

            { this.leftPaneContent() }
            <Messages messages={messages} />
            <ReservationList
              roomMeetings={agenda}
              handleEditClick={this.props.populateMeetingEditForm}
            />

            Hello

              { user.name }!

            Log Out

          <Agenda
            agenda={agenda}
            populateMeetingCreateForm={this.props.populateMeetingCreateForm}
          />

    );
  }
}

DashboardContainer.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string.isRequired,
  }),
  agenda: PropTypes.arrayOf(PropTypes.object),
  isEditingMeeting: PropTypes.bool,
  isCreatingMeeting: PropTypes.bool.isRequired,
  isCancellingMeeting: PropTypes.bool,
  selectedDate: PropTypes.shape({}).isRequired,
  messages: PropTypes.arrayOf(PropTypes.string),
  requestRooms: PropTypes.func,
  populateMeetingCreateForm: PropTypes.func.isRequired,
  populateMeetingEditForm: PropTypes.func.isRequired,
  logout: PropTypes.func.isRequired,
};

const mapMeeting = (room, user, date, requestedMeeting) => {
  const meetings = room.meetings
  .filter(meeting => isMeetingOnDate(meeting, date))
  .map(meeting => {
    const start = moment(meeting.start);
    const end = moment(meeting.end);
    const duration = end.diff(start, 'minutes') / 60;

    return {
      id: meeting.id,
      start,
      end,
      duration,
      participants: meeting.participants,
      owner: meeting.owner,
      title: meeting.title,
      room: room.room,
      // TODO: Change this to reflect actual meeting ownership
      // See commented line below
      isOwnedByUser: meeting.owner.name === 'Comes from the session!!!',
      // isOwnedByUser: meeting.owner && (user.email === meeting.owner.email),
      isSelected: requestedMeeting && meeting.id === requestedMeeting.id,
    };
  });

  return {
    room: room.room,
    meetings,
  };
};

const mapStateToProps = state => ({
  user: state.user,
  agenda: state.app.meetings.map(room => mapMeeting(room, state.user, state.app.selectedDate)),
  rooms: state.app.meetings.map(
    rm => mapMeeting(rm, state.user, state.app.selectedDate, state.app.requestedMeeting)
  ),
  isCreatingMeeting: state.app.isCreatingMeeting,
  isEditingMeeting: state.app.isEditingMeeting,
  isCancellingMeeting: state.app.isCancellingMeeting,
  meetingEditForm: state.app.meetingEditForm,
  messages: state.app.messages,
  selectedDate: state.app.selectedDate,
  requestedMeeting: state.app.requestedMeeting,
});

const mapDispatchToProps = dispatch => ({
  requestRooms: () => {
    // Why does `requestRooms` fetch Meetings?
    // TODO: Fetch meetings for selectedDate.
    dispatch(meetingsFetchStart());
  },
  populateMeetingCreateForm: (room, meeting) => {
    dispatch(populateMeetingCreateForm(room, meeting));
  },
  populateMeetingEditForm: meeting => {
    dispatch(populateMeetingEditForm(meeting));
  },
  logout: () => {
    dispatch(logout());
  },
});

const connected = connect(
  mapStateToProps,
  mapDispatchToProps,
)(DashboardContainer);

export default connected;
<|endoftext|>


<commit_before>
"use strict";

import {Component} from '../classes/Component';

let params;
let route;
let modal;

class ListController {

    constructor($route, $modal) {
        if ($route.current && $route.current.locals) {
            for (let p in $route.current.locals) {
                if (p.substring(0, 1) == '$') {
                    continue;
                }
                this[p] = $route.current.locals[p];
            }
        }
        this.$new = new this.Manager.model();
        this.items = [];
        params = $route.current.params;
        modal = $modal;
        route = $route;
        this.page = params.page || 1;
        let module = Component.get(this.module);
        this.path = module.paths.update;
        this.create = language => module.paths.update.replace(/:language/, language).replace(/:id/, 'create');
    }

    reload() {
        route.reload();
    }

    get page() {
        return this._page;
    }

    set page(page) {
        this._page = page;
        while (this.items.length) {
            this.items.pop();
        }
        this.Manager.list(params, {offset: (page - 1) * 10}).success(items => items.map(item => this.items.push(item)));
    };

    /**
     * Method allowing item deletion directly from a list:
     */
    ['delete'](item) {
        let modalInstance = modal.open({
            template: `

{{'monad.delete.title' | translate}}

    {{'monad.delete.body' | translate}}

    <button class="btn btn-primary" ng-click="ok()">{{'monad.delete.ok' | translate}}</button>
    <button class="btn btn-warning" ng-click="cancel()">{{'monad.delete.cancel' | translate}}</button>

`,
            controller: ['$scope', '$modalInstance', ($scope, $modalInstance) => {
                $scope.ok = () => {
                    this.Manager['delete'](item);
                    $modalInstance.close(item);
                    route.reload();
                };
                $scope.cancel = () => {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });
    }

};

ListController.$inject = ['$route', '$modal'];

export {ListController};

<commit_msg>this can go now<commit_after>
"use strict";

import {Component} from '../classes/Component';

let params;
let route;
let modal;

class ListController {

    constructor($route, $modal) {
        if ($route.current && $route.current.locals) {
            for (let p in $route.current.locals) {
                if (p.substring(0, 1) == '$') {
                    continue;
                }
                this[p] = $route.current.locals[p];
            }
        }
        this.$new = new this.Manager.model();
        this.items = [];
        params = $route.current.params;
        modal = $modal;
        route = $route;
        this.page = params.page || 1;
        let module = Component.get(this.module);
        this.path = module.paths.update;
        this.create = language => module.paths.update.replace(/:language/, language).replace(/:id/, 'create');
    }

    get page() {
        return this._page;
    }

    set page(page) {
        this._page = page;
        while (this.items.length) {
            this.items.pop();
        }
        this.Manager.list(params, {offset: (page - 1) * 10}).success(items => items.map(item => this.items.push(item)));
    };

    /**
     * Method allowing item deletion directly from a list:
     */
    ['delete'](item) {
        let modalInstance = modal.open({
            template: `

{{'monad.delete.title' | translate}}

    {{'monad.delete.body' | translate}}

    <button class="btn btn-primary" ng-click="ok()">{{'monad.delete.ok' | translate}}</button>
    <button class="btn btn-warning" ng-click="cancel()">{{'monad.delete.cancel' | translate}}</button>

`,
            controller: ['$scope', '$modalInstance', ($scope, $modalInstance) => {
                $scope.ok = () => {
                    this.Manager['delete'](item);
                    $modalInstance.close(item);
                    route.reset();
                    route.reload();
                };
                $scope.cancel = () => {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });
    }

};

ListController.$inject = ['$route', '$modal'];

export {ListController};

<|endoftext|>


<commit_before>const Joi = require('joi');
const config = require('../config/config');
const Boom = require('boom');
const validations = require('../config/validations');
const crypto = require('crypto');
const mongoose = require('mongoose');
var ObjectId = require('mongoose').Types.ObjectId;

exports.register = function (server, options, next) {

    server.log(['info'], 'Loading user controller');

    const User = server.plugins['db'].models.User;
    const Interest = server.plugins['db'].models.Interest;
    const ParticipantRequest = server.plugins['db'].models.ParticipantRequest;

    const changeAbleUserAttributes = [
        'name',
        'surname',
        'email',
        'phone_number',
        'is_private',
        'bio'
    ];

    const getUsers = function(request, reply) {
        server.log(['info'], 'getting all users');

        console.log(User);

        User.find(function (err, users) {
            if (!err) {
                reply(users);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user',
        config: {
            auth: false,
            handler: getUsers,
            description: 'Get all users',
            notes: 'Returns all users',
            tags: ['api', 'user']
        }
    });

    const getProfile = function(request, reply) {

        let userId =request.auth.credentials.id;

        User.findOne({
            _id : userId
        }, function(err, user) {
            if (!err) {
                reply(user);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user/profile',
        config: {
            handler: getProfile,
            description: 'get user profile',
            notes: 'get current user\'s profile info',
            tags: ['api', 'profile', 'user']
        }
    });

    const getUser = function(request, reply) {

        let userId = request.params.id;

        User.findOne({
            _id : userId
        }, function(err, user) {
            if (!err) {
                reply(user);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user/{id}',
        config: {
            auth: false,
            handler: getUser,
            description: 'Get user info by id',
            notes: 'Returns user by id.',
            tags: ['api', 'user'],
            validate: {
                params: {
                    id : validations.slug.description('user id')
                }
            }
        }
    });

    const getInterests = function(request, reply) {

        let userId = request.params.id;

        Interest.find({
            user : new ObjectId(userId),
            status: true
        }, function(err, interests) {
            if (!err) {
                reply(interests);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user/{id}/interest',
        config: {
            auth: false,
            handler: getInterests,
            description: 'Get user interests by id',
            notes: 'Returns user interests by id.',
            tags: ['api', 'user'],
            validate: {
                params: {
                    id : validations.slug.description('user id')
                }
            }
        }
    });

    const pendingRequests = function(request, reply) {

        ParticipantRequest.find({
            owner: new ObjectId(request.params.id),
            status: 'pending'
        })
            .populate('user')
            .populate('interest')
            .exec(function(err, result) {
                if (err)
                    return reply(Boom.badImplementation(err));

                reply(result);
            })

    };

    server.route({
        method: ['GET'],
        path: '/user/{id}/requests',
        config: {
            auth: false,
            handler: pendingRequests,
            description: 'Returns pending requests',
            notes: 'Returns pending requests',
            tags: ['api', 'user'],
            validate: {
                params: {
                    id : validations.slug.description('user id')
                }
            }
        }
    });

    server.log(['info'], 'User controller loaded');
    next(); //IMPORTANT
};

exports.register.attributes = {
    name: 'UserController'
};
<commit_msg>event past & future<commit_after>const Joi = require('joi');
const config = require('../config/config');
const Boom = require('boom');
const validations = require('../config/validations');
const crypto = require('crypto');
const mongoose = require('mongoose');
var ObjectId = require('mongoose').Types.ObjectId;

exports.register = function (server, options, next) {

    server.log(['info'], 'Loading user controller');

    const User = server.plugins['db'].models.User;
    const Interest = server.plugins['db'].models.Interest;
    const ParticipantRequest = server.plugins['db'].models.ParticipantRequest;

    const changeAbleUserAttributes = [
        'name',
        'surname',
        'email',
        'phone_number',
        'is_private',
        'bio'
    ];

    const getUsers = function(request, reply) {
        server.log(['info'], 'getting all users');

        console.log(User);

        User.find(function (err, users) {
            if (!err) {
                reply(users);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user',
        config: {
            auth: false,
            handler: getUsers,
            description: 'Get all users',
            notes: 'Returns all users',
            tags: ['api', 'user']
        }
    });

    const getProfile = function(request, reply) {

        let userId =request.auth.credentials.id;

        User.findOne({
            _id : userId
        }, function(err, user) {
            if (!err) {
                reply(user);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user/profile',
        config: {
            handler: getProfile,
            description: 'get user profile',
            notes: 'get current user\'s profile info',
            tags: ['api', 'profile', 'user']
        }
    });

    const getUser = function(request, reply) {

        let userId = request.params.id;

        User.findOne({
            _id : userId
        }, function(err, user) {
            if (!err) {
                reply(user);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user/{id}',
        config: {
            auth: false,
            handler: getUser,
            description: 'Get user info by id',
            notes: 'Returns user by id.',
            tags: ['api', 'user'],
            validate: {
                params: {
                    id : validations.slug.description('user id')
                }
            }
        }
    });

    const getInterests = function(request, reply) {

        let userId = request.params.id;

        let query = {
            user : new ObjectId(userId),
            status: true
        };

        if(request.query.type==='past') {
            query.endDate = {
                $lte: new Date()
            };
        }
        else if(request.query.type==='future') {
            query.startDate = {
                $gt: new Date()
            };
        }

        Interest.find(query, function(err, interests) {
            if (!err) {
                reply(interests);
            } else {
                reply(Boom.badImplementation(err)); // 500 error
            }
        });
    };

    server.route({
        method: ['GET'],
        path: '/user/{id}/interest',
        config: {
            auth: false,
            handler: getInterests,
            description: 'Get user interests',
            notes: 'Returns user interests',
            tags: ['api', 'user'],
            validate: {
                params: {
                    id : validations.slug.description('user id')
                },
                query: {
                    type: Joi.any().valid(['past', 'future']).optional().description('type')
                }
            }
        }
    });

    const pendingRequests = function(request, reply) {

        ParticipantRequest.find({
            owner: new ObjectId(request.params.id),
            status: 'pending'
        })
            .populate('user')
            .populate('interest')
            .exec(function(err, result) {
                if (err)
                    return reply(Boom.badImplementation(err));

                reply(result);
            })

    };

    server.route({
        method: ['GET'],
        path: '/user/{id}/requests',
        config: {
            auth: false,
            handler: pendingRequests,
            description: 'Returns pending requests',
            notes: 'Returns pending requests',
            tags: ['api', 'user'],
            validate: {
                params: {
                    id : validations.slug.description('user id')
                }
            }
        }
    });

    server.log(['info'], 'User controller loaded');
    next(); //IMPORTANT
};

exports.register.attributes = {
    name: 'UserController'
};
<|endoftext|>


<commit_before>var _ = require('lodash')
var moment = require('moment')

var natural = require('natural')
wordTokenizer = new natural.WordTokenizer();

var Subscriber = require('../../models/subscriber.model')

var weather = require('../weather')

exports.tokenizeIncomingMessage = function(messageBody) {
  // tokenize the message
  return wordTokenizer.tokenize(messageBody)
}

exports.craftResponseMessage = function (subscriber, tokenArray) {

  var responseMessage

  weather.currentWeather(subscriber.settings.fromZip, subscriber.settings.fromCountry)
    .then(function (weatherResponse) {
      return weatherResponse
    })

  // return responseMessage
}

exports.updateUserSettings = function(requestBody){

  var newSettings = {}

  // check each word token for a valid setting value and set it
  var tokenArray = wordTokenizer.tokenize(requestBody.Body)
  tokenArray.forEach(function (token) {
    if (zipcodeTest(token)){
      newSettings.zipCode = token;
    } else if (metricUnitTest(token) || imperialUnitTest(token)){
      newSettings.units = normalizeUnits(token) || newSettings.units;
    } else if (reminderTimeTest(token)){
      newSettings.reminderTime = token;
    }
  })

  // update subscriber
  return Subscriber.findOneAndUpdate(
    {phoneNumber: requestBody.From},
    {$set: {settings: newSettings}},
    {upsert: true, new: true}
  )

}

function zipcodeTest(token) {
  return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(token);
}

function metricUnitTest(token) {
  return /(C)|(Celsius)|(metric)/.test(token);
}

function imperialUnitTest(token) {
  return /(F)|(Fahrenheit)|(imperial)/.test(token);
}

function reminderTimeTest(token) {

  var validTimeFormats = ["LT","h:mm:ss A","HH:mm:ss","HH:mm"];

  return moment("2014-12-13 12:34 PM", validTimeFormats, true).isValid()
}

function normalizeUnits(token) {

  if (imperialUnitTest(token)){
    return 'imperial'
  } else if(metricUnitTest(token)){
    return 'metric'
  }

  // default
  return null
}

<commit_msg>return weather promise<commit_after>var _ = require('lodash')
var moment = require('moment')

var natural = require('natural')
wordTokenizer = new natural.WordTokenizer();

var Subscriber = require('../../models/subscriber.model')

var weather = require('../weather')

exports.tokenizeIncomingMessage = function(messageBody) {
  // tokenize the message
  return wordTokenizer.tokenize(messageBody)
}

exports.craftResponseMessage = function (subscriber, tokenArray) {

  var responseMessage

  return weather.currentWeather(subscriber.settings.fromZip, subscriber.settings.fromCountry)
    .then(function (weatherResponse) {
      return weatherResponse
    })

  // return responseMessage
}

exports.updateUserSettings = function(requestBody){

  var newSettings = {}

  // check each word token for a valid setting value and set it
  var tokenArray = wordTokenizer.tokenize(requestBody.Body)
  tokenArray.forEach(function (token) {
    if (zipcodeTest(token)){
      newSettings.zipCode = token;
    } else if (metricUnitTest(token) || imperialUnitTest(token)){
      newSettings.units = normalizeUnits(token) || newSettings.units;
    } else if (reminderTimeTest(token)){
      newSettings.reminderTime = token;
    }
  })

  // update subscriber
  return Subscriber.findOneAndUpdate(
    {phoneNumber: requestBody.From},
    {$set: {settings: newSettings}},
    {upsert: true, new: true}
  )

}

function zipcodeTest(token) {
  return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(token);
}

function metricUnitTest(token) {
  return /(C)|(Celsius)|(metric)/.test(token);
}

function imperialUnitTest(token) {
  return /(F)|(Fahrenheit)|(imperial)/.test(token);
}

function reminderTimeTest(token) {

  var validTimeFormats = ["LT","h:mm:ss A","HH:mm:ss","HH:mm"];

  return moment("2014-12-13 12:34 PM", validTimeFormats, true).isValid()
}

function normalizeUnits(token) {

  if (imperialUnitTest(token)){
    return 'imperial'
  } else if(metricUnitTest(token)){
    return 'metric'
  }

  // default
  return null
}

<|endoftext|>


<commit_before>/**
 * Created by fabiolombardi on 14/05/15.
 */
/**
 * Module dependencies.
 */
var mongoose = require('mongoose');

var Intervention = require('../models/intervention');
var _ = require('lodash');

var getQuery = function(req) {
    var query = {};
    if (req.query._company_id) {
        query._company_id = req.query._company_id;
    }
    if (req.query._specialist_id){
        query._specialist_id = req.query._specialist_id;
    }
    if (req.query.status){
        query.status = req.query.status;
    }
    /*if(req.query.firstName){
        query.patient = {
            'firstName' : req.query.firstName
        };
    }
    if(req.query.lastName){
        query.patient.lastName = req.query.lastName;
    }*/
    return query;
}

var getAll = function(req, res) {
    console.log(getQuery(req));
    Intervention.find(getQuery(req), function (err, interventions) {
        if (err)
            res.send(err);
        res.json(interventions);
    });
}

/**
 * List of interventions
 */
exports.all = function(req, res) {
    getAll(req,res);
};

/**
 * Create an new intervention
 */
exports.create = function(req, res) {
    var intervention = new Intervention(req.body);
    //from mean template article.user = req.user;

    intervention.save(function(err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot save the intervention:ß ' + err
            });
        }
        //res.json(article);
        getAll(req, res);
    });
};

/**
 * Find intervention by id
 */
exports.intervention = function(req, res, next, id) {
    Intervention.findById(id, function(err, intervention) {
        if (err) return next(err);
        if (!intervention) return next(new Error('Failed to load the intervention ' + id));
        req.intervention = intervention;
        next();
    });
};

/**
 * Show a single intervention
 */
exports.show = function(req, res) {
    res.json(req.intervention);
};

/**
 * Update a intervention
 */
exports.update = function(req, res) {
    var intervention = req.intervention;

    intervention = _.extend(intervention, req.body);

    intervention.save(function(err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot update the intervention: ' + err
            });
        }
        //res.json(article);
        getAll(req, res);
    });
};

/**
 * Delete a intervention
 */
exports.destroy = function(req, res) {
    var intervention = req.intervention;
    intervention.remove(function(err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot delete the intervention ' + err
            });
        }
        //res.json(article);
        getAll(req, res);
    });
};<commit_msg>Add interventions filter on day<commit_after>/**
 * Created by fabiolombardi on 14/05/15.
 */
/**
 * Module dependencies.
 */
var mongoose = require('mongoose');

var Intervention = require('../models/intervention');
var _ = require('lodash');

var getQuery = function(req) {
    var query = {};
    // filter by company_id
    if (req.query._company_id) {
        query._company_id = req.query._company_id;
    }
    // filter by specialist_id
    if (req.query._specialist_id){
        query._specialist_id = req.query._specialist_id;
    }
    // filter by status
    if (req.query.status){
        query.status = req.query.status;
    }
    //filter by date
    if (req.query.day){
        query.day = req.query.day;
    }
    /*if(req.query.firstName){
        query.patient = {
            'firstName' : req.query.firstName
        };
    }
    if(req.query.lastName){
        query.patient.lastName = req.query.lastName;
    }*/
    return query;
}

var getAll = function(req, res) {
    console.log(getQuery(req));
    Intervention.find(getQuery(req), function (err, interventions) {
        if (err)
            res.send(err);
        res.json(interventions);
    });
}

/**
 * List of interventions
 */
exports.all = function(req, res) {
    getAll(req,res);
};

/**
 * Create an new intervention
 */
exports.create = function(req, res) {
    var intervention = new Intervention(req.body);
    //from mean template article.user = req.user;

    intervention.save(function(err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot save the intervention:ß ' + err
            });
        }
        //res.json(article);
        getAll(req, res);
    });
};

/**
 * Find intervention by id
 */
exports.intervention = function(req, res, next, id) {
    Intervention.findById(id, function(err, intervention) {
        if (err) return next(err);
        if (!intervention) return next(new Error('Failed to load the intervention ' + id));
        req.intervention = intervention;
        next();
    });
};

/**
 * Show a single intervention
 */
exports.show = function(req, res) {
    res.json(req.intervention);
};

/**
 * Update a intervention
 */
exports.update = function(req, res) {
    var intervention = req.intervention;

    intervention = _.extend(intervention, req.body);

    intervention.save(function(err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot update the intervention: ' + err
            });
        }
        //res.json(article);
        getAll(req, res);
    });
};

/**
 * Delete a intervention
 */
exports.destroy = function(req, res) {
    var intervention = req.intervention;
    intervention.remove(function(err) {
        if (err) {
            return res.status(500).json({
                error: 'Cannot delete the intervention ' + err
            });
        }
        //res.json(article);
        getAll(req, res);
    });
};<|endoftext|>


<commit_before>const BaseAbility = require('./baseability.js');
const Costs = require('./costs.js');

class PlayAttachmentAction extends BaseAbility {
    constructor() {
        super({
            cost: [
                Costs.payReduceableFateCost('play'),
                Costs.playLimited()
            ]
        });
        this.title = 'PlayAttachmentAction';
        this.targets = {
            target: {
                cardCondition: this.cardCondition
            }
        };
    }

    cardCondition(card, context) {
        return context.source.owner.canAttach(context.source, card);
    }

    meetsRequirements(context) {
        return (
            context.game.currentPhase !== 'dynasty' &&
            context.source.getType() === 'attachment' &&
            context.source.location === 'hand' &&
            context.source.canPlay()
        );
    }

    executeHandler(context) {
        let targetPlayer = context.target.controller;
        targetPlayer.attach(context.player, context.source, context.target, 'play');
    }

    isCardAbility() {
        return false;
    }
}

module.exports = PlayAttachmentAction;

<commit_msg>attachment targeting fix<commit_after>const BaseAbility = require('./baseability.js');
const Costs = require('./costs.js');

class PlayAttachmentAction extends BaseAbility {
    constructor() {
        super({
            cost: [
                Costs.payReduceableFateCost('play'),
                Costs.playLimited()
            ],
            target: {
                cardCondition: (card, context) => context.source.owner.canAttach(context.source, card)
            }
        });
        this.title = 'PlayAttachmentAction';
    }

    meetsRequirements(context) {
        return (
            context.game.currentPhase !== 'dynasty' &&
            context.source.getType() === 'attachment' &&
            context.source.location === 'hand' &&
            context.source.canPlay()
        );
    }

    executeHandler(context) {
        let targetPlayer = context.target.controller;
        targetPlayer.attach(context.player, context.source, context.target, 'play');
    }

    isCardAbility() {
        return false;
    }
}

module.exports = PlayAttachmentAction;

<|endoftext|>


<commit_before>var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user/user.model');
var validator = require('validator');
var constants = require('../../config/constants.config');
var userBruteForce = require('../../bruteforce/bruteForce').userBruteForce;

passport.use('username', new LocalStrategy(
	function (username, password, done) {
		User.findOne({ username: username }, function (err, user) {
			if (err) { return done(err); }
			if (!user) return done('Incorrect username');
			if (user.isBanned) return done('User is banned');
			if (!user.isConfirmed) return done('User email is not confirmed');
			user.validPassword(password)
			.then(function (result) {
				if (result) return done(null, user);
				else done('Incorrect password');
			}).catch(function (err) {
				return done(err, null);
			});
		});
	}
));

passport.use('email', new LocalStrategy(
	function (username, password, done) {
		User.findOne({ email: username }, function (err, user) {
			if (err) return done(err);
			if (!user) return done('Incorrect email');
			if (user.isBanned) return done('User is banned');
			if (!user.isConfirmed) return done('User email is not confirmed');
			user.validPassword(password)
			.then(function (result) {
				if (result) return done(null, user);
				else done('Incorrect password');
			}).catch(function (err) {
				return done(err, null);
			});
		});
	}
));

module.exports = function (req, res, next) {
	/*
		A user can authenticate with both email and username.
		The body-field named username can contain both email and a username,
		this explains this somewhat weird setup.
	 */
	if (!req.body.password || !req.body.username) {
		return res.status(400).json({message: constants.httpResponseMessages.badRequest});
	}

	if (validator.isEmail(req.body.username)) {
		passport.authenticate('email', function (err, user) {
			if (err) return res.status(401).json({message: constants.httpResponseMessages.unauthorized});
			else {
				req.brute.reset();
				req.logIn(user, {session: false}, next);
			}
		})(req, res, next);
	}
	else {
		passport.authenticate('username', function (err, user) {
			if (err) return res.status(401).json({message: constants.httpResponseMessages.unauthorized});
			else {
				req.brute.reset();
				req.logIn(user, {session: false}, next);
			}
		})(req, res, next);
	}
};
<commit_msg>authenticate now ignores case when finding user.<commit_after>var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user/user.model');
var validator = require('validator');
var constants = require('../../config/constants.config');
var userBruteForce = require('../../bruteforce/bruteForce').userBruteForce;

passport.use('username', new LocalStrategy(
	function (username, password, done) {
		User.findOne({ username: username }, function (err, user) {
			if (err) { return done(err); }
			if (!user) return done('Incorrect username');
			if (user.isBanned) return done('User is banned');
			if (!user.isConfirmed) return done('User email is not confirmed');
			user.validPassword(password)
			.then(function (result) {
				if (result) return done(null, user);
				else done('Incorrect password');
			}).catch(function (err) {
				return done(err, null);
			});
		});
	}
));

passport.use('email', new LocalStrategy(
	function (username, password, done) {
		User.findOne({ email: username }, function (err, user) {
			if (err) return done(err);
			if (!user) return done('Incorrect email');
			if (user.isBanned) return done('User is banned');
			if (!user.isConfirmed) return done('User email is not confirmed');
			user.validPassword(password)
			.then(function (result) {
				if (result) return done(null, user);
				else done('Incorrect password');
			}).catch(function (err) {
				return done(err, null);
			});
		});
	}
));

module.exports = function (req, res, next) {
	/*
		A user can authenticate with both email and username.
		The body-field named username can contain both email and a username,
		this explains this somewhat weird setup.
	 */
	if (!req.body.password || !req.body.username) {
		return res.status(400).json({message: constants.httpResponseMessages.badRequest});
	}
	req.body.username = req.body.username.toLowerCase();
	if (validator.isEmail(req.body.username)) {
		passport.authenticate('email', function (err, user) {
			if (err) return res.status(401).json({message: constants.httpResponseMessages.unauthorized});
			else {
				req.brute.reset();
				req.logIn(user, {session: false}, next);
			}
		})(req, res, next);
	}
	else {
		passport.authenticate('username', function (err, user) {
			if (err) return res.status(401).json({message: constants.httpResponseMessages.unauthorized});
			else {
				req.brute.reset();
				req.logIn(user, {session: false}, next);
			}
		})(req, res, next);
	}
};
<|endoftext|>


<commit_before>var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user/user.model');

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

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  {
    session:false
  },
  function(username, password, done) {

    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) return done('Incorrect username');
      user.validPassword(password)
        .then(function(result){
          if(result) return done(null,user);
          done('Incorrect password');
          }).catch(function(err){
            return done('Something went wrong :(',null);
        });
    });
  }
));

module.exports = function(req, res, next){
  //TODO: Both email and username authentication. Handle bad request
  if(!req.username || ! req.password){
    return res.status(403).json({message: 'bad request'});
  }
  passport.authenticate('local', function(err, user){
      if (err) {
        res.status(403);
        return res.send({message: err});
      }
      req.logIn(user,next);
  })(req,res,next);
};<commit_msg>bugfix /login<commit_after>var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user/user.model');

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

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  {
    session:false
  },
  function(username, password, done) {

    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) return done('Incorrect username');
      user.validPassword(password)
        .then(function(result){
          if(result) return done(null,user);
          done('Incorrect password');
          }).catch(function(err){
            return done('Something went wrong :(',null);
        });
    });
  }
));

module.exports = function(req, res, next){
  //TODO: Both email and username authentication. Handle bad request
  if(!req.body.username || ! req.body.password){
    return res.status(403).json({message: 'bad request'});
  }
  passport.authenticate('local', function(err, user){
      if (err) {
        res.status(403);
        return res.send({message: err});
      }
      req.logIn(user,next);
  })(req,res,next);
};<|endoftext|>


<commit_before><commit_msg>remove unused code<commit_after><|endoftext|>


<commit_before>/**
 * Created by tomere on 26/04/2017.
 * jfTree
 */

class jfTreeController{

    /**
     * Constructor
     * */
    constructor($scope,$q,$timeout,$element){
        this.$scope = $scope;
        this.$timeout = $timeout;
        this.$element = $element;
        this.$q = $q;
        this.currentNode = {};
        this.generatedDictionay = {
            tabs: {
                result: 'result',
            }
        };
//        this.registerTreeEvents();
        this.initTree();
    }

    initTree() {
        this.buildTree().then(()=>{
            this.registerTreeEvents();
        });
    }

    /**
     * register a listener on the tree and delegate to
     * relevant methods
     *
     * @param element
     * @private
     */
    registerTreeEvents() {
        $(this.treeElement).on("select_node.jstree", (e, args) => {
            this.currentNode = args.node;
        });
        $(this.treeElement).on("check_node.jstree", (e, args) => {
            args.node.data.originalObject.$checked = true;
        });
        $(this.treeElement).on("uncheck_node.jstree", (e, args) => {
            args.node.data.originalObject.$checked = false;
        });
    }

    buildTree(){
        let defer = this.$q.defer();
        if(!this.treeData){
            defer.reject();
            return defer.promise;
        }
        this.transformedData = this.transformData(this.treeData);
        let TreeConfig = {
            'core': {
                'data': {}
            },
            "checkbox" : {
                "keep_selected_style" : false,
                "three_state" : true,
                "tie_selection" : false,
                "whole_node": true
            },
            'plugins' : this.plugins
        };
        this.$timeout(()=>{
            TreeConfig.core.data = this.transformedData;
            this.treeElement = $(this.$element).find('.tree-element');
            $(this.treeElement).jstree(TreeConfig);
            $(this.treeElement).on("ready.jstree", (e) => {
                let firstNode = $(this.treeElement).find('.jstree-li:first');
                if(firstNode){
                    let nodeId = firstNode.attr('id');
//                    $(this.treeElement).jstree('select_node', nodeId, true);
                    let node = $(this.treeElement).jstree('get_node', nodeId);
                    this.$timeout(()=>{
                        this.currentNode = node;
                    },100);
                }
                defer.resolve()
            });
        });
        return defer.promise;
    }

    jstree() {
        return $(this.treeElement).jstree();
    }

    transformData(origData){
        if(!origData || !origData.length) return;
        return _.map(origData,(origItem) => {
            let item = {};
            item.data = {originalObject: _.find(this.treeData,origItem)};
            item.children = this.transformData(this.getChildrenFunc({item:origItem}) || []);
            item.text = this.getTextFunc({item:origItem}) || '';
            item.icon = "jf-tree-no-icon";
            item.state =  {
                opened: false,
                disabled: false,
                selected: false,
                checked: false
            };
            return item;
        });
    }

    hasData() {
        return this.treeData && this.treeData.length;
    }

}

export function jfTree() {
    return {
        restrict: 'E',
        scope: {
            treeData: '=',
            treeHeader: '=',
            treeWidth: '=',
            treeHeight: '=',
            plugins: '=',
            getTextFunc: '&',
            getChildrenFunc: '&',
        },
        controller: jfTreeController,
        controllerAs: 'jfTree',
        templateUrl: 'directives/jf_tree/jf_tree.html',
        bindToController: true
    };
}
<commit_msg>jf-tree: Generalizations and improvements<commit_after>/**
 * Created by tomere on 26/04/2017.
 * jfTree
 */

class jfTreeController{

    /**
     * Constructor
     * */
    constructor($scope,$q,$timeout,$element){
        this.$scope = $scope;
        this.$timeout = $timeout;
        this.$element = $element;
        this.$q = $q;
        this.currentNode = {};
        this.generatedDictionay = {
            tabs: {
                result: 'result',
            }
        };
//        this.registerTreeEvents();
        this.initTree();
    }

    initTree() {
        this.buildTree().then(()=>{
            this.registerTreeEvents();
        });
    }

    /**
     * register a listener on the tree and delegate to
     * relevant methods
     *
     * @param element
     * @private
     */
    registerTreeEvents() {
        $(this.treeElement).on("select_node.jstree", (e, args) => {
            this.currentNode = args.node;
        });
        $(this.treeElement).on("check_node.jstree", (e, args) => {
            args.node.data.originalObject().$checked = true;
        });
        $(this.treeElement).on("uncheck_node.jstree", (e, args) => {
            args.node.data.originalObject().$checked = false;
        });
    }

    buildTree(){
        let defer = this.$q.defer();
        if(!this.treeData){
            defer.reject();
            return defer.promise;
        }
        this.transformedData = this.transformData(this.treeData);
        let TreeConfig = {
            'core': {
                'data': {}
            },
            "checkbox" : {
                "keep_selected_style" : false,
                "three_state" : true,
                "tie_selection" : false,
                "whole_node": true
            },
            'plugins' : this.plugins
        };
        this.$timeout(()=>{
            TreeConfig.core.data = this.transformedData;
            this.treeElement = $(this.$element).find('.tree-element');
            $(this.treeElement).jstree(TreeConfig);
            $(this.treeElement).on("ready.jstree", (e) => {
                let firstNode = $(this.treeElement).find('.jstree-li:first');
                if(firstNode){
                    let nodeId = firstNode.attr('id');
//                    $(this.treeElement).jstree('select_node', nodeId, true);
                    let node = $(this.treeElement).jstree('get_node', nodeId);
                    this.$timeout(()=>{
                        this.currentNode = node;
                    },100);
                }
                defer.resolve()
            });
        });
        return defer.promise;
    }

    jstree() {
        return $(this.treeElement).jstree();
    }

    transformData(origData){
        if(!origData || !origData.length) return;
        return _.map(origData,(origItem) => {
            let item = {};
            item.data = {originalObject: ()=>origItem};
            item.children = this.transformData(this.getChildrenFunc({item:origItem}) || []);
            item.text = this.getTextFunc({item:origItem}) || '';
            item.icon = "jf-tree-no-icon";
            item.state =  {
                opened: false,
                disabled: false,
                selected: false,
                checked: false
            };
            return item;
        });
    }

    hasData() {
        return this.treeData && this.treeData.length;
    }

}

export function jfTree() {
    return {
        restrict: 'E',
        scope: {
            treeData: '=',
            treeHeader: '=',
            treeWidth: '=',
            treeHeight: '=',
            plugins: '=',
            getTextFunc: '&',
            getChildrenFunc: '&',
        },
        controller: jfTreeController,
        controllerAs: 'jfTree',
        templateUrl: 'directives/jf_tree/jf_tree.html',
        bindToController: true
    };
}
<|endoftext|>


<commit_before>/* Copyright 2020 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { deprecated } from "./display_utils.js";
import { objectFromMap } from "../shared/util.js";

/**
 * Key/value storage for annotation data in forms.
 */
class AnnotationStorage {
  constructor() {
    this._storage = new Map();
    this._modified = false;

    // Callbacks to signal when the modification state is set or reset.
    // This is used by the viewer to only bind on `beforeunload` if forms
    // are actually edited to prevent doing so unconditionally since that
    // can have undesirable efffects.
    this.onSetModified = null;
    this.onResetModified = null;
  }

  /**
   * Get the value for a given key if it exists, or return the default value.
   *
   * @public
   * @memberof AnnotationStorage
   * @param {string} key
   * @param {Object} defaultValue
   * @returns {Object}
   */
  getValue(key, defaultValue) {
    const obj = this._storage.get(key);
    return obj !== undefined ? obj : defaultValue;
  }

  /**
   * @deprecated
   */
  getOrCreateValue(key, defaultValue) {
    deprecated("Use getValue instead.");
    if (this._storage.has(key)) {
      return this._storage.get(key);
    }

    this._storage.set(key, defaultValue);
    return defaultValue;
  }

  /**
   * Set the value for a given key
   *
   * @public
   * @memberof AnnotationStorage
   * @param {string} key
   * @param {Object} value
   */
  setValue(key, value) {
    const obj = this._storage.get(key);
    let modified = false;
    if (obj !== undefined) {
      for (const [entry, val] of Object.entries(value)) {
        if (obj[entry] !== val) {
          modified = true;
          obj[entry] = val;
        }
      }
    } else {
      this._storage.set(key, value);
      modified = true;
    }
    if (modified) {
      this._setModified();
    }
  }

  getAll() {
    return this._storage.size > 0 ? objectFromMap(this._storage) : null;
  }

  get size() {
    return this._storage.size;
  }

  /**
   * @private
   */
  _setModified() {
    if (!this._modified) {
      this._modified = true;
      if (typeof this.onSetModified === "function") {
        this.onSetModified();
      }
    }
  }

  resetModified() {
    if (this._modified) {
      this._modified = false;
      if (typeof this.onResetModified === "function") {
        this.onResetModified();
      }
    }
  }

  /**
   * PLEASE NOTE: Only intended for usage within the API itself.
   * @ignore
   */
  get serializable() {
    return this._storage.size > 0 ? this._storage : null;
  }
}

export { AnnotationStorage };
<commit_msg>Remove the deprecated `AnnotationStorage.getOrCreateValue`-method (PR 12759 follow-up)<commit_after>/* Copyright 2020 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { objectFromMap } from "../shared/util.js";

/**
 * Key/value storage for annotation data in forms.
 */
class AnnotationStorage {
  constructor() {
    this._storage = new Map();
    this._modified = false;

    // Callbacks to signal when the modification state is set or reset.
    // This is used by the viewer to only bind on `beforeunload` if forms
    // are actually edited to prevent doing so unconditionally since that
    // can have undesirable effects.
    this.onSetModified = null;
    this.onResetModified = null;
  }

  /**
   * Get the value for a given key if it exists, or return the default value.
   *
   * @public
   * @memberof AnnotationStorage
   * @param {string} key
   * @param {Object} defaultValue
   * @returns {Object}
   */
  getValue(key, defaultValue) {
    const obj = this._storage.get(key);
    return obj !== undefined ? obj : defaultValue;
  }

  /**
   * Set the value for a given key
   *
   * @public
   * @memberof AnnotationStorage
   * @param {string} key
   * @param {Object} value
   */
  setValue(key, value) {
    const obj = this._storage.get(key);
    let modified = false;
    if (obj !== undefined) {
      for (const [entry, val] of Object.entries(value)) {
        if (obj[entry] !== val) {
          modified = true;
          obj[entry] = val;
        }
      }
    } else {
      this._storage.set(key, value);
      modified = true;
    }
    if (modified) {
      this._setModified();
    }
  }

  getAll() {
    return this._storage.size > 0 ? objectFromMap(this._storage) : null;
  }

  get size() {
    return this._storage.size;
  }

  /**
   * @private
   */
  _setModified() {
    if (!this._modified) {
      this._modified = true;
      if (typeof this.onSetModified === "function") {
        this.onSetModified();
      }
    }
  }

  resetModified() {
    if (this._modified) {
      this._modified = false;
      if (typeof this.onResetModified === "function") {
        this.onResetModified();
      }
    }
  }

  /**
   * PLEASE NOTE: Only intended for usage within the API itself.
   * @ignore
   */
  get serializable() {
    return this._storage.size > 0 ? this._storage : null;
  }
}

export { AnnotationStorage };
<|endoftext|>


<commit_before><commit_msg>Use the stored $window.<commit_after><|endoftext|>


<commit_before><commit_msg>Whoopsies<commit_after><|endoftext|>


<commit_before><commit_msg>binance parseTrade symbol decoupling<commit_after><|endoftext|>


<commit_before>/**
 * Renderer constructors and general utilities for rendering Form objects
 * as HTML.
 *
 * @module
 */

/**
 * Module dependencies
 */

var events = require('kanso/events'),
    sanitize = require('kanso/sanitize'),
    _ = require('underscore')._;

var h = sanitize.escapeHtml;

/**
 * Generates a script tag that fires the event named {name}.
 */

exports.scriptTagForEvent = function (name) {
    var rv = (
        ''
    );

    return rv;
};

/**
 * Renders HTML for error messages.
 *
 * @name errorHTML(errors)
 * @param {Array} errors
 * @returns {String}
 * @api public
 */

exports.errorHTML = function (errors) {
    if (errors && errors.length) {
        var html = '
';
        for (var i = 0; i < errors.length; i++) {
            html += (
                '
' +
                    h(errors[i].message || errors[i].toString()) +
                '
'
            );
        }
        html += '
';
        return html;
    }
    return '';
};

/**
 * Generates the text for a field's label, depending on whether
 * a custom label is defined or not. If not, the name is captialized and
 * underscores are replaces with spaces to produce the label's text.
 *
 * @name labelText(field, name)
 * @param {Object} field
 * @param {String} name
 * @returns {String}
 * @api public
 */

exports.labelText = function (field, name) {
    if (field.label) {
        return field.label;
    }
    return name.substr(0, 1).toUpperCase() + name.substr(1).replace(/_/g, ' ');
};

/**
 * Generates HTML for label tags.
 *
 * @name labelHTML(field, name, id)
 * @param {Object} field
 * @param {String} name
 * @param {String} id
 * @returns {String}
 * @api public
 */

exports.labelHTML = function (field, name, opt) {
    opt = opt || {};
    var id = opt.id || field.widget._id(name, opt.offset, opt.path_extra);
    return '' +
        h(exports.labelText(field, (opt.caption || name), id)) +
    '';
};

/**
 * Generates HTML for field descriptions (if defined).
 *
 * @name descriptionHTML(obj)
 * @param {Object} obj
 * @returns {String}
 * @api public
 */

exports.descriptionHTML = function (obj) {
    if (obj.description) {
        return '
' + h(obj.description) + '
';
    }
    return '';
};

/**
 * Generates HTML for field hints (if defined).
 *
 * @name hintHTML(obj)
 * @param {Object} obj
 * @returns {String}
 * @api public
 */

exports.hintHTML = function (obj) {
    if (obj.hint) {
        return '
' + h(obj.hint) + '
';
    }
    return '';
};

/**
 * Creates an array of default class names for a field. This includes
 * 'required' for required fields and 'error' for fields failing validation.
 *
 * All fields are given a 'field' class.
 *
 * @name classes(field, errors)
 * @param {Object} field
 * @param {Array} errors
 * @returns {Array}
 * @api public
 */

exports.classes = function (field, errors) {
    var r = ['field'];
    if (errors && errors.length) {
        r.push('error');
    }
    if (field.required) {
        r.push('required');
    }
    return r;
};

/**
 * Determines the default renderer class, to be used globally by
 * instances of forms.Form that fail to specify a renderer class.
 *
 * @name defaultRenderer()
 * @returns {Function}
 * @api public
 */

exports.defaultRenderer = function () {
    return exports.div;
};

/**
 *  Renders a form using a series of properly-nested
 tags.
 *  These
s are labelled with specific CSS classes, some of which
 *  provide depth information (with the aim of simplifying CSS rules).
 *  See style.css for details on how to style this output.
 */
exports.div = function () {
    /**
     * Constructor for renderer; initializes object. The string returned
     * from this function is prepended to the form's markup.
     *
     * @constructor
    */
    this.start = function (errs) {
        this.depth = 0;
        var html = '
';
        if (errs && errs.length) {
            html += '
';
            _.each(errs, function (e) {
                html += '
' + (e.message || e.toString()) + '
';
            });
            html += '
';
        }
        return html;
    };

    /**
     * Called by the forms layer when it encounters a new
     * nesting context (i.e. a new grouping of fields). The
     * path parameter is an array of strings that describes
     * the path (in terms of document keys) to the new group.
     * When concatenated together with a dot, this array yields
     * the new prefix for named HTML form fields.
     *
     * @param {Array} path
    */
    this.beginGroup = function (path) {
        this.depth += 1;
        var name = _.last(path);
        var css_class = 'clear group level-' + this.depth;
        return (
            '
' +
            '
' +
                h(name.substr(0, 1).toUpperCase() +
                    name.substr(1).replace(/_/g, ' ')) +
            '
'
        );
    };

    /**
     * Called by the forms layer when it encounters the end
     * of a nesting context. In the absence of errors, this
     * function is guaranteed to be called once for each time
     * that beginGroup is called; the order will be nested and
     * properly balanced. The path argument is the same as it was
     * for the corresponding beginGroup call; see beginGroup.
     *
     * @param {Array} path
    */
    this.endGroup = function (path) {
        this.depth -= 1;
        return '
';
    };

    /**
     * Called by the forms layer when it encounters any regular
     * field -- i.e. one that is neither an embed nor an embedList.
     *
     * @param {Object} field
     * @param {Array} path
     * @param {Object} value
     * @param {String} raw
     * @param {Array} errors
     * @param {Object} options An object containing widget options, which
     *          will ultimately be provided to each widget's toHTML method.
    */
    this.field = function (field, path, value, raw, errors, options) {
        var name = path.join('.');
        var caption = path.slice(this.depth).join(' ');

        events.once('renderFinish', function () {
            if (field.widget.clientInit) {
                setTimeout(function () {
                    field.widget.clientInit(
                        field, path, value, raw, errors, (options || {})
                    );
                }, 0);
            }
        });

        if (field.widget.type === 'hidden') {
            return field.widget.toHTML(
                name, value, raw, field, (options || {})
            );
        }

        options.caption = caption;
        return (
            '
' +
                '
' +
                    exports.labelHTML(field, name, options) +
                    exports.descriptionHTML(field) +
                '
' +
                '
' +
                    '
' +
                        field.widget.toHTML(
                            name, value, raw, field, (options || {})
                        ) +
                    '
' +
                    '
' +
                        exports.hintHTML(field) +
                    '
' +
                    '
' +
                        exports.errorHTML(errors) +
                    '
' +
                    '
' +
                '
' +
            '
'
        );
    };

    /**
     * Called by the forms layer when it is finished rendering a form.
     * Markup returned from this function is appended to the form output.
     *
     * @param {String} field
     * @param {Array} path
     * @param {Object} value
     * @param {String} raw
     * @param {Array} errors
    */
    this.end = function () {
        return (
                '
' +
            '
'
        );
    };
};

<commit_msg>call sanitize.generateDomIdentifier directly instead of using widget._id when generating ids for form labels<commit_after>/**
 * Renderer constructors and general utilities for rendering Form objects
 * as HTML.
 *
 * @module
 */

/**
 * Module dependencies
 */

var events = require('kanso/events'),
    sanitize = require('kanso/sanitize'),
    _ = require('underscore')._;

var h = sanitize.escapeHtml;

/**
 * Generates a script tag that fires the event named {name}.
 */

exports.scriptTagForEvent = function (name) {
    var rv = (
        ''
    );

    return rv;
};

/**
 * Renders HTML for error messages.
 *
 * @name errorHTML(errors)
 * @param {Array} errors
 * @returns {String}
 * @api public
 */

exports.errorHTML = function (errors) {
    if (errors && errors.length) {
        var html = '
';
        for (var i = 0; i < errors.length; i++) {
            html += (
                '
' +
                    h(errors[i].message || errors[i].toString()) +
                '
'
            );
        }
        html += '
';
        return html;
    }
    return '';
};

/**
 * Generates the text for a field's label, depending on whether
 * a custom label is defined or not. If not, the name is captialized and
 * underscores are replaces with spaces to produce the label's text.
 *
 * @name labelText(field, name)
 * @param {Object} field
 * @param {String} name
 * @returns {String}
 * @api public
 */

exports.labelText = function (field, name) {
    if (field.label) {
        return field.label;
    }
    return name.substr(0, 1).toUpperCase() + name.substr(1).replace(/_/g, ' ');
};

/**
 * Generates HTML for label tags.
 *
 * @name labelHTML(field, name, id)
 * @param {Object} field
 * @param {String} name
 * @param {String} id
 * @returns {String}
 * @api public
 */

exports.labelHTML = function (field, name, opt) {
    opt = opt || {};
    var id = opt.id || sanitize.generateDomIdentifier(
        name, opt.offset, opt.path_extra
    );
    return '' +
        h(exports.labelText(field, (opt.caption || name), id)) +
    '';
};

/**
 * Generates HTML for field descriptions (if defined).
 *
 * @name descriptionHTML(obj)
 * @param {Object} obj
 * @returns {String}
 * @api public
 */

exports.descriptionHTML = function (obj) {
    if (obj.description) {
        return '
' + h(obj.description) + '
';
    }
    return '';
};

/**
 * Generates HTML for field hints (if defined).
 *
 * @name hintHTML(obj)
 * @param {Object} obj
 * @returns {String}
 * @api public
 */

exports.hintHTML = function (obj) {
    if (obj.hint) {
        return '
' + h(obj.hint) + '
';
    }
    return '';
};

/**
 * Creates an array of default class names for a field. This includes
 * 'required' for required fields and 'error' for fields failing validation.
 *
 * All fields are given a 'field' class.
 *
 * @name classes(field, errors)
 * @param {Object} field
 * @param {Array} errors
 * @returns {Array}
 * @api public
 */

exports.classes = function (field, errors) {
    var r = ['field'];
    if (errors && errors.length) {
        r.push('error');
    }
    if (field.required) {
        r.push('required');
    }
    return r;
};

/**
 * Determines the default renderer class, to be used globally by
 * instances of forms.Form that fail to specify a renderer class.
 *
 * @name defaultRenderer()
 * @returns {Function}
 * @api public
 */

exports.defaultRenderer = function () {
    return exports.div;
};

/**
 *  Renders a form using a series of properly-nested
 tags.
 *  These
s are labelled with specific CSS classes, some of which
 *  provide depth information (with the aim of simplifying CSS rules).
 *  See style.css for details on how to style this output.
 */
exports.div = function () {
    /**
     * Constructor for renderer; initializes object. The string returned
     * from this function is prepended to the form's markup.
     *
     * @constructor
    */
    this.start = function (errs) {
        this.depth = 0;
        var html = '
';
        if (errs && errs.length) {
            html += '
';
            _.each(errs, function (e) {
                html += '
' + (e.message || e.toString()) + '
';
            });
            html += '
';
        }
        return html;
    };

    /**
     * Called by the forms layer when it encounters a new
     * nesting context (i.e. a new grouping of fields). The
     * path parameter is an array of strings that describes
     * the path (in terms of document keys) to the new group.
     * When concatenated together with a dot, this array yields
     * the new prefix for named HTML form fields.
     *
     * @param {Array} path
    */
    this.beginGroup = function (path) {
        this.depth += 1;
        var name = _.last(path);
        var css_class = 'clear group level-' + this.depth;
        return (
            '
' +
            '
' +
                h(name.substr(0, 1).toUpperCase() +
                    name.substr(1).replace(/_/g, ' ')) +
            '
'
        );
    };

    /**
     * Called by the forms layer when it encounters the end
     * of a nesting context. In the absence of errors, this
     * function is guaranteed to be called once for each time
     * that beginGroup is called; the order will be nested and
     * properly balanced. The path argument is the same as it was
     * for the corresponding beginGroup call; see beginGroup.
     *
     * @param {Array} path
    */
    this.endGroup = function (path) {
        this.depth -= 1;
        return '
';
    };

    /**
     * Called by the forms layer when it encounters any regular
     * field -- i.e. one that is neither an embed nor an embedList.
     *
     * @param {Object} field
     * @param {Array} path
     * @param {Object} value
     * @param {String} raw
     * @param {Array} errors
     * @param {Object} options An object containing widget options, which
     *          will ultimately be provided to each widget's toHTML method.
    */
    this.field = function (field, path, value, raw, errors, options) {
        var name = path.join('.');
        var caption = path.slice(this.depth).join(' ');

        events.once('renderFinish', function () {
            if (field.widget.clientInit) {
                setTimeout(function () {
                    field.widget.clientInit(
                        field, path, value, raw, errors, (options || {})
                    );
                }, 0);
            }
        });

        if (field.widget.type === 'hidden') {
            return field.widget.toHTML(
                name, value, raw, field, (options || {})
            );
        }

        options.caption = caption;
        return (
            '
' +
                '
' +
                    exports.labelHTML(field, name, options) +
                    exports.descriptionHTML(field) +
                '
' +
                '
' +
                    '
' +
                        field.widget.toHTML(
                            name, value, raw, field, (options || {})
                        ) +
                    '
' +
                    '
' +
                        exports.hintHTML(field) +
                    '
' +
                    '
' +
                        exports.errorHTML(errors) +
                    '
' +
                    '
' +
                '
' +
            '
'
        );
    };

    /**
     * Called by the forms layer when it is finished rendering a form.
     * Markup returned from this function is appended to the form output.
     *
     * @param {String} field
     * @param {Array} path
     * @param {Object} value
     * @param {String} raw
     * @param {Array} errors
    */
    this.end = function () {
        return (
                '
' +
            '
'
        );
    };
};

<|endoftext|>


<commit_before><commit_msg>clean up request and cancel animation frame shim<commit_after><|endoftext|>


<commit_before>const iris = require('../index');
const dock = require('./docks/http');
const handler = require('./handlers/handler1');
const inputHook = require('./hooks/hook1');
const outputHook = require('./hooks/hook2');

iris.config = {
    threads: 4,
    logLevel: 'silly',
    events: {
        dispatcher: true,
        docks: true
    },
    vantage: {
        enabled: false,
        port: 1337
    }
};

dock.config = {
    port: 5000,
    parser: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    encoder: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    maxMessageLength: 100
};

iris.flow('Flow 1', {
    tag: 'tag1',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});

iris.flow('Flow 2', {
    tag: 'tag2',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});<commit_msg>Set example logLevel to 'info'<commit_after>const iris = require('../index');
const dock = require('./docks/http');
const handler = require('./handlers/handler1');
const inputHook = require('./hooks/hook1');
const outputHook = require('./hooks/hook2');

iris.config = {
    threads: 4,
    logLevel: 'info',
    events: {
        dispatcher: true,
        docks: true
    },
    vantage: {
        enabled: false,
        port: 1337
    }
};

dock.config = {
    port: 5000,
    parser: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    encoder: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    maxMessageLength: 100
};

iris.flow('Flow 1', {
    tag: 'tag1',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});

iris.flow('Flow 2', {
    tag: 'tag2',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});<|endoftext|>


<commit_before><commit_msg>Trying to make txt process thing work<commit_after><|endoftext|>


<commit_before>(function() {
  function shiftImage(amt) {
    var pos = parseInt(theImg.style.left);
    pos += amt;
    theImg.style.left = pos;
  }

  function keyCheck(e) {
    if (e.keyCode == 37) {
      shiftImg(-1);
    }
    else if (e.keyCode == 39) {
      shiftImg(1);
    }

    var theImg = document.getElementById("shiftyImg");
    if (theImg) {
      document.addEventListener("keydown", keyCheck);
    }
  }
}).call();
<commit_msg>Update moveImg.js<commit_after>(function() {
  function shiftImage(dir, amt) {
    var pos;
    if (dir == "lr") {
       pos = parseInt(theImg.style.left);
       pos += amt * 5;
      theImg.style.left = pos;
    }
    else {
      pos = parseInt(theImg.style.top);
      pos += amt * 5;
      theImg.style.top = pos;
    }
  }

  function keyCheck(e) {
    if (e.keyCode == 37) {
      shiftImg("lr", -1);
    }
    else if (e.keyCode == 39) {
      shiftImg("lr", 1);
    }
    else if (e.keyCode == 38) {
      shiftImg("ud", -1);
    }
    else if (e.keyCode == 40) {
      shiftImg("ud", 1);
    }
  }

  var theImg = document.getElementById("shiftyImg");
  if (theImg) {
    theImg.style.left = "0px";
    theImg.style.top = "0px";
    document.addEventListener("keydown", keyCheck);
  }
}).call();
<|endoftext|>


<commit_before>var Ajax = function(options){
	console.log('ok, got a query for ' + options.url);
	var request = new XMLHttpRequest();
	var url = options.url;
	var successCb = options.success;
	var failCb = options.fail;

	request.open('GET', url, true);

	request.onload = function() {
	  if (request.status >= 200 && request.status < 400) {
	    console.log('Success!')
	    var data = JSON.parse(request.responseText);
	    console.log(data);
	    successCb(data);
	  } else {
	    console.log('We reached our target server, but it returned an error');
	    failCb(request.status);
	  }
	};

	request.onerror = function() {
	  console.log('failed, connection issue');
	  failCb(request.status);
	};

	request.send();
}

var getEl = function(el){
	var sel = el.substring(1,el.length);
	if(el.charAt(0)==='#'){
		return document.getElementById(sel);
	}else if(el.charAt(0)==='.'){
		return document.getElementByClassName(sel);
	}
}

var addClass = function(el, clazz){
	if (el.classList){
		el.classList.add(clazz);
	}else{
		el.className += ' ' + clazz;
	}
  	return el;
}

var newEl = function (tagName, className, container) {

	var el = document.createElement(tagName);
	el.className = className;

	if (container) {
		container.appendChild(el);
	}

	return el;
}

<commit_msg>comment out the console.log()'s<commit_after>var Ajax = function(options){
	//console.log('ok, got a query for ' + options.url);
	var request = new XMLHttpRequest();
	var url = options.url;
	var successCb = options.success;
	var failCb = options.fail;

	request.open('GET', url, true);

	request.onload = function() {
	  if (request.status >= 200 && request.status < 400) {
	    //console.log('Success!')
	    var data = JSON.parse(request.responseText);
	    console.log(data);
	    successCb(data);
	  } else {
	    //console.log('We reached our target server, but it returned an error');
	    failCb(request.status);
	  }
	};

	request.onerror = function() {
	  console.log('failed, connection issue');
	  failCb(request.status);
	};

	request.send();
}

var getEl = function(el){
	var sel = el.substring(1,el.length);
	if(el.charAt(0)==='#'){
		return document.getElementById(sel);
	}else if(el.charAt(0)==='.'){
		return document.getElementByClassName(sel);
	}
}

var addClass = function(el, clazz){
	if (el.classList){
		el.classList.add(clazz);
	}else{
		el.className += ' ' + clazz;
	}
  	return el;
}

var newEl = function (tagName, className, container) {

	var el = document.createElement(tagName);
	el.className = className;

	if (container) {
		container.appendChild(el);
	}

	return el;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015-2016 TakWolf
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function() {

    /* return a int random num */
    function getRandomNum(min, max) {
        var range = max - min;
        var rand = Math.random();
        return(min + Math.round(rand * range));
    }

    /* cat class */
    function Cat() {

        /* reset position xy and speed */
        this.reset = function() {
            this.img.width = getRandomNum(100, 200);
            this.x = -this.img.width;
            this.y = getRandomNum(0, window.innerHeight - 100);
            this.img.style.left = this.x + 'px';
            this.img.style.top = this.y + 'px';
            this.speed = getRandomNum(1, 5);
        }

        this.img = document.createElement('img');
        this.img.src = 'img/nyancat.gif';
        this.img.style.position = 'fixed';
        this.wait = true; /* ture is not display */
        document.body.appendChild(this.img);
        this.reset();

        /* this should call in loop update callback */
        this.update = function(dt) {
            if (this.wait) {
                if (getRandomNum(0, 180) === 0) { /* about 3 seconds */
                    this.wait = false;
                    this.reset();
                }
            } else {
                this.x += this.speed;
                this.img.style.left = this.x + 'px';
                if (this.x > window.innerWidth + this.img.width) {
                    this.wait = true;
                }
            }
        }

    }

    /* cat array used to manage */
    var catArray = [];

    /* load callback */
    function load() {
        /* init cats */
        for (var n = 0; n < 20; n++) {
            catArray[n] = new Cat();
        }
        /* play bgm */
        var bgm = document.createElement('audio');
        bgm.src = 'bgm/nyancat.mp3';
        bgm.autoplay = 'autoplay';
        bgm.loop = 'loop'; /* FIXME : this is not work , I don't know why */
        window.setInterval(function() {
            bgm.src = 'bgm/nyancat.mp3'; /* FIXME : only this way can work , I am crazy !!! */
        }, 27097.687);
    }

    /* update callback */
    function update(dt) {
        for (var n = 0; n < catArray.length; n++) {
            catArray[n].update(dt);
        }
    }

    /* in load callback to make sure body element is exist */
    window.addEventListener('load', function() {
        /* make a fps loop frame */
        var fps = 60;
        var lastTime = new Date().getTime();
        var loop = function() {
            var nowTime = new Date().getTime();
            var deltaTime = nowTime - lastTime;
            if(deltaTime - 1000/fps >= 0) {
                lastTime = nowTime;
                update(deltaTime/1000);
            }
        };
        /* load callback */
        load();
        /* start loop as soon as possible */
        window.setInterval(loop, 1);
    }, false);

})();
<commit_msg>nyancat 音乐播放增加候选资源<commit_after>/*
 * Copyright 2015-2016 TakWolf
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
(function() {

    /* return a int random num */
    function getRandomNum(min, max) {
        var range = max - min;
        var rand = Math.random();
        return(min + Math.round(rand * range));
    }

    /* cat class */
    function Cat() {

        /* reset position xy and speed */
        this.reset = function() {
            this.img.width = getRandomNum(100, 200);
            this.x = -this.img.width;
            this.y = getRandomNum(0, window.innerHeight - 100);
            this.img.style.left = this.x + 'px';
            this.img.style.top = this.y + 'px';
            this.speed = getRandomNum(1, 5);
        }

        this.img = document.createElement('img');
        this.img.src = 'img/nyancat.gif';
        this.img.style.position = 'fixed';
        this.wait = true; /* ture is not display */
        document.body.appendChild(this.img);
        this.reset();

        /* this should call in loop update callback */
        this.update = function(dt) {
            if (this.wait) {
                if (getRandomNum(0, 180) === 0) { /* about 3 seconds */
                    this.wait = false;
                    this.reset();
                }
            } else {
                this.x += this.speed;
                this.img.style.left = this.x + 'px';
                if (this.x > window.innerWidth + this.img.width) {
                    this.wait = true;
                }
            }
        }

    }

    /* cat array used to manage */
    var catArray = [];

    /* load callback */
    function load() {
        /* init cats */
        for (var n = 0; n < 20; n++) {
            catArray[n] = new Cat();
        }
        /* play bgm */
        var bgm = document.createElement('audio');
        bgm.autoplay = 'autoplay';
        bgm.loop = 'loop'; /* FIXME : this is not work */
        var src1 = document.createElement('source');
        src1.src = 'bgm/nyancat.mp3';
        src1.type = 'audio/mpeg';
        bgm.appendChild(src1);
        var src2 = document.createElement('source');
        src2.src = 'bgm/nyancat.ogg';
        src2.type = 'audio/ogg';
        bgm.appendChild(src2);
        document.body.appendChild(bgm);
    }

    /* update callback */
    function update(dt) {
        for (var n = 0; n < catArray.length; n++) {
            catArray[n].update(dt);
        }
    }

    /* in load callback to make sure body element is exist */
    window.addEventListener('load', function() {
        /* make a fps loop frame */
        var fps = 60;
        var lastTime = new Date().getTime();
        var loop = function() {
            var nowTime = new Date().getTime();
            var deltaTime = nowTime - lastTime;
            if(deltaTime - 1000/fps >= 0) {
                lastTime = nowTime;
                update(deltaTime/1000);
            }
        };
        /* load callback */
        load();
        /* start loop as soon as possible */
        window.setInterval(loop, 1);
    }, false);

})();
<|endoftext|>


<commit_before><commit_msg>modified scenariosArray initialization<commit_after><|endoftext|>


<commit_before>;(function(window, document, $, chrome){

  'use strict';

  var getOptions = function(){
    chrome.storage.local.get(function(data){
      if(data.token){
        $('#token').val(data.token);
      }
      if(data.channel){
        $('#channel').val(data.channel);
      }
    });
  };

  var clearOptions = function(){
    chrome.storage.local.clear(function(){
      $('#token').val('');
      $('#channel').val('');
    });
  };

  var saveOptions = function(token, channel, $success_el){
    chrome.storage.local.set({
      'token': token,
      'channel': channel
    }, function(){
      $success_el.fadeIn();
    });
  };

  var checkToken = function(token) {
    return $.ajax({
      type: 'GET',
      url: 'https://slack.com/api/auth.test',
      data: { token: token }
    });
  };

  $(document).ready(function(){
    var $info_el = $('#info-message');

    getOptions();

    $('#save').click(function(e){
      e.preventDefault();
      saveOptions($('#token').val(), $('#channel').val(), $(this).find('.icon'));
    });

    $('#clear').click(function(e){
      e.preventDefault();
      clearOptions();
    });

    $('#check').click(function(e){
      e.preventDefault();
      var $success_el = $(this).find('.icon');

      checkToken($('#token').val()).then(function(resp){
        if(resp.ok){
          $success_el.fadeIn();
        }
        else{
          $info_el.find('.icon').show();
          $info_el.find('span').text(resp.error.replace(/_/g, ' '));
        }
      }).fail(function(){
        $info_el.find('span').text('network error');
      });
    });

    $('input').on('keyup', function(){
      $('.icon-exclamation-circle, .icon-check').hide();
      $('span').text('');
    });

    $('#help').click(function(e){
      e.preventDefault();
      $('#help-contents').toggle();
    });

  });

})(window, document, jQuery, chrome);
<commit_msg>Improve options js code<commit_after>;(function(window, document, $, chrome){

  'use strict';

  var getSavedOptions = function(){
    var dfd = $.Deferred();
    chrome.storage.local.get(function(data){
      dfd.resolve(data);
    });
    return dfd;
  };

  var clearOptions = function(){
    var dfd = $.Deferred();
    chrome.storage.local.clear(function(){
      dfd.resolve();
    });
    return dfd;
  };

  var saveOptions = function(token, channel){
    var dfd = $.Deferred();
    chrome.storage.local.set({
      'token': token,
      'channel': channel
    }, function(){
      dfd.resolve();
    });
    return dfd;
  };

  var checkToken = function(token) {
    return $.ajax({
      type: 'GET',
      url: 'https://slack.com/api/auth.test',
      data: { token: token }
    });
  };

  var humanize = function(str){
    return str.replace(/_/g, ' ');
  };

  $(document).ready(function(){

    //Cache Elements
    var $info_el = $('#info-message');
    var $info_icon = $info_el.find('.icon');
    var $info_text = $info_el.find('span');
    var $token_el = $('#token');
    var $channel_el = $('#channel');

    //Get saved option and show their values in input elements
    getSavedOptions().then(function(data){
      if(data.token){
        $token_el.val(data.token);
      }
      if(data.channel){
        $channel_el.val(data.channel);
      }
    });

    //Register Handlers
    $('#save').click(function(e){
      e.preventDefault();
      var $success_el = $(this).find('.icon');

      saveOptions($token_el.val(), $channel_el.val()).done(function(){
        $success_el.fadeIn();
      });
    });

    $('#clear').click(function(e){
      e.preventDefault();
      clearOptions().then(function(){
        $token_el.val('');
        $channel_el.val('');
      });
    });

    $('#check').click(function(e){
      e.preventDefault();
      var $success_el = $(this).find('.icon');

      checkToken($token_el.val()).done(function(resp){
        if(resp.ok){
          $success_el.fadeIn();
        }
        else{
          $info_icon.show();
          $info_text.text(humanize(resp.error));
        }
      }).fail(function(){
        $info_text.text('network error');
      });
    });

    $('input').on('keyup', function(){
      $('.icon-exclamation-circle, .icon-check').hide();
      $info_text.text('');
    });

    $('#help').click(function(e){
      e.preventDefault();
      $('#help-contents').toggle();
    });

  });

})(window, document, jQuery, chrome);
<|endoftext|>


<commit_before>$(function() {
	var ce = chrome.extension;
	var bg_win = ce.getBackgroundPage();
	var PREFiX = bg_win.PREFiX;
	var lscache = bg_win.lscache;

	$('#switch-account').click(function(e) {
		PREFiX.reset();
		close();
	});
	$('#version').text(PREFiX.version);

	var current = PREFiX.settings.current;

	$('[key]').each(function() {
		var $item = $(this);
		var key = $item.attr('key');
		var value = current[key];
		switch ($item.attr('type')) {
			case 'checkbox':
				$item.prop('checked', value);
				break;
			case 'select':
				$item.val(value);
				break;
		}
	});

	if (PREFiX.account) {
		$('#username').
		text('@' + PREFiX.account.name + ' (' + PREFiX.account.id + ')').
		prop('href', 'http://fanfou.com/' + PREFiX.account.id);
	} else {
		$('#user-info').text('您还没有登录饭否账号，请点击下面的按钮继续。')
		$('#switch-account').text('登入账号');
	}

	var last_used_page = lscache.get('last_used_page') || 0;
	$('#navbar li').each(function(i) {
		var $item = $(this);
		$item.click(function(e) {
			$('#navbar li').removeClass('current');
			$('.page').removeClass('current');
			$item.addClass('current');
			var page = $item.prop('id') + '-page';
			$('#' + page).addClass('current');
			lscache.set('last_used_page', i);
		});
	}).eq(last_used_page).click();

	var custom_consumer = lscache.get('custom_consumer');
	if (custom_consumer) {
		$('#key').val(custom_consumer.key);
		$('#secret').val(custom_consumer.secret);
	}
	$('#set-consumer').click(function(e) {
		var key = $('#key').val().trim();
		var secret = $('#secret').val().trim();
		if (! key || ! secret) return;
		if (key === custom_consumer.key ||
			secret === custom_consumer.secret) {
			alert('您已经成功设置了尾巴, 不需要重复设置. :)');
			return;
		}
		bg_win.enableCustomConsumer(key, secret);
	});
	$('#reset-consumer').click(function(e) {
		bg_win.disableCustomConsumer();
		location.reload();
	});

	var $usage_tip_list = $('#usage-tip-page ol');
	bg_win.usage_tips.forEach(function(tip) {
		var $li = $('<li />');
		$li.html(tip);
		$li.appendTo($usage_tip_list);
	});

	$('#status-count').text(bg_win.getStatusCount());
	$('#photo-count').text(bg_win.getPhotoCount());

	var install_time = lscache.get('install_time');
	install_time = bg_win.getYMD(install_time);
	$('#install-time').text(install_time);

	$('#show-updates').click(function(e) {
		var update = [];
		var history = bg_win.history;
		Object.keys(history).forEach(function(version) {
			update.push('# ' + version + ' #');
			update.push.apply(update, history[version]);
			update.push('');
		});
		alert(update.join('\n'));
	});

	onunload = function(e) {
		$('[key]').each(function() {
			var $item = $(this);
			var key = $item.attr('key');
			var value;
			switch ($item.attr('type')) {
				case 'checkbox':
					value = $item.prop('checked');
					break;
				case 'select':
					value = $item.val();
					break;
			}
			current[key] = value;
		});
		PREFiX.settings.save();
		PREFiX.settings.onSettingsUpdated();
	}
});<commit_msg>修正一处细节错误<commit_after>$(function() {
	var ce = chrome.extension;
	var bg_win = ce.getBackgroundPage();
	var PREFiX = bg_win.PREFiX;
	var lscache = bg_win.lscache;

	$('#switch-account').click(function(e) {
		PREFiX.reset();
		close();
	});
	$('#version').text(PREFiX.version);

	var current = PREFiX.settings.current;

	$('[key]').each(function() {
		var $item = $(this);
		var key = $item.attr('key');
		var value = current[key];
		switch ($item.attr('type')) {
			case 'checkbox':
				$item.prop('checked', value);
				break;
			case 'select':
				$item.val(value);
				break;
		}
	});

	if (PREFiX.account) {
		$('#username').
		text('@' + PREFiX.account.name + ' (' + PREFiX.account.id + ')').
		prop('href', 'http://fanfou.com/' + PREFiX.account.id);
	} else {
		$('#user-info').text('您还没有登录饭否账号，请点击下面的按钮继续。')
		$('#switch-account').text('登入账号');
	}

	var last_used_page = lscache.get('last_used_page') || 0;
	$('#navbar li').each(function(i) {
		var $item = $(this);
		$item.click(function(e) {
			$('#navbar li').removeClass('current');
			$('.page').removeClass('current');
			$item.addClass('current');
			var page = $item.prop('id') + '-page';
			$('#' + page).addClass('current');
			lscache.set('last_used_page', i);
		});
	}).eq(last_used_page).click();

	var custom_consumer = lscache.get('custom_consumer');
	if (custom_consumer) {
		$('#key').val(custom_consumer.key);
		$('#secret').val(custom_consumer.secret);
	} else {
		custom_consumer = { };
	}
	$('#set-consumer').click(function(e) {
		var key = $('#key').val().trim();
		var secret = $('#secret').val().trim();
		if (! key || ! secret) return;
		if (key === custom_consumer.key ||
			secret === custom_consumer.secret) {
			alert('您已经成功设置了尾巴, 不需要重复设置. :)');
			return;
		}
		bg_win.enableCustomConsumer(key, secret);
	});
	$('#reset-consumer').click(function(e) {
		bg_win.disableCustomConsumer();
		location.reload();
	});

	var $usage_tip_list = $('#usage-tip-page ol');
	bg_win.usage_tips.forEach(function(tip) {
		var $li = $('<li />');
		$li.html(tip);
		$li.appendTo($usage_tip_list);
	});

	$('#status-count').text(bg_win.getStatusCount());
	$('#photo-count').text(bg_win.getPhotoCount());

	var install_time = lscache.get('install_time');
	install_time = bg_win.getYMD(install_time);
	$('#install-time').text(install_time);

	$('#show-updates').click(function(e) {
		var update = [];
		var history = bg_win.history;
		Object.keys(history).forEach(function(version) {
			update.push('# ' + version + ' #');
			update.push.apply(update, history[version]);
			update.push('');
		});
		alert(update.join('\n'));
	});

	onunload = function(e) {
		$('[key]').each(function() {
			var $item = $(this);
			var key = $item.attr('key');
			var value;
			switch ($item.attr('type')) {
				case 'checkbox':
					value = $item.prop('checked');
					break;
				case 'select':
					value = $item.val();
					break;
			}
			current[key] = value;
		});
		PREFiX.settings.save();
		PREFiX.settings.onSettingsUpdated();
	}
});<|endoftext|>