<commit_before>var db = require('./db');
var Promise = require('bluebird');
var rawjs = require('raw.js');
var reddit = Promise.promisifyAll(new rawjs("SubredditSimulatorCommentAggregator"));

/**
 * Get comments from /comments and put them cloudant
 * @param {String} after - optional, an id to start "after" - for pagination
 */
var count;
function addCommentsToCloudant (after, link) {
  console.log('getting more comments...');
  // first we get some comments from reddit
  var redditargs = {r: 'SubredditSimulator', limit: 100};
  if (link) {
    redditargs['link'] = link;
    redditargs['sort'] = 'new';
    redditargs['depth'] = 3;
    console.log('link: ' + link);
  }
  if (after) {
    redditargs['after'] = 't1_' + after;
    redditargs['count'] = count;
    console.log('after: ' + after);
  } else {
    count = 0;
  }
  console.log('count: ' + count);

  var rawComments;
  return reddit.commentsAsync(redditargs).then(function (res) {
    rawComments = res.length ? res[0].data.children : res.data.children;
    count += rawComments.length;
    return uploadComments(rawComments);
  }).then(function (args) {
    var body = args[0];
    var headers = args[1];
    // get the next page of comments
    if (rawComments.length) {
      var nextIdToGet = rawComments[rawComments.length - 1].data._id;
    }
    // wait 3s before getting the next page
    if (nextIdToGet) {
      setTimeout(function () { addCommentsToCloudant(nextIdToGet, link); }.bind(this), 2000);
    }
  }).catch(function (e) {
    console.error(e);
  });
}

/**
 * Get the 100 newest posts, and then get the comments for 'em
 */
var posts, j = 0;
function addNewPostsToCloudant () {
  console.log('getting comments from posts...');
  var redditargs = {r: 'SubredditSimulator'};
  return reddit.newAsync(redditargs).then(function (args) {
    posts = args.children;
    for (var i = 0; i < posts.length; i++) {
      // kick 'em off every 20 seconds
      // TODO - have good promise handling in addCommentsToCloudant so we can chain these instead
      setTimeout(function () { addCommentsToCloudant(null, posts[j++].data.id)}.bind(this), i*4000);
    }
    // var post = posts[posts.length - 1].data;
    // return addCommentsToCloudant(null, post.id);
  }).catch(function (e) {
    console.error(e);
  });
}

/**
 * Given an array of raw comment data from the reddit api, upload it to cloudant
 * First check to see if that comment id is already in the database, if it is, update
 * it with the most recent data
 * @param {Array.<CommentJson>}
 */
function uploadComments (comments) {
  var ids = comments.map(function (child) { return child.data.id });
  return db.viewAsync('ss_design', 'ss_ids', {keys: ids}).then(function (args) {
    var body = args[0];
    var headers = args[1];
    // build a map of comment ids to _revs
    var idToRevMap = {};
    var rows = body.rows;
    if (rows.length) {
      for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        idToRevMap[row.id] = row.value._rev;
      }
    }
    // now we build an array of comments from the raw reddit data
    var docs = [];
    for (var i = 0; i < comments.length; i++) {
      var comment = comments[i].data;
      // if this comment is already in cloudant, tack on the _rev
      if (idToRevMap[comment.id]) {
        comment['_rev'] = idToRevMap[comment.id];
      }
      // we like to call these puppies _ids, not ids
      comment['_id'] = comment.id;
      delete comment.id;
      // add it to our array
      docs.push(comment);
    }
    // perform the bulk operation - this'll do updates for things that are already there
    // and insert the comments that we don't yet know about
    return db.bulkAsync({docs: docs}, {});
  });
}

module.exports = {
  addCommentsToCloudant: addCommentsToCloudant,
  addNewPostsToCloudant: addNewPostsToCloudant
}<commit_msg>have getAndUploadPostComments traverse forver<commit_after>var db = require('./db');
var Promise = require('bluebird');
var rawjs = require('raw.js');
var reddit = Promise.promisifyAll(new rawjs("SubredditSimulatorCommentAggregator"));

module.exports = {
  posts: undefined,
  postIterator: undefined,

  /**
   * For a given link (undefined if you wanna just load all new comments), keep loading
   * the next page and uploading the results to cloudant.
   * @return {Promise} resolves when done, rejects if it error'd out
   */
  getAndUploadComments: function (link) {
    return new Promise(function (resolve, reject) {
      this._getAndUploadHelper(null, link, null, resolve, reject);
    }.bind(this));
  },

  /**
   * Get comments from /comments and put them cloudant. Note: this is recursive.
   * @param {String} after - optional, a comment id to start "after" - for pagination
   * @param {String} link - optional, a link id to load new comments for
   * @param {number} count - optional, used for pagination, specify how many comments we've already loaded
   * @param {function} resolve - optional, a Promise's resolve function that we can resolve if we've retrieved the last comment
   * @param {function} reject - optional, a Promise's reject function we can reject
   */
  _getAndUploadHelper: function (after, link, count, resolve, reject) {
    var log;
    count = count || 0;
    // format the args for the commentsAsync api
    var redditargs = {r: 'SubredditSimulator', limit: 100};
    if (link) {
      redditargs.link = link;
      redditargs.sort = 'new';
      log = 'getting comments for post ' + link;
    } else {
      log = 'getting newest comments';
    }
    if (after) {
      redditargs.after = 't1_' + after;
      redditargs.count = count;
      log += ' after ' + after + ', total so far is ' + count;
    } else {
      count = 0;
    }
    console.log(log);

    var rawComments;
    return reddit.commentsAsync(redditargs).then(function (res) {
      rawComments = res.length ? res[0].data.children : res.data.children;
      count += rawComments.length;
      return this.uploadComments(rawComments);
    }.bind(this)).then(function (args) {
      var body = args[0];
      var headers = args[1];
      // get the next page of comments
      if (rawComments.length) {
        var nextIdToGet = rawComments[rawComments.length - 1].data._id;
      }
      // wait 3s before getting the next page
      if (nextIdToGet) {
        setTimeout(this._getAndUploadHelper.bind(this, nextIdToGet, link, count, resolve, reject), 2000);
      } else {
        resolve && resolve(count);
      }
    }.bind(this)).catch(function (e) {
      console.error(e);
      // gotta figure out why paging isnt working when specifying a link
      resolve && resolve(count);
    });
  },

  /**
   * Keep on loading posts until there are no more. For each post, load all of its comments
   * and upload them. Note: this recursively calls itself until it is done.
   * @param {String} after - optional, if we're paging, start the next fetch after this given id
   * @return {Promise} resolve when done
   */
  getAndUploadPostComments: function (after) {
    console.log('getting comments from posts...');
    var posts;
    var redditargs = {r: 'SubredditSimulator', limit: 100};
    if (after) {
      redditargs.after = 't3_' + after;
    }
    return reddit.newAsync(redditargs).then(function (args) {
      return (new Promise(function (resolve, reject) {
        return this._getAndUploadPostHelper(args.children, resolve, reject);
      }.bind(this))).then(function (lastid) {
        if (lastid) {
          return this.getAndUploadPostComments(lastid);
        } else {
          return;
        }
      }.bind(this));
    }.bind(this)).catch(function (e) {
      console.error(e);
    });
  },

  /**
   * Given an array of posts, load the comments for each post one by one and add them to
   * cloudant.
   * @param  {Array.<Reddit Post JSON>} posts - the array of posts
   * @param  {function} resolve - a Promise's resolve function
   * @param  {function} reject  [description]
   * @param  {String} lastid - passed down recursively so that we can resolve with the last ID
   * that we fetched comments for. Used for paging the posts
   */
  _getAndUploadPostHelper: function (posts, resolve, reject, lastid) {
    console.log('loading comments for ' + posts.length + ' more posts');
    if (posts.length) {
      var currPost = posts.shift();
      this.getAndUploadComments(currPost.data.id).then(function (count) {
        this._getAndUploadPostHelper(posts, resolve, reject, currPost.data.id);
      }.bind(this)).catch(function (e) {
        reject(e);
      });
    } else {
      resolve(lastid);
    }
  },

  /**
   * Given an array of raw comment data from the reddit api, upload it to cloudant
   * First check to see if that comment id is already in the database, if it is, update
   * it with the most recent data
   * @param {Array.<CommentJson>}
   */
  uploadComments: function (comments) {
    var ids = comments.map(function (child) { return child.data.id });
    return db.viewAsync('ss_design', 'ss_ids', {keys: ids}).then(function (args) {
      var body = args[0];
      var headers = args[1];
      // build a map of comment ids to _revs
      var idToRevMap = {};
      var rows = body.rows;
      if (rows.length) {
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i];
          idToRevMap[row.id] = row.value._rev;
        }
      }
      // now we build an array of comments from the raw reddit data
      var docs = [];
      for (var i = 0; i < comments.length; i++) {
        var comment = comments[i].data;
        // if this comment is already in cloudant, tack on the _rev
        if (idToRevMap[comment.id]) {
          comment['_rev'] = idToRevMap[comment.id];
        }
        // we like to call these puppies _ids, not ids
        comment['_id'] = comment.id;
        delete comment.id;
        // add it to our array
        docs.push(comment);
      }
      // perform the bulk operation - this'll do updates for things that are already there
      // and insert the comments that we don't yet know about
      return db.bulkAsync({docs: docs}, {});
    });
  }
}<|endoftext|>


<commit_before>'use strict';

const assert = require('assert');

const _ = require('lodash');
const Promise = require('bluebird');

const {makeExecutableSchema} = require('graphql-tools');

const schema = require('./schema/rootQuery');

const features = require('../util/features');

const _GeneratorFunction = (function*(){}).constructor;
const crMap = obj =>
    _.mapValues(obj, robj =>
        _.mapValues(robj, val =>
            val.constructor === _GeneratorFunction
                ? Promise.coroutine(val)
                : val
        )
    );

const baseResolvers = {
    Query: {
        * substances(data, args, ctx) {
            ctx.args = args;

            return yield* ctx.substances.getSubstances(args);
        },
        * effects(data, args, ctx) {
            ctx.args = args;

            return yield* ctx.substances.getEffects(args);
        }
    },
    Substance: {
        * effects(data, args, ctx) {
            const substance = _.get(data, 'name');

            return yield* ctx.substances.getSubstanceEffects(
                _.assign({}, {substance}, ctx.args)
            );
        },

        * dangerousInteraction(data, __, ctx) {
            const interactions = _.get(data, 'dangerousInteraction', null);

            if (!interactions) {
                return null;
            }

            return Promise.all(interactions.map(
                Promise.coroutine(function* (substanceName) {
                    const results = yield* ctx.substances.getSubstances({
                        query: substanceName,
                        limit: 1,
                        offset: 0
                    });

                    if (_.size(results) === 1) {
                        return results[0];
                    }

                    return null;
                })
            ));
        },

        * summary(data, args, ctx) {
            const substance = _.get(data, 'name');

            return yield* ctx.substances.getSubstanceAbstract(
                _.assign({}, {substance}, ctx.args)
            );
        }
    },
    Effect: {
        * substances(data, args, ctx) {
            const effect = _.get(data, 'name');

            return yield* ctx.substances.getEffectSubstances(
                _.assign({}, {effect}, ctx.args)
            );
        }
    }
};

if (features.has('plebiscite')) {
    _.assign(baseResolvers.Query, {
        * erowid(data, {substance, offset, limit}, {plebiscite}) {
            return yield* plebiscite.find({substance, offset, limit});
        }
    });
}

const resolvers = crMap(baseResolvers);

class PwEdge {
    get schema() {
        return makeExecutableSchema({
            typeDefs: [schema],
            resolvers
        });
    }
}

module.exports = PwEdge;
<commit_msg>Enforce array type for dangerousInteractions<commit_after>'use strict';

const _ = require('lodash');
const Promise = require('bluebird');

const {makeExecutableSchema} = require('graphql-tools');

const schema = require('./schema/rootQuery');

const features = require('../util/features');

const _GeneratorFunction = (function*(){}).constructor;
const crMap = obj =>
    _.mapValues(obj, robj =>
        _.mapValues(robj, val =>
            val.constructor === _GeneratorFunction
                ? Promise.coroutine(val)
                : val
        )
    );

const baseResolvers = {
    Query: {
        * substances(data, args, ctx) {
            ctx.args = args;

            return yield* ctx.substances.getSubstances(args);
        },
        * effects(data, args, ctx) {
            ctx.args = args;

            return yield* ctx.substances.getEffects(args);
        }
    },
    Substance: {
        * effects(data, args, ctx) {
            const substance = _.get(data, 'name');

            return yield* ctx.substances.getSubstanceEffects(
                _.assign({}, {substance}, ctx.args)
            );
        },

        * dangerousInteraction(data, __, ctx) {
            const interactions = _.get(data, 'dangerousInteraction', null);

            if (!_.isArray(interactions)) {
                return null;
            }

            return Promise.all(interactions.map(
                Promise.coroutine(function* (substanceName) {
                    const results = yield* ctx.substances.getSubstances({
                        query: substanceName,
                        limit: 1,
                        offset: 0
                    });

                    if (_.size(results) === 1) {
                        return results[0];
                    }

                    return null;
                })
            ));
        },

        * summary(data, args, ctx) {
            const substance = _.get(data, 'name');

            return yield* ctx.substances.getSubstanceAbstract(
                _.assign({}, {substance}, ctx.args)
            );
        }
    },
    Effect: {
        * substances(data, args, ctx) {
            const effect = _.get(data, 'name');

            return yield* ctx.substances.getEffectSubstances(
                _.assign({}, {effect}, ctx.args)
            );
        }
    }
};

if (features.has('plebiscite')) {
    _.assign(baseResolvers.Query, {
        * erowid(data, {substance, offset, limit}, {plebiscite}) {
            return yield* plebiscite.find({substance, offset, limit});
        }
    });
}

const resolvers = crMap(baseResolvers);

class PwEdge {
    get schema() {
        return makeExecutableSchema({
            typeDefs: [schema],
            resolvers
        });
    }
}

module.exports = PwEdge;
<|endoftext|>


<commit_before>const db = require('sqlite')
const squel = require('squel')
const debug = require('debug')
const log = debug('app:library:search')

async function searchLibrary(params = {}) {
  const songs = {
    result: [],
    entities: {}
  }

  const q = squel.select().from('songs')

  Object.keys(params).map(key => {
    if (key === 'meta' && typeof params.meta === 'object') {
      Object.keys(params.meta).map(i => {
        q.where(`json_extract(provider_json, '$.${i}') = ?`, params.meta[i])
      })
    } else {
      q.where(`${key} = ?`, params[key])
    }
  })

  // get songs
  try {
    // log(q.toString())
    const { text, values } = q.toParam()
    const rows = await db.all(text, values)

    // normalize results
    rows.forEach(function(row){
      songs.result.push(row.songId)
      songs.entities[row.songId] = row
    })
  } catch(err) {
    log(err.message)
    return Promise.reject(err)
  }

  log('%s result' + (songs.result.length === 1 ? '' : 's'), songs.result.length)
  return songs
}

module.exports = searchLibrary
<commit_msg>Add starred count to song (search) query<commit_after>const db = require('sqlite')
const squel = require('squel')
const debug = require('debug')
const log = debug('app:library:search')

async function searchLibrary(params = {}) {
  const songs = {
    result: [],
    entities: {}
  }

  const q = squel.select()
    .field('songs.*')
    .from('songs')

  Object.keys(params).map(key => {
    if (key === 'meta' && typeof params.meta === 'object') {
      Object.keys(params.meta).map(i => {
        q.where(`json_extract(provider_json, '$.${i}') = ?`, params.meta[i])
      })
    } else {
      q.where(`${key} = ?`, params[key])
    }
  })

  // starred count
  q.field('COUNT(stars.userId) AS stars')
    .left_join('stars USING(songId)')
    .group('songId')

  // get songs
  try {
    // log(q.toString())
    const { text, values } = q.toParam()
    const rows = await db.all(text, values)

    // normalize results
    rows.forEach(function(row){
      songs.result.push(row.songId)
      songs.entities[row.songId] = row
    })
  } catch(err) {
    log(err.message)
    return Promise.reject(err)
  }

  log('%s result' + (songs.result.length === 1 ? '' : 's'), songs.result.length)
  return songs
}

module.exports = searchLibrary
<|endoftext|>


<commit_before>/*
 * KodeBlox Copyright 2017 Sayak Mukhopadhyay
 *
 * 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.
 */

"use strict";

module.exports = new Promise((resolve, reject) => {
    let db = require('../db');
    let mongoose = db.mongoose;
    let Schema = mongoose.Schema;

    let system = new Schema({
        id: { type: Number, unique: true },
        edsm_id: Number,
        name: String,
        name_lower: { type: String, lowercase: true },
        x: Number,
        y: Number,
        z: Number,
        population: Number,
        is_populated: Boolean,
        government_id: Number,
        government: { type: String, lowercase: true },
        allegiance_id: Number,
        allegiance: { type: String, lowercase: true },
        state_id: Number,
        state: { type: String, lowercase: true },
        security_id: Number,
        security: { type: String, lowercase: true },
        primary_economy_id: Number,
        primary_economy: { type: String, lowercase: true },
        power: { type: String, lowercase: true },
        power_state: { type: String, lowercase: true },
        power_state_id: Number,
        needs_permit: Boolean,
        updated_at: Date,
        simbad_ref: { type: String, lowercase: true },
        controlling_minor_faction_id: { type: Number, ref: 'faction.id' },
        controlling_minor_faction: { type: String, lowercase: true, ref: 'faction.name' },
        reserve_type_id: Number,
        reserve_type: { type: String, lowercase: true },
    }, { runSettersOnQuery: true });

    system.pre('save', function (next) {
        lowerify(this);
        millisecondify(this);
        next();
    });

    system.pre('findOneAndUpdate', function (next) {
        lowerify(this._update);
        millisecondify(this._update);
        next();
    });

    let model = mongoose.model('system', system);

    let lowerify = ref => {
        ref.name_lower = ref.name;
    }

    let millisecondify = ref => {
        ref.updated_at *= 1000;
    }

    resolve(model);
})<commit_msg>Added index to lowername in systems<commit_after>/*
 * KodeBlox Copyright 2017 Sayak Mukhopadhyay
 *
 * 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.
 */

"use strict";

module.exports = new Promise((resolve, reject) => {
    let db = require('../db');
    let mongoose = db.mongoose;
    let Schema = mongoose.Schema;

    let system = new Schema({
        id: { type: Number, unique: true },
        edsm_id: Number,
        name: String,
        name_lower: { type: String, lowercase: true, index: true },
        x: Number,
        y: Number,
        z: Number,
        population: Number,
        is_populated: Boolean,
        government_id: Number,
        government: { type: String, lowercase: true },
        allegiance_id: Number,
        allegiance: { type: String, lowercase: true },
        state_id: Number,
        state: { type: String, lowercase: true },
        security_id: Number,
        security: { type: String, lowercase: true },
        primary_economy_id: Number,
        primary_economy: { type: String, lowercase: true },
        power: { type: String, lowercase: true },
        power_state: { type: String, lowercase: true },
        power_state_id: Number,
        needs_permit: Boolean,
        updated_at: Date,
        simbad_ref: { type: String, lowercase: true },
        controlling_minor_faction_id: { type: Number, ref: 'faction.id' },
        controlling_minor_faction: { type: String, lowercase: true, ref: 'faction.name' },
        reserve_type_id: Number,
        reserve_type: { type: String, lowercase: true },
    }, { runSettersOnQuery: true });

    system.pre('save', function (next) {
        lowerify(this);
        millisecondify(this);
        next();
    });

    system.pre('findOneAndUpdate', function (next) {
        lowerify(this._update);
        millisecondify(this._update);
        next();
    });

    let model = mongoose.model('system', system);

    let lowerify = ref => {
        ref.name_lower = ref.name;
    }

    let millisecondify = ref => {
        ref.updated_at *= 1000;
    }

    resolve(model);
})<|endoftext|>


<commit_before>var employees       = require('./data/employees');
var frameworkInfo   = require('./data/framework-info');
var redirects       = require('./data/redirects');
var trustedPartners = require('./data/trusted-partners');
var url             = require('url');
var followerCount   = null;
var tools           = require('./tools').getTwitterProfile().then(user => {
  followerCount = user ? user.followers_count : null
});

module.exports = function(req, res, next) {

  // redirect www
  if (req.headers.host.slice(0, 4) === 'www.') {
    var newHost = req.headers.host.slice(4);
    return res.redirect(301, 'https://' + newHost + req.originalUrl);
  }

  // redirect entire old sections
  var parts = url.parse(req.url);

  if (parts.path.indexOf('/blog') == 0) {
    return res.redirect(301, 'https://blog.ionicframework.com' + req.url.replace(/^\/blog/, ''));
  } else if (parts.path.indexOf('/creator/') == 0) {
    return res.redirect(301, '/products/creator' + req.url.replace(/^\/creator\//, ''));
  } else if (parts.path.indexOf('/tutorials') == 0) {
    return res.redirect(301, '/getting-started');
  } else if (parts.path.indexOf('/docs/v1/cli') == 0) {
    return res.redirect(301, '/docs/cli/');
  // } else if (parts.path.indexOf('/docs/pro') == 0) {
  //   return res.redirect(301, 'http://support.ionicjs.com');
  } else if (req.headers.host.indexOf('learn.') == 0) {
    return res.redirect(301, '/docs/');
  }

  // handle redirects
  var uri = req.url.split(/[\?|#]/g);
  var requrl = uri[0];
  if (requrl.endsWith('/')) {
    requrl = requrl.slice(0, -1);
  }

  if (redirects[requrl]) {
    if (uri[1]) {
      return res.redirect(301, redirects[requrl] + '?' + uri[1]);
    }
    return res.redirect(301, redirects[requrl]);
  }

  // don't index non production URLs, but favor HTTPS
  var protocol = 'https';
  if (req.hostname.indexOf('ionicframework.com') == -1) {
    res.setHeader('X-Robots-Tag', 'noindex, nofollow');
    protocol = 'http';
  } else if (req.protocol === 'http') {
    // force https in prod
    return res.redirect(301, `https://ionicframework.com${req.url}`);
  }

  // cache static files
  var staticURLS = ['/img/','/fonts/','/favicon.ico'];
  for (var i = 0; i <= staticURLS.length; i++) {
    if (req.url.indexOf(staticURLS[i]) === 0) {
      res.setHeader('Cache-Control', 'public, max-age=315360000000');
      res.setHeader('Expires', new Date(Date.now() + 315360000000).toUTCString());
      break;
    }
  }

  // Setting default Page Vars
  res.locals = {
    header_style: 'transparent',
    id: req.originalUrl.split('/').join('-'),
    employees: shuffle(employees),
    followerCount: followerCount,
    pre_footer: true,
    protocol: protocol,
    domain: req.get('host'),
    url: req.originalUrl,
    dev: req.get('host').indexOf('localhost') === 0,
    trustedPartners: shuffle(trustedPartners),
    frameworkInfo: frameworkInfo
  };

  return next();
};

function shuffle(array) {
  var currentIndex = array.length;
  var temporaryValue;
  var randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
};
<commit_msg>fixing bad redirect rule<commit_after>var employees       = require('./data/employees');
var frameworkInfo   = require('./data/framework-info');
var redirects       = require('./data/redirects');
var trustedPartners = require('./data/trusted-partners');
var url             = require('url');
var followerCount   = null;
var tools           = require('./tools').getTwitterProfile().then(user => {
  followerCount = user ? user.followers_count : null
});

module.exports = function(req, res, next) {

  // redirect www
  if (req.headers.host.slice(0, 4) === 'www.') {
    var newHost = req.headers.host.slice(4);
    return res.redirect(301, 'https://' + newHost + req.originalUrl);
  }

  // redirect entire old sections
  var parts = url.parse(req.url);

  if (parts.path.indexOf('/blog') == 0) {
    return res.redirect(301, 'https://blog.ionicframework.com' + req.url.replace(/^\/blog/, ''));
  } else if (parts.path.indexOf('/creator/') == 0) {
    return res.redirect(301, '/products/creator' + req.url.replace(/^\/creator\//, ''));
  } else if (parts.path.indexOf('/tutorials') == 0) {
    return res.redirect(301, '/getting-started');
  } else if (parts.path.indexOf('/docs/v1/cli') == 0) {
    return res.redirect(301, '/docs/cli/');
  // } else if (parts.path.indexOf('/docs/pro') == 0) {
  //   return res.redirect(301, 'http://support.ionicjs.com');
  } else if (req.headers.host.indexOf('learn.') == 0) {
    return res.redirect(301, '/docs/');
  }

  // handle redirects
  var uri = req.url.split(/[\?|#]/g);
  var requrl = uri[0];
  if (requrl.endsWith('/')) {
    requrl = requrl.slice(0, -1);
  }

  if (redirects[requrl]) {
    if (uri[1]) {
      return res.redirect(301, redirects[requrl] + '?' + uri[1]);
    }
    return res.redirect(301, redirects[requrl]);
  }

  // don't index non production URLs, but favor HTTPS
  var protocol = 'https';
  if (req.hostname.indexOf('ionicframework.com') == -1) {
    res.setHeader('X-Robots-Tag', 'noindex, nofollow');
    protocol = 'http';
  } else if (req.protocol === 'http') {
    // force https in prod
    // return res.redirect(301, `https://ionicframework.com${req.url}`);
  }

  // cache static files
  var staticURLS = ['/img/','/fonts/','/favicon.ico'];
  for (var i = 0; i <= staticURLS.length; i++) {
    if (req.url.indexOf(staticURLS[i]) === 0) {
      res.setHeader('Cache-Control', 'public, max-age=315360000000');
      res.setHeader('Expires', new Date(Date.now() + 315360000000).toUTCString());
      break;
    }
  }

  // Setting default Page Vars
  res.locals = {
    header_style: 'transparent',
    id: req.originalUrl.split('/').join('-'),
    employees: shuffle(employees),
    followerCount: followerCount,
    pre_footer: true,
    protocol: protocol,
    domain: req.get('host'),
    url: req.originalUrl,
    dev: req.get('host').indexOf('localhost') === 0,
    trustedPartners: shuffle(trustedPartners),
    frameworkInfo: frameworkInfo
  };

  return next();
};

function shuffle(array) {
  var currentIndex = array.length;
  var temporaryValue;
  var randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
};
<|endoftext|>


<commit_before>'use strict';

angular.module('iTravelApp', [
	'ngRoute'
])

/**
 * Configure the Routes
 */
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        // Home
        .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})

        // Pages
        .when("/login", {templateUrl: "partials/login.html", controller: "PageCtrl"})
        .when("/signup", {templateUrl: "partials/signup.html", controller: "PageCtrl"})
        .when("/travel", {templateUrl: "partials/travel.html", controller: "PageCtrl"})
        .when("/aboutus", {templateUrl: "partials/aboutus.html", controller: "PageCtrl"})
		.when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
        .when("/locations", {templateUrl: "partials/locations.html", controller: "PageCtrl"})
        .when("/tech", {templateUrl: "partials/tech.html", controller: "PageCtrl"})
        .when("/privacy", {templateUrl: "partials/privacy.html", controller: "PageCtrl"})
        .when("/security", {templateUrl: "partials/security.html", controller: "PageCtrl"})
        .when("/developer", {templateUrl: "partials/developer.html", controller: "PageCtrl"})

        // else error
        .otherwise("/error", {templateUrl: "partials/error.html", controller: "PageCtrl"});
}]);<commit_msg>delete var app cause errors, reverse it, leave for later change<commit_after>'use strict';

var app = angular.module('iTravelApp', [
	'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        // Home
        .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})

        // Pages
        .when("/login", {templateUrl: "partials/login.html", controller: "PageCtrl"})
        .when("/signup", {templateUrl: "partials/signup.html", controller: "PageCtrl"})
        .when("/travel", {templateUrl: "partials/travel.html", controller: "PageCtrl"})
        .when("/aboutus", {templateUrl: "partials/aboutus.html", controller: "PageCtrl"})
		.when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
        .when("/locations", {templateUrl: "partials/locations.html", controller: "PageCtrl"})
        .when("/tech", {templateUrl: "partials/tech.html", controller: "PageCtrl"})
        .when("/privacy", {templateUrl: "partials/privacy.html", controller: "PageCtrl"})
        .when("/security", {templateUrl: "partials/security.html", controller: "PageCtrl"})
        .when("/developer", {templateUrl: "partials/developer.html", controller: "PageCtrl"})

        // else error
        .otherwise("/error", {templateUrl: "partials/error.html", controller: "PageCtrl"});
}]);<|endoftext|>


<commit_before>const sockets = require('socket.io');

var num = 0;
// constant lookup for active users and rooms
const users = {};
const rooms = {};

module.exports = (server) => {
  const io = sockets(server);
  io.on('connection', (socket) => {
    // send back that it's ready -> mount React components
    console.log(`${++num} users online`);

    socket.on('join', data => {
      console.log('JOINED');
      const userId = socket.userId = data.userId;

      // add user to master users obj
      users[userId] = [];

      // join relevant channels (rooms)
      data.roomIds.forEach(roomId => {
        socket.join(roomId);

        rooms[roomId] = rooms[roomId] || 0;
        users[userId].push(roomId);
        // socket.nsp.in(roomId).emit('online room', { roomId, numOnline: rooms[roomId]++ });
      });
      // socket.broadcast.emit('online user', { userId });
    });

    socket.on('new message', (data) => {
      console.log('here');
      socket.broadcast.in(data.roomId).emit('new message', data);
    });

    socket.on('disconnect', () => {
      // users[socket.userId].forEach(roomId => rooms[roomId]--);
      delete users[socket.userId];
      console.log(`${--num} users online`);
    });
  });
};
<commit_msg>Remove console.logs<commit_after>const sockets = require('socket.io');

var num = 0;
// constant lookup for active users and rooms
const users = {};
const rooms = {};

module.exports = (server) => {
  const io = sockets(server);
  io.on('connection', (socket) => {
    // send back that it's ready -> mount React components
    console.log(`${++num} users online`);

    socket.on('join', data => {
      const userId = socket.userId = data.userId;

      // add user to master users obj
      users[userId] = [];

      // join relevant channels (rooms)
      data.roomIds.forEach(roomId => {
        socket.join(roomId);

        rooms[roomId] = rooms[roomId] || 0;
        users[userId].push(roomId);
        // socket.nsp.in(roomId).emit('online room', { roomId, numOnline: rooms[roomId]++ });
      });
      // socket.broadcast.emit('online user', { userId });
    });

    socket.on('new message', (data) => {
      socket.broadcast.in(data.roomId).emit('new message', data);
    });

    socket.on('disconnect', () => {
      // users[socket.userId].forEach(roomId => rooms[roomId]--);
      delete users[socket.userId];
      console.log(`${--num} users online`);
    });
  });
};
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Video Library - Data Model
////////////////////////////////////////////////////////////////////////////////
var	$path = require('path'),
		$media = require('../db/media'),
		quotes = require('../db/entity').quotes,
		sqlite = require('../tools/sqlite').sqlite,

library = function () {
	var self = {
		// queries the entire library
		getMedia: function (filter, handler) {
			var statement = [
				"SELECT mediaid, path, rating, group_concat(name || ':' || CASE WHEN kind IS NOT NULL THEN kind ELSE '' END) AS tags FROM media NATURAL JOIN tags",
				filter ? $media.filter(filter) : "",
				"GROUP BY mediaid;"
			].join(" ");

			console.log(statement);
			sqlite.exec(statement, handler, ['-header', '-line']);
		},

		// inserts videos into the database
		fill: function (data, handler) {
			var	statement = [],
					keywords,
					tags,
					i,
					buffer,
					fd,
					lastid = "(SELECT value FROM vars WHERE name = 'lastid')";

			console.log("Building ingest SQL statement...");
			statement.push("BEGIN TRANSACTION;");

			// adding temporary table to store last accessed media id
			statement.push("CREATE TEMPORARY TABLE vars (name TEXT, value INTEGER);");
			statement.push("INSERT INTO vars (name, value) VALUES ('lastid', 0);");

			for (path in data) {
				// inserting statement for media path
				statement.push([
					"INSERT OR IGNORE INTO media (path) VALUES ('",
					quotes(path),
					"');"
				].join(""));

				// updating last accessed media id so sub-inserts can use that
				statement.push([
					"UPDATE vars SET value = (",
					"SELECT mediaid FROM media WHERE path = '",
					quotes(path),
					"') WHERE name = 'lastid';"
				].join(""));

				// inserting statement for media keywords (properties)
				keywords = data[path];
				for (keyword in keywords) {
					statement.push([
						"INSERT OR REPLACE INTO keywords (mediaid, key, value) VALUES (",
						lastid, ",'",
						keyword, "','",
						quotes(keywords[keyword]),
						"');"
					].join(""));
				}

				// inserting statement for auto tags
				tags = []
					// filename broken down into its word-like components
					.concat($path.basename(path, $path.extname(path)).split(/[^A-Za-z0-9]+/))
					// path stripped of non-word characters and broken down by directory levels
					.concat($path.dirname(path).replace(/[^A-Za-z0-9\/\\\s]/g, '').split('/'));

				for (i = 0; i < tags.length; i++) {
					if (!tags[i].length) {
						continue;
					}
					statement.push([
						"INSERT OR REPLACE INTO tags (mediaid, name) VALUES (",
						lastid, ",'",
						quotes(tags[i]),
						"');"
					].join(""));
				}
			}
			statement.push("COMMIT;");
			console.log(["SQL statement built:", statement.length, "lines."].join(' '));

			// executing statement
			sqlite.exec(statement.join('\n'), handler, null, true);

			return self;
		}
	};

	return self;
}();

exports.library = library;

<commit_msg>both dos & linux slash serve as separator on splitting path<commit_after>////////////////////////////////////////////////////////////////////////////////
// Video Library - Data Model
////////////////////////////////////////////////////////////////////////////////
var	$path = require('path'),
		$media = require('../db/media'),
		quotes = require('../db/entity').quotes,
		sqlite = require('../tools/sqlite').sqlite,

library = function () {
	var self = {
		// queries the entire library
		getMedia: function (filter, handler) {
			var statement = [
				"SELECT mediaid, path, rating, group_concat(name || ':' || CASE WHEN kind IS NOT NULL THEN kind ELSE '' END) AS tags FROM media NATURAL JOIN tags",
				filter ? $media.filter(filter) : "",
				"GROUP BY mediaid;"
			].join(" ");

			console.log(statement);
			sqlite.exec(statement, handler, ['-header', '-line']);
		},

		// inserts videos into the database
		fill: function (data, handler) {
			var	statement = [],
					keywords,
					tags,
					i,
					buffer,
					fd,
					lastid = "(SELECT value FROM vars WHERE name = 'lastid')";

			console.log("Building ingest SQL statement...");
			statement.push("BEGIN TRANSACTION;");

			// adding temporary table to store last accessed media id
			statement.push("CREATE TEMPORARY TABLE vars (name TEXT, value INTEGER);");
			statement.push("INSERT INTO vars (name, value) VALUES ('lastid', 0);");

			for (path in data) {
				// inserting statement for media path
				statement.push([
					"INSERT OR IGNORE INTO media (path) VALUES ('",
					quotes(path),
					"');"
				].join(""));

				// updating last accessed media id so sub-inserts can use that
				statement.push([
					"UPDATE vars SET value = (",
					"SELECT mediaid FROM media WHERE path = '",
					quotes(path),
					"') WHERE name = 'lastid';"
				].join(""));

				// inserting statement for media keywords (properties)
				keywords = data[path];
				for (keyword in keywords) {
					statement.push([
						"INSERT OR REPLACE INTO keywords (mediaid, key, value) VALUES (",
						lastid, ",'",
						keyword, "','",
						quotes(keywords[keyword]),
						"');"
					].join(""));
				}

				// inserting statement for auto tags
				tags = []
					// filename broken down into its word-like components
					.concat($path.basename(path, $path.extname(path)).split(/[^A-Za-z0-9]+/))
					// path stripped of non-word characters and broken down by directory levels
					.concat($path.dirname(path).replace(/[^A-Za-z0-9\/\\\s]/g, '').split(/[\/\\]/));

				for (i = 0; i < tags.length; i++) {
					if (!tags[i].length) {
						continue;
					}
					statement.push([
						"INSERT OR REPLACE INTO tags (mediaid, name) VALUES (",
						lastid, ",'",
						quotes(tags[i]),
						"');"
					].join(""));
				}
			}
			statement.push("COMMIT;");
			console.log(["SQL statement built:", statement.length, "lines."].join(' '));

			// executing statement
			sqlite.exec(statement.join('\n'), handler, null, true);

			return self;
		}
	};

	return self;
}();

exports.library = library;

<|endoftext|>


<commit_before>angular.module('RadioBrowserApp').factory('radiobrowser', ['$http', function radiobrowser($http) {
    var SERVER = "https://de1.api.radio-browser.info";
    //var SERVER = "http://localhost:8080";

    function getStats() {
        return $http.get(SERVER + '/json/stats');
    }

    function post(relLink, data) {
        return $http.post(SERVER + relLink, data);
    }

    function get(relLink) {
        return $http.get(SERVER + relLink);
    }

    function get_changes(uuid) {
        return get('/json/stations/changed/' + uuid).then(function (data) {
            var list_changes = data.data;
            for (var i = 0; i < list_changes.length; i++) {
                list_changes[i].lastchangetime = new Date(list_changes[i].lastchangetime.replace(" ", "T") + "Z");
                list_changes[i].lastchangetime_locale = new Date(list_changes[i].lastchangetime).toLocaleString();
            }
            return list_changes;
        });
    }

    function get_clicks(uuid, seconds) {
        return get('/json/clicks/' + uuid + "?seconds=" + seconds).then(function (data) {
            var list_clicks = data.data;
            for (var i = 0; i < list_clicks.length; i++) {
                list_clicks[i].clicktimestamp = new Date(list_clicks[i].clicktimestamp.replace(" ", "T") + "Z");
                list_clicks[i].clicktimestamp_locale = new Date(list_clicks[i].clicktimestamp).toLocaleString();
            }
            return list_clicks;
        });
    }

    function get_checks(uuid) {
        return get('/json/checks/' + uuid).then(function (data) {
            var list_checks = data.data;
            for (var i = 0; i < list_checks.length; i++) {
                list_checks[i].timestamp = new Date(list_checks[i].timestamp.replace(" ", "T") + "Z");
                list_checks[i].timestamp_locale = new Date(list_checks[i].timestamp).toLocaleString();
            }
            return list_checks;
        });
    }

    return {
        'getStats': getStats,
        'get': get,
        'post': post,
        get_changes,
        get_clicks,
        get_checks,
    };
}]);
<commit_msg>added steps to lib<commit_after>angular.module('RadioBrowserApp').factory('radiobrowser', ['$http', function radiobrowser($http) {
    var SERVER = "https://de1.api.radio-browser.info";
    var SERVERs = [
        "de1.api.radio-browser.info",
        "nl1.api.radio-browser.info",
        "fr1.api.radio-browser.info",
    ];
    var PROTOCOL = "https";
    //var SERVER = "http://localhost:8080";

    function getStats() {
        return $http.get(SERVER + '/json/stats');
    }

    function post(relLink, data) {
        return $http.post(SERVER + relLink, data);
    }

    function get(relLink) {
        return $http.get(SERVER + relLink);
    }

    function build_check_step_tree(list, parent) {
        let result = [];
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if (item.parent_stepuuid === parent) {
                result.push(item);
                item.children = build_check_step_tree(list, item.stepuuid);
            }
        }
        return result;
    }

    function get_all_servers(relLink) {
        var jobs = [];
        for (var i = 0; i < SERVERs.length; i++) {
            var servername = "" + SERVERs[i];
            let job = $http.get(PROTOCOL + "://" + servername + relLink);
            jobs.push(job);
        }
        return Promise.all(jobs).then(function (results) {
            var list = [];
            for (var i = 0; i < SERVERs.length; i++) {
                list.push({
                    servername: SERVERs[i],
                    result: build_check_step_tree(results[i].data, null),
                });
            }
            return list;
        });
    }

    function get_changes(uuid) {
        return get('/json/stations/changed/' + uuid).then(function (data) {
            var list_changes = data.data;
            for (var i = 0; i < list_changes.length; i++) {
                list_changes[i].lastchangetime = new Date(list_changes[i].lastchangetime.replace(" ", "T") + "Z");
                list_changes[i].lastchangetime_locale = new Date(list_changes[i].lastchangetime).toLocaleString();
            }
            return list_changes;
        });
    }

    function get_clicks(uuid, seconds) {
        return get('/json/clicks/' + uuid + "?seconds=" + seconds).then(function (data) {
            var list_clicks = data.data;
            for (var i = 0; i < list_clicks.length; i++) {
                list_clicks[i].clicktimestamp = new Date(list_clicks[i].clicktimestamp.replace(" ", "T") + "Z");
                list_clicks[i].clicktimestamp_locale = new Date(list_clicks[i].clicktimestamp).toLocaleString();
            }
            return list_clicks;
        });
    }

    function get_checks(uuid) {
        return get('/json/checks/' + uuid).then(function (data) {
            var list_checks = data.data;
            for (var i = 0; i < list_checks.length; i++) {
                list_checks[i].timestamp = new Date(list_checks[i].timestamp.replace(" ", "T") + "Z");
                list_checks[i].timestamp_locale = new Date(list_checks[i].timestamp).toLocaleString();
            }
            return list_checks;
        });
    }

    function get_check_steps(uuid) {
        return get_all_servers('/json/checksteps?uuids=' + uuid).then(function (results) {
            return results;
        });
    }

    return {
        'getStats': getStats,
        'get': get,
        'post': post,
        get_changes,
        get_clicks,
        get_checks,
        get_check_steps,
    };
}]);
<|endoftext|>


<commit_before>import Vue from 'vue';
import App from './App';
import router from './router';
import Vuex from 'vuex';
import io from 'socket.io-client'

var socket = io.connect('http://localhost:8081');
    socket.emit('load', {});

    socket.on('load', function (data) {
      console.log('Loading');
    });

Vue.use(Vuex);

Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    places: [
      { place: 'London', title: '', active: false, id: 'london' },
      { place: 'France', title: '', active: false, id: 'france' },
      { place: 'Germany', title: '', active: false, id: 'germany' },
      { place: 'Sunderland', title: '', active: false, id: 'sunderland' }
    ],
    placeform: true
  },
  mutations: {
    activate (state, payload) {
      state.places.map((place)=>{ place.active = place.id===payload.id ? true : false; });
      if (payload.id==='placeform') {
        state.placeform = true;
      } else {
        state.placeform = false;
      }
      socket.emit('load', {});
    },
    remove (state, payload) {
      //delete signpost arm
      state.places.splice(payload.id, 1);
      state.places.map((p)=>{
        if (p.index > payload.id) {
          p.index--;
          //signpost.move(p.id, +1);
        }
      });
      state.placeform = true;
    }
  }
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
});
<commit_msg>Made app externally visible<commit_after>import Vue from 'vue';
import App from './App';
import router from './router';
import Vuex from 'vuex';
import io from 'socket.io-client'

Vue.use(Vuex);

Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    places: [
      { place: 'London', title: '', active: false, id: 'london' },
      { place: 'France', title: '', active: false, id: 'france' },
      { place: 'Germany', title: '', active: false, id: 'germany' },
      { place: 'Sunderland', title: '', active: false, id: 'sunderland' }
    ],
    placeform: true
  },
  mutations: {
    activate (state, payload) {
      state.places.map((place)=>{ place.active = place.id===payload.id ? true : false; });
      if (payload.id==='placeform') {
        state.placeform = true;
      } else {
        state.placeform = false;
      }
      socket.emit('load', {});
    },
    remove (state, payload) {
      //delete signpost arm
      state.places.splice(payload.id, 1);
      state.places.map((p)=>{
        if (p.index > payload.id) {
          p.index--;
          //signpost.move(p.id, +1);
        }
      });
      state.placeform = true;
    }
  }
});

/* eslint-disable no-new */
var app = new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App),
  methods: {
    alert: function() {

    }
  }
});

var socket = io.connect('http://localhost:8081');
    //socket.emit('load', {});

    socket.on('load', function (data) {
      console.log('Loading');
      app.alert();
    });
<|endoftext|>


<commit_before>const issue = (state = {}, action, currentIssue) => {
  switch (action.type) {
    case 'CREATE_ISSUE':
      return {
        id: action.id,
        text: action.text,
        alternatives: action.alternatives,
        votes: [],
        resolutionType: action.resolutionType,
      };

    case 'SEND_VOTE':
      // If the vote has been cancelled before this vote was submitted, it needs
      // to be discarded. We also skip it if this is not the current issue.
      if (state.id !== currentIssue || state.id !== action.id) {
        return state;
      }

      return {
        ...state,

        votes: [
          ...state.votes,

          {
            alternative: action.alternative,
            voter: action.voter,
          },
        ],
      };

    case 'RECEIVE_VOTE':
      if (state.id !== currentIssue || state.id !== action.id) {
        return state;
      }

      return {
        ...state,

        votes: [
          ...state.votes,

          {
            alternative: action.alternative,
            voter: action.voter,
          },
        ],
      };

    default:
      return state;
  }
};

const defaultIssues = [{
  id: 0,
  text: 'Trump',
  alternatives: [{
    id: 0,
    text: 'yes',
  }],

  votes: [],

  majorityTreshold: 0.5,
  isActive: false,
}];

const issues = (state = defaultIssues, action) => {
  switch (action.type) {
    case 'CREATE_ISSUE':
      return [
        ...state,
        issue(undefined, action),
      ];

    case 'SEND_VOTE':
      return state.map(i => issue(i, action, state[state.length - 1].id));

    case 'RECEIVE_VOTE':
      return state.map(i => issue(i, action, state[state.length - 1].id));

    default:
      return state;
  }
};

export default issues;
<commit_msg>add sample closed issues<commit_after>const issue = (state = {}, action, currentIssue) => {
  switch (action.type) {
    case 'CREATE_ISSUE':
      return {
        id: action.id,
        text: action.text,
        alternatives: action.alternatives,
        votes: [],
        resolutionType: action.resolutionType,
      };

    case 'SEND_VOTE':
      // If the vote has been cancelled before this vote was submitted, it needs
      // to be discarded. We also skip it if this is not the current issue.
      if (state.id !== currentIssue || state.id !== action.id) {
        return state;
      }

      return {
        ...state,

        votes: [
          ...state.votes,

          {
            alternative: action.alternative,
            voter: action.voter,
          },
        ],
      };

    case 'RECEIVE_VOTE':
      if (state.id !== currentIssue || state.id !== action.id) {
        return state;
      }

      return {
        ...state,

        votes: [
          ...state.votes,

          {
            alternative: action.alternative,
            voter: action.voter,
          },
        ],
      };

    default:
      return state;
  }
};

const defaultIssues = [{
  id: 0,
  text: 'Trump',
  alternatives: [{
    id: 0,
    text: 'yes',
  }],

  votes: [],

  majorityTreshold: 0.5,
  isActive: false,
}, {
  id: 1,
  text: 'YO hello this is long text',
  alternatives: [{
    id: 0,
    text: 'yes',
  }, {
    id: 1,
    text: 'yes',
  }, {
    id: 2,
    text: 'yes',
  }],

  votes: [],

  majorityTreshold: 0.5,
  isActive: false,
}, {
  id: 2,
  text: 'Half-giant jinxes peg-leg gillywater broken glasses large black dog Great Hall. Nearly-Headless Nick now string them together, and answer me this, which creature would you be unwilling to kiss? Poltergeist sticking charm, troll umbrella stand flying cars golden locket Lily Potter. Pumpkin juice Trevor wave your wand out glass orbs, a Grim knitted hats. Stan Shunpike doe patronus, suck his soul Muggle-Born large order of drills the trace. Bred in captivity fell through the veil, quaffle blue flame ickle diddykins Aragog. Yer a wizard, Harry Doxycide the woes of Mrs. Weasley Goblet of Fire',
  alternatives: [{
    id: 0,
    text: 'yes',
  }, {
    id: 1,
    text: 'yes',
  }, {
    id: 2,
    text: 'yes',
  }],

  votes: [],

  majorityTreshold: 0.5,
  isActive: false,
}];

const issues = (state = defaultIssues, action) => {
  switch (action.type) {
    case 'CREATE_ISSUE':
      return [
        ...state,
        issue(undefined, action),
      ];

    case 'SEND_VOTE':
      return state.map(i => issue(i, action, state[state.length - 1].id));

    case 'RECEIVE_VOTE':
      return state.map(i => issue(i, action, state[state.length - 1].id));

    default:
      return state;
  }
};

export default issues;
<|endoftext|>


<commit_before>import { handleActions } from 'redux-actions';

const initialState = {
  carMake: 'cadillac',
  value: 0,
  startYear:1990,
  endYear:2017,
  minPrice:1000,
  maxPrice:150000,
  zipcode:'',
  model: 'Fleetwood',
  loading: false,
  modelIndex: 3,
  searchResults:[],
  allCars: {
    amc: {
      name: 'AMC',
      models: ['AMX', 'Concord', 'Eagle', 'Gremlin', 'Matador', 'Pacer'],
    },
    alfa: {
      name: 'Alfa-Romeo',
      models: ['159', '4C', 'Alfasud', 'Brera', 'GTV6', 'Giulia', 'MiTo', 'Spider'],
    },
    aston: {
      name: 'Aston Martin',
      models: ['DB5', 'DB9', 'DBS', 'Rapide', 'Vanquish', 'Vantage'],
    },
    audi: {
      name: 'Audi',
      models: ['90', '4000', '5000', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'Q5', 'Q7'],
    },
    austin: {
      name: 'Austin',
      models: ['America', 'Maestro', 'Maxi', 'Mini', 'Montego', 'Princess'],
    },
    borgward: {
      name: 'Borgward',
      models: ['Hansa', 'Isabella', 'P100'],
    },
    buick: {
      name: 'Buick',
      models: ['Electra', 'LaCrosse', 'LeSabre', 'Park Avenue', 'Regal',
      'Roadmaster', 'Skylark'],
    },
    cadillac: {
      name: 'Cadillac',
      models: ['Catera', 'Cimarron', 'Eldorado', 'Fleetwood', 'Sedan de Ville'],
    },
    chevrolet: {
      name: 'Chevrolet',
      models: ['Astro', 'Aveo', 'Bel Air', 'Captiva', 'Cavalier', 'Chevelle',
      'Corvair', 'Corvette', 'Cruze', 'Nova', 'SS', 'Vega', 'Volt'],
    }
  }
};

export default handleActions({
  // GET_CARDATA: (state, { payload }) => ({
  //   ...state,
  //   ...payload.payload
  // }),
  GET_CARDATA: (state, action ) => ({ ...state, searchResults:[...action.payload.extractorData.data[0].group]}),
  SET_QUERY: (state, action) => ({
    ...state,
    ...action.payload })
}, initialState);
<commit_msg>save batched results to state<commit_after>import { handleActions } from 'redux-actions';

const initialState = {
  carMake: 'cadillac',
  value: 0,
  startYear:1990,
  endYear:2017,
  minPrice:1000,
  maxPrice:150000,
  zipcode:'',
  model: 'Fleetwood',
  loading: false,
  modelIndex: 3,
  searchResults:[],
  allCars: {
    amc: {
      name: 'AMC',
      models: ['AMX', 'Concord', 'Eagle', 'Gremlin', 'Matador', 'Pacer'],
    },
    alfa: {
      name: 'Alfa-Romeo',
      models: ['159', '4C', 'Alfasud', 'Brera', 'GTV6', 'Giulia', 'MiTo', 'Spider'],
    },
    aston: {
      name: 'Aston Martin',
      models: ['DB5', 'DB9', 'DBS', 'Rapide', 'Vanquish', 'Vantage'],
    },
    audi: {
      name: 'Audi',
      models: ['90', '4000', '5000', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'Q5', 'Q7'],
    },
    austin: {
      name: 'Austin',
      models: ['America', 'Maestro', 'Maxi', 'Mini', 'Montego', 'Princess'],
    },
    borgward: {
      name: 'Borgward',
      models: ['Hansa', 'Isabella', 'P100'],
    },
    buick: {
      name: 'Buick',
      models: ['Electra', 'LaCrosse', 'LeSabre', 'Park Avenue', 'Regal',
      'Roadmaster', 'Skylark'],
    },
    cadillac: {
      name: 'Cadillac',
      models: ['Catera', 'Cimarron', 'Eldorado', 'Fleetwood', 'Sedan de Ville'],
    },
    chevrolet: {
      name: 'Chevrolet',
      models: ['Astro', 'Aveo', 'Bel Air', 'Captiva', 'Cavalier', 'Chevelle',
      'Corvair', 'Corvette', 'Cruze', 'Nova', 'SS', 'Vega', 'Volt'],
    }
  }
};

export default handleActions({
  // GET_CARDATA: (state, { payload }) => ({
  //   ...state,
  //   ...payload.payload
  // }),
  GET_CARDATA: (state, action ) => ({ ...state, searchResults:[action.payload]}),
  SET_QUERY: (state, action) => ({
    ...state,
    ...action.payload })
}, initialState);
<|endoftext|>


<commit_before>(function (w, d) {
  'use strict';

  var config, logger;

  config = w.goodies = w.goodies || { };

  config.debugMode = !!localStorage.goodiesDebugMode;

  logger = {};
  ['debug', 'log', 'info', 'error', 'warn'].forEach(function (funcName) {
    logger[funcName] = function () {
      if (config.debugMode) {
        console[funcName].apply(console, arguments);
      }
    };
  });

  function addPlayerPuzzlesPageFunctionality(scope, titleElement) {
    var chk, ui = d.createElement('div');
    ui.innerHTML = '<input type="checkbox" id="chkTodo" />  ' +
                   'Only show unsolved unambiguous puzzles';

    titleElement.parentElement.insertBefore(ui, titleElement.nextElementSibling);

    chk = d.getElementById('chkTodo');
    chk.addEventListener('click', function () {
      scope.allPuzzles = scope.allPuzzles || scope.puzzles;

      if (this.checked) {
        scope.puzzles = scope.allPuzzles.filter(function (p) {
          return !(p.solved || p.ambiguous);
        });
      } else {
        scope.puzzles = scope.allPuzzles;
      }

      scope.$apply();
    });
  }

  function addPuzzleFunctionality(scope, topElement) {
    var puzzleAdapter, persistenceUI, persistence,
      puzzle = scope.puzzle,

      Cell = function (inputElement, angularModel) {
        Cell.emptyCellPlaceholder = '\xB7';

        var self = this;

        this.ui = inputElement;
        this.regexes = [];

        inputElement.addEventListener('input', function () {
          self.regexes.forEach(function (re) {
            re.validate();
          });
        });

        this.registerRegexElement = function (regexElement) {
          this.regexes.push(regexElement);
        };

        this.getValue = function () {
          if (inputElement.classList.contains('space')) {
            return ' ';
          }

          if (inputElement.value) {
            return inputElement.value.toUpperCase();
          }

          return null;
        };

        this.setValue = function (newValue) {
          if (newValue === ' ') {
            inputElement.classList.add('space');
          } else {
            inputElement.classList.remove('space');
          }

          if (newValue === Cell.emptyCellPlaceholder) {
            newValue = null;
          }
          angularModel.value = newValue;
        };
      },

      RegexElement = function (cells, expression, uiClueElement) {
        var self = this;

        cells.forEach(function (c) {
          c.registerRegexElement(self);
        });

        this.regex = new RegExp('^(?:' + expression + ')$');

        this.validate = function () {
          logger.debug('Validating: ' + this.regex);

          var answer = '', i, chr;

          for (i = 0; i < cells.length; i++) {
            chr = cells[i].getValue();

            if (chr) {
              answer += chr;
            } else {
              answer = null;
              break;
            }
          }

          uiClueElement.classList.remove('clue-error');
          uiClueElement.classList.remove('clue-ok');

          if (answer) {
            if (answer.match(this.regex)) {
              uiClueElement.classList.add('clue-ok');
            } else {
              uiClueElement.classList.add('clue-error');
            }
          }
        };
      },

      BasePuzzleAdapter = function () {
        this.regexElements = [];

        this.getAnswer = function () {
          var answer = '';

          this.cells.forEach(function (c) {
            answer += c.getValue() || Cell.emptyCellPlaceholder;
          });

          return answer;
        };

        this.setAnswer = function (answer) {
          var i;

          for (i = 0; i < this.cells.length; i++) {
            if (i >= answer.length) {
              break;
            }

            this.cells[i].setValue(answer[i]);

            scope.$apply();
          }
        };
      },

      RectangularPuzzleAdapter = function () {
        BasePuzzleAdapter.call(this);

        var rowCount, colCount, self = this;

        function getCells(textBoxes) {
          var cells = [], i, j;

          for (i = 0; i < rowCount; i++) {
            for (j = 0; j < colCount; j++) {
              cells.push(new Cell(
                textBoxes[i * colCount + j],
                scope.puzzle.answer.rows[i][j]
              ));
            }
          }

          return cells;
        }

        function addHorizontalRegexElements(cells) {
          var usedCells = [], patterns, i,
            clueUIElements = topElement.querySelectorAll('th.clue');

          for (i = 0; i < rowCount; i++) {
            usedCells = cells.slice(i * colCount, (i + 1) * colCount);

            patterns = scope.puzzle.patternsY.patterns[i];

            // left clue
            if (patterns.a.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.a.value, clueUIElements[i * 2])
              );
            }

            // right clue
            if (patterns.b.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.b.value, clueUIElements[i * 2 + 1])
              );
            }
          }
        }

        function addVerticalRegexElements(cells) {
          var usedCells, patterns, i, j,
            clueUIElements = topElement.querySelectorAll('div.clue');

          for (j = 0; j < colCount; j++) {
            usedCells = [];

            for (i = 0; i < rowCount; i++) {
              usedCells.push(cells[i * colCount + j]);
            }

            patterns = scope.puzzle.patternsX.patterns[j];

            // top clue
            if (patterns.a.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.a.value, clueUIElements[j])
              );
            }

            // bottom clue
            if (patterns.b.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.b.value, clueUIElements[j + colCount])
              );
            }
          }
        }

        this.init = function () {
          var textBoxes;

          rowCount = scope.puzzle.answer.rows.length;
          colCount = scope.puzzle.answer.rows[0].length;

          logger.debug('Rectangular puzzle ' + colCount + ' by ' + rowCount);
          textBoxes = topElement.querySelectorAll('input.char');

          if (textBoxes.length < rowCount * colCount) {
            logger.debug('Waiting for textboxes to render...');
            w.setTimeout(function () {
              self.init();
            }, 10);

            return;
          }

          this.cells = getCells(textBoxes);

          addHorizontalRegexElements(this.cells);
          addVerticalRegexElements(this.cells);
        };
      },

      HexagonalPuzzleAdapter = function () {
        var Hexagon = function (rowCount, middleRowSize, elements) {
          // tests for this class available at http://jsbin.com/biwoya/13/edit
          var i, j, diagonal, rowDelta, idx,
            currentOffset = 0,
            middleRowIndex = (rowCount - 1) / 2,
            currentRowSize = middleRowSize - middleRowIndex;

          this.rows = [];
          for (i = 0; i < rowCount; i++) {
            this.rows.push(elements.slice(currentOffset, currentOffset + currentRowSize));
            currentOffset = currentOffset + currentRowSize;
            currentRowSize += i < rowCount / 2 ? 1 : -1;
          }

          this.diagonalsNW_SE = [];
          for (j = 0; j < middleRowSize; j++) {
            diagonal = [];

            for (i = 0; i < rowCount; i++) {
              rowDelta = i < middleRowIndex ? (i - middleRowIndex) : 0;
              idx = j + rowDelta;

              if (idx >= 0 && idx < this.rows[i].length) {
                diagonal.push(this.rows[i][idx]);
              }
            }

            this.diagonalsNW_SE.push(diagonal.reverse());
          }

          this.diagonalsNE_SW = [];
          for (j = 0; j < middleRowSize; j++) {
            diagonal = [];

            for (i = 0; i < rowCount; i++) {
              rowDelta = i > middleRowIndex ? (middleRowIndex - i) : 0;
              idx = j + rowDelta;

              if (idx >= 0 && idx < this.rows[i].length) {
                diagonal.push(this.rows[i][idx]);
              }
            }

            this.diagonalsNE_SW.push(diagonal);
          }
        };

        BasePuzzleAdapter.call(this);

        this.init = function () {
          var hexPuzzle = scope.puzzle;

          this.rowCount = hexPuzzle.patternsY.length;
          this.middleRowLength = hexPuzzle.patternsX.length;

          this.cells = topElement.querySelectorAll('input.char');

          logger.warn('todo!');
        };
      },

      PersistenceUI = function () {
        var addButton = function (name) {
          var newBtn, controlContainer;

          newBtn = d.createElement('button');
          newBtn.type = 'button';
          newBtn.classList.add('btn');
          newBtn.classList.add('btn-default');
          newBtn.textContent = name;

          controlContainer = topElement.querySelector('h1');

          controlContainer.appendChild(document.createTextNode(' '));
          controlContainer.appendChild(newBtn);

          return newBtn;
        };

        this.init = function () {
          var saveBtn, loadBtn;

          saveBtn = addButton('Save');
          saveBtn.addEventListener('click', this.onSaveClick);

          loadBtn = addButton('Load');
          loadBtn.addEventListener('click', this.onLoadClick);
        };

        this.getTextBoxes = function () {
          return topElement.querySelectorAll('input.char');
        };
      };

    if (!puzzle) {
      // puzzle not yet loaded...
      return;
    }

    persistence = {
      load: function () {
        return w.prompt('Enter previous solution:');
      },
      save: function (currentSolution) {
        w.prompt('Put this in a safe place:', currentSolution);
      }
    };

    persistenceUI = new PersistenceUI();

    puzzleAdapter = puzzle.hexagonal
      ? new HexagonalPuzzleAdapter()
      : new RectangularPuzzleAdapter();

    persistenceUI.onLoadClick = function () {
      logger.info('loading.');
      puzzleAdapter.setAnswer(persistence.load());
    };
    persistenceUI.onSaveClick = function () {
      logger.info('saving.');
      persistence.save(puzzleAdapter.getAnswer());
    };

    persistenceUI.init();
    puzzleAdapter.init();

    puzzleAdapter.onAnswerChange = function () {
      puzzleAdapter.validate();
    };
  }

  function onViewChanged() {
    logger.log('View changed!');

    var scope, puzzleListTitleElement,
      puzzleElement = d.querySelector('div.challenge-puzzle') || d.querySelector('div.playerpuzzle');

    if (puzzleElement) {
      scope = angular.element(puzzleElement).scope();
      addPuzzleFunctionality(scope, puzzleElement);
      return;
    }

    puzzleListTitleElement = d.querySelector('div.container h2');

    if (puzzleListTitleElement && puzzleListTitleElement.textContent === 'Puzzles') {
      scope = angular.element(puzzleListTitleElement).scope();
      addPlayerPuzzlesPageFunctionality(scope, puzzleListTitleElement);
    }
  }

  function appendStyles() {
    var styleTag = d.createElement('style');
    styleTag.type = 'text/css';
    styleTag.textContent = '.clue-error{color:red;}.clue-ok{color:#2A2;}';
    d.head.appendChild(styleTag);
  }

  function start() {
    config.rootElement = d.querySelector('div[ng-view]');

    if (!config.rootElement) {
      logger.warn('root element not yet found.');
      w.setTimeout(start, 100);
      return;
    }

    appendStyles();

    logger.info('root element found!');
    config.rootScope = angular.element(config.rootElement).scope().$root;

    config.rootScope.$on('$viewContentLoaded', onViewChanged);
    onViewChanged();
  }

  start();

}(window, document));

<commit_msg>fixed player puzzle list bug<commit_after>(function (w, d) {
  'use strict';

  var config, logger;

  config = w.goodies = w.goodies || { };

  config.debugMode = !!localStorage.goodiesDebugMode;

  logger = {};
  ['debug', 'log', 'info', 'error', 'warn'].forEach(function (funcName) {
    logger[funcName] = function () {
      if (config.debugMode) {
        console[funcName].apply(console, arguments);
      }
    };
  });

  function addPlayerPuzzlesPageFunctionality(scope, titleElement) {
    var chk, ui = d.createElement('div');

    scope.allPuzzles = scope.puzzles;

    ui.innerHTML = '<input type="checkbox" id="chkTodo" />  ' +
                   'Only show unsolved unambiguous puzzles';

    titleElement.parentElement.insertBefore(ui, titleElement.nextElementSibling);
    chk = d.getElementById('chkTodo');
    chk.addEventListener('click', function () {
      if (this.checked) {
        scope.puzzles = scope.allPuzzles.filter(function (p) {
          return !(p.solved || p.ambiguous);
        });
      } else {
        scope.puzzles = scope.allPuzzles;
      }

      scope.$apply();
    });
  }

  function addPuzzleFunctionality(scope, topElement) {
    var puzzleAdapter, persistenceUI, persistence,
      puzzle = scope.puzzle,

      Cell = function (inputElement, angularModel) {
        Cell.emptyCellPlaceholder = '\xB7';

        var self = this;

        this.ui = inputElement;
        this.regexes = [];

        inputElement.addEventListener('input', function () {
          self.regexes.forEach(function (re) {
            re.validate();
          });
        });

        this.registerRegexElement = function (regexElement) {
          this.regexes.push(regexElement);
        };

        this.getValue = function () {
          if (inputElement.classList.contains('space')) {
            return ' ';
          }

          if (inputElement.value) {
            return inputElement.value.toUpperCase();
          }

          return null;
        };

        this.setValue = function (newValue) {
          if (newValue === ' ') {
            inputElement.classList.add('space');
          } else {
            inputElement.classList.remove('space');
          }

          if (newValue === Cell.emptyCellPlaceholder) {
            newValue = null;
          }
          angularModel.value = newValue;
        };
      },

      RegexElement = function (cells, expression, uiClueElement) {
        var self = this;

        cells.forEach(function (c) {
          c.registerRegexElement(self);
        });

        this.regex = new RegExp('^(?:' + expression + ')$');

        this.validate = function () {
          logger.debug('Validating: ' + this.regex);

          var answer = '', i, chr;

          for (i = 0; i < cells.length; i++) {
            chr = cells[i].getValue();

            if (chr) {
              answer += chr;
            } else {
              answer = null;
              break;
            }
          }

          uiClueElement.classList.remove('clue-error');
          uiClueElement.classList.remove('clue-ok');

          if (answer) {
            if (answer.match(this.regex)) {
              uiClueElement.classList.add('clue-ok');
            } else {
              uiClueElement.classList.add('clue-error');
            }
          }
        };
      },

      BasePuzzleAdapter = function () {
        this.regexElements = [];

        this.getAnswer = function () {
          var answer = '';

          this.cells.forEach(function (c) {
            answer += c.getValue() || Cell.emptyCellPlaceholder;
          });

          return answer;
        };

        this.setAnswer = function (answer) {
          var i;

          for (i = 0; i < this.cells.length; i++) {
            if (i >= answer.length) {
              break;
            }

            this.cells[i].setValue(answer[i]);

            scope.$apply();
          }
        };
      },

      RectangularPuzzleAdapter = function () {
        BasePuzzleAdapter.call(this);

        var rowCount, colCount, self = this;

        function getCells(textBoxes) {
          var cells = [], i, j;

          for (i = 0; i < rowCount; i++) {
            for (j = 0; j < colCount; j++) {
              cells.push(new Cell(
                textBoxes[i * colCount + j],
                scope.puzzle.answer.rows[i][j]
              ));
            }
          }

          return cells;
        }

        function addHorizontalRegexElements(cells) {
          var usedCells = [], patterns, i,
            clueUIElements = topElement.querySelectorAll('th.clue');

          for (i = 0; i < rowCount; i++) {
            usedCells = cells.slice(i * colCount, (i + 1) * colCount);

            patterns = scope.puzzle.patternsY.patterns[i];

            // left clue
            if (patterns.a.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.a.value, clueUIElements[i * 2])
              );
            }

            // right clue
            if (patterns.b.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.b.value, clueUIElements[i * 2 + 1])
              );
            }
          }
        }

        function addVerticalRegexElements(cells) {
          var usedCells, patterns, i, j,
            clueUIElements = topElement.querySelectorAll('div.clue');

          for (j = 0; j < colCount; j++) {
            usedCells = [];

            for (i = 0; i < rowCount; i++) {
              usedCells.push(cells[i * colCount + j]);
            }

            patterns = scope.puzzle.patternsX.patterns[j];

            // top clue
            if (patterns.a.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.a.value, clueUIElements[j])
              );
            }

            // bottom clue
            if (patterns.b.value) {
              self.regexElements.push(
                new RegexElement(usedCells, patterns.b.value, clueUIElements[j + colCount])
              );
            }
          }
        }

        this.init = function () {
          var textBoxes;

          rowCount = scope.puzzle.answer.rows.length;
          colCount = scope.puzzle.answer.rows[0].length;

          logger.debug('Rectangular puzzle ' + colCount + ' by ' + rowCount);
          textBoxes = topElement.querySelectorAll('input.char');

          if (textBoxes.length < rowCount * colCount) {
            logger.debug('Waiting for textboxes to render...');
            w.setTimeout(function () {
              self.init();
            }, 10);

            return;
          }

          this.cells = getCells(textBoxes);

          addHorizontalRegexElements(this.cells);
          addVerticalRegexElements(this.cells);
        };
      },

      HexagonalPuzzleAdapter = function () {
        var Hexagon = function (rowCount, middleRowSize, elements) {
          // tests for this class available at http://jsbin.com/biwoya/13/edit
          var i, j, diagonal, rowDelta, idx,
            currentOffset = 0,
            middleRowIndex = (rowCount - 1) / 2,
            currentRowSize = middleRowSize - middleRowIndex;

          this.rows = [];
          for (i = 0; i < rowCount; i++) {
            this.rows.push(elements.slice(currentOffset, currentOffset + currentRowSize));
            currentOffset = currentOffset + currentRowSize;
            currentRowSize += i < rowCount / 2 ? 1 : -1;
          }

          this.diagonalsNW_SE = [];
          for (j = 0; j < middleRowSize; j++) {
            diagonal = [];

            for (i = 0; i < rowCount; i++) {
              rowDelta = i < middleRowIndex ? (i - middleRowIndex) : 0;
              idx = j + rowDelta;

              if (idx >= 0 && idx < this.rows[i].length) {
                diagonal.push(this.rows[i][idx]);
              }
            }

            this.diagonalsNW_SE.push(diagonal.reverse());
          }

          this.diagonalsNE_SW = [];
          for (j = 0; j < middleRowSize; j++) {
            diagonal = [];

            for (i = 0; i < rowCount; i++) {
              rowDelta = i > middleRowIndex ? (middleRowIndex - i) : 0;
              idx = j + rowDelta;

              if (idx >= 0 && idx < this.rows[i].length) {
                diagonal.push(this.rows[i][idx]);
              }
            }

            this.diagonalsNE_SW.push(diagonal);
          }
        };

        BasePuzzleAdapter.call(this);

        this.init = function () {
          var hexPuzzle = scope.puzzle;

          this.rowCount = hexPuzzle.patternsY.length;
          this.middleRowLength = hexPuzzle.patternsX.length;

          this.cells = topElement.querySelectorAll('input.char');

          logger.warn('todo!');
        };
      },

      PersistenceUI = function () {
        var addButton = function (name) {
          var newBtn, controlContainer;

          newBtn = d.createElement('button');
          newBtn.type = 'button';
          newBtn.classList.add('btn');
          newBtn.classList.add('btn-default');
          newBtn.textContent = name;

          controlContainer = topElement.querySelector('h1');

          controlContainer.appendChild(document.createTextNode(' '));
          controlContainer.appendChild(newBtn);

          return newBtn;
        };

        this.init = function () {
          var saveBtn, loadBtn;

          saveBtn = addButton('Save');
          saveBtn.addEventListener('click', this.onSaveClick);

          loadBtn = addButton('Load');
          loadBtn.addEventListener('click', this.onLoadClick);
        };

        this.getTextBoxes = function () {
          return topElement.querySelectorAll('input.char');
        };
      };

    if (!puzzle) {
      // puzzle not yet loaded...
      return;
    }

    persistence = {
      load: function () {
        return w.prompt('Enter previous solution:');
      },
      save: function (currentSolution) {
        w.prompt('Put this in a safe place:', currentSolution);
      }
    };

    persistenceUI = new PersistenceUI();

    puzzleAdapter = puzzle.hexagonal
      ? new HexagonalPuzzleAdapter()
      : new RectangularPuzzleAdapter();

    persistenceUI.onLoadClick = function () {
      logger.info('loading.');
      puzzleAdapter.setAnswer(persistence.load());
    };
    persistenceUI.onSaveClick = function () {
      logger.info('saving.');
      persistence.save(puzzleAdapter.getAnswer());
    };

    persistenceUI.init();
    puzzleAdapter.init();

    puzzleAdapter.onAnswerChange = function () {
      puzzleAdapter.validate();
    };
  }

  function onViewChanged() {
    logger.log('View changed!');

    var scope, puzzleListTitleElement,
      puzzleElement = d.querySelector('div.challenge-puzzle') || d.querySelector('div.playerpuzzle');

    if (puzzleElement) {
      scope = angular.element(puzzleElement).scope();
      addPuzzleFunctionality(scope, puzzleElement);
      return;
    }

    puzzleListTitleElement = d.querySelector('div.container h2');

    if (puzzleListTitleElement && puzzleListTitleElement.textContent === 'Puzzles') {
      scope = angular.element(puzzleListTitleElement).scope();
      addPlayerPuzzlesPageFunctionality(scope, puzzleListTitleElement);
    }
  }

  function appendStyles() {
    var styleTag = d.createElement('style');
    styleTag.type = 'text/css';
    styleTag.textContent = '.clue-error{color:red;}.clue-ok{color:#2A2;}';
    d.head.appendChild(styleTag);
  }

  function start() {
    config.rootElement = d.querySelector('div[ng-view]');

    if (!config.rootElement) {
      logger.warn('root element not yet found.');
      w.setTimeout(start, 100);
      return;
    }

    appendStyles();

    logger.info('root element found!');
    config.rootScope = angular.element(config.rootElement).scope().$root;

    config.rootScope.$on('$viewContentLoaded', onViewChanged);
    onViewChanged();
  }

  start();

}(window, document));

<|endoftext|>


<commit_before>import vm from 'vm';
import fs from 'fs';
import path from 'path';
import moduleSystem from 'module';

function requireModules(keys, root, directory, regExp, recursive) {
  const files = fs.readdirSync(path.join(root, directory));

  files.forEach((filename) => {
    if (regExp.test(filename)) {
      // webpack adds a './' to the begining of the key
      // TODO: Check this in windows
      const entryKey = `./${path.join(directory, filename)}`;
      // eslint-disable-next-line no-param-reassign, global-require, import/no-dynamic-require
      keys[entryKey] = require(path.join(root, directory, filename));
      return;
    }

    if (!recursive) {
      return;
    }

    if (fs.statSync(path.join(root, directory, filename)).isDirectory()) {
      requireModules(keys, root, path.join(directory, filename), regExp, recursive);
    }
  });
}

function isRelativeRequest(request) {
  if (request.charCodeAt(0) !== 46/* .*/) {
    return false;
  }

  if (request === '.' || '..') {
    return true;
  }

  return request.charCodeAt(1) === 47/* /*/ || (
    request.charCodeAt(1) === 46/* .*/ && request.charCodeAt(2) === 47/* /*/);
}

export default function runWithRequireContext(content, options) {
  const { filename, dirname } = options;

  const newRequire = (request) => {
    if (isRelativeRequest(request)) {
      // eslint-disable-next-line global-require, import/no-dynamic-require
      return require(path.resolve(dirname, request));
    }

    // eslint-disable-next-line global-require, import/no-dynamic-require
    return require(request);
  };

  newRequire.resolve = require.resolve;
  newRequire.extensions = require.extensions;
  newRequire.main = require.main;
  newRequire.cache = require.cache;

  newRequire.context = (directory, useSubdirectories = false, regExp = /^\.\//) => {
    const fullPath = path.resolve(dirname, directory);
    const keys = {};
    requireModules(keys, fullPath, '.', regExp, useSubdirectories);

    const req = f => (keys[f]);
    req.keys = () => (Object.keys(keys));
    return req;
  };

  const compiledModule = vm.runInThisContext(moduleSystem.wrap(content));
  compiledModule(module.exports, newRequire, module, filename, dirname);
}
<commit_msg>Test regex for the whole path instead of just the filename<commit_after>import vm from 'vm';
import fs from 'fs';
import path from 'path';
import moduleSystem from 'module';

function requireModules(keys, root, directory, regExp, recursive) {
  const files = fs.readdirSync(path.join(root, directory));

  files.forEach((filename) => {
    if (regExp.test(path.join(directory, filename))) {
      // webpack adds a './' to the begining of the key
      // TODO: Check this in windows
      const entryKey = `./${path.join(directory, filename)}`;
      // eslint-disable-next-line no-param-reassign, global-require, import/no-dynamic-require
      keys[entryKey] = require(path.join(root, directory, filename));
      return;
    }

    if (!recursive) {
      return;
    }

    if (fs.statSync(path.join(root, directory, filename)).isDirectory()) {
      requireModules(keys, root, path.join(directory, filename), regExp, recursive);
    }
  });
}

function isRelativeRequest(request) {
  if (request.charCodeAt(0) !== 46/* .*/) {
    return false;
  }

  if (request === '.' || '..') {
    return true;
  }

  return request.charCodeAt(1) === 47/* /*/ || (
    request.charCodeAt(1) === 46/* .*/ && request.charCodeAt(2) === 47/* /*/);
}

export default function runWithRequireContext(content, options) {
  const { filename, dirname } = options;

  const newRequire = (request) => {
    if (isRelativeRequest(request)) {
      // eslint-disable-next-line global-require, import/no-dynamic-require
      return require(path.resolve(dirname, request));
    }

    // eslint-disable-next-line global-require, import/no-dynamic-require
    return require(request);
  };

  newRequire.resolve = require.resolve;
  newRequire.extensions = require.extensions;
  newRequire.main = require.main;
  newRequire.cache = require.cache;

  newRequire.context = (directory, useSubdirectories = false, regExp = /^\.\//) => {
    const fullPath = path.resolve(dirname, directory);
    const keys = {};
    requireModules(keys, fullPath, '.', regExp, useSubdirectories);

    const req = f => (keys[f]);
    req.keys = () => (Object.keys(keys));
    return req;
  };

  const compiledModule = vm.runInThisContext(moduleSystem.wrap(content));
  compiledModule(module.exports, newRequire, module, filename, dirname);
}
<|endoftext|>


<commit_before>import {Utilities} from '../validation/utilities';

export let data = {
  settings: {
    'numericRegex': /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/
  },
  messages: {
    'isRequired': 'is required',
    'onValidateCallback' : 'not a valid value',
    'AlphaNumericOrWhitespaceValidationRule': (newValue, threshold) => {
      return `can contain only alphanumerical characters or spaces`;
    },
    'AlphaNumericValidationRule': (newValue, threshold) => {
      return `can contain only alphanumerical characters`;
    },
    'AlphaValidationRule' : (newValue, threshold) => {
      return `can contain only letters`;
    },
    'AlphaOrWhitespaceValidationRule' : (newValue, threshold) => {
      return `can contain only letters or spaces`;
    },
    'BetweenLengthValidationRule': (newValue, threshold) => {
      return `needs to be at between ${Utilities.getValue(threshold.minimumLength)} and ${Utilities.getValue(threshold.maximumLength)} characters long`;
    },
    'BetweenValueValidationRule': (newValue, threshold) => {
      return `needs to be between ${Utilities.getValue(threshold.minimumValue)} and ${Utilities.getValue(threshold.maximumValue)}`;
    },
    'CustomFunctionValidationRule': (newValue, threshold) => {
      return `not a valid value`
    },
    'DigitValidationRule': (newValue, threshold) => {
      return `can contain only digits`;
    },
    'EmailValidationRule': (newValue, threshold) => {
      return `is not a valid email address`;
    },
    'EqualityValidationRule': (newValue, threshold) => {
      return `should be ${Utilities.getValue(threshold.otherValue)}`;
    },
    'InEqualityValidationRule' : (newValue, threshold) => {
        return `cannot be ${Utilities.getValue(threshold.otherValue)}`;
    },
    'EqualityWithOtherLabelValidationRule': (newValue, threshold) => {
      return `does not match ${Utilities.getValue(threshold.otherValueLabel)}`;
    },
    'InEqualityWithOtherLabelValidationRule' : (newValue, threshold) => {
      return `cannot match ${Utilities.getValue(threshold.otherValueLabel)}`;
    },
    'InCollectionValidationRule': (newValue, threshold) => {
      return `not a valid value`;
    },
    'MinimumInclusiveValueValidationRule' : (newValue, threshold) => {
      return `needs to be ${Utilities.getValue(threshold)} or more`;
    },
    'MinimumLengthValidationRule': (newValue, threshold) => {
      return `needs to be at least ${Utilities.getValue(threshold)} characters long`;
    },
    'MinimumValueValidationRule': (newValue, threshold) => {
      return `needs to be more than ${Utilities.getValue(threshold)}`;
    },
    'MaximumInclusiveValueValidationRule' : (newValue, threshold) => {
      return `needs to be ${Utilities.getValue(threshold)} or less`;
    },
    'MaximumLengthValidationRule': (newValue, threshold) => {
      return `cannot be longer then ${Utilities.getValue(threshold)} characters`;
    },
    'MaximumValueValidationRule': (newValue, threshold) => {
      return `needs to be less than ${Utilities.getValue(threshold)}`;
    },
    'NumericValidationRule': (newValue, threshold) => {
      return `needs to be a number`;
    },
    'RegexValidationRule': (newValue, threshold) => {
      return `not a valid value`;
    },
    'ContainsOnlyValidationRule': (newValue, threshold) => {
      return `not a valid value`;
    },
    'StrongPasswordValidationRule': (newValue, threshold) => {
      return `should contain a combination of lowercase letters, uppercase letters, digits and special characters`;
    },
    'MediumPasswordValidationRule' : (newValue, threshold) => {
      return `should contain at least ${Utilities.getValue(threshold)} of the following groups: lowercase letters, uppercase letters, digits or special characters`;
    }
  }
};
<commit_msg>fix(en-US): fixed message for BetweenLength<commit_after>import {Utilities} from '../validation/utilities';

export let data = {
  settings: {
    'numericRegex': /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/
  },
  messages: {
    'isRequired': 'is required',
    'onValidateCallback' : 'not a valid value',
    'AlphaNumericOrWhitespaceValidationRule': (newValue, threshold) => {
      return `can contain only alphanumerical characters or spaces`;
    },
    'AlphaNumericValidationRule': (newValue, threshold) => {
      return `can contain only alphanumerical characters`;
    },
    'AlphaValidationRule' : (newValue, threshold) => {
      return `can contain only letters`;
    },
    'AlphaOrWhitespaceValidationRule' : (newValue, threshold) => {
      return `can contain only letters or spaces`;
    },
    'BetweenLengthValidationRule': (newValue, threshold) => {
      return `needs to be between ${Utilities.getValue(threshold.minimumLength)} and ${Utilities.getValue(threshold.maximumLength)} characters long`;
    },
    'BetweenValueValidationRule': (newValue, threshold) => {
      return `needs to be between ${Utilities.getValue(threshold.minimumValue)} and ${Utilities.getValue(threshold.maximumValue)}`;
    },
    'CustomFunctionValidationRule': (newValue, threshold) => {
      return `not a valid value`
    },
    'DigitValidationRule': (newValue, threshold) => {
      return `can contain only digits`;
    },
    'EmailValidationRule': (newValue, threshold) => {
      return `is not a valid email address`;
    },
    'EqualityValidationRule': (newValue, threshold) => {
      return `should be ${Utilities.getValue(threshold.otherValue)}`;
    },
    'InEqualityValidationRule' : (newValue, threshold) => {
        return `cannot be ${Utilities.getValue(threshold.otherValue)}`;
    },
    'EqualityWithOtherLabelValidationRule': (newValue, threshold) => {
      return `does not match ${Utilities.getValue(threshold.otherValueLabel)}`;
    },
    'InEqualityWithOtherLabelValidationRule' : (newValue, threshold) => {
      return `cannot match ${Utilities.getValue(threshold.otherValueLabel)}`;
    },
    'InCollectionValidationRule': (newValue, threshold) => {
      return `not a valid value`;
    },
    'MinimumInclusiveValueValidationRule' : (newValue, threshold) => {
      return `needs to be ${Utilities.getValue(threshold)} or more`;
    },
    'MinimumLengthValidationRule': (newValue, threshold) => {
      return `needs to be at least ${Utilities.getValue(threshold)} characters long`;
    },
    'MinimumValueValidationRule': (newValue, threshold) => {
      return `needs to be more than ${Utilities.getValue(threshold)}`;
    },
    'MaximumInclusiveValueValidationRule' : (newValue, threshold) => {
      return `needs to be ${Utilities.getValue(threshold)} or less`;
    },
    'MaximumLengthValidationRule': (newValue, threshold) => {
      return `cannot be longer then ${Utilities.getValue(threshold)} characters`;
    },
    'MaximumValueValidationRule': (newValue, threshold) => {
      return `needs to be less than ${Utilities.getValue(threshold)}`;
    },
    'NumericValidationRule': (newValue, threshold) => {
      return `needs to be a number`;
    },
    'RegexValidationRule': (newValue, threshold) => {
      return `not a valid value`;
    },
    'ContainsOnlyValidationRule': (newValue, threshold) => {
      return `not a valid value`;
    },
    'StrongPasswordValidationRule': (newValue, threshold) => {
      return `should contain a combination of lowercase letters, uppercase letters, digits and special characters`;
    },
    'MediumPasswordValidationRule' : (newValue, threshold) => {
      return `should contain at least ${Utilities.getValue(threshold)} of the following groups: lowercase letters, uppercase letters, digits or special characters`;
    }
  }
};
<|endoftext|>


<commit_before>import Component from './component';
import Trie from 'route-trie';
import VText from 'virtual-dom/vnode/vtext';

export default class RouterComponent extends Component {

  constructor(application, parent, name, routes = {}) {
    let trie = new Trie();
    let compiledRoutes = {};
    for (let pattern of Object.keys(routes)) {
      compiledRoutes[pattern] = {
        node: trie.define(pattern),
        initializer: routes[pattern]
      };
    }

    let initialState = {
      currentComponentName: null,
      __trie: trie,
      __compiledRoutes: compiledRoutes
    };
    super(application, parent, name, initialState);

    this.onPopStateHandlerBinded = this.onPopStateHandler.bind(this);
  }

  activate() {
    super.activate();

    this.onPopStateHandler();
    window.addEventListener('popstate', this.onPopStateHandlerBinded);
  }

  deactivate() {
    window.removeEventListener('popstate', this.onPopStateHandlerBinded);

    super.deactivate();
  }

  get currentComponentName() {
    return this.state.currentComponentName;
  }

  get currentComponent() {
    return this.currentComponentName !== undefined && this.currentComponentName !== null ?
      this.state[this.currentComponentName] : null;
  }

  get __currentMatch() {
    let hash = this.application.rootNode.ownerDocument.location.hash;
    let path = hash.slice(1);
    return this.state.__trie.match(path);
  }

  onPopStateHandler() {
    if (this.currentComponentName !== undefined && this.currentComponentName !== null) {
      this.currentComponent.deactivate();
      this.state.remove(this.currentComponent.name);
    }
    this.state.remove('currentComponentName');

    if (this.__currentMatch !== null) {
      let currentPattern = currentMatch.node._nodeState.pattern;
      let currentRoute = this.state.__compiledRoutes[currentPattern];

      let currentComponent = currentRoute.initializer(currentMatch, this);

      this.state.set({
        currentComponentName: currentComponent.name,
        [currentComponent.name]: currentComponent
      });

      this.currentComponent.activate();
    }
  };

  render() {
    if (this.currentComponentName === undefined || this.currentComponentName === null) {
      return new VText('Invalid route!');
    }

    return this.currentComponent.render();
  }

}
<commit_msg>routerComponent: Make .routerComponent(|Name) undefined at start but null further<commit_after>import Component from './component';
import Trie from 'route-trie';
import VText from 'virtual-dom/vnode/vtext';

export default class RouterComponent extends Component {

  constructor(application, parent, name, routes = {}) {
    let trie = new Trie();
    let compiledRoutes = {};
    for (let pattern of Object.keys(routes)) {
      compiledRoutes[pattern] = {
        node: trie.define(pattern),
        initializer: routes[pattern]
      };
    }

    let initialState = {
      __trie: trie,
      __compiledRoutes: compiledRoutes
    };
    super(application, parent, name, initialState);

    this.onPopStateHandlerBinded = this.onPopStateHandler.bind(this);
  }

  activate() {
    super.activate();

    this.onPopStateHandler();
    window.addEventListener('popstate', this.onPopStateHandlerBinded);
  }

  deactivate() {
    window.removeEventListener('popstate', this.onPopStateHandlerBinded);

    super.deactivate();
  }

  get currentComponentName() {
    return this.state.currentComponentName;
  }

  get currentComponent() {
    return this.currentComponentName === undefined
      ? undefined
      : this.currentComponentName === null
        ? null
        : this.state[this.currentComponentName];
  }

  get __currentMatch() {
    let hash = this.application.rootNode.ownerDocument.location.hash;
    let path = hash.slice(1);
    return this.state.__trie.match(path);
  }

  onPopStateHandler() {
    if (this.currentComponentName !== undefined && this.currentComponentName !== null) {
      this.currentComponent.deactivate();
      this.state.set(this.currentComponentName, null);
    }
    this.state.set('currentComponentName', null);

    if (this.__currentMatch !== null) {
      let currentPattern = currentMatch.node._nodeState.pattern;
      let currentRoute = this.state.__compiledRoutes[currentPattern];

      let currentComponent = currentRoute.initializer(currentMatch, this);

      this.state.set({
        currentComponentName: currentComponent.name,
        [currentComponent.name]: currentComponent
      });

      this.currentComponent.activate();
    }
  };

  render() {
    if (this.currentComponentName === undefined || this.currentComponentName === null) {
      return new VText('Invalid route!');
    }

    return this.currentComponent.render();
  }

}
<|endoftext|>