<commit_before>const path = require('path');
const resolve = pkg => path.join(__dirname, '../../packages', pkg, 'src');

const customLaunchers = {
  slChrome: {
    base: 'SauceLabs',
    browserName: 'chrome'
  },
  slIphone5: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '9.3'
  },
  slIpad: {
    base: 'SauceLabs',
    browserName: 'ipad',
    version: '10.3'
  },
  slIpad2: {
    base: 'SauceLabs',
    browserName: 'ipad',
    version: '11.2'
  },
  slIphone6: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '10.3'
  },
  slIphone7: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '11.2'
  },
  slSafari8: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.10'
  },
  slSafari9: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.11'
  },
  sl_mac_firfox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'OS X 10.12'
  },
  sl_safari: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.12',
    version: '11'
  },
  slIE10: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '10'
  },
  slIE11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '11'
  },
  slEdge13: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    version: '13',
    platform: 'Windows 10'
  },
  slEdge14: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    version: '14',
    platform: 'Windows 10'
  },
  slEdge15: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    version: '15',
    platform: 'Windows 10'
  },
  slEdge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10'
  },
  sl_mac_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'macOS 10.12'
  },
  slFirefox: {
    base: 'SauceLabs',
    browserName: 'firefox'
  },
  slAndroid5: {
    base: 'SauceLabs',
    browserName: 'android',
    version: '5.1'
  },
  slAndroid7: {
    base: 'SauceLabs',
    browserName: 'android',
    version: '6.0'
  }
};

module.exports = function(config) {
  config.set({
    basePath: '../../',

    frameworks: ['jasmine', 'jasmine-matchers'],

    files: [path.join(__dirname, '../../fixtures/browser/test.index.js')],

    preprocessors: {
      './fixtures/browser/test.index.js': ['webpack']
    },

    client: {
      jasmine: {
        random: false // Adding jasmine.random false disables test random order
      }
    },

    reporters: ['dots', 'saucelabs'],
    sauceLabs: {
      build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      startConnect: true,
      testName: `InfernoJS`,
      recordVideo: false,
      recordScreenshots: false,
      videoUploadOnPass: false,
      recordLogs: false,
      captureHtml: false,
      commandTimeout: 400
    },

    plugins: ['karma-jasmine', 'karma-jasmine-matchers', 'karma-webpack', 'karma-failed-reporter', 'karma-sauce-launcher'],

    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),

    captureTimeout: 600000,
    browserNoActivityTimeout: 600000,
    browserDisconnectTolerance: 2,

    browserConsoleLogOptions: {
      level: 'warn',
      terminal: false
    },
    colors: true,
    singleRun: true,
    autoWatch: false,
    concurrency: 1,

    webpackMiddleware: {
      stats: 'errors-only',
      noInfo: true
    },
    webpack: {
      mode: 'development',
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query: {
              presets: ['stage-2'],
              plugins: [
                'transform-decorators-legacy',
                ['babel-plugin-inferno', { imports: true }],
                'transform-class-properties',
                'transform-object-rest-spread',
                'babel-plugin-syntax-jsx',
                'transform-class-properties'
              ]
            }
          },
          {
            test: /\.tsx?$/,
            loader: 'ts-loader',
            options: {
              compilerOptions: {
                target: 'es5',
                module: 'commonjs',
                sourceMap: false
              }
            }
          }
        ]
      },
      resolve: {
        alias: {
          inferno: resolve('inferno'),
          'inferno-component': resolve('inferno-component'),
          'inferno-compat': resolve('inferno-compat'),
          'inferno-create-class': resolve('inferno-create-class'),
          'inferno-create-element': resolve('inferno-create-element'),
          'inferno-devtools': resolve('inferno-devtools'),
          'inferno-hyperscript': resolve('inferno-hyperscript'),
          'inferno-mobx': resolve('inferno-mobx'),
          'inferno-redux': resolve('inferno-redux'),
          'inferno-router': resolve('inferno-router'),
          'inferno-server': resolve('inferno-server'),
          'inferno-shared': resolve('inferno-shared'),
          'inferno-test-utils': resolve('inferno-test-utils'),
          'inferno-utils': resolve('inferno-utils'),
          'inferno-vnode-flags': resolve('inferno-vnode-flags'),
          'inferno-clone-vnode': resolve('inferno-clone-vnode'),
          mobx: path.join(__dirname, '../../node_modules/mobx/lib/mobx.module.js')
        },
        extensions: ['.js', '.jsx', '.ts'],
        mainFields: ['browser', 'main']
      },
      devServer: {
        noInfo: true
      },
      stats: 'errors-only',
      performance: {
        hints: false
      }
    }
  });
};
<commit_msg>Removed karma-failed-reporter from plugins<commit_after>const path = require('path');
const resolve = pkg => path.join(__dirname, '../../packages', pkg, 'src');

const customLaunchers = {
  slChrome: {
    base: 'SauceLabs',
    browserName: 'chrome'
  },
  slIphone5: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '9.3'
  },
  slIpad: {
    base: 'SauceLabs',
    browserName: 'ipad',
    version: '10.3'
  },
  slIpad2: {
    base: 'SauceLabs',
    browserName: 'ipad',
    version: '11.2'
  },
  slIphone6: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '10.3'
  },
  slIphone7: {
    base: 'SauceLabs',
    browserName: 'iphone',
    version: '11.2'
  },
  slSafari8: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.10'
  },
  slSafari9: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.11'
  },
  sl_mac_firfox: {
    base: 'SauceLabs',
    browserName: 'firefox',
    platform: 'OS X 10.12'
  },
  sl_safari: {
    base: 'SauceLabs',
    browserName: 'safari',
    platform: 'OS X 10.12',
    version: '11'
  },
  slIE10: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '10'
  },
  slIE11: {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    platform: 'Windows 7',
    version: '11'
  },
  slEdge13: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    version: '13',
    platform: 'Windows 10'
  },
  slEdge14: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    version: '14',
    platform: 'Windows 10'
  },
  slEdge15: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    version: '15',
    platform: 'Windows 10'
  },
  slEdge: {
    base: 'SauceLabs',
    browserName: 'MicrosoftEdge',
    platform: 'Windows 10'
  },
  sl_mac_chrome: {
    base: 'SauceLabs',
    browserName: 'chrome',
    platform: 'macOS 10.12'
  },
  slFirefox: {
    base: 'SauceLabs',
    browserName: 'firefox'
  },
  slAndroid5: {
    base: 'SauceLabs',
    browserName: 'android',
    version: '5.1'
  },
  slAndroid7: {
    base: 'SauceLabs',
    browserName: 'android',
    version: '6.0'
  }
};

module.exports = function(config) {
  config.set({
    basePath: '../../',

    frameworks: ['jasmine', 'jasmine-matchers'],

    files: [path.join(__dirname, '../../fixtures/browser/test.index.js')],

    preprocessors: {
      './fixtures/browser/test.index.js': ['webpack']
    },

    client: {
      jasmine: {
        random: false // Adding jasmine.random false disables test random order
      }
    },

    reporters: ['dots', 'saucelabs'],
    sauceLabs: {
      build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
      startConnect: true,
      testName: `InfernoJS`,
      recordVideo: false,
      recordScreenshots: false,
      videoUploadOnPass: false,
      recordLogs: false,
      captureHtml: false,
      commandTimeout: 400
    },

    plugins: ['karma-jasmine', 'karma-jasmine-matchers', 'karma-webpack', 'karma-sauce-launcher'],

    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),

    captureTimeout: 600000,
    browserNoActivityTimeout: 600000,
    browserDisconnectTolerance: 2,

    browserConsoleLogOptions: {
      level: 'warn',
      terminal: false
    },
    colors: true,
    singleRun: true,
    autoWatch: false,
    concurrency: 1,

    webpackMiddleware: {
      stats: 'errors-only',
      noInfo: true
    },
    webpack: {
      mode: 'development',
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
            query: {
              presets: ['stage-2'],
              plugins: [
                'transform-decorators-legacy',
                ['babel-plugin-inferno', { imports: true }],
                'transform-class-properties',
                'transform-object-rest-spread',
                'babel-plugin-syntax-jsx',
                'transform-class-properties'
              ]
            }
          },
          {
            test: /\.tsx?$/,
            loader: 'ts-loader',
            options: {
              compilerOptions: {
                target: 'es5',
                module: 'commonjs',
                sourceMap: false
              }
            }
          }
        ]
      },
      resolve: {
        alias: {
          inferno: resolve('inferno'),
          'inferno-component': resolve('inferno-component'),
          'inferno-compat': resolve('inferno-compat'),
          'inferno-create-class': resolve('inferno-create-class'),
          'inferno-create-element': resolve('inferno-create-element'),
          'inferno-devtools': resolve('inferno-devtools'),
          'inferno-hyperscript': resolve('inferno-hyperscript'),
          'inferno-mobx': resolve('inferno-mobx'),
          'inferno-redux': resolve('inferno-redux'),
          'inferno-router': resolve('inferno-router'),
          'inferno-server': resolve('inferno-server'),
          'inferno-shared': resolve('inferno-shared'),
          'inferno-test-utils': resolve('inferno-test-utils'),
          'inferno-utils': resolve('inferno-utils'),
          'inferno-vnode-flags': resolve('inferno-vnode-flags'),
          'inferno-clone-vnode': resolve('inferno-clone-vnode'),
          mobx: path.join(__dirname, '../../node_modules/mobx/lib/mobx.module.js')
        },
        extensions: ['.js', '.jsx', '.ts'],
        mainFields: ['browser', 'main']
      },
      devServer: {
        noInfo: true
      },
      stats: 'errors-only',
      performance: {
        hints: false
      }
    }
  });
};
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs-extra')
const axios = require('axios')
const fglob = require('fast-glob')
const cliProgress = require('cli-progress')
const randomMua = require('random-mua')
const argv = require('yargs').argv
const env = require('dotenv').config({
  path: path.join(__dirname, '../.env')
}).parsed

// download fixtures
// --delete remove all fixtures

if (argv.delete) {
  deletion()
} else {
  main().catch(console.log)
}

async function main() {
  const proxyConfig = env.PROXY_HOST
    ? {
        proxy: {
          host: env.PROXY_HOST,
          port: env.PROXY_PORT
        }
      }
    : {}
  if (env.PROXY_HOST) {
    console.log(`with proxy:${env.PROXY_HOST}:${env.PROXY_PORT}`)
  }

  const progressBars = new cliProgress.MultiBar({
    format: ' {bar} | "{file}" | {value}/{total} | {status}',
    hideCursor: true,
    barCompleteChar: '\u2588',
    barIncompleteChar: '\u2591',
    clearOnComplete: false,
    stopOnComplete: true
  })

  const errors = []

  let fixturesPath = await fglob(['**/fixtures.js'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyFiles: true
  })

  if (argv.fileMatchPattern) {
    const matcher = new RegExp(argv.fileMatchPattern)
    fixturesPath = fixturesPath.filter(filePath => matcher.test(filePath))
  }

  await Promise.all(fixturesPath.map(fetchDictFixtures))

  if (errors.length > 0) {
    await fs.outputFile(
      path.join(__dirname, 'fixtures.log'),
      errors.map(([name, error]) => name + '\n' + error).join('\n\n')
    )
    console.log(
      '\nErrors:\n\n',
      errors.map(([name, e, url]) => `${name}\n${url}\n`).join('\n')
    )
  }

  async function fetchDictFixtures(fixturePath) {
    const fixture = require(fixturePath)

    const fetched = []

    for (const index in fixture.files) {
      const [filename, fetchUrl] = fixture.files[index]

      const destPath = fixturePath.replace(
        /fixtures.js$/,
        `response/${filename}`
      )
      const stat = await fs.stat(destPath).catch(() => null)
      if (stat && stat.isFile()) {
        fetched.push(await fs.readFile(destPath, 'utf8'))
        continue
      }

      const dictname = /[\\/]+([^\\/]+)[\\/]+fixtures.js$/.exec(fixturePath)[1]

      const pgBar = progressBars.create(100, 0, {
        file: `${dictname}/fixture${index + 1}`,
        status: 'downloading'
      })

      try {
        var customConfig =
          typeof fetchUrl === 'string'
            ? {
                url: fetchUrl
              }
            : fetchUrl(fetched)
      } catch (e) {
        pgBar.update(null, { status: 'parse error' })
        pgBar.stop()
        continue
      }

      const { origin, host } = new URL(customConfig.url)

      if (!customConfig) {
        pgBar.update(null, { status: 'empty config' })
        pgBar.stop()
        continue
      }

      const axiosConfig = {
        transformResponse: [data => data],
        ...proxyConfig,
        ...customConfig,
        headers: {
          'user-agent': randomMua(),
          ...(customConfig.headers || {})
        }
      }

      try {
        const { data: result } = await axios(axiosConfig).catch(e =>
          e.response && e.response.status === 404 && e.response.data
            ? e.response
            : axios({
                ...axiosConfig,
                headers: {
                  ...axiosConfig.headers,
                  origin,
                  host,
                  referer: origin
                }
              })
        )

        fetched.push(result)
        await fs.outputFile(
          fixturePath.replace(/fixtures.js$/, `response/${filename}`),
          result
        )

        pgBar.update(100, { status: 'success' })
        pgBar.stop()
      } catch (e) {
        errors.push([`${dictname}/${filename}`, e, axiosConfig.url])

        pgBar.update(null, { status: 'failed' })
        pgBar.stop()
      }
    }
  }
}

async function deletion() {
  const fixturesPath = await fglob(['**/response'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyDirectories: true
  })

  fixturesPath.forEach(fixturePath => {
    fs.remove(fixturePath)
  })
}
<commit_msg>chore: fix index string to number<commit_after>const path = require('path')
const fs = require('fs-extra')
const axios = require('axios')
const fglob = require('fast-glob')
const cliProgress = require('cli-progress')
const randomMua = require('random-mua')
const argv = require('yargs').argv
const env = require('dotenv').config({
  path: path.join(__dirname, '../.env')
}).parsed

// download fixtures
// --delete remove all fixtures

if (argv.delete) {
  deletion()
} else {
  main().catch(console.log)
}

async function main() {
  const proxyConfig = env.PROXY_HOST
    ? {
        proxy: {
          host: env.PROXY_HOST,
          port: env.PROXY_PORT
        }
      }
    : {}
  if (env.PROXY_HOST) {
    console.log(`with proxy:${env.PROXY_HOST}:${env.PROXY_PORT}`)
  }

  const progressBars = new cliProgress.MultiBar({
    format: ' {bar} | "{file}" | {value}/{total} | {status}',
    hideCursor: true,
    barCompleteChar: '\u2588',
    barIncompleteChar: '\u2591',
    clearOnComplete: false,
    stopOnComplete: true
  })

  const errors = []

  let fixturesPath = await fglob(['**/fixtures.js'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyFiles: true
  })

  if (argv.fileMatchPattern) {
    const matcher = new RegExp(argv.fileMatchPattern)
    fixturesPath = fixturesPath.filter(filePath => matcher.test(filePath))
  }

  await Promise.all(fixturesPath.map(fetchDictFixtures))

  if (errors.length > 0) {
    await fs.outputFile(
      path.join(__dirname, 'fixtures.log'),
      errors.map(([name, error]) => name + '\n' + error).join('\n\n')
    )
    console.log(
      '\nErrors:\n\n',
      errors.map(([name, e, url]) => `${name}\n${url}\n`).join('\n')
    )
  }

  async function fetchDictFixtures(fixturePath) {
    const fixture = require(fixturePath)

    const fetched = []

    for (const index in fixture.files) {
      const [filename, fetchUrl] = fixture.files[index]

      const destPath = fixturePath.replace(
        /fixtures.js$/,
        `response/${filename}`
      )
      const stat = await fs.stat(destPath).catch(() => null)
      if (stat && stat.isFile()) {
        fetched.push(await fs.readFile(destPath, 'utf8'))
        continue
      }

      const dictname = /[\\/]+([^\\/]+)[\\/]+fixtures.js$/.exec(fixturePath)[1]

      const pgBar = progressBars.create(100, 0, {
        file: `${dictname}/fixture${index * 1 + 1}`,
        status: 'downloading'
      })

      try {
        var customConfig =
          typeof fetchUrl === 'string'
            ? {
                url: fetchUrl
              }
            : fetchUrl(fetched)
      } catch (e) {
        pgBar.update(null, { status: 'parse error' })
        pgBar.stop()
        continue
      }

      const { origin, host } = new URL(customConfig.url)

      if (!customConfig) {
        pgBar.update(null, { status: 'empty config' })
        pgBar.stop()
        continue
      }

      const axiosConfig = {
        transformResponse: [data => data],
        ...proxyConfig,
        ...customConfig,
        headers: {
          'user-agent': randomMua(),
          ...(customConfig.headers || {})
        }
      }

      try {
        const { data: result } = await axios(axiosConfig).catch(e =>
          e.response && e.response.status === 404 && e.response.data
            ? e.response
            : axios({
                ...axiosConfig,
                headers: {
                  ...axiosConfig.headers,
                  origin,
                  host,
                  referer: origin
                }
              })
        )

        fetched.push(result)
        await fs.outputFile(
          fixturePath.replace(/fixtures.js$/, `response/${filename}`),
          result
        )

        pgBar.update(100, { status: 'success' })
        pgBar.stop()
      } catch (e) {
        errors.push([`${dictname}/${filename}`, e, axiosConfig.url])

        pgBar.update(null, { status: 'failed' })
        pgBar.stop()
      }
    }
  }
}

async function deletion() {
  const fixturesPath = await fglob(['**/response'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyDirectories: true
  })

  fixturesPath.forEach(fixturePath => {
    fs.remove(fixturePath)
  })
}
<|endoftext|>


<commit_before>const {clipboard} = require('electron')

var str;

function processFlow() {

var obtained_text = "How cover details obtained - ";
var obtained = document.getElementById("HowObtained");

var underwriter_text = "Underwriter - ";
var underwriter = document.getElementById("carrier");

var scheme_text = "Scheme - ";
var scheme = document.getElementById("Scheme");

var sumsinsured_text = "Sums Insured (BUI & CON) - ";
var sumsinsured = document.getElementById("SIValues");

var adcover_text = "AD Cover - Y/N - ";
var adcover = document.getElementById("ADCover");

var personal_text = "Personal Belongings/Personal Possessions cover - ";
var personal = document.getElementById("PP-PB");

var specified_text = "Specified cover & items - ";
var specified = document.getElementById("SpecCover");

var unspecified_text = "Unspecified cover - ";
var unspecified = document.getElementById("UnspecCover");

var standardxs_text = "Standard excesses incl. EOW, etc. - ";
var standardxs = document.getElementById("StandardXS");

var voluntaryxs_text = "Voluntary excesses - ";
var voluntaryxs = document.getElementById("VolXS");

var renewal_text = "Inception/Renewal date - ";
var renewal = document.getElementById("IncRenew");

var history_text = "Previous claims - ";
var history = document.getElementById("PreviousClaims");

var endorsements_text = "Endorsements - ";
var endorsements = document.getElementById("Endorsements");

var jph_text = "Any joint policy holders (JPH) - ";
var jph = document.getElementById("JPHPresent");

if (underwriter.value == "Please select") {

	alert("Please select underwriter first!");

} else {

str = obtained_text + obtained.value + "\r\n\r\n" +
underwriter_text + underwriter.value + "\r\n" +
scheme_text + scheme.value + "\r\n\r\n" +
sumsinsured_text + sumsinsured.value + "\r\n" +
adcover_text + adcover.value + "\r\n" +
personal_text + personal.value + "\r\n" +
specified_text + specified.value + "\r\n" +
unspecified_text + unspecified.value + "\r\n" +
standardxs_text + standardxs.value + "\r\n" +
voluntaryxs_text + voluntaryxs.value + "\r\n" +
renewal_text + renewal.value + "\r\n\r\n" +
history_text + history.value + "\r\n" +
jph_text + jph.value + "\r\n" +
endorsements_text + endorsements.value;

// alert(str);

clipboard.writeText(str);

document.getElementById("copy-button").innerText = "Copied!";
document.getElementById("copy-button").className = "copy-button-slow";
	setTimeout(function(){
		document.getElementById("copy-button").style.color = "#3b5166"
		setTimeout(function(){
			document.getElementById("copy-button").className = "copy-button-fast"
			document.getElementById("copy-button").innerText = "Copy to Clipboard";
			document.getElementById("copy-button").style.color = "#FFFFFF";
		}, 700);
	}, 500);
};

};

<commit_msg>Added flexible textarea boxes and rewrote HTML<commit_after>const {clipboard} = require('electron')

var str;

function processFlow() {

var obtained_text = "How cover details obtained - ";
var obtained = document.getElementById("how-obtained");

var underwriter_text = "Underwriter - ";
var underwriter = document.getElementById("carrier");

var scheme_text = "Scheme - ";
var scheme = document.getElementById("scheme");

var bui_sumsinsured_text = "Buildings SI - ";
var bui_sumsinsured = document.getElementById("bui-si");

var con_sumsinsured_text = "Contents SI - ";
var con_sumsinsured = document.getElementById("con-si");

var bui_adcover_text = "Buildings AD - ";

if (document.getElementById("bui-ad-q").checked == true) {
	var bui_adcover = "Yes";
} else {
	var bui_adcover = "No";
};

var con_adcover_text = "Buildings AD - ";

if (document.getElementById("con-ad-q").checked == true) {
	var con_adcover = "Yes";
} else {
	var con_adcover = "No";
};

var personal_text = "Personal Belongings/Personal Possessions cover - ";
var personal = document.getElementById("pp-si");

var specified_text = "Specified cover & items - ";
var specified = document.getElementById("spec-si-items").value.replace(/\n\r?/g, "\r\n");

var unspecified_text = "Unspecified cover - ";
var unspecified = document.getElementById("unspec-si");

var standardxs_text = "Standard excesses incl. EOW, etc. - ";
var standardxs = document.getElementById("standard-xs");

var voluntaryxs_text = "Voluntary excesses - ";
var voluntaryxs = document.getElementById("voluntary-xs");

var renewal_text = "Inception/Renewal date - ";
var renewal = document.getElementById("inc-renewal");

var history_text = "Previous claims - ";
var history = document.getElementById("prev-claims").value.replace(/\n\r?/g, "\r\n");

var endorsements_text = "Endorsements - ";
var endorsements = document.getElementById("endorsements").value.replace(/\n\r?/g, "\r\n");

var jph_text = "Any joint policy holders (JPH) - ";
var jph = document.getElementById("jph").value.replace(/\n\r?/g, "\r\n");

if (underwriter.value == "Please select") {

	alert("Please select underwriter first!");

} else {

str = obtained_text + obtained.value + "\r\n\r\n" +
underwriter_text + underwriter.value + "\r\n" +
scheme_text + scheme.value + "\r\n\r\n" +
renewal_text + renewal.value + "\r\n" +
jph_text + jph + "\r\n\r\n" +
bui_sumsinsured_text + bui_sumsinsured.value + "\r\n" +
bui_adcover_text + bui_adcover + "\r\n" +
con_sumsinsured_text + con_sumsinsured.value + "\r\n" +
con_adcover_text + con_adcover + "\r\n" +
personal_text + personal.value + "\r\n" +
unspecified_text + unspecified.value + "\r\n" +
specified_text + specified + "\r\n\r\n" +
standardxs_text + standardxs.value + "\r\n" +
voluntaryxs_text + voluntaryxs.value + "\r\n\r\n" +
history_text + history + "\r\n" +
endorsements_text + endorsements;

// alert(str);

clipboard.writeText(str);

document.getElementById("copy-button").innerText = "Copied!";
document.getElementById("copy-button").className = "copy-button-slow";
	setTimeout(function(){
		document.getElementById("copy-button").style.color = "#3b5166"
		setTimeout(function(){
			document.getElementById("copy-button").className = "copy-button-fast"
			document.getElementById("copy-button").innerText = "Copy to Clipboard";
			document.getElementById("copy-button").style.color = "#FFFFFF";
		}, 700);
	}, 500);
};

};

<|endoftext|>


<commit_before>var assert = chai.assert;

describe('Clipboard', () => {
    describe('#constructor', () => {
        it('should throw an error since there was no arguments passed', done => {
            try {
                new Clipboard();
            }
            catch(e) {
                done();
            }
        });

        it('should throw an error since an empty selector has been passed', done => {
            try {
                new Clipboard('#abc');
            }
            catch(e) {
                done();
            }
        });

        it('should create a NodeList and store it in a property', () => {
            let clipboard = new Clipboard('.btn');
            return assert.instanceOf(clipboard.triggers, NodeList);
        });
    });
});
<commit_msg>Adds tests for Clipboard.validate<commit_after>var assert = chai.assert;

describe('Clipboard', () => {
    describe('#constructor', () => {
        it('should throw an error since there was no arguments passed', done => {
            try {
                new Clipboard();
            }
            catch(e) {
                done();
            }
        });

        it('should throw an error since an empty selector has been passed', done => {
            try {
                new Clipboard('#abc');
            }
            catch(e) {
                done();
            }
        });

        it('should create a NodeList and store it in a property', () => {
            let clipboard = new Clipboard('.btn');
            return assert.instanceOf(clipboard.triggers, NodeList);
        });
    });

    describe('#validate', () => {
        var elem = document.createElement('input');
        let clipboard = new Clipboard('.btn');

        it('should throw an error since there was no "data-target" or "data-text"', (done) => {
            try {
                clipboard.validate({
                    currentTarget: elem
                });
            }
            catch(e) {
                done();
            }
        });

        it('should throw an error since "data-action" is invalid', (done) => {
            try {
                elem.setAttribute('data-action', 'paste');

                clipboard.validate({
                    currentTarget: elem
                });
            }
            catch(e) {
                done();
            }
        });

        it('should throw an error since "data-target" do not match any element', (done) => {
            try {
                elem.setAttribute('data-target', 'xyz');

                clipboard.validate({
                    currentTarget: elem
                });
            }
            catch(e) {
                done();
            }
        });
    });
});
<|endoftext|>


<commit_before>const path = require('path')
const fs = require('fs-extra')
const axios = require('axios')
const SocksProxyAgent = require('socks-proxy-agent')
const fglob = require('fast-glob')
const cliProgress = require('cli-progress')
const randomMua = require('random-mua')
const argv = require('yargs').argv
const env = require('dotenv').config({
  path: path.join(__dirname, '../.env')
}).parsed

// download fixtures
// default only download non-existed files
// --delete remove all fixtures
// --update remove then download all fixtures
// --fileMatchPattern filter file path with regex

main().catch(console.log)

async function main() {
  if (argv.delete) {
    deletion()
  } else {
    if (argv.update) {
      await deletion()
    }
    add()
  }
}

async function add() {
  let proxyConfig = {}

  if (env.PROXY_HOST) {
    if (env.PROXY_PROTOCAL && env.PROXY_PROTOCAL.startsWith('socks')) {
      const httpsAgent = new SocksProxyAgent(
        `socks5://${env.PROXY_HOST}:${env.PROXY_PORT}`
      )
      proxyConfig = {
        httpsAgent,
        httpAgent: httpsAgent
      }
    } else {
      proxyConfig = {
        proxy: {
          host: env.PROXY_HOST,
          port: env.PROXY_PORT
        }
      }
    }
  }

  if (env.PROXY_HOST) {
    console.log(
      `with proxy: ${env.PROXY_PROTOCAL}://${env.PROXY_HOST}:${env.PROXY_PORT}`
    )
  }

  const progressBars = new cliProgress.MultiBar({
    format: ' {bar} | "{file}" | {value}/{total} | {status}',
    hideCursor: true,
    barCompleteChar: '\u2588',
    barIncompleteChar: '\u2591',
    clearOnComplete: false,
    stopOnComplete: true
  })

  const errors = []

  let fixturesPath = await fglob(['**/fixtures.js'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyFiles: true
  })

  if (argv.fileMatchPattern) {
    const matcher = new RegExp(argv.fileMatchPattern)
    fixturesPath = fixturesPath.filter(filePath => matcher.test(filePath))
  }

  await Promise.all(fixturesPath.map(fetchDictFixtures))

  if (errors.length > 0) {
    await fs.outputFile(
      path.join(__dirname, 'fixtures.log'),
      errors.map(([name, error]) => name + '\n' + error).join('\n\n')
    )
    console.log(
      '\nErrors:\n\n',
      errors.map(([name, e, url]) => `${name}\n${url}\n`).join('\n')
    )
  }

  async function fetchDictFixtures(fixturePath) {
    const fixture = require(fixturePath)

    const fetched = []

    for (const index in fixture.files) {
      const [filename, fetchUrl] = fixture.files[index]

      const destPath = fixturePath.replace(
        /fixtures.js$/,
        `response/${filename}`
      )
      const stat = await fs.stat(destPath).catch(() => null)
      if (stat && stat.isFile()) {
        fetched.push(await fs.readFile(destPath, 'utf8'))
        continue
      }

      const dictname = /[\\/]+([^\\/]+)[\\/]+fixtures.js$/.exec(fixturePath)[1]

      const pgBar = progressBars.create(100, 0, {
        file: `${dictname}/fixture${index * 1 + 1}`,
        status: 'downloading'
      })

      try {
        var customConfig =
          typeof fetchUrl === 'string'
            ? {
                url: fetchUrl
              }
            : fetchUrl(fetched)
      } catch (e) {
        pgBar.update(null, { status: 'parse error' })
        pgBar.stop()
        continue
      }

      const { origin, host } = new URL(customConfig.url)

      if (!customConfig) {
        pgBar.update(null, { status: 'empty config' })
        pgBar.stop()
        continue
      }

      const axiosConfig = {
        transformResponse: [data => data],
        ...proxyConfig,
        ...customConfig,
        headers: {
          'user-agent': randomMua(),
          ...(customConfig.headers || {})
        }
      }

      try {
        const { data: result } = await axios(axiosConfig).catch(e =>
          e.response && e.response.status === 404 && e.response.data
            ? e.response
            : axios({
                ...axiosConfig,
                headers: {
                  ...axiosConfig.headers,
                  origin,
                  host,
                  referer: origin
                }
              })
        )

        fetched.push(result)
        await fs.outputFile(
          fixturePath.replace(/fixtures.js$/, `response/${filename}`),
          result
        )

        pgBar.update(100, { status: 'success' })
        pgBar.stop()
      } catch (e) {
        errors.push([`${dictname}/${filename}`, e, axiosConfig.url])

        pgBar.update(null, { status: 'failed' })
        pgBar.stop()
      }
    }
  }
}

async function deletion() {
  let fixturesPath = await fglob(['**/response'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyDirectories: true
  })

  if (argv.fileMatchPattern) {
    const matcher = new RegExp(argv.fileMatchPattern)
    fixturesPath = fixturesPath.filter(filePath => matcher.test(filePath))
  }

  await Promise.all(fixturesPath.map(fixturePath => fs.remove(fixturePath)))
}
<commit_msg>fix(fixtures): read url of undefined<commit_after>const path = require('path')
const fs = require('fs-extra')
const axios = require('axios')
const SocksProxyAgent = require('socks-proxy-agent')
const fglob = require('fast-glob')
const cliProgress = require('cli-progress')
const randomMua = require('random-mua')
const argv = require('yargs').argv
const env = require('dotenv').config({
  path: path.join(__dirname, '../.env')
}).parsed

// download fixtures
// default only download non-existed files
// --delete remove all fixtures
// --update remove then download all fixtures
// --fileMatchPattern filter file path with regex

main().catch(console.log)

async function main() {
  if (argv.delete) {
    deletion()
  } else {
    if (argv.update) {
      await deletion()
    }
    add()
  }
}

async function add() {
  let proxyConfig = {}

  if (env.PROXY_HOST) {
    if (env.PROXY_PROTOCAL && env.PROXY_PROTOCAL.startsWith('socks')) {
      const httpsAgent = new SocksProxyAgent(
        `socks5://${env.PROXY_HOST}:${env.PROXY_PORT}`
      )
      proxyConfig = {
        httpsAgent,
        httpAgent: httpsAgent
      }
    } else {
      proxyConfig = {
        proxy: {
          host: env.PROXY_HOST,
          port: env.PROXY_PORT
        }
      }
    }
  }

  if (env.PROXY_HOST) {
    console.log(
      `with proxy: ${env.PROXY_PROTOCAL}://${env.PROXY_HOST}:${env.PROXY_PORT}`
    )
  }

  const progressBars = new cliProgress.MultiBar({
    format: ' {bar} | "{file}" | {value}/{total} | {status}',
    hideCursor: true,
    barCompleteChar: '\u2588',
    barIncompleteChar: '\u2591',
    clearOnComplete: false,
    stopOnComplete: true
  })

  const errors = []

  let fixturesPath = await fglob(['**/fixtures.js'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyFiles: true
  })

  if (argv.fileMatchPattern) {
    const matcher = new RegExp(argv.fileMatchPattern)
    fixturesPath = fixturesPath.filter(filePath => matcher.test(filePath))
  }

  await Promise.all(fixturesPath.map(fetchDictFixtures))

  if (errors.length > 0) {
    await fs.outputFile(
      path.join(__dirname, 'fixtures.log'),
      errors.map(([name, error]) => name + '\n' + error).join('\n\n')
    )
    console.log(
      '\nErrors:\n\n',
      errors.map(([name, e, url]) => `${name}\n${url}\n`).join('\n')
    )
  }

  async function fetchDictFixtures(fixturePath) {
    const fixture = require(fixturePath)

    const fetched = []

    for (const index in fixture.files) {
      const [filename, fetchUrl] = fixture.files[index]

      const destPath = fixturePath.replace(
        /fixtures.js$/,
        `response/${filename}`
      )
      const stat = await fs.stat(destPath).catch(() => null)
      if (stat && stat.isFile()) {
        fetched.push(await fs.readFile(destPath, 'utf8'))
        continue
      }

      const dictname = /[\\/]+([^\\/]+)[\\/]+fixtures.js$/.exec(fixturePath)[1]

      const pgBar = progressBars.create(100, 0, {
        file: `${dictname}/fixture${index * 1 + 1}`,
        status: 'downloading'
      })

      try {
        var customConfig =
          typeof fetchUrl === 'string'
            ? {
                url: fetchUrl
              }
            : fetchUrl(fetched)
      } catch (e) {
        pgBar.update(null, { status: 'parse error' })
        pgBar.stop()
        continue
      }

      if (!customConfig) {
        pgBar.update(null, { status: 'empty config' })
        pgBar.stop()
        continue
      }

      const { origin, host } = new URL(customConfig.url)
      const axiosConfig = {
        transformResponse: [data => data],
        ...proxyConfig,
        ...customConfig,
        headers: {
          'user-agent': randomMua(),
          ...(customConfig.headers || {})
        }
      }

      try {
        const { data: result } = await axios(axiosConfig).catch(e =>
          e.response && e.response.status === 404 && e.response.data
            ? e.response
            : axios({
                ...axiosConfig,
                headers: {
                  ...axiosConfig.headers,
                  origin,
                  host,
                  referer: origin
                }
              })
        )

        fetched.push(result)
        await fs.outputFile(
          fixturePath.replace(/fixtures.js$/, `response/${filename}`),
          result
        )

        pgBar.update(100, { status: 'success' })
        pgBar.stop()
      } catch (e) {
        errors.push([`${dictname}/${filename}`, e, axiosConfig.url])

        pgBar.update(null, { status: 'failed' })
        pgBar.stop()
      }
    }
  }
}

async function deletion() {
  let fixturesPath = await fglob(['**/response'], {
    cwd: path.join(__dirname, '../test'),
    absolute: true,
    onlyDirectories: true
  })

  if (argv.fileMatchPattern) {
    const matcher = new RegExp(argv.fileMatchPattern)
    fixturesPath = fixturesPath.filter(filePath => matcher.test(filePath))
  }

  await Promise.all(fixturesPath.map(fixturePath => fs.remove(fixturePath)))
}
<|endoftext|>


<commit_before>require.config({
	baseUrl: '../js',
	paths: {
		angular: '../lib/angular-1.2.7/angular',
		angularRoute: '../lib/angular-1.2.7/angular-route',
		transition: '../lib/transition',
		modal: '../lib/modal'
	},
	shim: {
		angular: {
			exports: 'angular'
		},

		angularRoute: {
			exports: 'angular',
			deps: ['angular']
		},

		transition: {
			exports: 'angular',
			deps: ['angular']
		},

		modal: {
			exports: 'angular',
			deps: ['angular', 'transition']
		},
	}
});

require(['angular', 'angularRoute', 'home/controllers/appCtl'], function(angular) {

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

	// http://docs.angularjs.org/api/angular.Module
	// http://docs.angularjs.org/guide/module
	// module的 config方法 用于在app Module跑起来之前对咱们的app
	// 做一些详细的设置
	//
	// 可以看到在config的时候也是支持依赖注入的
	// 但是并不是所有的东西在此时都是可以被注入的
	// 只有 providers 和 constants可以被注入 暂时记住就OK
	app
	.config([
		'$routeProvider',
		'$locationProvider',
		function($routeProvider, $locationProvider) {

			// 详见 http://docs.angularjs.org/guide/dev_guide.services.$location
			// 设置下 location以何种方式改变
			// 如果是以HTML5的新的history模式的话
			// 设置html5Mode(true)即可 针对于IE8 9 不支持这种方式
			// 但是我们不用担心 angualr已经帮助我们做好了兼容
			//
			// 如果当是以hash的方式更新location的话 需要设置下hashPrefix
			// 就是以什么样的前缀 展现 默认不设置的话 是空的''
			$locationProvider.html5Mode(true).hashPrefix('!');

			// http://docs.angularjs.org/api/ngRoute.$routeProvider
			// 配置下route路由 很好理解
			// route需要配合 ng-view 指令才能正常工作
			// 在html 可以看到咱们在bdy的元素的子元素div上指定了
			// ng-view指令
			// 默认当匹配到指定路由的时候
			// 就会把路由对应的模板内容插入到ng-view指令所在的
			// 元素里
			$routeProvider
			.when('/', {
				templateUrl: '../partials/index.html',
				controller: 'indexCtl'
			})
			.when('/:itemId', {
				templateUrl: '../partials/indexDetail.html',
				controller: 'indexDetailCtl'
			})
			.when('/index1', {
				templateUrl: '../partials/index1.html',
				controller: 'index1Ctl'
			})
			.when('/index2', {
				templateUrl: '../partials/index2.html',
				controller: 'index2Ctl'
			})
			.otherwise({
				redirectTo: '/index'
			});

		}
	])

	// 另外一个长用的方法就是run方法了，显而易见 就是
	// module已经完成了依赖注入等操作 在启动的过程中运行的
	// 同样的只有支持依赖注入 但是
	// 只有 instances(实例) 和 constants(常量) 可以被注入
	.run([
		// http://docs.angularjs.org/api/ng.$rootScope
		// 每一个app都会对应着一个唯一的rootScope
		'$rootScope',
		// http://docs.angularjs.org/api/ng.$location
		// angular已经封装好的location 提供了很多
		// 便捷的方法 还有 当locationchange的时候有事件
		'$location',
		function($rootScope, $location) {

			var parsePath = function(path) {
				$rootScope.subPath = path;
				return path.replace(/^(\/\w+?)(\/\w*)?$/, '$1')
			};

			$rootScope.path = parsePath($location.path());

			$rootScope.$on('$routeChangeSuccess', function(newVal) {
				$rootScope.path = parsePath($location.path());
			});

		}
	]);

	// 启动
	angular.element().ready(function(){
		angular.bootstrap(document, [app.name]);
	});

});
<commit_msg>Update main.js<commit_after>require.config({
	baseUrl: '../js',
	paths: {
		angular: '../lib/angular-1.2.7/angular',
		angularRoute: '../lib/angular-1.2.7/angular-route',
		transition: '../lib/transition',
		modal: '../lib/modal'
	},
	shim: {
		angular: {
			exports: 'angular'
		},

		angularRoute: {
			exports: 'angular',
			deps: ['angular']
		},

		transition: {
			exports: 'angular',
			deps: ['angular']
		},

		modal: {
			exports: 'angular',
			deps: ['angular', 'transition']
		},
	}
});

require(['angular', 'angularRoute', 'home/controllers/appCtl'], function(angular) {

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

	// http://docs.angularjs.org/api/angular.Module
	// http://docs.angularjs.org/guide/module
	// module的 config方法 用于在app Module跑起来之前对咱们的app
	// 做一些详细的设置
	//
	// 可以看到在config的时候也是支持依赖注入的
	// 但是并不是所有的东西在此时都是可以被注入的
	// 只有 providers 和 constants可以被注入 暂时记住就OK
	app
	.config([
		'$routeProvider',
		'$locationProvider',
		function($routeProvider, $locationProvider) {

			// 详见 http://docs.angularjs.org/guide/dev_guide.services.$location
			// 设置下 location以何种方式改变
			// 如果是以HTML5的新的history模式的话
			// 设置html5Mode(true)即可 针对于IE8 9 不支持这种方式
			// 但是我们不用担心 angualr已经帮助我们做好了兼容
			//
			// 如果当是以hash的方式更新location的话 需要设置下hashPrefix
			// 就是以什么样的前缀 展现 默认不设置的话 是空的''
			$locationProvider.html5Mode(true).hashPrefix('!');

			// http://docs.angularjs.org/api/ngRoute.$routeProvider
			// 配置下route路由 很好理解
			// route需要配合 ng-view 指令才能正常工作
			// 在html 可以看到咱们在bdy的元素的子元素div上指定了
			// ng-view指令
			// 默认当匹配到指定路由的时候
			// 就会把路由对应的模板内容插入到ng-view指令所在的
			// 元素里
			$routeProvider
			.when('/', {
				templateUrl: '../partials/index.html',
				controller: 'indexCtl'
			})
			.when('/:itemId', {
				templateUrl: '../partials/indexDetail.html',
				controller: 'indexDetailCtl'
			})
			.when('/index1', {
				templateUrl: '../partials/index1.html',
				controller: 'index1Ctl'
			})
			.when('/index2', {
				templateUrl: '../partials/index2.html',
				controller: 'index2Ctl'
			})
			.otherwise({
				redirectTo: '/'
			});

		}
	])

	// 另外一个长用的方法就是run方法了，显而易见 就是
	// module已经完成了依赖注入等操作 在启动的过程中运行的
	// 同样的只有支持依赖注入 但是
	// 只有 instances(实例) 和 constants(常量) 可以被注入
	.run([
		// http://docs.angularjs.org/api/ng.$rootScope
		// 每一个app都会对应着一个唯一的rootScope
		'$rootScope',
		// http://docs.angularjs.org/api/ng.$location
		// angular已经封装好的location 提供了很多
		// 便捷的方法 还有 当locationchange的时候有事件
		'$location',
		function($rootScope, $location) {

			var parsePath = function(path) {
				$rootScope.subPath = path;
				return path.replace(/^(\/\w+?)(\/\w*)?$/, '$1')
			};

			$rootScope.path = parsePath($location.path());

			$rootScope.$on('$routeChangeSuccess', function(newVal) {
				$rootScope.path = parsePath($location.path());
			});

		}
	]);

	// 启动
	angular.element().ready(function(){
		angular.bootstrap(document, [app.name]);
	});

});
<|endoftext|>


<commit_before>const async = require('async')
const fs = require('fs')
const later = require('later')
const path = require('path')

const getOrderedSchedules = (schedules) => {
  return Object.keys(schedules)
    .sort((a, b) => {
      let sched_a = later.parse.cron(schedules[a].crontab)
      let sched_b = later.parse.cron(schedules[b].crontab)
      schedules[a].prev = new Date(later.schedule(sched_a).prev().getTime())
      schedules[b].prev = new Date(later.schedule(sched_b).prev().getTime())
      return (
        schedules[b].prev < schedules[a].prev
        || (
          schedules[b].prev === schedules[a].prev
          && schedules[b].ordinal < schedules[a].ordinal
        )
      )
    })
    .map((a) => {
      console.log(schedules[a].prev)
      return schedules[a]
    })
}

const getNextSchedule = (schedules) => {
  let nextSchedule = schedules[Object.keys(schedules)[0]]
  console.log('Set next', nextSchedule)
  Object.keys(schedules).forEach((a) => {
    console.log('Test', schedules[a])
    let crtab = schedules[a].crontab
    let sched = later.parse.cron(crtab)
    let now = new Date()
    now.setSeconds(now.getSeconds() + 1)
    schedules[a].next = new Date(later.schedule(sched).next(1, now).getTime())
    if (schedules[a].next < nextSchedule.next
        || (nextSchedule.next === schedules[a].next && schedules[a].ordinal < nextSchedule.ordinal)) {
      nextSchedule = schedules[a]
      console.log('Next', nextSchedule)
    }
  })
  return nextSchedule
}

// const getNextEventDelayMs = (schedule) => {
//   let crtab = schedule.crontab
//   let sched = later.parse.cron(crtab)
//   let now = new Date()
//   console.log(later.schedule(sched).next(1, now).getTime())
// }

module.exports.render = (_G, configuration, mainCallback) => {
  document.body.style.cursor = 'none'
  if (_G.DEV_MODE) {
    document.body.style.cursor = 'crosshair'
  }
  while (document.getElementById('player').hasChildNodes()) {
    document.getElementById('player').removeChild(document.getElementById('player').lastChild)
  }
  let playerRootNode = document.createElement('div')
  playerRootNode.id = configuration.screenEid
  playerRootNode.className = 'screen'
  document.getElementById('player').appendChild(playerRootNode)

  playerRootNode.stopPlayback = function () {
    playerRootNode.playbackStatus = 'stopped'
    _G.playbackLog.write(new Date().toJSON() + ' Stop  all' + '\n')
    Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
  }

  let configurationNode = document.createElement('pre')
  configurationNode.className = 'configuration'
  configurationNode.innerHTML = JSON.stringify(configuration, null, 4)
  document.getElementById('player').appendChild(configurationNode)

  // Schedules->layouts
  async.forEachOf(configuration.schedules, (schedule, scheduleEid, callback) => {
    schedule.layoutNode = document.createElement('div')
    let layoutNode = schedule.layoutNode
    layoutNode.swConfiguration = configuration
    // layoutNode.swSchedule = schedule
    playerRootNode.appendChild(layoutNode)
    layoutNode.id = layoutNode.parentNode.id + '.' + schedule.layoutEid
    layoutNode.className = 'layout'
    layoutNode.getNextSchedule = getNextSchedule
    layoutNode.timers = []
    let later_sched = later.parse.cron(schedule.crontab)

    layoutNode.stopPlayback = function () {
      layoutNode.timers.forEach((timer) => {
        clearTimeout(timer)
      })
      layoutNode.playbackStatus = 'stopped'
      _G.playbackLog.write(new Date().toJSON() + ' Stop  layout ' + layoutNode.id + '\n')
      Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
    }

    layoutNode.startPlayback = function () { // this === layoutNode
      if (schedule.cleanup) {
        _G.playbackLog.write(new Date().toJSON() + ' Schedule ' + schedule.eid + ' requesting cleanup\n')
        playerRootNode.stopPlayback()
      } else {
        layoutNode.stopPlayback()
      }
      layoutNode.playbackStatus = 'started'
      let self = this
      ms_until_next_playback = new Date(later.schedule(later_sched).next(1, new Date).getTime())

      // Schedule next occurrance from crontab
      setTimeout(() => {
        self.startPlayback()
      }, ms_until_next_playback)

      // Schedule might have duration less than time left until next playback
      if (schedule.duration && schedule.duration * 1e3 < ms_until_next_playback) {
        let ms_passed = new Date() - new Date(later.schedule(later_sched).prev())
        let ms_left = schedule.duration * 1e3 - ms_passed
        ms_left = (ms_left < 10 ? 10 : ms_left)
        setTimeout(function () {
          self.stopPlayback()
        }, ms_left)
      }

      // Start layout playlists (delayed a bit to avoid simultaneous pause/play)
      layoutNode.timers.push(setTimeout(function () {
        Array.from(self.childNodes).forEach((a) => {
          a.startPlayback()
        })
      }, 10))
    }

    // Playlists
    async.forEachOf(schedule.layoutPlaylists, (playlist, layoutPlaylistEid, callback) => {
      playlist.playlistNode = document.createElement('div')
      let playlistNode = playlist.playlistNode
      // playlistNode.swPlaylist = playlist
      layoutNode.appendChild(playlistNode)
      playlistNode.id = playlistNode.parentNode.id + '.' + playlist.playlistEid
      playlistNode.className = 'playlist'
      if (playlist.inPixels) {
        playlistNode.style.top = (playlist.top / schedule.height * 100) + '%'
        playlistNode.style.left = (playlist.left / schedule.width * 100) + '%'
        playlistNode.style.width = (playlist.width / schedule.width * 100) + '%'
        playlistNode.style.height = (playlist.height / schedule.height * 100) + '%'
      }
      else {
        playlistNode.style.top = playlist.top + '%'
        playlistNode.style.left = playlist.left + '%'
        playlistNode.style.width = playlist.width + '%'
        playlistNode.style.height = playlist.height + '%'
      }

      playlistNode.stopPlayback = function () {
        playlistNode.playbackStatus = 'stopped'
        _G.playbackLog.write(new Date().toJSON() + ' Stop  playlist ' + playlistNode.id + '\n')
        Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
      }

      playlistNode.startPlayback = function () { // this === playlistNode
        playlistNode.playbackStatus = 'started'
        _G.playbackLog.write(new Date().toJSON() + ' Start playlist ' + playlistNode.id + '\n')
        this.firstChild.startPlayback()
      }

      // Medias
      let firstMediaNode
      let lastMediaNode
      async.forEachOf(playlist.playlistMedias, (swMedia, playlistMediaEid, callback) => {
        swMedia.mediaNode = document.createElement('div')
        let mediaNode = swMedia.mediaNode
        mediaNode.playlistNode = playlistNode
        mediaNode.swMedia = swMedia

        if (firstMediaNode === undefined) { firstMediaNode = mediaNode }
        if (lastMediaNode !== undefined) {
          lastMediaNode.nextMediaNode = mediaNode
        }
        lastMediaNode = mediaNode

        playlistNode.appendChild(mediaNode)
        mediaNode.id = mediaNode.parentNode.id + '.' + swMedia.mediaEid
        mediaNode.style.visibility = 'hidden'
        mediaNode.className = 'media'

        mediaNode.stopPlayback = function () {
          mediaNode.timers.forEach((timer) => {
            clearTimeout(timer)
          })
          mediaNode.playbackStatus = 'stopped'
          _G.playbackLog.write(new Date().toJSON() + ' Stop  media ' + mediaNode.id + '\n')
          mediaNode.style.visibility = 'hidden'
          this.firstChild.pause()
          this.firstChild.currentTime = 0
        }

        mediaNode.startPlayback = function () { // this === mediaNode
          if (mediaNode.playlistNode.playbackStatus === 'started') {
            mediaNode.playbackStatus = 'started'
            _G.playbackLog.write(new Date().toJSON() + ' Start media ' + mediaNode.id + '\n')
            mediaNode.style.visibility = 'visible'
            this.firstChild.currentTime = 0
            this.firstChild.play()
            if (swMedia.duration) {
              mediaNode.timers.push(setTimeout(function () {
                console.log('mediaNode.stopPlayback() from "media duration exceeded" event.')
                mediaNode.stopPlayback()
                mediaNode.timers.push(setTimeout(function () {
                  mediaNode.nextMediaNode.startPlayback()
                }, swMedia.delay * 1e3))
              }, swMedia.duration * 1e3))
            }
          }
        }
        insertMedia(_G, mediaNode, swMedia, callback)
      }, function (err) {
        if (playlist.loop !== false) {
          console.log('Set loop')
          lastMediaNode.nextMediaNode = firstMediaNode
        } else {
          console.log('Do not loop')
        }
        if (err) { console.error(err.message) }
        callback()
      })
    }, function (err) {
      if (err) { console.error(err.message) }
      callback()
    })
  }, function (err) {
    if (err) { console.error(err.message) }
    mainCallback(null, _G.codes.DOM_RENDERED)
    console.log(_G.codes.DOM_RENDERED)
    getOrderedSchedules(configuration.schedules)
      .forEach((a) => {
        a.layoutNode.startPlayback()
      })
  })
}

const insertMedia = (_G, mediaNode, swMedia, callback) => {
  // console.log('Insert media ' + swMedia.mediaEid + '(' + mediaNode.id + ').', swMedia.type)
  mediaNode.timers = []
  let mediaDomElement
  if (swMedia.type === _G.codes.MEDIA_TYPE_VIDEO) {
    mediaDomElement = document.createElement('VIDEO')
    let mimetype = 'video/' + swMedia.fileName.split('.')[swMedia.fileName.split('.').length - 1]
    mediaDomElement.type = mimetype
    // console.log(mimetype)
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaDomElement.overflow = 'hidden'
    mediaDomElement.autoplay = false
    mediaDomElement.controls = _G.DEV_MODE
    mediaDomElement.muted = swMedia.mute
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.video'
    mediaDomElement.addEventListener('durationchange', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' duration ' + mediaDomElement.duration + 'sec\n')
    })
    mediaDomElement.addEventListener('play', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' started\n')
    })
    mediaDomElement.addEventListener('ended', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' ended. Start delay ' + swMedia.delay * 1e3 + 'ms\n')
      // console.log('mediaNode.stopPlayback() from "video ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    return callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_AUDIO) {
    let mediaDomElement = document.createElement('AUDIO')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.audio'
    mediaDomElement.addEventListener('ended', () => {
      console.log('mediaNode.stopPlayback() from "audio ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    return callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_IMAGE) {
    let mediaDomElement = document.createElement('IMG')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.img'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {}
    mediaDomElement.pause = () => {}
    return callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_URL) {
    let mediaDomElement = document.createElement('IFRAME')
    mediaDomElement.src = swMedia.url
    mediaDomElement.scrolling = 'yes'
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.url'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {}
    mediaDomElement.pause = () => {}
    return callback()
  }
}
<commit_msg>hotfix<commit_after>const async = require('async')
const fs = require('fs')
const later = require('later')
const path = require('path')

const getOrderedSchedules = (schedules) => {
  return Object.keys(schedules)
    .sort((a, b) => {
      let sched_a = later.parse.cron(schedules[a].crontab)
      let sched_b = later.parse.cron(schedules[b].crontab)
      schedules[a].prev = new Date(later.schedule(sched_a).prev().getTime())
      schedules[b].prev = new Date(later.schedule(sched_b).prev().getTime())
      return (
        schedules[b].prev < schedules[a].prev
        || (
          schedules[b].prev === schedules[a].prev
          && schedules[b].ordinal < schedules[a].ordinal
        )
      )
    })
    .map((a) => {
      console.log(schedules[a].prev)
      return schedules[a]
    })
}

const getNextSchedule = (schedules) => {
  let nextSchedule = schedules[Object.keys(schedules)[0]]
  console.log('Set next', nextSchedule)
  Object.keys(schedules).forEach((a) => {
    console.log('Test', schedules[a])
    let crtab = schedules[a].crontab
    let sched = later.parse.cron(crtab)
    let now = new Date()
    now.setSeconds(now.getSeconds() + 1)
    schedules[a].next = new Date(later.schedule(sched).next(1, now).getTime())
    if (schedules[a].next < nextSchedule.next
        || (nextSchedule.next === schedules[a].next && schedules[a].ordinal < nextSchedule.ordinal)) {
      nextSchedule = schedules[a]
      console.log('Next', nextSchedule)
    }
  })
  return nextSchedule
}

// const getNextEventDelayMs = (schedule) => {
//   let crtab = schedule.crontab
//   let sched = later.parse.cron(crtab)
//   let now = new Date()
//   console.log(later.schedule(sched).next(1, now).getTime())
// }

module.exports.render = (_G, configuration, mainCallback) => {
  document.body.style.cursor = 'none'
  if (_G.DEV_MODE) {
    document.body.style.cursor = 'crosshair'
  }
  while (document.getElementById('player').hasChildNodes()) {
    document.getElementById('player').removeChild(document.getElementById('player').lastChild)
  }
  let playerRootNode = document.createElement('div')
  playerRootNode.id = configuration.screenEid
  playerRootNode.className = 'screen'
  document.getElementById('player').appendChild(playerRootNode)

  playerRootNode.stopPlayback = function () {
    playerRootNode.playbackStatus = 'stopped'
    _G.playbackLog.write(new Date().toJSON() + ' Stop  all' + '\n')
    Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
  }

  let configurationNode = document.createElement('pre')
  configurationNode.className = 'configuration'
  configurationNode.innerHTML = JSON.stringify(configuration, null, 4)
  document.getElementById('player').appendChild(configurationNode)

  // Schedules->layouts
  async.forEachOf(configuration.schedules, (schedule, scheduleEid, callback) => {
    schedule.layoutNode = document.createElement('div')
    let layoutNode = schedule.layoutNode
    layoutNode.swConfiguration = configuration
    // layoutNode.swSchedule = schedule
    playerRootNode.appendChild(layoutNode)
    layoutNode.id = layoutNode.parentNode.id + '.' + schedule.layoutEid
    layoutNode.className = 'layout'
    layoutNode.getNextSchedule = getNextSchedule
    layoutNode.timers = []
    let later_sched = later.parse.cron(schedule.crontab)

    layoutNode.stopPlayback = function () {
      layoutNode.timers.forEach((timer) => {
        clearTimeout(timer)
      })
      layoutNode.playbackStatus = 'stopped'
      _G.playbackLog.write(new Date().toJSON() + ' Stop  layout ' + layoutNode.id + '\n')
      Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
    }

    layoutNode.startPlayback = function () { // this === layoutNode
      if (schedule.cleanup) {
        _G.playbackLog.write(new Date().toJSON() + ' Schedule ' + schedule.eid + ' requesting cleanup\n')
        playerRootNode.stopPlayback()
      } else {
        layoutNode.stopPlayback()
      }
      layoutNode.playbackStatus = 'started'
      let self = this
      ms_until_next_playback = new Date(later.schedule(later_sched).next()) - new Date()

      // Schedule next occurrance from crontab
      setTimeout(() => {
        self.startPlayback()
      }, ms_until_next_playback)

      // Schedule might have duration less than time left until next playback
      if (schedule.duration && schedule.duration * 1e3 < ms_until_next_playback) {
        let ms_passed = new Date() - new Date(later.schedule(later_sched).prev())
        let ms_left = schedule.duration * 1e3 - ms_passed
        ms_left = (ms_left < 10 ? 10 : ms_left)
        setTimeout(function () {
          self.stopPlayback()
        }, ms_left)
      }

      // Start layout playlists (delayed a bit to avoid simultaneous pause/play)
      layoutNode.timers.push(setTimeout(function () {
        Array.from(self.childNodes).forEach((a) => {
          a.startPlayback()
        })
      }, 10))
    }

    // Playlists
    async.forEachOf(schedule.layoutPlaylists, (playlist, layoutPlaylistEid, callback) => {
      playlist.playlistNode = document.createElement('div')
      let playlistNode = playlist.playlistNode
      // playlistNode.swPlaylist = playlist
      layoutNode.appendChild(playlistNode)
      playlistNode.id = playlistNode.parentNode.id + '.' + playlist.playlistEid
      playlistNode.className = 'playlist'
      if (playlist.inPixels) {
        playlistNode.style.top = (playlist.top / schedule.height * 100) + '%'
        playlistNode.style.left = (playlist.left / schedule.width * 100) + '%'
        playlistNode.style.width = (playlist.width / schedule.width * 100) + '%'
        playlistNode.style.height = (playlist.height / schedule.height * 100) + '%'
      }
      else {
        playlistNode.style.top = playlist.top + '%'
        playlistNode.style.left = playlist.left + '%'
        playlistNode.style.width = playlist.width + '%'
        playlistNode.style.height = playlist.height + '%'
      }

      playlistNode.stopPlayback = function () {
        playlistNode.playbackStatus = 'stopped'
        _G.playbackLog.write(new Date().toJSON() + ' Stop  playlist ' + playlistNode.id + '\n')
        Array.from(this.childNodes).forEach((a) => { a.stopPlayback() })
      }

      playlistNode.startPlayback = function () { // this === playlistNode
        playlistNode.playbackStatus = 'started'
        _G.playbackLog.write(new Date().toJSON() + ' Start playlist ' + playlistNode.id + '\n')
        this.firstChild.startPlayback()
      }

      // Medias
      let firstMediaNode
      let lastMediaNode
      async.forEachOf(playlist.playlistMedias, (swMedia, playlistMediaEid, callback) => {
        swMedia.mediaNode = document.createElement('div')
        let mediaNode = swMedia.mediaNode
        mediaNode.playlistNode = playlistNode
        mediaNode.swMedia = swMedia

        if (firstMediaNode === undefined) { firstMediaNode = mediaNode }
        if (lastMediaNode !== undefined) {
          lastMediaNode.nextMediaNode = mediaNode
        }
        lastMediaNode = mediaNode

        playlistNode.appendChild(mediaNode)
        mediaNode.id = mediaNode.parentNode.id + '.' + swMedia.mediaEid
        mediaNode.style.visibility = 'hidden'
        mediaNode.className = 'media'

        mediaNode.stopPlayback = function () {
          mediaNode.timers.forEach((timer) => {
            clearTimeout(timer)
          })
          mediaNode.playbackStatus = 'stopped'
          _G.playbackLog.write(new Date().toJSON() + ' Stop  media ' + mediaNode.id + '\n')
          mediaNode.style.visibility = 'hidden'
          this.firstChild.pause()
          this.firstChild.currentTime = 0
        }

        mediaNode.startPlayback = function () { // this === mediaNode
          if (mediaNode.playlistNode.playbackStatus === 'started') {
            mediaNode.playbackStatus = 'started'
            _G.playbackLog.write(new Date().toJSON() + ' Start media ' + mediaNode.id + '\n')
            mediaNode.style.visibility = 'visible'
            this.firstChild.currentTime = 0
            this.firstChild.play()
            if (swMedia.duration) {
              mediaNode.timers.push(setTimeout(function () {
                console.log('mediaNode.stopPlayback() from "media duration exceeded" event.')
                mediaNode.stopPlayback()
                mediaNode.timers.push(setTimeout(function () {
                  mediaNode.nextMediaNode.startPlayback()
                }, swMedia.delay * 1e3))
              }, swMedia.duration * 1e3))
            }
          }
        }
        insertMedia(_G, mediaNode, swMedia, callback)
      }, function (err) {
        if (playlist.loop !== false) {
          console.log('Set loop')
          lastMediaNode.nextMediaNode = firstMediaNode
        } else {
          console.log('Do not loop')
        }
        if (err) { console.error(err.message) }
        callback()
      })
    }, function (err) {
      if (err) { console.error(err.message) }
      callback()
    })
  }, function (err) {
    if (err) { console.error(err.message) }
    mainCallback(null, _G.codes.DOM_RENDERED)
    console.log(_G.codes.DOM_RENDERED)
    getOrderedSchedules(configuration.schedules)
      .forEach((a) => {
        a.layoutNode.startPlayback()
      })
  })
}

const insertMedia = (_G, mediaNode, swMedia, callback) => {
  // console.log('Insert media ' + swMedia.mediaEid + '(' + mediaNode.id + ').', swMedia.type)
  mediaNode.timers = []
  let mediaDomElement
  if (swMedia.type === _G.codes.MEDIA_TYPE_VIDEO) {
    mediaDomElement = document.createElement('VIDEO')
    let mimetype = 'video/' + swMedia.fileName.split('.')[swMedia.fileName.split('.').length - 1]
    mediaDomElement.type = mimetype
    // console.log(mimetype)
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaDomElement.overflow = 'hidden'
    mediaDomElement.autoplay = false
    mediaDomElement.controls = _G.DEV_MODE
    mediaDomElement.muted = swMedia.mute
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.video'
    mediaDomElement.addEventListener('durationchange', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' duration ' + mediaDomElement.duration + 'sec\n')
    })
    mediaDomElement.addEventListener('play', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' started\n')
    })
    mediaDomElement.addEventListener('ended', () => {
      _G.playbackLog.write(new Date().toJSON() + ' Video media ' + mediaNode.id + ' ended. Start delay ' + swMedia.delay * 1e3 + 'ms\n')
      // console.log('mediaNode.stopPlayback() from "video ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    return callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_AUDIO) {
    let mediaDomElement = document.createElement('AUDIO')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.audio'
    mediaDomElement.addEventListener('ended', () => {
      console.log('mediaNode.stopPlayback() from "audio ended" event.')
      mediaNode.stopPlayback()
      mediaNode.timers.push(setTimeout(function () {
        mediaNode.nextMediaNode.startPlayback()
      }, swMedia.delay * 1e3))
    })
    return callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_IMAGE) {
    let mediaDomElement = document.createElement('IMG')
    mediaDomElement.src = path.resolve(_G.MEDIA_DIR, swMedia.mediaEid.toString())
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.img'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {}
    mediaDomElement.pause = () => {}
    return callback()
  }
  else if (swMedia.type === _G.codes.MEDIA_TYPE_URL) {
    let mediaDomElement = document.createElement('IFRAME')
    mediaDomElement.src = swMedia.url
    mediaDomElement.scrolling = 'yes'
    mediaNode.appendChild(mediaDomElement)
    mediaDomElement.id = mediaNode.id + '.url'
    // Properties and methods not present natively
    // mediaDomElement.currentTime = 0
    mediaDomElement.play = () => {}
    mediaDomElement.pause = () => {}
    return callback()
  }
}
<|endoftext|>


<commit_before>define(
    [
        'text!app/templates/app.html'
    ],
    function(template) {
        var AppView = Backbone.View.extend({
            id: 'main',
            tagName: 'div',
            className: 'container-fluid',
            el: 'body',
            template: _.template(template),

            events: {
            },

            initialize: function() {
            },

            render: function() {
                this.$el.html(this.template());
                return this;
            }
        });

        return AppView;
    }
);
<commit_msg>remove app.js, not sure if this will break something<commit_after><|endoftext|>


<commit_before>'use strict';

var countries  = require('..').countries;
var currencies = require('..').currencies;
var languages  = require('..').languages;
var  assert = require('assert');
var _ = require('underscore');

describe('countries', function () {

  describe('all', function () {
    it('should be array', function () {
      assert( _.isArray(countries.all) );
    });
  });

  describe('alpha2', function () {
    it('should find USA', function () {
      assert.equal( countries.BE.name, 'Belgium');
      assert.equal( countries.US.name, 'United States');
    });
  });

  describe('alpha3', function () {
    it('should find France', function () {
      assert.equal( countries.FRA.name, 'France');
      assert.deepEqual( countries.FRA.currencies, ['EUR']);
    });
  });

  describe('check all countries have a status', function () {
    _.each( countries.all, function (country) {
      it(country, function () {
        assert( country.status );
      });
    });
  });

  describe('check currencies for each country', function () {
    _.each( countries.all, function (country) {
      describe(country.alpha2, function () {
        _.each( country.currencies, function (currency) {
          it(currency, function () {
            assert( currencies[currency] );
          });
        });
      });
    });
  });

  describe('check specific country currencies', function () {
    it('Latvian currency should be EUR', function () {
      assert.deepEqual( countries.LV.currencies, ['EUR']);
    });
  });

  describe('check languages for each country', function () {
    _.each( countries.all, function (country) {
      describe(country.alpha2, function () {
        _.each( country.languages, function (language) {
          it(language, function () {
            assert( languages[language] );
          });
        });
      });
    });
  });
});
<commit_msg>Refactor tests so we can add more<commit_after>'use strict';

var countries  = require('..').countries;
var currencies = require('..').currencies;
var languages  = require('..').languages;
var  assert = require('assert');
var _ = require('underscore');

describe('countries', function () {

  describe('all', function () {
    it('should be array', function () {
      assert( _.isArray(countries.all) );
    });
  });

  describe('alpha2', function () {
    it('should find USA', function () {
      assert.equal( countries.BE.name, 'Belgium');
      assert.equal( countries.US.name, 'United States');
    });
  });

  describe('alpha3', function () {
    it('should find France', function () {
      assert.equal( countries.FRA.name, 'France');
      assert.deepEqual( countries.FRA.currencies, ['EUR']);
    });
  });

  describe('check each country has correct form', function () {
    _.each( countries.all, function (country) {
      describe(country, function () {
        it('should have a status', function () {
          assert( country.status );
        });

      });
    });
  });

  describe('check currencies for each country', function () {
    _.each( countries.all, function (country) {
      describe(country.alpha2, function () {
        _.each( country.currencies, function (currency) {
          it(currency, function () {
            assert( currencies[currency] );
          });
        });
      });
    });
  });

  describe('check specific country currencies', function () {
    it('Latvian currency should be EUR', function () {
      assert.deepEqual( countries.LV.currencies, ['EUR']);
    });
  });

  describe('check languages for each country', function () {
    _.each( countries.all, function (country) {
      describe(country.alpha2, function () {
        _.each( country.languages, function (language) {
          it(language, function () {
            assert( languages[language] );
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @module storjshare-gui/fslogs
 */

'use strict';

var fs = require('fs');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

/**
 * Creates a logger and bind to view
 * @constructor
 */
function FsLogger(logfolder, prefix) {
  if (!(this instanceof FsLogger)) {
    return new FsLogger(logfolder, prefix);
  }

  //need to set defaults
  this._loglevel = 3;
  this._logfolder = (logfolder !== null && logfolder !== undefined) ? logfolder
    : require('os').tmpdir();

  this._prefix = (prefix !== null && prefix !== undefined) ? prefix + '_' : '';
  this._logfile = this._useExistingFile();

  assert(fs.existsSync(this._logfolder), 'Invalid Log Folder');

  // Create log if no log exists
  if (!(this._doesFileExist(this._logfile))) {
    this._newfile(this._logfolder);
  }

  EventEmitter.call(this);

}

inherits(FsLogger, EventEmitter);

/**
 * Determine the path of the latest log file used today
 * #_useExistingFile
 * @return {String} Returns path to last existing log file for today
 */
FsLogger.prototype._useExistingFile = function() {

  var today = this._builddate();
  var logname = this._logfolder + '/' + this._prefix + today;
  var filetype = '.log';
  var counter = 0;
  var log = logname + filetype;
  var lastExistingLog = '';

  var check = this._doesFileExist(log);

  while (check === true) {
    counter++;
    lastExistingLog = log;
    log = logname + '-(' + counter + ')' + filetype;
    check = this._doesFileExist(log);
  }

  return lastExistingLog;
};

/**
 * Create new Log File
 * #_newfile
 * @return {Boolean} Returns true if success
 */
FsLogger.prototype._newfile = function() {

  var today = this._builddate();
  var logname = this._logfolder + '/' + this._prefix + today;
  var filetype = '.log';
  var counter = 0;
  var log = logname + filetype;

  var check = this._doesFileExist(log);

  while (check === true) {
    counter++;
    log = logname + '-(' + counter + ')' + filetype;
    check = this._doesFileExist(log);
  }

  fs.writeFileSync(log, '['+new Date().getTime()+'] Log file created.');
  this._logfile = log;

  return true;
};

/**
 * Check if file exists
 * #_builddate
 * @return {String} String of date in the format of 1337-06-66
 */
FsLogger.prototype._builddate = function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();
  return year + '-' + month + '-' + day;
};

/**
 * Check if file exists
 * #_newfile
 * @param {String} log - full path of log file
 * @return {Boolean} True if file exists; false if not.
 */
FsLogger.prototype._doesFileExist = function(log) {
  try {
    fs.statSync(log);
  } catch(err) {
    return !(err && err.code === 'ENOENT');
  }

  if (!log.includes(this._builddate)) {
    return false;
  }

  return true;
};

/**
 * Log trace Mesage
 * #trace
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.trace = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 5) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log debug Mesage
 * #debug
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.debug = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 4) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log info Mesage
 * #info
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.info = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 3) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log warn Mesage
 * #warn
 * @param {String} message - Message to be logged
 */
FsLogger.prototype.warn = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 2) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log error Mesage
 * #error
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.error = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 1) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Emit error event with fs functions fail
 * #_bubbleError
 * @param {String} err - Message to be emitted
 * @return {Void}
 */
FsLogger.prototype._bubbleError = function(err) {
  if (err) {
    this.emit('error', err);
  }
};

/**
 * Check log level settings
 * #_checkLogLevel
 * @return {Number} Return current log level setting
 */
FsLogger.prototype._checkLogLevel = function() {
  return this._loglevel;
};

/**
 * Set log level settings
 * #_setLogLevel
 * @param {Number} loglevel
 */
FsLogger.prototype.setLogLevel = function(loglevel) {
  this._loglevel = loglevel;
};

/**
 * Log error Message
 * #log
 * @param {String} type - error, warn, info, debug, trace
 * @param {String} timestamp - Time of log
 * @param {String} message - Message to be logged
 */
FsLogger.prototype.log = function(type, timestamp, message) {

  var log = '\n{' + type + '} [' + timestamp + '] ' + message;

  switch(type) {
    case 'info':
      this.info(log);
      break;
    case 'warn':
      this.warn(log);
      break;
    case 'error':
      this.error(log);
      break;
    case 'debug':
      this.debug(log);
      break;
    case 'trace':
      this.trace(log);
      break;
    default:
      this.info(log);
  }
};

module.exports = FsLogger;
<commit_msg>Fix log saving bug<commit_after>/**
 * @module storjshare-gui/fslogs
 */

'use strict';

var fs = require('fs');
var assert = require('assert');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

/**
 * Creates a logger and bind to view
 * @constructor
 */
function FsLogger(logfolder, prefix) {
  if (!(this instanceof FsLogger)) {
    return new FsLogger(logfolder, prefix);
  }

  //need to set defaults
  this._loglevel = 3;
  this._logfolder = (logfolder !== null && logfolder !== undefined) ? logfolder
    : require('os').tmpdir();

  this._prefix = (prefix !== null && prefix !== undefined) ? prefix + '_' : '';
  this._logfile = this._useExistingFile();

  assert(fs.existsSync(this._logfolder), 'Invalid Log Folder');

  // Create log if no log exists
  if (!(this._doesFileExist(this._logfile))) {
    this._newfile(this._logfolder);
  }

  EventEmitter.call(this);

}

inherits(FsLogger, EventEmitter);

/**
 * Determine the path of the latest log file used today
 * #_useExistingFile
 * @return {String} Returns path to last existing log file for today
 */
FsLogger.prototype._useExistingFile = function() {

  var today = this._builddate();
  var logname = this._logfolder + '/' + this._prefix + today;
  var filetype = '.log';
  var counter = 0;
  var log = logname + filetype;
  var lastExistingLog = '';

  var check = this._doesFileExist(log);

  while (check === true) {
    counter++;
    lastExistingLog = log;
    log = logname + '-(' + counter + ')' + filetype;
    check = this._doesFileExist(log);
  }

  return lastExistingLog;
};

/**
 * Create new Log File
 * #_newfile
 * @return {Boolean} Returns true if success
 */
FsLogger.prototype._newfile = function() {

  var today = this._builddate();
  var logname = this._logfolder + '/' + this._prefix + today;
  var filetype = '.log';
  var counter = 0;
  var log = logname + filetype;

  var check = this._doesFileExist(log);

  while (check === true) {
    counter++;
    log = logname + '-(' + counter + ')' + filetype;
    check = this._doesFileExist(log);
  }

  fs.writeFileSync(log, '['+new Date().getTime()+'] Log file created.');
  this._logfile = log;

  return true;
};

/**
 * Check if file exists
 * #_builddate
 * @return {String} String of date in the format of 1337-06-66
 */
FsLogger.prototype._builddate = function() {
  var dateObj = new Date();
  var month = dateObj.getUTCMonth() + 1; //months from 1-12
  var day = dateObj.getUTCDate();
  var year = dateObj.getUTCFullYear();
  return year + '-' + month + '-' + day;
};

/**
 * Check if file exists
 * #_newfile
 * @param {String} log - full path of log file
 * @return {Boolean} True if file exists; false if not.
 */
FsLogger.prototype._doesFileExist = function(log) {
  try {
    fs.statSync(log);
  } catch(err) {
    return !(err && err.code === 'ENOENT');
  }

  if (log.indexOf(this._builddate()) === -1) {
    return false;
  }

  return true;
};

/**
 * Log trace Mesage
 * #trace
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.trace = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 5) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log debug Mesage
 * #debug
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.debug = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 4) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log info Mesage
 * #info
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.info = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 3) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log warn Mesage
 * #warn
 * @param {String} message - Message to be logged
 */
FsLogger.prototype.warn = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 2) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Log error Mesage
 * #error
 * @param {String} message - Message to be logged
 * @return {Void}
 */
FsLogger.prototype.error = function(message) {
  if (!(this._doesFileExist(this._logfile))){
    this._newfile();
  }
  if (this._checkLogLevel() >= 1) {
    fs.appendFile(this._logfile, message, this._bubbleError.bind(this));
  }
};

/**
 * Emit error event with fs functions fail
 * #_bubbleError
 * @param {String} err - Message to be emitted
 * @return {Void}
 */
FsLogger.prototype._bubbleError = function(err) {
  if (err) {
    this.emit('error', err);
  }
};

/**
 * Check log level settings
 * #_checkLogLevel
 * @return {Number} Return current log level setting
 */
FsLogger.prototype._checkLogLevel = function() {
  return this._loglevel;
};

/**
 * Set log level settings
 * #_setLogLevel
 * @param {Number} loglevel
 */
FsLogger.prototype.setLogLevel = function(loglevel) {
  this._loglevel = loglevel;
};

/**
 * Log error Message
 * #log
 * @param {String} type - error, warn, info, debug, trace
 * @param {String} timestamp - Time of log
 * @param {String} message - Message to be logged
 */
FsLogger.prototype.log = function(type, timestamp, message) {

  var log = '\n{' + type + '} [' + timestamp + '] ' + message;

  switch(type) {
    case 'info':
      this.info(log);
      break;
    case 'warn':
      this.warn(log);
      break;
    case 'error':
      this.error(log);
      break;
    case 'debug':
      this.debug(log);
      break;
    case 'trace':
      this.trace(log);
      break;
    default:
      this.info(log);
  }
};

module.exports = FsLogger;
<|endoftext|>


<commit_before>/*
 * periodicjs
 * http://github.com/typesettin/periodic
 *
 * Copyright (c) 2014 Yaw Joseph Etse. All rights reserved.
 */

'use strict';

/**
 * A module that represents a periodic app.
 * @{@link https://github.com/typesettin/periodic}
 * @author Yaw Joseph Etse
 * @copyright Copyright (c) 2014 Typesettin. All rights reserved.
 * @license MIT
 * @module periodic
 * @requires express
 * @requires path
 * @requires body-parser
 * @requires cookie-parser
 * @requires serve-favicon
 * @requires express-session
 * @requires silkscreenjs
 * @requires codemirror
 * @requires less
 * @requires filesaver.js
 * @requires jszip
 * @requires ejs
 * @requires path
 * @requires util
 * @todo to do later
 */
var express = require('express'),
	path = require('path'),
	fs = require('fs'),
	bodyParser = require('body-parser'),
	multer = require('multer'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	favicon = require('serve-favicon'),
	session = require('express-session'),
	responseTime = require('response-time'),
	compress = require('compression'),
	flash = require('connect-flash'),
	csrf = require('csurf'),
	ejs = require('ejs'),
	app = express(),
	MongoStore = require('connect-mongo')(session),
	expressAppLogger = require('morgan'),
	appLog = require('../../content/config/logger'),
	config = require('./config'),
	appconfig,
	logger,
	database = require('../../content/config/database'),
	db,
	dburl,
	mngse;
//https://github.com/expressjs/timeout
//https://github.com/expressjs/vhost

var init = {
	useLogger : function(){
		logger = new appLog(app.get('env'));
		process.on('uncaughtException',function(err){
			logger.error(err.message);
		});
	},
	loadConfiguration : function(){
		appconfig = new config();
		if(appconfig.settings().debug){
			console.log(appconfig.settings());
		}
		app.set('port',appconfig.settings().application.port);
		app.set('env',appconfig.settings().application.environment);
		if(appconfig.settings().theme){
			appconfig.setSetting('themepath',path.join(__dirname,'../../content/themes',appconfig.settings().theme));
		}
		db = database[app.get('env')];
		dburl = db.url;
		mngse =  db.mongoose;
	},
	viewSettings : function(){
		app.set('view engine', 'ejs');
		app.set('views', path.resolve(__dirname,'../views'));
		app.engine('html', require('ejs').renderFile);
		app.engine('ejs', require('ejs').renderFile);
	},
	expressSettings : function(){
		app.use(responseTime(5));
		app.use(flash());
		app.use(bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads/files' }));
		// app.get(bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads/files' }));
		// app.use(multer({dest: __dirname + '/public/uploads/files' }));
		app.use(methodOverride());
		app.use(cookieParser(appconfig.settings().cookies.cookieParser));
		app.use(favicon( path.resolve(__dirname,'../../public/favicon.ico') ) );
	},
	staticCaching : function(){
		var expressStaticOptions = (app.get('env') !== 'production') ? {} : {maxAge: 86400000};
		app.use(express.static(path.resolve(__dirname,'../../public'),expressStaticOptions));
	},
	pageCompression : function(){
		if(appconfig.settings().expressCompression){
			app.use(compress());
		}
	},
	appLogging : function(){
		if(appconfig.settings().debug){
			expressAppLogger.token('colorstatus', function(req, res){
				var color = 32; // green
				var status = res.statusCode;

				if (status >= 500) {color = 31;} // red
				else if (status >= 400) {color = 33;} // yellow
				else if (status >= 300) {color = 36;} // cyan
				return '\x1b[' + color + 'm'+status+'\x1b[90m';
			});
			expressAppLogger.format('app','\x1b[90m:remote-addr :method \x1b[37m:url\x1b[90m :colorstatus \x1b[97m:response-time ms\x1b[90m :date :referrer :user-agent\x1b[0m' );
			app.use(expressAppLogger({format:"app"}));
		}
	},
	useSessions: function(){
		if(appconfig.settings().sessions.enabled){
			var express_session_config = {};
			if(appconfig.settings().sessions.type==="mongo"){
				express_session_config = {
					secret:'hjoiuu87go9hui',
					maxAge: new Date(Date.now() + 3600000),
					store: new MongoStore({url:database[app.get('env')].url},function(err){
						console.log("error in mongostore:",err);
					})
				};
			}
			else{
				express_session_config = {
					secret:'hjoiuu87go9hui',
					maxAge: new Date(Date.now() + 3600000)
				};
			}

			app.use(session(express_session_config));
			if(appconfig.settings().crsf){
				app.use(csrf());
			}
		}
	},
	useLocals : function(){
		app.locals = require('./staticviewhelper');
		if(appconfig.settings().crsf){
			app.use(function(req,res,next){
				app.locals.token = req.csrfToken();
				next();
			});
		}
		else{
			app.use(function(req,res,next){
				app.locals.token = '';
				next();
			});
		}
		app.use(function(req,res,next){
			app.locals.isLoggedIn = function(){
				return req.user;
			};
			next();
		});
	},
	applicationRouting : function(){
		var periodicObj = {express:express,app:app,logger:logger,settings:appconfig.settings(),db:db,mongoose:mngse};
		require('../routes/index')(periodicObj);
	},
	serverStatus: function(){
		logger.info('Express server listening on port ' + app.get('port'));
		logger.info('Running in environment: '+app.get('env'));
	},
	catchErrors : function(){
		//log errors
		app.use(function (err, req, res, next){
			logger.error(err.message);
			logger.error(err.stack);
			next(err);
		});

		//send client errors
		//catch all errors
		app.use(function (err,req, res, next) {
			if (req.xhr) {
				res.send(500, { error: 'Something blew up!' });
			}
			else {
				res.status(500);
				res.render('home/error500', { message: err.message,error: err });
			}
		});

	},
};

console.time('Server Starting');
init.loadConfiguration();
init.useLogger();
init.viewSettings();
init.expressSettings();
init.staticCaching();
init.pageCompression();
init.appLogging();
init.useSessions();
init.useLocals();
init.applicationRouting();
init.serverStatus();
init.catchErrors();
console.timeEnd('Server Starting');

module.exports.app = app;
module.exports.port = app.get('port');<commit_msg>cleaning up mongo errors<commit_after>/*
 * periodicjs
 * http://github.com/typesettin/periodic
 *
 * Copyright (c) 2014 Yaw Joseph Etse. All rights reserved.
 */

'use strict';

/**
 * A module that represents a periodic app.
 * @{@link https://github.com/typesettin/periodic}
 * @author Yaw Joseph Etse
 * @copyright Copyright (c) 2014 Typesettin. All rights reserved.
 * @license MIT
 * @module periodic
 * @requires express
 * @requires path
 * @requires body-parser
 * @requires cookie-parser
 * @requires serve-favicon
 * @requires express-session
 * @requires silkscreenjs
 * @requires codemirror
 * @requires less
 * @requires filesaver.js
 * @requires jszip
 * @requires ejs
 * @requires path
 * @requires util
 * @todo to do later
 */
var express = require('express'),
	path = require('path'),
	fs = require('fs'),
	bodyParser = require('body-parser'),
	multer = require('multer'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	favicon = require('serve-favicon'),
	session = require('express-session'),
	responseTime = require('response-time'),
	compress = require('compression'),
	flash = require('connect-flash'),
	csrf = require('csurf'),
	ejs = require('ejs'),
	app = express(),
	MongoStore = require('connect-mongo')(session),
	expressAppLogger = require('morgan'),
	appLog = require('../../content/config/logger'),
	config = require('./config'),
	appconfig,
	logger,
	database = require('../../content/config/database'),
	db,
	dburl,
	mngse;
//https://github.com/expressjs/timeout
//https://github.com/expressjs/vhost

var init = {
	useLogger : function(){
		logger = new appLog(app.get('env'));
		process.on('uncaughtException',function(err){
			logger.error(err.message);
		});
	},
	loadConfiguration : function(){
		appconfig = new config();
		if(appconfig.settings().debug){
			console.log(appconfig.settings());
		}
		app.set('port',appconfig.settings().application.port);
		app.set('env',appconfig.settings().application.environment);
		if(appconfig.settings().theme){
			appconfig.setSetting('themepath',path.join(__dirname,'../../content/themes',appconfig.settings().theme));
		}
		db = database[app.get('env')];
		dburl = db.url;
		mngse =  db.mongoose;
	},
	viewSettings : function(){
		app.set('view engine', 'ejs');
		app.set('views', path.resolve(__dirname,'../views'));
		app.engine('html', require('ejs').renderFile);
		app.engine('ejs', require('ejs').renderFile);
	},
	expressSettings : function(){
		app.use(responseTime(5));
		app.use(flash());
		app.use(bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads/files' }));
		// app.get(bodyParser({ keepExtensions: true, uploadDir: __dirname + '/public/uploads/files' }));
		// app.use(multer({dest: __dirname + '/public/uploads/files' }));
		app.use(methodOverride());
		app.use(cookieParser(appconfig.settings().cookies.cookieParser));
		app.use(favicon( path.resolve(__dirname,'../../public/favicon.ico') ) );
	},
	staticCaching : function(){
		var expressStaticOptions = (app.get('env') !== 'production') ? {} : {maxAge: 86400000};
		app.use(express.static(path.resolve(__dirname,'../../public'),expressStaticOptions));
	},
	pageCompression : function(){
		if(appconfig.settings().expressCompression){
			app.use(compress());
		}
	},
	appLogging : function(){
		if(appconfig.settings().debug){
			expressAppLogger.token('colorstatus', function(req, res){
				var color = 32; // green
				var status = res.statusCode;

				if (status >= 500) {color = 31;} // red
				else if (status >= 400) {color = 33;} // yellow
				else if (status >= 300) {color = 36;} // cyan
				return '\x1b[' + color + 'm'+status+'\x1b[90m';
			});
			expressAppLogger.format('app','\x1b[90m:remote-addr :method \x1b[37m:url\x1b[90m :colorstatus \x1b[97m:response-time ms\x1b[90m :date :referrer :user-agent\x1b[0m' );
			app.use(expressAppLogger({format:"app"}));
		}
	},
	useSessions: function(){
		if(appconfig.settings().sessions.enabled){
			var express_session_config = {};
			if(appconfig.settings().sessions.type==="mongo"){
				express_session_config = {
					secret:'hjoiuu87go9hui',
					maxAge: new Date(Date.now() + 3600000),
					store: new MongoStore({url:database[app.get('env')].url})
				};
			}
			else{
				express_session_config = {
					secret:'hjoiuu87go9hui',
					maxAge: new Date(Date.now() + 3600000)
				};
			}

			app.use(session(express_session_config));
			if(appconfig.settings().crsf){
				app.use(csrf());
			}
		}
	},
	useLocals : function(){
		app.locals = require('./staticviewhelper');
		if(appconfig.settings().crsf){
			app.use(function(req,res,next){
				app.locals.token = req.csrfToken();
				next();
			});
		}
		else{
			app.use(function(req,res,next){
				app.locals.token = '';
				next();
			});
		}
		app.use(function(req,res,next){
			app.locals.isLoggedIn = function(){
				return req.user;
			};
			next();
		});
	},
	applicationRouting : function(){
		var periodicObj = {express:express,app:app,logger:logger,settings:appconfig.settings(),db:db,mongoose:mngse};
		require('../routes/index')(periodicObj);
	},
	serverStatus: function(){
		logger.info('Express server listening on port ' + app.get('port'));
		logger.info('Running in environment: '+app.get('env'));
	},
	catchErrors : function(){
		//log errors
		app.use(function (err, req, res, next){
			logger.error(err.message);
			logger.error(err.stack);
			next(err);
		});

		//send client errors
		//catch all errors
		app.use(function (err,req, res, next) {
			if (req.xhr) {
				res.send(500, { error: 'Something blew up!' });
			}
			else {
				res.status(500);
				res.render('home/error500', { message: err.message,error: err });
			}
		});
	},
};

console.time('Server Starting');
init.loadConfiguration();
init.useLogger();
init.viewSettings();
init.expressSettings();
init.staticCaching();
init.pageCompression();
init.appLogging();
init.useSessions();
init.useLocals();
init.applicationRouting();
init.serverStatus();
init.catchErrors();
console.timeEnd('Server Starting');

module.exports.app = app;
module.exports.port = app.get('port');<|endoftext|>