<commit_before>let target;

function render(html) {
  $(target).html(html);
}

function renderPage(data, state) {
  data = data || {};

  target = state.target || "#demo";
  state.tweets = state.tweets || [];
  data.tweets = data.tweets || [];

  if (data.tweets.length) {
    state.tweets = data.tweets;
  } else {
    if (!state.tweets.length) {
      renderLoading(data, state);
    }
    if (!data.force) {
      return;
    }
  }

  render(`<div>${statusToHtml(data)}${tweetsToHtml(state.tweets)}</div>`);
}

function renderError(e) {
  const msg = 'No data received from cache or network or error';
  render(`<div class="error">${msg}: ${e}</div>`);
}

function renderLoading(data, state) {
  if (state.tweets.length) return;
  render(`<div class="loading">Loading <span class="dots">...</span></div>`);
  setTimeout(renderDots, 250);
}

function renderDots(n) {
  n = n || 0;
  let dots = [".", ".", "."].filter((d, i) => i <= (n % 3)).join("");
  let $dots = $(target).find('.dots');
  if ($dots.length) {
    $dots.text(dots);
    setTimeout(() => renderDots(n+1), 250);
  }
}

function tweetsToHtml(tweets) {
  return tweets.sort((tw, i) => tw.id).map(tweetToHtml).join("");
}

function tweetToHtml(tweet) {
  let pics = _(tweet.entities.media).map(img => `<img src="${img.media_url_https}" class="tweet-img" />`).join("\n");
  return `

${tweet.text}

      ${pics}

  `;
}

function statusToHtml(data) {
  let deleteLink = "";
  if(data.source === "network") {
    deleteLink = `<a href="#" class="delete-cache">Delete cache</a>`
  }

  return `

        Refresh
        ${deleteLink}

      ${data.message}

  `;
}

export {
  renderPage,
  renderError
}
<commit_msg>Add missing import<commit_after>import _ from 'lodash';

let target;

function render(html) {
  $(target).html(html);
}

function renderPage(data, state) {
  data = data || {};

  target = state.target || "#demo";
  state.tweets = state.tweets || [];
  data.tweets = data.tweets || [];

  if (data.tweets.length) {
    state.tweets = data.tweets;
  } else {
    if (!state.tweets.length) {
      renderLoading(data, state);
    }
    if (!data.force) {
      return;
    }
  }

  render(`<div>${statusToHtml(data)}${tweetsToHtml(state.tweets)}</div>`);
}

function renderError(e) {
  const msg = 'No data received from cache or network or error';
  render(`<div class="error">${msg}: ${e}</div>`);
}

function renderLoading(data, state) {
  if (state.tweets.length) return;
  render(`<div class="loading">Loading <span class="dots">...</span></div>`);
  setTimeout(renderDots, 250);
}

function renderDots(n) {
  n = n || 0;
  let dots = [".", ".", "."].filter((d, i) => i <= (n % 3)).join("");
  let $dots = $(target).find('.dots');
  if ($dots.length) {
    $dots.text(dots);
    setTimeout(() => renderDots(n+1), 250);
  }
}

function tweetsToHtml(tweets) {
  return tweets.sort((tw, i) => tw.id).map(tweetToHtml).join("");
}

function tweetToHtml(tweet) {
  let pics = _(tweet.entities.media).map(img => `<img src="${img.media_url_https}" class="tweet-img" />`).join("\n");
  return `

${tweet.text}

      ${pics}

  `;
}

function statusToHtml(data) {
  let deleteLink = "";
  if(data.source === "network") {
    deleteLink = `<a href="#" class="delete-cache">Delete cache</a>`
  }

  return `

        Refresh
        ${deleteLink}

      ${data.message}

  `;
}

export {
  renderPage,
  renderError
}
<|endoftext|>


<commit_before>/* global define */

define([
  'underscore',
  'backbone',
  'models/settings-model'
], function (_, Backbone, Settings) {
  'use strict';

  var Routes = function () { };

  Routes.prototype = {
    schema: {
      'url':   function (page) {
        return 'page/' + page;
      },
      'query': function (page) {
        return '&page=' + page;
      }
    },

    /**
     * Extract route string from an absolute URL.
     * @param  {String} url Absolute or relative URL.
     * @return {String}     Route.
     */
    routeFromAbsoluteUrl: function (url) {
      if (Settings.get('site_url') + '/' === url) {
        return '';
      }

      var re = new RegExp('^' + Settings.get('site_url') + '/(.+?)/?$', 'g');
      return url.replace(re, '$1');
    },

    processRoutes: function (routes) {
      var keys    = _.keys(routes),
          mapping = {};

      _.each(keys, function (key) {
        var route = routes[key];
        if (!mapping.hasOwnProperty(route.type)) {
          mapping[route.type] = [];
        }

        mapping[route.type].push(getCurlyKey(key));
      });

      return mapping;
    },

    routeIsPaged: function (route) {
      var isPaged = route.match(/(page\/\d+\/?$)|([?&]page=\d+)/);
      return isPaged !== null && isPaged.length > 0;
    },

    buildUri: function (route, replace) {
      var pageRegex   = /(\(\/?page\/.*\))/g,
          pageSection = route.match(pageRegex);

      pageSection = (_.isEmpty(pageSection)) ? '' : pageSection[0];

      if (!replace.paged || replace.paged < 2) {
        route = route.replace(pageSection, '');
        delete replace.paged;
      } else {
        var pageSectionContentRegex = new RegExp(pageSection, 'g'),
            pageSectionContent      = pageSection.match(pageSectionContentRegex);

        route = route.replace(pageSection, pageSectionContent);
      }

      return route.supplant(replace);
    },

    getPagedRoute: function (filter, page) {
      var url   = this.schema[filter.get('paging-schema')],
          regex = /(page\/\d)|(&page=\d)/,
          route = this._getRoute();

      route = (this.routeIsPaged(route)) ? route.replace(regex, url(page))
                                         : route + '/' + url(page);
      return route;
    },

    _getRoute: function () {
      return Backbone.history.fragment;
    }
  };

  function getCurlyKey (key) {
    var attrs = key.match(/([:*]([^\/:()*]+))/g);
    _.each(attrs, function (attr) {
      key = key.replace(attr, '{' + attr.replace(/(:)|(\*)/g, '') + '}');
    });

    return key;
  }

  return new Routes();
});<commit_msg>Add method to get the current page<commit_after>/* global define */

define([
  'underscore',
  'backbone',
  'models/settings-model'
], function (_, Backbone, Settings) {
  'use strict';

  var Routes = function () { };

  Routes.prototype = {
    schema: {
      'url':   function (page) {
        return 'page/' + page;
      },
      'query': function (page) {
        return '&page=' + page;
      }
    },

    /**
     * Extract route string from an absolute URL.
     * @param  {String} url Absolute or relative URL.
     * @return {String}     Route.
     */
    routeFromAbsoluteUrl: function (url) {
      if (Settings.get('site_url') + '/' === url) {
        return '';
      }

      var re = new RegExp('^' + Settings.get('site_url') + '/(.+?)/?$', 'g');
      return url.replace(re, '$1');
    },

    processRoutes: function (routes) {
      var keys    = _.keys(routes),
          mapping = {};

      _.each(keys, function (key) {
        var route = routes[key];
        if (!mapping.hasOwnProperty(route.type)) {
          mapping[route.type] = [];
        }

        mapping[route.type].push(getCurlyKey(key));
      });

      return mapping;
    },

    routeIsPaged: function (route) {
      var isPaged = route.match(/(page\/\d+\/?$)|([?&]page=\d+)/);
      return isPaged !== null && isPaged.length > 0;
    },

    buildUri: function (route, replace) {
      var pageRegex   = /(\(\/?page\/.*\))/g,
          pageSection = route.match(pageRegex);

      pageSection = (_.isEmpty(pageSection)) ? '' : pageSection[0];

      if (!replace.paged || replace.paged < 2) {
        route = route.replace(pageSection, '');
        delete replace.paged;
      } else {
        var pageSectionContentRegex = new RegExp(pageSection, 'g'),
            pageSectionContent      = pageSection.match(pageSectionContentRegex);

        route = route.replace(pageSection, pageSectionContent);
      }

      return route.supplant(replace);
    },

    getPagedRoute: function (filter, page) {
      var url   = this.schema[filter.get('paging-schema')],
          regex = /(page\/\d)|(&page=\d)/,
          route = this._getRoute();

      route = (this.routeIsPaged(route)) ? route.replace(regex, url(page))
                                         : route + '/' + url(page);
      return route;
    },

    getCurrentPage: function () {
      var regex = /page\/(\d)|&page=\d/,
          route = this._getRoute();

      return parseInt(route.match(regex)[1], 10) || 1;
    },

    _getRoute: function () {
      return Backbone.history.fragment;
    }
  };

  function getCurlyKey (key) {
    var attrs = key.match(/([:*]([^\/:()*]+))/g);
    _.each(attrs, function (attr) {
      key = key.replace(attr, '{' + attr.replace(/(:)|(\*)/g, '') + '}');
    });

    return key;
  }

  return new Routes();
});<|endoftext|>


<commit_before>/*
 * Copyright (c) Dominick Baier, Brock Allen.  All rights reserved.
 * see license
 */

/// <reference path="../libs/angular/angular.1.3.15.js" />

window.identityServer = (function () {
    "use strict";

    var identityServer = {
        getModel: function () {
            var modelJson = document.getElementById("modelJson");
            var encodedJson = '';
            if (typeof (modelJson.textContent) !== undefined) {
                encodedJson = modelJson.textContent;
            } else {
                encodedJson = modelJson.innerHTML;
            }
            var json = Encoder.htmlDecode(encodedJson);
            var model = JSON.parse(json);
            return model;
        }
    };

    return identityServer;
})();

(function () {
    "use strict";

    (function () {
        var app = angular.module("app", []);

        app.controller("LayoutCtrl", function ($scope, Model) {
            $scope.model = Model;
        });

        app.directive("antiForgeryToken", function () {
            return {
                restrict: 'E',
                replace: true,
                scope: {
                    token: "="
                },
                template: "<input type='hidden' name='{{token.name}}' value='{{token.value}}'>"
            };
        });

        app.directive("focusIf", function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    focusIf:'='
                },
                link: function (scope, elem, attrs) {
                    if (scope.focusIf) {
                        $timeout(function () {
                            elem.focus();
                        }, 100);
                    }
                }
            };
        });
    })();

    (function () {
        var model = identityServer.getModel();
        angular.module("app").constant("Model", model);
        if (model.autoRedirect && model.redirectUrl) {
            if (model.autoRedirectDelay < 0) {
                model.autoRedirectDelay = 0;
            }
            window.setTimeout(function () {
                window.location = model.redirectUrl;
            }, model.autoRedirectDelay * 1000);
        }
    })();

})();
<commit_msg>Added the missing double quotation when checking for textContent compatibility (app.js)<commit_after>/*
 * Copyright (c) Dominick Baier, Brock Allen.  All rights reserved.
 * see license
 */

/// <reference path="../libs/angular/angular.1.3.15.js" />

window.identityServer = (function () {
    "use strict";

    var identityServer = {
        getModel: function () {
            var modelJson = document.getElementById("modelJson");
            var encodedJson = '';
            if (typeof (modelJson.textContent) !== "undefined") {
                encodedJson = modelJson.textContent;
            } else {
                encodedJson = modelJson.innerHTML;
            }
            var json = Encoder.htmlDecode(encodedJson);
            var model = JSON.parse(json);
            return model;
        }
    };

    return identityServer;
})();

(function () {
    "use strict";

    (function () {
        var app = angular.module("app", []);

        app.controller("LayoutCtrl", function ($scope, Model) {
            $scope.model = Model;
        });

        app.directive("antiForgeryToken", function () {
            return {
                restrict: 'E',
                replace: true,
                scope: {
                    token: "="
                },
                template: "<input type='hidden' name='{{token.name}}' value='{{token.value}}'>"
            };
        });

        app.directive("focusIf", function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    focusIf:'='
                },
                link: function (scope, elem, attrs) {
                    if (scope.focusIf) {
                        $timeout(function () {
                            elem.focus();
                        }, 100);
                    }
                }
            };
        });
    })();

    (function () {
        var model = identityServer.getModel();
        angular.module("app").constant("Model", model);
        if (model.autoRedirect && model.redirectUrl) {
            if (model.autoRedirectDelay < 0) {
                model.autoRedirectDelay = 0;
            }
            window.setTimeout(function () {
                window.location = model.redirectUrl;
            }, model.autoRedirectDelay * 1000);
        }
    })();

})();
<|endoftext|>


<commit_before>import React from 'react'
import { applyMiddleware, createStore, compose } from 'redux'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { applyRouterMiddleware, browserHistory, Router } from 'react-router'
import { ReduxAsyncConnect } from 'redux-connect'
import { persistState } from 'redux-devtools'
import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux'
import useScroll from 'react-router-scroll'

import PromiseMiddleware from './middlewares/PromiseMiddleware'
import reducers from './reducers'
import routes from './routes'

const initialState = window.__INITIAL_STATE__
const store = createStore(
  reducers,
  initialState,
  compose(
    applyMiddleware(
      PromiseMiddleware,
      routerMiddleware(browserHistory)
    )
  ),
  window.devToolsExtension && window.devToolsExtension(),
  persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
)

const history = syncHistoryWithStore(browserHistory, store)

render(
  <Provider store={ store }>
    <Router render={ (renderProps) => {
      return (
        <ReduxAsyncConnect { ...renderProps }
          render={ applyRouterMiddleware(useScroll()) } />
      )
    } } history={ history }>
      { routes }
    </Router>
  </Provider>,
  document.getElementById('root')
)<commit_msg>Fix invalid redux-devtools configure<commit_after>import React from 'react'
import { applyMiddleware, createStore, compose } from 'redux'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { applyRouterMiddleware, browserHistory, Router } from 'react-router'
import { ReduxAsyncConnect } from 'redux-connect'
import { persistState } from 'redux-devtools'
import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux'
import useScroll from 'react-router-scroll'

import PromiseMiddleware from './middlewares/PromiseMiddleware'
import reducers from './reducers'
import routes from './routes'

const initialState = window.__INITIAL_STATE__
const store = createStore(
  reducers,
  initialState,
  compose(
    applyMiddleware(
      PromiseMiddleware,
      routerMiddleware(browserHistory)
    ),
    window.devToolsExtension && window.devToolsExtension(),
    persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/))
  ),
)

const history = syncHistoryWithStore(browserHistory, store)

render(
  <Provider store={ store }>
    <Router render={ (renderProps) => {
      return (
        <ReduxAsyncConnect { ...renderProps }
          render={ applyRouterMiddleware(useScroll()) } />
      )
    } } history={ history }>
      { routes }
    </Router>
  </Provider>,
  document.getElementById('root')
)<|endoftext|>


<commit_before>module.exports = {
  browsers: {
    slIpad: {
      base: 'SauceLabs',
      browserName: 'ipad',
      version: '10.3'
    },
    slSafari10: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.11'
    },
    slSafari11: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.13'
    },
    slEdge: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      platform: 'Windows 10'
    },
    slChrome: {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    slFirefox: {
      base: 'SauceLabs',
      browserName: 'firefox'
    },
    slAndroid5: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '5.1'
    }
  }
}
<commit_msg>fixed: saucelab tests<commit_after>module.exports = {
  browsers: {
    slIpad: {
      base: 'SauceLabs',
      browserName: 'ipad',
      version: '10.3'
    },
    slSafari12: {
      base: 'SauceLabs',
      browserName: 'safari',
      platform: 'OS X 10.13'
    },
    slEdge: {
      base: 'SauceLabs',
      browserName: 'MicrosoftEdge',
      platform: 'Windows 10'
    },
    slChrome: {
      base: 'SauceLabs',
      browserName: 'chrome'
    },
    slFirefox: {
      base: 'SauceLabs',
      browserName: 'firefox'
    },
    slAndroid8: {
      base: 'SauceLabs',
      browserName: 'android',
      version: '8.0'
    }
  }
}
<|endoftext|>


<commit_before>
'use strict';

const path              = require('path');
const fs                = require('fs-extra');
const _                 = require('underscore');
const _s                = require('underscore.string');
const yaml              = require('js-yaml');
const utils             = require('./utils');
const contentProcessors = require('../functions/contentProcessors');

async function handler (activePageSlug, config) {
  activePageSlug = activePageSlug || '';
  const baseSlug = activePageSlug.split(/[\\/]/).slice(0, -1).join('/');
  const contentDir = utils.normalizeDir(path.normalize(config.content_dir));

  const files = await utils.promiseGlob(contentDir + '**/*');
  const filesProcessed = [];

  filesProcessed.push({
    slug: '.',
    title: '',
    show_on_home: true,
    is_index: true,
    active: (baseSlug === ''),
    class: 'category-index',
    sort: 0,
    files: []
  });

  const results = await Promise.all(
    files.map(filePath => processFile(config, activePageSlug, contentDir, filePath))
  );

  for (const result of results) {
    if (result && result.is_directory) {
      filesProcessed.push(result);
    } else if (result && !result.is_directory) {
      const dirSlug = path.dirname(result.slug);
      const parent = _.find(filesProcessed, item => item.slug === dirSlug);
      parent.files.push(result);
    }
  }

  const sortedFiles = _.sortBy(filesProcessed, cat => cat.sort);
  sortedFiles.forEach(category => {
    category.files = _.sortBy(category.files, file => file.sort);
  });

  return sortedFiles;
}

async function processFile (config, activePageSlug, contentDir, filePath) {
  const content_dir = path.normalize(contentDir);
  const page_sort_meta = config.page_sort_meta || '';
  const category_sort = config.category_sort || false;
  const shortPath = path.normalize(filePath).replace(content_dir, '').trim();
  const fileSlug = shortPath.split('\\').join('/');
  let stat = await fs.lstat(filePath);

  if (stat.isSymbolicLink()) {
    stat = await fs.lstat(await fs.readlink(filePath));
  }

  if (stat.isDirectory()) {

    let sort = 0;
    // ignore directories that has an ignore file under it
    const ignoreFile = contentDir + shortPath + '/ignore';

    const ignoreExists = await fs.lstat(ignoreFile).then(stat => stat.isFile(), () => {});
    if (ignoreExists) {
      return true;
    }

    let dirMetadata = {};
    try {
      const metaFile = await fs.readFile(path.join(contentDir, shortPath, 'meta'));
      dirMetadata = contentProcessors.cleanObjectStrings(yaml.safeLoad(metaFile.toString('utf-8')));
    } catch (e) {
      if (config.debug) {
        console.log('No meta file for', contentDir + shortPath);
      }
    }

    if (category_sort && !dirMetadata.sort) {
      try {
        const sortFile = await fs.readFile(path.join(contentDir, shortPath, 'sort'));
        sort = parseInt(sortFile.toString('utf-8'), 10);
      } catch (e) {
        if (config.debug) {
          console.log('No sort file for', contentDir + shortPath);
        }
      }
    }

    return {
      slug: fileSlug,
      title: dirMetadata.title || _s.titleize(_s.humanize(path.basename(shortPath))),
      show_on_home: dirMetadata.show_on_home ? (dirMetadata.show_on_home === 'true') : config.show_on_home_default,
      is_index: false,
      is_directory: true,
      active: activePageSlug.startsWith('/' + fileSlug),
      class: 'category-' + contentProcessors.cleanString(fileSlug),
      sort: dirMetadata.sort || sort,
      files: []
    };

  }

  if (stat.isFile() && path.extname(shortPath) === '.md') {
    try {
      const file = await fs.readFile(filePath);
      let slug = fileSlug;
      let pageSort = 0;

      if (fileSlug.indexOf('index.md') > -1) {
        slug = slug.replace('index.md', '');
      }

      slug = slug.replace('.md', '').trim();

      const meta = contentProcessors.processMeta(file.toString('utf-8'));

      if (page_sort_meta && meta[page_sort_meta]) {
        pageSort = parseInt(meta[page_sort_meta], 10);
      }

      return {
        slug: slug,
        title: meta.title ? meta.title : contentProcessors.slugToTitle(slug),
        show_on_home: meta.show_on_home ? (meta.show_on_home === 'true') : config.show_on_home_default,
        is_directory: false,
        active: (activePageSlug.trim() === '/' + slug),
        sort: pageSort
      };

    } catch (e) {
      if (config.debug) {
        console.log(e);
      }
    }
  }
}

exports.default = handler;
module.exports = exports.default;
<commit_msg>Use stat instead of lstat + readLink<commit_after>
'use strict';

const path              = require('path');
const fs                = require('fs-extra');
const _                 = require('underscore');
const _s                = require('underscore.string');
const yaml              = require('js-yaml');
const utils             = require('./utils');
const contentProcessors = require('../functions/contentProcessors');

async function handler (activePageSlug, config) {
  activePageSlug = activePageSlug || '';
  const baseSlug = activePageSlug.split(/[\\/]/).slice(0, -1).join('/');
  const contentDir = utils.normalizeDir(path.normalize(config.content_dir));

  const files = await utils.promiseGlob(contentDir + '**/*');
  const filesProcessed = [];

  filesProcessed.push({
    slug: '.',
    title: '',
    show_on_home: true,
    is_index: true,
    active: (baseSlug === ''),
    class: 'category-index',
    sort: 0,
    files: []
  });

  const results = await Promise.all(
    files.map(filePath => processFile(config, activePageSlug, contentDir, filePath))
  );

  for (const result of results) {
    if (result && result.is_directory) {
      filesProcessed.push(result);
    } else if (result && !result.is_directory) {
      const dirSlug = path.dirname(result.slug);
      const parent = _.find(filesProcessed, item => item.slug === dirSlug);
      parent.files.push(result);
    }
  }

  const sortedFiles = _.sortBy(filesProcessed, cat => cat.sort);
  sortedFiles.forEach(category => {
    category.files = _.sortBy(category.files, file => file.sort);
  });

  return sortedFiles;
}

async function processFile (config, activePageSlug, contentDir, filePath) {
  const content_dir = path.normalize(contentDir);
  const page_sort_meta = config.page_sort_meta || '';
  const category_sort = config.category_sort || false;
  const shortPath = path.normalize(filePath).replace(content_dir, '').trim();
  const fileSlug = shortPath.split('\\').join('/');
  const stat = await fs.stat(filePath);

  if (stat.isDirectory()) {

    let sort = 0;
    // ignore directories that has an ignore file under it
    const ignoreFile = contentDir + shortPath + '/ignore';

    const ignoreExists = await fs.lstat(ignoreFile).then(stat => stat.isFile(), () => {});
    if (ignoreExists) {
      return true;
    }

    let dirMetadata = {};
    try {
      const metaFile = await fs.readFile(path.join(contentDir, shortPath, 'meta'));
      dirMetadata = contentProcessors.cleanObjectStrings(yaml.safeLoad(metaFile.toString('utf-8')));
    } catch (e) {
      if (config.debug) {
        console.log('No meta file for', contentDir + shortPath);
      }
    }

    if (category_sort && !dirMetadata.sort) {
      try {
        const sortFile = await fs.readFile(path.join(contentDir, shortPath, 'sort'));
        sort = parseInt(sortFile.toString('utf-8'), 10);
      } catch (e) {
        if (config.debug) {
          console.log('No sort file for', contentDir + shortPath);
        }
      }
    }

    return {
      slug: fileSlug,
      title: dirMetadata.title || _s.titleize(_s.humanize(path.basename(shortPath))),
      show_on_home: dirMetadata.show_on_home ? (dirMetadata.show_on_home === 'true') : config.show_on_home_default,
      is_index: false,
      is_directory: true,
      active: activePageSlug.startsWith('/' + fileSlug),
      class: 'category-' + contentProcessors.cleanString(fileSlug),
      sort: dirMetadata.sort || sort,
      files: []
    };

  }

  if (stat.isFile() && path.extname(shortPath) === '.md') {
    try {
      const file = await fs.readFile(filePath);
      let slug = fileSlug;
      let pageSort = 0;

      if (fileSlug.indexOf('index.md') > -1) {
        slug = slug.replace('index.md', '');
      }

      slug = slug.replace('.md', '').trim();

      const meta = contentProcessors.processMeta(file.toString('utf-8'));

      if (page_sort_meta && meta[page_sort_meta]) {
        pageSort = parseInt(meta[page_sort_meta], 10);
      }

      return {
        slug: slug,
        title: meta.title ? meta.title : contentProcessors.slugToTitle(slug),
        show_on_home: meta.show_on_home ? (meta.show_on_home === 'true') : config.show_on_home_default,
        is_directory: false,
        active: (activePageSlug.trim() === '/' + slug),
        sort: pageSort
      };

    } catch (e) {
      if (config.debug) {
        console.log(e);
      }
    }
  }
}

exports.default = handler;
module.exports = exports.default;
<|endoftext|>


<commit_before>import PastelEvaluator from "./../pastel/evaluator.js";
import PastelError from "./../pastel/error.js";
import Parser from './../pastel/parser.js';
import CraftyStore from './../stores/CraftyStore.js';

// import ace for syntax highlighting
import ace from 'brace';

import 'brace/theme/monokai';
import '../editor/mode-pastel.js';

// import jquery
import $ from 'jquery';
import jQuery from 'jquery';
//// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;

import "./crafty.css";

class Crafty {
  constructor() {
    this.checkDeleteBtn;
    /* pastel compiler toolkit */
    this.compileToolkit = {};
  }

  render() {
    console.log("hi");

    /* pastel syntax highlighting parts */
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/pastel");
    editor.on('change', () => this.compileTest() );

    $(document).ready(() => {
      /* print console.log message when change codes in code-area */
      $('.define-function').click(function() {
        let FuncName = prompt("Type in your new functions name!");
        let FuncInputNumber = prompt("Number of input");
        let FuncOutputNumber = prompt("Number of output");
        // makeNewFunc(FuncName, FuncInputNumber, FuncOutputNumber);
      });

      $('.live-preview').click(() => {
        this.compile();
      });
    });

    this.compileToolkit.evaluator = new PastelEvaluator();
    this.compileToolkit.parser = new Parser();
    this.compileToolkit.CraftyStore = CraftyStore;
    this.compileToolkit.isError = function(result) {
    	return result instanceof PastelError;
    }
  }

  compileTest() {
    var editor = ace.edit("editor");
    var compilableText = editor.getValue();
    var result = this.compileToolkit.evaluator.evaluateText(compilableText);
    if (this.compileToolkit.isError(result)) {
      console.log("code-error");
      $('#compile-message').text(result.message);
      var message = document.getElementById("compile-message");
      message.className = "show";
    } else {
      var message = document.getElementById("compile-message");
      var tree = this.compileToolkit.parser.analyze(compilableText);
      this.compileToolkit.CraftyStore.set('tree', tree);
      this.compileToolkit.CraftyStore.emitChange();
      if(message.className == "show") {
        message.className = "hide";
        setTimeout(function() {
          message.className = "";
        }, 500);
      }
    }
  }

  compile() {
    console.log("compile!");
    var editor = ace.edit("editor");
    var compilableText = editor.getValue();
    var result = this.compileToolkit.evaluator.evaluateText(compilableText);
    if (this.compileToolkit.isError(result)) {
      $('#compile-message').text(result.message);
      var message = document.getElementById("compile-message");
      message.className = "show";
      alert("ERROR - check error message!");
    } else {
      alert(result);
    }
  }

  canvasChanged(BlockInfoList) {
    /* remove existing pre */
    $('.code-area').remove();

    /* make new pre, and attach it on code-area-container */
    var newPre = document.createElement("PRE");
    var i;
    for (i = 1; i <= BlockInfoList.length; i++) {
      var newText = document.createTextNode(BlockInfoList[i - 1]);
      newPre.appendChild(newText);
      newText = document.createTextNode("\n\n");
      newPre.appendChild(newText);
    }
    newPre.className += 'code-area';
    newPre.id = 'editor';
    $('.code-area-container').append(newPre);

    /* re-start pastel syntax highlighting parts */
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/pastel");

    /* re-start code-area keyup function : print console.log message when change codes in code-area */
    $('.code-area').keyup(() => {
      this.compileTest();
    });
  }

}

export default new Crafty();
<commit_msg>Place sidebar on the top layer<commit_after>import PastelEvaluator from "./../pastel/evaluator.js";
import PastelError from "./../pastel/error.js";
import Parser from './../pastel/parser.js';
import CraftyStore from './../stores/CraftyStore.js';

// import ace for syntax highlighting
import ace from 'brace';

import 'brace/theme/monokai';
import '../editor/mode-pastel.js';

// import jquery
import $ from 'jquery';
import jQuery from 'jquery';
//// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;

//  import editor styles
import "./crafty.css";

class Crafty {
  constructor() {
    this.checkDeleteBtn;
    /* pastel compiler toolkit */
    this.compileToolkit = {};
  }

  render() {
    console.log("hi");

    /* pastel syntax highlighting parts */
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/pastel");
    editor.on('change', () => this.compileTest() );

    $(document).ready(() => {
      /* print console.log message when change codes in code-area */
      $('.define-function').click(function() {
        let FuncName = prompt("Type in your new functions name!");
        let FuncInputNumber = prompt("Number of input");
        let FuncOutputNumber = prompt("Number of output");
        // makeNewFunc(FuncName, FuncInputNumber, FuncOutputNumber);
      });

      $('.live-preview').click(() => {
        this.compile();
      });
    });

    this.compileToolkit.evaluator = new PastelEvaluator();
    this.compileToolkit.parser = new Parser();
    this.compileToolkit.CraftyStore = CraftyStore;
    this.compileToolkit.isError = function(result) {
    	return result instanceof PastelError;
    }
  }

  compileTest() {
    var editor = ace.edit("editor");
    var compilableText = editor.getValue();
    var result = this.compileToolkit.evaluator.evaluateText(compilableText);
    if (this.compileToolkit.isError(result)) {
      console.log("code-error");
      $('#compile-message').text(result.message);
      var message = document.getElementById("compile-message");
      message.className = "show";
    } else {
      var message = document.getElementById("compile-message");
      var tree = this.compileToolkit.parser.analyze(compilableText);
      this.compileToolkit.CraftyStore.set('tree', tree);
      this.compileToolkit.CraftyStore.emitChange();
      if(message.className == "show") {
        message.className = "hide";
        setTimeout(function() {
          message.className = "";
        }, 500);
      }
    }
  }

  compile() {
    console.log("compile!");
    var editor = ace.edit("editor");
    var compilableText = editor.getValue();
    var result = this.compileToolkit.evaluator.evaluateText(compilableText);
    if (this.compileToolkit.isError(result)) {
      $('#compile-message').text(result.message);
      var message = document.getElementById("compile-message");
      message.className = "show";
      alert("ERROR - check error message!");
    } else {
      alert(result);
    }
  }

  canvasChanged(BlockInfoList) {
    /* remove existing pre */
    $('.code-area').remove();

    /* make new pre, and attach it on code-area-container */
    var newPre = document.createElement("PRE");
    var i;
    for (i = 1; i <= BlockInfoList.length; i++) {
      var newText = document.createTextNode(BlockInfoList[i - 1]);
      newPre.appendChild(newText);
      newText = document.createTextNode("\n\n");
      newPre.appendChild(newText);
    }
    newPre.className += 'code-area';
    newPre.id = 'editor';
    $('.code-area-container').append(newPre);

    /* re-start pastel syntax highlighting parts */
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/pastel");

    /* re-start code-area keyup function : print console.log message when change codes in code-area */
    $('.code-area').keyup(() => {
      this.compileTest();
    });
  }

}

export default new Crafty();
<|endoftext|>


<commit_before><commit_msg>Move some acceptance tests around and add playlist navigation tests.<commit_after><|endoftext|>


<commit_before>Vue.directive('focus', {
    inserted: function (el) {
        el.focus();
    }
});

Vue.component('todo-item', {
    props: ['item', 'index', 'editmode'],
    template: '\

\
      <input type="checkbox" v-if="!(editmode.enabled && editmode.index == index)" @click="$emit(\'strike\')" :checked="item.strikeout">\

\
      <textarea class="editor" v-focus="true" v-model.trim="item.text" type="text"></textarea>\

\

\
        <input type="checkbox" :checked="item.remind_enabled">\
        Remind\

\
      <input type="date" v-model="item.remind_date"> at \
      <input type="time" v-model="item.remind_time"> repeat \
      <select v-model="item.remind_repeat">\
        <option value="0">no repeat</option>\
        <option value="1">every minute</option>\
        <option value="2">every hour</option>\
        <option value="3">every day</option>\
        <option value="4">every week</option>\
        <option value="5">every month</option>\
        <option value="6">every year</option>\
      </select>\

\

\
        <button type="button" class="btn btn-default" @click="$emit(\'save\')" title="Ctrl+S">Save</button>\
        <button type="button" class="btn btn-default" @click="$emit(\'cancel\')" title="ESC">Cancel</button>\

\

\

\

\
       {{item.remind_date + \' \' + item.remind_time + getRepeatStr(item.remind_repeat)}}\

\
      {{item.text}}\

\

\
            <button type="button" class="btn btn-default" title="Edit item" @click="$emit(\'edit\');" v-if="!(editmode.enabled && editmode.index == index)">\
                \
            </button>\
            <button type="button" class="btn btn-default" title="Delete item" @click="$emit(\'delete\')" v-if="!(editmode.enabled && editmode.index == index)">\
                \
            </button>\

\

\
      ',
    methods: {
        getRepeatStr: function (repeat) {
            switch (repeat) {
                case '0':
                    return '';
                    break;
                case '1':
                    return ' and every minute';
                    break;
                case '2':
                    return ' and every hour';
                    break;
                case '3':
                    return ' and every day';
                    break;
                case '4':
                    return ' and every week';
                    break;
                case '5':
                    return ' and every month';
                    break;
                case '6':
                    return ' and every year';
                    break;
            }
        }
    },
    inserted: function (el) {
        // Focus the element
        el.focus()
    }
});

var vmTodoList = new Vue({
    el: '#todo-list',
    data: {
        newItemInput: '',
        todos: [],
        editMode: {
            enabled: false,
            index: 0
        }
    },
    methods: {
        addItem: function () {
            if (!this.newItemInput) return;
            this.todos.unshift({
                text: this.newItemInput,
                strikeout: false,
                remind_enabled: false,
                remind_date: convertDate(new Date()),
                remind_time: '00:00',
                remind_repeat: 0

            });
            this.newItemInput = '';
            loadTodosToSettings();
            updateAppSettings();
        },
        deleteItem: function (index) {
            if (confirm('Are you sure you want to delete this todo?')) {
                this.todos.splice(index, 1);
            }
        },
        strikeItem: function (index) {
            this.todos[index].strikeout = !this.todos[index].strikeout;
            loadTodosToSettings(index);
            updateAppSettings();
        },
        checkRemind: function (index) {
            this.todos[index].remind_enabled = !this.todos[index].remind_enabled;

        },
        editItem: function (index) {
            this.editMode.index = index;
            this.editMode.enabled = !this.editMode.enabled;
        },
        saveItem: function () {
            this.editMode.enabled = !this.editMode.enabled;
            for (var i in this.todos) {
                if (!this.todos[i].remind_date) {
                    this.todos[i].remind_date = convertDate(new Date());
                }
                if (!this.todos[i].remind_time) {
                    this.todos[i].remind_time = '00:00';
                }
            }
            loadTodosToSettings();
            updateAppSettings();
        },
        cancelChanges: function (index) {
            this.editMode.enabled = false;
            loadTodosFromSettings(index);
        }
    }

});

<commit_msg>update reminds<commit_after>Vue.directive('focus', {
    inserted: function (el) {
        el.focus();
    }
});

Vue.component('todo-item', {
    props: ['item', 'index', 'editmode'],
    template: '\

\
      <input type="checkbox" v-if="!(editmode.enabled && editmode.index == index)" @click="$emit(\'strike\')" :checked="item.strikeout">\

\
      <textarea class="editor" v-focus="true" v-model.trim="item.text" type="text"></textarea>\

\

\
        <input type="checkbox" :checked="item.remind_enabled">\
        Remind\

\
      <input type="date" v-model="item.remind_date"> at \
      <input type="time" v-model="item.remind_time"> repeat \
      <select v-model="item.remind_repeat">\
        <option value="0">no repeat</option>\
        <option value="1">every minute</option>\
        <option value="2">every hour</option>\
        <option value="3">every day</option>\
        <option value="4">every week</option>\
        <option value="5">every month</option>\
        <option value="6">every year</option>\
      </select>\

\

\
        <button type="button" class="btn btn-default" @click="$emit(\'save\')" title="Ctrl+S">Save</button>\
        <button type="button" class="btn btn-default" @click="$emit(\'cancel\')" title="ESC">Cancel</button>\

\

\

\

\
       {{moment(item.remind_date + \' \' + item.remind_time).format(\'DD.MM.YYYY HH:mm\') + getRepeatStr(item.remind_repeat)}}\

\
      {{item.text}}\

\

\
            <button type="button" class="btn btn-default" title="Edit item" @click="$emit(\'edit\');" v-if="!(editmode.enabled && editmode.index == index)">\
                \
            </button>\
            <button type="button" class="btn btn-default" title="Delete item" @click="$emit(\'delete\')" v-if="!(editmode.enabled && editmode.index == index)">\
                \
            </button>\

\

\
      ',
    methods: {
        getRepeatStr: function (repeat) {
            switch (repeat) {
                case '0':
                    return '';
                    break;
                case '1':
                    return ' and every minute';
                    break;
                case '2':
                    return ' and every hour';
                    break;
                case '3':
                    return ' and every day';
                    break;
                case '4':
                    return ' and every week';
                    break;
                case '5':
                    return ' and every month';
                    break;
                case '6':
                    return ' and every year';
                    break;
            }
        },
        moment: function(something) {
            return moment(something)
        }
    },

    inserted: function (el) {
        // Focus the element
        el.focus()
    }
});

var vmTodoList = new Vue({
    el: '#todo-list',
    data: {
        newItemInput: '',
        todos: [],
        editMode: {
            enabled: false,
            index: 0
        }
    },
    methods: {
        addItem: function () {
            if (!this.newItemInput) return;
            this.todos.unshift({
                text: this.newItemInput,
                strikeout: false,
                remind_enabled: false,
                remind_date: convertDate(new Date()),
                remind_time: '23:00',
                remind_repeat: 0

            });
            this.newItemInput = '';
            loadTodosToSettings();
            updateAppSettings();
        },
        deleteItem: function (index) {
            if (confirm('Are you sure you want to delete this todo?')) {
                this.todos.splice(index, 1);
            }
        },
        strikeItem: function (index) {
            this.todos[index].strikeout = !this.todos[index].strikeout;
            loadTodosToSettings(index);
            updateAppSettings();
        },
        checkRemind: function (index) {
            this.todos[index].remind_enabled = !this.todos[index].remind_enabled;

        },
        editItem: function (index) {
            this.editMode.index = index;
            this.editMode.enabled = !this.editMode.enabled;
        },
        saveItem: function () {
            this.editMode.enabled = !this.editMode.enabled;
            for (var i in this.todos) {
                if (!this.todos[i].remind_date) {
                    this.todos[i].remind_date = convertDate(new Date());
                }
                if (!this.todos[i].remind_time) {
                    this.todos[i].remind_time = '00:00';
                }
            }
            loadTodosToSettings();
            updateAppSettings();
        },
        cancelChanges: function (index) {
            this.editMode.enabled = false;
            loadTodosFromSettings(index);
        }
    }

});

<|endoftext|>


<commit_before>define(
[
	"goo/shapes/ShapeCreator"
], function(
	ShapeCreator
) {
	"use strict";

	describe("Sphere", function() {
		var a = ShapeCreator.createSphere(8, 4);

		it("Number of vertices and indices", function() {
			expect(a.vertexCount).toEqual(32);
			expect(a.indexCount).toEqual(144);
		});
	});
});
<commit_msg>#291: Adapted test for the new sphere<commit_after>define(
[
	"goo/shapes/ShapeCreator"
], function(
	ShapeCreator
) {
	"use strict";

	describe("Sphere", function() {
		var a = ShapeCreator.createSphere(8, 4);

		it("Number of vertices and indices", function() {
			expect(a.vertexCount).toEqual(37);
			expect(a.indexCount).toEqual(168);
		});
	});
});
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.10.0
var Nurse = require('./Nurse').Nurse;
var Doctor = require('./Doctor').Doctor;
var request = require('request');
var async = require('async');

module.exports = function(robot) {
  /* 自発的なサイトチェック */
  /* healthExamineイベント方式 */
  robot.hear(/she ex(?:amine)? with e(?:vent)?/i, function(msg) {
    var nurse, flags, list, i, len, site, results=[];
    nurse = new Nurse(robot);
    /* 出力内容の選定 */
    /* ###1st: error, 2nd: success, 3rd: fault */
    flags = [1,1,1];
    list = nurse.getList();
    for (i = 0, len = list.length; i < len; i++) {
      site = list[i];
      results.push(robot.emit('healthExamine', site, flags, "bot"));
    }
  });

  /* Doctor方式 */
  robot.hear(/she ex(?:amine)? with d(?:octor)?/i, function(msg) {
    var list, nurse, doctor, len, i, site;
    doctor = new Doctor();
    nurse = new Nurse(robot);
    list = nurse.getList();
    //監視対象リストとcallback関数とmsgを渡す。
    for(i = 0, len = list.length; i < len; i++) {
      site = list[i];
      doctor.examine(site, examineCallback, msg);
    }
  });
  /* examine終了後のcallback */
  var examineCallback = function(message, msg) {
    var results = [];
    if (message.status === "error") {
      results.push(msg.send(message.discription));
    } else if (message.status === "matched") {
      results.push(msg.send(message.discription));
    } else if (message.status === "unmatched") {
      results.push(msg.send(message.discription));
    } else {
      results.push(void 0);
    }
    return results;
  };

  /* Add nurse to check */
  robot.hear(/she[\s]+add[\s]+(\S+)[\s]+(\d+)$/i, function(msg) {
    var list, i, index, status, url, nurse;
    var key = 'sites';
    nurse = new Nurse(robot);
    list = nurse.getList();
    url = msg.match[1];
    status = Number(msg.match[2]);
    i = {
      url: url,
      status: status
    };
    if (nurse.checkConfliction(list, i.url)) {
      list.push(i);
      robot.brain.set(key, list); //@@!< keyがglobalの時も'sites'を参照するぞ
      index = nurse.searchIndex(list, i.url); //@@!
      return msg.send("added " + index + ": " + i.url + ", " + i.status);
    } else {
      return msg.send("Such url had already been registered.");
    }
  });

  /* Get List of nurse */
  robot.hear(/she[\s]+li?st?$/i, function(msg) {
    var list, message, nurse;
    nurse = new Nurse(robot);
    list = nurse.getList();
    message = list.map(function(i) {
      return (nurse.searchIndex(list, i.url)) + ": " + i.url + " " + i.status;
    }).join('\n');
    if (message) {
      return msg.send(message);
    } else {
      return msg.send("empty");
    }
  });

  /* Update expected status code */
  robot.hear(/she[\s]+up?d(?:ate)?[\s]+(\d+)[\s]+(\d+)$/i, function(msg) {
    var list, status, url, nurse;
    nurse = new Nurse(robot);
    list = nurse.getList();
    url = msg.match[1];
    status = Number(msg.match[2]);
    if (nurse.updateSite(url, status)) {
      return msg.send("updated " + list[msg.match[1]].url + ", " + list[msg.match[1]].status);
    } else {
      return msg.send("error: There are no such registered site.");
    }
  });

  /* Remove Url from list */
  return robot.hear(/she[\s]+re?m(?:ove)?[\s]+(\d+)$/i, function(msg) {
    var list, nurse;
    nurse = new Nurse(robot);
    list = nurse.removeSite(msg.match[1]);
    if (list !== false) {
      return msg.send("removed " + list.url + ", " + list.status);
    } else {
      return msg.send("error: There are no such registered site.");
    }
  });
};
<commit_msg>Modify "she examine with xx"<commit_after>// Generated by CoffeeScript 1.10.0
var Nurse = require('./Nurse').Nurse;
var Doctor = require('./Doctor').Doctor;
var request = require('request');
var async = require('async');

module.exports = function(robot) {
  /* 自発的なサイトチェック */
  /* healthExamineイベント方式 */
  // robot.hear(/she ex(?:amine)? with e(?:vent)?/i, function(msg) {
  //   var nurse, flags, list, i, len, site, results=[];
  //   nurse = new Nurse(robot);
  //   /* 出力内容の選定 */
  //   /* ###1st: error, 2nd: success, 3rd: fault */
  //   flags = [1,1,1];
  //   list = nurse.getList();
  //   for (i = 0, len = list.length; i < len; i++) {
  //     site = list[i];
  //     results.push(robot.emit('healthExamine', site, flags, "bot"));
  //   }
  // });

  /* Doctor方式 */
  // robot.hear(/she ex(?:amine)? with d(?:octor)?/i, function(msg) {
  //   var list, nurse, doctor, len, i, site;
  //   doctor = new Doctor();
  //   nurse = new Nurse(robot);
  //   list = nurse.getList();
  //   //監視対象リストとcallback関数とmsgを渡す。
  //   for(i = 0, len = list.length; i < len; i++) {
  //     site = list[i];
  //     doctor.examine(site, examineCallback, msg);
  //   }
  // });
  // /* examine終了後のcallback */
  // var examineCallback = function(message, msg) {
  //   var results = [];
  //   if (message.status === "error") {
  //     results.push(msg.send(message.discription));
  //   } else if (message.status === "matched") {
  //     results.push(msg.send(message.discription));
  //   } else if (message.status === "unmatched") {
  //     results.push(msg.send(message.discription));
  //   } else {
  //     results.push(void 0);
  //   }
  //   return results;
  // };

  /* Add nurse to check */
  robot.hear(/she[\s]+add[\s]+(\S+)[\s]+(\d+)$/i, function(msg) {
    var list, i, index, status, url, nurse;
    var key = 'sites';
    nurse = new Nurse(robot);
    list = nurse.getList();
    url = msg.match[1];
    status = Number(msg.match[2]);
    i = {
      url: url,
      status: status
    };
    if (nurse.checkConfliction(list, i.url)) {
      list.push(i);
      robot.brain.set(key, list); //@@!< keyがglobalの時も'sites'を参照するぞ
      index = nurse.searchIndex(list, i.url); //@@!
      return msg.send("added " + index + ": " + i.url + ", " + i.status);
    } else {
      return msg.send("Such url had already been registered.");
    }
  });

  /* Get List of nurse */
  robot.hear(/she[\s]+li?st?$/i, function(msg) {
    var list, message, nurse;
    nurse = new Nurse(robot);
    list = nurse.getList();
    message = list.map(function(i) {
      return (nurse.searchIndex(list, i.url)) + ": " + i.url + " " + i.status;
    }).join('\n');
    if (message) {
      return msg.send(message);
    } else {
      return msg.send("empty");
    }
  });

  /* Update expected status code */
  robot.hear(/she[\s]+up?d(?:ate)?[\s]+(\d+)[\s]+(\d+)$/i, function(msg) {
    var list, status, url, nurse;
    nurse = new Nurse(robot);
    list = nurse.getList();
    url = msg.match[1];
    status = Number(msg.match[2]);
    if (nurse.updateSite(url, status)) {
      return msg.send("updated " + list[msg.match[1]].url + ", " + list[msg.match[1]].status);
    } else {
      return msg.send("error: There are no such registered site.");
    }
  });

  /* Remove Url from list */
  return robot.hear(/she[\s]+re?m(?:ove)?[\s]+(\d+)$/i, function(msg) {
    var list, nurse;
    nurse = new Nurse(robot);
    list = nurse.removeSite(msg.match[1]);
    if (list !== false) {
      return msg.send("removed " + list.url + ", " + list.status);
    } else {
      return msg.send("error: There are no such registered site.");
    }
  });
};
<|endoftext|>


<commit_before>var keys = require('./keys.js');
var Article = require('./models/articleModel.js');
var Keyword = require('./models/keywordModel.js');
var Source = require('./models/sourceModel.js');
var bluebird = require('bluebird');

var fetchData = function (req, res){

  //Parse url queries for us in table lookup
  var startDate = req.query.startDate || 00000000;
  var endDate = req.query.endDate || new Date();
  var keyword = req.query.keyword;
  var source = req.query.source;
  var timePeriod = req.query.timePeriod;

  // Both keywordId and sourceId return promises
  var keywordId = function(){
    return new Keyword({'word': keyword})
    .fetch();
  };

  var sourceId = function(){
    return new Source({'name': source})
    .fetch();
  };

  // bluebird is used to resolve promises retured by keywordId and sourceId
  bluebird.join(keywordId(), sourceId())
    .then(function(array){
      return new Article()
        .query('where', 'published', '>', startDate )
        .query('where', 'published', '<', endDate )
        .query('where', 'word', '=', array[0].get('id') )
        .query('where', 'source', '=', array[1].get('id') )
        .fetchAll()
    })
    .then(function(articles) {
      res.send(articles.toJSON());
    }).catch(function(error) {
      console.log(error);
      res.send('An error occured, please ensure that you request a keyword and source.');
    });
};

module.exports = fetchData;

// var fetchID = function (table, value){
//   //TODO refactor with lookup to keyword/source tables
//   if (table = 'keywords'){
//     new Keywords({word: 'BP'})
//   }

  // if (table === 'keywords' && value === 'BP'){
  //     return 1;
  // } else if (table === 'sources' && value === 'newyorktimes'){
  //     return 1;
  // }
// };

  // if (timePeriod) {
  //     res.send('We\'ll get to this');
  //     //TODO refactor out
  //     // newyorktimesew Article()
  //     //     .query('count')
  //     //     .query('where', 'published', '>', startDate )
  //     //     .query('where', 'published', '<', endDate )
  //     //     .fetchAll()
  //     //     .then(function(frequencies) {
  //     //         res.send(frequencies.toJSON());
  //     //     }).catch(function(error) {
  //     //         console.log(error);
  //     //         res.send('An error occured');
  //     //     });
  // } else {
  // }
<commit_msg>(fix) Clean up comments and extraneous code<commit_after>var keys = require('./keys.js');
var Article = require('./models/articleModel.js');
var Keyword = require('./models/keywordModel.js');
var Source = require('./models/sourceModel.js');
var bluebird = require('bluebird');

var fetchData = function (req, res){

  //Parse url queries for us in table lookup
  var startDate = req.query.startDate || 00000000;
  var endDate = req.query.endDate || new Date();
  // Spaces in keyword queries must be percent encoded (e.g Jeb Bush -> Jeb%20Bush)
  var keyword = req.query.keyword;
  var source = req.query.source;

  // Both keywordId and sourceId return promises
  var keywordId = function(){
    return new Keyword({'word': keyword})
    .fetch();
  };

  var sourceId = function(){
    return new Source({'name': source})
    .fetch();
  };

  // bluebird is used to resolve promises retured by keywordId and sourceId
  bluebird.join(keywordId(), sourceId())
    .then(function(array){
      return new Article()
        .query('where', 'published', '>', startDate )
        .query('where', 'published', '<', endDate )
        .query('where', 'word', '=', array[0].get('id') )
        .query('where', 'source', '=', array[1].get('id') )
        .fetchAll()
    })
    .then(function(articles) {
      res.send(articles.toJSON());
    }).catch(function(error) {
      console.log(error);
      res.send('An error occured, please ensure that you request a keyword and source.');
    });
};

module.exports = fetchData;
<|endoftext|>


<commit_before>import $ from 'jquery';
import React from 'react';
import PropTypes from 'prop-types';
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import Reflux from 'reflux';
import alertify from 'alertifyjs';
import classNames from 'classnames';

import TextBox from 'js/components/textBox';

import bem from 'js/bem';
import stores from 'js/stores';
import mixins from 'js/mixins';
import ui from 'js/ui';
import actions from 'js/actions';
import {MODAL_TYPES} from 'js/constants'

import {t, getLangAsObject, getLangString, notify} from 'utils';

export class TranslationSettings extends React.Component {
  constructor(props){
    super(props);

    let translations = [];
    if (props.asset) {
      translations = props.asset.content.translations;
    }

    this.state = {
      assetUid: props.assetUid,
      asset: props.asset,
      translations: translations,
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    }
    autoBind(this);
  }
  componentDidMount () {
    this.listenTo(stores.asset, this.onAssetsChange);

    if (!this.state.asset && this.state.assetUid) {
      stores.allAssets.whenLoaded(this.props.assetUid, this.onAssetChange);
    }
  }
  onAssetChange(asset) {
    this.setState({
      translations: asset.content.translations,
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    })

    stores.pageState.showModal({
      type: MODAL_TYPES.FORM_LANGUAGES,
      asset: asset
    });
  }
  onAssetsChange(assetsList) {
    let uid;
    if (this.state.asset) {
      uid = this.state.asset.uid;
    } else if (this.state.assetUid) {
      uid = this.state.assetUid;
    }
    this.onAssetChange(assetsList[uid]);
  }
  showAddLanguageForm() {
    this.setState({
      showAddLanguageForm: true
    })
  }
  hideAddLanguageForm() {
    this.setState({
      showAddLanguageForm: false
    })
  }
  toggleRenameLanguageForm(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index'));
    if (this.state.renameLanguageIndex === index) {
      this.setState({
        renameLanguageIndex: -1
      });
    } else {
      this.setState({
        renameLanguageIndex: index
      });
    }
  }
  launchTranslationTableModal(evt) {
    const index = evt.currentTarget.dataset.index;
    stores.pageState.switchModal({
      type: MODAL_TYPES.FORM_TRANSLATIONS_TABLE,
      asset: this.state.asset,
      langIndex: index
    });
  }
  onLanguageChange(lang, index) {
    let content = this.state.asset.content;
    if (index > -1) {
      content.translations[index] = getLangString(lang);
    } else {
      content.translations.push(getLangString(lang));
      content = this.prepareTranslations(content);
    }

    this.updateAsset(content);
  }
  canAddLanguages() {
    return !(this.state.translations.length === 1 && this.state.translations[0] === null);
  }
  getAllLanguages(thisLanguage) {
    return this.state.translations;
  }
  deleteLanguage(evt) {
    const index = evt.currentTarget.dataset.index;
    const content = this.deleteTranslations(this.state.asset.content, index);
    if (content) {
      content.translations.splice(index, 1);
      const dialog = alertify.dialog('confirm');
      const opts = {
        title: t('Delete language?'),
        message: t('Are you sure you want to delete this language? This action is not reversible.'),
        labels: {ok: t('Delete'), cancel: t('Cancel')},
        onok: () => {
          this.updateAsset(content);
          dialog.destroy();
        },
        oncancel: () => {dialog.destroy()}
      };
      dialog.set(opts).show();
    } else {
      notify('Error: translation index mismatch. Cannot delete language.');
    }
  }
  prepareTranslations(content) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    // append null values to translations for each survey row
    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property] && row[property].length < translationsLength) {
          row[property].push(null);
        }
      }
    }

    // append null values to translations for choices
    if (content.choices && content.choices.length) {
      for (var i = 0, len = choices.length; i < len; i++) {
        if (choices[i].label.length < translationsLength) {
          choices[i].label.push(null);
        }
      }
    }
    return content;
  }
  deleteTranslations(content, langIndex) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property]) {
          if (row[property].length === translationsLength) {
            row[property].splice(langIndex, 1);
          } else {
            console.error('Translations index mismatch');
            return false;
          }
        }
      }
    }

    if (content.choices && content.choices.length) {
      for (var i = 0, len = choices.length; i < len; i++) {
        if (choices[i].label) {
          if (choices[i].label.length === translationsLength) {
            choices[i].label.splice(langIndex, 1);
          } else {
            console.error('Translations index mismatch');
            return false;
          }
        }
      }
    }
    return content;
  }
  updateAsset (content) {
    actions.resources.updateAsset(
      this.state.asset.uid,
      {content: JSON.stringify(content)}
    );
  }
  renderEmptyMessage() {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          <bem.FormView__cell>
            {t('There is nothing to translate in this form.')}
          </bem.FormView__cell>
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  renderTranslationsSettings(translations) {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          {(translations && translations[0] === null) ?
            <bem.FormView__cell m='translation-note'>
              {t('Here you can add more languages to your project, and translate the strings in each of them.')}

                {t('Note: make sure to configure your default language before adding more.')}

            </bem.FormView__cell>
            :
            <bem.FormView__cell m='label'>
              {t('Current languages')}
            </bem.FormView__cell>
          }
          {translations.map((l, i)=> {
            return (
              <React.Fragment key={`lang-${i}`}>
                <bem.FormView__cell m='translation'>
                  <bem.FormView__cell>
                    {l ? l : t('Unnamed language')}
                    {i === 0 ? ` ${t('default')}` : ''}
                  </bem.FormView__cell>
                  <bem.FormView__cell m='translation-actions'>
                    <bem.FormView__link
                      m='rename'
                      onClick={this.toggleRenameLanguageForm}
                      data-index={i}
                      data-tip={t('Edit language')}
                    >

                    </bem.FormView__link>

                    {i > 0 &&
                      <bem.FormView__link
                        m='translate'
                        data-index={i}
                        onClick={this.launchTranslationTableModal}
                        data-tip={t('Update translations')}
                      >

                      </bem.FormView__link>
                    }

                    {i > 0 &&
                      <bem.FormView__link
                        m='translate'
                        onClick={this.deleteLanguage}
                        data-index={i}
                        data-tip={t('Delete language')}
                      >

                      </bem.FormView__link>
                    }
                  </bem.FormView__cell>
                </bem.FormView__cell>
                {this.state.renameLanguageIndex === i &&
                  <bem.FormView__cell m='update-language-form'>
                    <LanguageForm
                      langString={l}
                      langIndex={i}
                      onLanguageChange={this.onLanguageChange}
                      existingLanguages={this.getAllLanguages(l)}
                    />
                  </bem.FormView__cell>
                }
              </React.Fragment>
            );
          })}
          {!this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language'>
              <button
                className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
                onClick={this.showAddLanguageForm}
                disabled={!this.canAddLanguages()}
              >
                {t('Add language')}
              </button>
            </bem.FormView__cell>
          }
          {this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language-form'>
              <bem.FormView__link m='close' onClick={this.hideAddLanguageForm}>

              </bem.FormView__link>
              <bem.FormView__cell m='label'>
                {t('Add a new language')}
              </bem.FormView__cell>
              <LanguageForm
                onLanguageChange={this.onLanguageChange}
                existingLanguages={this.getAllLanguages()}
              />
            </bem.FormView__cell>
          }
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  render () {
    let translations = this.state.translations;
    if (translations.length === 0) {
      return this.renderEmptyMessage();
    } else {
      return this.renderTranslationsSettings(translations);
    }
  }
};

reactMixin(TranslationSettings.prototype, Reflux.ListenerMixin);

export default TranslationSettings;

/*
Properties:
- langString <string>: follows pattern "NAME (CODE)"
- langIndex <string>
- onLanguageChange <function>: required
- existingLanguages <langString[]>: for validation purposes
*/
class LanguageForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      nameError: null,
      code: '',
      codeError: null
    }

    if (this.props.langString) {
      const lang = getLangAsObject(this.props.langString);
      this.state = {
        name: lang.name || '',
        code: lang.code || ''
      }
    }
    autoBind(this);
  }
  isLanguageNameValid() {
    if (this.props.existingLanguages) {
      let isNameUnique = true;
      this.props.existingLanguages.forEach((langString) => {
        if (this.props.langString && langString === this.props.langString) {
          // skip comparing to itself (editing language context)
        } else if (langString !== null) {
          const langObj = getLangAsObject(langString);
          if (langObj.name === this.state.name) {
            isNameUnique = false;
          }
        }
      });
      return isNameUnique;
    } else {
      return true;
    }
  }
  isLanguageCodeValid() {
    if (this.props.existingLanguages) {
      let isCodeUnique = true;
      this.props.existingLanguages.forEach((langString) => {
        if (this.props.langString && langString === this.props.langString) {
          // skip comparing to itself (editing language context)
        } else if (langString !== null) {
          const langObj = getLangAsObject(langString);
          if (langObj.code === this.state.code) {
            isCodeUnique = false;
          }
        }
      });
      return isCodeUnique;
    } else {
      return true;
    }
  }
  onSubmit(evt) {
    evt.preventDefault();

    const isNameValid = this.isLanguageNameValid();
    if (!isNameValid) {
      this.setState({nameError: t('Name must be unique!')});
    } else {
      this.setState({nameError: null});
    }

    const isCodeValid = this.isLanguageCodeValid();
    if (!isCodeValid) {
      this.setState({codeError: t('Code must be unique!')});
    } else {
      this.setState({codeError: null});
    }

    if (isNameValid && isCodeValid) {
      let langIndex = -1;
      if (this.props.langIndex !== undefined) {
        langIndex = this.props.langIndex;
      }
      this.props.onLanguageChange({
        name: this.state.name,
        code: this.state.code
      }, langIndex);
    }
  }
  onNameChange (newName) {
    this.setState({name: newName.trim()});
  }
  onCodeChange (newCode) {
    this.setState({code: newCode.trim()});
  }
  render () {
    let isAnyFieldEmpty = this.state.name.length === 0 || this.state.code.length === 0;

    return (
      <bem.FormView__form m='add-language-fields'>
        <bem.FormView__cell m='lang-name'>
          <bem.FormModal__item>
            {t('Language name')}
            <TextBox
              value={this.state.name}
              onChange={this.onNameChange}
              errors={this.state.nameError}
            />
          </bem.FormModal__item>
        </bem.FormView__cell>

        <bem.FormView__cell m='lang-code'>
          <bem.FormModal__item>
            {t('Language code')}
            <TextBox
              value={this.state.code}
              onChange={this.onCodeChange}
              errors={this.state.codeError}
            />
          </bem.FormModal__item>
        </bem.FormView__cell>

        <bem.FormView__cell m='submit-button'>
          <button
            className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
            onClick={this.onSubmit} type='submit'
            disabled={isAnyFieldEmpty}
          >
            {this.props.langIndex !== undefined ? t('Update') : t('Add')}
          </button>
        </bem.FormView__cell>
      </bem.FormView__form>
      );
  }
};
<commit_msg>render loading message<commit_after>import $ from 'jquery';
import React from 'react';
import PropTypes from 'prop-types';
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import Reflux from 'reflux';
import alertify from 'alertifyjs';
import classNames from 'classnames';

import TextBox from 'js/components/textBox';

import bem from 'js/bem';
import stores from 'js/stores';
import mixins from 'js/mixins';
import ui from 'js/ui';
import actions from 'js/actions';
import {MODAL_TYPES} from 'js/constants'

import {t, getLangAsObject, getLangString, notify} from 'utils';

export class TranslationSettings extends React.Component {
  constructor(props){
    super(props);

    let translations = [];
    if (props.asset) {
      translations = props.asset.content.translations;
    }

    this.state = {
      assetUid: props.assetUid,
      asset: props.asset,
      translations: translations,
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    }
    autoBind(this);
  }
  componentDidMount () {
    this.listenTo(stores.asset, this.onAssetsChange);

    if (!this.state.asset && this.state.assetUid) {
      stores.allAssets.whenLoaded(this.props.assetUid, this.onAssetChange);
    }
  }
  onAssetChange(asset) {
    this.setState({
      asset: asset,
      translations: asset.content.translations,
      showAddLanguageForm: false,
      renameLanguageIndex: -1
    })

    stores.pageState.showModal({
      type: MODAL_TYPES.FORM_LANGUAGES,
      asset: asset
    });
  }
  onAssetsChange(assetsList) {
    let uid;
    if (this.state.asset) {
      uid = this.state.asset.uid;
    } else if (this.state.assetUid) {
      uid = this.state.assetUid;
    }
    this.onAssetChange(assetsList[uid]);
  }
  showAddLanguageForm() {
    this.setState({
      showAddLanguageForm: true
    })
  }
  hideAddLanguageForm() {
    this.setState({
      showAddLanguageForm: false
    })
  }
  toggleRenameLanguageForm(e) {
    let index = parseInt($(e.target).closest('[data-index]').get(0).getAttribute('data-index'));
    if (this.state.renameLanguageIndex === index) {
      this.setState({
        renameLanguageIndex: -1
      });
    } else {
      this.setState({
        renameLanguageIndex: index
      });
    }
  }
  launchTranslationTableModal(evt) {
    const index = evt.currentTarget.dataset.index;
    stores.pageState.switchModal({
      type: MODAL_TYPES.FORM_TRANSLATIONS_TABLE,
      asset: this.state.asset,
      langIndex: index
    });
  }
  onLanguageChange(lang, index) {
    let content = this.state.asset.content;
    if (index > -1) {
      content.translations[index] = getLangString(lang);
    } else {
      content.translations.push(getLangString(lang));
      content = this.prepareTranslations(content);
    }

    this.updateAsset(content);
  }
  canAddLanguages() {
    return !(this.state.translations.length === 1 && this.state.translations[0] === null);
  }
  getAllLanguages(thisLanguage) {
    return this.state.translations;
  }
  deleteLanguage(evt) {
    const index = evt.currentTarget.dataset.index;
    const content = this.deleteTranslations(this.state.asset.content, index);
    if (content) {
      content.translations.splice(index, 1);
      const dialog = alertify.dialog('confirm');
      const opts = {
        title: t('Delete language?'),
        message: t('Are you sure you want to delete this language? This action is not reversible.'),
        labels: {ok: t('Delete'), cancel: t('Cancel')},
        onok: () => {
          this.updateAsset(content);
          dialog.destroy();
        },
        oncancel: () => {dialog.destroy()}
      };
      dialog.set(opts).show();
    } else {
      notify('Error: translation index mismatch. Cannot delete language.');
    }
  }
  prepareTranslations(content) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    // append null values to translations for each survey row
    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property] && row[property].length < translationsLength) {
          row[property].push(null);
        }
      }
    }

    // append null values to translations for choices
    if (content.choices && content.choices.length) {
      for (var i = 0, len = choices.length; i < len; i++) {
        if (choices[i].label.length < translationsLength) {
          choices[i].label.push(null);
        }
      }
    }
    return content;
  }
  deleteTranslations(content, langIndex) {
    let translated = content.translated,
        translationsLength = content.translations.length,
        survey = content.survey,
        choices = content.choices;

    for (var i = 0, len = survey.length; i < len; i++) {
      let row = survey[i];
      for (var j = 0, len2 = translated.length; j < len2; j++) {
        var property = translated[j];
        if (row[property]) {
          if (row[property].length === translationsLength) {
            row[property].splice(langIndex, 1);
          } else {
            console.error('Translations index mismatch');
            return false;
          }
        }
      }
    }

    if (content.choices && content.choices.length) {
      for (var i = 0, len = choices.length; i < len; i++) {
        if (choices[i].label) {
          if (choices[i].label.length === translationsLength) {
            choices[i].label.splice(langIndex, 1);
          } else {
            console.error('Translations index mismatch');
            return false;
          }
        }
      }
    }
    return content;
  }
  updateAsset (content) {
    actions.resources.updateAsset(
      this.state.asset.uid,
      {content: JSON.stringify(content)}
    );
  }
  renderEmptyMessage() {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          <bem.FormView__cell>
            {t('There is nothing to translate in this form.')}
          </bem.FormView__cell>
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  renderLoadingMessage() {
    return (
      <bem.Loading>
        <bem.Loading__inner>

          {t('loading...')}
        </bem.Loading__inner>
      </bem.Loading>
    );
  }
  renderTranslationsSettings(translations) {
    return (
      <bem.FormModal m='translation-settings'>
        <bem.FormModal__item>
          {(translations && translations[0] === null) ?
            <bem.FormView__cell m='translation-note'>
              {t('Here you can add more languages to your project, and translate the strings in each of them.')}

                {t('Note: make sure to configure your default language before adding more.')}

            </bem.FormView__cell>
            :
            <bem.FormView__cell m='label'>
              {t('Current languages')}
            </bem.FormView__cell>
          }
          {translations.map((l, i)=> {
            return (
              <React.Fragment key={`lang-${i}`}>
                <bem.FormView__cell m='translation'>
                  <bem.FormView__cell>
                    {l ? l : t('Unnamed language')}
                    {i === 0 ? ` ${t('default')}` : ''}
                  </bem.FormView__cell>
                  <bem.FormView__cell m='translation-actions'>
                    <bem.FormView__link
                      m='rename'
                      onClick={this.toggleRenameLanguageForm}
                      data-index={i}
                      data-tip={t('Edit language')}
                    >

                    </bem.FormView__link>

                    {i > 0 &&
                      <bem.FormView__link
                        m='translate'
                        data-index={i}
                        onClick={this.launchTranslationTableModal}
                        data-tip={t('Update translations')}
                      >

                      </bem.FormView__link>
                    }

                    {i > 0 &&
                      <bem.FormView__link
                        m='translate'
                        onClick={this.deleteLanguage}
                        data-index={i}
                        data-tip={t('Delete language')}
                      >

                      </bem.FormView__link>
                    }
                  </bem.FormView__cell>
                </bem.FormView__cell>
                {this.state.renameLanguageIndex === i &&
                  <bem.FormView__cell m='update-language-form'>
                    <LanguageForm
                      langString={l}
                      langIndex={i}
                      onLanguageChange={this.onLanguageChange}
                      existingLanguages={this.getAllLanguages(l)}
                    />
                  </bem.FormView__cell>
                }
              </React.Fragment>
            );
          })}
          {!this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language'>
              <button
                className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
                onClick={this.showAddLanguageForm}
                disabled={!this.canAddLanguages()}
              >
                {t('Add language')}
              </button>
            </bem.FormView__cell>
          }
          {this.state.showAddLanguageForm &&
            <bem.FormView__cell m='add-language-form'>
              <bem.FormView__link m='close' onClick={this.hideAddLanguageForm}>

              </bem.FormView__link>
              <bem.FormView__cell m='label'>
                {t('Add a new language')}
              </bem.FormView__cell>
              <LanguageForm
                onLanguageChange={this.onLanguageChange}
                existingLanguages={this.getAllLanguages()}
              />
            </bem.FormView__cell>
          }
        </bem.FormModal__item>
      </bem.FormModal>
    );
  }
  render () {
    if (!this.state.asset) {
      return this.renderLoadingMessage();
    }

    let translations = this.state.translations;
    if (translations.length === 0) {
      return this.renderEmptyMessage();
    } else {
      return this.renderTranslationsSettings(translations);
    }
  }
};

reactMixin(TranslationSettings.prototype, Reflux.ListenerMixin);

export default TranslationSettings;

/*
Properties:
- langString <string>: follows pattern "NAME (CODE)"
- langIndex <string>
- onLanguageChange <function>: required
- existingLanguages <langString[]>: for validation purposes
*/
class LanguageForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      nameError: null,
      code: '',
      codeError: null
    }

    if (this.props.langString) {
      const lang = getLangAsObject(this.props.langString);
      this.state = {
        name: lang.name || '',
        code: lang.code || ''
      }
    }
    autoBind(this);
  }
  isLanguageNameValid() {
    if (this.props.existingLanguages) {
      let isNameUnique = true;
      this.props.existingLanguages.forEach((langString) => {
        if (this.props.langString && langString === this.props.langString) {
          // skip comparing to itself (editing language context)
        } else if (langString !== null) {
          const langObj = getLangAsObject(langString);
          if (langObj.name === this.state.name) {
            isNameUnique = false;
          }
        }
      });
      return isNameUnique;
    } else {
      return true;
    }
  }
  isLanguageCodeValid() {
    if (this.props.existingLanguages) {
      let isCodeUnique = true;
      this.props.existingLanguages.forEach((langString) => {
        if (this.props.langString && langString === this.props.langString) {
          // skip comparing to itself (editing language context)
        } else if (langString !== null) {
          const langObj = getLangAsObject(langString);
          if (langObj.code === this.state.code) {
            isCodeUnique = false;
          }
        }
      });
      return isCodeUnique;
    } else {
      return true;
    }
  }
  onSubmit(evt) {
    evt.preventDefault();

    const isNameValid = this.isLanguageNameValid();
    if (!isNameValid) {
      this.setState({nameError: t('Name must be unique!')});
    } else {
      this.setState({nameError: null});
    }

    const isCodeValid = this.isLanguageCodeValid();
    if (!isCodeValid) {
      this.setState({codeError: t('Code must be unique!')});
    } else {
      this.setState({codeError: null});
    }

    if (isNameValid && isCodeValid) {
      let langIndex = -1;
      if (this.props.langIndex !== undefined) {
        langIndex = this.props.langIndex;
      }
      this.props.onLanguageChange({
        name: this.state.name,
        code: this.state.code
      }, langIndex);
    }
  }
  onNameChange (newName) {
    this.setState({name: newName.trim()});
  }
  onCodeChange (newCode) {
    this.setState({code: newCode.trim()});
  }
  render () {
    let isAnyFieldEmpty = this.state.name.length === 0 || this.state.code.length === 0;

    return (
      <bem.FormView__form m='add-language-fields'>
        <bem.FormView__cell m='lang-name'>
          <bem.FormModal__item>
            {t('Language name')}
            <TextBox
              value={this.state.name}
              onChange={this.onNameChange}
              errors={this.state.nameError}
            />
          </bem.FormModal__item>
        </bem.FormView__cell>

        <bem.FormView__cell m='lang-code'>
          <bem.FormModal__item>
            {t('Language code')}
            <TextBox
              value={this.state.code}
              onChange={this.onCodeChange}
              errors={this.state.codeError}
            />
          </bem.FormModal__item>
        </bem.FormView__cell>

        <bem.FormView__cell m='submit-button'>
          <button
            className='mdl-button mdl-js-button mdl-button--raised mdl-button--colored'
            onClick={this.onSubmit} type='submit'
            disabled={isAnyFieldEmpty}
          >
            {this.props.langIndex !== undefined ? t('Update') : t('Add')}
          </button>
        </bem.FormView__cell>
      </bem.FormView__form>
      );
  }
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Home Controller
 */
var passportConf  = require('../config/passport');

module.exports.controller = function (app) {

  app.get('/vote', function (req, res) {
    res.render('game/index', {
      url: req.url
    });
  });

  app.get('/home/youtube', function (req, res) {
    res.render('home/youtube');
  });
  app.get('/comingsoon', function (req, res) {
    res.render('comingsoon/main', {
      url: req.url
    });
  });
  app.get('/', function (req, res) {
//    if (req.user) {
//      return res.redirect('/home');
//    }
    res.render('home/index', {
      url: req.url
    });
  });
  app.get('/directive/rafflebox', function (req, res) {
    res.render('directive/rafflebox', {
      url: req.url
    });
  });
  app.get('/directive/biddingbox', function (req, res) {
    res.render('directive/biddingbox', {
      url: req.url
    });
  });
};
<commit_msg>coming soon server change<commit_after>'use strict';

/**
 * Home Controller
 */
var passportConf  = require('../config/passport');

module.exports.controller = function (app) {

  app.get('/vote', function (req, res) {
    res.render('game/index', {
      url: req.url
    });
  });

  app.get('/home/youtube', function (req, res) {
    res.render('home/youtube');
  });
  app.get('/comingsoon', function (req, res) {
    res.render('comingsoon/main', {
      url: req.url
    });
  });
  app.get('/', function (req, res) {
//    if (req.user) {
//      return res.redirect('/home');
//    }
    res.render('comingsoon/main', {
      url: req.url
    });
  });
  app.get('/directive/rafflebox', function (req, res) {
    res.render('directive/rafflebox', {
      url: req.url
    });
  });
  app.get('/directive/biddingbox', function (req, res) {
    res.render('directive/biddingbox', {
      url: req.url
    });
  });
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var bufrw = require('bufrw');
var fix8 = bufrw.FixedWidth(8);
var fix24 = bufrw.FixedWidth(24);

module.exports = Tracing;

var emptySpanId = Buffer(8);
var emptyParentId = Buffer(8);
var emptyTraceId = Buffer(8);
emptySpanId.fill(0);
emptyParentId.fill(0);
emptyTraceId.fill(0);

function Tracing(spanid, parentid, traceid, flags) {
    var self = this;
    Object.defineProperty(self, 'buffer', {
        value: null,
        writable: true
    });
    self.spanid = spanid || emptySpanId;
    self.parentid = parentid || emptyParentId;
    self.traceid = traceid || emptyTraceId;
    self.flags = flags || 0;
}

Tracing.RW = bufrw.Base(tracingByteLength, readTracingFrom, writeTracingInto);

function tracingByteLength() {
    return bufrw.LengthResult.just(
        8 + // spanid:8
        8 + // parentid:8
        8 + // traceid:8
        1   // flags:1
    );
}

function writeTracingInto(tracing, buffer, offset) {
    var res;

    if (tracing.buffer) {
        res = fix24.writeInto(tracing.buffer, buffer, offset);
    } else {
        res = fix8.writeInto(tracing.spanid, buffer, offset);
        if (res.err) return res;
        offset = res.offset;

        res = fix8.writeInto(tracing.parentid, buffer, offset);
        if (res.err) return res;
        offset = res.offset;

        res = fix8.writeInto(tracing.traceid, buffer, offset);
    }

    if (res.err) return res;
    offset = res.offset;

    res = bufrw.UInt8.writeInto(tracing.flags, buffer, offset);

    return res;
}

function readTracingFrom(buffer, offset) {
    var tracing = new Tracing();
    var res;

    res = fix24.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;

    tracing.buffer = res.value;
    tracing.spanid = tracing.buffer.slice(0, 8);
    tracing.parentid = tracing.buffer.slice(8, 16);
    tracing.traceid = tracing.buffer.slice(16, 24);

    res = bufrw.UInt8.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    tracing.flags = res.value;

    return bufrw.ReadResult.just(offset, tracing);
}

Tracing.emptyTracing = new Tracing();
<commit_msg>Revert "v2/tracing: reduce buffer reads/writes 3:1"<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var bufrw = require('bufrw');
var fix8 = bufrw.FixedWidth(8);

module.exports = Tracing;

var emptySpanId = Buffer(8);
var emptyParentId = Buffer(8);
var emptyTraceId = Buffer(8);
emptySpanId.fill(0);
emptyParentId.fill(0);
emptyTraceId.fill(0);

function Tracing(spanid, parentid, traceid, flags) {
    var self = this;
    self.spanid = spanid || emptySpanId;
    self.parentid = parentid || emptyParentId;
    self.traceid = traceid || emptyTraceId;
    self.flags = flags || 0;
}

Tracing.RW = bufrw.Base(tracingByteLength, readTracingFrom, writeTracingInto);

function tracingByteLength() {
    return bufrw.LengthResult.just(
        8 + // spanid:8
        8 + // parentid:8
        8 + // traceid:8
        1   // flags:1
    );
}

function writeTracingInto(tracing, buffer, offset) {
    var res;

    res = fix8.writeInto(tracing.spanid, buffer, offset);
    if (res.err) return res;
    offset = res.offset;

    res = fix8.writeInto(tracing.parentid, buffer, offset);
    if (res.err) return res;
    offset = res.offset;

    res = fix8.writeInto(tracing.traceid, buffer, offset);
    if (res.err) return res;
    offset = res.offset;

    res = bufrw.UInt8.writeInto(tracing.flags, buffer, offset);

    return res;
}

function readTracingFrom(buffer, offset) {
    var tracing = new Tracing();
    var res;

    res = fix8.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    tracing.spanid = res.value;

    res = fix8.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    tracing.parentid = res.value;

    res = fix8.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    tracing.traceid = res.value;

    res = bufrw.UInt8.readFrom(buffer, offset);
    if (res.err) return res;
    offset = res.offset;
    tracing.flags = res.value;

    return bufrw.ReadResult.just(offset, tracing);
}

Tracing.emptyTracing = new Tracing();
<|endoftext|>