<commit_before>function handleSubmit () {
  let val = document.getElementById('url').value
  if (val) {
    document.location += 'memento/*/' + val
  }
}

function shortestFirst (a, b) {
  return a.length - b.length
}

function hideURIs () {
  document.getElementById('uris').classList.add('hidden')
  document.getElementById('memCountListLink').classList.remove('activated')
  window.localStorage.setItem('showURIs', 'false')
}

function addURIListToDOM () {
  let ul = document.getElementById('uriList')
  const uriKeys = Object.keys(uris).sort(shortestFirst)

  uriKeys.forEach(urir => {
    uris[urir].forEach(function (memento) {
      let li = document.createElement('li')
      let a = document.createElement('a')
      a.href = 'memento/' + memento['datetime'] + '/' + urir
      a.appendChild(document.createTextNode(urir))
      dt = document.createTextNode(' (' + memento['datetime'] + ')')

      li.appendChild(a)
      li.appendChild(dt)

      li.setAttribute('data-mime', memento['mime'])
      li.setAttribute('data-status', memento['status'])

      const isHTML = memento['mime'].toLowerCase().startsWith('text/html')
      const isARedirect = memento['status'][0] === '3'
      if (isHTML && !isARedirect) {
        li.setAttribute('data-display', 'default')
      }
      ul.appendChild(li)
    })
  })
}

function showURIs () {
  if (document.getElementById('uriList').childNodes.length === 0) {
    addURIListToDOM() // Prevent multiple adds of the URI list to the DOM
  }

  document.getElementById('memCountListLink').className = ['activated']
  document.getElementById('uris').classList.remove('hidden')
  setPlurality()
  setShowAllButtonStatus()

  setUIExpandedState(uris)
  // Maintain visible state of URI display for future retrieval
  window.localStorage.setItem('showURIs', 'true')
}

function setUIExpandedState (urisObj) {
  const urisHash = calculateURIsHash(urisObj)
  setURIsHash(urisHash)
}

function calculateURIsHash (urisObj) {
  return JSON.stringify(urisObj).hashCode()
}

function getURIsHash () {
  return window.localStorage.getItem('urisHash')
}

function setURIsHash (hashIn) {
  return window.localStorage.setItem('urisHash', hashIn)
}

String.prototype.hashCode = function () {
  let hash = 0
  let i
  let chr
  if (this.length === 0) {
    return hash
  }
  for (i = 0; i < this.length; i++) {
    chr = this.charCodeAt(i)
    hash = ((hash << 5) - hash) + chr
    hash |= 0 // Convert to 32bit integer
  }
  return hash
}

function toggleURIDisplay () {
  if (window.localStorage.getItem('showURIs') === 'true') {
    hideURIs()
  } else {
    showURIs()
  }
}

function addEventListeners () {
  let target = document.getElementById('memCountListLink')
  target.addEventListener('click', toggleURIDisplay, false)

  let showAllInListingButton = document.getElementById('showEmbeddedURI')
  showAllInListingButton.onclick = function showAllURIs () {
    const uriList = document.getElementById('uriList')
    if (this.innerHTML === this.dataset.defaultvalue) {
      this.innerHTML = this.dataset.activatedvalue
      uriList.classList.add('forceDisplay')
    } else {
      this.innerHTML = this.dataset.defaultvalue
      uriList.classList.remove('forceDisplay')
    }
  }

  getIPFSWebUIAddress()
  updateServiceWorkerVersionUI()

  let reinstallServiceWorkerButton = document.getElementById('reinstallServiceWorker')
  reinstallServiceWorkerButton.onclick = reinstallServiceWorker

  setShowURIsVisibility()
}

function setShowURIsVisibility () {
  const previousHash = getURIsHash() + ''
  const newHash = calculateURIsHash(uris) + ''

  if (window.localStorage.getItem('showURIs') && previousHash === newHash) {
    showURIs()
  } else {
    hideURIs()
  }
}

function setPlurality () {
  const htmlFilesPlurality = document.getElementById('htmlPages').innerHTML

  if (htmlFilesPlurality === '1') {
    document.getElementById('htmlPagesPlurality').classList.add('hidden')
  }
}

function setShowAllButtonStatus () {
  const urimCount = document.getElementById('memCountInt').innerHTML
  const htmlFilesPlurality = document.getElementById('htmlPages').innerHTML
  if (urimCount === htmlFilesPlurality) {
    document.getElementById('showEmbeddedURI').setAttribute('disabled', 'disabled')
  }
}

function assignStatusButtonHandlers () {
  let button = document.getElementsByTagName('button')[0]
  if (button.innerHTML === 'Start') {
    button.addEventListener('click', startIPFSDaemon)
  } else {
    button.addEventListener('click', stopIPFSDaemon)
  }
}

function startIPFSDaemon () {
  sendCommandToIPFSDaemon('start')
  this.innerHTML = 'Starting...'
  this.setAttribute('disabled', 'disabled')
}

function stopIPFSDaemon () {
  sendCommandToIPFSDaemon('stop')
  this.innerHTML = 'Stopping...'
  this.setAttribute('disabled', 'disabled')
}

function getIPFSWebUIAddress () {
  const setIPFSWebUILink = function (resp) {
    document.getElementById('webui').setAttribute('href', 'http://' + resp)
  }
  const fail = function () { console.log('fail') }
  const err = function () { console.log('err') }
  makeAnAJAXRequest('/ipwbconfig/openEndedPlaceHolder', setIPFSWebUILink, fail, err)
}

function updateIPFSDaemonButtonUI () {
  window.setTimeout(function () {
    document.location.reload(true)
  }, 4000)
}

function sendCommandToIPFSDaemon (cmd) {
  const failFunction = function () { console.log('Comm w/ ipfs daemon failed.') }
  const errFunction = function () { console.log('Error talking to ipfs daemon.') }
  makeAnAJAXRequest('/ipfsdaemon/' + cmd, updateIPFSDaemonButtonUI,
    failFunction, errFunction)
}

function makeAnAJAXRequest (address, successFunction, failFunction, errorFunction) {
  let xmlhttp = new XMLHttpRequest()

  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === XMLHttpRequest.DONE) {
      if (xmlhttp.status === 200) {
        successFunction(xmlhttp.responseText)
      } else if (xmlhttp.status === 400) {
        failFunction()
      } else {
        errorFunction()
      }
    }
  }

  xmlhttp.open('GET', address, true)
  xmlhttp.send()
}

function injectIPWBJS () {
  registerServiceWorker()
}

function getServiceWorkerVersion () {
  return fetch(self.location.href)
    .then(function (resp) {
      return Promise.resolve(resp.headers.get('Server').split('/')[1])
    })
}

function reinstallServiceWorker () {
  console.log('Deleting old serviceWorker')
  deleteServiceWorker()
  document.getElementById('serviceWorkerVersion').innerHTML = 'Updating...'
  installServiceWorker()
  updateServiceWorkerVersionUI()
}

function deleteServiceWorker () {
  navigator.serviceWorker.getRegistrations().then(function (registrations) {
    for (let registration of registrations) {
      registration.unregister()
    }
  })
}

function updateServiceWorkerVersionUI () {
  getServiceWorkerVersion().then(function (resp) {
    console.log('updating to ...' + resp)
    document.getElementById('serviceWorkerVersion').innerHTML = 'ver. ' + resp
  })
}

function installServiceWorker () {
  let newInstallation = false

  if (navigator.serviceWorker.controller === null) { // Ideally we would use serviceWorker.getRegistration
    newInstallation = true
  }

  navigator.serviceWorker.register('/ipwbassets/serviceWorker.js', {scope: '/'}).then(
    function (registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope)
    }).catch(function (err) {
    console.log('ServiceWorker registration failed: ', err)
  }).then(function (rr) {
    const dt = document.location.href.split('/')[3]
    const viewingMemento = dt.length === 14 && parseInt(dt, 10) + '' === dt

    // Reload the page with processing by the newly installed Service Worker
    if (newInstallation && viewingMemento) {
      document.location.reload()
    }
  })
}

function registerServiceWorker () {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', installServiceWorker)
  } else {
    console.log('Browser does not support Service Worker.')
  }
}

function serviceWorkerUpToDate () {

}

function updateServiceWorker () {

}

function reloadPageFromServiceWorker () {
  console.log('reloading page from serviceWorker!')
}
<commit_msg>Split date from time and position it before URI-R in listing<commit_after>function handleSubmit () {
  let val = document.getElementById('url').value
  if (val) {
    document.location += 'memento/*/' + val
  }
}

function shortestFirst (a, b) {
  return a.length - b.length
}

function hideURIs () {
  document.getElementById('uris').classList.add('hidden')
  document.getElementById('memCountListLink').classList.remove('activated')
  window.localStorage.setItem('showURIs', 'false')
}

function splitDatetime (datetime) {
  return datetime.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1-$2-$3 $4:$5:$6')
}

function addURIListToDOM () {
  let ul = document.getElementById('uriList')
  const uriKeys = Object.keys(uris).sort(shortestFirst)

  uriKeys.forEach(urir => {
    uris[urir].forEach(function (memento) {
      let li = document.createElement('li')
      let a = document.createElement('a')
      a.href = 'memento/' + memento['datetime'] + '/' + urir
      a.appendChild(document.createTextNode(urir))
      dt = document.createTextNode('[' + splitDatetime(memento['datetime']) + '] ')

      li.appendChild(dt)
      li.appendChild(a)

      li.setAttribute('data-mime', memento['mime'])
      li.setAttribute('data-status', memento['status'])

      const isHTML = memento['mime'].toLowerCase().startsWith('text/html')
      const isARedirect = memento['status'][0] === '3'
      if (isHTML && !isARedirect) {
        li.setAttribute('data-display', 'default')
      }
      ul.appendChild(li)
    })
  })
}

function showURIs () {
  if (document.getElementById('uriList').childNodes.length === 0) {
    addURIListToDOM() // Prevent multiple adds of the URI list to the DOM
  }

  document.getElementById('memCountListLink').className = ['activated']
  document.getElementById('uris').classList.remove('hidden')
  setPlurality()
  setShowAllButtonStatus()

  setUIExpandedState(uris)
  // Maintain visible state of URI display for future retrieval
  window.localStorage.setItem('showURIs', 'true')
}

function setUIExpandedState (urisObj) {
  const urisHash = calculateURIsHash(urisObj)
  setURIsHash(urisHash)
}

function calculateURIsHash (urisObj) {
  return JSON.stringify(urisObj).hashCode()
}

function getURIsHash () {
  return window.localStorage.getItem('urisHash')
}

function setURIsHash (hashIn) {
  return window.localStorage.setItem('urisHash', hashIn)
}

String.prototype.hashCode = function () {
  let hash = 0
  let i
  let chr
  if (this.length === 0) {
    return hash
  }
  for (i = 0; i < this.length; i++) {
    chr = this.charCodeAt(i)
    hash = ((hash << 5) - hash) + chr
    hash |= 0 // Convert to 32bit integer
  }
  return hash
}

function toggleURIDisplay () {
  if (window.localStorage.getItem('showURIs') === 'true') {
    hideURIs()
  } else {
    showURIs()
  }
}

function addEventListeners () {
  let target = document.getElementById('memCountListLink')
  target.addEventListener('click', toggleURIDisplay, false)

  let showAllInListingButton = document.getElementById('showEmbeddedURI')
  showAllInListingButton.onclick = function showAllURIs () {
    const uriList = document.getElementById('uriList')
    if (this.innerHTML === this.dataset.defaultvalue) {
      this.innerHTML = this.dataset.activatedvalue
      uriList.classList.add('forceDisplay')
    } else {
      this.innerHTML = this.dataset.defaultvalue
      uriList.classList.remove('forceDisplay')
    }
  }

  getIPFSWebUIAddress()
  updateServiceWorkerVersionUI()

  let reinstallServiceWorkerButton = document.getElementById('reinstallServiceWorker')
  reinstallServiceWorkerButton.onclick = reinstallServiceWorker

  setShowURIsVisibility()
}

function setShowURIsVisibility () {
  const previousHash = getURIsHash() + ''
  const newHash = calculateURIsHash(uris) + ''

  if (window.localStorage.getItem('showURIs') && previousHash === newHash) {
    showURIs()
  } else {
    hideURIs()
  }
}

function setPlurality () {
  const htmlFilesPlurality = document.getElementById('htmlPages').innerHTML

  if (htmlFilesPlurality === '1') {
    document.getElementById('htmlPagesPlurality').classList.add('hidden')
  }
}

function setShowAllButtonStatus () {
  const urimCount = document.getElementById('memCountInt').innerHTML
  const htmlFilesPlurality = document.getElementById('htmlPages').innerHTML
  if (urimCount === htmlFilesPlurality) {
    document.getElementById('showEmbeddedURI').setAttribute('disabled', 'disabled')
  }
}

function assignStatusButtonHandlers () {
  let button = document.getElementsByTagName('button')[0]
  if (button.innerHTML === 'Start') {
    button.addEventListener('click', startIPFSDaemon)
  } else {
    button.addEventListener('click', stopIPFSDaemon)
  }
}

function startIPFSDaemon () {
  sendCommandToIPFSDaemon('start')
  this.innerHTML = 'Starting...'
  this.setAttribute('disabled', 'disabled')
}

function stopIPFSDaemon () {
  sendCommandToIPFSDaemon('stop')
  this.innerHTML = 'Stopping...'
  this.setAttribute('disabled', 'disabled')
}

function getIPFSWebUIAddress () {
  const setIPFSWebUILink = function (resp) {
    document.getElementById('webui').setAttribute('href', 'http://' + resp)
  }
  const fail = function () { console.log('fail') }
  const err = function () { console.log('err') }
  makeAnAJAXRequest('/ipwbconfig/openEndedPlaceHolder', setIPFSWebUILink, fail, err)
}

function updateIPFSDaemonButtonUI () {
  window.setTimeout(function () {
    document.location.reload(true)
  }, 4000)
}

function sendCommandToIPFSDaemon (cmd) {
  const failFunction = function () { console.log('Comm w/ ipfs daemon failed.') }
  const errFunction = function () { console.log('Error talking to ipfs daemon.') }
  makeAnAJAXRequest('/ipfsdaemon/' + cmd, updateIPFSDaemonButtonUI,
    failFunction, errFunction)
}

function makeAnAJAXRequest (address, successFunction, failFunction, errorFunction) {
  let xmlhttp = new XMLHttpRequest()

  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === XMLHttpRequest.DONE) {
      if (xmlhttp.status === 200) {
        successFunction(xmlhttp.responseText)
      } else if (xmlhttp.status === 400) {
        failFunction()
      } else {
        errorFunction()
      }
    }
  }

  xmlhttp.open('GET', address, true)
  xmlhttp.send()
}

function injectIPWBJS () {
  registerServiceWorker()
}

function getServiceWorkerVersion () {
  return fetch(self.location.href)
    .then(function (resp) {
      return Promise.resolve(resp.headers.get('Server').split('/')[1])
    })
}

function reinstallServiceWorker () {
  console.log('Deleting old serviceWorker')
  deleteServiceWorker()
  document.getElementById('serviceWorkerVersion').innerHTML = 'Updating...'
  installServiceWorker()
  updateServiceWorkerVersionUI()
}

function deleteServiceWorker () {
  navigator.serviceWorker.getRegistrations().then(function (registrations) {
    for (let registration of registrations) {
      registration.unregister()
    }
  })
}

function updateServiceWorkerVersionUI () {
  getServiceWorkerVersion().then(function (resp) {
    console.log('updating to ...' + resp)
    document.getElementById('serviceWorkerVersion').innerHTML = 'ver. ' + resp
  })
}

function installServiceWorker () {
  let newInstallation = false

  if (navigator.serviceWorker.controller === null) { // Ideally we would use serviceWorker.getRegistration
    newInstallation = true
  }

  navigator.serviceWorker.register('/ipwbassets/serviceWorker.js', {scope: '/'}).then(
    function (registration) {
      console.log('ServiceWorker registration successful with scope: ', registration.scope)
    }).catch(function (err) {
    console.log('ServiceWorker registration failed: ', err)
  }).then(function (rr) {
    const dt = document.location.href.split('/')[3]
    const viewingMemento = dt.length === 14 && parseInt(dt, 10) + '' === dt

    // Reload the page with processing by the newly installed Service Worker
    if (newInstallation && viewingMemento) {
      document.location.reload()
    }
  })
}

function registerServiceWorker () {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', installServiceWorker)
  } else {
    console.log('Browser does not support Service Worker.')
  }
}

function serviceWorkerUpToDate () {

}

function updateServiceWorker () {

}

function reloadPageFromServiceWorker () {
  console.log('reloading page from serviceWorker!')
}
<|endoftext|>


<commit_before>const config = require('./data/SiteConfig');

const pathPrefix = config.pathPrefix === '/' ? '' : config.pathPrefix;

module.exports = {
  pathPrefix: config.pathPrefix,
  siteMetadata: {
    siteUrl: config.siteUrl + pathPrefix,
    rssMetadata: {
      site_url: config.siteUrl + pathPrefix,
      feed_url: config.siteUrl + pathPrefix + config.siteRss,
      title: config.siteTitle,
      description: config.siteDescription,
      image_url: `${config.siteUrl + pathPrefix}/logos/logo-512.png`,
      author: config.userName,
      copyright: config.copyright,
    },
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-sass',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'docs',
        path: `${__dirname}/content/${config.docsDir}`,
      },
    },
    {
      resolve: 'gatsby-plugin-robots-txt',
      options: {
        host: config.siteUrl + pathPrefix,
        sitemap: `${config.siteUrl + pathPrefix}/sitemap.xml`,
        policy: [{ userAgent: '*', disallow: ['/'] }],
      },
    },
    {
      resolve: 'gatsby-plugin-google-tagmanager',
      options: {
        id: 'GTM-PQC59L',
        includeInDevelopment: false,
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 690,
            },
          },
          {
            resolve: 'gatsby-remark-responsive-iframe',
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          // 'gatsby-remark-autolink-headers',
          'sendgrid-remark-headers',
          'sendgrid-remark-tables',
        ],
      },
    },
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: config.googleAnalyticsID,
      },
    },
    {
      resolve: 'gatsby-plugin-nprogress',
      options: {
        color: config.themeColor,
      },
    },
    'gatsby-plugin-sharp',
    'gatsby-plugin-catch-links',
    // 'gatsby-plugin-sitemap',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        name: config.siteTitle,
        short_name: config.siteTitle,
        description: config.siteDescription,
        start_url: config.pathPrefix,
        background_color: config.backgroundColor,
        theme_color: config.themeColor,
        display: 'minimal-ui',
        icons: [
          {
            src: '/logos/logo-192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: '/logos/logo-512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
        ],
      },
    },
    'gatsby-plugin-offline',
  ],
};
<commit_msg>trigger build<commit_after>const config = require('./data/SiteConfig');

const pathPrefix = config.pathPrefix === '/' ? '' : config.pathPrefix;

module.exports = {
  pathPrefix: config.pathPrefix,
  siteMetadata: {
    siteUrl: config.siteUrl + pathPrefix,
    rssMetadata: {
      site_url: config.siteUrl + pathPrefix,
      feed_url: config.siteUrl + pathPrefix + config.siteRss,
      title: config.siteTitle,
      description: config.siteDescription,
      image_url: `${config.siteUrl + pathPrefix}/logos/logo-512.png`,
      author: config.userName,
      copyright: config.copyright,
    },
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-sass',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'docs',
        path: `${__dirname}/content/${config.docsDir}`,
      },
    },
    {
      resolve: 'gatsby-plugin-robots-txt',
      options: {
        host: config.siteUrl + pathPrefix,
        sitemap: `${config.siteUrl + pathPrefix}/sitemap.xml`,
        policy: [{ userAgent: '*', disallow: ['/'] }],
      },
    },
    {
      resolve: 'gatsby-plugin-google-tagmanager',
      options: {
        id: 'GTM-PQC59L',
        includeInDevelopment: false,
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 690,
            },
          },
          {
            resolve: 'gatsby-remark-responsive-iframe',
          },
          'gatsby-remark-prismjs',
          'gatsby-remark-copy-linked-files',
          // 'gatsby-remark-autolink-headers',
          'sendgrid-remark-headers',
          'sendgrid-remark-tables',
        ],
      },
    },
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: config.googleAnalyticsID,
      },
    },
    {
      resolve: 'gatsby-plugin-nprogress',
      options: {
        color: config.themeColor,
      },
    },
    'gatsby-plugin-sharp',
    'gatsby-plugin-catch-links',
    // 'gatsby-plugin-sitemap',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        name: config.siteTitle,
        short_name: config.siteTitle,
        description: config.siteDescription,
        start_url: config.pathPrefix,
        background_color: config.backgroundColor,
        theme_color: config.themeColor,
        display: 'minimal-ui',
        icons: [
          {
            src: '/logos/logo-192x192.png',
            sizes: '192x192',
            type: 'image/png',
          },
          {
            src: '/logos/logo-512x512.png',
            sizes: '512x512',
            type: 'image/png',
          },
        ],
      },
    },
    'gatsby-plugin-offline',
  ],
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var common = require('./common');
var os = require('os');

//@
//@ ### ln([options,] source, dest)
//@ Available options:
//@
//@ + `-s`: symlink
//@ + `-f`: force
//@
//@ Examples:
//@
//@ ```javascript
//@ ln('file', 'newlink');
//@ ln('-sf', 'file', 'existing');
//@ ```
//@
//@ Links source to dest. Use -f to force the link, should dest already exist.
function _ln(options, source, dest) {
  options = common.parseOptions(options, {
    's': 'symlink',
    'f': 'force'
  });

  if (!source || !dest) {
    common.error('Missing <source> and/or <dest>');
  }

  source = String(source);
  var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), '');
  var isAbsolute = (path.resolve(source) === sourcePath);
  dest = path.resolve(process.cwd(), String(dest));

  if ((isAbsolute && !fs.existsSync(sourcePath)) || !fs.existsSync(path.resolve(process.cwd(), path.dirname(dest), source))) {
    common.error('Source file does not exist', true);
  }

  if (fs.existsSync(dest)) {
    if (!options.force) {
      common.error('Destination file exists', true);
    }

    fs.unlinkSync(dest);
  }

  if (options.symlink) {
    fs.symlinkSync(source, dest, os.platform() === "win32" ? "junction" : null);
  } else {
    fs.linkSync(source, dest, os.platform() === "win32" ? "junction" : null);
  }
}
module.exports = _ln;
<commit_msg>Check that source exists for hard links<commit_after>var fs = require('fs');
var path = require('path');
var common = require('./common');
var os = require('os');

//@
//@ ### ln([options,] source, dest)
//@ Available options:
//@
//@ + `-s`: symlink
//@ + `-f`: force
//@
//@ Examples:
//@
//@ ```javascript
//@ ln('file', 'newlink');
//@ ln('-sf', 'file', 'existing');
//@ ```
//@
//@ Links source to dest. Use -f to force the link, should dest already exist.
function _ln(options, source, dest) {
  options = common.parseOptions(options, {
    's': 'symlink',
    'f': 'force'
  });

  if (!source || !dest) {
    common.error('Missing <source> and/or <dest>');
  }

  source = String(source);
  var sourcePath = path.normalize(source).replace(RegExp(path.sep + '$'), '');
  var isAbsolute = (path.resolve(source) === sourcePath);
  dest = path.resolve(process.cwd(), String(dest));

  if (fs.existsSync(dest)) {
    if (!options.force) {
      common.error('Destination file exists', true);
    }

    fs.unlinkSync(dest);
  }

  if (options.symlink) {
    if ((isAbsolute && !fs.existsSync(sourcePath)) || !fs.existsSync(path.resolve(process.cwd(), path.dirname(dest), source))) {
      common.error('Source file does not exist', true);
    }
    fs.symlinkSync(source, dest, os.platform() === "win32" ? "junction" : null);
  } else {
    if (!fs.existsSync(source)) {
      common.error('Source file does not exist', true);
    }
    fs.linkSync(source, dest, os.platform() === "win32" ? "junction" : null);
  }
}
module.exports = _ln;
<|endoftext|>


<commit_before>require("dotenv").config();
const config = require("./content/meta/config");

const query = `{
  allMarkdownRemark(filter: {id: {regex: "//post|pages//"}}) {
    edges {
      node {
        objectID: id
        fields {
          slug
        }
        frontmatter {
          title
          subTitle
        }
        excerpt
      }
    }
  }
}`;

const queries = [
  {
    query,
    transformer: ({ data }) => data.allMarkdownRemark.edges.map(({ node }) => node)
  }
];

module.exports = {
  siteMetadata: {
    title: config.siteTitle,
    description: config.siteDescription,
    siteUrl: config.siteUrl,
    pathPrefix: config.pathPrefix,
    algolia: {
      appId: process.env.ALGOLIA_APP_ID ? process.env.ALGOLIA_APP_ID : "",
      searchOnlyApiKey: process.env.ALGOLIA_SEARCH_ONLY_API_KEY
        ? process.env.ALGOLIA_SEARCH_ONLY_API_KEY
        : "",
      indexName: process.env.ALGOLIA_INDEX_NAME ? process.env.ALGOLIA_INDEX_NAME : ""
    },
    facebook: {
      appId: process.env.FB_APP_ID ? process.env.FB_APP_ID : ""
    }
  },
  plugins: [
    {
      resolve: `gatsby-plugin-algolia`,
      options: {
        appId: process.env.ALGOLIA_APP_ID ? process.env.ALGOLIA_APP_ID : "",
        apiKey: process.env.ALGOLIA_ADMIN_API_KEY ? process.env.ALGOLIA_ADMIN_API_KEY : "",
        indexName: process.env.ALGOLIA_INDEX_NAME ? process.env.ALGOLIA_INDEX_NAME : "",
        queries: queries,
        chunkSize: 10000 // default: 1000
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/posts/`,
        name: "posts"
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/pages/`,
        name: "pages"
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `parts`,
        path: `${__dirname}/content/parts/`
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-plugin-sharp`,
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 800,
              backgroundColor: "transparent"
            }
          },
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 2em`
            }
          },
          `gatsby-remark-prismjs`,
          `gatsby-remark-copy-linked-files`,
          `gatsby-remark-smartypants`
        ]
      }
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-catch-links`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: config.manifestName,
        short_name: config.manifestShortName,
        start_url: config.manifestStartUrl,
        background_color: config.manifestBackgroundColor,
        theme_color: config.manifestThemeColor,
        display: config.manifestDisplay,
        icons: [
          {
            src: "/icons/icon-48x48.png",
            sizes: "48x48",
            type: "image/png"
          },
          {
            src: "/icons/icon-96x96.png",
            sizes: "96x96",
            type: "image/png"
          },
          {
            src: "/icons/icon-144x144.png",
            sizes: "144x144",
            type: "image/png"
          },
          {
            src: "/icons/icon-192x192.png",
            sizes: "192x192",
            type: "image/png"
          },
          {
            src: "/icons/icon-256x256.png",
            sizes: "256x256",
            type: "image/png"
          },
          {
            src: "/icons/icon-384x384.png",
            sizes: "384x384",
            type: "image/png"
          },
          {
            src: "/icons/icon-512x512.png",
            sizes: "512x512",
            type: "image/png"
          }
        ]
      }
    },
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        query: `
          {
            site {
              siteMetadata {
                title
                description
                siteUrl
                site_url: siteUrl
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.edges.map(edge => {
                return Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.excerpt,
                  url: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  guid: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  custom_elements: [{ "content:encoded": edge.node.html }]
                });
              });
            },
            query: `
              {
                allMarkdownRemark(
                  limit: 1000,
                  sort: { order: DESC, fields: [fields___prefix] },
                  filter: { id: { regex: "//posts//" } }
                ) {
                  edges {
                    node {
                      excerpt
                      html
                      fields {
                        slug
                        prefix
                      }
                      frontmatter {
                        title
                      }
                    }
                  }
                }
              }
            `,
            output: "/rss.xml"
          }
        ]
      }
    },
    {
      resolve: `gatsby-plugin-sitemap`
    },
    {
      resolve: "gatsby-plugin-svgr",
      options: {
        dir: `svg-icons`
      }
    }
  ]
};
<commit_msg>Make the Angolia search index 14000 chars per document instead of 140<commit_after>require("dotenv").config();
const config = require("./content/meta/config");

const query = `{
  allMarkdownRemark(filter: {id: {regex: "//post|pages//"}}) {
    edges {
      node {
        objectID: id
        fields {
          slug
        }
        frontmatter {
          title
          subTitle
        }
        excerpt(pruneLength: 14000)
      }
    }
  }
}`;

const queries = [
  {
    query,
    transformer: ({ data }) => data.allMarkdownRemark.edges.map(({ node }) => node)
  }
];

module.exports = {
  siteMetadata: {
    title: config.siteTitle,
    description: config.siteDescription,
    siteUrl: config.siteUrl,
    pathPrefix: config.pathPrefix,
    algolia: {
      appId: process.env.ALGOLIA_APP_ID ? process.env.ALGOLIA_APP_ID : "",
      searchOnlyApiKey: process.env.ALGOLIA_SEARCH_ONLY_API_KEY
        ? process.env.ALGOLIA_SEARCH_ONLY_API_KEY
        : "",
      indexName: process.env.ALGOLIA_INDEX_NAME ? process.env.ALGOLIA_INDEX_NAME : ""
    },
    facebook: {
      appId: process.env.FB_APP_ID ? process.env.FB_APP_ID : ""
    }
  },
  plugins: [
    {
      resolve: `gatsby-plugin-algolia`,
      options: {
        appId: process.env.ALGOLIA_APP_ID ? process.env.ALGOLIA_APP_ID : "",
        apiKey: process.env.ALGOLIA_ADMIN_API_KEY ? process.env.ALGOLIA_ADMIN_API_KEY : "",
        indexName: process.env.ALGOLIA_INDEX_NAME ? process.env.ALGOLIA_INDEX_NAME : "",
        queries: queries,
        chunkSize: 10000 // default: 1000
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/posts/`,
        name: "posts"
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/content/pages/`,
        name: "pages"
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `parts`,
        path: `${__dirname}/content/parts/`
      }
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          `gatsby-plugin-sharp`,
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 800,
              backgroundColor: "transparent"
            }
          },
          {
            resolve: `gatsby-remark-responsive-iframe`,
            options: {
              wrapperStyle: `margin-bottom: 2em`
            }
          },
          `gatsby-remark-prismjs`,
          `gatsby-remark-copy-linked-files`,
          `gatsby-remark-smartypants`
        ]
      }
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-react-helmet`,
    `gatsby-plugin-catch-links`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: config.manifestName,
        short_name: config.manifestShortName,
        start_url: config.manifestStartUrl,
        background_color: config.manifestBackgroundColor,
        theme_color: config.manifestThemeColor,
        display: config.manifestDisplay,
        icons: [
          {
            src: "/icons/icon-48x48.png",
            sizes: "48x48",
            type: "image/png"
          },
          {
            src: "/icons/icon-96x96.png",
            sizes: "96x96",
            type: "image/png"
          },
          {
            src: "/icons/icon-144x144.png",
            sizes: "144x144",
            type: "image/png"
          },
          {
            src: "/icons/icon-192x192.png",
            sizes: "192x192",
            type: "image/png"
          },
          {
            src: "/icons/icon-256x256.png",
            sizes: "256x256",
            type: "image/png"
          },
          {
            src: "/icons/icon-384x384.png",
            sizes: "384x384",
            type: "image/png"
          },
          {
            src: "/icons/icon-512x512.png",
            sizes: "512x512",
            type: "image/png"
          }
        ]
      }
    },
    {
      resolve: `gatsby-plugin-feed`,
      options: {
        query: `
          {
            site {
              siteMetadata {
                title
                description
                siteUrl
                site_url: siteUrl
              }
            }
          }
        `,
        feeds: [
          {
            serialize: ({ query: { site, allMarkdownRemark } }) => {
              return allMarkdownRemark.edges.map(edge => {
                return Object.assign({}, edge.node.frontmatter, {
                  description: edge.node.excerpt,
                  url: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  guid: site.siteMetadata.siteUrl + edge.node.fields.slug,
                  custom_elements: [{ "content:encoded": edge.node.html }]
                });
              });
            },
            query: `
              {
                allMarkdownRemark(
                  limit: 1000,
                  sort: { order: DESC, fields: [fields___prefix] },
                  filter: { id: { regex: "//posts//" } }
                ) {
                  edges {
                    node {
                      excerpt
                      html
                      fields {
                        slug
                        prefix
                      }
                      frontmatter {
                        title
                      }
                    }
                  }
                }
              }
            `,
            output: "/rss.xml"
          }
        ]
      }
    },
    {
      resolve: `gatsby-plugin-sitemap`
    },
    {
      resolve: "gatsby-plugin-svgr",
      options: {
        dir: `svg-icons`
      }
    }
  ]
};
<|endoftext|>


<commit_before>// Copyright 2013 Michel Kraemer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var Sys = function() {
	this.abbrevsname = "default";
};

function __handleReturnValue__(val) {
	if (val == null) {
		return null;
	}
	var ji = val.toJson(__scriptRunner__.createJsonBuilder());
	if (ji.hasOwnProperty('length')) {
		return JSON.parse(ji);
	}
	return ji;
}

Sys.prototype.retrieveLocale = function(lang) {
	return new String(__localeProvider__.retrieveLocale(lang));
};

Sys.prototype.retrieveItem = function(id) {
	return __handleReturnValue__(__itemDataProvider__.retrieveItem(id));
};

Sys.prototype.getAbbreviation = function(styleID, abbrevs, name, category, orig, itemType) {
	var r = __handleReturnValue__(__abbreviationProvider__.getAbbreviations(this.abbrevsname));
	if (r == null) {
		return;
	}
	if (r[category] && r[category][orig]) {
		abbrevs[name][category][orig] = r[category][orig];
	} else {
		abbrevs[name][category][orig] = "";
	}
};

Sys.prototype.setAbbreviations = function(name) {
	this.abbrevsname = name;
};

Sys = new Sys();
<commit_msg>Really return null if locale does not exist<commit_after>// Copyright 2013 Michel Kraemer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var Sys = function() {
	this.abbrevsname = "default";
};

function __handleReturnValue__(val) {
	if (val == null) {
		return null;
	}
	var ji = val.toJson(__scriptRunner__.createJsonBuilder());
	if (ji.hasOwnProperty('length')) {
		return JSON.parse(ji);
	}
	return ji;
}

Sys.prototype.retrieveLocale = function(lang) {
	var l = __localeProvider__.retrieveLocale(lang);
	if (l == null) {
		return null;
	}
	return new String(l);
};

Sys.prototype.retrieveItem = function(id) {
	return __handleReturnValue__(__itemDataProvider__.retrieveItem(id));
};

Sys.prototype.getAbbreviation = function(styleID, abbrevs, name, category, orig, itemType) {
	var r = __handleReturnValue__(__abbreviationProvider__.getAbbreviations(this.abbrevsname));
	if (r == null) {
		return;
	}
	if (r[category] && r[category][orig]) {
		abbrevs[name][category][orig] = r[category][orig];
	} else {
		abbrevs[name][category][orig] = "";
	}
};

Sys.prototype.setAbbreviations = function(name) {
	this.abbrevsname = name;
};

Sys = new Sys();
<|endoftext|>


<commit_before>(function (angular, _, TL) {
  'use strict';

  function CartController($scope, $timeout, cart) {
    var vm = this,
      initialized = false;
    vm.show = false;
    vm.projects = [];
    vm.remote = [];
    vm.count = 0;
    vm.collapsed = {};
    vm.term = '';

    $scope.$on('cart.update', function () {
      getCart(false);
    });

    function getCart(collapse) {
      cart.all()
        .then(function (data) {
          var prev = vm.count;
          vm.count = 0;
          vm.projects = data.projects;
          vm.remote = data.remote;
          _.each(vm.projects, function (p) {
            vm.count += p.samples.length;
            if (collapse) {
              vm.collapsed[p.id] = true;
            }
          });
          vm.count += vm.getRemoteCount();
          if (collapse) {
            vm.collapsed.remote = true;
          }
          if (initialized && prev !== vm.count) {
            vm.animation = 'glow';
            $timeout(function () {
              vm.animation = '';
            }, 3000);
          } else {
            // This is just to prevent animation on page load.
            initialized = true;
          }
        });
    }

    vm.getRemoteCount = function () {
      return Object.keys(vm.remote).length;
    };

    getCart(true);
  }

  /**
   * Controller for functions on the cart slider
   * @param CartService The cart service to communicate with the server
   */
  function CartSliderController(CartService, $modal) {
    var vm = this;

    vm.clear = function () {
      CartService.clear();
    };

    vm.removeProject = function (projectId) {
      CartService.removeProject(projectId);
    };

    vm.removeRemoteSamples = function () {
      CartService.removeRemoteSamples();
    };

    vm.removeRemoteSample = function (sampleUrl) {
      CartService.removeRemoteSample(sampleUrl);
    };

    vm.removeSample = function (projectId, sampleId) {
      CartService.removeSample(projectId, sampleId);
    };

    vm.exportToGalaxy = function () {
      CartService.all()
        .then(function (data) {
          if (data !== null) {
            var firstProjID = data[0].id;

            $modal.open({
              templateUrl: TL.BASE_URL + 'cart/template/galaxy/project/' + firstProjID,
              controller: 'GalaxyDialogCtrl as gCtrl',
              resolve: {
                openedByCart: function () {
                  return true;
                },
                multiProject: function () {
                  return (data.length > 1);
                }
              }
            });
          }
        });
    };
  }

  function CartDirective() {
    return {
      restrict: 'E',
      templateUrl: '/cart.html',
      replace: true,
      controllerAs: 'cart',
      controller: ['$scope', '$timeout', 'CartService', CartController]
    };
  }

  function CartService(scope, $http, $q) {
    var svc = this,
      urls = {
        all: TL.BASE_URL + 'cart',
        add: TL.BASE_URL + 'cart/add/samples',
        addRemote: TL.BASE_URL + 'cart/add/samples/remote',
        removeRemote: TL.BASE_URL + 'cart/remove/samples/remote',
        project: TL.BASE_URL + 'cart/project/'
      };

    svc.all = function () {
      return $http.get(urls.all)
        .then(function (response) {
          if (response.data) {
            return {projects: response.data.projects, remote: response.data.remote};
          } else {
            return [];
          }
        });
    };

    svc.add = function (samples) {
      var promises = [];

      _.forEach(samples, function (s) {
        if (s.type === 'LOCAL' || s.type === 'ASSOCAITED') {
          promises.push($http.post(urls.add, {projectId: s.project, sampleIds: [s.sample]}));
        } else if (s.type === 'REMOTE') {
          promises.push($http.post(urls.addRemote, {sampleURL: s.sample}));
        }
      });

      $q.all(promises).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.clear = function () {
      //fire a DELETE to the server on the cart then broadcast the cart update event
      return $http.delete(urls.all).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeProject = function (projectId) {
      return $http.delete(urls.project + projectId).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeSample = function (projectId, sampleId) {
      return $http.delete(urls.project + projectId + '/samples/' + sampleId).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeRemoteSamples = function () {
      return $http.delete(urls.removeRemote).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeRemoteSample = function (sampleURL) {
      return $http.post(urls.removeRemote, {sampleURL: sampleURL}).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

  }

  function GalaxyExportService(CartService, StorageService) {
    var svc = this,
      params = {},
      samples = [];

    function initialize(libraryName, email, authCode, redirectURI) {
      params = {
        '_embedded': {
          'library': {'name': libraryName},
          'user': {'email': email},
          'oauth2': {
            'code': authCode,
            'redirect': redirectURI
          },
          'samples': samples
        }
      };
    }

    function addSampleFile(sampleName, sampleFilePath) {
      var sample = _.find(samples, function (sampleItr) {
        return (sampleItr.name === sampleName);
      });
      if (sample === undefined) {
        sample = {
          'name': sampleName,
          '_links': {'self': {'href': ''}}, //expected by the tool
          '_embedded': {'sample_files': []}
        };
        samples.push(sample);
      }
      sample._embedded.sample_files.push({'_links': {'self': {'href': sampleFilePath}}});
    }

    function getSampleFormEntities() {
      var sampleFormEntity = {
        'name': 'json_params',
        'value': JSON.stringify(params)
      };
      return [sampleFormEntity];
    }

    svc.exportFromProjSampPage = function (libraryName, email, authCode, redirectURI) {
      initialize(libraryName, email, authCode, redirectURI);

      var samples = StorageService.getSamples();
      _.each(samples, function (sample) {
        _.each(sample.embedded.sample_files, function (sequenceFile) {
          addSampleFile(sample.sample.label, sequenceFile._links.self.href);
        });
      });
      return getSampleFormEntities();
    };

    svc.exportFromCart = function (libraryName, email, authCode, redirectURI) {
      return CartService.all()
        .then(function (data) {
          initialize(libraryName, email, authCode, redirectURI);
          var projects = data;
          _.each(projects, function (project) {
            var samples = project.samples;
            _.each(samples, function (sample) {
              var sequenceFiles = sample.sequenceFiles;
              _.each(sequenceFiles, function (sequenceFile) {
                addSampleFile(sample.label, sequenceFile.selfRef);
              });
            });
          });
          return getSampleFormEntities();
        });
    };
  }

  function GalaxyDialogCtrl($modalInstance, $timeout, $scope, CartService, GalaxyExportService, openedByCart, multiProject) {
    var vm = this;
    vm.showOauthIframe = false;
    vm.showEmailLibInput = true;
    vm.redirectURI = TL.BASE_URL + 'galaxy/auth_code';

    vm.upload = function () {
      vm.makeOauth2AuthRequest(TL.galaxyClientID);
      vm.showEmailLibInput = false;
      vm.showOauthIframe = true;
    };

    vm.makeOauth2AuthRequest = function (clientID) {
      var request = buildOauth2Request(clientID, 'code', 'read', vm.redirectURI);
      vm.iframeSrc = TL.BASE_URL + 'api/oauth/authorize' + request;
    };

    function buildOauth2Request(clientID, responseType, scope, redirectURI) {
      return '?&client_id=' + clientID + '&response_type=' + responseType + '&scope=' + scope + '&redirect_uri=' + redirectURI;
    }

    $scope.$on('galaxyAuthCode', function (e, authToken) {

      if (authToken) {
        vm.uploading = true;

        vm.showOauthIframe = false;
        vm.showEmailLibInput = true;

        if (openedByCart) {
          GalaxyExportService.exportFromCart(vm.name, vm.email, authToken, vm.redirectURI).then(sendSampleForm);
        } else {
          sendSampleForm(GalaxyExportService.exportFromProjSampPage(vm.name, vm.email, authToken, vm.redirectURI));
        }
      }
    });

    function sendSampleForm(sampleFormEntities) {
      vm.sampleFormEntities = sampleFormEntities;

      if (openedByCart) {
        CartService.clear();
      }

      //$timeout is necessary because it adds a new event to the browser event queue,
      //allowing the full form to be generated before it is submitted.

      //Two timeouts are required now--this is starting to look like a real hack.
      $timeout(function () {
        $timeout(function () {
          document.getElementById('galSubFrm').submit();
          vm.close();
        });
      });
    }

    vm.setName = function (name, orgName) {
      if (multiProject) {
        vm.name = orgName;
      } else {
        vm.name = name;
      }
    };
    vm.setEmail = function (email) {
      vm.email = email;
    };
    vm.close = function () {
      $modalInstance.close();
    };

  }

  /**
   * @name cartFilter
   * @desc Filters the list of projects in the cart based on the term provided in the search input.
   * @type {Filter}
   */
  function CartFilter() {
    /**
     * @param list - list to filter
     * @param term - search term to use to filter the list.
     */
    return function (list, term) {
      //filter each element in the collection
      return _.filter(list, function (item) {
        //if we have a project, check for how many samples we have left
        if (item.samples) {
          return filterList(item.samples, term).length > 0;
        }
        //if we have an individual sample, filter it
        return filterSample(item, term);

      });
    };

    function filterList(samples, term) {
      return _.filter(samples, function (s) {
        return filterSample(s, term);
      });
    }

    function filterSample(item, term) {
      term = term.toLowerCase();
      return item.label.toLowerCase().indexOf(term) > -1;
    }

  }

  angular
    .module('irida.cart', [])
    .service('CartService', ['$rootScope', '$http', '$q', CartService])
    .controller('CartSliderController', ['CartService', '$modal', CartSliderController])
    .controller('GalaxyDialogCtrl', ['$modalInstance', '$timeout', '$scope', 'CartService', 'GalaxyExportService', 'openedByCart', 'multiProject', GalaxyDialogCtrl])
    .service('GalaxyExportService', ['CartService', 'StorageService', GalaxyExportService])
    .directive('cart', [CartDirective])
    .filter('cartFilter', [CartFilter])
  ;
})(window.angular, window._, window.TL);<commit_msg>fixed spelling in cart.  how did it work before?<commit_after>(function (angular, _, TL) {
  'use strict';

  function CartController($scope, $timeout, cart) {
    var vm = this,
      initialized = false;
    vm.show = false;
    vm.projects = [];
    vm.remote = [];
    vm.count = 0;
    vm.collapsed = {};
    vm.term = '';

    $scope.$on('cart.update', function () {
      getCart(false);
    });

    function getCart(collapse) {
      cart.all()
        .then(function (data) {
          var prev = vm.count;
          vm.count = 0;
          vm.projects = data.projects;
          vm.remote = data.remote;
          _.each(vm.projects, function (p) {
            vm.count += p.samples.length;
            if (collapse) {
              vm.collapsed[p.id] = true;
            }
          });
          vm.count += vm.getRemoteCount();
          if (collapse) {
            vm.collapsed.remote = true;
          }
          if (initialized && prev !== vm.count) {
            vm.animation = 'glow';
            $timeout(function () {
              vm.animation = '';
            }, 3000);
          } else {
            // This is just to prevent animation on page load.
            initialized = true;
          }
        });
    }

    vm.getRemoteCount = function () {
      return Object.keys(vm.remote).length;
    };

    getCart(true);
  }

  /**
   * Controller for functions on the cart slider
   * @param CartService The cart service to communicate with the server
   */
  function CartSliderController(CartService, $modal) {
    var vm = this;

    vm.clear = function () {
      CartService.clear();
    };

    vm.removeProject = function (projectId) {
      CartService.removeProject(projectId);
    };

    vm.removeRemoteSamples = function () {
      CartService.removeRemoteSamples();
    };

    vm.removeRemoteSample = function (sampleUrl) {
      CartService.removeRemoteSample(sampleUrl);
    };

    vm.removeSample = function (projectId, sampleId) {
      CartService.removeSample(projectId, sampleId);
    };

    vm.exportToGalaxy = function () {
      CartService.all()
        .then(function (data) {
          if (data !== null) {
            var firstProjID = data[0].id;

            $modal.open({
              templateUrl: TL.BASE_URL + 'cart/template/galaxy/project/' + firstProjID,
              controller: 'GalaxyDialogCtrl as gCtrl',
              resolve: {
                openedByCart: function () {
                  return true;
                },
                multiProject: function () {
                  return (data.length > 1);
                }
              }
            });
          }
        });
    };
  }

  function CartDirective() {
    return {
      restrict: 'E',
      templateUrl: '/cart.html',
      replace: true,
      controllerAs: 'cart',
      controller: ['$scope', '$timeout', 'CartService', CartController]
    };
  }

  function CartService(scope, $http, $q) {
    var svc = this,
      urls = {
        all: TL.BASE_URL + 'cart',
        add: TL.BASE_URL + 'cart/add/samples',
        addRemote: TL.BASE_URL + 'cart/add/samples/remote',
        removeRemote: TL.BASE_URL + 'cart/remove/samples/remote',
        project: TL.BASE_URL + 'cart/project/'
      };

    svc.all = function () {
      return $http.get(urls.all)
        .then(function (response) {
          if (response.data) {
            return {projects: response.data.projects, remote: response.data.remote};
          } else {
            return [];
          }
        });
    };

    svc.add = function (samples) {
      var promises = [];

      _.forEach(samples, function (s) {
        if (s.type === 'LOCAL' || s.type === 'ASSOCIATED') {
          promises.push($http.post(urls.add, {projectId: s.project, sampleIds: [s.sample]}));
        } else if (s.type === 'REMOTE') {
          promises.push($http.post(urls.addRemote, {sampleURL: s.sample}));
        }
      });

      $q.all(promises).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.clear = function () {
      //fire a DELETE to the server on the cart then broadcast the cart update event
      return $http.delete(urls.all).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeProject = function (projectId) {
      return $http.delete(urls.project + projectId).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeSample = function (projectId, sampleId) {
      return $http.delete(urls.project + projectId + '/samples/' + sampleId).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeRemoteSamples = function () {
      return $http.delete(urls.removeRemote).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

    svc.removeRemoteSample = function (sampleURL) {
      return $http.post(urls.removeRemote, {sampleURL: sampleURL}).then(function () {
        scope.$broadcast('cart.update', {});
      });
    };

  }

  function GalaxyExportService(CartService, StorageService) {
    var svc = this,
      params = {},
      samples = [];

    function initialize(libraryName, email, authCode, redirectURI) {
      params = {
        '_embedded': {
          'library': {'name': libraryName},
          'user': {'email': email},
          'oauth2': {
            'code': authCode,
            'redirect': redirectURI
          },
          'samples': samples
        }
      };
    }

    function addSampleFile(sampleName, sampleFilePath) {
      var sample = _.find(samples, function (sampleItr) {
        return (sampleItr.name === sampleName);
      });
      if (sample === undefined) {
        sample = {
          'name': sampleName,
          '_links': {'self': {'href': ''}}, //expected by the tool
          '_embedded': {'sample_files': []}
        };
        samples.push(sample);
      }
      sample._embedded.sample_files.push({'_links': {'self': {'href': sampleFilePath}}});
    }

    function getSampleFormEntities() {
      var sampleFormEntity = {
        'name': 'json_params',
        'value': JSON.stringify(params)
      };
      return [sampleFormEntity];
    }

    svc.exportFromProjSampPage = function (libraryName, email, authCode, redirectURI) {
      initialize(libraryName, email, authCode, redirectURI);

      var samples = StorageService.getSamples();
      _.each(samples, function (sample) {
        _.each(sample.embedded.sample_files, function (sequenceFile) {
          addSampleFile(sample.sample.label, sequenceFile._links.self.href);
        });
      });
      return getSampleFormEntities();
    };

    svc.exportFromCart = function (libraryName, email, authCode, redirectURI) {
      return CartService.all()
        .then(function (data) {
          initialize(libraryName, email, authCode, redirectURI);
          var projects = data;
          _.each(projects, function (project) {
            var samples = project.samples;
            _.each(samples, function (sample) {
              var sequenceFiles = sample.sequenceFiles;
              _.each(sequenceFiles, function (sequenceFile) {
                addSampleFile(sample.label, sequenceFile.selfRef);
              });
            });
          });
          return getSampleFormEntities();
        });
    };
  }

  function GalaxyDialogCtrl($modalInstance, $timeout, $scope, CartService, GalaxyExportService, openedByCart, multiProject) {
    var vm = this;
    vm.showOauthIframe = false;
    vm.showEmailLibInput = true;
    vm.redirectURI = TL.BASE_URL + 'galaxy/auth_code';

    vm.upload = function () {
      vm.makeOauth2AuthRequest(TL.galaxyClientID);
      vm.showEmailLibInput = false;
      vm.showOauthIframe = true;
    };

    vm.makeOauth2AuthRequest = function (clientID) {
      var request = buildOauth2Request(clientID, 'code', 'read', vm.redirectURI);
      vm.iframeSrc = TL.BASE_URL + 'api/oauth/authorize' + request;
    };

    function buildOauth2Request(clientID, responseType, scope, redirectURI) {
      return '?&client_id=' + clientID + '&response_type=' + responseType + '&scope=' + scope + '&redirect_uri=' + redirectURI;
    }

    $scope.$on('galaxyAuthCode', function (e, authToken) {

      if (authToken) {
        vm.uploading = true;

        vm.showOauthIframe = false;
        vm.showEmailLibInput = true;

        if (openedByCart) {
          GalaxyExportService.exportFromCart(vm.name, vm.email, authToken, vm.redirectURI).then(sendSampleForm);
        } else {
          sendSampleForm(GalaxyExportService.exportFromProjSampPage(vm.name, vm.email, authToken, vm.redirectURI));
        }
      }
    });

    function sendSampleForm(sampleFormEntities) {
      vm.sampleFormEntities = sampleFormEntities;

      if (openedByCart) {
        CartService.clear();
      }

      //$timeout is necessary because it adds a new event to the browser event queue,
      //allowing the full form to be generated before it is submitted.

      //Two timeouts are required now--this is starting to look like a real hack.
      $timeout(function () {
        $timeout(function () {
          document.getElementById('galSubFrm').submit();
          vm.close();
        });
      });
    }

    vm.setName = function (name, orgName) {
      if (multiProject) {
        vm.name = orgName;
      } else {
        vm.name = name;
      }
    };
    vm.setEmail = function (email) {
      vm.email = email;
    };
    vm.close = function () {
      $modalInstance.close();
    };

  }

  /**
   * @name cartFilter
   * @desc Filters the list of projects in the cart based on the term provided in the search input.
   * @type {Filter}
   */
  function CartFilter() {
    /**
     * @param list - list to filter
     * @param term - search term to use to filter the list.
     */
    return function (list, term) {
      //filter each element in the collection
      return _.filter(list, function (item) {
        //if we have a project, check for how many samples we have left
        if (item.samples) {
          return filterList(item.samples, term).length > 0;
        }
        //if we have an individual sample, filter it
        return filterSample(item, term);

      });
    };

    function filterList(samples, term) {
      return _.filter(samples, function (s) {
        return filterSample(s, term);
      });
    }

    function filterSample(item, term) {
      term = term.toLowerCase();
      return item.label.toLowerCase().indexOf(term) > -1;
    }

  }

  angular
    .module('irida.cart', [])
    .service('CartService', ['$rootScope', '$http', '$q', CartService])
    .controller('CartSliderController', ['CartService', '$modal', CartSliderController])
    .controller('GalaxyDialogCtrl', ['$modalInstance', '$timeout', '$scope', 'CartService', 'GalaxyExportService', 'openedByCart', 'multiProject', GalaxyDialogCtrl])
    .service('GalaxyExportService', ['CartService', 'StorageService', GalaxyExportService])
    .directive('cart', [CartDirective])
    .filter('cartFilter', [CartFilter])
  ;
})(window.angular, window._, window.TL);<|endoftext|>


<commit_before>var matrix = require('../src/matrix').matrix;
var assert = require('assert');

describe('matrix.transpose', function() {
    it('should transpose an empty matrix', function() {
        var a = [];
        var expected = [];
        var actual = matrix.transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose a non-empty square matrix', function() {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var expected = [[1, 4, 7], [2, 5, 8], [3, 6, 9]];
        var actual = matrix.transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose a non-empty non-square matrix', function() {
        var a = [[1, 2, 3], [4, 5, 6]];
        var expected = [[1, 4], [2, 5], [3, 6]];
        var actual = matrix.transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose a 1-by-n matrix', function() {
        var a = [[1, 2, 3, 4, 5]];
        var expected = [[1], [2], [3], [4], [5]];
        var actual = matrix.transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose an n-by-1 matrix', function() {
        var a = [[1], [2], [3], [4], [5]];
        var expected = [[1, 2, 3, 4, 5]];
        var actual = matrix.transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given an invalid matrix', function() {
        var a = [[1, 2, 3], [4, 5], [7, 8, 9]];
        assert.throws(function() {
            matrix.transpose(a);
        }, matrix.MatrixError, 'Given matrix is invalid.');
    });

    it('should throw MatrixError when not given a matrix', function() {
        var a = 12;
        assert.throws(function() {
            matrix.transpose(a);
        }, matrix.MatrixError, 'No matrix given.');
    });

    it('should be integrated to Array.prototype', function() {
        var expected = true;
        var actual = Array.prototype.hasOwnProperty('transpose');
        assert.equal(expected, actual);
    });

    it('should transpose an array through the Array.prototype property',
        function() {
            var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
            var expected = [[1, 4, 7], [2, 5, 8], [3, 6, 9]];
            var actual = a.transpose();
            assert.deepEqual(expected, actual);
        }
    );
});
<commit_msg>convert tests for matrix.transpose to es2015<commit_after>import { transpose, MatrixError } from '../src/matrix';
import assert from 'assert';

describe('matrix.transpose', () => {
    it('should transpose an empty matrix', () => {
        var a = [];
        var expected = [];
        var actual = transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose a non-empty square matrix', () => {
        var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
        var expected = [[1, 4, 7], [2, 5, 8], [3, 6, 9]];
        var actual = transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose a non-empty non-square matrix', () => {
        var a = [[1, 2, 3], [4, 5, 6]];
        var expected = [[1, 4], [2, 5], [3, 6]];
        var actual = transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose a 1-by-n matrix', () => {
        var a = [[1, 2, 3, 4, 5]];
        var expected = [[1], [2], [3], [4], [5]];
        var actual = transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should transpose an n-by-1 matrix', () => {
        var a = [[1], [2], [3], [4], [5]];
        var expected = [[1, 2, 3, 4, 5]];
        var actual = transpose(a);
        assert.deepEqual(expected, actual);
    });

    it('should throw MatrixError when given an invalid matrix', () => {
        var a = [[1, 2, 3], [4, 5], [7, 8, 9]];
        assert.throws(() => {
            transpose(a);
        }, MatrixError, 'Given matrix is invalid.');
    });

    it('should throw MatrixError when not given a matrix', () => {
        var a = 12;
        assert.throws(() => {
            transpose(a);
        }, MatrixError, 'No matrix given.');
    });

    it('should be integrated to Array.prototype', () => {
        var expected = true;
        var actual = Array.prototype.hasOwnProperty('transpose');
        assert.equal(expected, actual);
    });

    it('should transpose an array through the Array.prototype property',
        () => {
            var a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
            var expected = [[1, 4, 7], [2, 5, 8], [3, 6, 9]];
            var actual = a.transpose();
            assert.deepEqual(expected, actual);
        }
    );
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular.module('chaise.recordEdit', [
        '720kb.datepicker',
        'chaise.alerts',
        'chaise.authen',
        'chaise.delete',
        'chaise.errors',
        'chaise.filters',
        'chaise.modal',
        'chaise.navbar',
        'chaise.record.table',
        'chaise.utils',
        'chaise.validators',
        'chaise.html',
        'ermrestjs',
        'ngCookies',
        'ngMessages',
        'ngSanitize',
        'ui.bootstrap',
        'ui.mask',
        'ui.select'
    ])

    .config(['$cookiesProvider', function($cookiesProvider) {
        $cookiesProvider.defaults.path = '/';
        $cookiesProvider.defaults.secure = true;
    }])

    .run(['ERMrest', 'errorNames', 'ErrorService', 'headInjector', 'recordEditModel', 'Session', 'UiUtils', 'UriUtils', '$log', '$rootScope', '$window', '$cookies',
        function runRecordEditApp(ERMrest, errorNames, ErrorService, headInjector, recordEditModel, Session, UiUtils, UriUtils, $log, $rootScope, $window, $cookies) {

        var session,
            context = { booleanValues: ['', true, false] };

        UriUtils.setOrigin();
        headInjector.addTitle();
        headInjector.addCustomCSS();

        // This is to allow the dropdown button to open at the top/bottom depending on the space available
        UiUtils.setBootstrapDropdownButtonBehavior();
        UriUtils.setLocationChangeHandling();

        try {
            // If defined but false, throw an error
            if (!chaiseConfig.editRecord && chaiseConfig.editRecord !== undefined) {
                var message = 'Chaise is currently configured to disallow editing records. Check the editRecord setting in chaise-config.js.';
                var error = new Error(message);
                error.code = "Record Editing Disabled";

                throw error;
            }

            var ermrestUri = UriUtils.chaiseURItoErmrestURI($window.location);

            context = $rootScope.context = UriUtils.parseURLFragment($window.location, context);
            context.appName = "recordedit";

            Session.getSession().then(function getSession(_session) {
                session = _session;
                ERMrest.appLinkFn(UriUtils.appTagToURL);

                return ERMrest.resolve(ermrestUri, {cid: context.appName});
            }, function sessionFailed() {
                // do nothing but return without a session
                return ERMrest.resolve(ermrestUri, {cid: context.appName});
            }).then(function getReference(reference) {
                $rootScope.reference = ((context.filter && !context.copy) ? reference.contextualize.entryEdit : reference.contextualize.entryCreate);
                $rootScope.reference.session = session;

                $log.info("Reference: ", $rootScope.reference);

                // Case for creating an entity, with prefilled values
                if (context.prefill) {
                    // get the cookie with the prefill value
                    var cookie = $cookies.getObject(context.prefill);
                    if (cookie) {
                        // Update view model
                        recordEditModel.rows[recordEditModel.rows.length - 1][cookie.constraintName] = cookie.rowname;

                        // Update submission model
                        var columnNames = Object.keys(cookie.keys);
                        columnNames.forEach(function(colName) {
                            var colValue = cookie.keys[colName];
                            recordEditModel.submissionRows[recordEditModel.submissionRows.length - 1][colName] = colValue;
                        });
                    }
                    $log.info('Model: ', recordEditModel);
                    // Keep a copy of the initial rows data so that we can see if user has made any changes later
                    recordEditModel.oldRows = angular.copy(recordEditModel.rows);
                    $log.info('Old model.rows:', recordEditModel.oldRows);
                }

                // Case for editing an entity
                if (context.filter) {
                    if ($rootScope.reference.canUpdate) {
                        // check id range before reading?
                        $rootScope.reference.read(1).then(function getPage(page) {
                            $log.info("Page: ", page);

                            if (page.tuples.length < 1) {
                                var filter = context.filter;
                                var noDataMessage = "No entity exists with " + filter.column + filter.operator + filter.value;
                                var noDataError = new Error(noDataMessage);
                                noDataError.code = errorNames.notFound;

                                throw noDataError;
                            }

                            var column, value,
                                tuple = page.tuples[0],
                                values = tuple.values;

                            $rootScope.tuples = page.tuples;
                            $rootScope.displayname = (context.copy ? $rootScope.reference.displayname : tuple.displayname);

                            for (var i = 0; i < $rootScope.reference.columns.length; i++) {
                                column = $rootScope.reference.columns[i];

                                switch (column.type.name) {
                                    case "timestamp":
                                    case "timestamptz":
                                        if (values[i]) {
                                            // Cannot ensure that all timestamp values are formatted in ISO 8601
                                            // TODO: Fix pretty print fn in ermrestjs to return ISO 8601 format instead of toLocaleString?
                                            var ts = moment(values[i]);
                                            value = {
                                                date: ts.format('YYYY-MM-DD'),
                                                time: ts.format('hh:mm:ss'),
                                                meridiem: ts.format('A')
                                            };
                                        } else {
                                            value = {
                                                date: null,
                                                time: null,
                                                meridiem: null
                                            };
                                        }
                                        break;
                                    case "int2":
                                    case "int4":
                                    case "int8":
                                        value = (values[i] ? parseInt(values[i], 10) : '');
                                        break;
                                    case "float4":
                                    case "float8":
                                    case "numeric":
                                        value = (values[i] ? parseFloat(values[i]) : '');
                                        break;
                                    default:
                                        value = values[i];
                                        break;
                                }

                                if (!context.copy || !column.getInputDisabled(context.appContext)) {
                                    recordEditModel.rows[recordEditModel.rows.length - 1][column.name] = value;
                                }
                            }
                            $log.info('Model: ', recordEditModel);
                            // Keep a copy of the initial rows data so that we can see if user has made any changes later
                            recordEditModel.oldRows = angular.copy(recordEditModel.rows);
                        }, function error(response) {
                            $log.warn(response);
                            throw response;
                        }).catch(function readCatch(exception) {
                            ErrorService.errorPopup(exception.message, exception.code, "home page");
                        });
                    } else if (session) {
                        var notAuthorizedMessage = "You are not authorized to Update entities.";
                        var notAuthorizedError = new Error(notAuthorizedMessage);
                        notAuthorizedError.code = errorNames.forbidden;

                        throw notAuthorizedError;
                    } else {
                        var notAuthorizedMessage = "You are not authorized to Update entities.";
                        var notAuthorizedError = new Error(notAuthorizedMessage);

                        notAuthorizedError.code = errorNames.unauthorized;

                        throw notAuthorizedError;
                    }
                } else {
                    if ($rootScope.reference.canCreate) {
                        $rootScope.displayname = $rootScope.reference.displayname;

                        // populate defaults
                        angular.forEach($rootScope.reference.columns, function(column) {
                            if (column.default && typeof column.default !== "function" && !recordEditModel.rows[0][column.name]) {
                                recordEditModel.rows[0][column.name] = column.default;
                            }
                        });

                    } else if (session) {
                        var forbiddenMessage = "You are not authorized to Create entities.";
                        var forbiddenError = new Error(forbiddenMessage);

                        forbiddenError.code = errorNames.forbidden;

                        throw forbiddenError;
                    } else {
                        var notAuthorizedMessage = "You are not authorized to Create entities.";
                        var notAuthorizedError = new Error(notAuthorizedMessage);

                        notAuthorizedError.code = errorNames.unauthorized;

                        throw notAuthorizedError;
                    }
                }
            }, function error(response) {
                $log.warn(response);
                throw response;
            }).catch(function genericCatch(exception) {
                if (exception instanceof ERMrest.UnauthorizedError || exception.code == errorNames.unauthorized) {
                    ErrorService.catchAll(exception);
                } else if (exception.code == errorNames.forbidden) {
                    ErrorService.errorPopup(exception.message, exception.code, "previous page", $window.document.referrer);
                } else {
                    ErrorService.errorPopup(exception.message, exception.code, "home page");
                }
            });
        } catch (exception) {
            ErrorService.errorPopup(exception.message, exception.code, "home page");
        }
    }]);
})();
<commit_msg>added a comment<commit_after>(function() {
    'use strict';

    angular.module('chaise.recordEdit', [
        '720kb.datepicker',
        'chaise.alerts',
        'chaise.authen',
        'chaise.delete',
        'chaise.errors',
        'chaise.filters',
        'chaise.modal',
        'chaise.navbar',
        'chaise.record.table',
        'chaise.utils',
        'chaise.validators',
        'chaise.html',
        'ermrestjs',
        'ngCookies',
        'ngMessages',
        'ngSanitize',
        'ui.bootstrap',
        'ui.mask',
        'ui.select'
    ])

    .config(['$cookiesProvider', function($cookiesProvider) {
        $cookiesProvider.defaults.path = '/';
        $cookiesProvider.defaults.secure = true;
    }])

    .run(['ERMrest', 'errorNames', 'ErrorService', 'headInjector', 'recordEditModel', 'Session', 'UiUtils', 'UriUtils', '$log', '$rootScope', '$window', '$cookies',
        function runRecordEditApp(ERMrest, errorNames, ErrorService, headInjector, recordEditModel, Session, UiUtils, UriUtils, $log, $rootScope, $window, $cookies) {

        var session,
            context = { booleanValues: ['', true, false] };

        UriUtils.setOrigin();
        headInjector.addTitle();
        headInjector.addCustomCSS();

        // This is to allow the dropdown button to open at the top/bottom depending on the space available
        UiUtils.setBootstrapDropdownButtonBehavior();
        UriUtils.setLocationChangeHandling();

        try {
            // If defined but false, throw an error
            if (!chaiseConfig.editRecord && chaiseConfig.editRecord !== undefined) {
                var message = 'Chaise is currently configured to disallow editing records. Check the editRecord setting in chaise-config.js.';
                var error = new Error(message);
                error.code = "Record Editing Disabled";

                throw error;
            }

            var ermrestUri = UriUtils.chaiseURItoErmrestURI($window.location);

            context = $rootScope.context = UriUtils.parseURLFragment($window.location, context);
            context.appName = "recordedit";

            Session.getSession().then(function getSession(_session) {
                session = _session;
                ERMrest.appLinkFn(UriUtils.appTagToURL);

                return ERMrest.resolve(ermrestUri, {cid: context.appName});
            }, function sessionFailed() {
                // do nothing but return without a session
                return ERMrest.resolve(ermrestUri, {cid: context.appName});
            }).then(function getReference(reference) {
                $rootScope.reference = ((context.filter && !context.copy) ? reference.contextualize.entryEdit : reference.contextualize.entryCreate);
                $rootScope.reference.session = session;

                $log.info("Reference: ", $rootScope.reference);

                // Case for creating an entity, with prefilled values
                if (context.prefill) {
                    // get the cookie with the prefill value
                    var cookie = $cookies.getObject(context.prefill);
                    if (cookie) {
                        // Update view model
                        recordEditModel.rows[recordEditModel.rows.length - 1][cookie.constraintName] = cookie.rowname;

                        // Update submission model
                        var columnNames = Object.keys(cookie.keys);
                        columnNames.forEach(function(colName) {
                            var colValue = cookie.keys[colName];
                            recordEditModel.submissionRows[recordEditModel.submissionRows.length - 1][colName] = colValue;
                        });
                    }
                    $log.info('Model: ', recordEditModel);
                    // Keep a copy of the initial rows data so that we can see if user has made any changes later
                    recordEditModel.oldRows = angular.copy(recordEditModel.rows);
                    $log.info('Old model.rows:', recordEditModel.oldRows);
                }

                // Case for editing an entity
                if (context.filter) {
                    if ($rootScope.reference.canUpdate) {
                        // check id range before reading?
                        $rootScope.reference.read(1).then(function getPage(page) {
                            $log.info("Page: ", page);

                            if (page.tuples.length < 1) {
                                var filter = context.filter;
                                var noDataMessage = "No entity exists with " + filter.column + filter.operator + filter.value;
                                var noDataError = new Error(noDataMessage);
                                noDataError.code = errorNames.notFound;

                                throw noDataError;
                            }

                            var column, value,
                                tuple = page.tuples[0],
                                values = tuple.values;

                            $rootScope.tuples = page.tuples;
                            $rootScope.displayname = (context.copy ? $rootScope.reference.displayname : tuple.displayname);

                            for (var i = 0; i < $rootScope.reference.columns.length; i++) {
                                column = $rootScope.reference.columns[i];

                                switch (column.type.name) {
                                    case "timestamp":
                                    case "timestamptz":
                                        if (values[i]) {
                                            // Cannot ensure that all timestamp values are formatted in ISO 8601
                                            // TODO: Fix pretty print fn in ermrestjs to return ISO 8601 format instead of toLocaleString?
                                            var ts = moment(values[i]);
                                            value = {
                                                date: ts.format('YYYY-MM-DD'),
                                                time: ts.format('hh:mm:ss'),
                                                meridiem: ts.format('A')
                                            };
                                        } else {
                                            value = {
                                                date: null,
                                                time: null,
                                                meridiem: null
                                            };
                                        }
                                        break;
                                    case "int2":
                                    case "int4":
                                    case "int8":
                                        value = (values[i] ? parseInt(values[i], 10) : '');
                                        break;
                                    case "float4":
                                    case "float8":
                                    case "numeric":
                                        value = (values[i] ? parseFloat(values[i]) : '');
                                        break;
                                    default:
                                        value = values[i];
                                        break;
                                }

                                if (!context.copy || !column.getInputDisabled(context.appContext)) {
                                    recordEditModel.rows[recordEditModel.rows.length - 1][column.name] = value;
                                }
                            }
                            $log.info('Model: ', recordEditModel);
                            // Keep a copy of the initial rows data so that we can see if user has made any changes later
                            recordEditModel.oldRows = angular.copy(recordEditModel.rows);
                        }, function error(response) {
                            $log.warn(response);
                            throw response;
                        }).catch(function readCatch(exception) {
                            ErrorService.errorPopup(exception.message, exception.code, "home page");
                        });
                    } else if (session) {
                        var notAuthorizedMessage = "You are not authorized to Update entities.";
                        var notAuthorizedError = new Error(notAuthorizedMessage);
                        notAuthorizedError.code = errorNames.forbidden;

                        throw notAuthorizedError;
                    } else {
                        var notAuthorizedMessage = "You are not authorized to Update entities.";
                        var notAuthorizedError = new Error(notAuthorizedMessage);

                        notAuthorizedError.code = errorNames.unauthorized;

                        throw notAuthorizedError;
                    }
                } else {
                    if ($rootScope.reference.canCreate) {
                        $rootScope.displayname = $rootScope.reference.displayname;

                        // populate defaults
                        angular.forEach($rootScope.reference.columns, function(column) {
                            // if column.default == undefined, the second condition would be true so we need to check if column.default is defined
                            // only want to set values in the input fields so make sure it isn't a function
                            // check the recordEditModel to make sure a value wasn't already set based on the prefill condition
                            if (column.default && typeof column.default !== "function" && !recordEditModel.rows[0][column.name]) {
                                recordEditModel.rows[0][column.name] = column.default;
                            }
                        });
                    // if there is a session, user isn't allowed to create
                    } else if (session) {
                        var forbiddenMessage = "You are not authorized to Create entities.";
                        var forbiddenError = new Error(forbiddenMessage);

                        forbiddenError.code = errorNames.forbidden;

                        throw forbiddenError;
                    // user isn't logged in and neds permissions to create
                    } else {
                        var notAuthorizedMessage = "You are not authorized to Create entities.";
                        var notAuthorizedError = new Error(notAuthorizedMessage);

                        notAuthorizedError.code = errorNames.unauthorized;

                        throw notAuthorizedError;
                    }
                }
            }, function error(response) {
                $log.warn(response);
                throw response;
            }).catch(function genericCatch(exception) {
                if (exception instanceof ERMrest.UnauthorizedError || exception.code == errorNames.unauthorized) {
                    ErrorService.catchAll(exception);
                } else if (exception.code == errorNames.forbidden) {
                    ErrorService.errorPopup(exception.message, exception.code, "previous page", $window.document.referrer);
                } else {
                    ErrorService.errorPopup(exception.message, exception.code, "home page");
                }
            });
        } catch (exception) {
            ErrorService.errorPopup(exception.message, exception.code, "home page");
        }
    }]);
})();
<|endoftext|>