<commit_before>const routerBase = ''
const fbAppID = process.env.SERVER === 'prod' ? '1061200460616036' : '331606597252844'
const fbAdmins = 286133171723936
const utmCampaign = 'project_name'
const serverHostname = Object({
  dev: 'https://www.fundrich.com.tw' // 開發環境、系統集成測試（AWS）、用戶驗收測試（業演）、正式環境（竹北）、正式環境
}, require('../../common-elements/assets/js/data/server-hostname.json'))
const axiosBaseURL = Object({
  dev: ['https://www.fundrich.com.tw/', 'https://www.fundrich.com.tw/'] // 前為 server 內部位置, 後為 client 外部位置
}, require('../../common-elements/assets/js/data/axios-base-url.json'))
const staticURL = require('../../common-elements/assets/js/data/static-url.json')
const axiosServiceURL = Object.assign({
  serverBaseURL: axiosBaseURL[process.env.SERVER][0],
  clientBaseURL: axiosBaseURL[process.env.SERVER][1]
}, require('../../common-elements/assets/js/data/axios-service-url.json'))

module.exports = {
  mode: 'universal',

  /*
   * Create environment variables that will be shared for the client and server-side.
   */
  env: {
    routerBase,
    fbAppID,
    nodeServer: process.env.SERVER,
    serverHostname,
    staticURL,
    axios: axiosServiceURL
  },

  /*
  ** Headers of the page
  */
  head: {
    titleTemplate: '%s - FundRich 基富通',
    title: '網頁標題',
    htmlAttrs: {
      lang: 'zh-Hant-TW',
      prefix: 'og: http://ogp.me/ns#'
    },
    link: [
      { rel: 'icon', type: 'image/x-icon', href: `${routerBase}/favicon.ico` },
      { rel: 'icon', type: 'image/png', href: `${routerBase}/favicon.png` },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-640x1136.png`, media: '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-750x1294.png`, media: '(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1242x2148.png`, media: '(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1125x2436.png`, media: '(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1536x2048.png`, media: '(min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1668x2224.png`, media: '(min-device-width: 834px) and (max-device-width: 834px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-2048x2732.png`, media: '(min-device-width: 1024px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)' }
    ],
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1, viewport-fit=cover' },
      { name: 'apple-mobile-web-app-capable', content: 'yes' },
      { name: 'apple-mobile-web-app-status-bar-style', content: 'white' },
      { hid: 'keywords', name: 'keywords', content: '基富通,買基金,折扣優惠' },
      { hid: 'description', name: 'description', content: '基富通提供股票基金、債券基金、配息基金，等超過二千多級別的基金商品！並有基金淨值、基金搜尋、基金排行、智能理財多種投資理財工具，是您定期定額、單筆基金投資的好選擇！' },
      { property: 'og:type', content: 'website' },
      { property: 'og:site_name', content: 'FundRich 基富通 - 網路基金銷售平台' },
      { hid: 'og:url', property: 'og:url', content: `${serverHostname[process.env.SERVER]}${routerBase || '/'}` },
      { hid: 'og:title', property: 'og:title', content: '網頁標題 - FundRich 基富通' },
      { hid: 'og:description', property: 'og:description', content: '基富通提供股票基金、債券基金、配息基金，等超過二千多級別的基金商品！並有基金淨值、基金搜尋、基金排行、智能理財多種投資理財工具，是您定期定額、單筆基金投資的好選擇！' },
      { hid: 'og:image', property: 'og:image', content: `${serverHostname[process.env.SERVER]}${routerBase}/og.jpg` },
      { hid: 'og:image:type', property: 'og:image:type', content: 'image/jpeg' },
      { property: 'og:image:width', content: '1200' },
      { property: 'og:image:height', content: '628' },
      { property: 'fb:app_id', content: fbAppID },
      { property: 'fb:admins', content: fbAdmins },
      { property: 'fb:pages', content: fbAdmins },
      { 'http-equiv': 'cache-control', content: 'max-age=900' } // 活動站需要時時更新，從 client 端指定沒有 cache 週期
    ],
    script: [
      { hid: 'global-variable', type: 'text/javascript', innerHTML: `var MAGIC_DOMAIN = '${serverHostname[process.env.SERVER]}'; var MAGIC_DOMAIN_API = '${axiosBaseURL[process.env.SERVER][1]}';`, body: true }
    ],
    __dangerouslyDisableSanitizersByTagID: { 'global-variable': ['innerHTML'] }
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#ba9764' },

  /*
   ** Customize app manifest
   */
  meta: {
    ogTitle: false, // 設定為 false，就不會跟頁面中的 head: { meta: [{ hid: 'og:title' }] } 資訊重複
    ogDescription: false // 設定為 false，就不會跟頁面中的 head: { meta: [{ hid: 'og:description' }] } 資訊重複
  },
  manifest: {
    start_url: `${serverHostname[process.env.SERVER]}${routerBase || '/'}?utm_source=web_app_manifest&utm_campaign=${utmCampaign}`,
    name: '基富通系統名稱',
    short_name: '系統名稱',
    display: 'standalone',
    background_color: '#ffffff', // splash screen 背景色
    theme_color: '#ba9764', // 狀態列顏色
    orientation: 'portrait', // portrait: 直式, landscape: 橫式
    description: '系統化整理基富通所有基金',
    lang: 'zh-Hant-TW',
    publicPath: `${routerBase}/_nuxt`
  },

  /*
  ** Global CSS
  */
  css: ['normalize.css', '@/assets/sass/main.sass'],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    { src: '@/plugins/mixin' },
    { src: '@/plugins/facebook-sdk', ssr: false },
    { src: '@/plugins/google-sdk', ssr: false },
    { src: '@/plugins/facebook-pixel', ssr: false }
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://github.com/nuxt-community/axios-module#usage
    '@nuxtjs/axios',
    ['@nuxtjs/pwa', { workbox: false }]
  ],
  /*
  ** Axios module configuration
  */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    baseURL: axiosBaseURL[process.env.SERVER][0],
    browserBaseURL: axiosBaseURL[process.env.SERVER][1]
  },

  /*
   * Single page application is served under "./"
   */
  router: { base: routerBase },

  /*
   * Customize runtime options for rendering pages
   */
  cache: {
    maxAge: 60 * 15
  },
  render: {
    // 尚無法得知此以下設定是否有效
    // bundleRenderer: {
    //   shouldPreload: (file, type) => ['script', 'style', 'font'].includes(type)
    // },
    http2: { push: true, pushAssets: (req, res, publicPath, preloadFiles) => preloadFiles
      .filter(f => f.asType === 'script' && f.file === 'runtime.js')
      .map(f => `<${publicPath}${f.file}>; rel=preload; as=${f.asType}`) },
    static: { maxAge: 60 * 15 },
    compressor: { threshold: 9 },
    csp: false
  },
  messages: {
    nuxtjs: 'Nuxt.js',
    server_error: '網站忙碌中',
    server_error_details: '目前網站訪客過多，請按F5重新整理或稍後再試，敬請見諒。',
    client_error: '網站忙碌中',
    client_error_details: '目前網站訪客過多，請按F5重新整理或稍後再試，敬請見諒。',
    error_404: '您所前往的頁面並不存在，請返回基富通首頁重新查詢。',
    back_to_home: '返回首頁'
  },

  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    // analyze: true,
    // optimization: { // 目前 Nuxt.js 會自己將模組綁在一起, 但如果還是想要將些許模組放到另一個檔案, 可以參照以下設定
    //   minimize: true,
    //   minimizer: [],
    //   splitChunks: {
    //     automaticNameDelimiter: '.',
    //     cacheGroups: {
    //       commons: {
    //         test: /[\\/]node_modules[\\/](velocity-animate|jquery)[\\/]/,
    //         name: 'common-in-lazy',
    //         chunks: 'all',
    //       }
    //     }
    //   }
    // },
    extend(config, ctx) {
      config.node = { fs: 'empty' }
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}
<commit_msg>微調 axiosBaseURL 路徑<commit_after>const routerBase = ''
const fbAppID = process.env.SERVER === 'prod' ? '1061200460616036' : '331606597252844'
const fbAdmins = 286133171723936
const utmCampaign = 'project_name'
const serverHostname = Object({
  dev: 'https://www.fundrich.com.tw' // 開發環境、系統集成測試（AWS）、用戶驗收測試（業演）、正式環境（竹北）、正式環境
}, require('../../common-elements/assets/js/data/server-hostname.json'))
const axiosBaseURL = Object({
  dev: ['https://www.fundrich.com.tw', 'https://www.fundrich.com.tw'] // 前為 server 內部位置, 後為 client 外部位置
}, require('../../common-elements/assets/js/data/axios-base-url.json'))
const staticURL = require('../../common-elements/assets/js/data/static-url.json')
const axiosServiceURL = Object.assign({
  serverBaseURL: axiosBaseURL[process.env.SERVER][0],
  clientBaseURL: axiosBaseURL[process.env.SERVER][1]
}, require('../../common-elements/assets/js/data/axios-service-url.json'))

module.exports = {
  mode: 'universal',

  /*
   * Create environment variables that will be shared for the client and server-side.
   */
  env: {
    routerBase,
    fbAppID,
    nodeServer: process.env.SERVER,
    serverHostname,
    staticURL,
    axios: axiosServiceURL
  },

  /*
  ** Headers of the page
  */
  head: {
    titleTemplate: '%s - FundRich 基富通',
    title: '網頁標題',
    htmlAttrs: {
      lang: 'zh-Hant-TW',
      prefix: 'og: http://ogp.me/ns#'
    },
    link: [
      { rel: 'icon', type: 'image/x-icon', href: `${routerBase}/favicon.ico` },
      { rel: 'icon', type: 'image/png', href: `${routerBase}/favicon.png` },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-640x1136.png`, media: '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-750x1294.png`, media: '(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1242x2148.png`, media: '(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1125x2436.png`, media: '(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1536x2048.png`, media: '(min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-1668x2224.png`, media: '(min-device-width: 834px) and (max-device-width: 834px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)' },
      { rel: 'apple-touch-startup-image', href: `${routerBase}/launch-2048x2732.png`, media: '(min-device-width: 1024px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 2) and (orientation: portrait)' }
    ],
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1, viewport-fit=cover' },
      { name: 'apple-mobile-web-app-capable', content: 'yes' },
      { name: 'apple-mobile-web-app-status-bar-style', content: 'white' },
      { hid: 'keywords', name: 'keywords', content: '基富通,買基金,折扣優惠' },
      { hid: 'description', name: 'description', content: '基富通提供股票基金、債券基金、配息基金，等超過二千多級別的基金商品！並有基金淨值、基金搜尋、基金排行、智能理財多種投資理財工具，是您定期定額、單筆基金投資的好選擇！' },
      { property: 'og:type', content: 'website' },
      { property: 'og:site_name', content: 'FundRich 基富通 - 網路基金銷售平台' },
      { hid: 'og:url', property: 'og:url', content: `${serverHostname[process.env.SERVER]}${routerBase || '/'}` },
      { hid: 'og:title', property: 'og:title', content: '網頁標題 - FundRich 基富通' },
      { hid: 'og:description', property: 'og:description', content: '基富通提供股票基金、債券基金、配息基金，等超過二千多級別的基金商品！並有基金淨值、基金搜尋、基金排行、智能理財多種投資理財工具，是您定期定額、單筆基金投資的好選擇！' },
      { hid: 'og:image', property: 'og:image', content: `${serverHostname[process.env.SERVER]}${routerBase}/og.jpg` },
      { hid: 'og:image:type', property: 'og:image:type', content: 'image/jpeg' },
      { property: 'og:image:width', content: '1200' },
      { property: 'og:image:height', content: '628' },
      { property: 'fb:app_id', content: fbAppID },
      { property: 'fb:admins', content: fbAdmins },
      { property: 'fb:pages', content: fbAdmins },
      { 'http-equiv': 'cache-control', content: 'max-age=900' } // 活動站需要時時更新，從 client 端指定沒有 cache 週期
    ],
    script: [
      { hid: 'global-variable', type: 'text/javascript', innerHTML: `var MAGIC_DOMAIN = '${serverHostname[process.env.SERVER]}'; var MAGIC_DOMAIN_API = '${axiosBaseURL[process.env.SERVER][1]}';`, body: true }
    ],
    __dangerouslyDisableSanitizersByTagID: { 'global-variable': ['innerHTML'] }
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#ba9764' },

  /*
   ** Customize app manifest
   */
  meta: {
    ogTitle: false, // 設定為 false，就不會跟頁面中的 head: { meta: [{ hid: 'og:title' }] } 資訊重複
    ogDescription: false // 設定為 false，就不會跟頁面中的 head: { meta: [{ hid: 'og:description' }] } 資訊重複
  },
  manifest: {
    start_url: `${serverHostname[process.env.SERVER]}${routerBase || '/'}?utm_source=web_app_manifest&utm_campaign=${utmCampaign}`,
    name: '基富通系統名稱',
    short_name: '系統名稱',
    display: 'standalone',
    background_color: '#ffffff', // splash screen 背景色
    theme_color: '#ba9764', // 狀態列顏色
    orientation: 'portrait', // portrait: 直式, landscape: 橫式
    description: '系統化整理基富通所有基金',
    lang: 'zh-Hant-TW',
    publicPath: `${routerBase}/_nuxt`
  },

  /*
  ** Global CSS
  */
  css: ['normalize.css', '@/assets/sass/main.sass'],

  /*
  ** Plugins to load before mounting the App
  */
  plugins: [
    { src: '@/plugins/mixin' },
    { src: '@/plugins/facebook-sdk', ssr: false },
    { src: '@/plugins/google-sdk', ssr: false },
    { src: '@/plugins/facebook-pixel', ssr: false }
  ],

  /*
  ** Nuxt.js modules
  */
  modules: [
    // Doc: https://github.com/nuxt-community/axios-module#usage
    '@nuxtjs/axios',
    ['@nuxtjs/pwa', { workbox: false }]
  ],
  /*
  ** Axios module configuration
  */
  axios: {
    // See https://github.com/nuxt-community/axios-module#options
    baseURL: axiosBaseURL[process.env.SERVER][0],
    browserBaseURL: axiosBaseURL[process.env.SERVER][1]
  },

  /*
   * Single page application is served under "./"
   */
  router: { base: routerBase },

  /*
   * Customize runtime options for rendering pages
   */
  cache: {
    maxAge: 60 * 15
  },
  render: {
    // 尚無法得知此以下設定是否有效
    // bundleRenderer: {
    //   shouldPreload: (file, type) => ['script', 'style', 'font'].includes(type)
    // },
    http2: { push: true, pushAssets: (req, res, publicPath, preloadFiles) => preloadFiles
      .filter(f => f.asType === 'script' && f.file === 'runtime.js')
      .map(f => `<${publicPath}${f.file}>; rel=preload; as=${f.asType}`) },
    static: { maxAge: 60 * 15 },
    compressor: { threshold: 9 },
    csp: false
  },
  messages: {
    nuxtjs: 'Nuxt.js',
    server_error: '網站忙碌中',
    server_error_details: '目前網站訪客過多，請按F5重新整理或稍後再試，敬請見諒。',
    client_error: '網站忙碌中',
    client_error_details: '目前網站訪客過多，請按F5重新整理或稍後再試，敬請見諒。',
    error_404: '您所前往的頁面並不存在，請返回基富通首頁重新查詢。',
    back_to_home: '返回首頁'
  },

  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
    // analyze: true,
    // optimization: { // 目前 Nuxt.js 會自己將模組綁在一起, 但如果還是想要將些許模組放到另一個檔案, 可以參照以下設定
    //   minimize: true,
    //   minimizer: [],
    //   splitChunks: {
    //     automaticNameDelimiter: '.',
    //     cacheGroups: {
    //       commons: {
    //         test: /[\\/]node_modules[\\/](velocity-animate|jquery)[\\/]/,
    //         name: 'common-in-lazy',
    //         chunks: 'all',
    //       }
    //     }
    //   }
    // },
    extend(config, ctx) {
      config.node = { fs: 'empty' }
      // Run ESLint on save
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}
<|endoftext|>


<commit_before>/* global screen */
var robot = require('robotjs')
var vkey = require('vkey')

module.exports = function createEvents (data) {
  if (data.click) {
    var x = scale(data.clientX, 0, data.canvasWidth, 0, screen.width)
    var y = scale(data.clientY, 0, data.canvasHeight, 0, screen.height)
    var pos = robot.getMousePos() // hosts current x/y
    robot.moveMouse(x, y) // move to remotes pos
    setTimeout(function () {
      robot.mouseClick() // click on remote click spot
      setTimeout(function () {
        robot.moveMouse(pos.x, pos.y) // go back to hosts position
      }, 20)
    }, 20)
  }

  if (data.keyCode) {
    var k = vkey[data.keyCode].toLowerCase()
    if (k === '<space>') k = ' '
    var modifiers = []
    if (data.shift) modifiers.push('shift')
    if (data.control) modifiers.push('control')
    if (data.alt) modifiers.push('alt')
    if (data.meta) modifiers.push('command')
    if (k[0] !== '<') {
      console.log('typed ' + k + ' ' + JSON.stringify(modifiers))
      if (modifiers[0]) robot.keyTap(k, modifiers[0])
      else robot.keyTap(k)
    } else {
      if (k === '<enter>') robot.keyTap('enter')
      else if (k === '<backspace>') robot.keyTap('backspace')
      else if (k === '<up>') robot.keyTap('up')
      else if (k === '<down>') robot.keyTap('down')
      else if (k === '<left>') robot.keyTap('left')
      else if (k === '<right>') robot.keyTap('right')
      else if (k === '<delete>') robot.keyTap('delete')
      else if (k === '<home>') robot.keyTap('home')
      else if (k === '<end>') robot.keyTap('end')
      else if (k === '<page-up>') robot.keyTap('pageup')
      else if (k === '<page-down>') robot.keyTap('pagedown')
      else console.log('did not type ' + k)
    }
  }
}

function scale (x, fromLow, fromHigh, toLow, toHigh) {
  return (x - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow
}
<commit_msg>Removed trailing space.<commit_after>/* global screen */
var robot = require('robotjs')
var vkey = require('vkey')

module.exports = function createEvents (data) {
  if (data.click) {
    var x = scale(data.clientX, 0, data.canvasWidth, 0, screen.width)
    var y = scale(data.clientY, 0, data.canvasHeight, 0, screen.height)
    var pos = robot.getMousePos() // hosts current x/y
    robot.moveMouse(x, y) // move to remotes pos
    setTimeout(function () {
      robot.mouseClick() // click on remote click spot
      setTimeout(function () {
        robot.moveMouse(pos.x, pos.y) // go back to hosts position
      }, 20)
    }, 20)
  }

  if (data.keyCode) {
    var k = vkey[data.keyCode].toLowerCase()
    if (k === '<space>') k = ' '
    var modifiers = []
    if (data.shift) modifiers.push('shift')
    if (data.control) modifiers.push('control')
    if (data.alt) modifiers.push('alt')
    if (data.meta) modifiers.push('command')
    if (k[0] !== '<') {
      console.log('typed ' + k + ' ' + JSON.stringify(modifiers))
      if (modifiers[0]) robot.keyTap(k, modifiers[0])
      else robot.keyTap(k)
    } else {
      if (k === '<enter>') robot.keyTap('enter')
      else if (k === '<backspace>') robot.keyTap('backspace')
      else if (k === '<up>') robot.keyTap('up')
      else if (k === '<down>') robot.keyTap('down')
      else if (k === '<left>') robot.keyTap('left')
      else if (k === '<right>') robot.keyTap('right')
      else if (k === '<delete>') robot.keyTap('delete')
      else if (k === '<home>') robot.keyTap('home')
      else if (k === '<end>') robot.keyTap('end')
      else if (k === '<page-up>') robot.keyTap('pageup')
      else if (k === '<page-down>') robot.keyTap('pagedown')
      else console.log('did not type ' + k)
    }
  }
}

function scale (x, fromLow, fromHigh, toLow, toHigh) {
  return (x - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow
}
<|endoftext|>


<commit_before>document.addEventListener("DOMContentLoaded", function(){

	var squares = document.getElementsByClassName('square')

	var takenSquares = document.getElementsByClassName('square taken');

	var assortedSquares = [[squares[0], squares[1], squares[2]], [squares[3], squares[4], squares[5]], [squares[6], squares[7], squares[8]]]

	var newGame = new Game(squares);
	// newGame.makeComputerMove(newGame.currentPlayer, 1);
	for(var squareNumber = 0; squareNumber < squares.length; squareNumber ++){
		squares[squareNumber].addEventListener('click', makePlayerMove);

	}

	function makePlayerMove(){
		if(newGame.winner || newGame.tie){
			return
		}
		else{
			if(this.innerText === ''){
				letter = document.createTextNode(newGame.currentPlayer)
				this.appendChild(letter)
				newGame.checkForWinner();
				newGame.checkForTie();
				if(newGame.winner || newGame.Tie){
					return
				}
				else{
				newGame.switchPlayers();
				newGame.makeComputerMove();
				}
			}
			else{
				alert('invalid move')
			}
		}
	}
});

var simulationCount = 0;
////////////////////////////////////////////

////////////////////////////////////////////

// game objects

function Game(board){
	this.winner,
	this.tie,
	this.turn = 0;
	this.board = board,
	this.humanPlayer = "X",
	this.computerPlayer = "O",
	this.currentPlayer = this.humanPlayer,
	this.sortedBoard = this.sortBoard(board)
}

Game.prototype.switchPlayers = function(){
	if(this.currentPlayer === this.humanPlayer){
		this.currentPlayer = this.computerPlayer
	}
	else {
		this.currentPlayer = this.humanPlayer
	}
	this.turn++;
}

Game.prototype.makeComputerMove = function(
	){
	availableMoves = this.getAvailableMoves();

	for(var possibleMove = 0; possibleMove < availableMoves.length; possibleMove++){
		if(this.simulateMove(new Game(this.board), availableMoves[possibleMove], this.currentPlayer)){
			this.board[(this.simulateMove(new Game(this.board), availableMoves[possibleMove], this.currentPlayer))].innerText = this.currentPlayer;
			break;
		}
	}
	this.switchPlayers();
}

Game.prototype.getAvailableMoves = function(){
	availableMoves = [];
	for(var availableMoveIndex = 0; availableMoveIndex < this.board.length; availableMoveIndex++){
		if(this.board[availableMoveIndex].innerText === ''){
			availableMoves.push(availableMoveIndex)
		}
	}
	return availableMoves
}

// for in starts at 0
Game.prototype.getMoveScores = function(availableMoves){
	moveScores = {}
	for(var availableMoveIndex = 0; availableMoveIndex< availableMoves.length; availableMoveIndex++){
		moveScores[availableMoves[availableMoveIndex]] = 0
	}
	return moveScores
}

Game.prototype.simulateMove = function(simGame, moveIndex, currentPlayer){
	console.log(currentPlayer)
	simGame.board[moveIndex].innerText = currentPlayer;
	console.log(currentPlayer + 'appended to square' + moveIndex)
	console.log(simGame.board[moveIndex].innerText)
	simGame.checkForWinner();
	if(simGame.winner === simGame.humanPlayer){
		console.log('player will win at ' + moveIndex)
		return 1
	}
	else if(simGame.Winner === simGame.computerPlayer){
		// console.log('the computer may win!')
		return -1
	}
	else if(simGame.tie){
		// console.log('no moves')
		return 0
	}
	else{
		console.log(this.board)
		this.switchPlayers();
		console.log(this.currentPlayer)
		debugger
	// simGame.board[moveIndex].innerText = '';
	return false;
	}
}

Game.prototype.makeMove = function (game, player){
	marker = document.createTextNode(player)
	this.board[1].appendChild(marker)
}

Game.prototype.sortBoard = function(){
	sortedGameBoard = [[this.board[0], this.board[1], this.board[2]], [this.board[3], this.board[4], this.board[5]], [this.board[6], this.board[7], this.board[8]]]
	return sortedGameBoard
}

Game.prototype.checkThreeCells = function(arrayOfThreeCells){
	if(arrayOfThreeCells[0].innerText === this.currentPlayer && arrayOfThreeCells[0].innerText === arrayOfThreeCells[1].innerText && arrayOfThreeCells[1].innerText === arrayOfThreeCells[2].innerText){
		return true
	}
	else{
		return false;
	}
}

Game.prototype.checkRow = function(rowNumber, sortedGameBoard){
	row = sortedGameBoard[rowNumber]
	return this.checkThreeCells(row)
}

Game.prototype.checkColumn = function(columnNumber, sortedGameBoard){
	var column = [];
	for(var rowNumber = 0; rowNumber < sortedGameBoard.length; rowNumber++){
		column.push(sortedGameBoard[rowNumber][columnNumber])
	}
	return this.checkThreeCells(column)
}

Game.prototype.checkLeftDiagonal = function(sortedGameBoard){
	var leftDiagonal = [sortedGameBoard[0][0], sortedGameBoard[1][1], sortedGameBoard[2][2]]
	return this.checkThreeCells(leftDiagonal)
}

Game.prototype.checkRightDiagonal = function(sortedGameBoard){
	var rightDiagonal = [sortedGameBoard[0][2], sortedGameBoard[1][1], sortedGameBoard[2][0]]
	return this.checkThreeCells(rightDiagonal)
}

Game.prototype.checkForTie = function(){
	count = 0;
	for(var squareIndex =0; squareIndex < this.board.length; squareIndex++){
		if(this.board[squareIndex].innerText !== ''){
			count++;
		}
	}
	if(count === 9 && !this.checkForWinner()){
		this.tie = true;
		return true;
	}
	else if(count !== 9){
		return false
	}
}

Game.prototype.checkForWinner = function(){
	if(this.checkLeftDiagonal(this.sortedBoard) || this.checkRightDiagonal(this.sortedBoard)){
		this.winner = this.currentPlayer;
		return true
	}
	for(var index = 0; index < this.sortedBoard.length; index++){
		if(this.checkRow(index, this.sortedBoard) || this.checkColumn(index, this.sortedBoard)){
			this.winner = this.currentPlayer
			return true
		}
	}
	return false
}
<commit_msg>update simulate move function to change score of each possible move within a loop, scores are kept in an object representing a hash which will contain the total score for each move later on<commit_after>document.addEventListener("DOMContentLoaded", function(){

	var squares = document.getElementsByClassName('square')

	var takenSquares = document.getElementsByClassName('square taken');

	var assortedSquares = [[squares[0], squares[1], squares[2]], [squares[3], squares[4], squares[5]], [squares[6], squares[7], squares[8]]]

	var newGame = new Game(squares);
	// newGame.makeComputerMove(newGame.currentPlayer, 1);
	for(var squareNumber = 0; squareNumber < squares.length; squareNumber ++){
		squares[squareNumber].addEventListener('click', makePlayerMove);

	}

	function makePlayerMove(){
		if(newGame.winner || newGame.tie){
			return
		}
		else{
			if(this.innerText === ''){
				letter = document.createTextNode(newGame.currentPlayer)
				this.appendChild(letter)
				newGame.checkForWinner();
				newGame.checkForTie();
				if(newGame.winner || newGame.Tie){
					return
				}
				else{
				newGame.switchPlayers();
				newGame.makeComputerMove();
				}
			}
			else{
				alert('invalid move')
			}
		}
	}
});

var simulationCount = 0;
////////////////////////////////////////////

////////////////////////////////////////////

// game objects

function Game(board){
	this.winner,
	this.tie,
	this.turn = 0;
	this.board = board,
	this.humanPlayer = "X",
	this.computerPlayer = "O",
	this.currentPlayer = this.humanPlayer,
	this.sortedBoard = this.sortBoard(board)
}

Game.prototype.switchPlayers = function(){
	if(this.currentPlayer === this.humanPlayer){
		this.currentPlayer = this.computerPlayer
	}
	else {
		this.currentPlayer = this.humanPlayer
	}
	this.turn++;
}

Game.prototype.makeComputerMove = function(
	){
	availableMoves = this.getAvailableMoves();
	availableMovesAndScores = this.getMoveScores(availableMoves)
	console.log(availableMovesAndScores)
	debugger
	for(var possibleMove = 0; possibleMove < availableMoves.length; possibleMove++){
			console.log('return value')
			console.log(this.simulateMove(new Game(this.board), availableMoves[possibleMove], this.currentPlayer))
			availableMovesAndScores[availableMoves[possibleMove]] = this.simulateMove(new Game(this.board), availableMoves[possibleMove], this.currentPlayer)
			console.log(availableMovesAndScores)
			debugger
	}
	this.switchPlayers();
}

Game.prototype.getAvailableMoves = function(){
	availableMoves = [];
	for(var availableMoveIndex = 0; availableMoveIndex < this.board.length; availableMoveIndex++){
		if(this.board[availableMoveIndex].innerText === ''){
			availableMoves.push(availableMoveIndex)
		}
	}
	return availableMoves
}

// for in starts at 0
Game.prototype.getMoveScores = function(availableMoves){
	moveScores = {}
	for(var availableMoveIndex = 0; availableMoveIndex< availableMoves.length; availableMoveIndex++){
		moveScores[availableMoves[availableMoveIndex]] = 0
	}
	return moveScores
}

Game.prototype.simulateMove = function(simGame, moveIndex, currentPlayer){
	// console.log(currentPlayer)
	simGame.board[moveIndex].innerText = currentPlayer;
	// console.log(currentPlayer + 'appended to square' + moveIndex)
	// console.log(simGame.board[moveIndex].innerText)
	simGame.checkForWinner();
	if(simGame.winner === simGame.humanPlayer){
		console.log('player will win at ' + moveIndex)
		return 1
	}
	else if(simGame.Winner === simGame.computerPlayer){
		// console.log('the computer may win!')
		return -1
	}
	else if(simGame.tie){
		// console.log('no moves')
		return 0
	}
	else{
		// console.log(this.board)
		// this.switchPlayers();
		// console.log(this.currentPlayer)
	simGame.board[moveIndex].innerText = '';
	return 5;
	}
}

Game.prototype.makeMove = function (game, player){
	marker = document.createTextNode(player)
	this.board[1].appendChild(marker)
}

Game.prototype.sortBoard = function(){
	sortedGameBoard = [[this.board[0], this.board[1], this.board[2]], [this.board[3], this.board[4], this.board[5]], [this.board[6], this.board[7], this.board[8]]]
	return sortedGameBoard
}

Game.prototype.checkThreeCells = function(arrayOfThreeCells){
	if(arrayOfThreeCells[0].innerText === this.currentPlayer && arrayOfThreeCells[0].innerText === arrayOfThreeCells[1].innerText && arrayOfThreeCells[1].innerText === arrayOfThreeCells[2].innerText){
		return true
	}
	else{
		return false;
	}
}

Game.prototype.checkRow = function(rowNumber, sortedGameBoard){
	row = sortedGameBoard[rowNumber]
	return this.checkThreeCells(row)
}

Game.prototype.checkColumn = function(columnNumber, sortedGameBoard){
	var column = [];
	for(var rowNumber = 0; rowNumber < sortedGameBoard.length; rowNumber++){
		column.push(sortedGameBoard[rowNumber][columnNumber])
	}
	return this.checkThreeCells(column)
}

Game.prototype.checkLeftDiagonal = function(sortedGameBoard){
	var leftDiagonal = [sortedGameBoard[0][0], sortedGameBoard[1][1], sortedGameBoard[2][2]]
	return this.checkThreeCells(leftDiagonal)
}

Game.prototype.checkRightDiagonal = function(sortedGameBoard){
	var rightDiagonal = [sortedGameBoard[0][2], sortedGameBoard[1][1], sortedGameBoard[2][0]]
	return this.checkThreeCells(rightDiagonal)
}

Game.prototype.checkForTie = function(){
	count = 0;
	for(var squareIndex =0; squareIndex < this.board.length; squareIndex++){
		if(this.board[squareIndex].innerText !== ''){
			count++;
		}
	}
	if(count === 9 && !this.checkForWinner()){
		this.tie = true;
		return true;
	}
	else if(count !== 9){
		return false
	}
}

Game.prototype.checkForWinner = function(){
	if(this.checkLeftDiagonal(this.sortedBoard) || this.checkRightDiagonal(this.sortedBoard)){
		this.winner = this.currentPlayer;
		return true
	}
	for(var index = 0; index < this.sortedBoard.length; index++){
		if(this.checkRow(index, this.sortedBoard) || this.checkColumn(index, this.sortedBoard)){
			this.winner = this.currentPlayer
			return true
		}
	}
	return false
}
<|endoftext|>


<commit_before>if (Meteor.isClient) {
  // counter starts at 0

  Template.bottom.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });

  Template.top.events({
    'click .button-begin': function () {
      $(".chart-dummy").fadeOut(function(){
        $(".top h2").text("Please, follow the intructions below the chart.");
        $(".button-begin").fadeOut();
        $(".image").fadeIn( function(){
          $(".bottom").fadeIn();
          $(".tiny-dot").fadeIn( function(){
            var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
            $(".tiny-dot").one(animationEnd, function(){
              $(this).removeClass('animated flash');
            });
          });
        });
      });
    }
  });

  Template.bottom.events({
    'click u': function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
      console.log("asd");
    },
    "click .radio-vlow": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-low": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-regular": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-high": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-vhigh": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<commit_msg>Added main layout<commit_after>if (Meteor.isClient) {
  // counter starts at 0

  Template.bottom.helpers({
    counter: function () {
      return Session.get('counter');
    }
  });
 /***/
  Template.top.events({
    'click .button-begin': function () {
      $(".chart-dummy").fadeOut(function(){
        $(".top h2").text("Please, follow the intructions below the chart.");
        $(".button-begin").fadeOut();
        $(".image").fadeIn( function(){
          $(".bottom").fadeIn();
          $(".tiny-dot").fadeIn( function(){
            var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
            $(".tiny-dot").one(animationEnd, function(){
              $(this).removeClass('animated flash');
            });
          });
        });
      });
    }
  });

  Template.bottom.events({
    'click u': function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
      console.log("asd");
    },
    "click .radio-vlow": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-low": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-regular": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-high": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    },
    "click .radio-vhigh": function () {
      $(".tiny-dot").addClass('animated flash');
      var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
      $(".tiny-dot").one(animationEnd, function(){
        $(this).removeClass('animated flash');
      });
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<|endoftext|>


<commit_before>/**
 * Precision round
 *
 * @param {number} value
 * @param {number} step Minimal discrete to round
 *
 * @return {number}
 *
 * @example
 * toPrecision(213.34, 1) == 213
 * toPrecision(213.34, .1) == 213.3
 * toPrecision(213.34, 10) == 210
 */

module.exports = require('./wrap')(function(value, step) {
	if (step === 0) return value;
	if (!step) return Math.round(value);
	step = parseFloat(step);
	value = Math.round(value / step) * step;
	return parseFloat(value.toFixed(require('./precision')(step)));
});<commit_msg>Fix runtime include<commit_after>/**
 * Precision round
 *
 * @param {number} value
 * @param {number} step Minimal discrete to round
 *
 * @return {number}
 *
 * @example
 * toPrecision(213.34, 1) == 213
 * toPrecision(213.34, .1) == 213.3
 * toPrecision(213.34, 10) == 210
 */
var precision = require('./precision');

module.exports = require('./wrap')(function(value, step) {
	if (step === 0) return value;
	if (!step) return Math.round(value);
	step = parseFloat(step);
	value = Math.round(value / step) * step;
	return parseFloat(value.toFixed(precision(step)));
});<|endoftext|>


<commit_before>import fetch from 'isomorphic-fetch';
import {getConfig} from '../config';
import {clearError, setError} from './error';
export const REQUEST_NOTIFICATIONS = 'REQUEST_NOTIFICATIONS';
export const RECEIVE_NOTIFICATIONS = 'RECEIVE_NOTIFICATIONS'

//
function requestNotifications(user) {
    return {
        type: REQUEST_NOTIFICATIONS,
        user
    };
}

//
function receiveNotifications(user, json) {
    return {
        type: RECEIVE_NOTIFICATIONS,
        user,
        payload: json
    };
}

//Example call
// store.dispatch(fetchNotifications('userId'));

export function fetchNotifications(user, fromDate) {

    // Thunk middleware knows how to handle functions.
    // It passes the dispatch method as an argument to the function,
    // thus making it able to dispatch actions itself.
    //
    return function dispatchFetchNotifications(dispatch) {
        //read the conf after extension.
        const config = getConfig();
        //Create the URL
        const URL = `${config.rootURL}/${config.notificationURL}`

        // First dispatch: the app state is updated to inform
        // that the API call is starting.
        //Maybe see https://github.com/rackt/redux/issues/911#issuecomment-149361073 for a saner implementation instead of chaining two dispatch.
        dispatch(clearError());
        dispatch(requestNotifications(user));

        // The function called by the thunk middleware can return a value,
        // that is passed on as the return value of the dispatch method.

        // In this case, we return a promise to wait for.
        // This is not required by thunk middleware, but it is convenient for us.
        const datePartURL = fromDate ? `?date=${fromDate}` : '';
        const fetchOptions = config.useCredentials ? { credentials: 'include'} : {};
        return fetch(`${URL}${datePartURL}`, fetchOptions)
        .then(response => response.json())
        .then(json =>

            // Here, we update the app state with the results of the API call.

            dispatch(receiveNotifications(user, json))
        )
        .catch(err => dispatch(setError({content: err.message, type: 'network'})));
    };
}
<commit_msg>correction of cors options<commit_after>import fetch from 'isomorphic-fetch';
import {getConfig} from '../config';
import {clearError, setError} from './error';
export const REQUEST_NOTIFICATIONS = 'REQUEST_NOTIFICATIONS';
export const RECEIVE_NOTIFICATIONS = 'RECEIVE_NOTIFICATIONS'

//
function requestNotifications(user) {
    return {
        type: REQUEST_NOTIFICATIONS,
        user
    };
}

//
function receiveNotifications(user, json) {
    return {
        type: RECEIVE_NOTIFICATIONS,
        user,
        payload: json
    };
}

//Example call
// store.dispatch(fetchNotifications('userId'));

export function fetchNotifications(user, fromDate) {

    // Thunk middleware knows how to handle functions.
    // It passes the dispatch method as an argument to the function,
    // thus making it able to dispatch actions itself.
    //
    return function dispatchFetchNotifications(dispatch) {
        //read the conf after extension.
        const config = getConfig();
        //Create the URL
        const URL = `${config.rootURL}/${config.notificationURL}`

        // First dispatch: the app state is updated to inform
        // that the API call is starting.
        //Maybe see https://github.com/rackt/redux/issues/911#issuecomment-149361073 for a saner implementation instead of chaining two dispatch.
        dispatch(clearError());
        dispatch(requestNotifications(user));

        // The function called by the thunk middleware can return a value,
        // that is passed on as the return value of the dispatch method.

        // In this case, we return a promise to wait for.
        // This is not required by thunk middleware, but it is convenient for us.
        const datePartURL = fromDate ? `?date=${fromDate}` : '';
        const credentialOptions = config.useCredentials ? { credentials: 'include'} : {};
        return fetch(`${URL}${datePartURL}`, {...credentialOptions})
            .then(response => response.json())
            .then(json => dispatch(receiveNotifications(user, json))) // Here, we update the app state with the results of the API call.
            .catch(err => dispatch(setError({content: err.message, type: 'network'})));
    };
}
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');

const BulkWriter = function BulkWriter(client, options) {
  this.client = client;
  this.options = options;
  this.interval = options.interval || 5000;
  this.waitForActiveShards = options.waitForActiveShards;
  this.pipeline = options.pipeline;

  this.bulk = []; // bulk to be flushed
  this.running = false;
  this.timer = false;
  debug('created', this);
};

BulkWriter.prototype.start = function start() {
  this.checkEsConnection();
  this.running = true;
  this.tick();
  debug('started');
};

BulkWriter.prototype.stop = function stop() {
  this.running = false;
  if (!this.timer) { return; }
  clearTimeout(this.timer);
  this.timer = null;
  debug('stopped');
};

BulkWriter.prototype.schedule = function schedule() {
  const thiz = this;
  this.timer = setTimeout(() => {
    thiz.tick();
  }, this.interval);
};

BulkWriter.prototype.tick = function tick() {
  debug('tick');
  const thiz = this;
  if (!this.running) { return; }
  this.flush()
    .then(() => {
      // Emulate finally with last .then()
    })
    .then(() => { // finally()
      thiz.schedule();
    });
};

BulkWriter.prototype.flush = function flush() {
  // write bulk to elasticsearch
  const thiz = this;
  if (this.bulk.length === 0) {
    debug('nothing to flush');
    return new Promise((resolve) => {
      return resolve();
    });
  }
  const bulk = this.bulk.concat();
  this.bulk = [];
  debug('going to write', bulk);
  return this.client.bulk({
    body: bulk,
    waitForActiveShards: this.waitForActiveShards,
    timeout: this.interval + 'ms',
    type: this.type
  }).then((res) => {
    if (res.errors && res.items) {
      res.items.forEach((item) => {
        if (item.index && item.index.error) {
          // eslint-disable-next-line no-console
          console.error('Elasticsearch index error', item.index.error);
        }
      });
    }
  }).catch((e) => { // prevent [DEP0018] DeprecationWarning
    // rollback this.bulk array
    thiz.bulk = bulk.concat(thiz.bulk);
    // eslint-disable-next-line no-console
    console.error(e);
    debug('error occrrued', e);
    this.stop();
    this.checkEsConnection();
  });
};

BulkWriter.prototype.append = function append(index, type, doc) {
  this.bulk.push({
    index: {
      _index: index, _type: type, pipeline: this.pipeline
    }
  });
  this.bulk.push(doc);
};

BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
  const thiz = this;
  thiz.esConnection = false;

  const operation = retry.operation({
    forever: true,
    retries: 1,
    factor: 1,
    minTimeout: 1 * 1000,
    maxTimeout: 60 * 1000,
    randomize: false
  });
  return new Promise((fulfill, reject) => {
    operation.attempt((currentAttempt) => {
      debug('checking for connection');
      thiz.client.ping().then(
        (res) => {
          thiz.esConnection = true;
          // Ensure mapping template is existing if desired
          if (thiz.options.ensureMappingTemplate) {
            thiz.ensureMappingTemplate(fulfill, reject);
          } else {
            fulfill(true);
          }
          debug('starting bulk writer');
          thiz.running = true;
          thiz.tick();
        },
        (err) => {
          debug('checking for connection');
          if (operation.retry(err)) {
            return;
          }
          // thiz.esConnection = false;
          reject(new Error('Cannot connect to ES'));
        }
      );
    });
  });
};

BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
  const thiz = this;
  // eslint-disable-next-line prefer-destructuring
  let mappingTemplate = thiz.options.mappingTemplate;
  if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
    const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
    mappingTemplate = JSON.parse(rawdata);
  }
  const tmplCheckMessage = {
    name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix)
  };
  thiz.client.indices.getTemplate(tmplCheckMessage).then(
    (res) => {
      fulfill(res);
    },
    (res) => {
      if (res.status && res.status === 404) {
        const tmplMessage = {
          name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix),
          create: true,
          body: mappingTemplate
        };
        thiz.client.indices.putTemplate(tmplMessage).then(
          (res1) => {
            fulfill(res1);
          },
          (err1) => {
            reject(err1);
          }
        );
      }
    }
  );
};

module.exports = BulkWriter;
<commit_msg>fixed typo, log item instead of only the error in case of index error<commit_after>const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');

const BulkWriter = function BulkWriter(client, options) {
  this.client = client;
  this.options = options;
  this.interval = options.interval || 5000;
  this.waitForActiveShards = options.waitForActiveShards;
  this.pipeline = options.pipeline;

  this.bulk = []; // bulk to be flushed
  this.running = false;
  this.timer = false;
  debug('created', this);
};

BulkWriter.prototype.start = function start() {
  this.checkEsConnection();
  this.running = true;
  this.tick();
  debug('started');
};

BulkWriter.prototype.stop = function stop() {
  this.running = false;
  if (!this.timer) { return; }
  clearTimeout(this.timer);
  this.timer = null;
  debug('stopped');
};

BulkWriter.prototype.schedule = function schedule() {
  const thiz = this;
  this.timer = setTimeout(() => {
    thiz.tick();
  }, this.interval);
};

BulkWriter.prototype.tick = function tick() {
  debug('tick');
  const thiz = this;
  if (!this.running) { return; }
  this.flush()
    .then(() => {
      // Emulate finally with last .then()
    })
    .then(() => { // finally()
      thiz.schedule();
    });
};

BulkWriter.prototype.flush = function flush() {
  // write bulk to elasticsearch
  const thiz = this;
  if (this.bulk.length === 0) {
    debug('nothing to flush');
    return new Promise((resolve) => {
      return resolve();
    });
  }
  const bulk = this.bulk.concat();
  this.bulk = [];
  debug('going to write', bulk);
  return this.client.bulk({
    body: bulk,
    waitForActiveShards: this.waitForActiveShards,
    timeout: this.interval + 'ms',
    type: this.type
  }).then((res) => {
    if (res.errors && res.items) {
      res.items.forEach((item) => {
        if (item.index && item.index.error) {
          // eslint-disable-next-line no-console
          console.error('Elasticsearch index error', item);
        }
      });
    }
  }).catch((e) => { // prevent [DEP0018] DeprecationWarning
    // rollback this.bulk array
    thiz.bulk = bulk.concat(thiz.bulk);
    // eslint-disable-next-line no-console
    console.error(e);
    debug('error occurred', e);
    this.stop();
    this.checkEsConnection();
  });
};

BulkWriter.prototype.append = function append(index, type, doc) {
  this.bulk.push({
    index: {
      _index: index, _type: type, pipeline: this.pipeline
    }
  });
  this.bulk.push(doc);
};

BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
  const thiz = this;
  thiz.esConnection = false;

  const operation = retry.operation({
    forever: true,
    retries: 1,
    factor: 1,
    minTimeout: 1 * 1000,
    maxTimeout: 60 * 1000,
    randomize: false
  });
  return new Promise((fulfill, reject) => {
    operation.attempt((currentAttempt) => {
      debug('checking for connection');
      thiz.client.ping().then(
        (res) => {
          thiz.esConnection = true;
          // Ensure mapping template is existing if desired
          if (thiz.options.ensureMappingTemplate) {
            thiz.ensureMappingTemplate(fulfill, reject);
          } else {
            fulfill(true);
          }
          debug('starting bulk writer');
          thiz.running = true;
          thiz.tick();
        },
        (err) => {
          debug('checking for connection');
          if (operation.retry(err)) {
            return;
          }
          // thiz.esConnection = false;
          reject(new Error('Cannot connect to ES'));
        }
      );
    });
  });
};

BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
  const thiz = this;
  // eslint-disable-next-line prefer-destructuring
  let mappingTemplate = thiz.options.mappingTemplate;
  if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
    const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
    mappingTemplate = JSON.parse(rawdata);
  }
  const tmplCheckMessage = {
    name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix)
  };
  thiz.client.indices.getTemplate(tmplCheckMessage).then(
    (res) => {
      fulfill(res);
    },
    (res) => {
      if (res.status && res.status === 404) {
        const tmplMessage = {
          name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix),
          create: true,
          body: mappingTemplate
        };
        thiz.client.indices.putTemplate(tmplMessage).then(
          (res1) => {
            fulfill(res1);
          },
          (err1) => {
            reject(err1);
          }
        );
      }
    }
  );
};

module.exports = BulkWriter;
<|endoftext|>


<commit_before>const SAMPLE = `Intro
[A /// //// D /// ////]
[A /// //// D /// ////]

Verse 1
[A]  There's nothing worth more, that will ever come [D]close
No thing can compare, You're our living [A]hope
Your Presence [D]Lord

Verse 2
[A]  I've tasted and seen, of the sweetest of [D]loves
Where my heart becomes free, and my shame is und[A]one
In Your Presence [D]Lord

Chorus
[A]Holy Spirit You are welcome here
Come [D]flood this place and fill the [Bm]atmosphere
Your [A]Glory God is what our hearts long for
To be [D]overcome by Your [Bm]Presence Lord

Interlude
[A /// //// D /// Bm ///]

REPEAT VERSE 1
REPEAT VERSE 2
REPEAT CHORUS 2X

Interlude
[A /// //// D /// Bm ///]
[A /// //// D /// Bm ///]

Bridge
[A]Let us become more aware of Your Presence
Let us experience the Glory of Your Goodness

[D]  Let us be[A/C#]come more a[Bm]ware of Your [A/C#]Presence
[D]  Let us exp[A/C#]erience the [Bm]Glory of Your [A/C#]Goodness
 X3
[D]Lord

REPEAT CHORUS DOWN`;

export default function chordproParser( text ) {

	const lines = text ? text.split( /\n/ ) : ;
	let result = '';

	lines.forEach( line => {

		let chord = false;
		let chordLine = "";
		let textLine = "";

		for ( let i = 0, len = line.length; i < len; i++ ) {

			if ( line[ i ] === "[" ) {

				chord = true;

			} else if ( line[ i ] === "]" ) {

				chord = false;

			} else if ( chord ) {

				chordLine += line[ i ];

			} else {

				textLine += line[ i ];

				if ( textLine.length > chordLine.length ) {

					chordLine += " ";

				}

			}

		}

		result += `${chordLine}\n`;
		result += `${textLine}\n`;

	} );

	return result;

}

/*if ( module.hot ) {

	console.log( SAMPLE );
	console.log( '--------------------------------------------------------------------------' );
	console.log( chordproParser( SAMPLE ) );

}*/

<commit_msg>bug fix<commit_after>const SAMPLE = `Intro
[A /// //// D /// ////]
[A /// //// D /// ////]

Verse 1
[A]  There's nothing worth more, that will ever come [D]close
No thing can compare, You're our living [A]hope
Your Presence [D]Lord

Verse 2
[A]  I've tasted and seen, of the sweetest of [D]loves
Where my heart becomes free, and my shame is und[A]one
In Your Presence [D]Lord

Chorus
[A]Holy Spirit You are welcome here
Come [D]flood this place and fill the [Bm]atmosphere
Your [A]Glory God is what our hearts long for
To be [D]overcome by Your [Bm]Presence Lord

Interlude
[A /// //// D /// Bm ///]

REPEAT VERSE 1
REPEAT VERSE 2
REPEAT CHORUS 2X

Interlude
[A /// //// D /// Bm ///]
[A /// //// D /// Bm ///]

Bridge
[A]Let us become more aware of Your Presence
Let us experience the Glory of Your Goodness

[D]  Let us be[A/C#]come more a[Bm]ware of Your [A/C#]Presence
[D]  Let us exp[A/C#]erience the [Bm]Glory of Your [A/C#]Goodness
 X3
[D]Lord

REPEAT CHORUS DOWN`;

export default function chordproParser( text ) {

	const lines = text ? text.split( /\n/ ) : [];
	let result = '';

	lines.forEach( line => {

		let chord = false;
		let chordLine = "";
		let textLine = "";

		for ( let i = 0, len = line.length; i < len; i++ ) {

			if ( line[ i ] === "[" ) {

				chord = true;

			} else if ( line[ i ] === "]" ) {

				chord = false;

			} else if ( chord ) {

				chordLine += line[ i ];

			} else {

				textLine += line[ i ];

				if ( textLine.length > chordLine.length ) {

					chordLine += " ";

				}

			}

		}

		result += `${chordLine}\n`;
		result += `${textLine}\n`;

	} );

	return result;

}

/*if ( module.hot ) {

	console.log( SAMPLE );
	console.log( '--------------------------------------------------------------------------' );
	console.log( chordproParser( SAMPLE ) );

}*/

<|endoftext|>


<commit_before>/**
 * Created by vytautassugintas on 09/04/16.
 */
(function () {
    "use strict";
    angular.module("myApp")
        .factory("ProfileService", ProfileService);

    ProfileService.$inject = [
        "User",
        "Kudos",
        "Challenges",
        "Auth",
        "$q"
    ];

    function ProfileService(userBackend, kudosBackend, challengesBackend, authBackend, $q) {
        var service = {
            userHome: UserHome,
            updateUser: UpdateUser,
            remainingKudos: RemainingKudos,
            receivedKudos: ReceivedKudos,
            receivedChallenges: ReceivedChallenges,
            feedKudos: StreamKudos,
            feedKudosChanged: StreamKudosChanged,
            checkUser: CheckUser,
            logout: Logout
        };
        return service;

        function UserHome() {
            return userBackend.home();
        }

        function CheckUser() {
            return userBackend.check();
        }

        function UpdateUser(updateInfo) {
            return userBackend.update(updateInfo);
        }

        function RemainingKudos() {
            return kudosBackend.remaining();
        }

        function ReceivedKudos() {
            return kudosBackend.received();
        }

        function StreamKudos(requestData) {
            return kudosBackend.feed(requestData);
        }

        function StreamKudosChanged(requestData) {
            return kudosBackend.feedChanged(requestData);
        }

        function ReceivedChallenges() {
            return challengesBackend.receivedChallenges();
        }

        function Logout() {
            return authBackend.logout();
        }
    }
})();
<commit_msg>Reverted small mistake.<commit_after>/**
 * Created by vytautassugintas on 09/04/16.
 */
(function () {
    "use strict";
    angular.module("myApp")
        .factory("ProfileService", ProfileService);

    ProfileService.$inject = [
        "User",
        "Kudos",
        "Challenges",
        "Auth",
        "$q"
    ];

    function ProfileService(userBackend, kudosBackend, challengesBackend, authBackend, $q) {
        var service = {
            userHome: UserHome,
            updateUser: UpdateUser,
            listUsers: ListUsers,
            remainingKudos: RemainingKudos,
            receivedKudos: ReceivedKudos,
            receivedChallenges: ReceivedChallenges,
            feedKudos: StreamKudos,
            feedKudosChanged: StreamKudosChanged,
            checkUser: CheckUser,
            logout: Logout
        };
        return service;

        function UserHome() {
            return userBackend.home();
        }

        function CheckUser() {
            return userBackend.check();
        }

        function ListUsers() {
            return userBackend.list();
        }

        function UpdateUser(updateInfo) {
            return userBackend.update(updateInfo);
        }

        function RemainingKudos() {
            return kudosBackend.remaining();
        }

        function ReceivedKudos() {
            return kudosBackend.received();
        }

        function StreamKudos(requestData) {
            return kudosBackend.feed(requestData);
        }

        function StreamKudosChanged(requestData) {
            return kudosBackend.feedChanged(requestData);
        }

        function ReceivedChallenges() {
            return challengesBackend.receivedChallenges();
        }

        function Logout() {
            return authBackend.logout();
        }
    }
})();
<|endoftext|>


<commit_before>//////// Module Definition ////////////
define([
    'ajv',
    'parsimmon',
    'util/util.module'
], function(ajv, parsimmon) {
    ///////////////////////////////////////
    angular.module('util').factory('ruleParser', ['$http', '$q', 'util',
        function($http, $q, util) {
            var parse = function(rule) {
                var P = parsimmon;

                function word(w) {
                    return P.string(w).trim(P.regexp(/\s*/m));
                }

                function assignment(r, rhs) {
                    return P.seqObj(['attribute', r.ObjectTerm],
                                    r.colon,
                                    ['value', rhs]);
                }

                function specifier(r, opening, closing, typ) {
                    return P.seqObj(opening,
                                    ['assignments',
                                        P.sepBy(r.AssignmentWithPlaceholder,
                                                r.comma)],
                                    closing)
                            .thru(type(typ + '-specifier'));
                }

                function specifierExpression(r, type)
                {
                    return P.seqObj(r.openingParenthesis,
                                    ['lhs', r.SpecifierTerm],
                                    r[type],
                                    ['rhs', r.SpecifierTerm],
                                    r.closingParenthesis)
                            .map(function(obj) {
                                return Object.freeze({
                                    type: type,
                                    specifiers: [obj.lhs, obj.rhs]
                                });
                            });
                }

                function relationalAtom(r, setTerm) {
                    return P.seqObj(['subject', r.ObjectTerm],
                                    r.dot,
                                    ['predicate', r.ObjectTerm],
                                    r.equals,
                                    ['object', r.ObjectTerm],
                                    r.at,
                                    ['annotation', setTerm])
                        .map(function(obj) {
                            return Object.freeze({
                                type: 'relational-atom',
                                predicate: obj.predicate,
                                arguments: [obj.subject, obj.object],
                                annotation: obj.annotation
                            });
                        });
                }

                function type(type) {
                    return function(parser) {
                        return parser.map(function(obj) {
                            obj.type = type;
                            return Object.freeze(obj);
                        });
                    };
                }

                var MARPL = P.createLanguage({
                    at: function() { return word('@'); },
                    dot: function() { return word('.'); },
                    comma: function() { return word(','); },
                    colon: function() { return word(':'); },
                    arrow: function() { return word('->'); },
                    union: function() { return word('||'); },
                    equals: function() { return word('='); },
                    contains: function() { return word('#'); },
                    difference: function() { return word('\\'); },
                    intersection: function() { return word('&&'); },
                    openingBrace: function() { return word('{'); },
                    closingBrace: function() { return word('}'); },
                    openingFloor: function() { return word('|_'); },
                    closingFloor: function() { return word('_|'); },
                    openingBracket: function() { return word('['); },
                    closingBracket: function() { return word(']'); },
                    openingParenthesis: function() { return word('('); },
                    closingParenthesis: function() { return word(')'); },

                    ObjectVariable: function() {
                        return P.seqObj(['name', P.regexp(/\?[a-zA-Z]\w*/)])
                                .thru(type('variable'));
                    },
                    ObjectLiteral: function() {
                        return P.seqObj(['name', P.regexp(/[PQ]\d+/)])
                                .thru(type('literal'));
                    },
                    ObjectTerm: function(r) {
                        return P.alt(
                            r.ObjectVariable,
                            r.ObjectLiteral
                        );
                    },
                    SetLiteral: function(r) {
                        return P.seqObj(r.openingBrace,
                                        ['assignments', P.sepBy(r.Assignment, r.comma)],
                                        r.closingBrace)
                                .thru(type('set-term'));
                    },
                    SetVariable: function() {
                        return P.seqObj(['name', P.regexp(/\?\?[a-zA-Z]\w*/)])
                                .thru(type('set-variable'));
                    },
                    SetTerm: function(r) {
                        return P.alt(
                            r.SetLiteral,
                            r.SetVariable
                        );
                    },
                    SetAtom: function(r) {
                        return P.seqObj(r.openingParenthesis,
                                        ['attribute', r.ObjectTerm],
                                        r.colon,
                                        ['value', r.ObjectTerm],
                                        r.closingParenthesis,
                                        r.contains,
                                        ['set', r.SetTerm])
                                .thru(type('set-atom'));
                    },
                    FunctionTerm: function(r) {
                        return P.seqObj(['name', P.regexp(/[a-zA-Z]\w*/)],
                                        r.openingParenthesis,
                                        ['arguments',
                                         P.sepBy(P.alt(r.ObjectTerm,
                                                       r.SetTerm),
                                                 r.comma)],
                                        r.closingParenthesis)
                                .thru(type('function-term'));
                    },
                    RelationalAtom: function(r) {
                        return relationalAtom(r, r.SetTerm);
                    },
                    RelationalAtomWithFunctionTerm: function(r) {
                        return relationalAtom(r, r.FunctionTerm);
                    },
                    Placeholder: function() {
                        return P.alt(
                            word('*').map(function() {
                                return Object.freeze({
                                    type: "star"
                                });
                            }),
                            word('+').map(function() {
                                return Object.freeze({
                                    type: "plus"
                                });
                            })
                        );
                    },
                    Assignment: function(r) {
                        return assignment(r, r.ObjectTerm);
                    },
                    AssignmentWithPlaceholder: function(r) {
                        return assignment(r, P.alt(
                            r.ObjectTerm,
                            r.Placeholder
                        ));
                    },
                    Specifier: function(r) {
                        return P.alt(
                            specifier(r, r.openingFloor, r.closingFloor, 'open'),
                            specifier(r, r.openingBracket, r.closingBracket, 'closed')
                        );
                    },
                    SpecifierExpression: function(r) {
                        return P.alt(
                            specifierExpression(r, 'union'),
                            specifierExpression(r, 'intersection'),
                            specifierExpression(r, 'difference'));
                    },
                    SpecifierTerm: function(r) {
                        return P.alt(r.SpecifierExpression,
                                     r.Specifier);
                    },
                    SpecifierAtom: function(r) {
                        return P.seqObj(['specifier', r.SpecifierTerm],
                                        r.openingParenthesis,
                                        ['set', r.SetVariable],
                                        r.closingParenthesis);
                    },

                    Rule: function(r) {
                        return P.seqObj(['body', r.Body],
                                        r.arrow,
                                        ['head', r.Head]);
                    },
                    Head: function(r) {
                        return P.alt(
                            r.RelationalAtom,
                            r.RelationalAtomWithFunctionTerm
                        );
                    },
                    Body: function(r) {
                        return P.sepBy(
                            P.alt(
                                r.RelationalAtom,
                                r.SetAtom,
                                r.SpecifierAtom
                            ),
                            P.string(',')
                        );
                    }
                });

                return MARPL.SpecifierTerm.tryParse(rule);
            };

            return {
                parse: parse
            };
        }]);

    return {};
});
<commit_msg>Successfully parse rules<commit_after>//////// Module Definition ////////////
define([
    'ajv',
    'parsimmon',
    'util/util.module'
], function(ajv, parsimmon) {
    ///////////////////////////////////////
    angular.module('util').factory('ruleParser', ['$http', '$q', 'util',
        function($http, $q, util) {
            var parse = function(rule) {
                var P = parsimmon;

                function word(w) {
                    return P.string(w).trim(P.regexp(/\s*/m));
                }

                function assignment(r, rhs) {
                    return P.seqObj(['attribute', r.ObjectTerm],
                                    r.colon,
                                    ['value', rhs]);
                }

                function specifier(r, opening, closing, typ) {
                    return P.seqObj(opening,
                                    ['assignments',
                                        P.sepBy(r.AssignmentWithPlaceholder,
                                                r.comma)],
                                    closing)
                            .thru(type(typ + '-specifier'));
                }

                function specifierExpression(r, type)
                {
                    return P.seqObj(r.openingParenthesis,
                                    ['lhs', r.SpecifierTerm],
                                    r[type],
                                    ['rhs', r.SpecifierTerm],
                                    r.closingParenthesis)
                            .map(function(obj) {
                                return Object.freeze({
                                    type: type,
                                    specifiers: [obj.lhs, obj.rhs]
                                });
                            });
                }

                function relationalAtom(r, setTerm) {
                    return P.seqObj(['subject', r.ObjectTerm],
                                    r.dot,
                                    ['predicate', r.ObjectTerm],
                                    r.equals,
                                    ['object', r.ObjectTerm],
                                    r.at,
                                    ['annotation', setTerm])
                        .map(function(obj) {
                            return Object.freeze({
                                type: 'relational-atom',
                                predicate: obj.predicate,
                                arguments: [obj.subject, obj.object],
                                annotation: obj.annotation
                            });
                        });
                }

                function type(type) {
                    return function(parser) {
                        return parser.map(function(obj) {
                            obj.type = type;
                            return Object.freeze(obj);
                        });
                    };
                }

                var MARPL = P.createLanguage({
                    at: function() { return word('@'); },
                    dot: function() { return word('.'); },
                    comma: function() { return word(','); },
                    colon: function() { return word(':'); },
                    arrow: function() { return word('->'); },
                    union: function() { return word('||'); },
                    equals: function() { return word('='); },
                    contains: function() { return word('#'); },
                    difference: function() { return word('\\'); },
                    intersection: function() { return word('&&'); },
                    openingBrace: function() { return word('{'); },
                    closingBrace: function() { return word('}'); },
                    openingFloor: function() { return word('|_'); },
                    closingFloor: function() { return word('_|'); },
                    openingBracket: function() { return word('['); },
                    closingBracket: function() { return word(']'); },
                    openingParenthesis: function() { return word('('); },
                    closingParenthesis: function() { return word(')'); },

                    ObjectVariable: function() {
                        return P.seqObj(['name', P.regexp(/\?[a-zA-Z]\w*/)])
                                .thru(type('variable'));
                    },
                    ObjectLiteral: function() {
                        return P.seqObj(['name', P.regexp(/[PQ]\d+/)])
                                .thru(type('literal'));
                    },
                    ObjectTerm: function(r) {
                        return P.alt(
                            r.ObjectVariable,
                            r.ObjectLiteral
                        );
                    },
                    SetLiteral: function(r) {
                        return P.seqObj(r.openingBrace,
                                        ['assignments', P.sepBy(r.Assignment, r.comma)],
                                        r.closingBrace)
                                .thru(type('set-term'));
                    },
                    SetVariable: function() {
                        return P.seqObj(['name', P.regexp(/\?\?[a-zA-Z]\w*/)])
                                .thru(type('set-variable'));
                    },
                    SetTerm: function(r) {
                        return P.alt(
                            r.SetLiteral,
                            r.SetVariable
                        );
                    },
                    SetAtom: function(r) {
                        return P.seqObj(r.openingParenthesis,
                                        ['attribute', r.ObjectTerm],
                                        r.colon,
                                        ['value', r.ObjectTerm],
                                        r.closingParenthesis,
                                        r.contains,
                                        ['set', r.SetTerm])
                                .thru(type('set-atom'));
                    },
                    FunctionTerm: function(r) {
                        return P.seqObj(['name', P.regexp(/[a-zA-Z]\w*/)],
                                        r.openingParenthesis,
                                        ['arguments',
                                         P.sepBy(P.alt(r.ObjectTerm,
                                                       r.SetTerm),
                                                 r.comma)],
                                        r.closingParenthesis)
                                .thru(type('function-term'));
                    },
                    RelationalAtom: function(r) {
                        return relationalAtom(r, r.SetTerm);
                    },
                    RelationalAtomWithFunctionTerm: function(r) {
                        return relationalAtom(r, r.FunctionTerm);
                    },
                    Placeholder: function() {
                        return P.alt(
                            word('*').map(function() {
                                return Object.freeze({
                                    type: "star"
                                });
                            }),
                            word('+').map(function() {
                                return Object.freeze({
                                    type: "plus"
                                });
                            })
                        );
                    },
                    Assignment: function(r) {
                        return assignment(r, r.ObjectTerm);
                    },
                    AssignmentWithPlaceholder: function(r) {
                        return assignment(r, P.alt(
                            r.ObjectTerm,
                            r.Placeholder
                        ));
                    },
                    Specifier: function(r) {
                        return P.alt(
                            specifier(r, r.openingFloor, r.closingFloor, 'open'),
                            specifier(r, r.openingBracket, r.closingBracket, 'closed')
                        );
                    },
                    SpecifierExpression: function(r) {
                        return P.alt(
                            specifierExpression(r, 'union'),
                            specifierExpression(r, 'intersection'),
                            specifierExpression(r, 'difference'));
                    },
                    SpecifierTerm: function(r) {
                        return P.alt(r.SpecifierExpression,
                                     r.Specifier);
                    },
                    SpecifierAtom: function(r) {
                        return P.seqObj(['specifier', r.SpecifierTerm],
                                        r.openingParenthesis,
                                        ['set', r.SetVariable],
                                        r.closingParenthesis);
                    },

                    Rule: function(r) {
                        return P.seqObj(['body', r.Body],
                                        r.arrow,
                                        ['head', r.Head]);
                    },
                    Head: function(r) {
                        return P.alt(
                            r.RelationalAtom,
                            r.RelationalAtomWithFunctionTerm
                        );
                    },
                    Body: function(r) {
                        return P.sepBy(
                            P.alt(
                                r.RelationalAtom,
                                r.SetAtom,
                                r.SpecifierAtom
                            ),
                            P.string(',')
                        );
                    }
                });

                return MARPL.Rule.tryParse(rule);
            };

            return {
                parse: parse
            };
        }]);

    return {};
});
<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by YOURNAME @ YOURCOMPANY

// open an overlay when the page finishes loading
window.addEventListener("load", function() {
    load_overlay(window.location.hash.substring(1));
});

// open an overlay when the hash changes
window.addEventListener("hashchange", function() {
    load_overlay(window.location.hash.substring(1));
});

// function to open an overlay
// @param  {Element}  elem - An element to mark as active
function load_overlay(target_overlay) {
    if ((typeof target_overlay === "string")) {
        var overlays        = document.querySelectorAll("[data-overlay]"),
            overlay_closers = document.querySelectorAll(".overlay-closer");

        // make sure overlays exist
        if (overlays.length > 0) {
            for (var i = 0; i < overlays.length; i++) {
                // check if the current overlay matches the target overlay
                if (overlays[i].dataset.overlay === target_overlay) {
                    // mark the element as active
                    overlays[i].classList.add("is-active");

                    // mark the hidden element as unhidden, and focus it
                    if (overlays[i].hasAttribute("aria-hidden")) {
                        overlays[i].setAttribute("aria-hidden", "false");
                        overlays[i].focus();
                    }

                    // make sure overlay closers exist
                    if ((typeof overlay_closers === "object")) {
                        for (i2 = 0; i2 < overlay_closers.length; i2++) {
                            // mark the overlay closer as active
                            overlay_closers[i2].classList.add("is-active");

                            // mark the overlay closer as unhidden
                            overlay_closers[i2].setAttribute("aria-hidden", "false");
                        }
                    }
                // if the current overlay does not match the target overlay
                } else {
                    // mark the element as inactive
                    overlays[i].classList.remove("is-active");

                    // mark the element as hidden
                    if (overlays[i].hasAttribute("aria-hidden")) {
                        overlays[i].setAttribute("aria-hidden", "true");
                    }
                }
            }
        }
    }
}
<commit_msg>Correct overlay_load param description<commit_after>// JavaScript Document

// Scripts written by YOURNAME @ YOURCOMPANY

// open an overlay when the page finishes loading
window.addEventListener("load", function() {
    load_overlay(window.location.hash.substring(1));
});

// open an overlay when the hash changes
window.addEventListener("hashchange", function() {
    load_overlay(window.location.hash.substring(1));
});

// function to open an overlay
// @param  {String}  target_overlay - Name of the overlay to mark active
function load_overlay(target_overlay) {
    if ((typeof target_overlay === "string")) {
        var overlays        = document.querySelectorAll("[data-overlay]"),
            overlay_closers = document.querySelectorAll(".overlay-closer");

        // make sure overlays exist
        if (overlays.length > 0) {
            for (var i = 0; i < overlays.length; i++) {
                // check if the current overlay matches the target overlay
                if (overlays[i].dataset.overlay === target_overlay) {
                    // mark the element as active
                    overlays[i].classList.add("is-active");

                    // mark the hidden element as unhidden, and focus it
                    if (overlays[i].hasAttribute("aria-hidden")) {
                        overlays[i].setAttribute("aria-hidden", "false");
                        overlays[i].focus();
                    }

                    // make sure overlay closers exist
                    if ((typeof overlay_closers === "object")) {
                        for (i2 = 0; i2 < overlay_closers.length; i2++) {
                            // mark the overlay closer as active
                            overlay_closers[i2].classList.add("is-active");

                            // mark the overlay closer as unhidden
                            overlay_closers[i2].setAttribute("aria-hidden", "false");
                        }
                    }
                // if the current overlay does not match the target overlay
                } else {
                    // mark the element as inactive
                    overlays[i].classList.remove("is-active");

                    // mark the element as hidden
                    if (overlays[i].hasAttribute("aria-hidden")) {
                        overlays[i].setAttribute("aria-hidden", "true");
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// At build time, this (and everything else in this folder) is moved to
// ${pushkin_front_end_quizzes_dir}, so all paths are relative to that root

import React from 'react'
import s from './styles.scss'

export default class ${QUIZ_NAME} extends React.Component {
	render() {
		return (

Welcome to the ${QUIZ_NAME} quiz!

		);
	}
}
<commit_msg>relative message<commit_after>// At build time, this (and everything else in this folder) is moved to
// ${pushkin_front_end_quizzes_dir}, so all paths to modules located outside of this
// folder are relative to that root

import React from 'react'
import s from './styles.scss'

export default class ${QUIZ_NAME} extends React.Component {
	render() {
		return (

Welcome to the ${QUIZ_NAME} quiz!

		);
	}
}
<|endoftext|>


<commit_before>var Lang = A.Lang,
	isBoolean = Lang.isBoolean,
	isObject = Lang.isObject,
	isUndefined = Lang.isUndefined,

	toNumber = function(val) {
		return parseInt(val, 10) || 0;
	},

	DASH = '-',
	DOT = '.',
	EMPTY_STR = '',
	PIXEL = 'px',
	SPACE = ' ',

	ANIMATED = 'animated',
	ANIMATING = 'animating',
	BIND_DOM_EVENTS = 'bindDOMEvents',
	CLICK = 'click',
	COLLAPSED = 'collapsed',
	CONTENT = 'content',
	CUBIC_BEZIER = 'cubic-bezier',
	DOWN = 'down',
	ENTER = 'enter',
	ESC = 'esc',
	EXPANDED = 'expanded',
	EXPANDED_CHANGE = 'expandedChange',
	GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
	GUTTER = 'gutter',
	HEADER = 'header',
	HELPER = 'helper',
	KEYDOWN = 'keydown',
	LEFT = 'left',
	LINEAR = 'linear',
	MARGIN_TOP = 'marginTop',
	MINUS = 'minus',
	NUM_MINUS = 'num_minus',
	NUM_PLUS = 'num_plus',
	PARENT_NODE = 'parentNode',
	PLUS = 'plus',
	RIGHT = 'right',
	SPACE = 'space',
	TRANSITION = 'transition',
	TRANSITION_END = 'transitionEnd',
	TRANSITION_START = 'transitionStart',
	UP = 'up',
	WRAPPER = 'wrapper',
	ZIPPY = 'zippy',

	getCN = A.getClassName,

	CSS_ZIPPY_CONTENT = getCN(ZIPPY, CONTENT),
	CSS_ZIPPY_CONTENT_COLLAPSED = getCN(ZIPPY, CONTENT, COLLAPSED),
	CSS_ZIPPY_CONTENT_EXPANDED = getCN(ZIPPY, CONTENT, EXPANDED),
	CSS_ZIPPY_CONTENT_WRAPPER = getCN(ZIPPY, CONTENT, WRAPPER),
	CSS_ZIPPY_HEADER = getCN(ZIPPY, HEADER),
	CSS_ZIPPY_HEADER_COLLAPSED = getCN(ZIPPY, HEADER, COLLAPSED),
	CSS_ZIPPY_HEADER_EXPANDED = getCN(ZIPPY, HEADER, EXPANDED),

	CSS_ZIPPY_CONTENT_STATE = {
		'false': CSS_ZIPPY_CONTENT_COLLAPSED,
		'true': CSS_ZIPPY_CONTENT_EXPANDED
	},

	CSS_ZIPPY_HEADER_STATE = {
		'false': CSS_ZIPPY_HEADER_COLLAPSED,
		'true': CSS_ZIPPY_HEADER_EXPANDED
	},

	TPL_CONTENT_WRAPPER = '

';

var Zippy = A.Component.create({
	NAME: ZIPPY,

	ATTRS: {

		animated: {
			validator: isBoolean,
			value: false,
			writeOnce: true
		},

		animating: {
			validator: isBoolean,
			value: false
		},

		bindDOMEvents: {
			validator: isBoolean,
			value: true,
			writeOnce: true
		},

		content: {
			setter: A.one
		},

		expanded: {
			validator: isBoolean,
			value: true
		},

		header: {
			setter: A.one
		},

		transition: {
			validator: isObject,
			value: {
				duration: 0.4,
			    easing: CUBIC_BEZIER
			}
		}

	},

	EXTENDS: A.Base,

	headerEventHandler: function(event, instance) {
		if (event.type === CLICK || event.isKey(ENTER) || event.isKey(SPACE)) {
			event.preventDefault();

			return instance.toggle();
		}
		else if (event.isKey(DOWN) || event.isKey(RIGHT) || event.isKey(NUM_PLUS)) {
			event.preventDefault();

			return instance.expand();
		}
		else if (event.isKey(UP) || event.isKey(LEFT) || event.isKey(ESC) || event.isKey(NUM_MINUS)) {
			event.preventDefault();

			return instance.collapse();
		}
	},

	prototype: {

		initializer: function() {
			var instance = this;

			instance.bindUI();
			instance.syncUI();

			instance._uiSetExpanded(instance.get(EXPANDED));
		},

		bindUI: function() {
			var instance = this;
			var header = instance.get(HEADER);

			header.setData(ZIPPY, instance);

			instance.on(EXPANDED_CHANGE, A.bind(instance._onExpandedChange, instance));

			if (instance.get(BIND_DOM_EVENTS)) {
				header.on([CLICK, KEYDOWN], A.rbind(Zippy.headerEventHandler, null, instance));
			}
		},

		syncUI: function() {
			var instance = this;

			instance.get(CONTENT).addClass(CSS_ZIPPY_CONTENT);
			instance.get(HEADER).addClass(CSS_ZIPPY_HEADER);
		},

		animate: function(config, fn) {
			var instance = this;

			instance._uiSetExpanded(true);

			var transition = A.merge(config, instance.get(TRANSITION));

			instance.get(CONTENT).transition(transition, A.bind(fn, instance));
		},

		collapse: function() {
			var instance = this;

			return instance.toggle(false);
		},

		expand: function() {
			var instance = this;

			return instance.toggle(true);
		},

		getContentHeight: function() {
			var instance = this;
			var content = instance.get(CONTENT);
			var expanded = instance.get(EXPANDED), height;

			if (!expanded) {
				instance._uiSetExpanded(true);
			}

			if (content.hasMethod(GET_BOUNDING_CLIENT_RECT)) {
				var preciseRegion = content.invoke(GET_BOUNDING_CLIENT_RECT);

				if (preciseRegion) {
					height = preciseRegion.bottom - preciseRegion.top;
				}
			}
			else {
				height = content.get(OFFSET_HEIGHT);
			}

			if (!expanded) {
				instance._uiSetExpanded(false);
			}

			return height;
		},

		toggle: function(expanded) {
			var instance = this;

			if (isUndefined(expanded)) {
				expanded = !instance.get(EXPANDED);
			}

			if (instance.get(ANIMATED)) {
				if (instance.get(ANIMATING)) {
					return expanded;
				}

				var content = instance.get(CONTENT);

				if (isUndefined(instance[GUTTER])) {
					instance[GUTTER] = toNumber(content.getStyle(MARGIN_TOP));

					content.wrap(TPL_CONTENT_WRAPPER);
				}

				var height = instance.getContentHeight();

				if (expanded) {
					content.setStyle(MARGIN_TOP, -(height + instance[GUTTER]));
				}

				instance.set(ANIMATING, true);

				instance.animate(
					{
						marginTop: (expanded ? instance[GUTTER] : -(height + instance[GUTTER])) + PIXEL
					},
					function() {
						instance.set(ANIMATING, false);

						instance.set(EXPANDED, expanded);
					}
				);
			}
			else {
				instance.set(EXPANDED, expanded);
			}

			return expanded;
		},

		_onExpandedChange: function(event) {
			var instance = this;

			instance._uiSetExpanded(event.newVal);
		},

		_uiSetExpanded: function(val) {
			var instance = this;

			instance.get(CONTENT).replaceClass(CSS_ZIPPY_CONTENT_STATE[!val], CSS_ZIPPY_CONTENT_STATE[val]);
			instance.get(HEADER).replaceClass(CSS_ZIPPY_HEADER_STATE[!val], CSS_ZIPPY_HEADER_STATE[val]);
		}

	}
});

A.Zippy = Zippy;<commit_msg>AUI-615 Refactoring toggle method<commit_after>var Lang = A.Lang,
	isBoolean = Lang.isBoolean,
	isObject = Lang.isObject,
	isUndefined = Lang.isUndefined,

	toNumber = function(val) {
		return parseInt(val, 10) || 0;
	},

	DASH = '-',
	DOT = '.',
	EMPTY_STR = '',
	PIXEL = 'px',
	SPACE = ' ',

	ANIMATED = 'animated',
	ANIMATING = 'animating',
	BIND_DOM_EVENTS = 'bindDOMEvents',
	CLICK = 'click',
	COLLAPSED = 'collapsed',
	CONTENT = 'content',
	CUBIC_BEZIER = 'cubic-bezier',
	DOWN = 'down',
	ENTER = 'enter',
	ESC = 'esc',
	EXPANDED = 'expanded',
	EXPANDED_CHANGE = 'expandedChange',
	GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect',
	GUTTER = 'gutter',
	HEADER = 'header',
	HELPER = 'helper',
	KEYDOWN = 'keydown',
	LEFT = 'left',
	LINEAR = 'linear',
	MARGIN_TOP = 'marginTop',
	MINUS = 'minus',
	NUM_MINUS = 'num_minus',
	NUM_PLUS = 'num_plus',
	PARENT_NODE = 'parentNode',
	PLUS = 'plus',
	RIGHT = 'right',
	SPACE = 'space',
	TRANSITION = 'transition',
	TRANSITION_END = 'transitionEnd',
	TRANSITION_START = 'transitionStart',
	UP = 'up',
	WRAPPER = 'wrapper',
	ZIPPY = 'zippy',

	getCN = A.getClassName,

	CSS_ZIPPY_CONTENT = getCN(ZIPPY, CONTENT),
	CSS_ZIPPY_CONTENT_COLLAPSED = getCN(ZIPPY, CONTENT, COLLAPSED),
	CSS_ZIPPY_CONTENT_EXPANDED = getCN(ZIPPY, CONTENT, EXPANDED),
	CSS_ZIPPY_CONTENT_WRAPPER = getCN(ZIPPY, CONTENT, WRAPPER),
	CSS_ZIPPY_HEADER = getCN(ZIPPY, HEADER),
	CSS_ZIPPY_HEADER_COLLAPSED = getCN(ZIPPY, HEADER, COLLAPSED),
	CSS_ZIPPY_HEADER_EXPANDED = getCN(ZIPPY, HEADER, EXPANDED),

	CSS_ZIPPY_CONTENT_STATE = {
		'false': CSS_ZIPPY_CONTENT_COLLAPSED,
		'true': CSS_ZIPPY_CONTENT_EXPANDED
	},

	CSS_ZIPPY_HEADER_STATE = {
		'false': CSS_ZIPPY_HEADER_COLLAPSED,
		'true': CSS_ZIPPY_HEADER_EXPANDED
	},

	TPL_CONTENT_WRAPPER = '

';

var Zippy = A.Component.create({
	NAME: ZIPPY,

	ATTRS: {

		animated: {
			validator: isBoolean,
			value: false,
			writeOnce: true
		},

		animating: {
			validator: isBoolean,
			value: false
		},

		bindDOMEvents: {
			validator: isBoolean,
			value: true,
			writeOnce: true
		},

		content: {
			setter: A.one
		},

		expanded: {
			validator: isBoolean,
			value: true
		},

		header: {
			setter: A.one
		},

		transition: {
			validator: isObject,
			value: {
				duration: 0.4,
			    easing: CUBIC_BEZIER
			}
		}

	},

	EXTENDS: A.Base,

	headerEventHandler: function(event, instance) {
		if (event.type === CLICK || event.isKey(ENTER) || event.isKey(SPACE)) {
			event.preventDefault();

			return instance.toggle();
		}
		else if (event.isKey(DOWN) || event.isKey(RIGHT) || event.isKey(NUM_PLUS)) {
			event.preventDefault();

			return instance.expand();
		}
		else if (event.isKey(UP) || event.isKey(LEFT) || event.isKey(ESC) || event.isKey(NUM_MINUS)) {
			event.preventDefault();

			return instance.collapse();
		}
	},

	prototype: {

		initializer: function() {
			var instance = this;

			instance.bindUI();
			instance.syncUI();

			instance._uiSetExpanded(instance.get(EXPANDED));
		},

		bindUI: function() {
			var instance = this;
			var header = instance.get(HEADER);

			header.setData(ZIPPY, instance);

			instance.on(EXPANDED_CHANGE, A.bind(instance._onExpandedChange, instance));

			if (instance.get(BIND_DOM_EVENTS)) {
				header.on([CLICK, KEYDOWN], A.rbind(Zippy.headerEventHandler, null, instance));
			}
		},

		syncUI: function() {
			var instance = this;

			instance.get(CONTENT).addClass(CSS_ZIPPY_CONTENT);
			instance.get(HEADER).addClass(CSS_ZIPPY_HEADER);
		},

		animate: function(config, fn) {
			var instance = this;

			instance._uiSetExpanded(true);

			var transition = A.merge(config, instance.get(TRANSITION));

			instance.get(CONTENT).transition(transition, A.bind(fn, instance));
		},

		collapse: function() {
			var instance = this;

			return instance.toggle(false);
		},

		expand: function() {
			var instance = this;

			return instance.toggle(true);
		},

		getContentHeight: function() {
			var instance = this;
			var content = instance.get(CONTENT);
			var expanded = instance.get(EXPANDED), height;

			if (!expanded) {
				instance._uiSetExpanded(true);
			}

			if (content.hasMethod(GET_BOUNDING_CLIENT_RECT)) {
				var preciseRegion = content.invoke(GET_BOUNDING_CLIENT_RECT);

				if (preciseRegion) {
					height = preciseRegion.bottom - preciseRegion.top;
				}
			}
			else {
				height = content.get(OFFSET_HEIGHT);
			}

			if (!expanded) {
				instance._uiSetExpanded(false);
			}

			return height;
		},

		toggle: function(expand) {
			var instance = this;

			if (isUndefined(expand)) {
				expand = !instance.get(EXPANDED);
			}

			if (instance.get(ANIMATED)) {
				if (instance.get(ANIMATING)) {
					return expand;
				}

				var content = instance.get(CONTENT);

				var height = instance.getContentHeight();
				var gutter = toNumber(content.getStyle(MARGIN_TOP));

				if (!instance.wrapped) {
					content.wrap(TPL_CONTENT_WRAPPER);

					if (expand) {
						gutter = -(height + gutter);

						content.setStyle(MARGIN_TOP, gutter);
					}

					instance.wrapped = true;
				}

				instance.set(ANIMATING, true);

				instance.animate(
					{
						marginTop: -(height + gutter) + PIXEL
					},
					function() {
						instance.set(ANIMATING, false);

						instance.set(EXPANDED, expand);
					}
				);
			}
			else {
				instance.set(EXPANDED, expand);
			}

			return expand;
		},

		_onExpandedChange: function(event) {
			var instance = this;

			instance._uiSetExpanded(event.newVal);
		},

		_uiSetExpanded: function(val) {
			var instance = this;

			instance.get(CONTENT).replaceClass(CSS_ZIPPY_CONTENT_STATE[!val], CSS_ZIPPY_CONTENT_STATE[val]);
			instance.get(HEADER).replaceClass(CSS_ZIPPY_HEADER_STATE[!val], CSS_ZIPPY_HEADER_STATE[val]);
		}

	}
});

A.Zippy = Zippy;<|endoftext|>