<commit_before>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule("bugpack");
var core                = enableModule("core");
var nodejs              = enableModule("nodejs");

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    packageJson: {
        name: "bugunit",
        version: "0.0.14",
        main: "./lib/bug-unit-cli-module.js",
        private: true,
        bin: "bin/bugunit",
        scripts: {
            start: "node ./scripts/bugunit-cli-start.js"
        },
        dependencies: {
            npm: "1.2.x",
            tar: "0.1.x",
            bugpack: "https://s3.amazonaws.com/airbug/bugpack-0.0.5.tgz"
        }
    },
    sourcePaths: [
        "../bugjs/projects/bugjs/js/src",
        "../bugjs/projects/bugfs/js/src",
        "../bugjs/projects/bugflow/js/src",
        '../bugjs/projects/bugtrace/js/src',
        "./projects/bugunit-cli/js/src"
    ],
    scriptPaths: [
        "./projects/bugunit-cli/js/scripts"
    ],
    binPaths: [
        "./projects/bugunit-cli/bin"
    ]
});

//-------------------------------------------------------------------------------
// Declare Tasks
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
// Declare Flows
//-------------------------------------------------------------------------------

// Clean Flow
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local Flow
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths"),
                binPaths: buildProject.getProperty("binPaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        acl: "public-read",
                        encrypt: true
                    }
                });
            },
            properties: {
                bucket: "{{local-bucket}}"
            }
        })
    ])
).makeDefault();

// Prod Flow
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        acl: "public-read",
                        encrypt: true
                    }
                });
            },
            properties: {
                bucket: "{{prod-deploy-bucket}}"
            }
        })
    ])
);<commit_msg>Update production aws bucket in node dependencies<commit_after>//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require("buildbug");

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule("bugpack");
var core                = enableModule("core");
var nodejs              = enableModule("nodejs");

//-------------------------------------------------------------------------------
// Declare Properties
//-------------------------------------------------------------------------------

buildProperties({
    packageJson: {
        name: "bugunit",
        version: "0.0.14",
        main: "./lib/bug-unit-cli-module.js",
        private: true,
        bin: "bin/bugunit",
        scripts: {
            start: "node ./scripts/bugunit-cli-start.js"
        },
        dependencies: {
            npm: "1.2.x",
            tar: "0.1.x",
            bugpack: "https://s3.amazonaws.com/deploy-airbug/bugpack-0.0.5.tgz"
        }
    },
    sourcePaths: [
        "../bugjs/projects/bugjs/js/src",
        "../bugjs/projects/bugfs/js/src",
        "../bugjs/projects/bugflow/js/src",
        '../bugjs/projects/bugtrace/js/src',
        "./projects/bugunit-cli/js/src"
    ],
    scriptPaths: [
        "./projects/bugunit-cli/js/scripts"
    ],
    binPaths: [
        "./projects/bugunit-cli/bin"
    ]
});

//-------------------------------------------------------------------------------
// Declare Tasks
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
// Declare Flows
//-------------------------------------------------------------------------------

// Clean Flow
//-------------------------------------------------------------------------------

buildTarget("clean").buildFlow(
    targetTask("clean")
);

// Local Flow
//-------------------------------------------------------------------------------

buildTarget("local").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths"),
                binPaths: buildProject.getProperty("binPaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        acl: "public-read",
                        encrypt: true
                    }
                });
            },
            properties: {
                bucket: "{{local-bucket}}"
            }
        })
    ])
).makeDefault();

// Prod Flow
//-------------------------------------------------------------------------------

buildTarget("prod").buildFlow(
    series([

        // TODO BRN: This "clean" task is temporary until we"re not modifying the build so much. This also ensures that
        // old source files are removed. We should figure out a better way of doing that.

        targetTask("clean"),
        targetTask("createNodePackage", {
            properties: {
                packageJson: buildProject.getProperty("packageJson"),
                sourcePaths: buildProject.getProperty("sourcePaths")
            }
        }),
        targetTask('generateBugPackRegistry', {
            init: function(task, buildProject, properties) {
                var nodePackage = nodejs.findNodePackage(
                    buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version")
                );
                task.updateProperties({
                    sourceRoot: nodePackage.getBuildPath()
                });
            }
        }),
        targetTask("packNodePackage", {
            properties: {
                packageName: buildProject.getProperty("packageJson.name"),
                packageVersion: buildProject.getProperty("packageJson.version")
            }
        }),
        targetTask("s3PutFile", {
            init: function(task, buildProject, properties) {
                var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("packageJson.name"),
                    buildProject.getProperty("packageJson.version"));
                task.updateProperties({
                    file: packedNodePackage.getFilePath(),
                    options: {
                        acl: "public-read",
                        encrypt: true
                    }
                });
            },
            properties: {
                bucket: "{{prod-deploy-bucket}}"
            }
        })
    ])
);<|endoftext|>


<commit_before>const axios = require('axios')
const cheerio = require('cheerio')
const match = require('match-sorter')

const SEARCH_URI = 'https://myanimelist.net/search/prefix.json'

const getFromBorder = ($, t) => {
  return $(`span:contains("${t}")`).parent().text().trim().split(' ').slice(1).join(' ').split('\n')[0].trim()
}

const parseCharacterOrStaff = (tr, isStaff = false) => {
  return JSON.parse(JSON.stringify({
    link: tr.find('td:nth-child(1)').find('a').attr('href'),
    name: tr.find('td:nth-child(2)').text().trim().split('\n')[0],
    role: tr.find('td:nth-child(2)').text().trim().split('\n')[2].trim(),
    seiyuu: !isStaff ? {
      link: tr.find('td:nth-child(3)').find('a').attr('href'),
      name: tr.find('td:nth-child(3)').find('a').text().trim()
    } : undefined
  }))
}

const getCharactersAndStaff = ($) => {
  const results = {
    characters: [],
    staff: []
  }

  // Characters
  const leftC = $('div.detail-characters-list').first().find('div.left-column')
  const rightC = $('div.detail-characters-list').first().find('div.left-right')

  const nbLeftC = leftC.children('table').length
  const nbRightC = rightC.children('table').length

  // Staff
  const leftS = $('div.detail-characters-list').last().find('div.left-column')
  const rightS = $('div.detail-characters-list').last().find('div.left-right')

  const nbLeftS = leftS.children('table').length
  const nbRightS = rightS.children('table').length

  // Characters
  for (let i = 1; i <= nbLeftC; ++i) {
    results.characters.push(parseCharacterOrStaff(leftC.find(`table:nth-child(${i}) > tbody > tr`)))
  }

  for (let i = 1; i <= nbRightC; ++i) {
    results.characters.push(parseCharacterOrStaff(rightC.find(`table:nth-child(${i}) > tbody > tr`)))
  }

  // Staff
  for (let i = 1; i <= nbLeftS; ++i) {
    results.staff.push(parseCharacterOrStaff(leftS.find(`table:nth-child(${i}) > tbody > tr`), true))
  }

  for (let i = 1; i <= nbRightS; ++i) {
    results.staff.push(parseCharacterOrStaff(rightS.find(`table:nth-child(${i}) > tbody > tr`), true))
  }

  return results
}

const parsePage = (data) => {
  const $ = cheerio.load(data)
  const result = {}

  result.title = $('span[itemprop="name"]').first().text()
  result.synopsis = $('.js-scrollfix-bottom-rel span[itemprop="description"]').text()
  result.picture = $('img.ac').attr('src')

  const staffAndCharacters = getCharactersAndStaff($)
  result.characters = staffAndCharacters.characters
  result.staff = staffAndCharacters.staff

  result.trailer = $('a.iframe.js-fancybox-video.video-unit.promotion').attr('href')

  // Parsing left border.
  result.englishTitle = getFromBorder($, 'English:')
  result.japaneseTitle = getFromBorder($, 'Japanese:')
  result.synonyms = getFromBorder($, 'Synonyms:')
  result.type = getFromBorder($, 'Type:')
  result.episodes = getFromBorder($, 'Episodes:')
  result.status = getFromBorder($, 'Status:')
  result.aired = getFromBorder($, 'Aired:')
  result.premiered = getFromBorder($, 'Premiered:')
  result.broadcast = getFromBorder($, 'Broadcast:')
  result.producers = getFromBorder($, 'Producers:').split(',       ')
  result.studios = getFromBorder($, 'Studios:').split(',       ')
  result.source = getFromBorder($, 'Source:')
  result.genres = getFromBorder($, 'Genres:').split(', ')
  result.duration = getFromBorder($, 'Duration:')
  result.rating = getFromBorder($, 'Rating:')
  result.score = getFromBorder($, 'Score:').split(' ')[0].slice(0, -1)
  result.scoreStats = getFromBorder($, 'Score:').split(' ').slice(1).join(' ').slice(1, -1)
  result.ranked = getFromBorder($, 'Ranked:').slice(0, -1)
  result.popularity = getFromBorder($, 'Popularity:')
  result.members = getFromBorder($, 'Members:')
  result.favorites = getFromBorder($, 'Favorites:')

  return result
}

const getInfoFromURL = (url) => {
  return new Promise((resolve, reject) => {
    if (!url || typeof url !== 'string' || !url.toLocaleLowerCase().includes('myanimelist')) {
      reject(new Error('[Mal-Scraper]: Invalid Url.'))
    }

    axios.get(url)
      .then(({data}) => {
        const res = parsePage(data)
        res.id = +url.split('/').splice(-2, 1)[0]
        resolve(res)
      })
      .catch(/* istanbul ignore next */(err) => reject(err))
  })
}

const getResultsFromSearch = (keyword) => {
  return new Promise((resolve, reject) => {
    if (!keyword) reject(new Error('[Mal-Scraper]: Received no keyword to search.'))

    axios.get(SEARCH_URI, {
      params: {
        type: 'anime',
        keyword
      }
    }).then(({data}) => {
      const items = []

      data.categories.forEach((elem) => {
        elem.items.forEach((item) => {
          items.push(item)
        })
      })

      resolve(items)
    }).catch(/* istanbul ignore next */(err) => {
      reject(err)
    })
  })
}

const getInfoFromName = (name) => {
  return new Promise((resolve, reject) => {
    if (!name || typeof name !== 'string') {
      reject(new Error('[Mal-Scraper]: Invalid name.'))
    }

    getResultsFromSearch(name)
      .then(async (items) => {
        try {
          const bestMacth = match(items, name, { keys: ['name'] })[0]
          const url = bestMacth ? bestMacth.url : items[0].url
          const data = await getInfoFromURL(url)

          data.url = url

          resolve(data)
        } catch (e) {
          /* istanbul ignore next */
          reject(e)
        }
      })
      .catch(/* istanbul ignore next */(err) => reject(err))
  })
}

module.exports = {
  getInfoFromURL,
  getResultsFromSearch,
  getInfoFromName
}
<commit_msg>Fixed a bug where getInfoFromURL would throw an UNESCAPEDCHAR error<commit_after>const axios = require('axios')
const cheerio = require('cheerio')
const match = require('match-sorter')

const SEARCH_URI = 'https://myanimelist.net/search/prefix.json'

const getFromBorder = ($, t) => {
  return $(`span:contains("${t}")`).parent().text().trim().split(' ').slice(1).join(' ').split('\n')[0].trim()
}

const parseCharacterOrStaff = (tr, isStaff = false) => {
  return JSON.parse(JSON.stringify({
    link: tr.find('td:nth-child(1)').find('a').attr('href'),
    name: tr.find('td:nth-child(2)').text().trim().split('\n')[0],
    role: tr.find('td:nth-child(2)').text().trim().split('\n')[2].trim(),
    seiyuu: !isStaff ? {
      link: tr.find('td:nth-child(3)').find('a').attr('href'),
      name: tr.find('td:nth-child(3)').find('a').text().trim()
    } : undefined
  }))
}

const getCharactersAndStaff = ($) => {
  const results = {
    characters: [],
    staff: []
  }

  // Characters
  const leftC = $('div.detail-characters-list').first().find('div.left-column')
  const rightC = $('div.detail-characters-list').first().find('div.left-right')

  const nbLeftC = leftC.children('table').length
  const nbRightC = rightC.children('table').length

  // Staff
  const leftS = $('div.detail-characters-list').last().find('div.left-column')
  const rightS = $('div.detail-characters-list').last().find('div.left-right')

  const nbLeftS = leftS.children('table').length
  const nbRightS = rightS.children('table').length

  // Characters
  for (let i = 1; i <= nbLeftC; ++i) {
    results.characters.push(parseCharacterOrStaff(leftC.find(`table:nth-child(${i}) > tbody > tr`)))
  }

  for (let i = 1; i <= nbRightC; ++i) {
    results.characters.push(parseCharacterOrStaff(rightC.find(`table:nth-child(${i}) > tbody > tr`)))
  }

  // Staff
  for (let i = 1; i <= nbLeftS; ++i) {
    results.staff.push(parseCharacterOrStaff(leftS.find(`table:nth-child(${i}) > tbody > tr`), true))
  }

  for (let i = 1; i <= nbRightS; ++i) {
    results.staff.push(parseCharacterOrStaff(rightS.find(`table:nth-child(${i}) > tbody > tr`), true))
  }

  return results
}

const parsePage = (data) => {
  const $ = cheerio.load(data)
  const result = {}

  result.title = $('span[itemprop="name"]').first().text()
  result.synopsis = $('.js-scrollfix-bottom-rel span[itemprop="description"]').text()
  result.picture = $('img.ac').attr('src')

  const staffAndCharacters = getCharactersAndStaff($)
  result.characters = staffAndCharacters.characters
  result.staff = staffAndCharacters.staff

  result.trailer = $('a.iframe.js-fancybox-video.video-unit.promotion').attr('href')

  // Parsing left border.
  result.englishTitle = getFromBorder($, 'English:')
  result.japaneseTitle = getFromBorder($, 'Japanese:')
  result.synonyms = getFromBorder($, 'Synonyms:')
  result.type = getFromBorder($, 'Type:')
  result.episodes = getFromBorder($, 'Episodes:')
  result.status = getFromBorder($, 'Status:')
  result.aired = getFromBorder($, 'Aired:')
  result.premiered = getFromBorder($, 'Premiered:')
  result.broadcast = getFromBorder($, 'Broadcast:')
  result.producers = getFromBorder($, 'Producers:').split(',       ')
  result.studios = getFromBorder($, 'Studios:').split(',       ')
  result.source = getFromBorder($, 'Source:')
  result.genres = getFromBorder($, 'Genres:').split(', ')
  result.duration = getFromBorder($, 'Duration:')
  result.rating = getFromBorder($, 'Rating:')
  result.score = getFromBorder($, 'Score:').split(' ')[0].slice(0, -1)
  result.scoreStats = getFromBorder($, 'Score:').split(' ').slice(1).join(' ').slice(1, -1)
  result.ranked = getFromBorder($, 'Ranked:').slice(0, -1)
  result.popularity = getFromBorder($, 'Popularity:')
  result.members = getFromBorder($, 'Members:')
  result.favorites = getFromBorder($, 'Favorites:')

  return result
}

const getInfoFromURL = (url) => {
  return new Promise((resolve, reject) => {
    if (!url || typeof url !== 'string' || !url.toLocaleLowerCase().includes('myanimelist')) {
      reject(new Error('[Mal-Scraper]: Invalid Url.'))
    }

    url = encodeURI(url)

    axios.get(url)
      .then(({data}) => {
        const res = parsePage(data)
        res.id = +url.split('/').splice(-2, 1)[0]
        resolve(res)
      })
      .catch(/* istanbul ignore next */(err) => reject(err))
  })
}

const getResultsFromSearch = (keyword) => {
  return new Promise((resolve, reject) => {
    if (!keyword) reject(new Error('[Mal-Scraper]: Received no keyword to search.'))

    axios.get(SEARCH_URI, {
      params: {
        type: 'anime',
        keyword
      }
    }).then(({data}) => {
      const items = []

      data.categories.forEach((elem) => {
        elem.items.forEach((item) => {
          items.push(item)
        })
      })

      resolve(items)
    }).catch(/* istanbul ignore next */(err) => {
      reject(err)
    })
  })
}

const getInfoFromName = (name) => {
  return new Promise((resolve, reject) => {
    if (!name || typeof name !== 'string') {
      reject(new Error('[Mal-Scraper]: Invalid name.'))
    }

    getResultsFromSearch(name)
      .then(async (items) => {
        try {
          const bestMacth = match(items, name, { keys: ['name'] })[0]
          const url = bestMacth ? bestMacth.url : items[0].url
          const data = await getInfoFromURL(url)

          data.url = url

          resolve(data)
        } catch (e) {
          /* istanbul ignore next */
          reject(e)
        }
      })
      .catch(/* istanbul ignore next */(err) => reject(err))
  })
}

module.exports = {
  getInfoFromURL,
  getResultsFromSearch,
  getInfoFromName
}
<|endoftext|>


<commit_before>import Ember from 'ember';

const STATUS_HELP = {
    pending: function(registration) {
        return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!';
    },
    accepted: function(registration) {
        if (registration.directSource) {
            return registration.sourceName + ' have been approved as a source. Start pushing data!';
        }
        return registration.sourceName + ' have been approved as a source but we have not started scraping it yet.';
    },
    implemented: function(registration) {
        return registration.sourceName + ' is now a source. Check it out!';
    },
    rejected: function(registration) {
        return registration.sourceName + ' has been rejected as a source. Contact support@osf.io for additional information.';
    },
};

export default Ember.Component.extend({
    init() {
        this._super(...arguments);
        Ember.run.schedule('afterRender', this, function() {
            this.send('enablePopover');
        });
    },

    colorClass: Ember.computed('registration.data.status', 'registration.data.sourceName', function() {
        return this.getStatusColor(this.get('registration.data'));
    }),

    helpText: Ember.computed('registration.data.status', function() {
        let registration = this.get('registration.data');
        return STATUS_HELP[registration.status](registration);
    }),

    getStatusColor(registration) {
        if (registration.status === 'pending') {
            return 'bg-warning';
        } else if (registration.directSource && registration.status === 'accepted') {
            return 'bg-success';
        } else if (registration.status === 'accepted') {
            return 'bg-info';
        } else if (registration.status === 'implemented') {
            return 'bg-success';
        }
        return 'bg-danger';
    },

    actions: {
        enablePopover() {
            Ember.$('[data-toggle="popover"]').popover();
        }
    }
});
<commit_msg>Fix accepted tooltip grammar (#129)<commit_after>import Ember from 'ember';

const STATUS_HELP = {
    pending: function(registration) {
        return 'The application for ' + registration.sourceName + ' is being reviewed. Check back soon!';
    },
    accepted: function(registration) {
        if (registration.directSource) {
            return registration.sourceName + ' has been approved as a source. Start pushing data!';
        }
        return registration.sourceName + ' has been approved as a source but we have not started scraping it yet.';
    },
    implemented: function(registration) {
        return registration.sourceName + ' is now a source. Check it out!';
    },
    rejected: function(registration) {
        return registration.sourceName + ' has been rejected as a source. Contact support@osf.io for additional information.';
    },
};

export default Ember.Component.extend({
    init() {
        this._super(...arguments);
        Ember.run.schedule('afterRender', this, function() {
            this.send('enablePopover');
        });
    },

    colorClass: Ember.computed('registration.data.status', 'registration.data.sourceName', function() {
        return this.getStatusColor(this.get('registration.data'));
    }),

    helpText: Ember.computed('registration.data.status', function() {
        let registration = this.get('registration.data');
        return STATUS_HELP[registration.status](registration);
    }),

    getStatusColor(registration) {
        if (registration.status === 'pending') {
            return 'bg-warning';
        } else if (registration.directSource && registration.status === 'accepted') {
            return 'bg-success';
        } else if (registration.status === 'accepted') {
            return 'bg-info';
        } else if (registration.status === 'implemented') {
            return 'bg-success';
        }
        return 'bg-danger';
    },

    actions: {
        enablePopover() {
            Ember.$('[data-toggle="popover"]').popover();
        }
    }
});
<|endoftext|>


<commit_before>goog.provide('annotorious.modules.openlayers.OpenLayersAnnotator');

goog.require('goog.dom');
goog.require('goog.style');

/**
 * The OpenLayersAnnotator is responsible for handling annotation functionality
 * on one OpenLayers map in the page.
 * @param {OpenLayers.Map} map the OpenLayers map
 * @constructor
 */
annotorious.modules.openlayers.OpenLayersAnnotator = function(map) {
  /** @private **/
  this._map = map;

  /** @private **/
  this._div = map.div;
  var width = parseInt(goog.style.getComputedStyle(this._div, 'width'));
  var height = parseInt(goog.style.getComputedStyle(this._div, 'height'));

  /** @private **/
  this._eventBroker = new annotorious.events.EventBroker();

  var annotationLayer = goog.dom.createDom('div', 'annotorious-annotationlayer');
  goog.style.setStyle(annotationLayer, 'position', 'relative');
  goog.style.setSize(annotationLayer, width, height);
  goog.dom.replaceNode(annotationLayer, this._div);
  goog.dom.appendChild(annotationLayer, this._div);

  /** @private **/
  var hint = new annotorious.hint.Hint(this, annotationLayer, 'Hold CTRL to Annotate');

  var secondaryHint = goog.soy.renderAsElement(annotorious.templates.openlayers.secondaryHint, {msg: 'Click and Drag'});
  goog.style.setStyle(secondaryHint, 'z-index', 9998);
  goog.style.setOpacity(secondaryHint, 0);
  goog.dom.appendChild(annotationLayer, secondaryHint);

  /** @private **/
  this.popup = new annotorious.viewer.Popup(annotationLayer, this);

  /** @private **/
  this._viewer = new annotorious.modules.openlayers.Viewer(map, this.popup, this);

  /** @private **/
  this._editCanvas = goog.soy.renderAsElement(annotorious.templates.image.canvas,
    { width:width, height:height });
  goog.style.showElement(this._editCanvas, false);
  goog.style.setStyle(this._editCanvas, 'z-index', 9999);
  goog.dom.appendChild(annotationLayer, this._editCanvas);

  /** @private **/
  this._selector = new annotorious.plugins.selection.RectDragSelector();
  this._selector.init(this._editCanvas, this);

  /** @private **/
  this.editor = new annotorious.editor.Editor(this, annotationLayer);
  goog.style.setStyle(this.editor.element, 'z-index', 10000);

  var self = this;
  goog.events.listen(annotationLayer, goog.events.EventType.MOUSEOVER, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(annotationLayer, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OVER_ANNOTATABLE_ITEM);
  });

  goog.events.listen(annotationLayer, goog.events.EventType.MOUSEOUT, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(annotationLayer, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OUT_OF_ANNOTATABLE_ITEM);
  });

  goog.events.listen(document, goog.events.EventType.KEYDOWN, function(event) {
    if (event.keyCode == 17) {
      goog.style.setOpacity(secondaryHint, 0.8);
      goog.style.showElement(self._editCanvas, true);
      window.setTimeout(function() {
        goog.style.setOpacity(secondaryHint, 0);
      }, 2000);
    }
  });

  goog.events.listen(this._editCanvas, goog.events.EventType.MOUSEDOWN, function(event) {
    self._selector.startSelection(event.clientX, event.clientY);
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_COMPLETED, function(event) {
    var bounds = event.viewportBounds;
    self.editor.setPosition({ x: bounds.left + self._div.offsetLeft,
                              y: bounds.bottom + 4 + self._div.offsetTop });
    self.editor.open();
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_CANCELED, function(event) {
    self.stopSelection();
  });
}

/**
 * Standard Annotator method: editAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.editAnnotation = function(annotation) {
  // Step 1 - remove from viewer
  this._viewer.removeAnnotation(annotation);

  // Step 2 - TODO find a suitable selector for the shape
  var selector = this._selector;

  // Step 3 - open annotation in editor
  var self = this;
  if (selector) {
    goog.style.showElement(this._editCanvas, true);
    this._viewer.highlightAnnotation(undefined);

    // TODO make editable - not just draw (selector implementation required)
    var g2d = this._editCanvas.getContext('2d');
    var shape = annotation.shapes[0];
    var viewportShape = annotorious.shape.transform(shape, function(xy) { return self.fromItemCoordinates(xy); });
    selector.drawShape(g2d, viewportShape);
  }

  var bounds = annotorious.shape.getBoundingRect(annotation.shapes[0]);
  var viewportBounds = annotorious.shape.transform(bounds, function(xy) { return self.fromItemCoordinates(xy); });
  this.editor.setPosition({ x: viewportBounds.x + this._div.offsetLeft,
                            y: viewportBounds.y + viewportBounds.height + 4 + this._div.offsetTop });
  this.editor.open(annotation);
}

/**
 * Standard Annotator method: addAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.addAnnotation = function(annotation) {
  this._viewer.addAnnotation(annotation);
}

/**
 * Standard Annotator method: addHandler
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.addHandler = function(type, handler) {
  this._eventBroker.addHandler(type, handler);
}

/**
 * Standard Annotator method: addSelector
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.addSelector = function(selector) {

}

/**
 * Standard Annotator method: fireEvent
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.fireEvent = function(type, event) {
  this._eventBroker.fireEvent(type, event);
}

/**
 * Standard Annotator method: fromItemCoordinates
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.fromItemCoordinates = function(itemCoords) {
  var pxCoords = this._map.getViewPortPxFromLonLat(new OpenLayers.LonLat(itemCoords.x, itemCoords.y));
  return { x: pxCoords.x, y: pxCoords.y };
}

/**
 * Standard Annotator method: getActiveSelector
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getActiveSelector = function() {
  return this._selector;
}

/**
 * Standard Annotator method: getAnnotations
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getAnnotations = function() {

}

/**
 * Standard Annotator method: getAvailableSelectors
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getAvailableSelectors = function() {

}

/**
 * Standard Annotator method: getItem
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getItem = function() {
  // TODO implement something decent!
  return {src: "map://openlayers/something"};
}

/**
 * Standard Annotator method: highlightAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.highlightAnnotation = function(annotation) {
  this._viewer.highlightAnnotation(annotation);
}

/**
 * Standard Annotator method: removeAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.removeAnnotation = function(annotation) {
  this._viewer.removeAnnotation(annotation);
}

/**
 * Standard Annotator method: removeHandler
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.removeHandler = function(type, handler) {
  this._eventBroker.removeHandler(type, handler);
}

/**
 * Standard Annotator method: setActiveSelector
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.setActiveSelector = function(selector) {

}

/**
 * Standard Annotator method: setSelectionEnabled
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.setSelectionEnabled = function(enabled) {

}

/**
 * Standard Annotator method: stopSelection
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.stopSelection = function(original_annotation) {
   goog.style.showElement(this._editCanvas, false);
   this._selector.stopSelection();

   // If this was an edit of an annotation (rather than creation of a new one) re-add to viewer!
   if (original_annotation)
     this._viewer.addAnnotation(original_annotation);
}

/**
 * Standard Annotator method: toItemCoordinates
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.toItemCoordinates = function(xy) {
  var itemCoords = this._map.getLonLatFromPixel(new OpenLayers.Pixel(xy.x, xy.y));
  return { x: itemCoords.lon, y: itemCoords.lat };
}
<commit_msg>OpenLayers: bugfix/optimization<commit_after>goog.provide('annotorious.modules.openlayers.OpenLayersAnnotator');

goog.require('goog.dom');
goog.require('goog.style');

/**
 * The OpenLayersAnnotator is responsible for handling annotation functionality
 * on one OpenLayers map in the page.
 * @param {OpenLayers.Map} map the OpenLayers map
 * @constructor
 */
annotorious.modules.openlayers.OpenLayersAnnotator = function(map) {
  /** @private **/
  this._map = map;

  /** @private **/
  this._div = map.div;
  var width = parseInt(goog.style.getComputedStyle(this._div, 'width'));
  var height = parseInt(goog.style.getComputedStyle(this._div, 'height'));

  /** @private **/
  this._eventBroker = new annotorious.events.EventBroker();

  var annotationLayer = goog.dom.createDom('div', 'annotorious-annotationlayer');
  goog.style.setStyle(annotationLayer, 'position', 'relative');
  goog.style.setSize(annotationLayer, width, height);
  goog.dom.replaceNode(annotationLayer, this._div);
  goog.dom.appendChild(annotationLayer, this._div);

  /** @private **/
  var hint = new annotorious.hint.Hint(this, annotationLayer, 'Hold CTRL to Annotate');

  var secondaryHint = goog.soy.renderAsElement(annotorious.templates.openlayers.secondaryHint, {msg: 'Click and Drag'});
  goog.style.setStyle(secondaryHint, 'z-index', 9998);
  goog.style.setOpacity(secondaryHint, 0);
  goog.dom.appendChild(annotationLayer, secondaryHint);

  /** @private **/
  this.popup = new annotorious.viewer.Popup(annotationLayer, this);

  /** @private **/
  this._viewer = new annotorious.modules.openlayers.Viewer(map, this.popup, this);

  /** @private **/
  this._editCanvas = goog.soy.renderAsElement(annotorious.templates.image.canvas,
    { width:width, height:height });
  goog.style.showElement(this._editCanvas, false);
  goog.style.setStyle(this._editCanvas, 'z-index', 9999);
  goog.dom.appendChild(annotationLayer, this._editCanvas);

  /** @private **/
  this._selector = new annotorious.plugins.selection.RectDragSelector();
  this._selector.init(this._editCanvas, this);

  /** @private **/
  this.editor = new annotorious.editor.Editor(this, annotationLayer);
  goog.style.setStyle(this.editor.element, 'z-index', 10000);

  var self = this;
  goog.events.listen(annotationLayer, goog.events.EventType.MOUSEOVER, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(annotationLayer, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OVER_ANNOTATABLE_ITEM);
  });

  goog.events.listen(annotationLayer, goog.events.EventType.MOUSEOUT, function(event) {
    var relatedTarget = event.relatedTarget;
    if (!relatedTarget || !goog.dom.contains(annotationLayer, relatedTarget))
      self._eventBroker.fireEvent(annotorious.events.EventType.MOUSE_OUT_OF_ANNOTATABLE_ITEM);
  });

  goog.events.listen(document, goog.events.EventType.KEYDOWN, function(event) {
    if (event.keyCode == 17) {
      goog.style.setOpacity(secondaryHint, 0.8);
      goog.style.showElement(self._editCanvas, true);
      window.setTimeout(function() {
        goog.style.setOpacity(secondaryHint, 0);
      }, 2000);
    }
  });

  goog.events.listen(this._editCanvas, goog.events.EventType.MOUSEDOWN, function(event) {
    self._selector.startSelection(event.clientX, event.clientY);
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_COMPLETED, function(event) {
    var bounds = event.viewportBounds;
    self.editor.setPosition({ x: bounds.left + self._div.offsetLeft,
                              y: bounds.bottom + 4 + self._div.offsetTop });
    self.editor.open();
  });

  this._eventBroker.addHandler(annotorious.events.EventType.SELECTION_CANCELED, function(event) {
    self.stopSelection();
  });
}

/**
 * Standard Annotator method: editAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.editAnnotation = function(annotation) {
  // Step 1 - remove from viewer
  this._viewer.removeAnnotation(annotation);

  // Step 2 - TODO find a suitable selector for the shape
  var selector = this._selector;

  // Step 3 - open annotation in editor
  var self = this;
  if (selector) {
    goog.style.showElement(this._editCanvas, true);
    this._viewer.highlightAnnotation(undefined);

    // TODO make editable - not just draw (selector implementation required)
    var g2d = this._editCanvas.getContext('2d');
    var shape = annotation.shapes[0];
    var viewportShape = annotorious.shape.transform(shape, function(xy) { return self.fromItemCoordinates(xy); });
    selector.drawShape(g2d, viewportShape);

    var viewportBounds = annotorious.shape.getBoundingRect(viewportShape).geometry;
    this.editor.setPosition({ x: viewportBounds.x + this._div.offsetLeft,
                            y: viewportBounds.y + viewportBounds.height + 4 + this._div.offsetTop });
    this.editor.open(annotation);
  }
}

/**
 * Standard Annotator method: addAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.addAnnotation = function(annotation) {
  this._viewer.addAnnotation(annotation);
}

/**
 * Standard Annotator method: addHandler
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.addHandler = function(type, handler) {
  this._eventBroker.addHandler(type, handler);
}

/**
 * Standard Annotator method: addSelector
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.addSelector = function(selector) {

}

/**
 * Standard Annotator method: fireEvent
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.fireEvent = function(type, event) {
  this._eventBroker.fireEvent(type, event);
}

/**
 * Standard Annotator method: fromItemCoordinates
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.fromItemCoordinates = function(itemCoords) {
  var pxCoords = this._map.getViewPortPxFromLonLat(new OpenLayers.LonLat(itemCoords.x, itemCoords.y));
  return { x: pxCoords.x, y: pxCoords.y };
}

/**
 * Standard Annotator method: getActiveSelector
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getActiveSelector = function() {
  return this._selector;
}

/**
 * Standard Annotator method: getAnnotations
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getAnnotations = function() {

}

/**
 * Standard Annotator method: getAvailableSelectors
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getAvailableSelectors = function() {

}

/**
 * Standard Annotator method: getItem
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.getItem = function() {
  // TODO implement something decent!
  return {src: "map://openlayers/something"};
}

/**
 * Standard Annotator method: highlightAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.highlightAnnotation = function(annotation) {
  this._viewer.highlightAnnotation(annotation);
}

/**
 * Standard Annotator method: removeAnnotation
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.removeAnnotation = function(annotation) {
  this._viewer.removeAnnotation(annotation);
}

/**
 * Standard Annotator method: removeHandler
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.removeHandler = function(type, handler) {
  this._eventBroker.removeHandler(type, handler);
}

/**
 * Standard Annotator method: setActiveSelector
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.setActiveSelector = function(selector) {

}

/**
 * Standard Annotator method: setSelectionEnabled
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.setSelectionEnabled = function(enabled) {

}

/**
 * Standard Annotator method: stopSelection
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.stopSelection = function(original_annotation) {
   goog.style.showElement(this._editCanvas, false);
   this._selector.stopSelection();

   // If this was an edit of an annotation (rather than creation of a new one) re-add to viewer!
   if (original_annotation)
     this._viewer.addAnnotation(original_annotation);
}

/**
 * Standard Annotator method: toItemCoordinates
 */
annotorious.modules.openlayers.OpenLayersAnnotator.prototype.toItemCoordinates = function(xy) {
  var itemCoords = this._map.getLonLatFromPixel(new OpenLayers.Pixel(xy.x, xy.y));
  return { x: itemCoords.lon, y: itemCoords.lat };
}
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Session } from 'meteor/session';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';

import { wrs } from '/imports/framework/Functions/Async';
import { checkLanguage, logout } from '/imports/framework/Managers/RouteManager.Helpers';

FlowRouter.notFound = {
  action: () => {
    BlazeLayout.render('blankLayout', { content: 'notFound' });
  }
};

FlowRouter.route('/:language/welcome', {
  name: 'welcome',
  triggersEnter: [ checkLanguage ],
  action: () => {
    BlazeLayout.render('blankLayout', { content: 'landing' });
  }
});

FlowRouter.route('/:language/login', {
  name: 'login',
  triggersEnter: [ checkLanguage ],
  action: () => {
    Tracker.autorun((tracker) => {
      if (Meteor.userId()) {
        wrs(() => {
          FlowRouter.go('dashboard.details');
        });
        tracker.stop();
      } else {
        BlazeLayout.render('blankLayout', { content: 'login' });
      }
    });
  }
});

FlowRouter.route('/:language/forgot', {
  name: 'forgotPassword',
  triggersEnter: [ checkLanguage, logout ],
  action: () => {
    Session.set('parent', 'dashboard.details');
    BlazeLayout.render('blankLayout', { content: 'forgotPassword' });
  }
});

FlowRouter.route('/:language/reset', {
  name: 'resetPassword',
  triggersEnter: [ checkLanguage, logout ],
  action: () => {
    Session.set('parent', 'dashboard.details');
    BlazeLayout.render('blankLayout', { content: 'resetPassword' });
  }
});

FlowRouter.route('/:language/firstLogin', {
  name: 'firstLogin',
  triggersEnter: [ checkLanguage, logout ],
  action: () => {
    Session.set('parent', 'dashboard.details');
    BlazeLayout.render('blankLayout', { content: 'firstLogin' });
  }
});
<commit_msg>make oldDashboard default page after login, again; #219<commit_after>import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Session } from 'meteor/session';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';

import { wrs } from '/imports/framework/Functions/Async';
import { checkLanguage, logout } from '/imports/framework/Managers/RouteManager.Helpers';

FlowRouter.notFound = {
  action: () => {
    BlazeLayout.render('blankLayout', { content: 'notFound' });
  }
};

FlowRouter.route('/:language/welcome', {
  name: 'welcome',
  triggersEnter: [ checkLanguage ],
  action: () => {
    BlazeLayout.render('blankLayout', { content: 'landing' });
  }
});

FlowRouter.route('/:language/login', {
  name: 'login',
  triggersEnter: [ checkLanguage ],
  action: () => {
    Tracker.autorun((tracker) => {
      if (Meteor.userId()) {
        wrs(() => FlowRouter.go('home'));
        tracker.stop();
      } else {
        BlazeLayout.render('blankLayout', { content: 'login' });
      }
    });
  }
});

FlowRouter.route('/:language/forgot', {
  name: 'forgotPassword',
  triggersEnter: [ checkLanguage, logout ],
  action: () => {
    Session.set('parent', 'dashboard.details');
    BlazeLayout.render('blankLayout', { content: 'forgotPassword' });
  }
});

FlowRouter.route('/:language/reset', {
  name: 'resetPassword',
  triggersEnter: [ checkLanguage, logout ],
  action: () => {
    Session.set('parent', 'dashboard.details');
    BlazeLayout.render('blankLayout', { content: 'resetPassword' });
  }
});

FlowRouter.route('/:language/firstLogin', {
  name: 'firstLogin',
  triggersEnter: [ checkLanguage, logout ],
  action: () => {
    Session.set('parent', 'dashboard.details');
    BlazeLayout.render('blankLayout', { content: 'firstLogin' });
  }
});
<|endoftext|>


<commit_before>'use strict';

const pug = require('pug');

module.exports.updateIndex = (s3, config) => {
  const html = pug.renderFile('views/index.pug', config.podcast)

  return s3.putObject({
    Bucket:      config.bucket,
    Key:         'index.html',
    Body:        html,
    ContentType: 'text/html; charset=utf-8',
    ACL:         'public-read',
    CacheControl: 'max-age=3600'
  }).promise()
}

module.exports.updateError = (s3, config) => {
  const html = pug.renderFile('views/error.pug', config.podcast)

  return s3.putObject({
    Bucket:      config.bucket,
    Key:         'error.html',
    Body:        html,
    ContentType: 'text/html; charset=utf-8',
    ACL:         'public-read',
    CacheControl: 'max-age=3600'
  }).promise()
}

module.exports.updateFeed = (s3, config, episodes) => {
  const xml = pug.renderFile('views/feed.pug', {
    podcast: config.podcast,
    episodes
  });

  return s3.putObject({
    Bucket: config.bucket,
    Key: 'feed.xml',
    Body: xml,
    ContentType: 'text/xml; charset=utf-8',
    ACL: 'public-read',
    CacheControl: 'max-age=3600'
  }).promise()
}

module.exports.updatePublish = (s3, config, auth) => {
  const html = pug.renderFile('views/publish.pug', { config, auth });

  return s3.putObject({
    Bucket: config.bucket,
    Key: 'publish.html',
    Body: html,
    ContentType: 'text/html; charset=utf-8',
    ACL: 'public-read',
    CacheControl: 'max-age=3600'
  }).promise()
}
<commit_msg>Change CacheControl to no-cache for HTML<commit_after>'use strict';

const pug = require('pug');

module.exports.updateIndex = (s3, config) => {
  const html = pug.renderFile('views/index.pug', config.podcast)

  return s3.putObject({
    Bucket:      config.bucket,
    Key:         'index.html',
    Body:        html,
    ContentType: 'text/html; charset=utf-8',
    ACL:         'public-read',
    CacheControl: 'no-cache'
  }).promise()
}

module.exports.updateError = (s3, config) => {
  const html = pug.renderFile('views/error.pug', config.podcast)

  return s3.putObject({
    Bucket:      config.bucket,
    Key:         'error.html',
    Body:        html,
    ContentType: 'text/html; charset=utf-8',
    ACL:         'public-read',
    CacheControl: 'no-cache'
  }).promise()
}

module.exports.updateFeed = (s3, config, episodes) => {
  const xml = pug.renderFile('views/feed.pug', {
    podcast: config.podcast,
    episodes
  });

  return s3.putObject({
    Bucket: config.bucket,
    Key: 'feed.xml',
    Body: xml,
    ContentType: 'text/xml; charset=utf-8',
    ACL: 'public-read',
    CacheControl: 'no-cache'
  }).promise()
}

module.exports.updatePublish = (s3, config, auth) => {
  const html = pug.renderFile('views/publish.pug', { config, auth });

  return s3.putObject({
    Bucket: config.bucket,
    Key: 'publish.html',
    Body: html,
    ContentType: 'text/html; charset=utf-8',
    ACL: 'public-read',
    CacheControl: 'max-age=3600'
  }).promise()
}
<|endoftext|>


<commit_before>//You really need body parser for things to work correctly
var express = require('express'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    bodyParser = require('body-parser'),
    http = require('http'),
    models = require('../models/models.js'),
    restify = require('express-restify-mongoose'),
    methodOverride = require('method-override');;

mongoose.connect('mongodb://localhost/lcbo');

var InventoryModel = mongoose.model('inventory', models.schema.inventory);
var StoreModel = mongoose.model('store', models.schema.store);

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));

var router = express.Router();
restify.serve(router, InventoryModel);
restify.serve(router, StoreModel);

app.use(router);

app.listen(3000, function() {
    console.log("Express server listening on port 3000");
});<commit_msg>loader done, api for 2 models complete<commit_after>//You really need body parser for things to work correctly
var express = require('express'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    bodyParser = require('body-parser'),
    http = require('http'),
    models = require('../models/models.js'),
    restify = require('express-restify-mongoose'),
    methodOverride = require('method-override');;

mongoose.connect('mongodb://localhost/lcbo');

var InventoryModel = mongoose.model('inventory', models.schema.inventory);
var StoreModel = mongoose.model('store', models.schema.store);
var ProductModel = mongoose.model('product', models.schema.product);

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));

var router = express.Router();
restify.serve(router, InventoryModel);
restify.serve(router, StoreModel);
restify.serve(router, ProductModel);

app.use(router);

app.listen(3000, function() {
    console.log("Express server listening on port 3000");
});<|endoftext|>


<commit_before>define([
    "app/assetmanager",
    "app/audiomanager",
    "app/entitycreator",
    "app/ecs/world",
    "app/ecs/entity",
    "app/systems/animationsystem",
    "app/systems/collisionsystem",
    "app/systems/deathsystem",
    "app/systems/deterioratesystem",
    "app/systems/inputsystem",
    "app/systems/movementsystem",
    "app/systems/rendersystem"
], function(AssetManager, AudioManager, EntityCreator, World, Entity,
            AnimationSystem, CollisionSystem, DeathSystem, DeteriorateSystem,
            InputSystem, MovementSystem, RenderSystem) {
    "use strict";

    const MANIFEST = "assets/configs/manifest.json";
    const PLAYER_COLLISIONS_ENABLED = true;
    const TARGET_FPS = 60;
    const CACHE_LEVEL = true;

    var canvas,
        width,
        height;

    var world,
        assetManager,
        audioManager,
        entityCreator;

    function Game(canvasElement) {
        canvas = canvasElement;
        width = canvasElement.width;
        height = canvasElement.height;

        // Keep aspect ratio and in-game resolution on browser resize
        window.addEventListener("resize", resize, false);
        // Make sure the canvas is initially correct
        resize();
    }

    Game.prototype.start = function() {
        world = new World();
        assetManager = new AssetManager(MANIFEST);
        audioManager = new AudioManager(assetManager);
        entityCreator = new EntityCreator(world, audioManager);

        // Order is important!
        world.addSystem(new DeteriorateSystem());
        world.addSystem(new DeathSystem(entityCreator));
        world.addSystem(new InputSystem(entityCreator));
        world.addSystem(new MovementSystem());
        world.addSystem(new CollisionSystem(PLAYER_COLLISIONS_ENABLED));
        world.addSystem(new AnimationSystem());
        world.addSystem(new RenderSystem(canvas, tick, TARGET_FPS));

        assetManager.load(function() {
            loadLevel();
            loadEntities();
        });
    };

    function loadLevel() {
        var level = assetManager.get("level");
        entityCreator.createLevel(level, CACHE_LEVEL);
    }

    function loadEntities() {
        var controls = assetManager.get("controls");
        loadPlayer("Player 1", "link", 0, 0, controls.keyBindings[0]);
        loadPlayer("Player 2", "alien", 100, 100, controls.keyBindings[1]);
    }

    function loadPlayer(name, assetId, posX, posY, keyBindings) {
        var spriteSheet = assetManager.get(assetId);
        entityCreator.createPlayer(name, posX, posY, spriteSheet, keyBindings);
    }

    function tick(event) {
        world.update(event.delta);
    }

    function resize() {
        var gameWidth = window.innerWidth;
        var gameHeight = window.innerHeight;
        var scaleToFitX = gameWidth / width;
        var scaleToFitY = gameHeight / height;

        var currentScreenRatio = gameWidth / gameHeight;
        var optimalRatio = Math.min(scaleToFitX, scaleToFitY);

        if (currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
            canvas.style.width = gameWidth + "px";
            canvas.style.height = gameHeight + "px";
        }
        else {
            canvas.style.width = width * optimalRatio + "px";
            canvas.style.height = height * optimalRatio + "px";
        }
    }

    return Game;
});<commit_msg>Change initial player positions<commit_after>define([
    "app/assetmanager",
    "app/audiomanager",
    "app/entitycreator",
    "app/ecs/world",
    "app/ecs/entity",
    "app/systems/animationsystem",
    "app/systems/collisionsystem",
    "app/systems/deathsystem",
    "app/systems/deterioratesystem",
    "app/systems/inputsystem",
    "app/systems/movementsystem",
    "app/systems/rendersystem"
], function(AssetManager, AudioManager, EntityCreator, World, Entity,
            AnimationSystem, CollisionSystem, DeathSystem, DeteriorateSystem,
            InputSystem, MovementSystem, RenderSystem) {
    "use strict";

    const MANIFEST = "assets/configs/manifest.json";
    const PLAYER_COLLISIONS_ENABLED = true;
    const TARGET_FPS = 60;
    const CACHE_LEVEL = true;

    var canvas,
        width,
        height;

    var world,
        assetManager,
        audioManager,
        entityCreator;

    function Game(canvasElement) {
        canvas = canvasElement;
        width = canvasElement.width;
        height = canvasElement.height;

        // Keep aspect ratio and in-game resolution on browser resize
        window.addEventListener("resize", resize, false);
        // Make sure the canvas is initially correct
        resize();
    }

    Game.prototype.start = function() {
        world = new World();
        assetManager = new AssetManager(MANIFEST);
        audioManager = new AudioManager(assetManager);
        entityCreator = new EntityCreator(world, audioManager);

        // Order is important!
        world.addSystem(new DeteriorateSystem());
        world.addSystem(new DeathSystem(entityCreator));
        world.addSystem(new InputSystem(entityCreator));
        world.addSystem(new MovementSystem());
        world.addSystem(new CollisionSystem(PLAYER_COLLISIONS_ENABLED));
        world.addSystem(new AnimationSystem());
        world.addSystem(new RenderSystem(canvas, tick, TARGET_FPS));

        assetManager.load(function() {
            loadLevel();
            loadEntities();
        });
    };

    function loadLevel() {
        var level = assetManager.get("level");
        entityCreator.createLevel(level, CACHE_LEVEL);
    }

    function loadEntities() {
        var controls = assetManager.get("controls");
        loadPlayer("Player 1", "link", 100, 500, controls.keyBindings[0]);
        loadPlayer("Player 2", "alien", 900, 350, controls.keyBindings[1]);
    }

    function loadPlayer(name, assetId, posX, posY, keyBindings) {
        var spriteSheet = assetManager.get(assetId);
        entityCreator.createPlayer(name, posX, posY, spriteSheet, keyBindings);
    }

    function tick(event) {
        world.update(event.delta);
    }

    function resize() {
        var gameWidth = window.innerWidth;
        var gameHeight = window.innerHeight;
        var scaleToFitX = gameWidth / width;
        var scaleToFitY = gameHeight / height;

        var currentScreenRatio = gameWidth / gameHeight;
        var optimalRatio = Math.min(scaleToFitX, scaleToFitY);

        if (currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
            canvas.style.width = gameWidth + "px";
            canvas.style.height = gameHeight + "px";
        }
        else {
            canvas.style.width = width * optimalRatio + "px";
            canvas.style.height = height * optimalRatio + "px";
        }
    }

    return Game;
});<|endoftext|>


<commit_before>const del = require('del');
const gulp = require('gulp');
const livereload = require('gulp-livereload');
const path = require('path');

const env = require('tools/gulp/env');

const sources_dir = path.join('sources', 'html');

const sources = (env.isDevelopment
	? path.join(sources_dir, '**/*.html')
	: path.join(sources_dir, 'index.html'));

gulp.task('html-clean', () => del(path.join(env.outputDirectory, 'index.html')));

gulp.task('html', () => gulp.src(sources)
	.pipe(gulp.dest(env.outputDirectory))
	.pipe(livereload())
);

gulp.task('html-watch', ['html'], () => gulp.watch(sources, ['html']));

module.exports = {
	build: 'html',
	clean: 'html-clean',
	watch: 'html-watch'
};
<commit_msg>big refactor to generate changelog<commit_after>const path = require('path');

const del = require('del');

const gulp = require('gulp');
const livereload = require('gulp-livereload');
const metalsmith = require('gulp-metalsmith');

const layouts = require('metalsmith-layouts');
const markdown = require('metalsmith-markdown');
const partialContent = require('tools/metalsmith/partial-content');

const env = require('tools/gulp/env');

const sources_dir = path.join('sources', 'html');

function Task(taskName) {
	const TaskBuilder = (target, ...deps) => function(task) {
		gulp.task(target, deps, task);
		return this;
	};

	const state = {
		build: `html-${taskName}`,
		clean: `html-${taskName}-clean`,
		watch: `html-${taskName}-watch`
	};

	return {
		clean: TaskBuilder(state.clean),
		build: TaskBuilder(state.build, state.clean),
		watch(sources) {
			gulp.task(state.watch, [state.build], () => {
				return gulp.watch(sources, [state.build]);
			});
			return this;
		},
		get tasks() {
			return Object.assign({}, state);
		}
	};
}

const tasks = [];

const game_suffix = 'index.html';
const game_source = path.join(sources_dir, game_suffix);

tasks.push(Task('game')
	.build(() => {
		return gulp
			.src(game_source)
			.pipe(gulp.dest(env.outputDirectory))
			.pipe(livereload());
	})
	.clean(() => del(path.join(env.outputDirectory, game_suffix)))
	.watch(game_source)
	.tasks
);

const changelog_layout_dir = path.join(sources_dir, 'changelog');
const changelog_content_dir = path.join('sources', 'changelogs');
const changelog_sources = [
	path.join(changelog_layout_dir, 'index.md'),
	path.join(changelog_layout_dir, 'index.hbs'),
	path.join(changelog_content_dir, '**/*.md')
];
const changelog_output_dir = path.join(env.outputDirectory, 'changelog');
tasks.push(Task('changelog')
	.build(() => {
		return gulp
			.src(changelog_sources[0])
			.pipe(metalsmith({
				use: [
					markdown(),
					partialContent({
						directory: changelog_content_dir,
						attr: 'changelogs'
					}),
					layouts({
						directory: changelog_layout_dir,
						default: 'index.hbs',
						engine: 'handlebars'
					})
				]
			}))
			.pipe(gulp.dest(changelog_output_dir))
			.pipe(livereload());
	})
	.clean(() => del(path.join(changelog_output_dir, 'index.html')))
	.watch(changelog_sources)
	.tasks
);

if (env.isDevelopment) {
	const editor_suffix = path.join('editor', 'index.html');
	const editor_source = path.join(sources_dir, editor_suffix);
	const editor_output_dir = path.join(env.outputDirectory, 'editor');
	tasks.push(Task('editor')
		.build(() => {
			return gulp
				.src(editor_source)
				.pipe(gulp.dest(editor_output_dir))
				.pipe(livereload());
		})
		.clean(() => {
			return del(path.join(editor_output_dir, editor_suffix));
		})
		.watch(editor_source)
		.tasks
	);
}

module.exports = Object.entries(tasks.reduce((current, task) => {
	return {
		build: current.build.concat(task.build),
		clean: current.clean.concat(task.clean),
		watch: current.watch.concat(task.watch)
	};
}, {
	build: [],
	clean: [],
	watch: []
})).reduce((current, [target, tasks]) => {
	const gulp_target = target === 'build' ? 'html' : `html-${target}`;
	gulp.task(gulp_target, tasks);
	return Object.assign({}, current, {[target]: gulp_target});
}, {});
<|endoftext|>


<commit_before>'use babel';

import _ from 'lodash';

const getTypTemplate = () => (
`/* @flow */
import type {
  ComponentType,
  ComponentPropsType,
  MapStateToPropsType,
  MapDispatchToPropsType
} from 'types/types';

export type OwnProps = {|
  className?: string,
|};

/* set to void if not used*/
export type StateProps = {|
  className: ?string,
|};

/* set to void if not used*/
export type DispatchProps = {|

|};

export type MapStateToProps = MapStateToPropsType<StateProps>;
export type MapDispatchToProps = MapDispatchToPropsType<DispatchProps>;
export type Props = ComponentPropsType<StateProps, DispatchProps>
export type Component = ComponentType<OwnProps>;

`
);

const getContainerTemplate = name => (
`/* @flow */
import { connect } from 'react-redux';
import ${name} from './${name}.cmp';

import type {
  OwnProps,
  MapStateToProps,
  MapDispatchToProps,
  Component
} from './${name}.typ';

const mapStateToProps: MapStateToProps = (state, ownProps: OwnProps) => ({
  className: ownProps.className,
});

const mapDispatchToProps: MapDispatchToProps = dispatch => ({

});

const connector = connect(mapStateToProps, mapDispatchToProps);
const component: Component = connector(${name});

export default component;
`
);

const getComponentTemplate = (name) => {
  const baseComponent = atom.config.get('davs-package.assetPath');
  const importEntity = baseComponent === 'Entity';

  return (
`/* @flow */
import React from 'react';\
${importEntity && '\nimport { Entity } from \'aframe-react\';'}
import type { Props } from './${name}.typ';

const ${name} = (props: Props) => (
  <${baseComponent} className={\`${_.kebabCase(name)} \${props.className || ''}\`}>

</${baseComponent}>
);

export default ${name};
`
  );
};

const getCssTemplate = name => (
`.${_.kebabCase(name)}{}
`
);

const getDuckTemplate = (name) => {
  const rootPath = atom.project.getPaths()[0];
  const projectName = rootPath.split('\\').pop();
  return (
`const ACTION = '${projectName}/${name}/ACTION';

const initialState = {};

const ${name} = (state = initialState, action = {}) => {
  switch (action.type) {
    case ACTION:
      return { ...state };
    default:
      return state;
  }
};

export const action = () => ({
  type: ACTION,
});

export default ${name};
`
  );
};

const getDuckSpecTemplate = name => (
`import ${name}Duck from './${name}';

describe('${name}Duck', () => {
  it('should exist', () => {
    expect(${name}Duck.toBeDefined());
  });
});
`
);

const getServiceTemplate = name => (
`const ${name}Service = {

};

export default ${name}Service;
`
);

const getServiceSpecTemplate = name => (
`import ${name}Service from './${name}';

describe('${name}Service', () => {
  it('should exist', () => {
    expect(${name}Service.toBeDefined());
  });
});
`
);

const templatesService = {
  getTypTemplate,
  getContainerTemplate,
  getComponentTemplate,
  getCssTemplate,
  getDuckTemplate,
  getDuckSpecTemplate,
  getServiceTemplate,
  getServiceSpecTemplate,
};
export default templatesService;
<commit_msg>added spacing before component closing<commit_after>'use babel';

import _ from 'lodash';

const getTypTemplate = () => (
`/* @flow */
import type {
  ComponentType,
  ComponentPropsType,
  MapStateToPropsType,
  MapDispatchToPropsType
} from 'types/types';

export type OwnProps = {|
  className?: string,
|};

/* set to void if not used*/
export type StateProps = {|
  className: ?string,
|};

/* set to void if not used*/
export type DispatchProps = {|

|};

export type MapStateToProps = MapStateToPropsType<StateProps>;
export type MapDispatchToProps = MapDispatchToPropsType<DispatchProps>;
export type Props = ComponentPropsType<StateProps, DispatchProps>
export type Component = ComponentType<OwnProps>;

`
);

const getContainerTemplate = name => (
`/* @flow */
import { connect } from 'react-redux';
import ${name} from './${name}.cmp';

import type {
  OwnProps,
  MapStateToProps,
  MapDispatchToProps,
  Component
} from './${name}.typ';

const mapStateToProps: MapStateToProps = (state, ownProps: OwnProps) => ({
  className: ownProps.className,
});

const mapDispatchToProps: MapDispatchToProps = dispatch => ({

});

const connector = connect(mapStateToProps, mapDispatchToProps);
const component: Component = connector(${name});

export default component;
`
);

const getComponentTemplate = (name) => {
  const baseComponent = atom.config.get('davs-package.baseComponent');
  const importEntity = baseComponent === 'Entity';

  return (
`/* @flow */
import React from 'react';\
${importEntity && '\nimport { Entity } from \'aframe-react\';'}
import type { Props } from './${name}.typ';

const ${name} = (props: Props) => (
  <${baseComponent} className={\`${_.kebabCase(name)} \${props.className || ''}\`}>

  </${baseComponent}>
);

export default ${name};
`
  );
};

const getCssTemplate = name => (
`.${_.kebabCase(name)}{}
`
);

const getDuckTemplate = (name) => {
  const rootPath = atom.project.getPaths()[0];
  const projectName = rootPath.split('\\').pop();
  return (
`const ACTION = '${projectName}/${name}/ACTION';

const initialState = {};

const ${name} = (state = initialState, action = {}) => {
  switch (action.type) {
    case ACTION:
      return { ...state };
    default:
      return state;
  }
};

export const action = () => ({
  type: ACTION,
});

export default ${name};
`
  );
};

const getDuckSpecTemplate = name => (
`import ${name}Duck from './${name}';

describe('${name}Duck', () => {
  it('should exist', () => {
    expect(${name}Duck.toBeDefined());
  });
});
`
);

const getServiceTemplate = name => (
`const ${name}Service = {

};

export default ${name}Service;
`
);

const getServiceSpecTemplate = name => (
`import ${name}Service from './${name}';

describe('${name}Service', () => {
  it('should exist', () => {
    expect(${name}Service.toBeDefined());
  });
});
`
);

const templatesService = {
  getTypTemplate,
  getContainerTemplate,
  getComponentTemplate,
  getCssTemplate,
  getDuckTemplate,
  getDuckSpecTemplate,
  getServiceTemplate,
  getServiceSpecTemplate,
};
export default templatesService;
<|endoftext|>


<commit_before>/****************************************************************************
 Copyright (c) 2013 cocos2d-x.org

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS();     }, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

var s_testArray = [
    {
        title: "UIButtonTest",
        func: function () {
            return new UIButtonTest();
        }
    },
    {
        title: "UIButtonTest_Scale9",
        func: function () {
            return new UIButtonTest_Scale9();
        }
    },
    {
        title: "UIButtonTest_PressedAction",
        func: function () {
            return new UIButtonTest_PressedAction();
        }
    },
    {
        title: "UIButtonTest_Title",
        func: function () {
            return new UIButtonTest_Title();
        }
    },
    {
        title: "UICheckBoxTest",
        func: function () {
            return new UICheckBoxTest();
        }
    },
    {
        title: "UISliderTest",
        func: function () {
            return new UISliderTest();
        }
    },
    {
        title: "UISliderTest_Scale9",
        func: function () {
            return new UISliderTest_Scale9();
        }
    },
    {
        title: "UIImageViewTest",
        func: function () {
            return new UIImageViewTest();
        }
    },
    {
        title: "UIImageViewTest_Scale9",
        func: function () {
            return new UIImageViewTest_Scale9();
        }
    },
    {
        title: "UILoadingBarTest_Left",
        func: function () {
            return new UILoadingBarTest_Left();
        }
    },
    {
        title: "UILoadingBarTest_Right",
        func: function () {
            return new UILoadingBarTest_Right();
        }
    },
    {
        title: "UILoadingBarTest_Left_Scale9",
        func: function () {
            return new UILoadingBarTest_Left_Scale9();
        }
    },
    {
        title: "UILoadingBarTest_Right_Scale9",
        func: function () {
            return new UILoadingBarTest_Right_Scale9();
        }
    },
    {
        title: "UILabelAtlasTest",
        func: function () {
            return new UILabelAtlasTest();
        }
    },
    {
        title: "UILabelTest",
        func: function () {
            return new UILabelTest();
        }
    },
    {
        title: "UILabelTest_LineWrap",
        func: function () {
            return new UILabelTest_LineWrap();
        }
    },
    {
        title: "UILabelBMFontTest",
        func: function () {
            return new UILabelBMFontTest();
        }
    },
    {
        title: "UITextFieldTest",
        func: function () {
            return new UITextFieldTest();
        }
    },
    {
        title: "UITextFieldTest_MaxLength",
        func: function () {
            return new UITextFieldTest_MaxLength();
        }
    },
    {
        title: "UITextFieldTest_Password",
        func: function () {
            return new UITextFieldTest_Password();
        }
    },
    {
        title: "UILayoutTest",
        func: function () {
            return new UILayoutTest();
        }
    },
    {
        title: "UILayoutTest_Color",
        func: function () {
            return new UILayoutTest_Color();
        }
    },
    {
        title: "UILayoutTest_Gradient", func: function () {
        return new UILayoutTest_Gradient();
    }
    },
    {
        title: "UILayoutTest_BackGroundImage",
        func: function () {
            return new UILayoutTest_BackGroundImage();
        }
    },
    {
        title: "UILayoutTest_BackGroundImage_Scale9",
        func: function () {
            return new UILayoutTest_BackGroundImage_Scale9();
        }
    },
    {
        title: "UILayoutTest_Layout_Linear_Vertical",
        func: function () {
            return new UILayoutTest_Layout_Linear_Vertical();
        }
    },
    {
        title: "UILayoutTest_Layout_Linear_Horizontal",
        func: function () {
            return new UILayoutTest_Layout_Linear_Horizontal();
        }
    },
    {
        title: "UIScrollViewTest_Vertical",
        func: function () {
            return new UIScrollViewTest_Vertical();
        }
    },
    {
        title: "UIScrollViewTest_Horizontal",
        func: function () {
            return new UIScrollViewTest_Horizontal();
        }
    },
    {
        title: "UIScrollViewTest_Both",
        func: function () {
            return new UIScrollViewTest_Both();
        }
    },
    {
        title: "UIScrollViewTest_ScrollToPercentBothDirection",
        func: function () {
            return new UIScrollViewTest_ScrollToPercentBothDirection();
        }
    },
    {
        title: "UIScrollViewTest_ScrollToPercentBothDirection_Bounce",
        func: function () {
            return new UIScrollViewTest_ScrollToPercentBothDirection_Bounce();
        }
    },
    {
        title: "UIPageViewTest",
        func: function () {
            return new UIPageViewTest();
        }
    },
    {
        title: "UIListViewTest_Vertical",
        func: function () {
            return new UIListViewTest_Vertical();
        }
    },
    {
        title: "UIListViewTest_Horizontal",
        func: function () {
            return new UIListViewTest_Horizontal();
        }
    },
    {
        title: "UIWidgetAddNodeTest",
        func: function () {
            return new UIWidgetAddNodeTest();
        }
    },
    {
        title: "UIRichTextTest",
        func: function () {
            return new UIRichTextTest();
        }
    }
];
UISceneManager = cc.Class.extend({
    _currentUISceneId: 0,
    ctor: function () {
        this._currentUISceneId = 0;
    },
    nextUIScene: function () {
        this._currentUISceneId++;
        if (this._currentUISceneId > s_testArray.length - 1) {
            this._currentUISceneId = 0;
        }
        return this.currentUIScene();
    },
    previousUIScene: function () {
        this._currentUISceneId--;
        if (this._currentUISceneId < 0) {
            this._currentUISceneId = s_testArray.length - 1;
        }
        return this.currentUIScene();
    },
    currentUIScene: function () {
        var test = s_testArray[this._currentUISceneId];
        var sence = test.func();
        sence.init();
        sence.setSceneTitle(test.title);
        return sence;
    }
});
UISceneManager._instance = null;
UISceneManager.getInstance = function () {
    if (!this._instance) {
        this._instance = new UISceneManager();
    }
    return this._instance;
};
UISceneManager.purge = function () {
    this._instance = null;
};

GUITestScene = cc.Class.extend({
    runThisTest:function () {
        var manager = UISceneManager.getInstance();
        var scene = manager.currentUIScene();
        cc.director.runScene(scene);
    }
});
<commit_msg>Issue #4294: Remove RichText test in JSB<commit_after>/****************************************************************************
 Copyright (c) 2013 cocos2d-x.org

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS();     }, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/

var s_testArray = [
    {
        title: "UIButtonTest",
        func: function () {
            return new UIButtonTest();
        }
    },
    {
        title: "UIButtonTest_Scale9",
        func: function () {
            return new UIButtonTest_Scale9();
        }
    },
    {
        title: "UIButtonTest_PressedAction",
        func: function () {
            return new UIButtonTest_PressedAction();
        }
    },
    {
        title: "UIButtonTest_Title",
        func: function () {
            return new UIButtonTest_Title();
        }
    },
    {
        title: "UICheckBoxTest",
        func: function () {
            return new UICheckBoxTest();
        }
    },
    {
        title: "UISliderTest",
        func: function () {
            return new UISliderTest();
        }
    },
    {
        title: "UISliderTest_Scale9",
        func: function () {
            return new UISliderTest_Scale9();
        }
    },
    {
        title: "UIImageViewTest",
        func: function () {
            return new UIImageViewTest();
        }
    },
    {
        title: "UIImageViewTest_Scale9",
        func: function () {
            return new UIImageViewTest_Scale9();
        }
    },
    {
        title: "UILoadingBarTest_Left",
        func: function () {
            return new UILoadingBarTest_Left();
        }
    },
    {
        title: "UILoadingBarTest_Right",
        func: function () {
            return new UILoadingBarTest_Right();
        }
    },
    {
        title: "UILoadingBarTest_Left_Scale9",
        func: function () {
            return new UILoadingBarTest_Left_Scale9();
        }
    },
    {
        title: "UILoadingBarTest_Right_Scale9",
        func: function () {
            return new UILoadingBarTest_Right_Scale9();
        }
    },
    {
        title: "UILabelAtlasTest",
        func: function () {
            return new UILabelAtlasTest();
        }
    },
    {
        title: "UILabelTest",
        func: function () {
            return new UILabelTest();
        }
    },
    {
        title: "UILabelTest_LineWrap",
        func: function () {
            return new UILabelTest_LineWrap();
        }
    },
    {
        title: "UILabelBMFontTest",
        func: function () {
            return new UILabelBMFontTest();
        }
    },
    {
        title: "UITextFieldTest",
        func: function () {
            return new UITextFieldTest();
        }
    },
    {
        title: "UITextFieldTest_MaxLength",
        func: function () {
            return new UITextFieldTest_MaxLength();
        }
    },
    {
        title: "UITextFieldTest_Password",
        func: function () {
            return new UITextFieldTest_Password();
        }
    },
    {
        title: "UILayoutTest",
        func: function () {
            return new UILayoutTest();
        }
    },
    {
        title: "UILayoutTest_Color",
        func: function () {
            return new UILayoutTest_Color();
        }
    },
    {
        title: "UILayoutTest_Gradient", func: function () {
        return new UILayoutTest_Gradient();
    }
    },
    {
        title: "UILayoutTest_BackGroundImage",
        func: function () {
            return new UILayoutTest_BackGroundImage();
        }
    },
    {
        title: "UILayoutTest_BackGroundImage_Scale9",
        func: function () {
            return new UILayoutTest_BackGroundImage_Scale9();
        }
    },
    {
        title: "UILayoutTest_Layout_Linear_Vertical",
        func: function () {
            return new UILayoutTest_Layout_Linear_Vertical();
        }
    },
    {
        title: "UILayoutTest_Layout_Linear_Horizontal",
        func: function () {
            return new UILayoutTest_Layout_Linear_Horizontal();
        }
    },
    {
        title: "UIScrollViewTest_Vertical",
        func: function () {
            return new UIScrollViewTest_Vertical();
        }
    },
    {
        title: "UIScrollViewTest_Horizontal",
        func: function () {
            return new UIScrollViewTest_Horizontal();
        }
    },
    {
        title: "UIScrollViewTest_Both",
        func: function () {
            return new UIScrollViewTest_Both();
        }
    },
    {
        title: "UIScrollViewTest_ScrollToPercentBothDirection",
        func: function () {
            return new UIScrollViewTest_ScrollToPercentBothDirection();
        }
    },
    {
        title: "UIScrollViewTest_ScrollToPercentBothDirection_Bounce",
        func: function () {
            return new UIScrollViewTest_ScrollToPercentBothDirection_Bounce();
        }
    },
    {
        title: "UIPageViewTest",
        func: function () {
            return new UIPageViewTest();
        }
    },
    {
        title: "UIListViewTest_Vertical",
        func: function () {
            return new UIListViewTest_Vertical();
        }
    },
    {
        title: "UIListViewTest_Horizontal",
        func: function () {
            return new UIListViewTest_Horizontal();
        }
    },
    {
        title: "UIWidgetAddNodeTest",
        func: function () {
            return new UIWidgetAddNodeTest();
        }
    }
];
if (!cc.sys.isNative) {
	s_testArray.push(
		{
			title: "UIRichTextTest",
			func: function () {
				return new UIRichTextTest();
			}
		}
	);
}

UISceneManager = cc.Class.extend({
    _currentUISceneId: 0,
    ctor: function () {
        this._currentUISceneId = 0;
    },
    nextUIScene: function () {
        this._currentUISceneId++;
        if (this._currentUISceneId > s_testArray.length - 1) {
            this._currentUISceneId = 0;
        }
        return this.currentUIScene();
    },
    previousUIScene: function () {
        this._currentUISceneId--;
        if (this._currentUISceneId < 0) {
            this._currentUISceneId = s_testArray.length - 1;
        }
        return this.currentUIScene();
    },
    currentUIScene: function () {
        var test = s_testArray[this._currentUISceneId];
        var sence = test.func();
        sence.init();
        sence.setSceneTitle(test.title);
        return sence;
    }
});
UISceneManager._instance = null;
UISceneManager.getInstance = function () {
    if (!this._instance) {
        this._instance = new UISceneManager();
    }
    return this._instance;
};
UISceneManager.purge = function () {
    this._instance = null;
};

GUITestScene = cc.Class.extend({
    runThisTest:function () {
        var manager = UISceneManager.getInstance();
        var scene = manager.currentUIScene();
        cc.director.runScene(scene);
    }
});
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const spawn = require('child_process').spawn;

const concat = require('concat-stream');
const hash = require('object-hash');
const joi = require('joi');
const Promise = require('bluebird');
const waitress = require('waitress');

const validate = require('../lib/validate');

class Builder {

  constructor(options) {
    options = options || {};
    this.DOCKER_TAG = options.dockerTag || 'browserify-builder';
    this._inProgress = Object.create(null);
  }

  static _hash(options) {
    return hash(options);
  }

  static _execError(message, results) {
    const err = new Error(message);
    Object.assign(err, results);
    return err;
  }

  static _exec(cmd, argv, opts) {
    const child = spawn(cmd, argv, opts);

    const p = new Promise((resolve, reject) => {

      let stdout = '';
      let stderr = '';
      let code;

      const finish = waitress(3, (err) => {
        if (err) {
          return reject(err);
        }
        return resolve({ code: code, stdout: stdout, stderr: stderr });
      });

      child.stdout.pipe(concat((_out) => {
        if (_out) {
          stdout = _out.toString();
        }
        finish();
      }));
      child.stderr.pipe(concat((_err) => {
        if (_err) {
          stderr = _err.toString();
        }
        finish();
      }));

      child.on('exit', (c) => {
        code = c;
        finish();
      });

      child.on('error', finish);
    });

    p.stdin = child.stdin;

    return p;
  }

  _getVersions() {
    return this.constructor._exec(
      'docker',
      [ 'run', '--rm', this.DOCKER_TAG, 'bash', './versions.sh' ]
    ).then((results) => {
      let output;
      const stderr = results.stderr;

      try {
        output = JSON.parse(results.stdout);
      }
      catch (parseError) {
        throw this.constructor._execError(
          'Could not parse result from fetching versions',
          Object.assign(results, { error: parseError.message })
        );
      }

      if (stderr) {
        throw this.constructor._execError(
          'Unexpected stderr while fetching versions',
          results
        );
      }

      return output;
    });
  }

  bootstrap() {
    return this.constructor._exec(
      'docker',
      [ 'build', '.', '-t', this.DOCKER_TAG ],
      {
        cwd: path.join(__dirname, 'container')
      }
    ).then((results) => {
      if (results.stderr) {
        throw this.constructor._execError(
          'Unexpected stderr from docker init',
          results
        );
      }

      return results.stdout;
    });
  }

  init() {
    return this._getVersions().then((versions) => {
      this.versions = versions;
      return null;
    });
  }

  build(options) {
    const key = this.constructor._hash(options);

    if (this._inProgress[key]) {
      return this._inProgress[key];
    }

    this._inProgress[key] = this._build(options);

    this._inProgress[key].then((result) => {
      this._inProgress[key] = undefined;
    }, (err) => {
      // This error should get handled elsewhere, we just need to clean up our memoization
      this._inProgress[key] = undefined;
    });

    return this._inProgress[key];
  }

  _build(options) {
    return Promise.try(() => {
      options = validate.validateInput(options);

      const p = this.constructor._exec(
        'docker',
        // TODO: Sane setting for --name ?
        [ 'run', '-i', '--rm', this.DOCKER_TAG, 'bash', './build.sh' ]
      );

      p.stdin.end(JSON.stringify(options));

      return p;
    }).then((results) => {
      let output;
      const stderr = results.stderr;

      try {
        output = JSON.parse(results.stdout);

      }
      catch (parseError) {
        throw this.constructor._execError(
          'Could not parse result from builder',
          Object.assign(results, { error: parseError.message })
        );
      }

      if (stderr) {
        throw this.constructor._execError(
          'Unexpected stderr from builder',
          Object.assign({}, results, output)
        );
      }

      if (output.code !== 0) {
        throw this.constructor._execError(
          'Unexpected exit code from builder',
          Object.assign({}, results, output)
        );
      }

      return output;
    });
  }
}

module.exports = Builder;
<commit_msg>String over toString in builder index<commit_after>'use strict';

const path = require('path');
const spawn = require('child_process').spawn;

const concat = require('concat-stream');
const hash = require('object-hash');
const joi = require('joi');
const Promise = require('bluebird');
const waitress = require('waitress');

const validate = require('../lib/validate');

class Builder {

  constructor(options) {
    options = options || {};
    this.DOCKER_TAG = options.dockerTag || 'browserify-builder';
    this._inProgress = Object.create(null);
  }

  static _hash(options) {
    return hash(options);
  }

  static _execError(message, results) {
    const err = new Error(message);
    Object.assign(err, results);
    return err;
  }

  static _exec(cmd, argv, opts) {
    const child = spawn(cmd, argv, opts);

    const p = new Promise((resolve, reject) => {

      let stdout = '';
      let stderr = '';
      let code;

      const finish = waitress(3, (err) => {
        if (err) {
          return reject(err);
        }
        return resolve({ code: code, stdout: stdout, stderr: stderr });
      });

      child.stdout.pipe(concat((_out) => {
        if (_out) {
          stdout = _out.toString();
        }
        finish();
      }));
      child.stderr.pipe(concat((_err) => {
        if (_err) {
          stderr = String(_err);
        }
        finish();
      }));

      child.on('exit', (c) => {
        code = c;
        finish();
      });

      child.on('error', finish);
    });

    p.stdin = child.stdin;

    return p;
  }

  _getVersions() {
    return this.constructor._exec(
      'docker',
      [ 'run', '--rm', this.DOCKER_TAG, 'bash', './versions.sh' ]
    ).then((results) => {
      let output;
      const stderr = results.stderr;

      try {
        output = JSON.parse(results.stdout);
      }
      catch (parseError) {
        throw this.constructor._execError(
          'Could not parse result from fetching versions',
          Object.assign(results, { error: parseError.message })
        );
      }

      if (stderr) {
        throw this.constructor._execError(
          'Unexpected stderr while fetching versions',
          results
        );
      }

      return output;
    });
  }

  bootstrap() {
    return this.constructor._exec(
      'docker',
      [ 'build', '.', '-t', this.DOCKER_TAG ],
      {
        cwd: path.join(__dirname, 'container')
      }
    ).then((results) => {
      if (results.stderr) {
        throw this.constructor._execError(
          'Unexpected stderr from docker init',
          results
        );
      }

      return results.stdout;
    });
  }

  init() {
    return this._getVersions().then((versions) => {
      this.versions = versions;
      return null;
    });
  }

  build(options) {
    const key = this.constructor._hash(options);

    if (this._inProgress[key]) {
      return this._inProgress[key];
    }

    this._inProgress[key] = this._build(options);

    this._inProgress[key].then((result) => {
      this._inProgress[key] = undefined;
    }, (err) => {
      // This error should get handled elsewhere, we just need to clean up our memoization
      this._inProgress[key] = undefined;
    });

    return this._inProgress[key];
  }

  _build(options) {
    return Promise.try(() => {
      options = validate.validateInput(options);

      const p = this.constructor._exec(
        'docker',
        // TODO: Sane setting for --name ?
        [ 'run', '-i', '--rm', this.DOCKER_TAG, 'bash', './build.sh' ]
      );

      p.stdin.end(JSON.stringify(options));

      return p;
    }).then((results) => {
      let output;
      const stderr = results.stderr;

      try {
        output = JSON.parse(results.stdout);

      }
      catch (parseError) {
        throw this.constructor._execError(
          'Could not parse result from builder',
          Object.assign(results, { error: parseError.message })
        );
      }

      if (stderr) {
        throw this.constructor._execError(
          'Unexpected stderr from builder',
          Object.assign({}, results, output)
        );
      }

      if (output.code !== 0) {
        throw this.constructor._execError(
          'Unexpected exit code from builder',
          Object.assign({}, results, output)
        );
      }

      return output;
    });
  }
}

module.exports = Builder;
<|endoftext|>