<commit_before>var fs = require('fs')

var config = {};

//set defaults
config.clientId = '2574228432.104777884963';
config.port = 3004;
config.axosoftClientId = '4b62de06-1f39-41f7-ae38-37ec5262478a'

var prefix = process.env.BUILD_LIFECYCLE;

if (prefix == 'production') {
    prefix = '';
}

config.redirectUri = prefix + 'slackbot.axosoft.com:3004';
config.mongoUri = 'mongodb://' + prefix + 'slackbot.axosoft.com:27017/slackData'

if (process.env.AXO_slackbot_secret && process.env.AXO_slackbot_axosoft_secret) {
console.log('updating config file...')
    config.clientSecret = process.env.AXO_slackbot_secret;
    config.axosoftClientSecret = process.env.AXO_slackbot_axosoft_secret;
}

// write to file
console.log(config);
fs.writeFileSync('./config.json', JSON.stringify(config));<commit_msg>log proccess.env<commit_after>var fs = require('fs')

var config = {};

//set defaults
config.clientId = '2574228432.104777884963';
config.port = 3004;
config.axosoftClientId = '4b62de06-1f39-41f7-ae38-37ec5262478a'

var prefix = process.env.BUILD_LIFECYCLE;

if (prefix == 'production') {
    prefix = '';
}

config.redirectUri = prefix + 'slackbot.axosoft.com:3004';
config.mongoUri = 'mongodb://' + prefix + 'slackbot.axosoft.com:27017/slackData'

// test for process.env
console.log(process.env);

if (process.env.AXO_slackbot_secret && process.env.AXO_slackbot_axosoft_secret) {
console.log('updating config file...')
    config.clientSecret = process.env.AXO_slackbot_secret;
    config.axosoftClientSecret = process.env.AXO_slackbot_axosoft_secret;
}

// write to file
console.log(config);
fs.writeFileSync('./config.json', JSON.stringify(config));<|endoftext|>


<commit_before>const b = require('substance-bundler')
const fs = require('fs')
const path = require('path')
const fork = require('substance-bundler/extensions/fork')
const vfs = require('substance-bundler/extensions/vfs')

const DIST = 'dist/'
const APPDIST = 'app-dist/'
const TMP = 'tmp/'
const RNG_SEARCH_DIRS = [
  path.join(__dirname, 'src', 'article')
]

const RNG_FILES = [
  'src/article/JATS-archiving.rng',
  'src/article/TextureArticle.rng'
]

// Server configuration

const port = 4000 // TODO: make this configurable
b.setServerPort(port)
b.yargs.option('d', {
  type: 'string',
  alias: 'rootDir',
  describe: 'Root directory of served archives'
})
let argv = b.yargs.argv
if (argv.d) {
  const darServer = require('dar-server')
  const rootDir = argv.d
  const archiveDir = path.resolve(path.join(__dirname, rootDir))
  darServer.serve(b.server, {
    port,
    serverUrl: 'http://localhost:' + port,
    rootDir: archiveDir,
    apiUrl: '/archives'
  })
}
b.serve({ static: true, route: '/', folder: './dist' })

// Make Targets

b.task('clean', function () {
  b.rm(DIST)
  b.rm(TMP)
  b.rm(APPDIST)
}).describe('removes all generated files and folders.')

b.task('lib', ['clean', 'build:schema', 'build:assets', 'build:lib'])
  .describe('builds the library bundle.')

b.task('browser', ['clean', 'build:schema', 'build:assets', 'build:browser'])
  .describe('builds the browser bundle.')

b.task('publish', ['clean', 'build:schema', 'build:assets', 'build:lib', 'build:web'])
  .describe('builds the release bundle (library + web).')

b.task('web', ['clean', 'build:schema', 'build:assets', 'build:browser', 'build:web'])
  .describe('builds the web bundle (browser + web).')

b.task('app', ['clean', 'build:schema', 'build:assets', 'build:browser', 'build:app'])
  .describe('builds the app bundle (electron app).')

b.task('test-nodejs', ['clean', 'build:schema', 'build:test-assets'])
  .describe('prepares everything necessary to run tests in node.')

b.task('test-browser', ['clean', 'build:schema', 'build:browser', 'build:test-assets', 'build:test-browser'])
  .describe('builds the test-suite for the browser.')

// an alias because in all our other projects it is named this way
b.task('test:browser', ['test-browser'])

b.task('default', ['publish'])
  .describe('default: publish')

// spawns electron after build is ready
b.task('run-app', ['app'], () => {
  // Note: `await=false` is important, as otherwise bundler would await this to finish
  fork(b, require.resolve('electron/cli.js'), '.', { verbose: true, cwd: APPDIST, await: false })
})
  .describe('runs the application in electron.')

// low-level make targets

b.task('schema:single-jats-file', _singleJATSFile)

b.task('schema:jats', () => {
  _compileSchema('JATS-archiving', RNG_FILES[0], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 1))
})

b.task('schema:dar-article', () => {
  _compileSchema('TextureArticle', RNG_FILES[1], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 2))
})

b.task('schema:dar-manifest', () => {
  _compileSchema('Manifest', 'src/dar/Manifest.rng', [path.join(__dirname, 'src', 'dar')], [])
})

b.task('schema:texture-article', () => {
})

b.task('schema:debug', () => {
  _compileSchema('JATS-archiving', RNG_FILES[0], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 1), { debug: true })
  _compileSchema('TextureArticle', RNG_FILES[1], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 2), { debug: true })
})

b.task('build:assets', function () {
  b.copy('./node_modules/font-awesome', DIST + 'font-awesome')
  b.copy('./node_modules/inter-ui', DIST + 'inter-ui')
  b.copy('./node_modules/katex/dist', DIST + 'katex')
  b.copy('./node_modules/substance/dist', DIST + 'substance/dist')
  b.css('texture.css', DIST + 'texture.css')
  b.css('texture-reset.css', DIST + 'texture-reset.css')
})

b.task('build:schema', ['schema:jats', 'schema:dar-article', 'schema:texture-article', 'schema:dar-manifest'])

b.task('build:browser', () => {
  _buildLib(DIST, 'browser')
})

b.task('build:nodejs', () => {
  _buildLib(DIST, 'nodejs')
})

b.task('build:lib', () => {
  _buildLib(DIST, 'all')
})

b.task('build:cover', () => {
  _buildLib(TMP, 'cover')
})

b.task('build:app', () => {
  b.copy('app/index.html', APPDIST)
  b.copy('app/build-resources', APPDIST)
  b.copy('data', APPDIST)
  // FIXME: this command leads to an extra run when a  file is updated
  // .. instead copying the files explicitly for now
  // b.copy('dist', APPDIST+'lib/')
  b.copy('dist/font-awesome', APPDIST + 'lib/')
  b.copy('dist/katex', APPDIST + 'lib/')
  b.copy('dist/substance', APPDIST + 'lib/')
  ;[
    'texture.js',
    'texture.css',
    'texture-pagestyle.css',
    'texture-reset.css'
  ].forEach(f => {
    b.copy(`dist/${f}`, APPDIST + 'lib/')
    b.copy(`dist/${f}.map`, APPDIST + 'lib/')
  })

  // TODO: maybe we could come up with an extension
  // that expands a source file using a given dict.
  b.custom('Creating application package.json...', {
    src: 'app/package.json.in',
    dest: APPDIST + 'package.json',
    execute () {
      let { version } = require('./package.json')
      let tpl = fs.readFileSync('app/package.json.in', 'utf8')
      let out = tpl.replace('${version}', version) // eslint-disable-line no-template-curly-in-string
      fs.writeFileSync(APPDIST + 'package.json', out)
    }
  })
  b.js('app/main.js', {
    output: [{
      file: APPDIST + 'main.js',
      format: 'cjs'
    }],
    external: ['electron', 'path', 'url']
  })
  b.js('app/app.js', {
    output: [{
      file: APPDIST + 'app.js',
      format: 'umd',
      name: 'textureApp',
      globals: {
        'substance': 'substance',
        'substance-texture': 'texture',
        'katex': 'katex'
      }
    }],
    external: [ 'substance', 'substance-texture', 'katex' ]
  })
  // execute 'install-app-deps'
  fork(b, require.resolve('electron-builder/out/cli/cli.js'), 'install-app-deps', { verbose: true, cwd: APPDIST, await: true })
})

b.task('build:vfs', () => {
  vfs(b, {
    src: ['./data/**/*'],
    dest: DIST + 'vfs.js',
    format: 'umd',
    moduleName: 'vfs',
    rootDir: path.join(__dirname, 'data')
  })
})

b.task('build:web', ['build:vfs'], () => {
  b.copy('web/index.html', DIST)
  b.copy('web/reader.html', DIST)
  b.js('./web/editor.js', {
    output: [{
      file: DIST + 'editor.js',
      format: 'umd',
      name: 'textureEditor',
      globals: {
        'substance': 'substance',
        'substance-texture': 'texture',
        'katex': 'katex'
      }
    }],
    external: ['substance', 'substance-texture', 'katex']
  })
  b.js('./web/reader.js', {
    output: [{
      file: DIST + 'reader.js',
      format: 'umd',
      name: 'textureReader',
      globals: {
        'substance': 'substance',
        'substance-texture': 'texture',
        'katex': 'katex'
      }
    }],
    external: ['substance', 'substance-texture', 'katex']
  })
  b.copy('./data', DIST + 'data')
})

b.task('build:test-assets', ['build:vfs'], () => {
  vfs(b, {
    src: ['./test/fixture/**/*.xml'],
    dest: DIST + 'test/test-vfs.js',
    format: 'umd',
    moduleName: 'TEST_VFS',
    rootDir: path.join(__dirname, 'test', 'fixture')
  })
})

b.task('build:test-browser', ['build:assets', 'build:test-assets'], () => {
  b.copy('test/index.html', 'dist/test/index.html')
  b.copy('node_modules/substance-test/dist/testsuite.js', 'dist/test/testsuite.js')
  b.copy('node_modules/substance-test/dist/test.css', 'dist/test/test.css')

  // NOTE: by declaring texture/index.js as external we manage to serve both environments, browser and nodejs
  // with the same code.
  // In the browser, texture is used via the regular texture bundle, in nodejs it is resolved in the regular way
  const INDEX_JS = path.join(__dirname, 'index.js')
  const TEST_VFS = path.join(__dirname, 'tmp', 'test-vfs.js')
  let globals = {
    'substance': 'substance',
    'substance-test': 'substanceTest',
    'katex': 'katex',
    // TODO: this should be done in the same way as INDEX_JS and TEST_VFS
    'vfs': 'vfs'
  }
  globals[INDEX_JS] = 'texture'
  globals[TEST_VFS] = 'testVfs'

  b.js('test/index.js', {
    output: [{
      file: 'dist/test/tests.js',
      format: 'umd',
      name: 'tests',
      globals
    }],
    external: [
      'substance',
      'substance-test',
      INDEX_JS,
      'katex',
      'vfs',
      TEST_VFS
    ]
  })
})

/* HELPERS */

function _buildLib (DEST, platform) {
  let targets = []
  let istanbul
  if (platform === 'browser' || platform === 'all') {
    targets.push({
      file: DEST + 'texture.js',
      format: 'umd',
      name: 'texture',
      sourcemapRoot: __dirname,
      sourcemapPrefix: 'texture',
      globals: {
        'substance': 'substance',
        'katex': 'katex',
        'vfs': 'vfs'
      }
    })
  }
  if (platform === 'nodejs' || platform === 'all') {
    targets.push({
      file: DEST + 'texture.cjs.js',
      format: 'cjs'
    })
  }
  if (platform === 'es' || platform === 'all') {
    targets.push({
      file: DEST + 'texture.es.js',
      format: 'es'
    })
  }
  b.js('./index.js', {
    output: targets,
    external: ['substance', 'katex', 'vfs'],
    istanbul
  })
}

function _compileSchema (name, src, searchDirs, deps, options = {}) {
  const DEST = `tmp/${name}.data.js`
  const ISSUES = `tmp/${name}.issues.txt`
  const SCHEMA = `tmp/${name}.schema.md`
  const entry = path.basename(src)
  b.custom(`Compiling schema '${name}'...`, {
    src: [src].concat(deps),
    dest: DEST,
    execute () {
      const { compileRNG, checkSchema } = require('substance')
      const xmlSchema = compileRNG(fs, searchDirs, entry)
      b.writeFileSync(DEST, `export default ${JSON.stringify(xmlSchema)}`)
      b.writeFileSync(SCHEMA, xmlSchema.toMD())
      if (options.debug) {
        const issues = checkSchema(xmlSchema)
        const issuesData = [`${issues.length} issues:`, ''].concat(issues).join('\n')
        b.writeFileSync(ISSUES, issuesData)
      }
    }
  })
}

// we used this internally just to get a single-file version of
// the offficial JATS 1.1 rng data set
function _singleJATSFile () {
  [{
    RNG_DIR: 'data/jats/archiving',
    ENTRY: 'JATS-archive-oasis-article1-mathml3.rng',
    DEST: 'src/article/JATS-archiving.rng'
  }].forEach(({ RNG_DIR, ENTRY, DEST }) => {
    b.custom(`Pulling JATS spec into a single file...`, {
      src: [RNG_DIR + '/*.rng'],
      dest: DEST,
      execute () {
        const { loadRNG } = require('substance')
        let rng = loadRNG(fs, [RNG_DIR], ENTRY)
        // sort definitions by name
        let grammar = rng.find('grammar')
        let others = []
        let defines = []
        grammar.getChildren().forEach((child) => {
          if (child.tagName === 'define') {
            defines.push(child)
          } else {
            others.push(child)
          }
        })
        defines.sort((a, b) => {
          const aname = a.getAttribute('name').toLowerCase()
          const bname = b.getAttribute('name').toLowerCase()
          if (aname < bname) return -1
          if (bname < aname) return 1
          return 0
        })
        grammar.empty()
        defines.concat(others).forEach((el) => {
          grammar.appendChild('\n  ')
          grammar.appendChild(el)
        })
        let xml = rng.serialize()
        b.writeFileSync(DEST, xml)
      }
    })
  })
}
<commit_msg>Remove texture-pagestyle.css from build script.<commit_after>const b = require('substance-bundler')
const fs = require('fs')
const path = require('path')
const fork = require('substance-bundler/extensions/fork')
const vfs = require('substance-bundler/extensions/vfs')

const DIST = 'dist/'
const APPDIST = 'app-dist/'
const TMP = 'tmp/'
const RNG_SEARCH_DIRS = [
  path.join(__dirname, 'src', 'article')
]

const RNG_FILES = [
  'src/article/JATS-archiving.rng',
  'src/article/TextureArticle.rng'
]

// Server configuration

const port = 4000 // TODO: make this configurable
b.setServerPort(port)
b.yargs.option('d', {
  type: 'string',
  alias: 'rootDir',
  describe: 'Root directory of served archives'
})
let argv = b.yargs.argv
if (argv.d) {
  const darServer = require('dar-server')
  const rootDir = argv.d
  const archiveDir = path.resolve(path.join(__dirname, rootDir))
  darServer.serve(b.server, {
    port,
    serverUrl: 'http://localhost:' + port,
    rootDir: archiveDir,
    apiUrl: '/archives'
  })
}
b.serve({ static: true, route: '/', folder: './dist' })

// Make Targets

b.task('clean', function () {
  b.rm(DIST)
  b.rm(TMP)
  b.rm(APPDIST)
}).describe('removes all generated files and folders.')

b.task('lib', ['clean', 'build:schema', 'build:assets', 'build:lib'])
  .describe('builds the library bundle.')

b.task('browser', ['clean', 'build:schema', 'build:assets', 'build:browser'])
  .describe('builds the browser bundle.')

b.task('publish', ['clean', 'build:schema', 'build:assets', 'build:lib', 'build:web'])
  .describe('builds the release bundle (library + web).')

b.task('web', ['clean', 'build:schema', 'build:assets', 'build:browser', 'build:web'])
  .describe('builds the web bundle (browser + web).')

b.task('app', ['clean', 'build:schema', 'build:assets', 'build:browser', 'build:app'])
  .describe('builds the app bundle (electron app).')

b.task('test-nodejs', ['clean', 'build:schema', 'build:test-assets'])
  .describe('prepares everything necessary to run tests in node.')

b.task('test-browser', ['clean', 'build:schema', 'build:browser', 'build:test-assets', 'build:test-browser'])
  .describe('builds the test-suite for the browser.')

// an alias because in all our other projects it is named this way
b.task('test:browser', ['test-browser'])

b.task('default', ['publish'])
  .describe('default: publish')

// spawns electron after build is ready
b.task('run-app', ['app'], () => {
  // Note: `await=false` is important, as otherwise bundler would await this to finish
  fork(b, require.resolve('electron/cli.js'), '.', { verbose: true, cwd: APPDIST, await: false })
})
  .describe('runs the application in electron.')

// low-level make targets

b.task('schema:single-jats-file', _singleJATSFile)

b.task('schema:jats', () => {
  _compileSchema('JATS-archiving', RNG_FILES[0], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 1))
})

b.task('schema:dar-article', () => {
  _compileSchema('TextureArticle', RNG_FILES[1], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 2))
})

b.task('schema:dar-manifest', () => {
  _compileSchema('Manifest', 'src/dar/Manifest.rng', [path.join(__dirname, 'src', 'dar')], [])
})

b.task('schema:texture-article', () => {
})

b.task('schema:debug', () => {
  _compileSchema('JATS-archiving', RNG_FILES[0], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 1), { debug: true })
  _compileSchema('TextureArticle', RNG_FILES[1], RNG_SEARCH_DIRS, RNG_FILES.slice(0, 2), { debug: true })
})

b.task('build:assets', function () {
  b.copy('./node_modules/font-awesome', DIST + 'font-awesome')
  b.copy('./node_modules/inter-ui', DIST + 'inter-ui')
  b.copy('./node_modules/katex/dist', DIST + 'katex')
  b.copy('./node_modules/substance/dist', DIST + 'substance/dist')
  b.css('texture.css', DIST + 'texture.css')
  b.css('texture-reset.css', DIST + 'texture-reset.css')
})

b.task('build:schema', ['schema:jats', 'schema:dar-article', 'schema:texture-article', 'schema:dar-manifest'])

b.task('build:browser', () => {
  _buildLib(DIST, 'browser')
})

b.task('build:nodejs', () => {
  _buildLib(DIST, 'nodejs')
})

b.task('build:lib', () => {
  _buildLib(DIST, 'all')
})

b.task('build:cover', () => {
  _buildLib(TMP, 'cover')
})

b.task('build:app', () => {
  b.copy('app/index.html', APPDIST)
  b.copy('app/build-resources', APPDIST)
  b.copy('data', APPDIST)
  // FIXME: this command leads to an extra run when a  file is updated
  // .. instead copying the files explicitly for now
  // b.copy('dist', APPDIST+'lib/')
  b.copy('dist/font-awesome', APPDIST + 'lib/')
  b.copy('dist/katex', APPDIST + 'lib/')
  b.copy('dist/substance', APPDIST + 'lib/')
  ;[
    'texture.js',
    'texture.css',
    'texture-reset.css'
  ].forEach(f => {
    b.copy(`dist/${f}`, APPDIST + 'lib/')
    b.copy(`dist/${f}.map`, APPDIST + 'lib/')
  })

  // TODO: maybe we could come up with an extension
  // that expands a source file using a given dict.
  b.custom('Creating application package.json...', {
    src: 'app/package.json.in',
    dest: APPDIST + 'package.json',
    execute () {
      let { version } = require('./package.json')
      let tpl = fs.readFileSync('app/package.json.in', 'utf8')
      let out = tpl.replace('${version}', version) // eslint-disable-line no-template-curly-in-string
      fs.writeFileSync(APPDIST + 'package.json', out)
    }
  })
  b.js('app/main.js', {
    output: [{
      file: APPDIST + 'main.js',
      format: 'cjs'
    }],
    external: ['electron', 'path', 'url']
  })
  b.js('app/app.js', {
    output: [{
      file: APPDIST + 'app.js',
      format: 'umd',
      name: 'textureApp',
      globals: {
        'substance': 'substance',
        'substance-texture': 'texture',
        'katex': 'katex'
      }
    }],
    external: [ 'substance', 'substance-texture', 'katex' ]
  })
  // execute 'install-app-deps'
  fork(b, require.resolve('electron-builder/out/cli/cli.js'), 'install-app-deps', { verbose: true, cwd: APPDIST, await: true })
})

b.task('build:vfs', () => {
  vfs(b, {
    src: ['./data/**/*'],
    dest: DIST + 'vfs.js',
    format: 'umd',
    moduleName: 'vfs',
    rootDir: path.join(__dirname, 'data')
  })
})

b.task('build:web', ['build:vfs'], () => {
  b.copy('web/index.html', DIST)
  b.copy('web/reader.html', DIST)
  b.js('./web/editor.js', {
    output: [{
      file: DIST + 'editor.js',
      format: 'umd',
      name: 'textureEditor',
      globals: {
        'substance': 'substance',
        'substance-texture': 'texture',
        'katex': 'katex'
      }
    }],
    external: ['substance', 'substance-texture', 'katex']
  })
  b.js('./web/reader.js', {
    output: [{
      file: DIST + 'reader.js',
      format: 'umd',
      name: 'textureReader',
      globals: {
        'substance': 'substance',
        'substance-texture': 'texture',
        'katex': 'katex'
      }
    }],
    external: ['substance', 'substance-texture', 'katex']
  })
  b.copy('./data', DIST + 'data')
})

b.task('build:test-assets', ['build:vfs'], () => {
  vfs(b, {
    src: ['./test/fixture/**/*.xml'],
    dest: DIST + 'test/test-vfs.js',
    format: 'umd',
    moduleName: 'TEST_VFS',
    rootDir: path.join(__dirname, 'test', 'fixture')
  })
})

b.task('build:test-browser', ['build:assets', 'build:test-assets'], () => {
  b.copy('test/index.html', 'dist/test/index.html')
  b.copy('node_modules/substance-test/dist/testsuite.js', 'dist/test/testsuite.js')
  b.copy('node_modules/substance-test/dist/test.css', 'dist/test/test.css')

  // NOTE: by declaring texture/index.js as external we manage to serve both environments, browser and nodejs
  // with the same code.
  // In the browser, texture is used via the regular texture bundle, in nodejs it is resolved in the regular way
  const INDEX_JS = path.join(__dirname, 'index.js')
  const TEST_VFS = path.join(__dirname, 'tmp', 'test-vfs.js')
  let globals = {
    'substance': 'substance',
    'substance-test': 'substanceTest',
    'katex': 'katex',
    // TODO: this should be done in the same way as INDEX_JS and TEST_VFS
    'vfs': 'vfs'
  }
  globals[INDEX_JS] = 'texture'
  globals[TEST_VFS] = 'testVfs'

  b.js('test/index.js', {
    output: [{
      file: 'dist/test/tests.js',
      format: 'umd',
      name: 'tests',
      globals
    }],
    external: [
      'substance',
      'substance-test',
      INDEX_JS,
      'katex',
      'vfs',
      TEST_VFS
    ]
  })
})

/* HELPERS */

function _buildLib (DEST, platform) {
  let targets = []
  let istanbul
  if (platform === 'browser' || platform === 'all') {
    targets.push({
      file: DEST + 'texture.js',
      format: 'umd',
      name: 'texture',
      sourcemapRoot: __dirname,
      sourcemapPrefix: 'texture',
      globals: {
        'substance': 'substance',
        'katex': 'katex',
        'vfs': 'vfs'
      }
    })
  }
  if (platform === 'nodejs' || platform === 'all') {
    targets.push({
      file: DEST + 'texture.cjs.js',
      format: 'cjs'
    })
  }
  if (platform === 'es' || platform === 'all') {
    targets.push({
      file: DEST + 'texture.es.js',
      format: 'es'
    })
  }
  b.js('./index.js', {
    output: targets,
    external: ['substance', 'katex', 'vfs'],
    istanbul
  })
}

function _compileSchema (name, src, searchDirs, deps, options = {}) {
  const DEST = `tmp/${name}.data.js`
  const ISSUES = `tmp/${name}.issues.txt`
  const SCHEMA = `tmp/${name}.schema.md`
  const entry = path.basename(src)
  b.custom(`Compiling schema '${name}'...`, {
    src: [src].concat(deps),
    dest: DEST,
    execute () {
      const { compileRNG, checkSchema } = require('substance')
      const xmlSchema = compileRNG(fs, searchDirs, entry)
      b.writeFileSync(DEST, `export default ${JSON.stringify(xmlSchema)}`)
      b.writeFileSync(SCHEMA, xmlSchema.toMD())
      if (options.debug) {
        const issues = checkSchema(xmlSchema)
        const issuesData = [`${issues.length} issues:`, ''].concat(issues).join('\n')
        b.writeFileSync(ISSUES, issuesData)
      }
    }
  })
}

// we used this internally just to get a single-file version of
// the offficial JATS 1.1 rng data set
function _singleJATSFile () {
  [{
    RNG_DIR: 'data/jats/archiving',
    ENTRY: 'JATS-archive-oasis-article1-mathml3.rng',
    DEST: 'src/article/JATS-archiving.rng'
  }].forEach(({ RNG_DIR, ENTRY, DEST }) => {
    b.custom(`Pulling JATS spec into a single file...`, {
      src: [RNG_DIR + '/*.rng'],
      dest: DEST,
      execute () {
        const { loadRNG } = require('substance')
        let rng = loadRNG(fs, [RNG_DIR], ENTRY)
        // sort definitions by name
        let grammar = rng.find('grammar')
        let others = []
        let defines = []
        grammar.getChildren().forEach((child) => {
          if (child.tagName === 'define') {
            defines.push(child)
          } else {
            others.push(child)
          }
        })
        defines.sort((a, b) => {
          const aname = a.getAttribute('name').toLowerCase()
          const bname = b.getAttribute('name').toLowerCase()
          if (aname < bname) return -1
          if (bname < aname) return 1
          return 0
        })
        grammar.empty()
        defines.concat(others).forEach((el) => {
          grammar.appendChild('\n  ')
          grammar.appendChild(el)
        })
        let xml = rng.serialize()
        b.writeFileSync(DEST, xml)
      }
    })
  })
}
<|endoftext|>


<commit_before>/*
 * lanyrd-scraper
 * https://github.com/markdalgleish/node-lanyrd-scraper
 *
 * Copyright (c) 2012 Mark Dalgleish
 * Licensed under the MIT license.
 */

var scraper = require('scraper'),
	Helper = require('./helper');

exports.scrape = function(uri, callback) {
	var helper = new Helper();

	uri = helper.resolveUrl(uri);

	scraper(uri, function(err, $) {
		if (err) {
			callback(err, null);
			return;
		}

		helper.setContext($);

		var data = {};

		data.title = helper.getText('h1.summary');
		data.tagline = helper.getText('h2.tagline');

		data.websiteUrl = helper.getHref('div.item-meta a.website');
		data.scheduleUrl = helper.getHref('div.item-meta a.seeschedule');

		data.location = '' + helper.getText('p.prominent-place a.sub-place') + ', ' + helper.getText('p.prominent-place span.place-context a');
		if (data.location === ', ') {
			data.location = undefined;
		}

		// Parse the address and notes
		var addressValues = $('#venues p:eq(1)').text().split('- ');
		var address = $.trim(addressValues[0]);
		addressValues.shift();
		var note = addressValues.length > 0 ? $.trim(addressValues.join('- ')) : undefined;

		data.venues = [];

		data.venues.push({
			name: helper.getText('#venues h3 a'),
			address: address,
			note: note,
			googleMapsUrl: helper.getHref('#venues a.map-icon')
		});

		data.startDate = helper.getTitle('p.main-date abbr.dtstart');
		data.endDate = helper.getTitle('p.main-date abbr.dtend');
		data.time = helper.getText('p.main-date abbr.dtstart span.time');

		data.hashtag = helper.getText('div.item-meta a.hashtag');
		data.twitterHandle = helper.getText('div.item-meta a.twitter');

		data.speakers = [];
		$('#speaker-list li').each(function(){
			var speaker = {},
				$this = $(this);

			speaker.name = $this.find('span.name').text();
			speaker.twitterHandle = helper.getText($this.find('span.handle'));

			data.speakers.push(speaker);
		});

		data.sessions = [];
		$('li.session-detail').each(function(){
			var $this = $(this),
				$titleLink = $this.find('h3 a'),
				$link = $this.find('p a'),
				$time = $this.find('.time');

			var session = {
				title: $titleLink.text(),
				url: helper.getHref($titleLink),
				startTime: helper.getText($time),
				speakers: []
			};

			var $paragraph = $this.find('p');

			// Remove 'presented by'
			$paragraph.find('strong').remove();

			// Loop through all speakers with accounts, remove tags from DOM
			$paragraph.find('a').remove().each(function(){
				var $link = $(this);

				session.speakers.push({
					name: $link.text(),
					twitterHandle: helper.getTwitterHandle($link)
				});
			});

			// Convert remaining names into an array
			$paragraph.text().replace(' and ', ', ').split(', ').forEach(function(speakerName){
				speakerName = $.trim(speakerName);

				if (speakerName !== '') {
					session.speakers.push({
						name: speakerName
					});
				}
			});

			data.sessions.push(session);
		});

		data.attendees = [];
		$('div.attendees-placeholder ul.user-list li').each(function(){
			var attendee = {},
				$this = $(this);

			attendee.name = $this.find('img:first').attr('alt');
			attendee.twitterHandle = helper.getTwitterHandle($this.find('a'));

			data.attendees.push(attendee);
		});

		data.trackers = [];
		$('div.trackers-placeholder ul.user-list li').each(function(){
			var tracker = {},
				$this = $(this);

			tracker.name = $this.find('img:first').attr('alt');
			tracker.twitterHandle = helper.getTwitterHandle($this.find('a'));

			data.trackers.push(tracker);
		});

		callback(null, data);
	});
};<commit_msg>Make references to URL consistent<commit_after>/*
 * lanyrd-scraper
 * https://github.com/markdalgleish/node-lanyrd-scraper
 *
 * Copyright (c) 2012 Mark Dalgleish
 * Licensed under the MIT license.
 */

var scraper = require('scraper'),
	Helper = require('./helper');

exports.scrape = function(url, callback) {
	var helper = new Helper();

	url = helper.resolveUrl(url);

	scraper(url, function(err, $) {
		if (err) {
			callback(err, null);
			return;
		}

		helper.setContext($);

		var data = {};

		data.title = helper.getText('h1.summary');
		data.tagline = helper.getText('h2.tagline');

		data.websiteUrl = helper.getHref('div.item-meta a.website');
		data.scheduleUrl = helper.getHref('div.item-meta a.seeschedule');

		data.location = '' + helper.getText('p.prominent-place a.sub-place') + ', ' + helper.getText('p.prominent-place span.place-context a');
		if (data.location === ', ') {
			data.location = undefined;
		}

		// Parse the address and notes
		var addressValues = $('#venues p:eq(1)').text().split('- ');
		var address = $.trim(addressValues[0]);
		addressValues.shift();
		var note = addressValues.length > 0 ? $.trim(addressValues.join('- ')) : undefined;

		data.venues = [];

		data.venues.push({
			name: helper.getText('#venues h3 a'),
			address: address,
			note: note,
			googleMapsUrl: helper.getHref('#venues a.map-icon')
		});

		data.startDate = helper.getTitle('p.main-date abbr.dtstart');
		data.endDate = helper.getTitle('p.main-date abbr.dtend');
		data.time = helper.getText('p.main-date abbr.dtstart span.time');

		data.hashtag = helper.getText('div.item-meta a.hashtag');
		data.twitterHandle = helper.getText('div.item-meta a.twitter');

		data.speakers = [];
		$('#speaker-list li').each(function(){
			var speaker = {},
				$this = $(this);

			speaker.name = $this.find('span.name').text();
			speaker.twitterHandle = helper.getText($this.find('span.handle'));

			data.speakers.push(speaker);
		});

		data.sessions = [];
		$('li.session-detail').each(function(){
			var $this = $(this),
				$titleLink = $this.find('h3 a'),
				$link = $this.find('p a'),
				$time = $this.find('.time');

			var session = {
				title: $titleLink.text(),
				url: helper.getHref($titleLink),
				startTime: helper.getText($time),
				speakers: []
			};

			var $paragraph = $this.find('p');

			// Remove 'presented by'
			$paragraph.find('strong').remove();

			// Loop through all speakers with accounts, remove tags from DOM
			$paragraph.find('a').remove().each(function(){
				var $link = $(this);

				session.speakers.push({
					name: $link.text(),
					twitterHandle: helper.getTwitterHandle($link)
				});
			});

			// Convert remaining names into an array
			$paragraph.text().replace(' and ', ', ').split(', ').forEach(function(speakerName){
				speakerName = $.trim(speakerName);

				if (speakerName !== '') {
					session.speakers.push({
						name: speakerName
					});
				}
			});

			data.sessions.push(session);
		});

		data.attendees = [];
		$('div.attendees-placeholder ul.user-list li').each(function(){
			var attendee = {},
				$this = $(this);

			attendee.name = $this.find('img:first').attr('alt');
			attendee.twitterHandle = helper.getTwitterHandle($this.find('a'));

			data.attendees.push(attendee);
		});

		data.trackers = [];
		$('div.trackers-placeholder ul.user-list li').each(function(){
			var tracker = {},
				$this = $(this);

			tracker.name = $this.find('img:first').attr('alt');
			tracker.twitterHandle = helper.getTwitterHandle($this.find('a'));

			data.trackers.push(tracker);
		});

		callback(null, data);
	});
};<|endoftext|>


<commit_before><commit_msg>This commit comes with the first first version of jtouchsupport js<commit_after>
JTouchSupport = function() {

	this.isTouchDevice = function() {
		if ("ontouchstart" in document.documentElement) {
			return true;
		} else {
			return false;
		}
	};

	this.getX = function(event) {

		if( this.isTouchDevice() ) {
			return event.targetTouches[0].pageX;
		} else {
			return event.pageX;
		}

	}

	this.getY = function(event) {

		if( this.isTouchDevice() ) {
			return event.targetTouches[0].pageY;
		} else {
			return event.pageY;
		}

	}

};

//EOF<|endoftext|>


<commit_before>const Helper = require('../_helper');
const createList = require('../_list');

module.exports = new Helper("Patch", "patches", {
  api: 'title',
  columns: [
    'id',
    'name_de',
    'name_en',
    'name_fr',
    'name_ja',
    'name_female_de',
    'name_female_en',
    'name_female_fr',
    'name_female_ja',
    'is_prefix',
    'patch'
  ],
  list: true,
  format: (data, args) => {
    return {
      data: data.map(entry => {
        const response = {
          id: entry.id,
          name: {
            de: entry.name_de,
            en: entry.name_en,
            fr: entry.name_fr,
            jp: entry.name_ja
          }
        }

        if (args && args[0]) {
          response.achievement = args[0].data.filter(achievement => (
            achievement.reward && achievement.reward.title === entry.id
          )).map(achievement => ({
            id: achievement.id,
            name: achievement.name,
            patch: achievement.patch
          }))[0];
        }

        if (response.achievement) {
          response.patch = response.achievement.patch;
          delete response.achievement.patch;
        }

        if (entry.name_en !== entry.name_female_en)
          response.female = {
            de: entry.name_female_de,
            en: entry.name_female_en,
            fr: entry.name_female_fr,
            jp: entry.name_female_ja
          }

        return response;
      })
    }
  }
}, (data, base, _helperCreateJSONFn) => {
  createList("titles", data, base, _helperCreateJSONFn);
});<commit_msg>Added prefix to titles api.<commit_after>const Helper = require('../_helper');
const createList = require('../_list');

module.exports = new Helper("Patch", "patches", {
  api: 'title',
  columns: [
    'id',
    'name_de',
    'name_en',
    'name_fr',
    'name_ja',
    'name_female_de',
    'name_female_en',
    'name_female_fr',
    'name_female_ja',
    'is_prefix',
    'patch'
  ],
  list: true,
  format: (data, args) => {
    return {
      data: data.map(entry => {
        const response = {
          id: entry.id,
          name: {
            de: entry.name_de,
            en: entry.name_en,
            fr: entry.name_fr,
            jp: entry.name_ja
          },
          prefix: entry.is_prefix
        }

        if (args && args[0]) {
          response.achievement = args[0].data.filter(achievement => (
            achievement.reward && achievement.reward.title === entry.id
          )).map(achievement => ({
            id: achievement.id,
            name: achievement.name,
            patch: achievement.patch
          }))[0];
        }

        if (response.achievement) {
          response.patch = response.achievement.patch;
          delete response.achievement.patch;
        }

        if (entry.name_en !== entry.name_female_en)
          response.female = {
            de: entry.name_female_de,
            en: entry.name_female_en,
            fr: entry.name_female_fr,
            jp: entry.name_female_ja
          }

        return response;
      })
    }
  }
}, (data, base, _helperCreateJSONFn) => {
  createList("titles", data, base, _helperCreateJSONFn);
});<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.1.0');
		this.setClientTag('node:18-06-24');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.1.0');
		this.setClientTag('node:18-06-25');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>var licenses = document.querySelectorAll( '.licenseRow p' ),
    link,
    title,
    element;

if( licenses )
{
	for( var i = 0, length = licenses.length; i < length; i++ )
	{
		element = licenses[ i ];
		title = element.textContent;

		link = document.createElement( 'a' );
		link.className = 'steamdb_button';
		link.target = '_blank';
		link.href = GetHomepage() + 'search/?a=sub&q=' + encodeURIComponent( title );
		link.appendChild( document.createTextNode( title ) );

		element.parentNode.replaceChild( link, element );
	}
}
<commit_msg>Fix package links on account page<commit_after>var licenses = document.querySelectorAll( '.account_table tr > td:first-child' ),
    link,
    title,
    element;

if( licenses )
{
	for( var i = 0, length = licenses.length; i < length; i++ )
	{
		element = licenses[ i ];
		title = element.textContent;

		link = document.createElement( 'a' );
		link.className = 'steamdb_button';
		link.target = '_blank';
		link.href = GetHomepage() + 'search/?a=sub&q=' + encodeURIComponent( title );
		link.appendChild( document.createTextNode( title ) );

		element.replaceChild( link, element.firstChild );
	}
}
<|endoftext|>


<commit_before>'use babel';

export default {
  config: {
    compilerExecPath: {
      title: 'Compiler Executable Path',
      description: 'The path (with excutable) to be run by the IDE in the background. By default the IDE will use the compiler in your path.',
      type: 'string',
      default: 'crystal'
    },
    buildArtifacts: {
      title: 'Output Build Artifacts',
      description: 'When true the compiler will create build artifacts when run by the linter.',
      type: 'boolean',
      default: false
    },
    colorOutput: {
      title: 'Compiler passing Color Output',
      description: 'When false the compiler will not pass ASCII color characters to the linter when run by the linter.',
      type: 'boolean',
      default: false
    },
    command: {
      title: 'Compiler Command',
      description: 'The command passed to the commpiler during linting.',
      type: 'string',
      default: 'build'
    }
  },

  activate: () => {
    require("atom-package-deps").install("linter-crystal");
  },

  provideLinter: () => {
    const helpers = require('atom-linter')
    const regex = '(?<type>.+) in (?<file>.+):(?<line>\\d+): (?<message>.+)'
    return {
      grammarScopes: ['source.crystal'],
      scope: 'file',
      lintOnFly: false,
      lint: (activeEditor) => {
        const command = atom.config.get('linter-crystal.compilerExecPath')
        const file = activeEditor.getPath()
        const args = []
        args.push(atom.config.get('linter-crystal.command'))
        if(!atom.config.get('linter-crystal.buildArtifacts')) {
          args.push('--no-build')
        }
        if(!atom.config.get('linter-crystal.colorOutput')) {
          args.push('--no-color')
        }
        return helpers.execFilePath(command, args, file).then(output =>
          helpers.parse(output, regex)
        )
      }
    }
  }
}
<commit_msg>Update for Crystal 0.7.6<commit_after>'use babel';

export default {
  config: {
    compilerExecPath: {
      title: 'Compiler Executable Path',
      description: 'The path (with excutable) to be run by the IDE in the background. By default the IDE will use the compiler in your path.',
      type: 'string',
      default: 'crystal'
    },
    buildArtifacts: {
      title: 'Output Build Artifacts',
      description: 'When true the compiler will create build artifacts when run by the linter.',
      type: 'boolean',
      default: false
    },
    colorOutput: {
      title: 'Compiler passing Color Output',
      description: 'When false the compiler will not pass ASCII color characters to the linter when run by the linter.',
      type: 'boolean',
      default: false
    },
    command: {
      title: 'Compiler Command',
      description: 'The command passed to the commpiler during linting.',
      type: 'string',
      default: 'build'
    }
  },

  activate: () => {
    require("atom-package-deps").install("linter-crystal");
  },

  provideLinter: () => {
    const helpers = require('atom-linter')
    const regex = '(?<type>.+) in (?<file>.+):(?<line>\\d+): (?<message>.+)'
    return {
      grammarScopes: ['source.crystal'],
      scope: 'file',
      lintOnFly: false,
      lint: (activeEditor) => {
        const command = atom.config.get('linter-crystal.compilerExecPath')
        const file = activeEditor.getPath()
        const args = []
        args.push(atom.config.get('linter-crystal.command'))
        if(!atom.config.get('linter-crystal.buildArtifacts')) {
          args.push('--no-codegen')
        }
        if(!atom.config.get('linter-crystal.colorOutput')) {
          args.push('--no-color')
        }
        return helpers.execFilePath(command, args, file).then(output =>
          helpers.parse(output, regex)
        )
      }
    }
  }
}
<|endoftext|>


<commit_before>var backend = require("./databaseBackendMongodb");
var listeners = require("./listeners");
var routing = require("./routing");
var utils = require("./utils");

function getPadData(padId, callback) {
	backend.getPadData(padId, function(err, data) {
		if(err || data != null)
			return callback(err, data);

		backend.createPad(padId, callback);
	});
}

function updatePadData(padId, data, callback) {
	backend.updatePadData(padId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(padId, "padData", data);
		callback(null, data);
	});
}

function getViews(padId) {
	return backend.getViews(padId);
}

function createView(padId, data, callback) {
	if(data.name == null || data.name.trim().length == 0)
		return callback("No name provided.");

	backend.createView(padId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "view", data);
		callback(null, data);
	});
}

function updateView(viewId, data, callback) {
	if(data.name == null || data.name.trim().length == 0)
		return callback("No name provided.");

	backend.updateView(viewId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "view", data);
		callback(null, data);
	});
}

function deleteView(viewId, callback) {
	backend.deleteView(viewId, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "deleteView", { id: data.id });
		callback(null, data);
	});
}

function getPadMarkers(padId, bbox) {
	return backend.getPadMarkers(padId, bbox);
}

function createMarker(padId, data, callback) {
	backend.createMarker(padId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(padId, "marker", _getMarkerDataFunc(data));
		callback(null, data);
	});
}

function updateMarker(markerId, data, callback) {
	backend.updateMarker(markerId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "marker", _getMarkerDataFunc(data));
		callback(null, data);
	});
}

function deleteMarker(markerId, callback) {
	backend.deleteMarker(markerId, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "deleteMarker", { id: data.id });
		callback(null, data);
	});
}

function getPadLines(padId, bbox) {
	return utils.filterStreamAsync(backend.getPadLines(padId, bbox), function(data, next) {
		_getLinePoints(data.id, bbox, function(err, points) {
			if(err)
				return next(err);

			data.actualPoints = points;
			next(null, data);
		});
	});
}

function createLine(padId, data, callback) {
	backend.createLine(padId, data, function(err, data) {
		if(err)
			return callback(err);

		_calculateRouting(data, function(err, data, actualPoints) {
			if(err)
				return callback(err);

			backend.setLinePoints(data.id, actualPoints, function(err) {
				if(err)
					return callback;

				listeners.notifyPadListeners(data._pad, "line", _getLineDataFunc(data, actualPoints));
				callback(null, data);
			});
		});
	});
}

function updateLine(lineId, data, callback) {
	backend.updateLine(lineId, data, function(err, data) {
		if(err)
			return callback(err);

		_calculateRouting(data, function(err, data, actualPoints) {
			if(err)
				return callback(err);

			backend.setLinePoints(lineId, actualPoints, function(err) {
				if(err)
					return callback;

				listeners.notifyPadListeners(data._pad, "line", _getLineDataFunc(data, actualPoints));
				callback(null, data);
			});
		});
	});
}

function deleteLine(lineId, callback) {
	backend.deleteLine(lineId, function(err, data) {
		if(err)
			return callback(err);

		backend.setLinePoints(lineId, [ ], function(err) {
			if(err)
				return callback;

			listeners.notifyPadListeners(data._pad, "deleteLine", { id: data.id });
			callback(null, data);
		});
	});
}

function _calculateRouting(line, callback) {
	if(line.points && line.points.length >= 2 && line.mode) {
		routing.calculateRouting(line.points, line.mode, function(err, routeData) {
			if(err)
				return callback(err);

			line.distance = routeData.distance;
			line.time = routeData.time;
			callback(null, line, routeData.actualPoints);
		});
	} else {
		line.distance = utils.calculateDistance(line.points);
		line.time = null;

		var actualPoints = [ ];
		for(var i=0; i<line.points.length; i++) {
			actualPoints.push(utils.extend({ }, line.points[i], { zoom: 1 }));
		}
		callback(null, line, actualPoints);
	}
}

function _getMarkerDataFunc(marker) {
	return function(bbox) {
		if(!utils.isInBbox(marker.position, bbox))
			return null;

		return marker;
	};
}

function _getLineDataFunc(line, actualPoints) {
	return function(bbox) {
		var points = routing.prepareForBoundingBox(actualPoints, bbox);
		if(points.length <= 1)
			return null;

		return utils.extend({ }, line, { actualPoints: points });
	};
}

function _getLinePoints(lineId, bboxWithZoom, callback) {
	backend.getLinePointsByBbox(lineId, bboxWithZoom, function(err, data) {
		if(err)
			return callback(err);

		// Get one more point outside of the bbox for each segment
		var indexes = [ ];
		for(var i=0; i<data.length; i++) {
			if(i == 0 || data[i-1].idx != data[i].idx-1) // Beginning of segment
				indexes.push(data[i].idx-1);

			indexes.push(data[i].idx);

			if(i == data.length-1 || data[i+1].idx != data[i].idx+1) // End of segment
				indexes.push(data[i].idx+1);
		}

		if(indexes.length == 0)
			return callback(null, [ ]);

		backend.getLinePointsByIdx(lineId, indexes, callback);
	});
}

module.exports = {
	connect : backend.connect,
	getPadData : getPadData,
	updatePadData : updatePadData,
	getViews : getViews,
	createView : createView,
	updateView : updateView,
	deleteView : deleteView,
	getPadMarkers : getPadMarkers,
	createMarker : createMarker,
	updateMarker : updateMarker,
	deleteMarker : deleteMarker,
	getPadLines : getPadLines,
	createLine : createLine,
	updateLine : updateLine,
	deleteLine : deleteLine
};<commit_msg>Fixing missing distance for lines<commit_after>var backend = require("./databaseBackendMongodb");
var listeners = require("./listeners");
var routing = require("./routing");
var utils = require("./utils");

function getPadData(padId, callback) {
	backend.getPadData(padId, function(err, data) {
		if(err || data != null)
			return callback(err, data);

		backend.createPad(padId, callback);
	});
}

function updatePadData(padId, data, callback) {
	backend.updatePadData(padId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(padId, "padData", data);
		callback(null, data);
	});
}

function getViews(padId) {
	return backend.getViews(padId);
}

function createView(padId, data, callback) {
	if(data.name == null || data.name.trim().length == 0)
		return callback("No name provided.");

	backend.createView(padId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "view", data);
		callback(null, data);
	});
}

function updateView(viewId, data, callback) {
	if(data.name == null || data.name.trim().length == 0)
		return callback("No name provided.");

	backend.updateView(viewId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "view", data);
		callback(null, data);
	});
}

function deleteView(viewId, callback) {
	backend.deleteView(viewId, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "deleteView", { id: data.id });
		callback(null, data);
	});
}

function getPadMarkers(padId, bbox) {
	return backend.getPadMarkers(padId, bbox);
}

function createMarker(padId, data, callback) {
	backend.createMarker(padId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(padId, "marker", _getMarkerDataFunc(data));
		callback(null, data);
	});
}

function updateMarker(markerId, data, callback) {
	backend.updateMarker(markerId, data, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "marker", _getMarkerDataFunc(data));
		callback(null, data);
	});
}

function deleteMarker(markerId, callback) {
	backend.deleteMarker(markerId, function(err, data) {
		if(err)
			return callback(err);

		listeners.notifyPadListeners(data._pad, "deleteMarker", { id: data.id });
		callback(null, data);
	});
}

function getPadLines(padId, bbox) {
	return utils.filterStreamAsync(backend.getPadLines(padId, bbox), function(data, next) {
		_getLinePoints(data.id, bbox, function(err, points) {
			if(err)
				return next(err);

			data.actualPoints = points;
			next(null, data);
		});
	});
}

function createLine(padId, data, callback) {
	_calculateRouting(data, function(err, data, actualPoints) {
		if(err)
			return callback(err);
		backend.createLine(padId, data, function(err, data) {
			if(err)
				return callback(err);

			backend.setLinePoints(data.id, actualPoints, function(err) {
				if(err)
					return callback;

				listeners.notifyPadListeners(data._pad, "line", _getLineDataFunc(data, actualPoints));
				callback(null, data);
			});
		});
	});
}

function updateLine(lineId, data, callback) {
	_calculateRouting(data, function(err, data, actualPoints) {
		if(err)
			return callback(err);

		backend.updateLine(lineId, data, function(err, data) {
			if(err)
				return callback(err);

			backend.setLinePoints(lineId, actualPoints, function(err) {
				if(err)
					return callback;

				listeners.notifyPadListeners(data._pad, "line", _getLineDataFunc(data, actualPoints));
				callback(null, data);
			});
		});
	});
}

function deleteLine(lineId, callback) {
	backend.deleteLine(lineId, function(err, data) {
		if(err)
			return callback(err);

		backend.setLinePoints(lineId, [ ], function(err) {
			if(err)
				return callback;

			listeners.notifyPadListeners(data._pad, "deleteLine", { id: data.id });
			callback(null, data);
		});
	});
}

function _calculateRouting(line, callback) {
	if(line.points && line.points.length >= 2 && line.mode) {
		routing.calculateRouting(line.points, line.mode, function(err, routeData) {
			if(err)
				return callback(err);

			line.distance = routeData.distance;
			line.time = routeData.time;
			callback(null, line, routeData.actualPoints);
		});
	} else {
		line.distance = utils.calculateDistance(line.points);
		line.time = null;

		var actualPoints = [ ];
		for(var i=0; i<line.points.length; i++) {
			actualPoints.push(utils.extend({ }, line.points[i], { zoom: 1 }));
		}
		callback(null, line, actualPoints);
	}
}

function _getMarkerDataFunc(marker) {
	return function(bbox) {
		if(!utils.isInBbox(marker.position, bbox))
			return null;

		return marker;
	};
}

function _getLineDataFunc(line, actualPoints) {
	return function(bbox) {
		var points = routing.prepareForBoundingBox(actualPoints, bbox);
		if(points.length <= 1)
			return null;

		return utils.extend({ }, line, { actualPoints: points });
	};
}

function _getLinePoints(lineId, bboxWithZoom, callback) {
	backend.getLinePointsByBbox(lineId, bboxWithZoom, function(err, data) {
		if(err)
			return callback(err);

		// Get one more point outside of the bbox for each segment
		var indexes = [ ];
		for(var i=0; i<data.length; i++) {
			if(i == 0 || data[i-1].idx != data[i].idx-1) // Beginning of segment
				indexes.push(data[i].idx-1);

			indexes.push(data[i].idx);

			if(i == data.length-1 || data[i+1].idx != data[i].idx+1) // End of segment
				indexes.push(data[i].idx+1);
		}

		if(indexes.length == 0)
			return callback(null, [ ]);

		backend.getLinePointsByIdx(lineId, indexes, callback);
	});
}

module.exports = {
	connect : backend.connect,
	getPadData : getPadData,
	updatePadData : updatePadData,
	getViews : getViews,
	createView : createView,
	updateView : updateView,
	deleteView : deleteView,
	getPadMarkers : getPadMarkers,
	createMarker : createMarker,
	updateMarker : updateMarker,
	deleteMarker : deleteMarker,
	getPadLines : getPadLines,
	createLine : createLine,
	updateLine : updateLine,
	deleteLine : deleteLine
};<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.7.0');
		this.setClientTag('node:20-08-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.7.0');
		this.setClientTag('node:20-08-08');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>var chalk = require('chalk');
var config = require('../config').logger;

// Logger settings
var WRITE_LEVELS = {
  'DEBUG': 1,
  'INFO': 2,
  'WARNING': 3,
  'ERROR': 4,
  'DISABLED': 5
};

// Internal variables
var currentWriteLevel;
var debugStyle;
var infoStyle;
var warningStyle;
var errorStyle;

module.exports = Logger;

/**
 * Wheelie logger
 * @constructor
 * @param {Object} options - Logger configurations
 * @param {Object} options.colors - Defines used color for each write level
 * @param {number} options.writeLevel - Defines the logger write level
 */
function Logger(options) {
  options = options || config;

  var colors = options.colors;
  var writeLevel = options.writeLevel;

  // setting current write level
  this.setWriteLevel(writeLevel);

  // setting console styles
  debugStyle = chalk[colors.DEBUG];
  infoStyle = chalk[colors.INFO];
  warningStyle = chalk[colors.WARNING];
  errorStyle = chalk[colors.ERROR];
}

/**
 * Prints to stdout with newline, using the DEBUG chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.debug = function(text) {
  if (this.writeIsEnabled('DEBUG')) {
    console.debug(debugStyle(text));
  }
}

/**
 * Prints to stdout with newline, using the INFO chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.info = function(text) {
  if (this.writeIsEnabled('INFO')) {
    console.info(infoStyle(text));
  }
}

/**
 * Prints to stdout with newline, using the WARNING chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.warning = function(text) {
  if (this.writeIsEnabled('WARNING')) {
    console.warn(debugStyle(text));
  }
}

/**
 * Prints to stdout with newline, using the ERROR chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.error = function(text) {
  if (this.writeIsEnabled('ERROR')) {
    console.error(errorStyle(text));
  }
}

/**
 * Sets the current write level; returns an error if writeLevel doesn't exist
 * @param {string} writeLevel - The new write level
 */
Logger.prototype.setWriteLevel = function(writeLevel) {
  if (WRITE_LEVELS[writeLevel] === undefined) {
    console.error("Selected write level '", writeLevel, "' doesn't exist");
  } else {
    currentWriteLevel = writeLevel;
  }
}

/**
 * Returns the current write level
 * @return {string} the current write level
 */
Logger.prototype.getWriteLevel = function() {
  return currentWriteLevel;
}

/**
 * Returns if this write level is enabled, according to the current write level
 * @param {string} writeLevel - Write level to test
 */
Logger.prototype.writeIsEnabled = function(writeLevel) {
  return WRITE_LEVELS[writeLevel] > WRITE_LEVELS[currentWriteLevel];
}
<commit_msg>raising errors if the chosen write level doesn't exist<commit_after>var chalk = require('chalk');
var config = require('../config').logger;

// Logger settings
var WRITE_LEVELS = {
  'DEBUG': 1,
  'INFO': 2,
  'WARNING': 3,
  'ERROR': 4,
  'DISABLED': 5
};

// Internal variables
var currentWriteLevel;
var debugStyle;
var infoStyle;
var warningStyle;
var errorStyle;

module.exports = Logger;

/**
 * Wheelie logger
 * @constructor
 * @param {Object} options - Logger configurations
 * @param {Object} options.colors - Defines used color for each write level
 * @param {number} options.writeLevel - Defines the logger write level
 */
function Logger(options) {
  options = options || config;

  var colors = options.colors;
  var writeLevel = options.writeLevel;

  // setting current write level
  this.setWriteLevel(writeLevel);

  // setting console styles
  debugStyle = chalk[colors.DEBUG];
  infoStyle = chalk[colors.INFO];
  warningStyle = chalk[colors.WARNING];
  errorStyle = chalk[colors.ERROR];
}

/**
 * Prints to stdout with newline, using the DEBUG chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.debug = function(text) {
  if (this.writeIsEnabled('DEBUG')) {
    console.debug(debugStyle(text));
  }
}

/**
 * Prints to stdout with newline, using the INFO chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.info = function(text) {
  if (this.writeIsEnabled('INFO')) {
    console.info(infoStyle(text));
  }
}

/**
 * Prints to stdout with newline, using the WARNING chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.warning = function(text) {
  if (this.writeIsEnabled('WARNING')) {
    console.warn(debugStyle(text));
  }
}

/**
 * Prints to stdout with newline, using the ERROR chalk style
 * @param {string} text - Text to print
 */
Logger.prototype.error = function(text) {
  if (this.writeIsEnabled('ERROR')) {
    console.error(errorStyle(text));
  }
}

/**
 * Sets the current write level; returns an error if writeLevel doesn't exist
 * @param {string} writeLevel - The new write level
 */
Logger.prototype.setWriteLevel = function(writeLevel) {
  if (WRITE_LEVELS[writeLevel] === undefined) {
    throw new Error("Selected write level '" +  writeLevel + "' doesn't exist");
  } else {
    currentWriteLevel = writeLevel;
  }
}

/**
 * Returns the current write level
 * @return {string} the current write level
 */
Logger.prototype.getWriteLevel = function() {
  return currentWriteLevel;
}

/**
 * Returns if this write level is enabled, according to the current write level
 * @param {string} writeLevel - Write level to test
 */
Logger.prototype.writeIsEnabled = function(writeLevel) {
  return WRITE_LEVELS[writeLevel] > WRITE_LEVELS[currentWriteLevel];
}
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2019  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.17.0');
		this.setClientTag('node:19-04-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2019  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.17.0');
		this.setClientTag('node:19-04-08');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>export { TwinArray };

import * as TensorPlaceholder from "../TensorPlaceholder.js";
//import * as BoundsArraySet from "../BoundsArraySet.js";
import { Base } from "./Operation_Base.js";

/**
 * An array of operations. Every time appending operation, one or parallel twin operations could be appended.
 *
 * Its .output0 and .output1 (tensor placeholder) are pointer to the last operation's output0 and output1. This could simply the
 * decision of what tensor placeholders should be used as the next operation's input.
 *
 *
 *
 * @member {function} apply

//!!! ...unfinished... (2022/06/01)

 *
 */
let TwinArray = ( ParentClass = Object ) => class extends Base( ParentClass ) {

  /**
   *
   */
  constructor( inputTensorPlaceholder0, inputTensorPlaceholder1 ) {
    super( inputTensorPlaceholder0, inputTensorPlaceholder1, 0 );
    this.operationArray = new Array();
    this.disposeTensors();
  }

  /**
   * @override
   */
  disposeTensors() {

    if ( this.operationArray ) {
      for ( let i = 0; i < this.operationArray.length; ++i ) {
        let operation = this.operationArray[ i ];
        operation.disposeTensors();
      }
      this.operationArray.length = 0;
    }

//!!! ...unfinished... (2022/06/02) ???
    this.output0 = this.input0;
    this.output1 = this.input1;

    super.disposeTensors();
  }

  /**
   * @override
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {

    // TensorPlaceholders requested to keep their tensors.
    let alwaysKeepSet;
    {
      if ( bKeepInputTensor0 || bKeepInputTensor1 ) {
        alwaysKeepSet = new Set();

        if ( bKeepInputTensor0 )
          alwaysKeepSet.add( this.input0 );

        if ( bKeepInputTensor1 )
          alwaysKeepSet.add( this.input1 );
      }
    }

    for ( let i = 0; i < this.operationArray.length; ++i ) {
    }
//!!!

//!!! ...unfinished... (2022/06/01)
// call setKeepInputTensor_IfNotLastOperation_Or_In( alwaysKeepSet ) for every operation?
  setKeepInputTensor_IfNotLastOperation_Or_In( alwaysKeepSet )

    // Note: If an
  }

//!!! ...unfinished... (2022/06/01)
  /**
   * @param {Base} this
   *   The Block.Base object whose .byteOffsetEnd might be updated.
   *
   * @param {Class} operationClass
   *   What kind of operation TO be created.
   *
   * @param {Array} constructorArgs
   *   The arguments to be passed to the constructor of operationClass. If null, the constructor will be called without any argument.
   *
   * @param {Array} initArgs
   *   The arguments to be passed to the init() method of operation object.
   *   - If null, the operation object's init() will not be called. Usually, this means the operation object needs not extract any weights.
   *   - If the .init() is called and returns false, this method will failed and return null.
   *   - If the .init() is called and returns true, this method will update this.byteOffsetEnd.
   *
   * @return {object} If success, return the created operation object. If failed, return null.
   */
  static operation_create__update_byteOffsetEnd_if_init( operationClass, constructorArgs, initArgs ) {
    let operationObject;

    // Construct.
    if ( constructorArgs != undefined ) {
      operationObject = new operationClass( ...constructorArgs );
    } else {
      operationObject = new operationClass();
    }

    // Intialize.
    if ( initArgs ) {
      if ( !operationObject.init( ...initArgs ) )
        return null;  // e.g. input array does not have enough data.

      this.byteOffsetEnd = operationObject.byteOffsetEnd;

    // Otherwise (i.e. no initArgs), do not call operationObject.init() and do not update this.byteOffsetEnd
    }

    return operationObject;
  }

  /**
   * Only one operation object (operationObject0) will be created and appended into this.operationArray[].
   *
   *   - this.output0 will be pointered to operationObject0.output0
   *
   *   - this.output1:
   *
   *     - will not be modified, if operationObject0 has no output1.
   *         (i.e. could be viewed as passing through from previous operation output to this operation output).
   *
   *     - will be pointered to operationObject0.output1, if operationObject0 has output1.
   *
   *
   * @param {Class} operationClass
   *   What kind of operation to be created and appended into this.operationArray[].
   *
   * @param {Array} constructorArgs
   *   The arguments to be passed to the constructor of operationClass. If null, the constructor will be called without any argument.
   *
   * @param {Array} initArgs
   *   The arguments to be passed to the .init() method of operation object.
   *   - If null, the operation object's init() will not be called. Usually, this means the operation object needs not extract any weights.
   *   - If the .init() is called and returns false, this method will failed and return false.
   *   - If the .init() is called and returns true, this method will update this.byteOffsetEnd.
   *
   * @return {boolean}
   *   Return true, if success.
   */
  operation_append_one( operationClass, constructorArgs, initArgs ) {

    // 1. Create and initialize.
    let operationObject0 = Base.operation_create__update_byteOffsetEnd_if_init.call( this, operationClass, constructorArgs, initArgs );
    if ( !operationObject0 )
      return false;  // e.g. input array does not have enough data.

    // 2. Put into queue.
    this.operationArray.push( operationObject0 );

    // 3. Tracking the current output tensor placeholders for next operation's input.
    {
      this.output0 = operationObject0.output0;

      // If the (first) only operation has two outputs, pointer to the second output of the (first) only operation.
      if ( operationObject0.output1 ) {
        this.currentTensorPlaceholder1 = operationObject0.output1;

      // Otherwise, keep this.output1 the same (i.e. bypass from previous output to this output).
      }
    }

    return true;
  }

  /**
   * Two operation objects (operationObject0 and operationObject1) will be created (with the same operationClass,
   *       constructorArgs, initArgs) and appended into this.operationArray[].
   *
   *   - this.output0 will be pointered to operationObject0.output0
   *       (i.e. operationObject0.output1 will be ignored even if it exists)
   *
   *   - this.output1 will be pointered to operationObject1.output0
   *       (i.e. operationObject1.output1 will be ignored even if it exists)
   *
   *
   * @param {Class} operationClass0   The 1st operation class.
   * @param {Array} constructorArgs0  The 1st operation constructor's arguments.
   * @param {Array} initArgs0         The 1st operation .init()'s arguments.
   *
   * @param {Class} operationClass1   The 2nd operation class.
   * @param {Array} constructorArgs1  The 2nd operation constructor's arguments.
   * @param {Array} initArgs1         The 2nd operation .init()'s arguments.
   *
   * @return {boolean}
   *   Return true, if success.
   *
   * @see operation_append_one()
   */
  operation_append_twin(
    operationClass0, constructorArgs0, initArgs0,
    operationClass1, constructorArgs1, initArgs1 ) {

    // 1. Create and initialize.

    // 1.1 1st operation object.
    let operationObject0 = Base.operation_create__update_byteOffsetEnd_if_init.call( this, operationClass0, constructorArgs0, initArgs0 );
    if ( !operationObject0 )
      return false;  // e.g. input array does not have enough data.

    // 1.2 2nd operation object.
    let operationObject1 = Base.operation_create__update_byteOffsetEnd_if_init.call( this, operationClass1, constructorArgs1, initArgs1 );
    if ( !operationObject1 )
      return false;  // e.g. input array does not have enough data.

    // 2. Put into queue.
    this.operationArray.push( operationObject0 );
    this.operationArray.push( operationObject1 );

    // 3. Tracking the current output tensor placeholders for next operation's input.
    {
      // When there two parallel operations, they should not have output1 (i.e. should only have output0).
      tf.util.assert( ( operationObject0.output1 == undefined ) && ( operationObject1.output1 == undefined ),
        `Operation.TwinArray.operation_append_twin(): `
          + `Both `
          + `operationObject0.output1 ( ${operationObject0.output1} ) and `
          + `operationObject1.output1 ( ${operationObject1.output1} ) `
          + `should all be undefined.`
      );

      this.output0 = operationObject0.output0;
      this.output1 = operationObject1.output0;
    }

    return true;
  }

  /**
   * @override
   */
  apply() {

//!!! ...unfinished... (2022/06/01)
// What if not operation at all when needs or needs not keep-input?

  }

  /** @return {number} Sum of operations' tensorWeightCountExtracted. */
  get tensorWeightCountExtracted() {
//!!! ...unfinished... (2022/06/01)
    return 0;
  }

  /** @return {number} Sum of operations' tensorWeightCountTotal. */
  get tensorWeightCountTotal() {
//!!! ...unfinished... (2022/06/01)
    return 0;
  }

}
<commit_msg>Update Operation_TwinArray.js<commit_after>export { TwinArray };

import * as TensorPlaceholder from "../TensorPlaceholder.js";
//import * as BoundsArraySet from "../BoundsArraySet.js";
import { Base } from "./Operation_Base.js";

/**
 * An array of operations. Every time appending operation, one or parallel twin operations could be appended.
 *

//!!! ...unfinished... (2022/06/02)

 * Its .output0 and .output1 (tensor placeholder) are pointer to the last operation's output0 and output1. This could simply the
 * decision of what tensor placeholders should be used as the next operation's input.
 *
 *
 *
 * @member {function} apply

//!!! ...unfinished... (2022/06/02)

 *
 */
let TwinArray = ( ParentClass = Object ) => class extends Base( ParentClass ) {

  /**
   *
   */
  constructor( inputTensorPlaceholder0, inputTensorPlaceholder1 ) {
    super( inputTensorPlaceholder0, inputTensorPlaceholder1, 0 );
    this.operationArray = new Array();
    this.disposeTensors();
  }

  /**
   * @override
   */
  disposeTensors() {

    if ( this.operationArray ) {
      for ( let i = 0; i < this.operationArray.length; ++i ) {
        let operation = this.operationArray[ i ];
        operation.disposeTensors();
      }
      this.operationArray.length = 0;
    }

//!!! ...unfinished... (2022/06/02) ???
    this.output0 = this.input0;
    this.output1 = this.input1;

    super.disposeTensors();
  }

  /**
   * @override
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {

    // TensorPlaceholders requested to keep their tensors.
    let alwaysKeepSet;
    {
      if ( bKeepInputTensor0 || bKeepInputTensor1 ) {
        alwaysKeepSet = new Set();

        if ( bKeepInputTensor0 )
          alwaysKeepSet.add( this.input0 );

        if ( bKeepInputTensor1 )
          alwaysKeepSet.add( this.input1 );
      }
    }

    // Every input tensors' last operation should be responsible for releasing the tensor. Except the input tensors are requested
    // to be kept (i.e. inside alwaysKeepSet).
    //
    for ( let i = 0; i < this.operationArray.length; ++i ) {
      let operation = this.operationArray[ i ];
      operation.setKeepInputTensor_IfNotLastOperation_Or_In( alwaysKeepSet );
    }

//!!! ...unfinished... (2022/06/02) What if .operationArray[] is empty ?

  }

//!!! ...unfinished... (2022/06/01)
  /**
   * @param {Base} this
   *   The Block.Base object whose .byteOffsetEnd might be updated.
   *
   * @param {Class} operationClass
   *   What kind of operation TO be created.
   *
   * @param {Array} constructorArgs
   *   The arguments to be passed to the constructor of operationClass. If null, the constructor will be called without any argument.
   *
   * @param {Array} initArgs
   *   The arguments to be passed to the init() method of operation object.
   *   - If null, the operation object's init() will not be called. Usually, this means the operation object needs not extract any weights.
   *   - If the .init() is called and returns false, this method will failed and return null.
   *   - If the .init() is called and returns true, this method will update this.byteOffsetEnd.
   *
   * @return {object} If success, return the created operation object. If failed, return null.
   */
  static operation_create__update_byteOffsetEnd_if_init( operationClass, constructorArgs, initArgs ) {
    let operationObject;

    // Construct.
    if ( constructorArgs != undefined ) {
      operationObject = new operationClass( ...constructorArgs );
    } else {
      operationObject = new operationClass();
    }

    // Intialize.
    if ( initArgs ) {
      if ( !operationObject.init( ...initArgs ) )
        return null;  // e.g. input array does not have enough data.

      this.byteOffsetEnd = operationObject.byteOffsetEnd;

    // Otherwise (i.e. no initArgs), do not call operationObject.init() and do not update this.byteOffsetEnd
    }

    return operationObject;
  }

  /**
   * Only one operation object (operationObject0) will be created and appended into this.operationArray[].
   *
   *   - this.output0 will be pointered to operationObject0.output0
   *
   *   - this.output1:
   *
   *     - will not be modified, if operationObject0 has no output1.
   *         (i.e. could be viewed as passing through from previous operation output to this operation output).
   *
   *     - will be pointered to operationObject0.output1, if operationObject0 has output1.
   *
   *
   * @param {Class} operationClass
   *   What kind of operation to be created and appended into this.operationArray[].
   *
   * @param {Array} constructorArgs
   *   The arguments to be passed to the constructor of operationClass. If null, the constructor will be called without any argument.
   *
   * @param {Array} initArgs
   *   The arguments to be passed to the .init() method of operation object.
   *   - If null, the operation object's init() will not be called. Usually, this means the operation object needs not extract any weights.
   *   - If the .init() is called and returns false, this method will failed and return false.
   *   - If the .init() is called and returns true, this method will update this.byteOffsetEnd.
   *
   * @return {boolean}
   *   Return true, if success.
   */
  operation_append_one( operationClass, constructorArgs, initArgs ) {

    // 1. Create and initialize.
    let operationObject0 = Base.operation_create__update_byteOffsetEnd_if_init.call( this, operationClass, constructorArgs, initArgs );
    if ( !operationObject0 )
      return false;  // e.g. input array does not have enough data.

    // 2. Put into queue.
    this.operationArray.push( operationObject0 );

    // 3. Tracking the current output tensor placeholders for next operation's input.
    {
      this.output0 = operationObject0.output0;

      // If the (first) only operation has two outputs, pointer to the second output of the (first) only operation.
      if ( operationObject0.output1 ) {
        this.currentTensorPlaceholder1 = operationObject0.output1;

      // Otherwise, keep this.output1 the same (i.e. bypass from previous output to this output).
      }
    }

    return true;
  }

  /**
   * Two operation objects (operationObject0 and operationObject1) will be created (with the same operationClass,
   *       constructorArgs, initArgs) and appended into this.operationArray[].
   *
   *   - this.output0 will be pointered to operationObject0.output0
   *       (i.e. operationObject0.output1 will be ignored even if it exists)
   *
   *   - this.output1 will be pointered to operationObject1.output0
   *       (i.e. operationObject1.output1 will be ignored even if it exists)
   *
   *
   * @param {Class} operationClass0   The 1st operation class.
   * @param {Array} constructorArgs0  The 1st operation constructor's arguments.
   * @param {Array} initArgs0         The 1st operation .init()'s arguments.
   *
   * @param {Class} operationClass1   The 2nd operation class.
   * @param {Array} constructorArgs1  The 2nd operation constructor's arguments.
   * @param {Array} initArgs1         The 2nd operation .init()'s arguments.
   *
   * @return {boolean}
   *   Return true, if success.
   *
   * @see operation_append_one()
   */
  operation_append_twin(
    operationClass0, constructorArgs0, initArgs0,
    operationClass1, constructorArgs1, initArgs1 ) {

    // 1. Create and initialize.

    // 1.1 1st operation object.
    let operationObject0 = Base.operation_create__update_byteOffsetEnd_if_init.call( this, operationClass0, constructorArgs0, initArgs0 );
    if ( !operationObject0 )
      return false;  // e.g. input array does not have enough data.

    // 1.2 2nd operation object.
    let operationObject1 = Base.operation_create__update_byteOffsetEnd_if_init.call( this, operationClass1, constructorArgs1, initArgs1 );
    if ( !operationObject1 )
      return false;  // e.g. input array does not have enough data.

    // 2. Put into queue.
    this.operationArray.push( operationObject0 );
    this.operationArray.push( operationObject1 );

    // 3. Tracking the current output tensor placeholders for next operation's input.
    {
      // When there two parallel operations, they should not have output1 (i.e. should only have output0).
      tf.util.assert( ( operationObject0.output1 == undefined ) && ( operationObject1.output1 == undefined ),
        `Operation.TwinArray.operation_append_twin(): `
          + `Both `
          + `operationObject0.output1 ( ${operationObject0.output1} ) and `
          + `operationObject1.output1 ( ${operationObject1.output1} ) `
          + `should all be undefined.`
      );

      this.output0 = operationObject0.output0;
      this.output1 = operationObject1.output0;
    }

    return true;
  }

  /**
   * @override
   */
  apply() {

//!!! ...unfinished... (2022/06/01)
// What if not operation at all when needs or needs not keep-input?

  }

  /** @return {number} Sum of operations' tensorWeightCountExtracted. */
  get tensorWeightCountExtracted() {
//!!! ...unfinished... (2022/06/01)
    return 0;
  }

  /** @return {number} Sum of operations' tensorWeightCountTotal. */
  get tensorWeightCountTotal() {
//!!! ...unfinished... (2022/06/01)
    return 0;
  }

}
<|endoftext|>