<commit_before>/* eslint-disable no-magic-numbers */
// NOTE This file is an important documentation of the data structure of v9.

var c = require('./common');
var db = require('tresdb-db');

module.exports = {
  collections: {

    config: [{
      key: 'schemaVersion',
      value: 10, // NOTE
    }],

    entries: [{
      _id: db.id('581f166110a1482dd0b7ea01'),
      data: {
        isVisit: false,
        markdown: 'A ghost town',
        filepath: null,
        mimetype: null,
        thumbfilepath: null,
        thumbmimetype: null,
      },
      deleted: false,
      locationId: c.irbeneId,
      time: '2009-09-04T23:44:21.000Z',
      type: 'location_entry',
      user: 'admin',
    }, {
      _id: db.id('581f166110a1482dd0b7ea02'),
      comments: [
        {
          time: '2009-10-04T19:55:01.000Z',
          user: 'admin',
          message: 'Hello world',
        },
      ],
      data: {
        isVisit: false,
        markdown: null,
        filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
        mimetype: 'image/jpeg',
        thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
        thumbmimetype: 'image/jpeg',
      },
      deleted: false,
      locationId: c.irbeneId,
      time: '2009-10-02T11:11:01.000Z',
      type: 'location_entry',
      user: 'admin',
    }],

    events: [{
      data: {
        lng: 21.857705,
        lat: 57.55341,
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-07-30T10:44:57.000Z',
      type: 'location_created',
      user: 'admin',
    }, {
      data: {
        entryId: db.id('581f166110a1482dd0b7ea01'),
        isVisit: false,
        markdown: 'A ghost town',
        filepath: null,
        mimetype: null,
        thumbfilepath: null,
        thumbmimetype: null,
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-09-04T23:44:21.000Z',
      type: 'location_entry_created',
      user: 'admin',
    }, {
      data: {
        newTags: ['abandoned'],
        oldTags: [],
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-09-04T23:45:20.000Z',
      type: 'location_tags_changed', // legacy event type
      user: 'admin',
    }, {
      data: {
        entryId: db.id('581f166110a1482dd0b7ea02'),
        isVisit: false,
        markdown: null,
        filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
        mimetype: 'image/jpeg',
        thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
        thumbmimetype: 'image/jpeg',
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-10-02T11:11:01.000Z',
      type: 'location_entry_created',
      user: 'admin',
    }, {
      data: {
        entryId: db.id('581f166110a1482dd0b7ea02'),
        message: 'Dang radar, dude',
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-10-04T19:55:01.000Z',
      type: 'location_entry_comment_created',
      user: 'admin',
    }],

    users: [{
      admin: true,
      email: 'admin@example.com',
      hash: c.PASSWORD,
      name: 'admin',
      points: 0,
      // points7days: created by worker
      // points30days: created by worker
      status: 'active',
    }],

    locations: [{
      _id: c.irbeneId,
      creator: 'admin',
      deleted: false,
      geom: {
        type: 'Point',
        coordinates: [21.857705, 57.55341],
      },
      layer: 12,
      childLayer: 0, // NOTE
      isLayered: true,
      name: 'Irbene',
      points: 0,
      places: [],
      status: 'abandoned',
      type: 'default',
      visits: [], // NOTE
      text1: '',
      text2: '',
    }],
  },
};
<commit_msg>Correct version in comment<commit_after>/* eslint-disable no-magic-numbers */
// NOTE This file is an important documentation of the data structure at v10.

var c = require('./common');
var db = require('tresdb-db');

module.exports = {
  collections: {

    config: [{
      key: 'schemaVersion',
      value: 10, // NOTE
    }],

    entries: [{
      _id: db.id('581f166110a1482dd0b7ea01'),
      data: {
        isVisit: false,
        markdown: 'A ghost town',
        filepath: null,
        mimetype: null,
        thumbfilepath: null,
        thumbmimetype: null,
      },
      deleted: false,
      locationId: c.irbeneId,
      time: '2009-09-04T23:44:21.000Z',
      type: 'location_entry',
      user: 'admin',
    }, {
      _id: db.id('581f166110a1482dd0b7ea02'),
      comments: [
        {
          time: '2009-10-04T19:55:01.000Z',
          user: 'admin',
          message: 'Hello world',
        },
      ],
      data: {
        isVisit: false,
        markdown: null,
        filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
        mimetype: 'image/jpeg',
        thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
        thumbmimetype: 'image/jpeg',
      },
      deleted: false,
      locationId: c.irbeneId,
      time: '2009-10-02T11:11:01.000Z',
      type: 'location_entry',
      user: 'admin',
    }],

    events: [{
      data: {
        lng: 21.857705,
        lat: 57.55341,
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-07-30T10:44:57.000Z',
      type: 'location_created',
      user: 'admin',
    }, {
      data: {
        entryId: db.id('581f166110a1482dd0b7ea01'),
        isVisit: false,
        markdown: 'A ghost town',
        filepath: null,
        mimetype: null,
        thumbfilepath: null,
        thumbmimetype: null,
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-09-04T23:44:21.000Z',
      type: 'location_entry_created',
      user: 'admin',
    }, {
      data: {
        newTags: ['abandoned'],
        oldTags: [],
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-09-04T23:45:20.000Z',
      type: 'location_tags_changed', // legacy event type
      user: 'admin',
    }, {
      data: {
        entryId: db.id('581f166110a1482dd0b7ea02'),
        isVisit: false,
        markdown: null,
        filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
        mimetype: 'image/jpeg',
        thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
        thumbmimetype: 'image/jpeg',
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-10-02T11:11:01.000Z',
      type: 'location_entry_created',
      user: 'admin',
    }, {
      data: {
        entryId: db.id('581f166110a1482dd0b7ea02'),
        message: 'Dang radar, dude',
      },
      locationId: c.irbeneId,
      locationName: 'Irbene',
      time: '2009-10-04T19:55:01.000Z',
      type: 'location_entry_comment_created',
      user: 'admin',
    }],

    users: [{
      admin: true,
      email: 'admin@example.com',
      hash: c.PASSWORD,
      name: 'admin',
      points: 0,
      // points7days: created by worker
      // points30days: created by worker
      status: 'active',
    }],

    locations: [{
      _id: c.irbeneId,
      creator: 'admin',
      deleted: false,
      geom: {
        type: 'Point',
        coordinates: [21.857705, 57.55341],
      },
      layer: 12,
      childLayer: 0, // NOTE
      isLayered: true,
      name: 'Irbene',
      points: 0,
      places: [],
      status: 'abandoned',
      type: 'default',
      visits: [], // NOTE
      text1: '',
      text2: '',
    }],
  },
};
<|endoftext|>


<commit_before>var gulp         = require('gulp'),
    git          = require('gulp-git'),
    bump         = require('gulp-bump'),
    filter       = require('gulp-filter'),
    tagVersion   = require('gulp-tag-version');

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp patch     # makes v0.1.0 → v0.1.1
 *     gulp feature   # makes v0.1.1 → v0.2.0
 *     gulp release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */

var packageFiles = ['./package.json', './composer.json'];

/**
 * Increments the version number in each of the packageFiles, commits the change & git tag's it
 *
 * @param {'major'|'minor'|'patch'|'prerelease'} importance
 */
function inc(importance) {
  // get all the files to bump version in
  return gulp.src(packageFiles)
    // bump the version number in those files
    .pipe(bump({type: importance}))
    // save it back to filesystem
    .pipe(gulp.dest('./'))
    // commit the changed version number
    .pipe(git.commit('Bumped package version'))

    // read only one file to get the version number
    .pipe(filter('composer.json'))
    // **tag it in the repository**
    .pipe(tagVersion());
}

module.exports.addTasks = function () {
  gulp.task('release:patch', function () {
    return inc('patch');
  });
  gulp.task('release:minor', function () {
    return inc('minor');
  });
  gulp.task('release:major', function () {
    return inc('major');
  });
};<commit_msg>Run tests before releasing<commit_after>var gulp         = require('gulp'),
    git          = require('gulp-git'),
    bump         = require('gulp-bump'),
    filter       = require('gulp-filter'),
    tagVersion   = require('gulp-tag-version');

/**
 * Bumping version number and tagging the repository with it.
 * Please read http://semver.org/
 *
 * You can use the commands
 *
 *     gulp patch     # makes v0.1.0 → v0.1.1
 *     gulp feature   # makes v0.1.1 → v0.2.0
 *     gulp release   # makes v0.2.1 → v1.0.0
 *
 * To bump the version numbers accordingly after you did a patch,
 * introduced a feature or made a backwards-incompatible release.
 */

var packageFiles = ['./package.json', './composer.json'];

/**
 * Increments the version number in each of the packageFiles, commits the change & git tag's it
 *
 * @param {'major'|'minor'|'patch'|'prerelease'} importance
 */
function inc(importance) {
  // get all the files to bump version in
  return gulp.src(packageFiles)
    // bump the version number in those files
    .pipe(bump({type: importance}))
    // save it back to filesystem
    .pipe(gulp.dest('./'))
    // commit the changed version number
    .pipe(git.commit('Bumped package version'))

    // read only one file to get the version number
    .pipe(filter('composer.json'))
    // **tag it in the repository**
    .pipe(tagVersion());
}

module.exports.addTasks = function () {
  gulp.task('release:patch', ['test'], function () {
    return inc('patch');
  });
  gulp.task('release:minor', ['test'], function () {
    return inc('minor');
  });
  gulp.task('release:major', ['test'], function () {
    return inc('major');
  });
};<|endoftext|>


<commit_before>/* eslint-disable no-magic-numbers */
// NOTE This file is an important documentation of the data structure at v11.
// NOTE Changed properties are marked with NOTE

var c = require('./common');
var db = require('tresdb-db');

module.exports = {
  collections: {

    config: [{
      key: 'schemaVersion',
      value: 11, // NOTE
    }],

    entries: [
      {
        _id: db.id('581f166110a1482dd0b7ea01'),
        data: {
          isVisit: false,
          markdown: 'A ghost town',
          filepath: null,
          mimetype: null,
          thumbfilepath: null,
          thumbmimetype: null,
        },
        deleted: false,
        locationId: c.irbeneId,
        time: '2009-09-04T23:44:21.000Z',
        type: 'location_entry',
        user: 'admin',
        // NOTE in v11 we allow missing comments prop.
        // NOTE In v12 the comments prop is required.
      },
      {
        _id: c.locatorEntryId,
        comments: [
          {
            time: '2009-10-04T19:55:01.000Z',
            user: 'admin',
            message: 'Hello world',
          },
        ],
        data: {
          isVisit: true, // NOTE changed by location_entry_changed
          markdown: 'Ventspils RT-32 radio telescope', // NOTE changed by ev
          filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
          mimetype: 'image/jpeg',
          thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          thumbmimetype: 'image/jpeg',
          overlay: {}, // NOTE mimic failed overlay to ensure removal in v11v12
        },
        deleted: false,
        locationId: c.irbeneId,
        time: '2009-10-02T11:11:01.000Z',
        type: 'location_entry',
        user: 'admin',
      },
    ],

    events: [
      {
        data: {
          lng: 21.857705,
          lat: 57.55341,
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-07-30T10:44:57.000Z',
        type: 'location_created',
        user: 'admin',
      },
      {
        data: {
          entryId: db.id('581f166110a1482dd0b7ea01'),
          isVisit: false,
          markdown: 'A ghost town',
          filepath: null,
          mimetype: null,
          thumbfilepath: null,
          thumbmimetype: null,
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-09-04T23:44:21.000Z',
        type: 'location_entry_created',
        user: 'admin',
      },
      {
        data: {
          newTags: ['abandoned'],
          oldTags: [],
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-09-04T23:45:20.000Z',
        type: 'location_tags_changed', // legacy event type
        user: 'admin',
      },
      {
        data: {
          entryId: c.locatorEntryId,
          isVisit: false,
          markdown: null,
          filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
          mimetype: 'image/jpeg',
          thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          thumbmimetype: 'image/jpeg',
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-10-02T11:11:01.000Z',
        type: 'location_entry_created',
        user: 'admin',
      },
      {
        data: {
          entryId: c.locatorEntryId,
          message: 'Dang radar, dude',
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-10-04T19:55:01.000Z',
        type: 'location_entry_comment_created',
        user: 'admin',
      },
      { // NOTE added location_entry_changed ev for docs and v11v12 migr.
        _id: db.id('581f166110a1482dd038f33a'),
        type: 'location_entry_changed',
        user: 'admin',
        time: '2017-06-29T18:44:21.194Z',
        locationId: c.irbeneId,
        locationName: 'Irbene',
        data: {
          entryId: c.locatorEntryId,
          oldMarkdown: null,
          newMarkdown: 'Ventspils RT-32 radio telescope',
          oldIsVisit: false,
          newIsVisit: true,
          oldFilepath: '2009/RxRvKSlbl/radar.jpg',
          newFilepath: '2009/RxRvKSlbl/radar.jpg',
          oldMimetype: 'image/jpeg',
          newMimetype: 'image/jpeg',
          oldThumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          newThumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          oldThumbmimetype: 'image/jpeg',
          newThumbmimetype: 'image/jpeg',
        },
      },
      // NOTE an entry create-remove pair to test removal of these orphans
      {
        _id: db.id('581f166110a1482dd577fbba'),
        type: 'location_entry_created',
        user: 'admin',
        time: '2021-02-15T22:16:10.000Z',
        locationId: c.irbeneId,
        locationName: 'Irbene',
        data: {
          entryId: db.id('d784ee5136f59eb3dda9c79e'),
          isVisit: false,
          markdown: 'Something not so relevant',
          filepath: null,
          mimetype: null,
          thumbfilepath: null,
          thumbmimetype: null,
        },
      },
      {
        _id: db.id('581f166110a1482dd577fbbb'),
        type: 'location_entry_removed',
        user: 'admin',
        time: '2021-02-15T22:18:13.000Z',
        locationId: c.irbeneId,
        locationName: 'Irbene',
        data: {
          entryId: db.id('d784ee5136f59eb3dda9c79e'),
        },
      },
    ],

    users: [{
      admin: true,
      email: 'admin@example.com',
      hash: c.PASSWORD,
      name: 'admin',
      points: 0,
      // points7days: created by worker
      // points30days: created by worker
      status: 'active',
      createdAt: '2009-07-29T12:34:56.000Z', // NOTE
      loginAt: '2009-10-05T12:34:56.000Z', // NOTE
    }],

    locations: [{
      _id: c.irbeneId,
      creator: 'admin',
      deleted: false,
      geom: {
        type: 'Point',
        coordinates: [21.857705, 57.55341],
      },
      layer: 12,
      childLayer: 0,
      isLayered: true,
      name: 'Irbene',
      points: 0,
      places: [],
      status: 'abandoned',
      type: 'default',
      visits: [],
      text1: '',
      text2: '',
    }],
  },
};
<commit_msg>Add prefilled v12 comment to v11<commit_after>/* eslint-disable no-magic-numbers */
// NOTE This file is an important documentation of the data structure at v11.
// NOTE Changed properties are marked with NOTE

var c = require('./common');
var db = require('tresdb-db');

module.exports = {
  collections: {

    config: [{
      key: 'schemaVersion',
      value: 11, // NOTE
    }],

    entries: [
      {
        _id: db.id('581f166110a1482dd0b7ea01'),
        data: {
          isVisit: false,
          markdown: 'A ghost town',
          filepath: null,
          mimetype: null,
          thumbfilepath: null,
          thumbmimetype: null,
        },
        deleted: false,
        locationId: c.irbeneId,
        time: '2009-09-04T23:44:21.000Z',
        type: 'location_entry',
        user: 'admin',
        // NOTE in v11 we allow missing comments prop.
        // NOTE In v12 the comments prop is required.
      },
      {
        _id: c.locatorEntryId,
        comments: [
          {
            time: '2009-10-04T19:55:01.000Z',
            user: 'admin',
            message: 'Hello world',
          },
          {
            time: '2021-02-10T20:30:01.000Z',
            user: 'admin',
            message: 'Tunnel ground',
            attachments: ['adebd2rq'], // NOTE not v11 but prefilled v12
          },
        ],
        data: {
          isVisit: true, // NOTE changed by location_entry_changed
          markdown: 'Ventspils RT-32 radio telescope', // NOTE changed by ev
          filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
          mimetype: 'image/jpeg',
          thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          thumbmimetype: 'image/jpeg',
          overlay: {}, // NOTE mimic failed overlay to ensure removal in v11v12
        },
        deleted: false,
        locationId: c.irbeneId,
        time: '2009-10-02T11:11:01.000Z',
        type: 'location_entry',
        user: 'admin',
      },
    ],

    events: [
      {
        data: {
          lng: 21.857705,
          lat: 57.55341,
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-07-30T10:44:57.000Z',
        type: 'location_created',
        user: 'admin',
      },
      {
        data: {
          entryId: db.id('581f166110a1482dd0b7ea01'),
          isVisit: false,
          markdown: 'A ghost town',
          filepath: null,
          mimetype: null,
          thumbfilepath: null,
          thumbmimetype: null,
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-09-04T23:44:21.000Z',
        type: 'location_entry_created',
        user: 'admin',
      },
      {
        data: {
          newTags: ['abandoned'],
          oldTags: [],
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-09-04T23:45:20.000Z',
        type: 'location_tags_changed', // legacy event type
        user: 'admin',
      },
      {
        data: {
          entryId: c.locatorEntryId,
          isVisit: false,
          markdown: null,
          filepath: '2009/RxRvKSlbl/radar.jpg', // the sample contains this
          mimetype: 'image/jpeg',
          thumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          thumbmimetype: 'image/jpeg',
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-10-02T11:11:01.000Z',
        type: 'location_entry_created',
        user: 'admin',
      },
      {
        data: {
          entryId: c.locatorEntryId,
          message: 'Dang radar, dude',
        },
        locationId: c.irbeneId,
        locationName: 'Irbene',
        time: '2009-10-04T19:55:01.000Z',
        type: 'location_entry_comment_created',
        user: 'admin',
      },
      { // NOTE added location_entry_changed ev for docs and v11v12 migr.
        _id: db.id('581f166110a1482dd038f33a'),
        type: 'location_entry_changed',
        user: 'admin',
        time: '2017-06-29T18:44:21.194Z',
        locationId: c.irbeneId,
        locationName: 'Irbene',
        data: {
          entryId: c.locatorEntryId,
          oldMarkdown: null,
          newMarkdown: 'Ventspils RT-32 radio telescope',
          oldIsVisit: false,
          newIsVisit: true,
          oldFilepath: '2009/RxRvKSlbl/radar.jpg',
          newFilepath: '2009/RxRvKSlbl/radar.jpg',
          oldMimetype: 'image/jpeg',
          newMimetype: 'image/jpeg',
          oldThumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          newThumbfilepath: '2009/RxRvKSlbl/radar_medium.jpg',
          oldThumbmimetype: 'image/jpeg',
          newThumbmimetype: 'image/jpeg',
        },
      },
      // NOTE an entry create-remove pair to test removal of these orphans
      {
        _id: db.id('581f166110a1482dd577fbba'),
        type: 'location_entry_created',
        user: 'admin',
        time: '2021-02-15T22:16:10.000Z',
        locationId: c.irbeneId,
        locationName: 'Irbene',
        data: {
          entryId: db.id('d784ee5136f59eb3dda9c79e'),
          isVisit: false,
          markdown: 'Something not so relevant',
          filepath: null,
          mimetype: null,
          thumbfilepath: null,
          thumbmimetype: null,
        },
      },
      {
        _id: db.id('581f166110a1482dd577fbbb'),
        type: 'location_entry_removed',
        user: 'admin',
        time: '2021-02-15T22:18:13.000Z',
        locationId: c.irbeneId,
        locationName: 'Irbene',
        data: {
          entryId: db.id('d784ee5136f59eb3dda9c79e'),
        },
      },
    ],

    users: [{
      admin: true,
      email: 'admin@example.com',
      hash: c.PASSWORD,
      name: 'admin',
      points: 0,
      // points7days: created by worker
      // points30days: created by worker
      status: 'active',
      createdAt: '2009-07-29T12:34:56.000Z', // NOTE
      loginAt: '2009-10-05T12:34:56.000Z', // NOTE
    }],

    locations: [{
      _id: c.irbeneId,
      creator: 'admin',
      deleted: false,
      geom: {
        type: 'Point',
        coordinates: [21.857705, 57.55341],
      },
      layer: 12,
      childLayer: 0,
      isLayered: true,
      name: 'Irbene',
      points: 0,
      places: [],
      status: 'abandoned',
      type: 'default',
      visits: [],
      text1: '',
      text2: '',
    }],
  },
};
<|endoftext|>


<commit_before>var prompt = require('gulp-prompt');
var bump = require('gulp-bump');
var git = require('gulp-git');
var del = require('del');
var runSequence = require('run-sequence');
var spawn = require('child_process').spawn;
var mkdirp = require('mkdirp');

var gulpUtils = require('./gulpfile-utils');

module.exports = function(gulp, opts) {
  gulp.task('release:bump', function(done) {
    gulp.src('./')
      .pipe(prompt.prompt({
        type: 'input',
        name: 'bump',
        message: 'What type of bump would you like to do (patch, minor, major)?',
        validate: function(pass) {
          if (pass !== 'patch' && pass !== 'minor' && pass !== 'major') {
            return false;
          }
          return true;
        }
      }, function(res) {
        gulp.src('./docs/package.json')
        .pipe(bump({
          type: res.bump
        })).pipe(gulp.dest('./docs'));

        gulp.src('./package.json')
        .pipe(bump({
          type: res.bump
        }))
        .pipe(gulp.dest('./')).on('end', function() {
          opts.copyAssets.push({
            filename: 'package.json',
            asset: JSON.stringify(gulpUtils.getPackageJSON(), null, 2)
          });
          done();
        });
      }));
  });

  gulp.task('release:npm', function(done) {
    process.chdir('dist');
    spawn('npm', ['publish'], {
      stdio: 'inherit'
    }).on('close', function() {
      process.chdir(__dirname);
      var version = 'v' + gulpUtils.getPackageJSON().version;
      gulp.src('./')
        .pipe(git.add({
          args: '--all'
        }))
        .pipe(git.commit(version)).on('end', function() {
          git.push('origin', 'master', function(err) {
            if (err) {
              throw err;
            }

            git.tag(version, version, function(err) {
              if (err) {
                throw err;
              }

              git.push('origin', version, function(err) {
                if (err) {
                  throw err;
                }
                process.chdir(__dirname);
                done();
              });
            });
          });
        });
    });
  });

  gulp.task('release:createTmp', function(done) {
    del.sync(['./tmp']);
    mkdirp('./tmp', function(err) {
      if (err) {
        throw err;
      }
      done();
    });
  });

  gulp.task('release:bower', ['release:createTmp'], function(done) {
    git.clone('https://github.com/grommet/grommet-bower.git',
      {
        cwd: './tmp/'
      },
      function(err) {
        if (err) {
          throw err;
        }
        gulp.src('./dist-bower/**').pipe(gulp.dest('./tmp/grommet-bower'));

        var version = 'v' + gulpUtils.getPackageJSON().version;
        process.chdir('./tmp/grommet-bower');
        gulp.src('./*')
          .pipe(git.add({
            args: '--all'
          }))
          .pipe(git.commit(version)).on('end', function() {
            git.push('origin', 'master', function(err) {
              if (err) {
                throw err;
              }

              git.tag(version, version, function(err) {
                if (err) {
                  throw err;
                }

                git.push('origin', version, function(err) {
                  if (err) {
                    throw err;
                  }
                  process.chdir(__dirname);
                  done();
                });
              });
            });
          });
      }
    );
  });

  gulp.task('release:stable', ['dist', 'release:createTmp'], function(done) {
    if (process.env.CI) {
      git.clone('https://' + process.env.GH_TOKEN + '@github.com/grommet/grommet.git',
        {
          cwd: './tmp/'
        },
        function(err) {
          if (err) {
            throw err;
          }

          process.chdir('./tmp/grommet');
          git.checkout('stable', function(err) {
            if (err) {
              throw err;
            }

            del('./**');

            gulp.src('../../dist/**').pipe(gulp.dest('./')).on('end', function() {
              git.status({
                args: '--porcelain'
              }, function(err, stdout) {
                if (err) {
                  throw err;
                }

                if (stdout && stdout !== '') {
                  gulp.src('./')
                    .pipe(git.add({
                      args: '--all'
                    }))
                    .pipe(git.commit('Stable dev version update.')).on('end', function() {
                      git.push('origin', 'stable', { quiet: true }, function(err) {
                        if (err) {
                          throw err;
                        }

                        process.chdir(__dirname);
                        done();
                      });
                    });
                } else {
                  console.log('No difference since last commit, skipping stable release.');

                  process.chdir(__dirname);
                  done();
                }
              });
            });
          });
        }
      );
    } else {
      console.warn('Skipping release. Release:stable task should be executed by CI only.');
    }
  });

  gulp.task('release:clean', function() {
    del.sync(['./tmp']);
  });

  gulp.task('release', function(done) {
    runSequence('release:bump', ['dist-bower', 'dist'], 'release:npm', 'release:bower', 'release:clean', done);
  });
};
<commit_msg>Added delete sync option for gulp release stable.<commit_after>var prompt = require('gulp-prompt');
var bump = require('gulp-bump');
var git = require('gulp-git');
var del = require('del');
var runSequence = require('run-sequence');
var spawn = require('child_process').spawn;
var mkdirp = require('mkdirp');

var gulpUtils = require('./gulpfile-utils');

module.exports = function(gulp, opts) {
  gulp.task('release:bump', function(done) {
    gulp.src('./')
      .pipe(prompt.prompt({
        type: 'input',
        name: 'bump',
        message: 'What type of bump would you like to do (patch, minor, major)?',
        validate: function(pass) {
          if (pass !== 'patch' && pass !== 'minor' && pass !== 'major') {
            return false;
          }
          return true;
        }
      }, function(res) {
        gulp.src('./docs/package.json')
        .pipe(bump({
          type: res.bump
        })).pipe(gulp.dest('./docs'));

        gulp.src('./package.json')
        .pipe(bump({
          type: res.bump
        }))
        .pipe(gulp.dest('./')).on('end', function() {
          opts.copyAssets.push({
            filename: 'package.json',
            asset: JSON.stringify(gulpUtils.getPackageJSON(), null, 2)
          });
          done();
        });
      }));
  });

  gulp.task('release:npm', function(done) {
    process.chdir('dist');
    spawn('npm', ['publish'], {
      stdio: 'inherit'
    }).on('close', function() {
      process.chdir(__dirname);
      var version = 'v' + gulpUtils.getPackageJSON().version;
      gulp.src('./')
        .pipe(git.add({
          args: '--all'
        }))
        .pipe(git.commit(version)).on('end', function() {
          git.push('origin', 'master', function(err) {
            if (err) {
              throw err;
            }

            git.tag(version, version, function(err) {
              if (err) {
                throw err;
              }

              git.push('origin', version, function(err) {
                if (err) {
                  throw err;
                }
                process.chdir(__dirname);
                done();
              });
            });
          });
        });
    });
  });

  gulp.task('release:createTmp', function(done) {
    del.sync(['./tmp']);
    mkdirp('./tmp', function(err) {
      if (err) {
        throw err;
      }
      done();
    });
  });

  gulp.task('release:bower', ['release:createTmp'], function(done) {
    git.clone('https://github.com/grommet/grommet-bower.git',
      {
        cwd: './tmp/'
      },
      function(err) {
        if (err) {
          throw err;
        }
        gulp.src('./dist-bower/**').pipe(gulp.dest('./tmp/grommet-bower'));

        var version = 'v' + gulpUtils.getPackageJSON().version;
        process.chdir('./tmp/grommet-bower');
        gulp.src('./*')
          .pipe(git.add({
            args: '--all'
          }))
          .pipe(git.commit(version)).on('end', function() {
            git.push('origin', 'master', function(err) {
              if (err) {
                throw err;
              }

              git.tag(version, version, function(err) {
                if (err) {
                  throw err;
                }

                git.push('origin', version, function(err) {
                  if (err) {
                    throw err;
                  }
                  process.chdir(__dirname);
                  done();
                });
              });
            });
          });
      }
    );
  });

  gulp.task('release:stable', ['dist', 'release:createTmp'], function(done) {
    if (process.env.CI) {
      git.clone('https://' + process.env.GH_TOKEN + '@github.com/grommet/grommet.git',
        {
          cwd: './tmp/'
        },
        function(err) {
          if (err) {
            throw err;
          }

          process.chdir('./tmp/grommet');
          git.checkout('stable', function(err) {
            if (err) {
              throw err;
            }

            del.sync(['./**/*']);

            gulp.src('../../dist/**').pipe(gulp.dest('./')).on('end', function() {
              git.status({
                args: '--porcelain'
              }, function(err, stdout) {
                if (err) {
                  throw err;
                }

                if (stdout && stdout !== '') {
                  gulp.src('./')
                    .pipe(git.add({
                      args: '--all'
                    }))
                    .pipe(git.commit('Stable dev version update.')).on('end', function() {
                      git.push('origin', 'stable', { quiet: true }, function(err) {
                        if (err) {
                          throw err;
                        }

                        process.chdir(__dirname);
                        done();
                      });
                    });
                } else {
                  console.log('No difference since last commit, skipping stable release.');

                  process.chdir(__dirname);
                  done();
                }
              });
            });
          });
        }
      );
    } else {
      console.warn('Skipping release. Release:stable task should be executed by CI only.');
    }
  });

  gulp.task('release:clean', function() {
    del.sync(['./tmp']);
  });

  gulp.task('release', function(done) {
    runSequence('release:bump', ['dist-bower', 'dist'], 'release:npm', 'release:bower', 'release:clean', done);
  });
};
<|endoftext|>


<commit_before>/**
 * Runs Galleon Server.
 *
 * @param  {Config} Object
 */

/* -- Modules -- */
// Core
var incoming = require('./fleet/incoming/incoming');
var outgoing = require('./fleet/outgoing/outgoing');

var outbound = require('./fleet/outgoing/outbound');
var queue = require('./fleet/outgoing/queue');

var Server = require('./seascape/server');
var Database = require('./fleet/connection');

// Essential
var eventEmmiter = require('events').EventEmitter;
var util         = require("util");

// Utilities
var portscanner  = require('portscanner');
var colors = require('colors'); // Better looking error handling
var Spamc = require('spamc');
/* -- ------- -- */

var handlers = {};
var pass = true, fail = false;

colors.setTheme({
	silly: 'rainbow',
	input: 'grey',
	verbose: 'cyan',
	prompt: 'grey',
	success: 'green',
	data: 'grey',
	help: 'cyan',
	warn: 'yellow',
	debug: 'grey',
	bgWhite: 'bgWhite',
	bold: 'bold',
	error: 'red'
});

var Globals = {};
var Defaults = {
	// Ports
	ports: {
		incoming: 25,
		outgoing: 587,
		server: 3000
	}
};

var Galleon = function(config, callback){
	// Defaults
	// if((!config.port)||(typeof config.port != 'number')||(config.port % 1 != 0)) config.port = 25; // Sets to default port
	//

	// Internal
	var _this = this;
	if(!config) callback = config;
	if(!callback) callback = function(){};

	Database(function(error, connection){
		console.log("Connection attempted".warn);
		if(error) {
			console.error("Connection error!".error);
			callback(error);
			throw error;
		}

		var ports = Defaults.ports;
		InternalMethods.checkPorts([ports.incoming, ports.server], function(check){
			console.log(colors.success(check));
		});

		console.log("Database connection established".success);
		// Globalize database connection
		Globals.databaseConnection = connection;

		// Emit -ready- event
		_this.emit('ready');
		callback(error, connection);
	})

	eventEmmiter.call(this);
}

util.inherits(Galleon, eventEmmiter);

var Methods = {
	dock: function(callback){

		// Internal
		if(!callback) callback = function(){};

		var INCOMING = new incoming();
		INCOMING.listen(Defaults.ports.incoming, Globals.databaseConnection, new Spamc()); // Start SMTP Incoming Server

		//var OUTGOING = new outgoing();
		//OUTGOING.listen(587); // Start SMTP Incoming Server - Sets to default port for now

		// ERROR | INCOMING | OUTGOING //
		callback(undefined, INCOMING);
	},

	dispatch: function(mail, callback){
		var QUEUE = new queue();
		QUEUE.add(Globals.databaseConnection, mail, Defaults);
	},

	server: function(callback) {

		// Internal
		if(!callback) callback = function(){};

		Server(Defaults.ports.server, Globals.databaseConnection);
		callback(undefined, true);
	}
}

var InternalMethods = {
	checkPorts: function(ports, callback){
		var check = pass;

		// forEach is sync
		ports.forEach(function(port){
			InternalMethods.checkPort(port, function(test) {
				if(test == fail) {
					check = fail;
					// Log failure
					console.warn("Port " + port + " is occupied");
				}
			});
		});

		callback(check);
	},

	checkPort: function(port, callback) {
		portscanner.checkPortStatus(port, '127.0.0.1', function(error, status) {
			if(error) console.error(error);

			// Status is 'open' if currently in use or 'closed' if available
			if(status == 'open') return callback(fail);
			else if (status == 'closed') return callback(pass);
		})
	}
}

Galleon.prototype.dock = Methods.dock;
Galleon.prototype.dispatch = Methods.dispatch;
Galleon.prototype.server = Methods.server;

module.exports = Galleon;<commit_msg>Added Defaults<commit_after>/**
 * Runs Galleon Server.
 *
 * @param  {Config} Object
 */

/* -- Modules -- */
// Core
var incoming = require('./fleet/incoming/incoming');
var outgoing = require('./fleet/outgoing/outgoing');

var outbound = require('./fleet/outgoing/outbound');
var queue = require('./fleet/outgoing/queue');

var Server = require('./seascape/server');
var Database = require('./fleet/connection');

// Essential
var eventEmmiter = require('events').EventEmitter;
var util         = require("util");

// Utilities
var portscanner  = require('portscanner');
var colors = require('colors'); // Better looking error handling
var Spamc = require('spamc');
/* -- ------- -- */

var handlers = {};
var pass = true, fail = false;

colors.setTheme({
	silly: 'rainbow',
	input: 'grey',
	verbose: 'cyan',
	prompt: 'grey',
	success: 'green',
	data: 'grey',
	help: 'cyan',
	warn: 'yellow',
	debug: 'grey',
	bgWhite: 'bgWhite',
	bold: 'bold',
	error: 'red'
});

var Globals = {};
var Defaults = {
	// Ports
	ports: {
		incoming: 25,
		outgoing: 587,
		server: 3000
	},
	dock: false
};

var Galleon = function(config, callback){
	// Defaults
	// if((!config.port)||(typeof config.port != 'number')||(config.port % 1 != 0)) config.port = 25; // Sets to default port
		_.defaults(config, Defaults);
		Defaults = config;
	//

	// Internal
	var _this = this;
	if(!config) callback = config;
	if(!callback) callback = function(){};

	Database(function(error, connection){
		console.log("Connection attempted".warn);
		if(error) {
			console.error("Connection error!".error);
			callback(error);
			throw error;
		}

		console.log("Database connection established".success);

		var ports = Defaults.ports;
		InternalMethods.checkPorts([ports.incoming, ports.server], function(check){
			if(check) console.log("All requested ports are free");

			// Globalize database connection
			Globals.databaseConnection = connection;

			if(Defaults.dock) {
				Methods.dock(function(error, incoming) {
					_this.emit('ready', error, incoming);
					callback(error, incoming, connection);
				});
			}else{
				// Emit -ready- event
				_this.emit('ready');
				callback(error, connection);
			}
		});
	})

	eventEmmiter.call(this);
}

util.inherits(Galleon, eventEmmiter);

var Methods = {
	dock: function(callback){

		// Internal
		if(!callback) callback = function(){};

		var INCOMING = new incoming();
		INCOMING.listen(Defaults.ports.incoming, Globals.databaseConnection, new Spamc()); // Start SMTP Incoming Server

		//var OUTGOING = new outgoing();
		//OUTGOING.listen(587); // Start SMTP Incoming Server - Sets to default port for now

		// ERROR | INCOMING | OUTGOING //
		callback(undefined, INCOMING);
	},

	dispatch: function(mail, callback){
		var QUEUE = new queue();
		QUEUE.add(Globals.databaseConnection, mail, Defaults);
	},

	server: function(callback) {

		// Internal
		if(!callback) callback = function(){};

		Server(Defaults.ports.server, Globals.databaseConnection);
		callback(undefined, true);
	}
}

var InternalMethods = {
	checkPorts: function(ports, callback){
		var check = pass;

		// forEach is sync
		ports.forEach(function(port){
			InternalMethods.checkPort(port, function(test) {
				if(test == fail) {
					check = fail;
					// Log failure
					console.warn("Port " + port + " is occupied");
				}
			});
		});

		callback(check);
	},

	checkPort: function(port, callback) {
		portscanner.checkPortStatus(port, '127.0.0.1', function(error, status) {
			if(error) console.error(error);

			// Status is 'open' if currently in use or 'closed' if available
			if(status == 'open') return callback(fail);
			else if (status == 'closed') return callback(pass);
		})
	}
}

Galleon.prototype.dock = Methods.dock;
Galleon.prototype.dispatch = Methods.dispatch;
Galleon.prototype.server = Methods.server;

module.exports = Galleon;<|endoftext|>


<commit_before>// Stopgap atom.js file for handling normal browser things that atom
// does not yet have stable from the browser-side API.
// - Opening external links in default web browser
// - Saving files/downloads to disk
$(document).ready(function() {
    if (typeof process === 'undefined') return;
    if (typeof process.versions['atom-shell'] === undefined) return;

    var remote = require('remote');
    var shell = require('shell');
    var http = require('http');
    var url = require('url');
    var fs = require('fs');

    $('body').on('click', 'a', function(ev) {
        var uri = url.parse(ev.currentTarget.href);

        // Opening external URLs.
        if (uri.hostname && uri.hostname !== 'localhost') {
            shell.openExternal(ev.currentTarget.href);
            return false;
        }

        // File saving.
        var fileTypes = {
            'Package': [
                'tm2z'
            ],
            'Tiles': [
                'mbtiles'
            ],
            'Image': [
                'png',
                'jpg',
                'jpeg'
            ]
        }
        var typeLabel = '';
        var typeExtension = '';
        for (var label in fileTypes) {
            for (var i in fileTypes[label]) {
                if (uri.pathname.split('.').pop().toLowerCase() == fileTypes[label][i]) {
                    typeLabel = label;
                    typeExtension = fileTypes[label][i];
                    break;
                }
            }
        }
        if (typeExtension) {
            var filePath = remote.require('dialog').showSaveDialog({
                title: 'Save ' + typeLabel,
                defaultPath: '~/Untitled ' + typeLabel + '.' + typeExtension
            });
            if (filePath) {
                uri.method = 'GET';
                var writeStream = fs.createWriteStream(filePath);
                var req = http.request(uri, function(res) {
                    if (res.statusCode !== 200) return;
                    res.pipe(writeStream);
                });
                req.end();
            }
            return false;
        }
        // Passthrough everything else.
    });
});
<commit_msg>simplify save extension lookups<commit_after>// Stopgap atom.js file for handling normal browser things that atom
// does not yet have stable from the browser-side API.
// - Opening external links in default web browser
// - Saving files/downloads to disk
$(document).ready(function() {
    if (typeof process === 'undefined') return;
    if (typeof process.versions['atom-shell'] === undefined) return;

    var remote = require('remote');
    var shell = require('shell');
    var http = require('http');
    var url = require('url');
    var fs = require('fs');

    $('body').on('click', 'a', function(ev) {
        var uri = url.parse(ev.currentTarget.href);

        // Opening external URLs.
        if (uri.hostname && uri.hostname !== 'localhost') {
            shell.openExternal(ev.currentTarget.href);
            return false;
        }

        // File saving.
        var fileTypes = {
            tm2z: 'Package',
            mbtiles: 'Tiles',
            png: 'Image',
            jpg: 'Image',
            jpeg: 'Image'
        }
        var typeExtension = uri.pathname.split('.').pop().toLowerCase();
        var typeLabel = fileTypes[typeExtension];
        if (typeLabel) {
            var filePath = remote.require('dialog').showSaveDialog({
                title: 'Save ' + typeLabel,
                defaultPath: '~/Untitled ' + typeLabel + '.' + typeExtension
            });
            if (filePath) {
                uri.method = 'GET';
                var writeStream = fs.createWriteStream(filePath);
                var req = http.request(uri, function(res) {
                    if (res.statusCode !== 200) return;
                    res.pipe(writeStream);
                });
                req.end();
            }
            return false;
        }
        // Passthrough everything else.
    });
});
<|endoftext|>


<commit_before>import angular from 'angular';
import {appName, firebaseUrl} from './constants';

const authFactory = ($firebaseAuth) => {
  const ref = new Firebase(firebaseUrl);
  return $firebaseAuth(ref);
};

authFactory.$inject = ['$firebaseAuth'];

angular.module(appName).factory('Auth', authFactory);
<commit_msg>fix(auth): add import firebase<commit_after>import angular from 'angular';
import Firebase from 'firebase';
import {appName, firebaseUrl} from './constants';

const authFactory = ($firebaseAuth) => {
  const ref = new Firebase(firebaseUrl);
  return $firebaseAuth(ref);
};

authFactory.$inject = ['$firebaseAuth'];

angular.module(appName).factory('Auth', authFactory);
<|endoftext|>


<commit_before>export default {
  signup: async function (body, cb) {
    let response = await fetch('http://localhost:3000/signup', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    });

    let { success, message } = await response.json();
    if (success) this.login(body, cb);
    else cb({ success, message });
  },

  login: async function (body, cb) {
    let response = await fetch('http://localhost:3000/api/authenticate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    });

    let { success, message, token, user } = await response.json();

    if (success) {
      localStorage.token = token;
      localStorage.userId = user._id;
      localStorage.userEmail = user.email;
      cb({ success, message, user });
    } else {
      cb({ message });
    }
  },

  logout(cb) {
    delete localStorage.token;
    if (cb) cb();
  },

  loggedIn() {
    return !!localStorage.token;
  },

  getUserEmail() {
    return localStorage.userEmail;
  },

  getUserId() {
    return localStorage.userId;
  }
};
<commit_msg>Removed absolute paths.<commit_after>export default {
  signup: async function (body, cb) {
    let response = await fetch('/signup', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    });

    let { success, message } = await response.json();
    if (success) this.login(body, cb);
    else cb({ success, message });
  },

  login: async function (body, cb) {
    let response = await fetch('/api/authenticate', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    });

    let { success, message, token, user } = await response.json();

    if (success) {
      localStorage.token = token;
      localStorage.userId = user._id;
      localStorage.userEmail = user.email;
      cb({ success, message, user });
    } else {
      cb({ message });
    }
  },

  logout(cb) {
    delete localStorage.token;
    if (cb) cb();
  },

  loggedIn() {
    return !!localStorage.token;
  },

  getUserEmail() {
    return localStorage.userEmail;
  },

  getUserId() {
    return localStorage.userId;
  }
};
<|endoftext|>


<commit_before>var counter;
var header = 160;
var effectiveWindowWidth, effectiveWindowHeight;
var objectSize = 80;

function setup() {
    effectiveWindowWidth = windowWidth - 16;
    effectiveWindowHeight = windowHeight - header;
    var canvas = createCanvas(effectiveWindowWidth, effectiveWindowHeight);

    if (displayWidth < 700)
        objectSize = 30;

    canvas.parent('play');
    counter = new Counter();
    counter.new();

    var buttons = selectAll('.value-button');

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].mouseClicked(function () {
            if (counter.loosing)
                counter.new();
            else
                counter.guess(this.elt.innerHTML);
        });
    }

    var enterButton = select('.enter-button');
    enterButton.mouseClicked(function () {
        if (counter.loosing)
            counter.new();
        else
            counter.submitGuess();
    });
}

function draw() {
    background(255, 255, 255);
    counter.draw();
}

function windowResized() {
    effectiveWindowWidth = windowWidth - 16;
    effectiveWindowHeight = windowHeight - header;
    resizeCanvas(effectiveWindowWidth, effectiveWindowHeight);
}

function keyTyped() {
    if (key === ' ' || counter.loosing) {
        counter.new();
        return;
    }
    if (keyCode == ENTER) {
        counter.submitGuess();
        return;
    }
    var numbers = ["1","2","3","4","5","6","7","8","9","0"];
    if (numbers.indexOf(key) > - 1) {
        counter.guess(key);
    }
}

function touchStarted() {
    if (touches.length > 0) {
        var touch = touches[0];
        if (
            touch.x >= 0 && touch.x < effectiveWindowWidth &&
            touch.y >= 0 && touch.y < effectiveWindowHeight
        )
        {
            if (counter.loosing)
                counter.new();
        }
    }
}

function Counter () {
    this.objects = [];
    this.score = 0;
    this.number = 0;
    var gap = objectSize + 5;
    this.new = function () {
        this.lastGuess = null;
        this.loosing = false;
        this.objects = [];
        this.number = floor(random(1, 10));
        var newPosition;
        while(this.objects.length < this.number) {
            newPosition = this.findNewPosition();
            if (!newPosition)
            {
                this.number--;
                continue;
            }
            this.objects.push({
                    position: newPosition,
                    color: color('red'),
                    type: 'ellipse'
                });
        }
        var level2 = floor(random(1, 5));
        if (this.score > 5) {
            for(var i = 0; i < level2; i++) {
                newPosition = this.findNewPosition();
                if (!newPosition)
                {
                    level2--;
                    continue;
                }
                this.objects.push({
                    position: newPosition,
                    color: color('blue'),
                    type: 'ellipse'
                });
            }
        }
        var level3 = floor(random(1, 5));
        if (this.score > 10) {
            for(var i = 0; i < level3; i++) {
                newPosition = this.findNewPosition();
                if (!newPosition)
                {
                    level3--;
                    continue;
                }
                this.objects.push({
                    position: newPosition,
                    color: color('red'),
                    type: 'rect'
                });
            }
        }
        var div = select('#solution');
        div.html("Count the RED circles and press ENTER!");
    }

    this.findNewPosition = function() {
        var counter = 0;
        while(true)
        {
            var newPosition = createVector(random(gap, effectiveWindowWidth - gap), random(gap, effectiveWindowHeight - gap));

            if (this.objects.every(function(item){
                return p5.Vector.sub(item.position, newPosition).mag() > objectSize * 2 + 5;
            }))
            {
                return newPosition;
            }
            counter++;
            if (counter > 200)
                break;
        }
    }

    this.draw = function() {
        for(var i = 0; i < this.objects.length; i++) {
            var object = this.objects[i];
            fill(object.color);
            switch (object.type)
            {
                case 'ellipse':
                    ellipse(object.position.x, object.position.y, objectSize * 2);
                break;
                case 'rect':
                    rect(object.position.x - objectSize, object.position.y - objectSize, objectSize * 2, objectSize * 2, 20);
                break;
            }
        }
        fill(0,0,0);
        textSize(30);
        text(this.score, 10, 35);
    }

    this.guess = function(guess) {
        this.lastGuess = guess;

        var div = select('#solution');
        div.html("Your guess is: " + this.lastGuess);
    }

    this.submitGuess = function(guess) {
        if (!this.lastGuess)
            return;
        if (this.isValid()) {
            var div = select('#solution');
            div.html("Right");
            this.win();
            this.new();
        }
        else{
            var div = select('#solution');
            div.html("Wrong. Press any key/touch to restart.");
            this.loose();
        }
    }

    this.isValid = function() {
        return this.lastGuess == this.number;
    }

    this.win = function() {
        this.score += 1;
    }

    this.loose = function() {
        this.score = 0;
        this.objects = [];
        this.loosing = true;
    }
}<commit_msg>Fix typo<commit_after>var counter;
var header = 160;
var effectiveWindowWidth, effectiveWindowHeight;
var objectSize = 80;

function setup() {
    effectiveWindowWidth = windowWidth - 16;
    effectiveWindowHeight = windowHeight - header;
    var canvas = createCanvas(effectiveWindowWidth, effectiveWindowHeight);

    if (displayWidth < 700)
        objectSize = 30;

    canvas.parent('play');
    counter = new Counter();
    counter.new();

    var buttons = selectAll('.value-button');

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].mouseClicked(function () {
            if (counter.losing)
                counter.new();
            else
                counter.guess(this.elt.innerHTML);
        });
    }

    var enterButton = select('.enter-button');
    enterButton.mouseClicked(function () {
        if (counter.losing)
            counter.new();
        else
            counter.submitGuess();
    });
}

function draw() {
    background(255, 255, 255);
    counter.draw();
}

function windowResized() {
    effectiveWindowWidth = windowWidth - 16;
    effectiveWindowHeight = windowHeight - header;
    resizeCanvas(effectiveWindowWidth, effectiveWindowHeight);
}

function keyTyped() {
    if (key === ' ' || counter.loosing) {
        counter.new();
        return;
    }
    if (keyCode == ENTER) {
        counter.submitGuess();
        return;
    }
    var numbers = ["1","2","3","4","5","6","7","8","9","0"];
    if (numbers.indexOf(key) > - 1) {
        counter.guess(key);
    }
}

function touchStarted() {
    if (touches.length > 0) {
        var touch = touches[0];
        if (
            touch.x >= 0 && touch.x < effectiveWindowWidth &&
            touch.y >= 0 && touch.y < effectiveWindowHeight
        )
        {
            if (counter.loosing)
                counter.new();
        }
    }
}

function Counter () {
    this.objects = [];
    this.score = 0;
    this.number = 0;
    var gap = objectSize + 5;
    this.new = function () {
        this.lastGuess = null;
        this.loosing = false;
        this.objects = [];
        this.number = floor(random(1, 10));
        var newPosition;
        while(this.objects.length < this.number) {
            newPosition = this.findNewPosition();
            if (!newPosition)
            {
                this.number--;
                continue;
            }
            this.objects.push({
                    position: newPosition,
                    color: color('red'),
                    type: 'ellipse'
                });
        }
        var level2 = floor(random(1, 5));
        if (this.score > 5) {
            for(var i = 0; i < level2; i++) {
                newPosition = this.findNewPosition();
                if (!newPosition)
                {
                    level2--;
                    continue;
                }
                this.objects.push({
                    position: newPosition,
                    color: color('blue'),
                    type: 'ellipse'
                });
            }
        }
        var level3 = floor(random(1, 5));
        if (this.score > 10) {
            for(var i = 0; i < level3; i++) {
                newPosition = this.findNewPosition();
                if (!newPosition)
                {
                    level3--;
                    continue;
                }
                this.objects.push({
                    position: newPosition,
                    color: color('red'),
                    type: 'rect'
                });
            }
        }
        var div = select('#solution');
        div.html("Count the RED circles and press ENTER!");
    }

    this.findNewPosition = function() {
        var counter = 0;
        while(true)
        {
            var newPosition = createVector(random(gap, effectiveWindowWidth - gap), random(gap, effectiveWindowHeight - gap));

            if (this.objects.every(function(item){
                return p5.Vector.sub(item.position, newPosition).mag() > objectSize * 2 + 5;
            }))
            {
                return newPosition;
            }
            counter++;
            if (counter > 200)
                break;
        }
    }

    this.draw = function() {
        for(var i = 0; i < this.objects.length; i++) {
            var object = this.objects[i];
            fill(object.color);
            switch (object.type)
            {
                case 'ellipse':
                    ellipse(object.position.x, object.position.y, objectSize * 2);
                break;
                case 'rect':
                    rect(object.position.x - objectSize, object.position.y - objectSize, objectSize * 2, objectSize * 2, 20);
                break;
            }
        }
        fill(0,0,0);
        textSize(30);
        text(this.score, 10, 35);
    }

    this.guess = function(guess) {
        this.lastGuess = guess;

        var div = select('#solution');
        div.html("Your guess is: " + this.lastGuess);
    }

    this.submitGuess = function(guess) {
        if (!this.lastGuess)
            return;
        if (this.isValid()) {
            var div = select('#solution');
            div.html("Right");
            this.win();
            this.new();
        }
        else{
            var div = select('#solution');
            div.html("Wrong. Press any key/touch to restart.");
            this.lose();
        }
    }

    this.isValid = function() {
        return this.lastGuess == this.number;
    }

    this.win = function() {
        this.score += 1;
    }

    this.lose = function() {
        this.score = 0;
        this.objects = [];
        this.losing = true;
    }
}<|endoftext|>


<commit_before>export default {
  creatorIsOpen: false,
  title: '',
  description: '',
  placeholder: '',
  creationStatus: {
    failed: false,
    fields: []
  },
  datasets: {
    name: 'datasets',
    selected: null,
    data: [],
    loading: false,
    loaded: false,
    child: {
      name: 'visualisations',
      selected: null,
      data: [],
      loading: false,
      loaded: false,
      child: {
        name: 'locations',
        selected: null,
        data: [],
        loading: false,
        loaded: false,
        child: {
          name: 'models',
          selected: null,
          data: [],
          loading: false,
          loaded: false,
          child: {
            name: 'scenarios',
            selected: null,
            data: [],
            loading: false,
            loaded: false,
            child: {
              name: 'categories',
              selected: null,
              data: [],
              loading: false,
              loaded: false,
              child: {
                name: 'subcategories',
                selected: null,
                data: [],
                loading: false,
                loaded: false,
                child: {
                  name: 'indicators',
                  selected: null,
                  data: [],
                  loading: false,
                  loaded: false,
                  child: {
                    name: 'years',
                    selected: null,
                    data: [],
                    loading: false,
                    loaded: false,
                    child: {
                      name: 'timeseries',
                      selected: null,
                      data: [],
                      loading: false,
                      loaded: false
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
};
<commit_msg>Remove placeholder from initial state<commit_after>export default {
  creatorIsOpen: false,
  title: '',
  description: '',
  creationStatus: {
    failed: false,
    fields: []
  },
  datasets: {
    name: 'datasets',
    selected: null,
    data: [],
    loading: false,
    loaded: false,
    child: {
      name: 'visualisations',
      selected: null,
      data: [],
      loading: false,
      loaded: false,
      child: {
        name: 'locations',
        selected: null,
        data: [],
        loading: false,
        loaded: false,
        child: {
          name: 'models',
          selected: null,
          data: [],
          loading: false,
          loaded: false,
          child: {
            name: 'scenarios',
            selected: null,
            data: [],
            loading: false,
            loaded: false,
            child: {
              name: 'categories',
              selected: null,
              data: [],
              loading: false,
              loaded: false,
              child: {
                name: 'subcategories',
                selected: null,
                data: [],
                loading: false,
                loaded: false,
                child: {
                  name: 'indicators',
                  selected: null,
                  data: [],
                  loading: false,
                  loaded: false,
                  child: {
                    name: 'years',
                    selected: null,
                    data: [],
                    loading: false,
                    loaded: false,
                    child: {
                      name: 'timeseries',
                      selected: null,
                      data: [],
                      loading: false,
                      loaded: false
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>var Provoke = require('../util/provoke.js');

var MergeTemplateService = function() {

  //***** private methods *****//

  //***** public methods *****//

  this.create = function(template) {
    return Provoke('MergeTemplateService', 'create', template.toConfig());
  };

  this.getAll = function() {
    return Provoke('MergeTemplateService', 'getAll');
  };

  this.getOne = function(id) {
    return Provoke('MergeTemplateService', 'getByID', id);
  };

  this.update = function(template) {
    return Provoke('MergeTemplateService', 'update', template.toConfig());
  };

  this.delete = function(template) {
    return Provoke('MergeTemplateService', 'deleteByID', template.getID());
  }
};

module.exports = MergeTemplateService;
<commit_msg>Added a makeRepeat function that sets up a repeater for a MergeTemplate.<commit_after>var Provoke = require('../util/provoke.js');
var Promise = require('promise');

var MergeTemplateService = function() {

  //***** private methods *****//

  //***** public methods *****//

  this.create = function(template) {
    return Provoke('MergeTemplateService', 'create', template.toConfig());
  };

  this.getAll = function() {
    return Provoke('MergeTemplateService', 'getAll');
  };

  this.getOne = function(id) {
    return Provoke('MergeTemplateService', 'getByID', id);
  };

  this.update = function(template) {
    return Provoke('MergeTemplateService', 'update', template.toConfig());
  };

  this.delete = function(template) {
    return Provoke('MergeTemplateService', 'deleteByID', template.getID());
  }

  this.repeat = function(template) {
    return Provoke('MergeTemplateService', 'getRepeatConfig', template.toConfig()).then(
      function(config) {
        return config;
      },
      function(err) {
        throw err;
      }
    );
  }
};

module.exports = MergeTemplateService;
<|endoftext|>


<commit_before>/**
 * Created by zhangpn on 11/3/2014.
 */
define(['plugin/PluginConfig',
        'plugin/PluginBase',
        'js/Widgets/DiagramDesigner/DiagramDesignerWidget.DecoratorBase',], function (PluginConfig, PluginBase, Decorator) {

    'use strict';

    var NAME = 'name',
        ISPORT = 'isPort',
        DELIM = '=>';

    var LayoutExporterPlugin = function () {
        PluginBase.call(this);
        this.modelID = 0;
        this.diagram = {};
        this.idLUT = {};
        this.error = '';
        this.connections = [];
        this.components = [];
    };

    LayoutExporterPlugin.prototype = Object.create(PluginBase.prototype);
    LayoutExporterPlugin.prototype.constructor = LayoutExporterPlugin;

    LayoutExporterPlugin.prototype.getName = function () {
        return 'LayoutExporter';
    };

    LayoutExporterPlugin.prototype.main = function (callback) {

        var self = this,
            selectedNode = self.activeNode,
            afterAllVisited;

        // uncomment this to enable updating "validPlugin" field
//        var newRootHash,
//            result,
//            core = self.core;
//        core.setRegistry(self.rootNode, 'validPlugins', '');
//        // Commit changes.
//        core.persist(self.rootNode, function (err) {
//        });
//        newRootHash = core.getHash(self.rootNode);
//        console.info("Plugin updated model");
//        result = {'commitHash': self.commitHash};
//        result.commitHash = self.project.makeCommit([result.commitHash], newRootHash, 'Plugin updated the model.', function (err) {
//        });

        if (!selectedNode) {
            callback('selectedNode is not defined', self.result);
            return;
        }

        // after all children are visited
        afterAllVisited = function (err) {
            var output = {
                components: self.components,
                connections: self.connections
            };

            if (err) {
                callback(err, self.result);
                return;
            }

            // a dirty way to get component size, port relative position, connection pathpoints
            if (window.document) {

                self.getData(window.document);
            }

            self.saveResults(output, callback);

            console.info("Plugin completed");

        };

        self.getChildrenFromNode(selectedNode, afterAllVisited);

    };

    LayoutExporterPlugin.prototype.getChildrenFromNode = function (node, callback) {
        var self = this,
            afterLoading;

        afterLoading = function (err, children) {
            var i,
                itrCallback,
                error = '';
            if (err) {
                callback('Could not load children for object, err: ' + err);
                return;
            }

            for (i = 0; i < children.length; i += 1) {
                self.atNode(children[i], function (err) {
                    if (err) {
                        // todo: error handling
                    }

                });
            }

            callback(null);
        };

        // load activeNode's children
        self.core.loadChildren(node, afterLoading);
    };

    LayoutExporterPlugin.prototype.atNode = function (node, callback) {

        var self = this,
            core = self.core,
            SRCPTR = "src",
            DSTPTR = "dst",
            ptrArray = core.getOwnPointerNames(node),
            component = {},
            connection = {},
            srcPath,
            dstPath,
            counter = 2,
            error = "",
            afterLoadingSrc,
            afterLoadingDst,
            pushConnection,
            afterLoadingChildren;

        afterLoadingSrc = function (err, node) {
            var isPort = core.getRegistry(node, ISPORT),
                portId = "",
                srcObj;

            if (err) {
                pushConnection(err);
                return;
            }

            // if src node is a port, then return srcObj as its parent node
            if (isPort) {
                srcObj = core.getParent(node);
                portId = DELIM + core.getPath(node);
            } else {
                // else return node as srcObj
                srcObj = node;
            }

            connection.srcID = core.getPath(srcObj) + portId;
            pushConnection(null, connection);
        };

        afterLoadingDst = function (err, node) {
            var isPort = core.getRegistry(node, ISPORT),
                portId = "",
                dstObj;

            if (err) {
                pushConnection(err);
                return;
            }

            // if dst node is a port, then return dstObj as its parent node
            if (isPort) {
                dstObj = core.getParent(node);
                portId = DELIM + core.getPath(node);
            } else {
                // else return node as dstObj
                dstObj = node;
            }

            connection.dstID = core.getPath(dstObj) + portId;

            pushConnection(null, connection);
        };

        pushConnection = function (err, connection) {
            // todo: get pathpoints of connection
            if (err) {
                error += err;
            }

            --counter;
            // waiting on two threads -- srcobj and dstobj threads
            if (counter === 0) {
                if (error) {
                    callback(error);
                    return;
                }
                self.connections.push(connection);
                callback(null);
            }
        };

        afterLoadingChildren = function (err, children) {
            var port,
                i;

            if (err) {
                error += err;
                callback(error);
                return;
            }

            // todo: fix relative position of ports
            if (children.length > 0) {
                component.ports = [];
                for (i = 0; i < children.length; i += 1) {
                    port = {
                        name: core.getAttribute(children[i], NAME),
                        id: core.getPath(children[i]),
                        relative_position: {
                            x: 0,
                            y: 0
                        }
                    };
                    component.ports.push(port);
                }
            }

            self.components.push(component);
            callback(null);
        };

        // check if node is a connection
        // todo: find a better way to get connections...
        if (ptrArray.indexOf(SRCPTR) > -1 && ptrArray.indexOf(DSTPTR) > - 1) {
            // get source object and dst object:

            srcPath = core.getPointerPath(node, SRCPTR);
            dstPath = core.getPointerPath(node, DSTPTR);

            // name, id, srcid, dstid, pathpoints

            connection.name = core.getAttribute(node, NAME);
            connection.id = core.getPath(node);

            core.loadByPath(self.rootNode, srcPath, afterLoadingSrc);
            core.loadByPath(self.rootNode, dstPath, afterLoadingDst);

        } else {
            // node is a component, get id, name, position, size if there's one
            // get ports if component has ports

            component.name = core.getAttribute(node, NAME);
            component.id = core.getPath(node);
            component.position = node.data.reg.position;

            // get ports of component if any
            core.loadChildren(node, afterLoadingChildren);
        }
    };

    LayoutExporterPlugin.prototype.saveResults = function (obj, callback) {
        var self = this,
            core = self.core,
            artifact = self.blobClient.createArtifact('LayoutExporterOutput'),
            file = {};

        file[core.getAttribute(self.activeNode, NAME) + ".json"] = JSON.stringify(obj, null, 4);

        artifact.addFiles(file, function (err, hashes) {
            if (err) {
                callback(err, self.result);
                return;
            }
            self.logger.warning(hashes.toString());
            artifact.save(function (err, hash) {
                if (err) {
                    callback(err, self.result);
                    return;
                }
                self.result.addArtifact(hash);
                self.result.setSuccess(true);
                callback(null, self.result);
            });
        });
    };

    LayoutExporterPlugin.prototype.getData = function (doc) {
        var self = this,
            items = $(doc).find('.items'),
            conns = items.children()[0],
            comps = items.find('.designer-item'),
            i,
            j,
            matchFound;

        // find components in designer-items and get size for each component
        for (i = 0; i < comps.length; i += 1) {
            for (j = 0; j < self.components.length; j += 1) {

                // if x pos and y pos of designer item is +/- 6px of component x pos and y pos,
                // then get size of decorator and store it in our layout object
                matchFound = match(comps[i].style.left, comps[i].style.top, self.components[j].position.x, self.components[j].position.y);
                if (matchFound) {
                    self.components[j].size = {};
                    self.components[j].size.width = parseInt($(comps[i]).find('.svg-container')[0].children[0].getAttribute('width'));
                    self.components[j].size.height = parseInt($(comps[i]).find('.svg-container')[0].children[0].getAttribute('height'));

                    // get ports relative position info
                    if (self.components[j].ports) {

                    }
                    break;
                }
            }
        }

        // find connection info

    };

    var match = function (x, y, targetX, targetY) {
        var _meetTarget,
            xMeet,
            yMeet;

        _meetTarget = function (val, target) {
            var RANGE_OFFSET = 6;

            return parseInt(val) <= target + RANGE_OFFSET && parseInt(val) >= target - RANGE_OFFSET;
        };

        xMeet = _meetTarget(x, targetX);
        yMeet = _meetTarget(y, targetY);

        return xMeet && yMeet;
    };

    return LayoutExporterPlugin;
});<commit_msg>Updated LayoutExporter plugin to be compatible with webgme@1.0.1<commit_after>/**
 * Created by zhangpn on 11/3/2014.
 */
define(['plugin/PluginConfig',
        'plugin/PluginBase',
        'js/Widgets/DiagramDesigner/DiagramDesignerWidget.DecoratorBase',], function (PluginConfig, PluginBase, Decorator) {

    'use strict';

    var NAME = 'name',
        ISPORT = 'isPort',
        DELIM = '=>';

    var LayoutExporterPlugin = function () {
        PluginBase.call(this);
        this.modelID = 0;
        this.diagram = {};
        this.idLUT = {};
        this.error = '';
        this.connections = [];
        this.components = [];
    };

    LayoutExporterPlugin.prototype = Object.create(PluginBase.prototype);
    LayoutExporterPlugin.prototype.constructor = LayoutExporterPlugin;

    LayoutExporterPlugin.prototype.getName = function () {
        return 'LayoutExporter';
    };

    LayoutExporterPlugin.prototype.main = function (callback) {

        var self = this,
            selectedNode = self.activeNode,
            afterAllVisited;

        // uncomment this to enable updating "validPlugin" field
//        var newRootHash,
//            result,
//            core = self.core;
//        core.setRegistry(self.rootNode, 'validPlugins', '');
//        // Commit changes.
//        core.persist(self.rootNode, function (err) {
//        });
//        newRootHash = core.getHash(self.rootNode);
//        console.info("Plugin updated model");
//        result = {'commitHash': self.commitHash};
//        result.commitHash = self.project.makeCommit([result.commitHash], newRootHash, 'Plugin updated the model.', function (err) {
//        });

        if (!selectedNode) {
            callback('selectedNode is not defined', self.result);
            return;
        }

        // after all children are visited
        afterAllVisited = function (err) {
            var output = {
                components: self.components,
                connections: self.connections
            };

            if (err) {
                callback(err, self.result);
                return;
            }

            // a dirty way to get component size, port relative position, connection pathpoints
            if (window.document) {

                self.getData(window.document);
            }

            self.saveResults(output, callback);

            console.info("Plugin completed");

        };

        self.getChildrenFromNode(selectedNode, afterAllVisited);

    };

    LayoutExporterPlugin.prototype.getChildrenFromNode = function (node, callback) {
        var self = this,
            afterLoading;

        afterLoading = function (err, children) {
            var i,
                itrCallback,
                error = '';
            if (err) {
                callback('Could not load children for object, err: ' + err);
                return;
            }

            for (i = 0; i < children.length; i += 1) {
                self.atNode(children[i], function (err) {
                    if (err) {
                        // todo: error handling
                    }

                });
            }

            callback(null);
        };

        // load activeNode's children
        self.core.loadChildren(node, afterLoading);
    };

    LayoutExporterPlugin.prototype.atNode = function (node, callback) {

        var self = this,
            core = self.core,
            SRCPTR = "src",
            DSTPTR = "dst",
            ptrArray = core.getOwnPointerNames(node),
            component = {},
            connection = {},
            srcPath,
            dstPath,
            counter = 2,
            error = "",
            afterLoadingSrc,
            afterLoadingDst,
            pushConnection,
            afterLoadingChildren;

        afterLoadingSrc = function (err, node) {
            var isPort = core.getRegistry(node, ISPORT),
                portId = "",
                srcObj;

            if (err) {
                pushConnection(err);
                return;
            }

            // if src node is a port, then return srcObj as its parent node
            if (isPort) {
                srcObj = core.getParent(node);
                portId = DELIM + core.getPath(node);
            } else {
                // else return node as srcObj
                srcObj = node;
            }

            connection.srcID = core.getPath(srcObj) + portId;
            pushConnection(null, connection);
        };

        afterLoadingDst = function (err, node) {
            var isPort = core.getRegistry(node, ISPORT),
                portId = "",
                dstObj;

            if (err) {
                pushConnection(err);
                return;
            }

            // if dst node is a port, then return dstObj as its parent node
            if (isPort) {
                dstObj = core.getParent(node);
                portId = DELIM + core.getPath(node);
            } else {
                // else return node as dstObj
                dstObj = node;
            }

            connection.dstID = core.getPath(dstObj) + portId;

            pushConnection(null, connection);
        };

        pushConnection = function (err, connection) {
            // todo: get pathpoints of connection
            if (err) {
                error += err;
            }

            --counter;
            // waiting on two threads -- srcobj and dstobj threads
            if (counter === 0) {
                if (error) {
                    callback(error);
                    return;
                }
                self.connections.push(connection);
                callback(null);
            }
        };

        afterLoadingChildren = function (err, children) {
            var port,
                i;

            if (err) {
                error += err;
                callback(error);
                return;
            }

            // todo: fix relative position of ports
            if (children.length > 0) {
                component.ports = [];
                for (i = 0; i < children.length; i += 1) {
                    port = {
                        name: core.getAttribute(children[i], NAME),
                        id: core.getPath(children[i]),
                        relative_position: {
                            x: 0,
                            y: 0
                        }
                    };
                    component.ports.push(port);
                }
            }

            self.components.push(component);
            callback(null);
        };

        // check if node is a connection
        // todo: find a better way to get connections...
        if (ptrArray.indexOf(SRCPTR) > -1 && ptrArray.indexOf(DSTPTR) > - 1) {
            // get source object and dst object:

            srcPath = core.getPointerPath(node, SRCPTR);
            dstPath = core.getPointerPath(node, DSTPTR);

            // name, id, srcid, dstid, pathpoints

            connection.name = core.getAttribute(node, NAME);
            connection.id = core.getPath(node);

            core.loadByPath(self.rootNode, srcPath, afterLoadingSrc);
            core.loadByPath(self.rootNode, dstPath, afterLoadingDst);

        } else {
            // node is a component, get id, name, position, size if there's one
            // get ports if component has ports

            component.name = core.getAttribute(node, NAME);
            component.id = core.getPath(node);
            component.position = node.data.reg.position;

            // get ports of component if any
            core.loadChildren(node, afterLoadingChildren);
        }
    };

    LayoutExporterPlugin.prototype.saveResults = function (obj, callback) {
        var self = this,
            core = self.core,
            artifact = self.blobClient.createArtifact('LayoutExporterOutput'),
            file = {};

        file[core.getAttribute(self.activeNode, NAME) + ".json"] = JSON.stringify(obj, null, 4);

        artifact.addFiles(file, function (err, hashes) {
            if (err) {
                callback(err, self.result);
                return;
            }
            self.logger.warn(hashes.toString());
            artifact.save(function (err, hash) {
                if (err) {
                    callback(err, self.result);
                    return;
                }
                self.result.addArtifact(hash);
                self.result.setSuccess(true);
                callback(null, self.result);
            });
        });
    };

    LayoutExporterPlugin.prototype.getData = function (doc) {
        var self = this,
            items = $(doc).find('.items'),
            conns = items.children()[0],
            comps = items.find('.designer-item'),
            i,
            j,
            matchFound;

        // find components in designer-items and get size for each component
        for (i = 0; i < comps.length; i += 1) {
            for (j = 0; j < self.components.length; j += 1) {

                // if x pos and y pos of designer item is +/- 6px of component x pos and y pos,
                // then get size of decorator and store it in our layout object
                matchFound = match(comps[i].style.left, comps[i].style.top, self.components[j].position.x, self.components[j].position.y);
                if (matchFound) {
                    self.components[j].size = {};
                    self.components[j].size.width = parseInt($(comps[i]).find('.svg-container')[0].children[0].getAttribute('width'));
                    self.components[j].size.height = parseInt($(comps[i]).find('.svg-container')[0].children[0].getAttribute('height'));

                    // todo: get ports relative position info
                    // different decors wrap connectors differently
                    if (self.components[j].ports) {

                    }
                    break;
                }
            }
        }

        // find connection info

    };

    var match = function (x, y, targetX, targetY) {
        var _meetTarget,
            xMeet,
            yMeet;

        _meetTarget = function (val, target) {
            var RANGE_OFFSET = 6;

            return parseInt(val) <= target + RANGE_OFFSET && parseInt(val) >= target - RANGE_OFFSET;
        };

        xMeet = _meetTarget(x, targetX);
        yMeet = _meetTarget(y, targetY);

        return xMeet && yMeet;
    };

    return LayoutExporterPlugin;
});<|endoftext|>


<commit_before>// ==UserScript==
// @name            Kaskus User Post Viewer
// @namespace       zackad's script
// @version         0.4
// @description     Read Full Post from Kaskus Profile
// @grant           GM_addStyle
// @include         http://www.kaskus.co.id/profile/viewallposts/*
// @include			http://www.kaskus.co.id/viewallposts/*
// @require         http://code.jquery.com/jquery-1.10.1.min.js
// @copyright       2015, zackad
// ==/UserScript==
/*
	CHANGELOG
		v0.4
		- debug mode
		v0.3
		- all post from thread
		V0.2
		- tested with scratchpad
*/
$(document).ready(function(){
	var __DEBUG__ = 0;
	var style = ''
		+ ''
		;
	$('head').append(style);
	var pItems = $('.entry-content');
	pItems.each(function(){
		var postID = $(this).find('a');
		var currentItem = $(this);
		postID = postID.attr('href');
		postID = postID.replace('post', 'show_post');
		var title = $(this).find('h4');
		clog(title);
		clog(postID);
		var ajaxURL = 'http://www.kaskus.co.id'+postID;
		clog(ajaxURL);
		$.ajax(ajaxURL).
			done(function(response){
				currentItem.text('');
				currentItem.append(title);
				currentItem.text('');
				currentItem.append(title);
				currentItem.append('
');
				var hasil = $(response).find('.entry').html();
				currentItem.append(hasil);
			});
	})

	function clog(x){
		if(__DEBUG__ == 0) return;
		console.log(x);
	}
});
<commit_msg>autoload image<commit_after>// ==UserScript==
// @name            Kaskus User Post Viewer
// @namespace       zackad's script
// @version         0.5
// @description     Read Full Post from Kaskus Profile
// @grant           GM_addStyle
// @include         http://www.kaskus.co.id/profile/viewallposts/*
// @include			http://www.kaskus.co.id/viewallposts/*
// @require         http://code.jquery.com/jquery-1.10.1.min.js
// @copyright       2015, zackad
// ==/UserScript==
/*
	CHANGELOG
		v0.5
		- autload image
		v0.4
		- debug mode
		v0.3
		- all post from thread
		V0.2
		- tested with scratchpad
*/
$(document).ready(function(){
	var __DEBUG__ = 0;
	var style = ''
		+ ''
		;
	$('head').append(style);
	var pItems = $('.entry-content');
	pItems.each(function(){
		var postID = $(this).find('a');
		var currentItem = $(this);
		postID = postID.attr('href');
		postID = postID.replace('post', 'show_post');
		var title = $(this).find('h4');
		clog(title);
		clog(postID);
		var ajaxURL = 'http://www.kaskus.co.id'+postID;
		clog(ajaxURL);
		$.ajax(ajaxURL).
			done(function(response){
				currentItem.text('');
				currentItem.append(title);
				currentItem.text('');
				currentItem.append(title);
				currentItem.append('
');
				var hasil = $(response).find('.entry').html();
				currentItem.append(hasil);
				unloadImage = $('img[src="http://s.kaskus.id/banner/1x1.gif"]');
				unloadImage.each(function(){
					var source = $(this).attr('data-src');
					$(this).attr('src', source);
				});
			});
	});

	function clog(x){
		if(__DEBUG__ == 0) return;
		console.log(x);
	}
});
<|endoftext|>