<commit_before>import React from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { media } from '../utils/style'

import PostList from '../component/PostList'

const SearchKeyword = styled.h1`
  text-align: center;
  ${media.mobile`font-size: 1rem;`}
`

class SearchPage extends React.Component {
  state = {
    searchKeyword: null,
  }

  componentDidMount() {
    const { search } = window.location
    const searchKeyword = search
      .replace('?', '')
      .split('&')
      .reduce((acc, params) => {
        const [key, value] = params.split('=')
        return (key === 'q' && decodeURIComponent(value)) || ''
      }, '')
    this.setState({ searchKeyword })
  }

  getNodesWithSearchKeyword(searchKeyword) {
    if (!searchKeyword) return []
    return this.props.data.allMarkdownRemark.edges
      .map(({ node }) => node)
      .filter(({ fields, frontmatter, html }) => {
        return (
          fields.slug.includes(searchKeyword) ||
          frontmatter.title.includes(searchKeyword) ||
          frontmatter.date.includes(searchKeyword) ||
          html.includes(searchKeyword)
        )
      })
  }

  render() {
    const resultNodes = this.getNodesWithSearchKeyword(this.state.searchKeyword);
    return (

        <Link to="/"> Go to Home</Link>
        <SearchKeyword>
          {this.state.searchKeyword && resultNodes.length > 0 &&
            `😀 ${resultNodes.length} results about '${
              this.state.searchKeyword
            }'`}
          {this.state.searchKeyword && resultNodes.length === 0 &&
            `🙃 no results about '${this.state.searchKeyword}'`}
        </SearchKeyword>
        {resultNodes.length > 0 && <PostList markdownNodes={resultNodes} />}

    )
  }
}

export default SearchPage

export const query = graphql`
  query SearchPageQuery {
    allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
      totalCount
      edges {
        node {
          id
          frontmatter {
            title
            date(formatString: "YYYY-MM-DD")
          }
          fields {
            slug
          }
          html
        }
      }
    }
  }
`
<commit_msg>search query<commit_after>import React from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { media } from '../utils/style'

import PostList from '../component/PostList'

const SearchKeyword = styled.h1`
  text-align: center;
  ${media.mobile`font-size: 1rem;`}
`

class SearchPage extends React.Component {
  state = {
    searchKeyword: null,
  }

  componentDidMount() {
    const { search } = window.location
    const searchKeyword = search
      .replace('?', '')
      .split('&')
      .reduce((acc, params) => {
        const [key, value] = params.split('=')
        return (key === 'q' && decodeURIComponent(value)) || ''
      }, '')
    this.setState({ searchKeyword })
  }

  getNodesWithSearchKeyword(searchKeyword) {
    if (!searchKeyword) return []
    return this.props.data.allMarkdownRemark.edges
      .map(({ node }) => node)
      .filter(({ fields, frontmatter, html }) => {
        return (
          fields.slug.includes(searchKeyword) ||
          frontmatter.title.includes(searchKeyword) ||
          frontmatter.date.includes(searchKeyword) ||
          html.includes(searchKeyword)
        )
      })
  }

  render() {
    const resultNodes = this.getNodesWithSearchKeyword(this.state.searchKeyword);
    return (

        <Link to="/"> Go to Home</Link>
        <SearchKeyword>
          {this.state.searchKeyword && resultNodes.length > 0 &&
            `😀 ${resultNodes.length} results about '${
              this.state.searchKeyword
            }'`}
          {this.state.searchKeyword && resultNodes.length === 0 &&
            `🙃 no results about '${this.state.searchKeyword}'`}
        </SearchKeyword>
        {resultNodes.length > 0 && <PostList markdownNodes={resultNodes} />}

    )
  }
}

export default SearchPage

export const query = graphql`
query SearchPageQuery {
  allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
    totalCount
    edges {
      node {
        id
        frontmatter {
          title
          category
          date(formatString: "YYYY-MM-DD")
          description
        }
        fields {
          slug
        }
        html
      }
    }
  }
}
`

// export const query = graphql`
//   query SearchPageQuery {
//     allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) {
//       totalCount
//       edges {
//         node {
//           id
//           frontmatter {
//             title
//             date(formatString: "YYYY-MM-DD")
//           }
//           fields {
//             slug
//           }
//           html
//         }
//       }
//     }
//   }
// `
<|endoftext|>


<commit_before>import path from 'path';
import remark from 'remark';
import inject from 'mdast-util-inject';
import { read, write } from './fs';

export default function parser(dir = process.cwd()) {
    const pathname = path.resolve(dir, 'CHANGELOG.md');
    const contents = read(pathname);
    return {
        remark,
        root: remark.parse(contents),
        createMDAST(value) {
            const result = remark.parse(value);
            if (result.children.length === 1) {
                return result.children[0];
            }
            return result.children;
        },
        exists() {
            return contents !== null;
        },
        write() {
            return write(pathname, this.stringify());
        },
        stringify() {
            return this.remark.stringify(this.root);
        },
        addedHeaderExists() {
            return this.root.children[3] &&
                this.root.children[3].type === 'heading' &&
                this.root.children[3].children[0] &&
                this.root.children[3].children[0].value === 'Added';
        },
        unreleased() {
            if (!(this.root.children[4] && this.root.children[4].type === 'list')) {
                // probably we should create it?
                return false;
            }
            return this.root.children[4];
        },
        added(value) {
            let result = false;
            if (!this.addedHeaderExists()) {
                inject('Unreleased', this.root, remark.parse('### Added\n'));
            }
            const unreleasedAST = this.unreleased();
            if ( unreleasedAST ) {
                const toAdd = remark.parse(value);
                unreleasedAST.children.push(toAdd.children[0].children[0]); // add 'each' children.children?
                const astToString = remark.stringify(unreleasedAST)
                result = inject('Added', this.root, remark.parse(astToString));
            } else {
                result = inject('Added', this.root, remark.parse(value));
            }
            return result;
        }
    };
}
<commit_msg>Update: lint fix<commit_after>import path from 'path';
import remark from 'remark';
import inject from 'mdast-util-inject';
import { read, write } from './fs';

export default function parser(dir = process.cwd()) {
    const pathname = path.resolve(dir, 'CHANGELOG.md');
    const contents = read(pathname);
    return {
        remark,
        root: remark.parse(contents),
        createMDAST(value) {
            const result = remark.parse(value);
            if (result.children.length === 1) {
                return result.children[0];
            }
            return result.children;
        },
        exists() {
            return contents !== null;
        },
        write() {
            return write(pathname, this.stringify());
        },
        stringify() {
            return this.remark.stringify(this.root);
        },
        addedHeaderExists() {
            return this.root.children[3] &&
                this.root.children[3].type === 'heading' &&
                this.root.children[3].children[0] &&
                this.root.children[3].children[0].value === 'Added';
        },
        unreleased() {
            if (!(this.root.children[4] && this.root.children[4].type === 'list')) {
                // probably we should create it?
                return false;
            }
            return this.root.children[4];
        },
        added(value) {
            let result = false;
            if (!this.addedHeaderExists()) {
                inject('Unreleased', this.root, remark.parse('### Added\n'));
            }
            const unreleasedAST = this.unreleased();
            if ( unreleasedAST ) {
                const toAdd = remark.parse(value);
                unreleasedAST.children.push(toAdd.children[0].children[0]); // add 'each' children.children?
                const astToString = remark.stringify(unreleasedAST);
                result = inject('Added', this.root, remark.parse(astToString));
            } else {
                result = inject('Added', this.root, remark.parse(value));
            }
            return result;
        }
    };
}
<|endoftext|>


<commit_before>define('parsley/form', [
  'parsley/abstract',
  'parsley/utils'
], function (ParsleyAbstract, ParsleyUtils) {
  var ParsleyForm = function (element, domOptions, options) {
    this.__class__ = 'ParsleyForm';
    this.__id__ = ParsleyUtils.generateID();

    this.$element = $(element);
    this.domOptions = domOptions;
    this.options = options;

    this.fields = [];
    this.validationResult = null;
  };

  ParsleyForm.prototype = {
    onSubmitValidate: function (event) {
      this.validate(undefined, undefined, event);

      // prevent form submission if validation fails
      if ((false === this.validationResult || !this._trigger('submit')) && event instanceof $.Event) {
        event.stopImmediatePropagation();
        event.preventDefault();
      }

      return this;
    },

    // @returns boolean
    validate: function (group, force, event) {
      this.submitEvent = event;
      this.validationResult = true;

      var fieldValidationResult = [];

      // fire validate event to eventually modify things before very validation
      this._trigger('validate');

      // Refresh form DOM options and form's fields that could have changed
      this._refreshFields();

      // loop through fields to validate them one by one
      for (var i = 0; i < this.fields.length; i++) {

        // do not validate a field if not the same as given validation group
        if (group && !this._isFieldInGroup(this.fields[i], group))
          continue;

        fieldValidationResult = this.fields[i].validate(force);

        if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult)
          this.validationResult = false;
      }

      this._trigger(this.validationResult ? 'success' : 'error');
      this._trigger('validated');

      return this.validationResult;
    },

    // Iterate over refreshed fields, and stop on first failure
    isValid: function (group, force) {
      this._refreshFields();

      for (var i = 0; i < this.fields.length; i++) {

        // do not validate a field if not the same as given validation group
        if (group && !this._isFieldInGroup(this.fields[i], group))
          continue;

        if (false === this.fields[i].isValid(force))
          return false;
      }

      return true;
    },

    _isFieldInGroup: function (field, group) {
      if($.isArray(field.options.group))
        return -1 !== $.inArray(group, field.options.group);
      return field.options.group === group;
    },

    _refreshFields: function () {
      return this.actualizeOptions()._bindFields();
    },

    _bindFields: function () {
      var self = this,
        oldFields = this.fields;

      this.fields = [];
      this.fieldsMappedById = {};

      this.$element.find(this.options.inputs).each(function () {
        var fieldInstance = new window.Parsley(this, {}, self);

        // Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
        if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && !fieldInstance.$element.is(fieldInstance.options.excluded))
          if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
            self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
            self.fields.push(fieldInstance);
          }
      });

      $(oldFields).not(self.fields).each(function () {
        this._trigger('reset');
        // If DOM element is detached or removed from the form, also trigger
        // at the form level:
        if (!jQuery.contains(self.$element[0], this.$element[0])) {
          self.$element.trigger('field:reset.parsley', [this]);
        }
      });
      return this;
    },

    // Internal only.
    // Shortcut to trigger an event
    // Returns true iff event is not interrupted and default not prevented.
    _trigger: function (eventName) {
      var event = jQuery.Event('form:' + eventName + '.parsley');
      this.$element.trigger(event, [this]);
      return !(event.isDefaultPrevented() || event.isImmediatePropagationStopped() || event.isPropagationStopped());
    }

  };

  return ParsleyForm;
});
<commit_msg>Avoid multiple form reactualizing [#855] Would be much nicer with block lambdas See http://yehudakatz.com/2012/01/10/javascript-needs-blocks/<commit_after>define('parsley/form', [
  'parsley/abstract',
  'parsley/utils'
], function (ParsleyAbstract, ParsleyUtils) {
  var ParsleyForm = function (element, domOptions, options) {
    this.__class__ = 'ParsleyForm';
    this.__id__ = ParsleyUtils.generateID();

    this.$element = $(element);
    this.domOptions = domOptions;
    this.options = options;

    this.fields = [];
    this.validationResult = null;
  };

  ParsleyForm.prototype = {
    onSubmitValidate: function (event) {
      this.validate(undefined, undefined, event);

      // prevent form submission if validation fails
      if ((false === this.validationResult || !this._trigger('submit')) && event instanceof $.Event) {
        event.stopImmediatePropagation();
        event.preventDefault();
      }

      return this;
    },

    // @returns boolean
    validate: function (group, force, event) {
      this.submitEvent = event;
      this.validationResult = true;

      var fieldValidationResult = [];

      // fire validate event to eventually modify things before very validation
      this._trigger('validate');

      // Refresh form DOM options and form's fields that could have changed
      this._refreshFields();

      this._withoutReactualizingFormOptions(function(){
      // loop through fields to validate them one by one
      for (var i = 0; i < this.fields.length; i++) {

        // do not validate a field if not the same as given validation group
        if (group && !this._isFieldInGroup(this.fields[i], group))
          continue;

        fieldValidationResult = this.fields[i].validate(force);

        if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult)
          this.validationResult = false;
      }
      });

      this._trigger(this.validationResult ? 'success' : 'error');
      this._trigger('validated');

      return this.validationResult;
    },

    // Iterate over refreshed fields, and stop on first failure
    isValid: function (group, force) {
      this._refreshFields();

      return this._withoutReactualizingFormOptions(function(){
      for (var i = 0; i < this.fields.length; i++) {

        // do not validate a field if not the same as given validation group
        if (group && !this._isFieldInGroup(this.fields[i], group))
          continue;

        if (false === this.fields[i].isValid(force))
          return false;
      }

      return true;
      });
    },

    _isFieldInGroup: function (field, group) {
      if($.isArray(field.options.group))
        return -1 !== $.inArray(group, field.options.group);
      return field.options.group === group;
    },

    _refreshFields: function () {
      return this.actualizeOptions()._bindFields();
    },

    _bindFields: function () {
      var self = this,
        oldFields = this.fields;

      this.fields = [];
      this.fieldsMappedById = {};

      this._withoutReactualizingFormOptions(function(){
      this.$element.find(this.options.inputs).each(function () {
        var fieldInstance = new window.Parsley(this, {}, self);

        // Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
        if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && !fieldInstance.$element.is(fieldInstance.options.excluded))
          if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
            self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
            self.fields.push(fieldInstance);
          }
      });

      $(oldFields).not(self.fields).each(function () {
        this._trigger('reset');
        // If DOM element is detached or removed from the form, also trigger
        // at the form level:
        if (!jQuery.contains(self.$element[0], this.$element[0])) {
          self.$element.trigger('field:reset.parsley', [this]);
        }
      });
      });
      return this;
    },

    // Internal only.
    // Looping on a form's fields to do validation or similar
    // will trigger reactualizing options on all of them, which
    // in turn will reactualize the form's options.
    // To avoid calling actualizeOptions so many times on the form
    // for nothing, _withoutReactualizingFormOptions temporarily disables
    // the method actualizeOptions on this form while `fn` is called.
    _withoutReactualizingFormOptions: function (fn) {
      var oldActualizeOptions = this.actualizeOptions;
      this.actualizeOptions = $.noop;
      var result = fn.call(this); // Keep the current `this`.
      this.actualizeOptions = oldActualizeOptions;
      return result;
    },

    // Internal only.
    // Shortcut to trigger an event
    // Returns true iff event is not interrupted and default not prevented.
    _trigger: function (eventName) {
      var event = jQuery.Event('form:' + eventName + '.parsley');
      this.$element.trigger(event, [this]);
      return !(event.isDefaultPrevented() || event.isImmediatePropagationStopped() || event.isPropagationStopped());
    }

  };

  return ParsleyForm;
});
<|endoftext|>


<commit_before>/* eslint-disable no-var, no-console */
var url = require('url')

if (process.env.NODE_ENV === 'development') {
  require('dotenv').load()
}

var run = !module.parent

function configure(dbUrl = process.env.RETHINKDB_URL, dbCert = process.env.RETHINKDB_CERT) {
  var dbConfig
  var parsedUrl = url.parse(dbUrl)
  dbConfig = {
    host: parsedUrl.hostname,
    port: parseInt(parsedUrl.port, 10),
    db: parsedUrl.pathname ? parsedUrl.pathname.slice(1) : undefined,
    authKey: parsedUrl.auth ? parsedUrl.auth.split(':')[1] : undefined,
  }
  if (dbCert) {
    dbConfig.ssl = {
      ca: dbCert
    }
  }

  return dbConfig
}

var createOptions = {
  replicas: (process.env.NODE_ENV === 'production') ? 3 : 1
}

if (run) {
  console.log(JSON.stringify(configure()))
}

module.exports = configure
module.exports.createOptions = createOptions
<commit_msg>ES5 compatibility<commit_after>/* eslint-disable no-var, no-console */
var url = require('url')

if (process.env.NODE_ENV === 'development') {
  require('dotenv').load()
}

var run = !module.parent

function configure(dbUrl, dbCert) {
  dbUrl = dbUrl || process.env.RETHINKDB_URL
  dbCert = dbCert || process.env.RETHINKDB_CERT
  var dbConfig
  var parsedUrl = url.parse(dbUrl)
  dbConfig = {
    host: parsedUrl.hostname,
    port: parseInt(parsedUrl.port, 10),
    db: parsedUrl.pathname ? parsedUrl.pathname.slice(1) : undefined,
    authKey: parsedUrl.auth ? parsedUrl.auth.split(':')[1] : undefined,
  }
  if (dbCert) {
    dbConfig.ssl = {
      ca: dbCert
    }
  }

  return dbConfig
}

var createOptions = {
  replicas: (process.env.NODE_ENV === 'production') ? 3 : 1
}

if (run) {
  console.log(JSON.stringify(configure()))
}

module.exports = configure
module.exports.createOptions = createOptions
<|endoftext|>


<commit_before>var knex = require('knex')({
	client: 'mysql',
	connection: {
		host: '127.0.0.1',
		user: 'root',
		password: '',
		database: 'waypointdb',
		charset: 'utf8',
	}
});

var db = require('bookshelf')(knex);

db.knex.schema.hasTable('paths').then(function(exists) {
	if (!exists){
		db.knex.schema.createTable('paths', function(path){
			path.increments('id').primary();
			path.integer('creator_id');
			path.string('title', 100).unique();
			path.string('length', 100);
			path.string('description', 5000);
			path.string('estimated_time', 100);
			// Creates created_at and updated_at columns
			path.timestamps();
		}).then(function(table){
			console.log('Created table', table);
		});
	}
});

db.knex.schema.hasTable('waypoints').then(function(exists) {
	if (!exists) {
		db.knex.schema.createTable('waypoints', function(waypoint){
			waypoint.increments('id').primary();
			waypoint.integer('path_id');
			waypoint.integer('index_in_path');
			waypoint.float('latitude', 30);
			waypoint.float('longitude', 30);
			waypoint.string('title', 100);
			waypoint.string('description', 5000);
			// Creates created_at and updated_at columns
			waypoint.timestamps();
		}).then(function(table){
			console.log('Created table', table);
		});
	}
});

module.exports = db;
<commit_msg>update config file to connect with cleardb<commit_after>var knex = require('knex')({
	client: 'mysql',
	connection: {
		host: process.env.DATABASE_URL || '127.0.0.1',
		user: 'root',
		password: '',
		database: 'waypointdb',
		charset: 'utf8',
	}
});

var db = require('bookshelf')(knex);

db.knex.schema.hasTable('paths').then(function(exists) {
	if (!exists){
		db.knex.schema.createTable('paths', function(path){
			path.increments('id').primary();
			path.integer('creator_id');
			path.string('title', 100).unique();
			path.string('length', 100);
			path.string('description', 5000);
			path.string('estimated_time', 100);
			// Creates created_at and updated_at columns
			path.timestamps();
		}).then(function(table){
			console.log('Created table', table);
		});
	}
});

db.knex.schema.hasTable('waypoints').then(function(exists) {
	if (!exists) {
		db.knex.schema.createTable('waypoints', function(waypoint){
			waypoint.increments('id').primary();
			waypoint.integer('path_id');
			waypoint.integer('index_in_path');
			waypoint.float('latitude', 30);
			waypoint.float('longitude', 30);
			waypoint.string('title', 100);
			waypoint.string('description', 5000);
			// Creates created_at and updated_at columns
			waypoint.timestamps();
		}).then(function(table){
			console.log('Created table', table);
		});
	}
});

module.exports = db;
<|endoftext|>


<commit_before>'use strict'

const {connect, disconnect} = require('./database')

const user = require('../models/user')

connect()

.then(()=> user.remove({}))
.then(()=> user.insertMany({}))

.catch(console.error)
.then(disconnect)
<commit_msg>added comment to seed file<commit_after>'use strict'
// comment
const {connect, disconnect} = require('./database')

const user = require('../models/user')

connect()

.then(()=> user.remove({}))
.then(()=> user.insertMany({}))

.catch(console.error)
.then(disconnect)
<|endoftext|>


<commit_before>import 'babel-polyfill';
import Aws from 'aws-sdk';
import path from 'path';
import fs from 'fs';
import ulid from 'ulid';

const gm = require('gm').subClass({ imageMagick: true });

const s3 = new Aws.S3();

const downloadImage = params =>
   new Promise((resolve, reject) => {
     console.log('downloadImage start...');
     const destPath = path.join('/tmp', (new Date()).getTime().toString());
     s3.getObject(params).promise()
      .then((data) => {
        fs.writeFileSync(destPath, data.Body);
        return resolve(destPath);
      })
      .catch(err => reject(err));
   })
;

const imageInfo = imagePath =>
   new Promise((resolve, reject) => {
     console.log('imageInfo start...');
     gm(imagePath)
      .identify((err, info) => {
        if (err) return reject(err);
        console.log('Source image info: %j', info);
        return resolve(info);
      });
   })
;

const resizeImage = (imagePath, info) =>
   new Promise((resolve, reject) => {
     console.log('resizeImage start...');
     const resizeOpts = /^(\d+)x(\d+)([%@!<>])?$/g.exec(process.env.RESIZE_OPTION);

     gm(imagePath)
      .resize(resizeOpts[1], resizeOpts[2], resizeOpts[3])
      .toBuffer(info.format, (err, buffer) => (
        err ? reject(err) : resolve(buffer)
      ));
   })
;

const uploadImage = (buffer, info) =>
   new Promise((resolve, reject) => {
     console.log('uploadImage start...');
     const params = {
       Bucket: process.env.DEST_S3_BUCKET_NAME,
       Key: `${process.env.DEST_S3_PREFIX}/${ulid()}.${info.format}`,
       Body: buffer,
       ContentType: info['Mime type'],
     };

     s3.upload(params, (err, data) => (
       err ? reject(err) : resolve(data)
     ));
   })
;

export default async (event) => {
  const imagePath = await downloadImage({
    Bucket: event.bucket.name,
    Key: event.object.key,
  });
  const info = await imageInfo(imagePath);
  const imageBuffer = await resizeImage(imagePath, info);
  const result = await uploadImage(imageBuffer, info);
  return result;
};

<commit_msg>Require `dotenv` to use environment variables in AWS Lambda.<commit_after>import 'babel-polyfill';
import dotenv from 'dotenv';
import Aws from 'aws-sdk';
import path from 'path';
import fs from 'fs';
import ulid from 'ulid';

dotenv.config();

const gm = require('gm').subClass({ imageMagick: true });
const s3 = new Aws.S3();

const downloadImage = params =>
   new Promise((resolve, reject) => {
     console.log('downloadImage start...');
     const destPath = path.join('/tmp', (new Date()).getTime().toString());
     s3.getObject(params).promise()
      .then((data) => {
        fs.writeFileSync(destPath, data.Body);
        return resolve(destPath);
      })
      .catch(err => reject(err));
   })
;

const imageInfo = imagePath =>
   new Promise((resolve, reject) => {
     console.log('imageInfo start...');
     gm(imagePath)
      .identify((err, info) => {
        if (err) return reject(err);
        console.log('Source image info: %j', info);
        return resolve(info);
      });
   })
;

const resizeImage = (imagePath, info) =>
   new Promise((resolve, reject) => {
     console.log('resizeImage start...');
     const resizeOpts = /^(\d+)x(\d+)([%@!<>])?$/g.exec(process.env.RESIZE_OPTION);

     gm(imagePath)
      .resize(resizeOpts[1], resizeOpts[2], resizeOpts[3])
      .toBuffer(info.format, (err, buffer) => (
        err ? reject(err) : resolve(buffer)
      ));
   })
;

const uploadImage = (buffer, info) =>
   new Promise((resolve, reject) => {
     console.log('uploadImage start...');
     const params = {
       Bucket: process.env.DEST_S3_BUCKET_NAME,
       Key: `${process.env.DEST_S3_PREFIX}/${ulid()}.${info.format}`,
       Body: buffer,
       ContentType: info['Mime type'],
     };

     s3.upload(params, (err, data) => (
       err ? reject(err) : resolve(data)
     ));
   })
;

export default async (event) => {
  const imagePath = await downloadImage({
    Bucket: event.bucket.name,
    Key: event.object.key,
  });
  const info = await imageInfo(imagePath);
  const imageBuffer = await resizeImage(imagePath, info);
  const result = await uploadImage(imageBuffer, info);
  return result;
};

<|endoftext|>


<commit_before>import styleMaps from './style-maps.js';

export default class PhotonMixin {
	static getPtClassSet() {
		const classes = {};
		const ptClass = this.props.ptClass && styleMaps.CLASSES[this.props.ptClass];

		if (ptClass) {
			classes[ptClass] = true;
			const prefix = '#{ptClass}-';
			const ptSize = this.props.ptSize && styleMaps.SIZES[this.props.ptSize];

			if (ptSize) {
				classes[prefix + ptSize] = true;
			}

			if (this.props.ptStyle) {
				if (styleMaps.STYLES.indexOf(this.props.ptStyle) >= 0) {
					classes[prefix + this.props.ptStyle] = true;
				} else {
					classes[this.props.ptStyle] = true;
				}
			}

			const ptType = this.props.ptType && styleMaps.TYPES[this.props.ptType];
			if (ptType) {
				classes[prefix + ptType] = true;
			}

			return classes;
		}
	}
}
<commit_msg>Fix PhotonMixin: not static<commit_after>import styleMaps from './style-maps.js';

export default class PhotonMixin {
	getPtClassSet() {
		const classes = {};
		const ptClass = this.props.ptClass && styleMaps.CLASSES[this.props.ptClass];

		if (ptClass) {
			classes[ptClass] = true;
			const prefix = '#{ptClass}-';
			const ptSize = this.props.ptSize && styleMaps.SIZES[this.props.ptSize];

			if (ptSize) {
				classes[prefix + ptSize] = true;
			}

			if (this.props.ptStyle) {
				if (styleMaps.STYLES.indexOf(this.props.ptStyle) >= 0) {
					classes[prefix + this.props.ptStyle] = true;
				} else {
					classes[this.props.ptStyle] = true;
				}
			}

			const ptType = this.props.ptType && styleMaps.TYPES[this.props.ptType];
			if (ptType) {
				classes[prefix + ptType] = true;
			}

			return classes;
		}
	}
}
<|endoftext|>


<commit_before>PiCard.Chart = PiCard.defineClass(
    [ PiCard.Configurable, PiCard.Localized ],

    function(container, data, options) {
        PiCard.Configurable.call(this, options);
        PiCard.Localized.call(this, this.options.locale);
        this.container = container;
        this.data = data;
        this.initialize();
    },

    {
        defaultOptions: {
            axisWidth:          1,
            plotPadding:        10,
            labelMargin:        10,
            plotMarkerSize:     6,
            plotMarkerWidth:    1,
            minPieRadius:       2,
            maxPieRadius:       20,
            startAngle:         -90,
            clockwise:          true,
            drawAllPlotMarkers: false,
            dotScale:           "quad",
            legendFormat:       "{0} ({1})",
            fontFamily:         "Verdana, Arial, Helvetica, sans-serif",
            fontSize:           12,
            activeOpacity:      1.0,
            inactiveOpacity:    0.2,
            axisColor:          "#666",
            plotMarkerColor:    "#999",
            axisLabelColor:     "#666",
            pieColors:          [
                "#C90", "#0C9", "#90C", "#9C0", "#09C", "#C09",
                "#C00", "#0C0", "#00C", "#099", "#909", "#990",
                "#C66", "#6C6", "#66C", "#999"
            ],
            usersKey:           ".users"
        },

        initialize: function() {
            var that = this;
            that.determineUserNames();
            that.calculateTotals();
            that.determineMaximum();
            that.setUserColors();
            that.calculateMeasurements();
            that.createPlotArea();
            that.createPlots();
            that.createAxes();
            that.createLegend();
            that.prepareContainer();
            that.createStage();
            that.container.trigger("picard.ready", [ that ]);
        },

        determineUserNames: function() {
            var that = this;
            if (that.options.usersKey !== undefined
                    && that.options.usersKey in that.data) {
                that.users = that.data[that.options.usersKey];
                delete that.data[that.options.usersKey];
            } else {
                that.users = that.sortUserNames();
            }
        },

        sortUserNames: function() {
            var that = this;
            var users = [];
            $.each(that.data, function(user, perDay) {
                users.push(user);
            });
            users.sort();
            return users;
        },

        prepareContainer: function() {
            var that = this;
            var id = that.container.attr("id") + "-chart";
            that.chartContainer = $("<div>")
                .attr("class", "picard-chart")
                .attr("id", id);
            that.container
                .empty()
                .append(that.legend)
                .append(that.chartContainer);
        },

        createStage: function() {
            var that = this;
            that.stage = new Kinetic.Stage({
                container: that.chartContainer.attr("id"),
                width:     that.measure.width,
                height:    that.measure.height
            });
            that.stage.add(that.plotArea);
            $.each(that.plots, function(user, plot) {
                that.stage.add(plot);
            });
            that.stage.add(that.axes);
        },

        createLegend: function() {
            var that = this;
            var userTotals = {};
            var grandTotal = 0;
            $.each(that.data, function(user, perDay) {
                var total = 0;
                $.each(perDay, function(d, perHour) {
                    $.each(perHour, function(h, amount) {
                        total += amount;
                    });
                });
                userTotals[user] = total;
                grandTotal += total;
            });
            that.legend = $("<div/>")
                .attr("class", "picard-legend")
                .append($("<span/>")
                    .attr("class", "picard-legend-label")
                    .text(that.locale.summaryLabel + " "
                        + that.formatNumber(grandTotal)));
            $.each(that.users, function(i, user) {
                var strings = [
                    user,
                    that.formatNumber(userTotals[user])
                ];
                var code = that.options.legendFormat.replace(
                    /\{([0-9]+)\}/g,
                    function(m0, m1) {
                        return strings[parseInt(m1, 10)];
                    });
                that.legend.append(" ");
                that.legend.append($("<span>")
                    .attr("class", "picard-legend-item")
                    .css("color", that.userColors[user])
                    .mouseover({ user: user, that: that }, that.setActive)
                    .mouseout({ user: null, that: that }, that.setActive)
                    .html(code));
            });
        },

        setActive: function(event) {
            var user = event.data.user;
            var that = event.data.that;
            that.container.trigger("picard.activate", [ that, user ]);
            $.each(that.plots, function(u, plot) {
                that.setOpacity(plot, (user === null || user == u)
                    ? that.options.activeOpacity
                    : that.options.inactiveOpacity);
            });
            that.setOpacity(that.plotArea, (user === null)
                ? that.options.activeOpacity
                : that.options.inactiveOpacity);
        },

        setOpacity: function(layer, opacity) {
            var that = this;
            if (layer.getOpacity() != opacity) {
                layer.setOpacity(opacity);
                layer.draw();
            }
        },

        createPlotArea: function() {
            var that = this;
            that.plotArea = new Kinetic.Layer();
            var x0 = that.measure.yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + that.options.plotPadding
                + that.options.maxPieRadius;
            var y = that.options.plotPadding + that.options.maxPieRadius;
            var s = that.options.plotMarkerSize / 2;
            for (var d = 0; d < 7; d++) {
                var x = x0;
                for (var h = 0; h < 24; h++) {
                    if (that.options.drawAllPlotMarkers || !that.totals[d][h]) {
                        that.plotArea.add(new Kinetic.Line({
                            points:      [ x - s, y, x + s, y ],
                            stroke:      that.options.plotMarkerColor,
                            strokeWidth: that.options.plotMarkerWidth
                        }));
                        that.plotArea.add(new Kinetic.Line({
                            points:      [ x, y - s, x, y + s ],
                            stroke:      that.options.plotMarkerColor,
                            strokeWidth: that.options.plotMarkerWidth
                        }));
                    }
                    x += that.options.maxPieRadius * 2;
                }
                y += that.options.maxPieRadius * 2;
            }
        },

        createPlots: function() {
            var that = this;
            that.plots = {};
            $.each(that.userColors, function(user, color) {
                that.plots[user] = new Kinetic.Layer();
                that.plots[user].setOpacity(that.options.activeOpacity);
            });
            var x0 = that.measure.yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + that.options.plotPadding
                + that.options.maxPieRadius;
            var y = that.options.plotPadding + that.options.maxPieRadius;
            for (var d = 0; d < 7; d++) {
                var x = x0;
                for (var h = 0; h < 24; h++) {
                    if (that.totals[d] && that.totals[d][h]) {
                        that.plotPie(d, h, x, y);
                    }
                    x += that.options.maxPieRadius * 2;
                }
                y += that.options.maxPieRadius * 2;
            }
        },

        plotPie: function(d, h, x, y) {
            var that = this;
            var total = that.totals[d][h];
            var ratio = that.getRatio(total);
            if (ratio <= 0) {
                return;
            }
            var radius = Math.max(that.options.minPieRadius,
                ratio * that.options.maxPieRadius);
            var angle = (that.options.startAngle === null)
                ? Math.random() * 360 : that.options.startAngle;
            $.each(that.data, function(user, perDay) {
                if (perDay[d] && perDay[d][h]) {
                    var degrees = 360 * (perDay[d][h] / total);
                    if (that.options.clockWise) {
                        degrees = -degrees;
                    }
                    var wedge = new Kinetic.Wedge({
                        x:           x,
                        y:           y,
                        radius:      radius,
                        rotationDeg: angle,
                        angleDeg:    degrees,
                        fill:        that.userColors[user]
                    });
                    that.plots[user].add(wedge);
                    angle += degrees;
                }
            });
        },

        getRatio: function(value) {
            var that = this;
            if (value <= 0) {
                return 0;
            }
            var transform = (that.options.scale == "quad") ? Math.sqrt
                : (that.options.scale == "log") ? Math.log
                : function(n) { return n; };
            return transform(value) / transform(that.maximum);
        },

        createAxes: function() {
            var that = this;
            that.axes = new Kinetic.Layer();
            that.createXAxis();
            that.createYAxis();
        },

        createXAxis: function(axes) {
            var that = this;
            that.axes.add(new Kinetic.Line({
                points:      [
                    that.measure.yLabelWidth + that.options.labelMargin,
                    that.measure.plotHeight + that.options.axisWidth / 2,
                    that.measure.width,
                    that.measure.plotHeight + that.options.axisWidth / 2
                ],
                stroke:      that.options.axisColor,
                strokeWidth: that.options.axisWidth
            }));
            var x = that.measure.yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + that.options.plotPadding
                + that.options.maxPieRadius;
            var y = that.measure.plotHeight + that.options.axisWidth
                + that.options.labelMargin;
            for (var h = 0; h < 24; h++) {
                var text = that.createText((h < 10) ? "0" + h : h,
                    x, y, that.options.axisLabelColor);
                text.setOffset({
                    x: text.getWidth() / 2
                });
                that.axes.add(text);
                x += that.options.maxPieRadius * 2;
            }
        },

        createYAxis: function() {
            var that = this;
            that.axes.add(new Kinetic.Line({
                points:      [
                    that.measure.yLabelWidth + that.options.labelMargin
                        + that.options.axisWidth / 2,
                    0,
                    that.measure.yLabelWidth + that.options.labelMargin
                        + that.options.axisWidth / 2,
                    that.measure.plotHeight + that.options.axisWidth
                ],
                stroke:      that.options.axisColor,
                strokeWidth: that.options.axisWidth
            }));
            var x = that.measure.yLabelWidth;
            var y = that.options.plotPadding + that.options.maxPieRadius
                - that.measure.labelHeight / 2;
            for (var d = 0; d < 7; d++) {
                var text = that.createText(that.locale.dayNames[d],
                    x, y, that.options.axisLabelColor);
                text.setOffset({
                    x: text.getWidth()
                });
                that.axes.add(text);
                y += that.options.maxPieRadius * 2;
            }
        },

        calculateTotals: function() {
            var that = this;
            that.totals = [];
            for (var d = 0; d < 7; d++) {
                var dayTotals = [];
                for (var h = 0; h < 24; h++) {
                    dayTotals[h] = 0;
                    $.each(that.data, function(user, perDay) {
                        if (perDay[d] && perDay[d][h]) {
                            dayTotals[h] += perDay[d][h];
                        }
                    });
                }
                that.totals[d] = dayTotals;
            }
        },

        determineMaximum: function() {
            var that = this;
            that.maximum = 0;
            for (var d = 0; d < 7; d++) {
                for (var h = 0; h < 24; h++) {
                    if (that.totals[d] && that.totals[d][h]) {
                        that.maximum = Math.max(that.maximum, that.totals[d][h]);
                    }
                }
            }
        },

        setUserColors: function() {
            var that = this;
            that.userColors = {};
            $.each(that.users, function(i, user) {
                that.userColors[user]
                    = that.options.pieColors[i % that.options.pieColors.length];
            });
        },

        calculateMeasurements: function() {
            var that = this;
            var yLabelWidth = 0;
            for (var d = 0; d < 7; d++) {
                var text = that.createText(that.locale.dayNames[d], 0, 0, "black");
                yLabelWidth = Math.max(yLabelWidth, text.getWidth());
            }
            var labelHeight = that.createText("X", 0, 0, "black").getHeight();

            var plotWidth = that.options.plotPadding
                + that.options.maxPieRadius * 2 * 24 + that.options.plotPadding;
            var plotHeight = that.options.plotPadding
                + that.options.maxPieRadius * 2 * 7 + that.options.plotPadding;
            var width = yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + plotWidth;
            var height = plotHeight + that.options.axisWidth
                + that.options.labelMargin + labelHeight;

            that.measure = {
                width:       width,
                height:      height,
                plotWidth:   plotWidth,
                plotHeight:  plotHeight,
                yLabelWidth: yLabelWidth,
                labelHeight: labelHeight
            };
        },

        createText: function(text, x, y, color) {
            var that = this;
            return new Kinetic.Text({
                text:       text,
                fontFamily: that.options.fontFamily,
                fontSize:   that.options.fontSize,
                fill:       color,
                x:          x,
                y:          y
            });
        }
    }
);
<commit_msg>Supporting custom user colors<commit_after>PiCard.Chart = PiCard.defineClass(
    [ PiCard.Configurable, PiCard.Localized ],

    function(container, data, options) {
        PiCard.Configurable.call(this, options);
        PiCard.Localized.call(this, this.options.locale);
        this.container = container;
        this.data = data;
        this.initialize();
    },

    {
        defaultOptions: {
            axisWidth:          1,
            plotPadding:        10,
            labelMargin:        10,
            plotMarkerSize:     6,
            plotMarkerWidth:    1,
            minPieRadius:       2,
            maxPieRadius:       20,
            startAngle:         -90,
            clockwise:          true,
            drawAllPlotMarkers: false,
            dotScale:           "quad",
            legendFormat:       "{0} ({1})",
            fontFamily:         "Verdana, Arial, Helvetica, sans-serif",
            fontSize:           12,
            activeOpacity:      1.0,
            inactiveOpacity:    0.2,
            axisColor:          "#666",
            plotMarkerColor:    "#999",
            axisLabelColor:     "#666",
            pieColors:          [
                "#C90", "#0C9", "#90C", "#9C0", "#09C", "#C09",
                "#C00", "#0C0", "#00C", "#099", "#909", "#990",
                "#C66", "#6C6", "#66C", "#999"
            ],
            userColors:         {},
            usersKey:           ".users"
        },

        initialize: function() {
            var that = this;
            that.determineUserNames();
            that.calculateTotals();
            that.determineMaximum();
            that.setUserColors();
            that.calculateMeasurements();
            that.createPlotArea();
            that.createPlots();
            that.createAxes();
            that.createLegend();
            that.prepareContainer();
            that.createStage();
            that.container.trigger("picard.ready", [ that ]);
        },

        determineUserNames: function() {
            var that = this;
            if (that.options.usersKey !== undefined
                    && that.options.usersKey in that.data) {
                that.users = that.data[that.options.usersKey];
                delete that.data[that.options.usersKey];
            } else {
                that.users = that.sortUserNames();
            }
        },

        sortUserNames: function() {
            var that = this;
            var users = [];
            $.each(that.data, function(user, perDay) {
                users.push(user);
            });
            users.sort();
            return users;
        },

        prepareContainer: function() {
            var that = this;
            var id = that.container.attr("id") + "-chart";
            that.chartContainer = $("<div>")
                .attr("class", "picard-chart")
                .attr("id", id);
            that.container
                .empty()
                .append(that.legend)
                .append(that.chartContainer);
        },

        createStage: function() {
            var that = this;
            that.stage = new Kinetic.Stage({
                container: that.chartContainer.attr("id"),
                width:     that.measure.width,
                height:    that.measure.height
            });
            that.stage.add(that.plotArea);
            $.each(that.plots, function(user, plot) {
                that.stage.add(plot);
            });
            that.stage.add(that.axes);
        },

        createLegend: function() {
            var that = this;
            var userTotals = {};
            var grandTotal = 0;
            $.each(that.data, function(user, perDay) {
                var total = 0;
                $.each(perDay, function(d, perHour) {
                    $.each(perHour, function(h, amount) {
                        total += amount;
                    });
                });
                userTotals[user] = total;
                grandTotal += total;
            });
            that.legend = $("<div/>")
                .attr("class", "picard-legend")
                .append($("<span/>")
                    .attr("class", "picard-legend-label")
                    .text(that.locale.summaryLabel + " "
                        + that.formatNumber(grandTotal)));
            $.each(that.users, function(i, user) {
                var strings = [
                    user,
                    that.formatNumber(userTotals[user])
                ];
                var code = that.options.legendFormat.replace(
                    /\{([0-9]+)\}/g,
                    function(m0, m1) {
                        return strings[parseInt(m1, 10)];
                    });
                that.legend.append(" ");
                that.legend.append($("<span>")
                    .attr("class", "picard-legend-item")
                    .css("color", that.userColors[user])
                    .mouseover({ user: user, that: that }, that.setActive)
                    .mouseout({ user: null, that: that }, that.setActive)
                    .html(code));
            });
        },

        setActive: function(event) {
            var user = event.data.user;
            var that = event.data.that;
            that.container.trigger("picard.activate", [ that, user ]);
            $.each(that.plots, function(u, plot) {
                that.setOpacity(plot, (user === null || user == u)
                    ? that.options.activeOpacity
                    : that.options.inactiveOpacity);
            });
            that.setOpacity(that.plotArea, (user === null)
                ? that.options.activeOpacity
                : that.options.inactiveOpacity);
        },

        setOpacity: function(layer, opacity) {
            var that = this;
            if (layer.getOpacity() != opacity) {
                layer.setOpacity(opacity);
                layer.draw();
            }
        },

        createPlotArea: function() {
            var that = this;
            that.plotArea = new Kinetic.Layer();
            var x0 = that.measure.yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + that.options.plotPadding
                + that.options.maxPieRadius;
            var y = that.options.plotPadding + that.options.maxPieRadius;
            var s = that.options.plotMarkerSize / 2;
            for (var d = 0; d < 7; d++) {
                var x = x0;
                for (var h = 0; h < 24; h++) {
                    if (that.options.drawAllPlotMarkers || !that.totals[d][h]) {
                        that.plotArea.add(new Kinetic.Line({
                            points:      [ x - s, y, x + s, y ],
                            stroke:      that.options.plotMarkerColor,
                            strokeWidth: that.options.plotMarkerWidth
                        }));
                        that.plotArea.add(new Kinetic.Line({
                            points:      [ x, y - s, x, y + s ],
                            stroke:      that.options.plotMarkerColor,
                            strokeWidth: that.options.plotMarkerWidth
                        }));
                    }
                    x += that.options.maxPieRadius * 2;
                }
                y += that.options.maxPieRadius * 2;
            }
        },

        createPlots: function() {
            var that = this;
            that.plots = {};
            $.each(that.userColors, function(user, color) {
                that.plots[user] = new Kinetic.Layer();
                that.plots[user].setOpacity(that.options.activeOpacity);
            });
            var x0 = that.measure.yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + that.options.plotPadding
                + that.options.maxPieRadius;
            var y = that.options.plotPadding + that.options.maxPieRadius;
            for (var d = 0; d < 7; d++) {
                var x = x0;
                for (var h = 0; h < 24; h++) {
                    if (that.totals[d] && that.totals[d][h]) {
                        that.plotPie(d, h, x, y);
                    }
                    x += that.options.maxPieRadius * 2;
                }
                y += that.options.maxPieRadius * 2;
            }
        },

        plotPie: function(d, h, x, y) {
            var that = this;
            var total = that.totals[d][h];
            var ratio = that.getRatio(total);
            if (ratio <= 0) {
                return;
            }
            var radius = Math.max(that.options.minPieRadius,
                ratio * that.options.maxPieRadius);
            var angle = (that.options.startAngle === null)
                ? Math.random() * 360 : that.options.startAngle;
            $.each(that.data, function(user, perDay) {
                if (perDay[d] && perDay[d][h]) {
                    var degrees = 360 * (perDay[d][h] / total);
                    if (that.options.clockWise) {
                        degrees = -degrees;
                    }
                    var wedge = new Kinetic.Wedge({
                        x:           x,
                        y:           y,
                        radius:      radius,
                        rotationDeg: angle,
                        angleDeg:    degrees,
                        fill:        that.userColors[user]
                    });
                    that.plots[user].add(wedge);
                    angle += degrees;
                }
            });
        },

        getRatio: function(value) {
            var that = this;
            if (value <= 0) {
                return 0;
            }
            var transform = (that.options.scale == "quad") ? Math.sqrt
                : (that.options.scale == "log") ? Math.log
                : function(n) { return n; };
            return transform(value) / transform(that.maximum);
        },

        createAxes: function() {
            var that = this;
            that.axes = new Kinetic.Layer();
            that.createXAxis();
            that.createYAxis();
        },

        createXAxis: function(axes) {
            var that = this;
            that.axes.add(new Kinetic.Line({
                points:      [
                    that.measure.yLabelWidth + that.options.labelMargin,
                    that.measure.plotHeight + that.options.axisWidth / 2,
                    that.measure.width,
                    that.measure.plotHeight + that.options.axisWidth / 2
                ],
                stroke:      that.options.axisColor,
                strokeWidth: that.options.axisWidth
            }));
            var x = that.measure.yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + that.options.plotPadding
                + that.options.maxPieRadius;
            var y = that.measure.plotHeight + that.options.axisWidth
                + that.options.labelMargin;
            for (var h = 0; h < 24; h++) {
                var text = that.createText((h < 10) ? "0" + h : h,
                    x, y, that.options.axisLabelColor);
                text.setOffset({
                    x: text.getWidth() / 2
                });
                that.axes.add(text);
                x += that.options.maxPieRadius * 2;
            }
        },

        createYAxis: function() {
            var that = this;
            that.axes.add(new Kinetic.Line({
                points:      [
                    that.measure.yLabelWidth + that.options.labelMargin
                        + that.options.axisWidth / 2,
                    0,
                    that.measure.yLabelWidth + that.options.labelMargin
                        + that.options.axisWidth / 2,
                    that.measure.plotHeight + that.options.axisWidth
                ],
                stroke:      that.options.axisColor,
                strokeWidth: that.options.axisWidth
            }));
            var x = that.measure.yLabelWidth;
            var y = that.options.plotPadding + that.options.maxPieRadius
                - that.measure.labelHeight / 2;
            for (var d = 0; d < 7; d++) {
                var text = that.createText(that.locale.dayNames[d],
                    x, y, that.options.axisLabelColor);
                text.setOffset({
                    x: text.getWidth()
                });
                that.axes.add(text);
                y += that.options.maxPieRadius * 2;
            }
        },

        calculateTotals: function() {
            var that = this;
            that.totals = [];
            for (var d = 0; d < 7; d++) {
                var dayTotals = [];
                for (var h = 0; h < 24; h++) {
                    dayTotals[h] = 0;
                    $.each(that.data, function(user, perDay) {
                        if (perDay[d] && perDay[d][h]) {
                            dayTotals[h] += perDay[d][h];
                        }
                    });
                }
                that.totals[d] = dayTotals;
            }
        },

        determineMaximum: function() {
            var that = this;
            that.maximum = 0;
            for (var d = 0; d < 7; d++) {
                for (var h = 0; h < 24; h++) {
                    if (that.totals[d] && that.totals[d][h]) {
                        that.maximum = Math.max(that.maximum, that.totals[d][h]);
                    }
                }
            }
        },

        setUserColors: function() {
            var that = this;
            that.userColors = {};
            var i = 0;
            var numPieColors = that.options.pieColors.length;
            $.each(that.users, function(idx, user) {
                that.userColors[user] = that.options.userColors[user]
                    || that.options.pieColors[i++ % numPieColors];
            });
        },

        calculateMeasurements: function() {
            var that = this;
            var yLabelWidth = 0;
            for (var d = 0; d < 7; d++) {
                var text = that.createText(that.locale.dayNames[d], 0, 0, "black");
                yLabelWidth = Math.max(yLabelWidth, text.getWidth());
            }
            var labelHeight = that.createText("X", 0, 0, "black").getHeight();

            var plotWidth = that.options.plotPadding
                + that.options.maxPieRadius * 2 * 24 + that.options.plotPadding;
            var plotHeight = that.options.plotPadding
                + that.options.maxPieRadius * 2 * 7 + that.options.plotPadding;
            var width = yLabelWidth + that.options.labelMargin
                + that.options.axisWidth + plotWidth;
            var height = plotHeight + that.options.axisWidth
                + that.options.labelMargin + labelHeight;

            that.measure = {
                width:       width,
                height:      height,
                plotWidth:   plotWidth,
                plotHeight:  plotHeight,
                yLabelWidth: yLabelWidth,
                labelHeight: labelHeight
            };
        },

        createText: function(text, x, y, color) {
            var that = this;
            return new Kinetic.Text({
                text:       text,
                fontFamily: that.options.fontFamily,
                fontSize:   that.options.fontSize,
                fill:       color,
                x:          x,
                y:          y
            });
        }
    }
);
<|endoftext|>


<commit_before>define(function () {

  /**
   * An unordered list is created via typing '*' or '-' followed
   * immediately by a space. An ordered list is created by typing '1.'
   * followed by a space. Text after the trigger does not matter, so
   *
1.|Stuff
 (where | is the caret) and pressing space will
   * still make a list whose first item is 'Stuff'.
   */

  function onKeydown (e) {
    var container = this.selection.getContaining(),
        sel = window.getSelection(),
        range,
        marker,
        list,
        text,
        li

    if (!container || !sel.isCollapsed) return

    range = sel.getRangeAt(0).cloneRange()

    if (e.keyCode === 32 && container.nodeName === 'P') {
      // Space bar.

      // Get text:
      range.setStartBefore(container)
      text = range.cloneContents().firstChild.textContent

      // TODO: I can't seem to make a RegExp that works for this.
      if (text !== '1.' && text !== '*' && text !== '-') return

      // The space bar just creates the list; we don't actually want
      // to insert a space.
      e.preventDefault()

      // Place marker (there should only be one):
      this.selection.placeMarkers()
      marker = this.selection.getMarkers()[0]

      // Placing the marker will have split the text, so the previous
      // sibling will be the '1.' or whatever else.
      while (marker.previousSibling)
        marker.parentNode.removeChild(marker.previousSibling)

      // Turn our
 into a

      li = document.createElement('li')

      while (container.firstChild)
        li.appendChild(container.removeChild(container.firstChild))

      // Insert a
 if necessary (no textContent and no existing
)
      if (!li.textContent && !li.querySelector('br')) {
        marker.parentNode
          .insertBefore(document.createElement('br'), marker.nextSibling)
      }

      // Make the new list. Merging of consecutive lists is handled by
      // the sanitizer filter, so we don't bother checking that here.
      list = text === '1.' ? 'ol' : 'ul'
      list = document.createElement(list)
      list.appendChild(li)

      this.elem.replaceChild(list, container)

      this.selection.selectMarkers()

      // Trigger change if necessary.
      this.emit('input')

    } else if (e.keyCode === 8 || e.keyCode === 13) {
      // Backspace or enter.

      // Get the parent list element, if applicable.
      container = this.selection.childOf(/^LI$/i)

      if (!container) return

      if ((e.keyCode === 8 && this.selection.atStartOf(container)) ||
          (e.keyCode === 13 && !container.textContent)) {
        e.preventDefault()

        this.list.splitList(container)

        this.emit('input')
      }
    }
  }

  function autoList (Quill) {
    this.selection = Quill.selection
    this.elem = Quill.elem

    // Store bound event handlers for later removal.
    this.onKeydown = onKeydown.bind(Quill)

    this.elem.addEventListener('keydown', this.onKeydown)

    Quill.sanitizer
      .addElements(['ol', 'ul', 'li'])
      .addFilter(function (params) {
        var elem = params.node,
            name = params.node_name,
            node,
            next,
            li

        if (!/^[ou]l$/.test(name)) return null

        // Merge consecutive lists.
        node = elem.nextSibling
        while (node && node.nodeName === elem.nodeName) {
          next = node.nextSibling

          while (node.firstChild)
            elem.appendChild(node.removeChild(node.firstChild))

          node.parentNode.removeChild(node)

          node = next
        }

        // Wrap all children in
s, if applicable.
        node = elem.firstChild
        while (node) {

          if (node.nodeName !== 'LI') {
            li = document.createElement('li')
            li.appendChild(node.cloneNode(true))

            // Consecutive non-
 nodes get merged into a single
.
            while (node.nextSibling && node.nextSibling.nodeName !== 'LI')
              li.appendChild(elem.removeChild(node.nextSibling))

            next = node.nextSibling
            elem.replaceChild(li, node)
            node = next

          } else node = node.nextSibling
        }
      })
  }

  /**
   * splitList(listItem) splits a list at the given
. The
 is
   * transformed into a
. If no
s remain in the list, the list
   * is removed.
   *
   * @param {Element} listItem
   */
  autoList.prototype.splitList = function (listItem) {
    var parent = listItem.parentNode,
        listType = parent.nodeName,
        before,
        after,
        node,
        next,
        p

    if (!/^[OU]L$/.test(listType)) return

    this.selection.placeMarkers()

    before = document.createElement(listType)
    after = document.createElement(listType)

    node = parent.firstChild
    next = node.nextSibling
    while (node !== listItem) {
      before.appendChild(parent.removeChild(node))
      node = next
      if (node) next = node.nextSibling
    }

    if (before.childNodes.length)
      parent.parentNode.insertBefore(before, parent)

    node = listItem.nextSibling
    while (node) {
      next = node.nextSibling
      after.appendChild(parent.removeChild(node))
      node = next
    }

    if (after.childNodes.length)
      parent.parentNode.insertBefore(after, parent.nextSibling)

    // Turn the list item into a paragraph.
    p = document.createElement('p')
    while (listItem.firstChild)
      p.appendChild(listItem.removeChild(listItem.firstChild))

    // Replace the
's parent with the new paragraph.
    parent.parentNode.replaceChild(p, parent)

    this.selection.selectMarkers()

    return p
  }

  autoList.prototype.destroy = function () {
    this.elem.removeEventListener('keydown', this.onKeydown)
  }

  // Plugin name:
  autoList.plugin = 'list'

  return autoList
})<commit_msg>Optionally disregard selection in list.splitList( )<commit_after>define(function () {

  /**
   * An unordered list is created via typing '*' or '-' followed
   * immediately by a space. An ordered list is created by typing '1.'
   * followed by a space. Text after the trigger does not matter, so
   *
1.|Stuff
 (where | is the caret) and pressing space will
   * still make a list whose first item is 'Stuff'.
   */

  function onKeydown (e) {
    var container = this.selection.getContaining(),
        sel = window.getSelection(),
        range,
        marker,
        list,
        text,
        li

    if (!container || !sel.isCollapsed) return

    range = sel.getRangeAt(0).cloneRange()

    if (e.keyCode === 32 && container.nodeName === 'P') {
      // Space bar.

      // Get text:
      range.setStartBefore(container)
      text = range.cloneContents().firstChild.textContent

      // TODO: I can't seem to make a RegExp that works for this.
      if (text !== '1.' && text !== '*' && text !== '-') return

      // The space bar just creates the list; we don't actually want
      // to insert a space.
      e.preventDefault()

      // Place marker (there should only be one):
      this.selection.placeMarkers()
      marker = this.selection.getMarkers()[0]

      // Placing the marker will have split the text, so the previous
      // sibling will be the '1.' or whatever else.
      while (marker.previousSibling)
        marker.parentNode.removeChild(marker.previousSibling)

      // Turn our
 into a

      li = document.createElement('li')

      while (container.firstChild)
        li.appendChild(container.removeChild(container.firstChild))

      // Insert a
 if necessary (no textContent and no existing
)
      if (!li.textContent && !li.querySelector('br')) {
        marker.parentNode
          .insertBefore(document.createElement('br'), marker.nextSibling)
      }

      // Make the new list. Merging of consecutive lists is handled by
      // the sanitizer filter, so we don't bother checking that here.
      list = text === '1.' ? 'ol' : 'ul'
      list = document.createElement(list)
      list.appendChild(li)

      this.elem.replaceChild(list, container)

      this.selection.selectMarkers()

      // Trigger change if necessary.
      this.emit('input')

    } else if (e.keyCode === 8 || e.keyCode === 13) {
      // Backspace or enter.

      // Get the parent list element, if applicable.
      container = this.selection.childOf(/^LI$/i)

      if (!container) return

      if ((e.keyCode === 8 && this.selection.atStartOf(container)) ||
          (e.keyCode === 13 && !container.textContent)) {
        e.preventDefault()

        this.list.splitList(container)

        this.emit('input')
      }
    }
  }

  function autoList (Quill) {
    this.selection = Quill.selection
    this.elem = Quill.elem

    // Store bound event handlers for later removal.
    this.onKeydown = onKeydown.bind(Quill)

    this.elem.addEventListener('keydown', this.onKeydown)

    Quill.sanitizer
      .addElements(['ol', 'ul', 'li'])
      .addFilter(function (params) {
        var elem = params.node,
            name = params.node_name,
            node,
            next,
            li

        if (!/^[ou]l$/.test(name)) return null

        // Merge consecutive lists.
        node = elem.nextSibling
        while (node && node.nodeName === elem.nodeName) {
          next = node.nextSibling

          while (node.firstChild)
            elem.appendChild(node.removeChild(node.firstChild))

          node.parentNode.removeChild(node)

          node = next
        }

        // Wrap all children in
s, if applicable.
        node = elem.firstChild
        while (node) {

          if (node.nodeName !== 'LI') {
            li = document.createElement('li')
            li.appendChild(node.cloneNode(true))

            // Consecutive non-
 nodes get merged into a single
.
            while (node.nextSibling && node.nextSibling.nodeName !== 'LI')
              li.appendChild(elem.removeChild(node.nextSibling))

            next = node.nextSibling
            elem.replaceChild(li, node)
            node = next

          } else node = node.nextSibling
        }
      })
  }

  /**
   * splitList(listItem) splits a list at the given
. The
 is
   * transformed into a
. If no
s remain in the list, the list
   * is removed. If rmSelection is true, the selection is disregarded.
   *
   * @param {Element} listItem
   * @param {Boolean} rmSelection
   */
  autoList.prototype.splitList = function (listItem, rmSelection) {
    var parent = listItem.parentNode,
        listType = parent.nodeName,
        before,
        after,
        node,
        next,
        p

    if (!/^[OU]L$/.test(listType)) return

    if (!rmSelection)
      this.selection.placeMarkers()

    before = document.createElement(listType)
    after = document.createElement(listType)

    node = parent.firstChild
    next = node.nextSibling
    while (node !== listItem) {
      before.appendChild(parent.removeChild(node))
      node = next
      if (node) next = node.nextSibling
    }

    if (before.childNodes.length)
      parent.parentNode.insertBefore(before, parent)

    node = listItem.nextSibling
    while (node) {
      next = node.nextSibling
      after.appendChild(parent.removeChild(node))
      node = next
    }

    if (after.childNodes.length)
      parent.parentNode.insertBefore(after, parent.nextSibling)

    // Turn the list item into a paragraph.
    p = document.createElement('p')
    while (listItem.firstChild)
      p.appendChild(listItem.removeChild(listItem.firstChild))

    // Replace the
's parent with the new paragraph.
    parent.parentNode.replaceChild(p, parent)

    if (!rmSelection)
      this.selection.selectMarkers()

    return p
  }

  autoList.prototype.destroy = function () {
    this.elem.removeEventListener('keydown', this.onKeydown)
  }

  // Plugin name:
  autoList.plugin = 'list'

  return autoList
})<|endoftext|>


<commit_before>/**
 * @file preprocessor.js
 * @author schoeu
 * 文件预处理
 * */

var fs = require('fs-extra');
var path = require('path');
var child_process = require('child_process');
var pinyin = {};
var glob = require('glob');
var utils = require('./utils.js');
var logger = require('./logger.js');
var config = require('./config');
var tempCache = [];
var usePinyin = config.get('usePinyin');
if (usePinyin) {
    pinyin = require('pinyin');
}

module.exports = function () {

    // 定制脚本路径
    var preScript = config.get('preprocessScript');

    // 如果有定制脚本则先执行定制脚本
    if (preScript) {
        try {
            var presInfo = child_process.execFileSync(preScript);
            logger.info({'preprocessInfo: ': presInfo.toString()});
        }
        catch(e){
            logger.error({'preprocess script error: ': e});
        }
    }

    var docPath = config.get('docPath');
    var mdFiles = glob.sync(path.join(docPath, '**/*.md')) || [];
    var htmlFiles = glob.sync(path.join(docPath, '**/*.html')) || [];
    var files = mdFiles.concat(htmlFiles);

    // 清空索引
    tempCache = [];

    files.forEach(function (it) {
        var pos = [];
        var len = 0;
        var initials = '';
        var spell = '';

        it = decodeURIComponent(it);

        var title = utils.getMdTitle(it);

        if (usePinyin) {
            initials = pinyin(title, {
                style: pinyin.STYLE_FIRST_LETTER
            }).join('');

            spell = pinyin(title, {
                style: pinyin.STYLE_NORMAL
            }).map(function (s) {
                s = s.toString();
                pos.push(len);
                len += s.length;
                return s;
            }).join('');
        }

        tempCache.push({
            title: title,
            pos: pos,
            path: it.replace(docPath, ''),
            spell: spell,
            initials: initials
        });
    });

    return tempCache;
};<commit_msg>delete useless package<commit_after>/**
 * @file preprocessor.js
 * @author schoeu
 * 文件预处理
 * */

var path = require('path');
var child_process = require('child_process');
var pinyin = {};
var glob = require('glob');
var utils = require('./utils.js');
var logger = require('./logger.js');
var config = require('./config');
var tempCache = [];
var usePinyin = config.get('usePinyin');
if (usePinyin) {
    pinyin = require('pinyin');
}

module.exports = function () {

    // 定制脚本路径
    var preScript = config.get('preprocessScript');

    // 如果有定制脚本则先执行定制脚本
    if (preScript) {
        try {
            var presInfo = child_process.execFileSync(preScript);
            logger.info({'preprocessInfo: ': presInfo.toString()});
        }
        catch(e){
            logger.error({'preprocess script error: ': e});
        }
    }

    var docPath = config.get('docPath');
    var mdFiles = glob.sync(path.join(docPath, '**/*.md')) || [];
    var htmlFiles = glob.sync(path.join(docPath, '**/*.html')) || [];
    var files = mdFiles.concat(htmlFiles);

    // 清空索引
    tempCache = [];

    files.forEach(function (it) {
        var pos = [];
        var len = 0;
        var initials = '';
        var spell = '';

        it = decodeURIComponent(it);

        var title = utils.getMdTitle(it);

        if (usePinyin) {
            initials = pinyin(title, {
                style: pinyin.STYLE_FIRST_LETTER
            }).join('');

            spell = pinyin(title, {
                style: pinyin.STYLE_NORMAL
            }).map(function (s) {
                s = s.toString();
                pos.push(len);
                len += s.length;
                return s;
            }).join('');
        }

        tempCache.push({
            title: title,
            pos: pos,
            path: it.replace(docPath, ''),
            spell: spell,
            initials: initials
        });
    });

    return tempCache;
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
app.set('title', 'ESPN Bowl Mania Scraper');
app.set('jsonp callback', true);

var nodeio = require('node.io');
var options = {timeout: 10, max: 2, benchmark: true};
var bowlmania = {};

app.configure(function(){
    app.use(express.logger());
});

// heroku logging
var logfmt = require("logfmt");
app.use(logfmt.requestLogger());

app.use('/bowlmania.json', function(req, res){

    nodeio.start(scraper, function (err, output) {

        if (err) {
            console.log('ERROR', err);
        } else {
            //console.log(output);
            //console.log('SENT');
            /*res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Expires", "0");*/
            res.setHeader("Cache-Control", "public, max-age=60");// + (10 * 60));

            res.jsonp(bowlmania);
        }
    }, true);

});

/*var fs = require('fs');
fs.stat(__filename, function(err, stats) { console.log('Last modified', stats.mtime); });
delete fs;*/

app.listen(80);// used 9898 for pony.kulturny.com deployment
console.log('Started server on port 80.');

var scraper = new nodeio.Job(options, {

    input: ['confidence', 'straight'],
    run: function (entryType) {

        //console.log('JOB:', entryType);

        var self = this;

        //this.getHtml('http://localhost/bowls/espn-passthru.php?type=' + entryType, function (err, $) {
        this.getHtml('http://pony.kulturny.com/bowls/espn-passthru.php?type=' + entryType, function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                $('table.scoresheet tbody tr').each(function(listing) {

					try {

	                    var entryName = $('td.games-left a', listing).first().fulltext;
	                    var player = $('td.games-left a', listing).last().fulltext;

	                } catch (err) {

	                	// 2013: skip onto the next

 if there's no player
	                	return false;

	                }

                    //self.emit(player + ': ' + entryName);

                    var realName = whoIsThis(player);
                    if (bowlmania[realName] === undefined) bowlmania[realName] = {};

                    bowlmania[realName][entryType] = {};
                    var obj = bowlmania[realName][entryType];

                    obj.entryName = entryName;

                    var picks = {};
                    //var picksEcho = '';

                    $('td.pick', listing).each(function(pick){

						try {

		                    var team = $('span img', pick).attribs.alt;
	                        var confidencePoints = $('span', pick).text;

		                } catch (err) {

		                	// 2013: skip onto the next 	 if there's no pick
		                	return;

		                }

                        var winLose = $('span', pick).attribs.class;

						if (team == 'MSU') {
							var hack = 'http://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/344.png&w=25&h=0&scale=none';
							var url = $('span img', pick).attribs.src;
							if (url == hack) team = 'MSST';
						}

                        // redundant: if (team == '--'/* || !winLose*/) return;

                        picks[team] = {};
                        if (entryType == "confidence") picks[team].pts = parseInt(confidencePoints);
                        picks[team].win = (winLose == 'win') ? 1 : (winLose == 'loss') ? 0 : -1;

                        //picksEcho += team + ' ' + confidencePoints + ' (' + winLose + '), ';

                    });

                    obj.picks = picks;

                    //self.emit(picksEcho);

                });

                //self.emit(bowlmania);
                self.skip();

            }

        });

    },
    complete: function () {

        //console.log(JSON.stringify(bowlmania));
        return (JSON.stringify(bowlmania));

    }

});

function whoIsThis(data) {

	switch(data) {
		case 'jasonthefool':       return 'jason'; break;
    	case 'FightingOnInOregon': return 'akiyo'; break;
    	case 'arjayw':             return 'dad'; break;
    	case 'Superelf7':          return 'nathan'; break;
    	case 'Meerazha':           return 'meera'; break;
    	case 'robins422003':       return 'robin'; break;

		default: return data;
	}

};

/*

        this.getHtml('http://games.espn.go.com/college-bowl-mania/en/m/scoresheet?groupID=' + encodeURIComponent(groupID), function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                $('table.scoresheet tbody tr').each(function(listing) {
                    var entryName = $('td.games-left a', listing).first().fulltext;
                    var player = $('td.games-left a', listing).last().fulltext;

                    self.emit(player + ': ' + entryName);

                    var pickCount = 0;
                    var picks = '    ';
                    $('td.pick', listing).each(function(pick){
                        pickCount++;

                        picks += $('span', pick).fulltext + ' ';

                    });

                    self.emit(picks);
                    self.emit('    (' + pickCount + ' picks)');

                });

            }

        });

        this.getHtml('http://games.espn.go.com/college-bowl-mania/en/m/entry?entryID=' + encodeURIComponent(entryID), function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                var pickCount = 0;
                var picks = '    ';

                $('table.pickemTable tbody tr').each(function(game) {
                    var gameTitle = $('td.title', game).fulltext;
                    var gameUserPick;
                    var gameTeam1 = $('td.teams span.pickem-teamName', game).first.fulltext;
                    var gameTeam2 = $('td.teams span.pickem-teamName', game).last.fulltext;

                    var gameUserPoints = $('td.points span.entryPoints', game).fulltext;

                    if ($('td.teams td.incorrect', game).notNull) {
                        gameUserPick = $('td.teams td.incorrect', game).fulltext;
                    } else if ($('td.teams td.correct', game).notNull) {
                        gameUserPick = $('td.teams td.correct', game).fulltext;
                    } else {
                        gameUserPick = "dunno";
                    }

                    pickCount++;

                    self.emit(gameTitle + ': ' + gameUserPick + ' (' + gameUserPoints + ')');

                });

                self.emit('    (' + pickCount + ' picks)');

            }

        });

*/<commit_msg>port change<commit_after>var express = require('express');
var app = express();
app.set('title', 'ESPN Bowl Mania Scraper');
app.set('jsonp callback', true);

var nodeio = require('node.io');
var options = {timeout: 10, max: 2, benchmark: true};
var bowlmania = {};

app.configure(function(){
    app.use(express.logger());
});

// heroku logging
var logfmt = require("logfmt");
app.use(logfmt.requestLogger());

app.use('/bowlmania.json', function(req, res){

    nodeio.start(scraper, function (err, output) {

        if (err) {
            console.log('ERROR', err);
        } else {
            //console.log(output);
            //console.log('SENT');
            /*res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            res.setHeader("Pragma", "no-cache");
            res.setHeader("Expires", "0");*/
            res.setHeader("Cache-Control", "public, max-age=60");// + (10 * 60));

            res.jsonp(bowlmania);
        }
    }, true);

});

/*var fs = require('fs');
fs.stat(__filename, function(err, stats) { console.log('Last modified', stats.mtime); });
delete fs;*/

var port = process.env.PORT || 5000;
app.listen(port);// used 9898 for pony.kulturny.com deployment
console.log('Started server on port ' + port);

var scraper = new nodeio.Job(options, {

    input: ['confidence', 'straight'],
    run: function (entryType) {

        //console.log('JOB:', entryType);

        var self = this;

        //this.getHtml('http://localhost/bowls/espn-passthru.php?type=' + entryType, function (err, $) {
        this.getHtml('http://pony.kulturny.com/bowls/espn-passthru.php?type=' + entryType, function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                $('table.scoresheet tbody tr').each(function(listing) {

					try {

	                    var entryName = $('td.games-left a', listing).first().fulltext;
	                    var player = $('td.games-left a', listing).last().fulltext;

	                } catch (err) {

	                	// 2013: skip onto the next

 if there's no player
	                	return false;

	                }

                    //self.emit(player + ': ' + entryName);

                    var realName = whoIsThis(player);
                    if (bowlmania[realName] === undefined) bowlmania[realName] = {};

                    bowlmania[realName][entryType] = {};
                    var obj = bowlmania[realName][entryType];

                    obj.entryName = entryName;

                    var picks = {};
                    //var picksEcho = '';

                    $('td.pick', listing).each(function(pick){

						try {

		                    var team = $('span img', pick).attribs.alt;
	                        var confidencePoints = $('span', pick).text;

		                } catch (err) {

		                	// 2013: skip onto the next 	 if there's no pick
		                	return;

		                }

                        var winLose = $('span', pick).attribs.class;

						if (team == 'MSU') {
							var hack = 'http://a.espncdn.com/combiner/i?img=/i/teamlogos/ncaa/500/344.png&w=25&h=0&scale=none';
							var url = $('span img', pick).attribs.src;
							if (url == hack) team = 'MSST';
						}

                        // redundant: if (team == '--'/* || !winLose*/) return;

                        picks[team] = {};
                        if (entryType == "confidence") picks[team].pts = parseInt(confidencePoints);
                        picks[team].win = (winLose == 'win') ? 1 : (winLose == 'loss') ? 0 : -1;

                        //picksEcho += team + ' ' + confidencePoints + ' (' + winLose + '), ';

                    });

                    obj.picks = picks;

                    //self.emit(picksEcho);

                });

                //self.emit(bowlmania);
                self.skip();

            }

        });

    },
    complete: function () {

        //console.log(JSON.stringify(bowlmania));
        return (JSON.stringify(bowlmania));

    }

});

function whoIsThis(data) {

	switch(data) {
		case 'jasonthefool':       return 'jason'; break;
    	case 'FightingOnInOregon': return 'akiyo'; break;
    	case 'arjayw':             return 'dad'; break;
    	case 'Superelf7':          return 'nathan'; break;
    	case 'Meerazha':           return 'meera'; break;
    	case 'robins422003':       return 'robin'; break;

		default: return data;
	}

};

/*

        this.getHtml('http://games.espn.go.com/college-bowl-mania/en/m/scoresheet?groupID=' + encodeURIComponent(groupID), function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                $('table.scoresheet tbody tr').each(function(listing) {
                    var entryName = $('td.games-left a', listing).first().fulltext;
                    var player = $('td.games-left a', listing).last().fulltext;

                    self.emit(player + ': ' + entryName);

                    var pickCount = 0;
                    var picks = '    ';
                    $('td.pick', listing).each(function(pick){
                        pickCount++;

                        picks += $('span', pick).fulltext + ' ';

                    });

                    self.emit(picks);
                    self.emit('    (' + pickCount + ' picks)');

                });

            }

        });

        this.getHtml('http://games.espn.go.com/college-bowl-mania/en/m/entry?entryID=' + encodeURIComponent(entryID), function (err, $) {

            if (err) {

                console.log("ERROR", err);
                self.retry();

            } else {

                var pickCount = 0;
                var picks = '    ';

                $('table.pickemTable tbody tr').each(function(game) {
                    var gameTitle = $('td.title', game).fulltext;
                    var gameUserPick;
                    var gameTeam1 = $('td.teams span.pickem-teamName', game).first.fulltext;
                    var gameTeam2 = $('td.teams span.pickem-teamName', game).last.fulltext;

                    var gameUserPoints = $('td.points span.entryPoints', game).fulltext;

                    if ($('td.teams td.incorrect', game).notNull) {
                        gameUserPick = $('td.teams td.incorrect', game).fulltext;
                    } else if ($('td.teams td.correct', game).notNull) {
                        gameUserPick = $('td.teams td.correct', game).fulltext;
                    } else {
                        gameUserPick = "dunno";
                    }

                    pickCount++;

                    self.emit(gameTitle + ': ' + gameUserPick + ' (' + gameUserPoints + ')');

                });

                self.emit('    (' + pickCount + ' picks)');

            }

        });

*/<|endoftext|>