<commit_before>var http = require('http'),
  _ = require('underscore'),
  updateTimer;

function JenkinsButler(options) {
  var self = this;

  self.options = options || {};
  self.host = self.options.host || null;
  if (!self.host) throw new Error('JenkinsButler: No Jenkins host provided.');

  self.port = self.options.port || null;
  if (!self.port) throw new Error('JenkinsButler: No Jenkins port provided.');

  self.username = self.options.username || null;
  if (!self.username) throw new Error('JenkinsButler: No username provided.');

  self.token = self.options.token || null;
  if (!self.token) throw new Error('JenkinsButler: No token provided.');

  self.jobs = self.options.jobs || null;
  if (!self.jobs) throw new Error('JenkinsButler: No jobs provided.');

  self.updateIntervall = self.options.updateIntervall || null;
}

JenkinsButler.prototype.buildRequestOptions = function(job) {
  var options = {
    hostname: this.host,
    port: this.port,
    path: '/job/' + job.job + '/lastBuild/api/json?token=' + this.token,
    headers: {
      'Authorization': 'Basic ' + new Buffer(this.username + ':' + this.token).toString('base64')
    }
  };
  return options;
}

JenkinsButler.prototype.getJobStatus = function(job, callback) {
  console.log('get status ' + JSON.stringify(job));

  http.get(this.buildRequestOptions(job), function(res) {

    if (res.statusCode != 200) {
      callback('Failed to fetch jenkins data, http status: ' + res.statusCode);
      return;
    }

    var response = '';

    res.on('data', function(data) {
      response += data;
    });

    res.on('end', function(){
      var resi = JSON.parse(response);
      callback(null, resi.building ? "BUILDING" : resi.result);
    })

  }).on('error', function(e) {
    console.error('Error: ' + e);
    callback(e);
    return;
  }).on('end', function(e) {
    console.error('End:' + e);
    callback(e);
    return;
  });
}

function updateStatesOfJobs(options) {
  console.log('update status from all jobs');
  butler.jobs.forEach(function(job, index) {

    var delay = Math.floor((Math.random() * 10) + 1) * 1000;
    console.log("waiting for: " + delay);

    setTimeout( butler.getJobStatus(job, function(err, result) {
       console.log('[' + index + "]." + job.job + ' is ' + JSON.stringify(result));

        if (!err) {
          setLEDForJob(job, result, options, function(err) {
            console.log("request finished.");
          });
        } else {
          console.log("ERROR: " + err);
        }
    }), delay);
  });
}

function setLEDForJob(job, result, options, callback) {
  switch (result) {
    case "UNSTABLE":
      http.get(buildLedRequestOptions(options, job, options.leds.unstable)).on('error', onRequestError).on('end', callback);
      break;
    case "FAILURE":
      http.get(buildLedRequestOptions(options, job, options.leds.failed)).on('error', onRequestError).on('end', callback);
      break;
    case "SUCCESS":
      http.get(buildLedRequestOptions(options, job, options.leds.success)).on('error', onRequestError).on('end', callback);
      break;
    case "ABORTED":
      http.get(buildLedRequestOptions(options, job, options.leds.aborted)).on('error', onRequestError).on('end', callback);
      break;
    case "BUILDING":
      http.get(buildLedRequestOptions(options, job, options.leds.building)).on('error', onRequestError).on('end', callback);
      break;
    default:
      console.log('something is happen... Request: ' + JSON.stringify(option) + " JOB: " + JSON.stringify(job))
      http.get(buildLedRequestOptions(options, job, "000000")).on('error', onRequestError).on('end', callback);
  }
}

function onRequestError(err) {
  console.log("Got error: " + err.message);
}

function buildLedRequestOptions(options, job, color) {
  console.log ("build request to set led for " + JSON.stringify(job) + " to " + color );

  return {
    hostname: options.leds.host,
    port: options.leds.port,
    path: '/led/from/' + job.leds.start + '/to/' + job.leds.end + '/fill/' + color
  };
}

// function buildLedRequestOptionsPost(options) {
//   return {
//     hostname: options.leds.host,
//     port: options.leds.port,
//     method: "POST",
//     path: "/api/range",
//     headers: {
//       'Content-Type': "application/json"
//     }
//   };
// }
//
// function makeLedsShining(start, end, color, options) {
//   req = http.request(buildLedRequestOptionsPost(options));
//
//   req.on('error', function(e) {
//     console.log('problem with request: ' + e.message);
//   });
//
//   var post_data = JSON.stringify({
//     "from": start,
//     "to": end,
//     "rgb": color
//   });
//
//   req.write(post_data);
//   req.end();
// }

function JenkinsButlerService(options) {

}

JenkinsButlerService.prototype.setup = function(config) {
  butler = new JenkinsButler(config.jenkins);
  updateStatesOfJobs(config);
  updateTimer = setInterval(updateStatesOfJobs, config.jenkins.updateIntervall * 1000, config);
}

JenkinsButlerService.prototype.shutdown = function(config) {
  if (updateTimer) {
    console.log('JenkinsButlerService shutdown...')
    clearInterval(updateTimer);

    http.get({
      hostname: config.leds.host,
      port: config.leds.port,
      path: '/api/black'
    }, function(res) {
      console.log("Result: " + res.statusCode)
    });
  }
}

exports = module.exports = new JenkinsButlerService();
exports.JenkinsButler = JenkinsButler;
exports.ServiceName = 'JenkinsButlerService';
<commit_msg>handling with delayed requests removed<commit_after>var http = require('http'),
  _ = require('underscore'),
  updateTimer;

function JenkinsButler(options) {
  var self = this;

  self.options = options || {};
  self.host = self.options.host || null;
  if (!self.host) throw new Error('JenkinsButler: No Jenkins host provided.');

  self.port = self.options.port || null;
  if (!self.port) throw new Error('JenkinsButler: No Jenkins port provided.');

  self.username = self.options.username || null;
  if (!self.username) throw new Error('JenkinsButler: No username provided.');

  self.token = self.options.token || null;
  if (!self.token) throw new Error('JenkinsButler: No token provided.');

  self.jobs = self.options.jobs || null;
  if (!self.jobs) throw new Error('JenkinsButler: No jobs provided.');

  self.updateIntervall = self.options.updateIntervall || null;
}

JenkinsButler.prototype.buildRequestOptions = function(job) {
  var options = {
    hostname: this.host,
    port: this.port,
    path: '/job/' + job.job + '/lastBuild/api/json?token=' + this.token,
    headers: {
      'Authorization': 'Basic ' + new Buffer(this.username + ':' + this.token).toString('base64')
    }
  };
  return options;
}

JenkinsButler.prototype.getJobStatus = function(job, callback) {
  console.log('get status ' + JSON.stringify(job));

  http.get(this.buildRequestOptions(job), function(res) {

    if (res.statusCode != 200) {
      callback('Failed to fetch jenkins data, http status: ' + res.statusCode);
      return;
    }

    var response = '';

    res.on('data', function(data) {
      response += data;
    });

    res.on('end', function(){
      var resi = JSON.parse(response);
      callback(null, resi.building ? "BUILDING" : resi.result);
    })

  }).on('error', function(e) {
    console.error('Error: ' + e);
    callback(e);
    return;
  }).on('end', function(e) {
    console.error('End:' + e);
    callback(e);
    return;
  });
}

function updateStatesOfJobs(options) {
  console.log('update status from all jobs');
  butler.jobs.forEach(function(job, index) {
    butler.getJobStatus(job, function(err, result) {
       console.log('[' + index + "]." + job.job + ' is ' + JSON.stringify(result));

        if (!err) {
          setLEDForJob(job, result, options, function(reqErr) {
            if (reqErr)
            console.log("request error. " + JSON.stringify(reqErr) );
          });
        } else {
          console.log("ERROR: " + err);
        }
    });
  });
}

function setLEDForJob(job, result, options, callback) {
  switch (result) {
    case "UNSTABLE":
      http.get(buildLedRequestOptions(options, job, options.leds.unstable)).on('error', onRequestError).on('end', callback);
      break;
    case "FAILURE":
      http.get(buildLedRequestOptions(options, job, options.leds.failed)).on('error', onRequestError).on('end', callback);
      break;
    case "SUCCESS":
      http.get(buildLedRequestOptions(options, job, options.leds.success)).on('error', onRequestError).on('end', callback);
      break;
    case "ABORTED":
      http.get(buildLedRequestOptions(options, job, options.leds.aborted)).on('error', onRequestError).on('end', callback);
      break;
    case "BUILDING":
      http.get(buildLedRequestOptions(options, job, options.leds.building)).on('error', onRequestError).on('end', callback);
      break;
    default:
      console.log('something is happen... Request: ' + JSON.stringify(option) + " JOB: " + JSON.stringify(job))
      http.get(buildLedRequestOptions(options, job, "000000")).on('error', onRequestError).on('end', callback);
  }
}

function onRequestError(err) {
  console.log("Got error: " + err.message);
}

function buildLedRequestOptions(options, job, color) {
  console.log ("build request to set led for " + JSON.stringify(job) + " to " + color );

  return {
    hostname: options.leds.host,
    port: options.leds.port,
    path: '/led/from/' + job.leds.start + '/to/' + job.leds.end + '/fill/' + color
  };
}

// function buildLedRequestOptionsPost(options) {
//   return {
//     hostname: options.leds.host,
//     port: options.leds.port,
//     method: "POST",
//     path: "/api/range",
//     headers: {
//       'Content-Type': "application/json"
//     }
//   };
// }
//
// function makeLedsShining(start, end, color, options) {
//   req = http.request(buildLedRequestOptionsPost(options));
//
//   req.on('error', function(e) {
//     console.log('problem with request: ' + e.message);
//   });
//
//   var post_data = JSON.stringify({
//     "from": start,
//     "to": end,
//     "rgb": color
//   });
//
//   req.write(post_data);
//   req.end();
// }

function JenkinsButlerService(options) {

}

JenkinsButlerService.prototype.setup = function(config) {
  butler = new JenkinsButler(config.jenkins);
  updateStatesOfJobs(config);
  updateTimer = setInterval(updateStatesOfJobs, config.jenkins.updateIntervall * 1000, config);
}

JenkinsButlerService.prototype.shutdown = function(config) {
  if (updateTimer) {
    console.log('JenkinsButlerService shutdown...')
    clearInterval(updateTimer);

    http.get({
      hostname: config.leds.host,
      port: config.leds.port,
      path: '/api/black'
    }, function(res) {
      console.log("Result: " + res.statusCode)
    });
  }
}

exports = module.exports = new JenkinsButlerService();
exports.JenkinsButler = JenkinsButler;
exports.ServiceName = 'JenkinsButlerService';
<|endoftext|>


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

  var pathRule = /^\/([0-9a-z]+)(\.|\/|$)/;

  function go (id, pre, next) {
    $.openLink('', {
      post: {
        op: 'view',
        id: id,
        pre: pre,
        next: next,
      },
    });
  }

  function getNext1 (i) {
    return i.value;
  }

  function getNext2 (i) {
    var next = i.onclick && i.onclick.toString().match(/value='([^']+)'/);
    if (next) {
      next = next[1];
      return next;
    } else {
      return i.value;
    }
  }

  function helper (id, getNext) {
    var i = $.$('input[name="next"]');
    if (i) {
      // first stage
      var next = getNext(i);
      go(id, $('input[name="pre"]').value, next);
      return;
    }

    i = $.$('img.pic');
    if (i) {
      // second stage
      $.openImage(i.src);
      return;
    }

    // other page
    _.info('do nothing');
  }

  $.register({
    rule: {
      host: [
        /^img(paying|mega|zeus|monkey|trex)\.com$/,
        /^(www\.)?imgsee\.me$/,
        /^imgclick\.net$/,
        /^(uploadrr|imageeer|imzdrop|www\.uimgshare)\.com$/,
        /^imgdrive\.co$/,
        /^cuteimg\.cc$/,
        /^imgtiger\.org$/,
      ],
      path: pathRule,
    },
    ready: function (m) {
      helper(m.path[1], getNext1);
    },
  });

  $.register({
    rule: {
      host: /^imgrock\.net$/,
      path: pathRule,
    },
    ready: function (m) {
      // they have random invalid forms here
      var d = $.$('#imageviewir input[type=submit]:not([style])');
      if (!d) {
        helper(m.path[1], getNext1);
        return;
      }
      // the form has a random field, directly use this form
      d = d.parentNode;
      d.submit();
    },
  });

  $.register({
    rule: {
      host: /^chronos\.to$/,
      path: pathRule,
    },
    ready: function (m) {
      helper(m.path[1], getNext2);
    },
  });

})();
// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>myimg.club<commit_after>(function () {
  'use strict';

  var pathRule = /^\/([0-9a-z]+)(\.|\/|$)/;

  function go (id, pre, next) {
    $.openLink('', {
      post: {
        op: 'view',
        id: id,
        pre: pre,
        next: next,
      },
    });
  }

  function getNext1 (i) {
    return i.value;
  }

  function getNext2 (i) {
    var next = i.onclick && i.onclick.toString().match(/value='([^']+)'/);
    if (next) {
      next = next[1];
      return next;
    } else {
      return i.value;
    }
  }

  function helper (id, getNext) {
    var i = $.$('input[name="next"]');
    if (i) {
      // first stage
      var next = getNext(i);
      go(id, $('input[name="pre"]').value, next);
      return;
    }

    i = $.$('img.pic');
    if (i) {
      // second stage
      $.openImage(i.src);
      return;
    }

    // other page
    _.info('do nothing');
  }

  $.register({
    rule: {
      host: [
        /^img(paying|mega|zeus|monkey|trex)\.com$/,
        /^(www\.)?imgsee\.me$/,
        /^imgclick\.net$/,
        /^(uploadrr|imageeer|imzdrop|www\.uimgshare)\.com$/,
        /^imgdrive\.co$/,
        /^cuteimg\.cc$/,
        /^imgtiger\.org$/,
        /^myimg\.club$/,
      ],
      path: pathRule,
    },
    ready: function (m) {
      helper(m.path[1], getNext1);
    },
  });

  $.register({
    rule: {
      host: /^imgrock\.net$/,
      path: pathRule,
    },
    ready: function (m) {
      // they have random invalid forms here
      var d = $.$('#imageviewir input[type=submit]:not([style])');
      if (!d) {
        helper(m.path[1], getNext1);
        return;
      }
      // the form has a random field, directly use this form
      d = d.parentNode;
      d.submit();
    },
  });

  $.register({
    rule: {
      host: /^chronos\.to$/,
      path: pathRule,
    },
    ready: function (m) {
      helper(m.path[1], getNext2);
    },
  });

})();
// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>function GetPluginSettings() {
    return {
        "name": "Cocoon Facebook",
        "id": "ATPFacebook",
        "version": "1.0",
        "description": "Cocoon plugin for Facebook",
        "author": "Ludei",
        "help url": "http://cocoon.io",
        "category": "Platform specific",
        "type": "object", // not in layout
        "rotatable": false,
        "flags": pf_singleglobal,
        "dependency": "achievements.html;achievement_locked.png;close.png;loading.gif;main.css;page_achievements.css;page_leaderboards.css;style.css;leaderboards.html;jquery.equalheights.js;"
    };
};

/**
 * Conditions
 */

AddCondition(0, cf_trigger, "On login success", "Social", "On login succeeded", "Triggered when the user has logged into the social service.", "onFacebookLoginSuccess");

AddCondition(1, cf_trigger, "On login fail", "Social", "On login Failed", "Triggered if the login of the social service has failed.", "onFacebookLoginFail");

AddCondition(2, cf_trigger, "On logout success", "Social", "On logout succeeded", "Triggered when the user has logged out the social service.", "onFacebookLogoutSuccess");

AddCondition(3, cf_trigger, "On logout fail", "Social", "On logout failed", "Triggered if the logout of the social service has failed.", "onFacebookLogoutFail");

AddCondition(4, cf_trigger, "On publish message with dialog success", "Social", "On publish message with dialog success", "Triggered when the message has been successfully published", "onPublishMessageWithDialogSuccess");

AddCondition(5, cf_trigger, "On publish message with dialog fail", "Social", "On publish message with dialog fail", "Triggered when the publishing has failed", "onPublishMessageWithDialogFail");

// Leaderboards
AddCondition(6, cf_trigger, "On score submit success", "Leaderboards", "On score submit success", "Triggered after submitting a score completes successfully", "onFacebookSubmitScoreSuccess");

AddCondition(7, cf_trigger, "On score submit failed", "Leaderboards", "On score submit fail", "Triggered after submitting a score fails to complete successfully.", "onFacebookSubmitScoreFail");

AddCondition(8, cf_trigger, "On request score success", "Leaderboards", "On request score success", "Triggered after requesting a score completes successfully.", "onFacebookRequestScoreSuccess");

AddCondition(9, cf_trigger, "On request score failed", "Leaderboards", "On request score fail", "Triggered after requesting a score fails to complete successfully.", "onFacebookRequestScoreFail");

AddCondition(10, cf_trigger, "On Leaderboard open", "Leaderboards", "On Leaderboards view opened", "Triggered when the leaderboard view opens successfully.", "onFacebookOpenLeaderBoardSuccess");

AddCondition(11, cf_trigger, "On Leaderboard closed", "Leaderboards", "On Leaderboards view closed", "Triggered when the leaderboard view is closed by the user.", "onFacebookOpenLeaderBoardClosed");

// Achievements
AddCondition(12, cf_trigger, "On Achievements view closed", "Achievements", "On Achievements view closed", "Triggered when the Achievements view is closed by the user.", "onFacebookOpenAchievementsClosed");

AddCondition(13, cf_trigger, "On Achievements view open", "Achievements", "On Achievements view open", "Triggered when the Achievements view is open by the user.", "onFacebookOpenAchievementsSuccess");

AddCondition(14, cf_trigger, "On reset achievements complete", "Achievements", "On reset achievements completed", "Triggered when the achievements have been reset.", "onFacebookResetAchievementsComplete");

AddCondition(15, cf_trigger, "On reset achievements fail", "Achievements", "On reset achievements failed", "Triggered if something fails when trying to reset the achievements", "onFacebookResetAchievementsFail");

AddCondition(16, cf_trigger, "On submit achievement success", "Achievements", "On submit achievement success", "Triggered when the achievement has been correctly.", "onFacebookSubmitAchievementComplete");

AddCondition(17, cf_trigger, "On submit achievement fail", "Achievements", "On submit achievement failed", "Triggered if something fails when trying to submit an achievement", "onFacebookSubmitAchievementFail");

AddCondition(18, cf_trigger, "Is user the logged in", "Social", "Is the user logged in", "Returns true if the user is loggedin in the Facebook service, false otherwise", "isLoggedIn");

/**
 * Actions
 */

AddAction(0, af_none, "Request login", "Social", "Request Facebook login", "", "facebookRequestLogin");

AddAction(1, af_none, "Request logout", "Social", "Request Facebook logout", "", "facebookRequestLogout");

AddStringParam("Message", "The message to be published.");
AddStringParam("Media URL", "An URL to a media (image, video, ...).");
AddStringParam("Link URL", "An URL to add to the message so the user can click on that link to get more information.");
AddStringParam("Link Text", "The text that will appear in the message link.");
AddStringParam("Link Caption", "The text caption that will appear in the message link.");
AddAction(2, af_none, "Publish message with dialog", "Social", "Publish message with dialog", "Publishes a message with dialog in Facebook", "publishMessageWithDialog");

// Leaderboards
AddNumberParam("Score", "The score to submit to Game Center.");
AddStringParam("Leaderboard", "The name of the leaderboard to submit to, e.g. \"My Game Name\"");
AddAction(3, af_none, "Submit Facebook score", "Leaderboards", "Submit score of {0} to the leaderboard {1}", "Submit a score to the specified leaderboard.", "facebookSubmitScore");

AddStringParam("Leaderboard", "The name of the leaderboard to retrieve from, e.g. \"My Game Name\"");
AddAction(4, af_none, "Request Facebook player score", "Leaderboards", "Request player score", "Requests the user score from the {0} leaderboard", "facebookRequestScore");

AddStringParam("Leaderboard", "The name of the leaderboard to be openned, e.g. \"My Game Name\"");
AddAction(5, af_none, "Open leaderboard", "Leaderboards", "Open Facebook leaderboard", "Opens Facebook leaderboard", "facebookOpenLeaderboard");

// Achievements
AddAction(6, af_none, "Show achievements", "Achievements", "Show Facebook achievements", "Shows the achievements window", "facebookOpenAchievements");

AddAction(7, af_none, "Reset achievements", "Achievements", "Reset Facebook achievements", "Resets the achievements", "facebookResetAchievements");

AddStringParam("Achievement ID", "The ID of the achievement to be sent");
AddAction(8, af_none, "Submit achievement", "Achievements", "Submit Facebook achievement", "Submits an achievement", "facebookSubmitAchievement");

/**
 * Expressions
 */

AddExpression(0, ef_return_string, "", "Leaderboards", "PlayerScore", "Returns the current player score.");

ACESDone();

/**
 * Plugin properties
 */
var property_list = [

    new cr.Property(ept_text,
        "Facebook AppID",
        "",
        "The AppID of your Facebook app (create one at Facebook development site to get yours)",
        ""),
    new cr.Property(ept_text,
        "Facebook channel",
        "",
        "The Facebook channel for your app",
        "")
];

// Called by IDE when a new object type is to be created
function CreateIDEObjectType() {
    return new IDEObjectType();
}

// Class representing an object type in the IDE
function IDEObjectType() {
    assert2(this instanceof arguments.callee, "Constructor called as a function");
}

// Called by IDE when a new object instance of this type is to be created
IDEObjectType.prototype.CreateInstance = function(instance) {
    return new IDEInstance(instance, this);
}

// Class representing an individual instance of an object in the IDE
function IDEInstance(instance, type) {
    assert2(this instanceof arguments.callee, "Constructor called as a function");

    // Save the constructor parameters
    this.instance = instance;
    this.type = type;

    // Set the default property values from the property table
    this.properties = {};

    for (var i = 0; i < property_list.length; i++)
        this.properties[property_list[i].name] = property_list[i].initial_value;
}

// Called by the IDE after all initialization on this instance has been completed
IDEInstance.prototype.OnCreate = function() {}

// Called by the IDE after a property has been changed
IDEInstance.prototype.OnPropertyChanged = function(property_name) {}

// Called by the IDE to draw this instance in the editor
IDEInstance.prototype.Draw = function(renderer) {}

// Called by the IDE when the renderer has been released (ie. editor closed)
// All handles to renderer-created resources (fonts, textures etc) must be dropped.
// Don't worry about releasing them - the renderer will free them - just null out references.
IDEInstance.prototype.OnRendererReleased = function() {}
<commit_msg>Change the Facebook isLoggedIn condition type.<commit_after>function GetPluginSettings() {
    return {
        "name": "Cocoon Facebook",
        "id": "ATPFacebook",
        "version": "1.0",
        "description": "Cocoon plugin for Facebook",
        "author": "Ludei",
        "help url": "http://cocoon.io",
        "category": "Platform specific",
        "type": "object", // not in layout
        "rotatable": false,
        "flags": pf_singleglobal,
        "dependency": "achievements.html;achievement_locked.png;close.png;loading.gif;main.css;page_achievements.css;page_leaderboards.css;style.css;leaderboards.html;jquery.equalheights.js;"
    };
};

/**
 * Conditions
 */

AddCondition(0, cf_trigger, "On login success", "Social", "On login succeeded", "Triggered when the user has logged into the social service.", "onFacebookLoginSuccess");

AddCondition(1, cf_trigger, "On login fail", "Social", "On login Failed", "Triggered if the login of the social service has failed.", "onFacebookLoginFail");

AddCondition(2, cf_trigger, "On logout success", "Social", "On logout succeeded", "Triggered when the user has logged out the social service.", "onFacebookLogoutSuccess");

AddCondition(3, cf_trigger, "On logout fail", "Social", "On logout failed", "Triggered if the logout of the social service has failed.", "onFacebookLogoutFail");

AddCondition(4, cf_trigger, "On publish message with dialog success", "Social", "On publish message with dialog success", "Triggered when the message has been successfully published", "onPublishMessageWithDialogSuccess");

AddCondition(5, cf_trigger, "On publish message with dialog fail", "Social", "On publish message with dialog fail", "Triggered when the publishing has failed", "onPublishMessageWithDialogFail");

// Leaderboards
AddCondition(6, cf_trigger, "On score submit success", "Leaderboards", "On score submit success", "Triggered after submitting a score completes successfully", "onFacebookSubmitScoreSuccess");

AddCondition(7, cf_trigger, "On score submit failed", "Leaderboards", "On score submit fail", "Triggered after submitting a score fails to complete successfully.", "onFacebookSubmitScoreFail");

AddCondition(8, cf_trigger, "On request score success", "Leaderboards", "On request score success", "Triggered after requesting a score completes successfully.", "onFacebookRequestScoreSuccess");

AddCondition(9, cf_trigger, "On request score failed", "Leaderboards", "On request score fail", "Triggered after requesting a score fails to complete successfully.", "onFacebookRequestScoreFail");

AddCondition(10, cf_trigger, "On Leaderboard open", "Leaderboards", "On Leaderboards view opened", "Triggered when the leaderboard view opens successfully.", "onFacebookOpenLeaderBoardSuccess");

AddCondition(11, cf_trigger, "On Leaderboard closed", "Leaderboards", "On Leaderboards view closed", "Triggered when the leaderboard view is closed by the user.", "onFacebookOpenLeaderBoardClosed");

// Achievements
AddCondition(12, cf_trigger, "On Achievements view closed", "Achievements", "On Achievements view closed", "Triggered when the Achievements view is closed by the user.", "onFacebookOpenAchievementsClosed");

AddCondition(13, cf_trigger, "On Achievements view open", "Achievements", "On Achievements view open", "Triggered when the Achievements view is open by the user.", "onFacebookOpenAchievementsSuccess");

AddCondition(14, cf_trigger, "On reset achievements complete", "Achievements", "On reset achievements completed", "Triggered when the achievements have been reset.", "onFacebookResetAchievementsComplete");

AddCondition(15, cf_trigger, "On reset achievements fail", "Achievements", "On reset achievements failed", "Triggered if something fails when trying to reset the achievements", "onFacebookResetAchievementsFail");

AddCondition(16, cf_trigger, "On submit achievement success", "Achievements", "On submit achievement success", "Triggered when the achievement has been correctly.", "onFacebookSubmitAchievementComplete");

AddCondition(17, cf_trigger, "On submit achievement fail", "Achievements", "On submit achievement failed", "Triggered if something fails when trying to submit an achievement", "onFacebookSubmitAchievementFail");

AddCondition(18, cf_none, "Is Logged In", "Social", "Is Logged In", "Returns true if the user is loggedin in the Facebook service, false otherwise", "isLoggedIn");

/**
 * Actions
 */

AddAction(0, af_none, "Request login", "Social", "Request Facebook login", "", "facebookRequestLogin");

AddAction(1, af_none, "Request logout", "Social", "Request Facebook logout", "", "facebookRequestLogout");

AddStringParam("Message", "The message to be published.");
AddStringParam("Media URL", "An URL to a media (image, video, ...).");
AddStringParam("Link URL", "An URL to add to the message so the user can click on that link to get more information.");
AddStringParam("Link Text", "The text that will appear in the message link.");
AddStringParam("Link Caption", "The text caption that will appear in the message link.");
AddAction(2, af_none, "Publish message with dialog", "Social", "Publish message with dialog", "Publishes a message with dialog in Facebook", "publishMessageWithDialog");

// Leaderboards
AddNumberParam("Score", "The score to submit to Game Center.");
AddStringParam("Leaderboard", "The name of the leaderboard to submit to, e.g. \"My Game Name\"");
AddAction(3, af_none, "Submit Facebook score", "Leaderboards", "Submit score of {0} to the leaderboard {1}", "Submit a score to the specified leaderboard.", "facebookSubmitScore");

AddStringParam("Leaderboard", "The name of the leaderboard to retrieve from, e.g. \"My Game Name\"");
AddAction(4, af_none, "Request Facebook player score", "Leaderboards", "Request player score", "Requests the user score from the {0} leaderboard", "facebookRequestScore");

AddStringParam("Leaderboard", "The name of the leaderboard to be openned, e.g. \"My Game Name\"");
AddAction(5, af_none, "Open leaderboard", "Leaderboards", "Open Facebook leaderboard", "Opens Facebook leaderboard", "facebookOpenLeaderboard");

// Achievements
AddAction(6, af_none, "Show achievements", "Achievements", "Show Facebook achievements", "Shows the achievements window", "facebookOpenAchievements");

AddAction(7, af_none, "Reset achievements", "Achievements", "Reset Facebook achievements", "Resets the achievements", "facebookResetAchievements");

AddStringParam("Achievement ID", "The ID of the achievement to be sent");
AddAction(8, af_none, "Submit achievement", "Achievements", "Submit Facebook achievement", "Submits an achievement", "facebookSubmitAchievement");

/**
 * Expressions
 */

AddExpression(0, ef_return_string, "", "Leaderboards", "PlayerScore", "Returns the current player score.");

ACESDone();

/**
 * Plugin properties
 */
var property_list = [

    new cr.Property(ept_text,
        "Facebook AppID",
        "",
        "The AppID of your Facebook app (create one at Facebook development site to get yours)",
        ""),
    new cr.Property(ept_text,
        "Facebook channel",
        "",
        "The Facebook channel for your app",
        "")
];

// Called by IDE when a new object type is to be created
function CreateIDEObjectType() {
    return new IDEObjectType();
}

// Class representing an object type in the IDE
function IDEObjectType() {
    assert2(this instanceof arguments.callee, "Constructor called as a function");
}

// Called by IDE when a new object instance of this type is to be created
IDEObjectType.prototype.CreateInstance = function(instance) {
    return new IDEInstance(instance, this);
}

// Class representing an individual instance of an object in the IDE
function IDEInstance(instance, type) {
    assert2(this instanceof arguments.callee, "Constructor called as a function");

    // Save the constructor parameters
    this.instance = instance;
    this.type = type;

    // Set the default property values from the property table
    this.properties = {};

    for (var i = 0; i < property_list.length; i++)
        this.properties[property_list[i].name] = property_list[i].initial_value;
}

// Called by the IDE after all initialization on this instance has been completed
IDEInstance.prototype.OnCreate = function() {}

// Called by the IDE after a property has been changed
IDEInstance.prototype.OnPropertyChanged = function(property_name) {}

// Called by the IDE to draw this instance in the editor
IDEInstance.prototype.Draw = function(renderer) {}

// Called by the IDE when the renderer has been released (ie. editor closed)
// All handles to renderer-created resources (fonts, textures etc) must be dropped.
// Don't worry about releasing them - the renderer will free them - just null out references.
IDEInstance.prototype.OnRendererReleased = function() {}
<|endoftext|>


<commit_before>/**
 * Does a deep selection on a property with support for propertynames which contain a period.
 */

'use strict';
var vm = require('vm');
var _ = require('lodash');
_.mixin(require('underscore.string'));

function runCode(code, obj) {
  try {
    if (code[0] !== '.' && code[0] !== '[') {
      code = '.' + code;
    }
    code = 'wrapper' + code;
    return vm.runInNewContext(code, {wrapper:obj});
  } catch (e) {
    return undefined;
  }
}

function get(obj, path) {
  return runCode(path, obj);
}

function setIfExists(obj, path, value) {
  var setCode = path + '=' + JSON.stringify(value);
  return runCode(setCode, obj);
}

function createFromPath(path, value) {
  var objAsString = path.trim();
  // x.y["q.{r"].z
  if(objAsString[0] !== '{') {
    objAsString = '{"' + objAsString;
  }
  // {"x.y["q.{r"].z
  // Replace all occurrences of [ and . with :{ unless the found characters are part of a string
  objAsString = objAsString.replace(/[\[\.](?=([^"']*["'][^"']*["'])*[^"']*$)/g, '":{"');
  // {"x":{"y":{""q.{r"]":{"z
  // Remove any ] and single quotes
  objAsString = objAsString.replace(/[\]\']/g, '');
  // {"x":{"y":{""q.{r"":{"z
  // Let's make sure that the last property will contain a value of {} at the end
  objAsString = objAsString + '":{';
  // {"x":{"y":{""q.{r"":{"z":{
  // Remove any double " which are caused by the usage of " in the source
  objAsString = objAsString.replace(/"{2,}/g, '"');
  // {"x":{"y":{"q.{r":{"z":{

  // counting the left curly braces which are *not* surrounded by double quotes
  // these will need to be balanced
  var countCurlyBraces = objAsString.match(/[\{](?=([^"]*"[^"]*")*[^"]*$)/g).length;
  // Balance the curly braces
  objAsString = objAsString + _.repeat('}', countCurlyBraces);
  // {"x":{"y":{"q.{r":{"z":{}}}}}

  //Create JSON object
  var JSONobject = JSON.parse(objAsString);
  if (value) {
    //set value if supplied
    setIfExists(JSONobject, path, value);
  }

  return JSONobject;
}

function set(obj, path, value) {
  if (!_.isUndefined(get(obj, path))) {
    return setIfExists(obj, path, value);
  }

  var newObj = createFromPath(path, value);
  _.merge(obj, newObj);

  return obj;
}

module.exports = {
  get: get,
  set: set,
  setIfExists: setIfExists
};
<commit_msg>Optimize performance by reusing a single sandbox<commit_after>/**
 * Does a deep selection on a property with support for propertynames which contain a period.
 */

'use strict';
var vm = require('vm');
var _ = require('lodash');
_.mixin(require('underscore.string'));

var sandbox = vm.createContext({});

function runCode(code, obj) {
  try {
    if (code[0] !== '.' && code[0] !== '[') {
      code = '.' + code;
    }
    code = 'wrapper' + code;
    sandbox.wrapper = obj;
    return vm.runInContext(code, sandbox);
  } catch (e) {
    return undefined;
  }
}

function get(obj, path) {
  return runCode(path, obj);
}

function setIfExists(obj, path, value) {
  var setCode = path + '=' + JSON.stringify(value);
  return runCode(setCode, obj);
}

function createFromPath(path, value) {
  var objAsString = path.trim();
  // x.y["q.{r"].z
  if(objAsString[0] !== '{') {
    objAsString = '{"' + objAsString;
  }
  // {"x.y["q.{r"].z
  // Replace all occurrences of [ and . with :{ unless the found characters are part of a string
  objAsString = objAsString.replace(/[\[\.](?=([^"']*["'][^"']*["'])*[^"']*$)/g, '":{"');
  // {"x":{"y":{""q.{r"]":{"z
  // Remove any ] and single quotes
  objAsString = objAsString.replace(/[\]\']/g, '');
  // {"x":{"y":{""q.{r"":{"z
  // Let's make sure that the last property will contain a value of {} at the end
  objAsString = objAsString + '":{';
  // {"x":{"y":{""q.{r"":{"z":{
  // Remove any double " which are caused by the usage of " in the source
  objAsString = objAsString.replace(/"{2,}/g, '"');
  // {"x":{"y":{"q.{r":{"z":{

  // counting the left curly braces which are *not* surrounded by double quotes
  // these will need to be balanced
  var countCurlyBraces = objAsString.match(/[\{](?=([^"]*"[^"]*")*[^"]*$)/g).length;
  // Balance the curly braces
  objAsString = objAsString + _.repeat('}', countCurlyBraces);
  // {"x":{"y":{"q.{r":{"z":{}}}}}

  //Create JSON object
  var JSONobject = JSON.parse(objAsString);
  if (value) {
    //set value if supplied
    setIfExists(JSONobject, path, value);
  }

  return JSONobject;
}

function set(obj, path, value) {
  if (!_.isUndefined(get(obj, path))) {
    return setIfExists(obj, path, value);
  }

  var newObj = createFromPath(path, value);
  _.merge(obj, newObj);

  return obj;
}

module.exports = {
  get: get,
  set: set,
  setIfExists: setIfExists
};
<|endoftext|>


<commit_before>/**
 * Initializes directories, installs dependencies then starts all
 * configured servers for the Hoodie application
 */

var path = require('path'),
    async = require('async'),
    colors = require('colors'),
    utils = require('./utils'),
    couch = require('./couch'),
    server = require('./server'),
    installer = require('./installer'),
    localtld = require('./localtld'),
    workers = require('./workers'),
    prompt = require('prompt'),
    _ = require('underscore');

/**
 * Initializes and starts a new Hoodie app server
 */

exports.init = function (config, callback) {
    // start the prompt module and set appropriate options
    prompt.start();
    prompt.message = '';
    prompt.delimiter = '';
    prompt.colors = false;

    // show an attempt at the hoodie logo in ascii
    exports.asciiLogo();

    // register services with local-tld
    localtld(config, function (err, config) {
        if (err) {
            return callback(err);
        }

        // configuration for the main www server
        var www = server({
            name: 'www',
            host: config.host,
            port: config.www_port,
            root: path.resolve(config.project_dir, 'www'),
            message: (config.local_tld ?
                'WWW:   ' + config.www_local_url:
                'WWW:   http://' + config.host + ':' + config.www_port
            )
        });

        // configuration for the admin server
        var admin = server({
            name: 'admin',
            host: config.host,
            port: config.admin_port,
            root: path.resolve(__dirname, '../node_modules/hoodie-pocket/www'),
            message: (config.local_tld ?
                'Admin: ' + config.admin_local_url:
                'Admin: http://' + config.host + ':' + config.admin_port
            )
        });

        // start the app
        console.log('Initializing...');
        async.applyEachSeries([
            exports.ensurePaths,
            couch.start,
            installer.install,
            utils.linebreak,
            www,
            admin,
            utils.linebreak,
            workers.startAll
        ],
        config, callback);
    });
};

/**
 * Makes sure the appropriate app directories exists
 */

exports.ensurePaths = function (config, callback) {
    var paths = [
        config.hoodie.path,
        config.hoodie.apps_path,
        config.hoodie.app_path
    ];
    async.map(paths, utils.ensureDir, callback);
};

/**
 * Outputs the Hoodie logo in color ascii art
 */

exports.asciiLogo = function () {
    var lines = [
        [".d$b.  .d$b.", "  .d$$$$$$b.  ", "  .d$$$$$$b.  ", ".d$$$$$$b.  ",  ".d$b.", ".d$$$$$$$$b."],
        ["$$$$$..$$$$$", ".$$$$$$$$$$$b ", ".$$$$$$$$$$$b ", "$$$$$$$$$$b ",  "$$$$$", "$$$$$$$$$$P'"],
        ["$$$$$$$$$$$$", "d$$$$$$$$$$$$b", "d$$$$$$$$$$$$b", "$$$$$$$$$$$b",  "$$$$$", "$$$$$$$$$$b."],
        ["$$$$$$$$$$$$", "Q$$$$$$$$$$$$P", "Q$$$$$$$$$$$$P", "$$$$$$$$$$$P",  "$$$$$", "$$$$$$$$$$P'"],
        ["$$$$$´`$$$$$", "'$$$$$$$$$$$$'", "'$$$$$$$$$$$$'", "$$$$$$$$$$P ",  "$$$$$", "$$$$$$$$$$b."],
        ["'Q$P'  'Q$P'", "  'Q$$$$$$P'  ", "  'Q$$$$$$P'  ", "'Q$$$$$$$P  ",  "'Q$P'", "'Q$$$$$$$$P'"],
        ["", "", "", "",  "", ""],
        [" Hi!", "", "", "",  "", ""]
    ];
    var logo = _.map(lines, function (line) {
        var blue = clc.xterm(25);
        var green = clc.xterm(28);
        var yellow = clc.xterm(214);
        var orange = clc.xterm(202);
        var brown = clc.xterm(240);
        var red = clc.xterm(160);
        return blue(line[0]) +
            green(line[1]) +
            yellow(line[2]) +
            orange(line[3]) +
            brown(line[4]) +
            red(line[5]);
    }).join('\n');

    console.log('\n' + logo + '\n');
};
<commit_msg>require clc-color module in app.js<commit_after>/**
 * Initializes directories, installs dependencies then starts all
 * configured servers for the Hoodie application
 */

var path = require('path'),
    async = require('async'),
    clc = require('cli-color'),
    utils = require('./utils'),
    couch = require('./couch'),
    server = require('./server'),
    installer = require('./installer'),
    localtld = require('./localtld'),
    workers = require('./workers'),
    prompt = require('prompt'),
    _ = require('underscore');

/**
 * Initializes and starts a new Hoodie app server
 */

exports.init = function (config, callback) {
    // start the prompt module and set appropriate options
    prompt.start();
    prompt.message = '';
    prompt.delimiter = '';
    prompt.colors = false;

    // show an attempt at the hoodie logo in ascii
    exports.asciiLogo();

    // register services with local-tld
    localtld(config, function (err, config) {
        if (err) {
            return callback(err);
        }

        // configuration for the main www server
        var www = server({
            name: 'www',
            host: config.host,
            port: config.www_port,
            root: path.resolve(config.project_dir, 'www'),
            message: (config.local_tld ?
                'WWW:   ' + config.www_local_url:
                'WWW:   http://' + config.host + ':' + config.www_port
            )
        });

        // configuration for the admin server
        var admin = server({
            name: 'admin',
            host: config.host,
            port: config.admin_port,
            root: path.resolve(__dirname, '../node_modules/hoodie-pocket/www'),
            message: (config.local_tld ?
                'Admin: ' + config.admin_local_url:
                'Admin: http://' + config.host + ':' + config.admin_port
            )
        });

        // start the app
        console.log('Initializing...');
        async.applyEachSeries([
            exports.ensurePaths,
            couch.start,
            installer.install,
            utils.linebreak,
            www,
            admin,
            utils.linebreak,
            workers.startAll
        ],
        config, callback);
    });
};

/**
 * Makes sure the appropriate app directories exists
 */

exports.ensurePaths = function (config, callback) {
    var paths = [
        config.hoodie.path,
        config.hoodie.apps_path,
        config.hoodie.app_path
    ];
    async.map(paths, utils.ensureDir, callback);
};

/**
 * Outputs the Hoodie logo in color ascii art
 */

exports.asciiLogo = function () {
    var lines = [
        [".d$b.  .d$b.", "  .d$$$$$$b.  ", "  .d$$$$$$b.  ", ".d$$$$$$b.  ",  ".d$b.", ".d$$$$$$$$b."],
        ["$$$$$..$$$$$", ".$$$$$$$$$$$b ", ".$$$$$$$$$$$b ", "$$$$$$$$$$b ",  "$$$$$", "$$$$$$$$$$P'"],
        ["$$$$$$$$$$$$", "d$$$$$$$$$$$$b", "d$$$$$$$$$$$$b", "$$$$$$$$$$$b",  "$$$$$", "$$$$$$$$$$b."],
        ["$$$$$$$$$$$$", "Q$$$$$$$$$$$$P", "Q$$$$$$$$$$$$P", "$$$$$$$$$$$P",  "$$$$$", "$$$$$$$$$$P'"],
        ["$$$$$´`$$$$$", "'$$$$$$$$$$$$'", "'$$$$$$$$$$$$'", "$$$$$$$$$$P ",  "$$$$$", "$$$$$$$$$$b."],
        ["'Q$P'  'Q$P'", "  'Q$$$$$$P'  ", "  'Q$$$$$$P'  ", "'Q$$$$$$$P  ",  "'Q$P'", "'Q$$$$$$$$P'"],
        ["", "", "", "",  "", ""],
        [" Hi!", "", "", "",  "", ""]
    ];
    var logo = _.map(lines, function (line) {
        var blue = clc.xterm(25);
        var green = clc.xterm(28);
        var yellow = clc.xterm(214);
        var orange = clc.xterm(202);
        var brown = clc.xterm(240);
        var red = clc.xterm(160);
        return blue(line[0]) +
            green(line[1]) +
            yellow(line[2]) +
            orange(line[3]) +
            brown(line[4]) +
            red(line[5]);
    }).join('\n');

    console.log('\n' + logo + '\n');
};
<|endoftext|>


<commit_before>var Oro = Oro || {};
Oro.Filter = Oro.Filter || {};

/**
 * Choice filter: filter type as option + filter value as string
 *
 * @class   Oro.Filter.ChoiceFilter
 * @extends Oro.Filter.TextFilter
 */
Oro.Filter.ChoiceFilter = Oro.Filter.TextFilter.extend({
    /**
     * Template for filter criteria
     *
     * @property {function(Object, ?Object=): String}
     */
    popupCriteriaTemplate: _.template(
        '
' +
            '
' +
                '
' +
                    '<button class="btn dropdown-toggle" data-toggle="dropdown">' +
                        'Action' +
                        '' +
                    '</button>' +
                    '
' +
                        '<% _.each(choices, function (hint, value) { %>' +
                            '
<a class="choice_value" href="#" data-value="<%= value %>"><%= hint %>
' +
                        '<% }); %>' +
                    '
' +
                    '<input class="span2" type="text" name="value" value="">' +
                    '<input class="name_input" type="hidden" name="<%= name %>" id="<%= name %>" value=""/>' +
                    '
' +

                '
' +
                '<button class="btn btn-primary filter-update" type="button">Update</button>' +
            '
' +
        '
'
    ),

    /**
     * Selectors for filter criteria elements
     *
     * @property {Object}
     */
    criteriaValueSelectors: {
        value: 'input[name="value"]',
        type: 'input[type="hidden"]'
    },

    /** @property */
    choices: {},

    /**
     * Empty value object
     *
     * @property {Object}
     */
    emptyValue: {
        value: '',
        type: ''
    },

    /**
     * @inheritDoc
     */
    _renderCriteria: function(el) {
        $(el).append(this.popupCriteriaTemplate({
            name: this.name,
            choices: this.choices
        }));
        return this;
    },

    /**
     * @inheritDoc
     */
    _getCriteriaHint: function() {
        var value = this._getDisplayValue();
        if (!value.value) {
            return this.defaultCriteriaHint;
        } else if (_.has(this.choices, value.type)) {
            return this.choices[value.type] + ' "' + value.value + '"'
        } else {
            return '"' + value.value + '"';
        }
    },

    /**
     * @inheritDoc
     */
    _writeDOMValue: function(value) {
        this._setInputValue(this.criteriaValueSelectors.value, value.value);
        this._setInputValue(this.criteriaValueSelectors.type, value.type);
        return this;
    },

    /**
     * @inheritDoc
     */
    _readDOMValue: function() {
        return {
            value: this._getInputValue(this.criteriaValueSelectors.value),
            type: this._getInputValue(this.criteriaValueSelectors.type)
        }
    },

    /**
     * @inheritDoc
     */
    _triggerUpdate: function(newValue, oldValue) {
        if (newValue.value || oldValue.value) {
            this.trigger('update');
        }
    },

    /**
     * Filter events
     *
     * @property
     */
    events: {
        'keyup input': '_onReadCriteriaInputKey',
        'click .filter-update': '_onClickUpdateCriteria',
        'click .filter-criteria-selector': '_onClickCriteriaSelector',
        'click .filter-criteria .filter-criteria-hide': '_onClickCloseCriteria',
        'click .disable-filter': '_onClickDisableFilter',
        'click .choice_value': '_onClickChoiceValue'
    },

    /**
     * Open/close select dropdown
     *
     * @param {Event} e
     * @protected
     */
    _onClickChoiceValue: function(e) {
        var parentDiv = $(e.currentTarget).parent().parent().parent();
        parentDiv.find('.name_input').val($(e.currentTarget).attr('data-value'));
        parentDiv.find('button').html($(e.currentTarget).html());
        e.preventDefault();
    }
});

<commit_msg>Fix filter<commit_after>var Oro = Oro || {};
Oro.Filter = Oro.Filter || {};

/**
 * Choice filter: filter type as option + filter value as string
 *
 * @class   Oro.Filter.ChoiceFilter
 * @extends Oro.Filter.TextFilter
 */
Oro.Filter.ChoiceFilter = Oro.Filter.TextFilter.extend({
    /**
     * Template for filter criteria
     *
     * @property {function(Object, ?Object=): String}
     */
    popupCriteriaTemplate: _.template(
        '
' +
            '
' +
                '
' +
                    '<button class="btn dropdown-toggle" data-toggle="dropdown">' +
                        'Action' +
                        '' +
                    '</button>' +
                    '
' +
                        '<% _.each(choices, function (hint, value) { %>' +
                            '
<a class="choice_value" href="#" data-value="<%= value %>"><%= hint %>
' +
                        '<% }); %>' +
                    '
' +
                    '<input class="span2" type="text" name="value" value="">' +
                    '<input class="name_input" type="hidden" name="<%= name %>" id="<%= name %>" value=""/>' +
                    '
' +

                '
' +
                '<button class="btn btn-primary filter-update" type="button">Update</button>' +
            '
' +
        '
'
    ),

    /**
     * Selectors for filter criteria elements
     *
     * @property {Object}
     */
    criteriaValueSelectors: {
        value: 'input[name="value"]',
        type: 'input[type="hidden"]'
    },

    /** @property */
    choices: {},

    /**
     * Empty value object
     *
     * @property {Object}
     */
    emptyValue: {
        value: '',
        type: ''
    },

    /**
     * @inheritDoc
     */
    _renderCriteria: function(el) {
        $(el).append(this.popupCriteriaTemplate({
            name: this.name,
            choices: this.choices
        }));
        return this;
    },

    /**
     * @inheritDoc
     */
    _getCriteriaHint: function() {
        var value = this._getDisplayValue();
        if (!value.value) {
            return this.defaultCriteriaHint;
        } else if (_.has(this.choices, value.type)) {
            return this.choices[value.type] + ' "' + value.value + '"'
        } else {
            return '"' + value.value + '"';
        }
    },

    /**
     * @inheritDoc
     */
    _writeDOMValue: function(value) {
        this._setInputValue(this.criteriaValueSelectors.value, value.value);
        this._setInputValue(this.criteriaValueSelectors.type, value.type);
        return this;
    },

    /**
     * @inheritDoc
     */
    _readDOMValue: function() {
        return {
            value: this._getInputValue(this.criteriaValueSelectors.value),
            type: this._getInputValue(this.criteriaValueSelectors.type)
        }
    },

    /**
     * @inheritDoc
     */
    _triggerUpdate: function(newValue, oldValue) {
        if (newValue.value || oldValue.value) {
            this.trigger('update');
        }
    },

    /**
     * Filter events
     *
     * @property
     */
    events: {
        'keyup input': '_onReadCriteriaInputKey',
        'click .filter-update': '_onClickUpdateCriteria',
        'click .filter-criteria-selector': '_onClickCriteriaSelector',
        'click .filter-criteria .filter-criteria-hide': '_onClickCloseCriteria',
        'click .disable-filter': '_onClickDisableFilter',
        'click .choice_value': '_onClickChoiceValue'
    },

    /**
     * Open/close select dropdown
     *
     * @param {Event} e
     * @protected
     */
    _onClickChoiceValue: function(e) {
        $(e.currentTarget).parent().parent().find('li').each(function( index ) {
            $(this).removeClass('active');
        });
        $(e.currentTarget).parent().addClass('active');
        var parentDiv = $(e.currentTarget).parent().parent().parent();
        parentDiv.find('.name_input').val($(e.currentTarget).attr('data-value'));
        parentDiv.find('button').html($(e.currentTarget).html() + '');
        e.preventDefault();
    }
});

<|endoftext|>


<commit_before>var MyApp;
var originalLookup = Ember.lookup, lookup, TemplateTests, view, container;

module("Support for {{template}} helper", {
  setup: function() {
    Ember.TESTING_DEPRECATION = true;

    Ember.lookup = lookup = { Ember: Ember };
    MyApp = lookup.MyApp = Ember.Object.create({});
    container = new Ember.Container();
    container.optionsForType('template', { instantiate: false });
    Ember.TESTING_DEPRECATION = true;
  },
  teardown: function() {
    Ember.TESTING_DEPRECATION = false;
    Ember.run(function() {
      if (view) {
        view.destroy();
      }
    });
    Ember.lookup = originalLookup;

    Ember.TESTING_DEPRECATION = false;
  }
});

test("should render other templates via the container", function() {
  container.register('template:sub_template_from_container', Ember.Handlebars.compile('sub-template'));

  view = Ember.View.create({
    container: container,
    template: Ember.Handlebars.compile('This {{template "sub_template_from_container"}} is pretty great.')
  });

  Ember.run(function() {
    view.appendTo('#qunit-fixture');
  });

  equal(Ember.$.trim(view.$().text()), "This sub-template is pretty great.");
});

test("should use the current view's context", function() {
  container.register('template:person_name', Ember.Handlebars.compile("{{firstName}} {{lastName}}"));

  view = Ember.View.create({
    container: container,
    template: Ember.Handlebars.compile('Who is {{template "person_name"}}?')
  });
  view.set('controller', Ember.Object.create({
    firstName: 'Kris',
    lastName: 'Selden'
  }));

  Ember.run(function() {
    view.appendTo('#qunit-fixture');
  });

  equal(Ember.$.trim(view.$().text()), "Who is Kris Selden?");
});
<commit_msg>Revert "ignore deprecation warnings, for testing known deprecated functionality."<commit_after>var MyApp;
var originalLookup = Ember.lookup, lookup, TemplateTests, view, container;

module("Support for {{template}} helper", {
  setup: function() {
    Ember.TESTING_DEPRECATION = true;

    Ember.lookup = lookup = { Ember: Ember };
    MyApp = lookup.MyApp = Ember.Object.create({});
    container = new Ember.Container();
    container.optionsForType('template', { instantiate: false });
  },
  teardown: function() {
    Ember.run(function() {
      if (view) {
        view.destroy();
      }
    });
    Ember.lookup = originalLookup;

    Ember.TESTING_DEPRECATION = false;
  }
});

test("should render other templates via the container", function() {
  container.register('template:sub_template_from_container', Ember.Handlebars.compile('sub-template'));

  view = Ember.View.create({
    container: container,
    template: Ember.Handlebars.compile('This {{template "sub_template_from_container"}} is pretty great.')
  });

  Ember.run(function() {
    view.appendTo('#qunit-fixture');
  });

  equal(Ember.$.trim(view.$().text()), "This sub-template is pretty great.");
});

test("should use the current view's context", function() {
  container.register('template:person_name', Ember.Handlebars.compile("{{firstName}} {{lastName}}"));

  view = Ember.View.create({
    container: container,
    template: Ember.Handlebars.compile('Who is {{template "person_name"}}?')
  });
  view.set('controller', Ember.Object.create({
    firstName: 'Kris',
    lastName: 'Selden'
  }));

  Ember.run(function() {
    view.appendTo('#qunit-fixture');
  });

  equal(Ember.$.trim(view.$().text()), "Who is Kris Selden?");
});
<|endoftext|>


<commit_before>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2014 Gilles Bedel
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {
    var rootUrl = get_tatoeba_root_url();
    $(document).watch("addrule", function() {
        // Show the transcribe buttons if there are some
        // hidden transcriptions
        $('.needsReview:hidden').each(function(index) {
            var transcr = $(this);
            if (transcr.closest('.translations').length == 0) {
                /* Transcription of the main sentence, not a translation */
                /* Move the show button in the menu */
                var menu = transcr.closest('.sentences_set').find('.transcribe-buttons');
                var button = transcr.find('.transcribe.option');
                button.click(function(event) {
                    button.remove();
                    transcr.toggle(true);
                });
                button.toggle(true);
                menu.empty().append(button);
            }
        });

        // For transcriptions marked with class 'blend',
        // replace the sentence content with the transcription
        $('.transcriptionContainer.blend').each(function() {
            var container = $(this);
            var transcr = container.find('.transcription');
            var sentence = container.closest('.sentence').find('.content .text');
            sentence.data('text', sentence.text());
            sentence.html(transcr.html());
            container.toggle(false);

            var isMainSentence = container.closest('.translations').length == 0;
            if (isMainSentence) {
                // Allow to unblend back the transcription and the sentence
                // by clicking on the transcribe button
                var menu = container.closest('.sentences_set').find('.transcribe-buttons');
                var button = container.find('.transcribe.option');
                button.click(function(event) {
                    sentence.text(sentence.data('text'));
                    button.remove();
                    container.toggle(true);
                });
                button.toggle(true);
                menu.empty().append(button);
            }
        });

        function escapeUnicodeChar(c) {
            var code = c.charCodeAt(0);
            if (code >= 128) {
               c = '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
            }
            return c;
        }

        function escapeUnicodeString(input) {
            var output = '';
            for (var i = 0, l = input.length; i < l; i++) {
                output += escapeUnicodeChar(input.charAt(i));
            }
            return output;
        }

        function uniRegExp(regex, flags) {
           return new RegExp(escapeUnicodeString(regex), flags);
        }

        function markupToStored(lang, text) {
            if (lang == 'ja-Hrkt') {
                // Converts the kanji｛reading｝ notation into [kanji|reading]
                var hiragana = 'ぁ-ゖーゝゞ'; // \p{Hiragana}
                var katakana = 'ァ-ヺーヽヾ'; // \p{Katakana}
                var punct = '　-〄〇-〠・'; // 。、「」etc.
                punct += '！＂＃＇（），．／：；？［＼］＾｀～｟｠'; // fullwitdh forms
                punct += ' '; // space
                var regex = '([^｝' + hiragana + katakana + punct + ']*)｛([^｝]*)｝';
                text = text.replace(uniRegExp(regex, 'g'), '[$1|$2]');
                text = text.replace(uniRegExp('｜', 'g'),  '|');
            }
            return text;
        }

        $('.editable.transcription').each(function() {
            var div = $(this);
            var previousValue = {};

            sentenceId = div.parent().parent().attr('data-sentence-id');
            script = div.attr('data-script');
            saveUrl = rootUrl + '/transcriptions/save/' + sentenceId + '/' + script;

            $(this).editable(saveUrl, {
                type      : 'textarea',
                cancel    : div.attr('data-cancel'),
                submit    : div.attr('data-submit'),
                event     : 'edit_transcription',
                id        : 'divId',
                height    : false, // disable autoheight, we'll set it in onedit()
                onedit    : function(settings, self) {
                    $(self).find("rt").hide();
                    settings.height = $(self).height();
                    $(self).find("rt").show();
                },
                data : function(value, settings) {
                    var contents = $('').html(value);
                    return contents.find('.markup').text() || contents.text();
                },
                ajaxoptions : {
                    success : function(result, status) {
                        div.editing = false;
                        div.parent().replaceWith(result);
                    }
                },
                onsubmit  : function(settings, self) {
                    // Save the submitted value to restore it on error
                    $(self).find("textarea").each(function(idx) {
                        previousValue[idx] = $(this).val();
                    });

                    // Format entered transcription
                    var input = $(this).find("textarea");
                    var entered = input.val();
                    var storedFormat = markupToStored($(self).attr('lang'), entered);
                    input.val(storedFormat);

                    // Handle reset button
                    if (self.resetClicked) {
                        self.resetClicked = false;
                        settings.target = settings.target.replace(/\/save\//, '/reset/');
                    }
                    return true;
                },
                onerror   : function (settings, self, xhr) {
                    // Go back to the previous editing state
                    $(self).html(self.revert);
                    self.editing = false;
                    $(self).trigger(settings.event);

                    // Restore the previous value
                    $(self).find("textarea").each(function(idx) {
                        $(this).val(previousValue[idx]);
                    });

                    // Display errors
                    $(self).prepend(xhr.responseText);

                    // Restore after reset button hackery
                    settings.target = settings.target.replace(/\/reset\//, '/save/');
                    return false; // don't reset the form
                },
                indicator : "

",
                tooltip   : div.attr('title'),
                cssclass  : 'editInPlaceForm',
                onblur    : 'ignore'
            }).bind('edit_transcription', function(e) {
                $(this).find('textarea').keydown(function(event) {
                    if (event.which == 13)
                        $(this).closest('form').submit();
                });
                // Add third reset button
                if ($(this).find('button').length == 2) {
                    var editable = this;
                    var reset = $('<button type="submit"/>');
                    reset.html(div.attr('data-reset'));
                    reset.click(function(event) {
                        // hack to distinguish submit event
                        // triggered from this button
                        editable.resetClicked = true;
                    });
                    $(editable).find('form').append(reset);
                }
            });

            $(".edit_transcription").bind("click", function() {
                $(this).closest('.transcriptionContainer').find('.transcription').trigger("edit_transcription");
            });
        });

        // review button
        $('.transcriptionContainer .option.review').click(function() {
            transcription = $(this).closest('.transcriptionContainer').find('.transcription');
            transcription.trigger('edit_transcription');
            transcription.find('form').submit();
        });
    });
});
<commit_msg>Fix transcribe button display<commit_after>/**
 * Tatoeba Project, free collaborative creation of multilingual corpuses project
 * Copyright (C) 2014 Gilles Bedel
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function() {
    var rootUrl = get_tatoeba_root_url();
    $(document).watch("addrule", function() {
        // Show the transcribe buttons if there are some
        // hidden transcriptions
        $('.needsReview:hidden').each(function(index) {
            var transcr = $(this);
            var menu = transcr.closest('.mainSentence')
                              .closest('.sentences_set')
                              .find('.transcribe-buttons');
            if (menu.length) {
                /* Transcription of the main sentence, not a translation */
                /* Move the show button in the menu */
                var button = transcr.find('.transcribe.option');
                button.click(function(event) {
                    button.remove();
                    transcr.toggle(true);
                });
                button.toggle(true);
                menu.empty().append(button);
            }
        });

        // For transcriptions marked with class 'blend',
        // replace the sentence content with the transcription
        $('.transcriptionContainer.blend').each(function() {
            var container = $(this);
            var transcr = container.find('.transcription');
            var sentence = container.closest('.sentence').find('.content .text');
            sentence.data('text', sentence.text());
            sentence.html(transcr.html());
            container.toggle(false);

            var isMainSentence = container.closest('.translations').length == 0;
            if (isMainSentence) {
                // Allow to unblend back the transcription and the sentence
                // by clicking on the transcribe button
                var menu = container.closest('.sentences_set').find('.transcribe-buttons');
                var button = container.find('.transcribe.option');
                button.click(function(event) {
                    sentence.text(sentence.data('text'));
                    button.remove();
                    container.toggle(true);
                });
                button.toggle(true);
                menu.empty().append(button);
            }
        });

        function escapeUnicodeChar(c) {
            var code = c.charCodeAt(0);
            if (code >= 128) {
               c = '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
            }
            return c;
        }

        function escapeUnicodeString(input) {
            var output = '';
            for (var i = 0, l = input.length; i < l; i++) {
                output += escapeUnicodeChar(input.charAt(i));
            }
            return output;
        }

        function uniRegExp(regex, flags) {
           return new RegExp(escapeUnicodeString(regex), flags);
        }

        function markupToStored(lang, text) {
            if (lang == 'ja-Hrkt') {
                // Converts the kanji｛reading｝ notation into [kanji|reading]
                var hiragana = 'ぁ-ゖーゝゞ'; // \p{Hiragana}
                var katakana = 'ァ-ヺーヽヾ'; // \p{Katakana}
                var punct = '　-〄〇-〠・'; // 。、「」etc.
                punct += '！＂＃＇（），．／：；？［＼］＾｀～｟｠'; // fullwitdh forms
                punct += ' '; // space
                var regex = '([^｝' + hiragana + katakana + punct + ']*)｛([^｝]*)｝';
                text = text.replace(uniRegExp(regex, 'g'), '[$1|$2]');
                text = text.replace(uniRegExp('｜', 'g'),  '|');
            }
            return text;
        }

        $('.editable.transcription').each(function() {
            var div = $(this);
            var previousValue = {};

            sentenceId = div.parent().parent().attr('data-sentence-id');
            script = div.attr('data-script');
            saveUrl = rootUrl + '/transcriptions/save/' + sentenceId + '/' + script;

            $(this).editable(saveUrl, {
                type      : 'textarea',
                cancel    : div.attr('data-cancel'),
                submit    : div.attr('data-submit'),
                event     : 'edit_transcription',
                id        : 'divId',
                height    : false, // disable autoheight, we'll set it in onedit()
                onedit    : function(settings, self) {
                    $(self).find("rt").hide();
                    settings.height = $(self).height();
                    $(self).find("rt").show();
                },
                data : function(value, settings) {
                    var contents = $('').html(value);
                    return contents.find('.markup').text() || contents.text();
                },
                ajaxoptions : {
                    success : function(result, status) {
                        div.editing = false;
                        div.parent().replaceWith(result);
                    }
                },
                onsubmit  : function(settings, self) {
                    // Save the submitted value to restore it on error
                    $(self).find("textarea").each(function(idx) {
                        previousValue[idx] = $(this).val();
                    });

                    // Format entered transcription
                    var input = $(this).find("textarea");
                    var entered = input.val();
                    var storedFormat = markupToStored($(self).attr('lang'), entered);
                    input.val(storedFormat);

                    // Handle reset button
                    if (self.resetClicked) {
                        self.resetClicked = false;
                        settings.target = settings.target.replace(/\/save\//, '/reset/');
                    }
                    return true;
                },
                onerror   : function (settings, self, xhr) {
                    // Go back to the previous editing state
                    $(self).html(self.revert);
                    self.editing = false;
                    $(self).trigger(settings.event);

                    // Restore the previous value
                    $(self).find("textarea").each(function(idx) {
                        $(this).val(previousValue[idx]);
                    });

                    // Display errors
                    $(self).prepend(xhr.responseText);

                    // Restore after reset button hackery
                    settings.target = settings.target.replace(/\/reset\//, '/save/');
                    return false; // don't reset the form
                },
                indicator : "

",
                tooltip   : div.attr('title'),
                cssclass  : 'editInPlaceForm',
                onblur    : 'ignore'
            }).bind('edit_transcription', function(e) {
                $(this).find('textarea').keydown(function(event) {
                    if (event.which == 13)
                        $(this).closest('form').submit();
                });
                // Add third reset button
                if ($(this).find('button').length == 2) {
                    var editable = this;
                    var reset = $('<button type="submit"/>');
                    reset.html(div.attr('data-reset'));
                    reset.click(function(event) {
                        // hack to distinguish submit event
                        // triggered from this button
                        editable.resetClicked = true;
                    });
                    $(editable).find('form').append(reset);
                }
            });

            $(".edit_transcription").bind("click", function() {
                $(this).closest('.transcriptionContainer').find('.transcription').trigger("edit_transcription");
            });
        });

        // review button
        $('.transcriptionContainer .option.review').click(function() {
            transcription = $(this).closest('.transcriptionContainer').find('.transcription');
            transcription.trigger('edit_transcription');
            transcription.find('form').submit();
        });
    });
});
<|endoftext|>


<commit_before>'use strict';
var assert = require('assert');
var should = require('should');
var fs = require('fs');
var twitter = require('../index');
var noCache = new twitter('xxx', 'xxx', 'xxx', 'xxx', false);
var cache = new twitter('xxx', 'xxx', 'xxx', 'xxx', true);

//mockups
noCache.oa = {};
cache.oa = {};
noCache.oa.get = function(a,b,c,callback){
  callback({error: 'none'}, {test: 'test'});
};
noCache.oa.post = function(a,b,c,d,callback){
  callback({error: 'none'}, {test: 'test'});
};
cache.oa.get = function(a,b,c,callback){
  callback({error: 'none'}, {test: 'test'});
};

describe('Globals: ', function(){
  it('Object should exist', function () {
    assert(typeof twitter, 'function');
  });
});

describe('Events emmiters without cache: ', function(){
  it('Get data works', function () {
    noCache.on('get:whatever', function(error, data){
      data.test.should.equal('test');
    });
  });
  it('Post data works', function () {
    noCache.on('post:whatever', function(error, data){
      data.test.should.equal('test');
    });
  });
});

describe('Callbacks without cache: ', function(){
  it('Get data works', function () {
    noCache.get('whatever', function(error, data) {
      data.test.should.equal('test');
    });
  });
  it('Post data works', function () {
    noCache.post('whatever', {}, function(error, data) {
      data.test.should.equal('test');
    });
  });
});

describe('Event emmiters Callbacks with cache: ', function(){
  it('Get data works', function () {
    cache.on('get:whatever2', function(error, data) {
      data.test.should.equal('test');
    }).get('whatever2');
  });
});

describe('Callbacks with cache: ', function(){
  it('Get data works', function () {
    cache.get('whatever', function(error, data) {
      data.test.should.equal('test');
    });
    cache.oa.get = function(a,b,c,callback){
      callback({error: 'none'}, {test: 'test2'});
    };
    cache.get('whatever', function(error, data) {
      data.test.should.equal('test');
      fs.unlink('cache/whatever.json');
    });
  });
});
<commit_msg>test fix<commit_after>'use strict';
var assert = require('assert');
var should = require('should');
var fs = require('fs');
var twitter = require('../index');
var noCache = new twitter('xxx', 'xxx', 'xxx', 'xxx', false);
var cache = new twitter('xxx', 'xxx', 'xxx', 'xxx', 3600);

//mockups
noCache.oa = {};
cache.oa = {};
noCache.oa.get = function(a,b,c,callback){
  callback({error: 'none'}, {test: 'test'});
};
noCache.oa.post = function(a,b,c,d,callback){
  callback({error: 'none'}, {test: 'test'});
};
cache.oa.get = function(a,b,c,callback){
  callback({error: 'none'}, {test: 'test'});
};

describe('Globals: ', function(){
  it('Object should exist', function () {
    assert(typeof twitter, 'function');
  });
});

describe('Events emmiters without cache: ', function(){
  it('Get data works', function () {
    noCache.on('get:whatever', function(error, data){
      data.test.should.equal('test');
    });
  });
  it('Post data works', function () {
    noCache.on('post:whatever', function(error, data){
      data.test.should.equal('test');
    });
  });
});

describe('Callbacks without cache: ', function(){
  it('Get data works', function () {
    noCache.get('whatever', function(error, data) {
      data.test.should.equal('test');
    });
  });
  it('Post data works', function () {
    noCache.post('whatever', {}, function(error, data) {
      data.test.should.equal('test');
    });
  });
});

describe('Event emmiters Callbacks with cache: ', function(){
  it('Get data works', function () {
    cache.on('get:whatever2', function(error, data) {
      data.test.should.equal('test');
    }).get('whatever2');
  });
});

describe('Callbacks with cache: ', function(){
  it('Get data works', function () {
    cache.get('whatever', function(error, data) {
      data.test.should.equal('test');
    });
    cache.oa.get = function(a,b,c,callback){
      callback({error: 'none'}, {test: 'test2'});
    };
    cache.get('whatever', function(error, data) {
      data.test.should.equal('test');
      fs.unlink('cache/whatever.json');
    });
  });
});
<|endoftext|>


<commit_before>var optimist = require('optimist'),
    http = require('http'),
    https = require('https'),
    argv = optimist.argv,
    fs = require('fs'),
    path = require('path'),
    zlib = require('zlib'),
    tar = require('tar'),
    url = require('url'),
    prompt = require('prompt'),
    Auth = require('./auth');

var supportedTemplates = {
  'angular': {
    'url': 'https://codeload.github.com/firebase/angularFire-seed/legacy.tar.gz/master',
    'public': '.' + path.sep + 'app',
    'rules': '.' + path.sep + 'config' + path.sep + 'security-rules.json',
    'config': './app/js/config.js',
    'configRegex': /INSTANCE/
  }
};

var routes = {
  init: function() {
    this.settingsFile = path.resolve('./firebase.json');
    if (fs.existsSync(this.settingsFile)) {
      console.log('Directory already initialized');
      return;
    }
    var that = this,
        schema = {
          properties: {
            firebase: {
              required: true,
              pattern: /^[a-z0-9]([a-z0-9-]*[a-z0-9]|)$/,
              description: 'Firebase',
              message: 'Please enter the firebase you wish to associate this ' +
                       'app with'
            }
          }
        };
    prompt.get(schema, function(err, result) {
      if (err) {
        return;
      }
      console.log('Initializing app into current directory');
      Auth.checkCanAccess(result.firebase, function(err) {
        if (err) {
          console.log('You do not have permission to use that Firebase');
          return;
        }
        console.log('Writing firebase.json settings file');
        var settings = {
          'firebase': result.firebase,
          'public': '.', // TODO: prompt for public directory?
          'rules': '.' + path.sep + 'rules.json'
        };
        var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
        try {
          fs.writeFileSync(that.settingsFile, settingsJSON);
          console.log('Done')
        } catch(err) {
          console.log('Could not initialize app');
        }
      });
    });
  },
  bootstrap: function() {
    var that = this,
        schema = {
          properties: {
            firebase: {
              required: true,
              pattern: /^[a-z0-9]([a-z0-9-]*[a-z0-9]|)$/,
              description: 'Firebase',
              message: 'Please enter the firebase you wish to associate this ' +
                       'app with'
            },
            template: {
              required: true,
              pattern: /^[a-z]+$/,
              description: 'Template',
              message: 'Please enter a valid template'
            }
          }
        };
    prompt.get(schema, function(err, result) {
      if (err) {
        return;
      }
      if (!supportedTemplates.hasOwnProperty(result.template)) {
        console.log('Template not supported. Available templates are:');
        console.log(Object.keys(supportedTemplates).join(', '));
        return;
      }
      Auth.checkCanAccess(result.firebase, function(err) {
        if (err) {
          console.log('You do not have permission to use that Firebase');
          return;
        }

        var dir = result.firebase;
        var projectDir = path.resolve(dir);
        if (fs.existsSync(projectDir)) {
          var i = 1;
          do {
            dir = result.firebase + '_' + i++;
            projectDir = path.resolve(dir);
          } while (fs.existsSync(projectDir));
        }
        console.log('Creating directory ' + dir);
        try {
          fs.mkdirSync(projectDir, '0755');
        } catch(err) {
          console.log('Could not create new directory');
          return;
        }

        console.log('Downloading and unpacking template');
        var gunzip = zlib.createGunzip();
        var untar = tar.Extract({
          path: projectDir,
          strip: 1
        });
        var urlParts = url.parse(supportedTemplates[result.template].url);
        var protocol, port;
        if (urlParts.protocol === 'https:') {
          protocol = https;
          port = 443;
        } else {
          protocol = http;
          port = 80;
        }
        if (urlParts.port) {
          port = urlParts.port;
        }
        var request = protocol.get({
          host: urlParts.hostname,
          path: urlParts.pathname,
          port: port
        });
        request.on('response', function(response) {
          try {
            response.pipe(gunzip).pipe(untar);
          } catch (err) {
            console.log('Could not download template');
            return
          }
          response.on('end', function() {
            var config = path.join(
                           projectDir,
                           supportedTemplates[result.template].config
                         );
            try {
              var data = fs.readFileSync(config, 'utf8');
              var replaced = data.replace(
                               supportedTemplates[result.template].configRegex,
                               result.firebase
                             );
              fs.writeFileSync(config, replaced);
            } catch (err) {
              console.log(err);
              console.log('Couldn\'t update template with project settings');
              return;
            }

            console.log('Writing firebase.json settings file');
            var settings = {
              'firebase': result.firebase,
              'public': supportedTemplates[result.template]['public'],
              'rules': supportedTemplates[result.template]['rules']
            };
            var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
            var settingsFile = path.join(projectDir, 'firebase.json');
            try {
              fs.writeFileSync(settingsFile, settingsJSON);
            } catch(err) {
              console.log('Could not save settings file');
              return;
            }
            console.log('Done');
          });
        });
      });
    });
  },
  deploy: function() {
    console.log('deploy');
  }
};

function App() {
  var that = this;
  if ((argv._.length > 1) && (routes.hasOwnProperty(argv._[1]))) {
    Auth.requireLogin(function(err) {
      if (err) {
        console.log("Sorry, we couldn't log you in");
        return;
      }
      routes[argv._[1]].bind(that)();
    });
  } else {
    // TODO: Print module level help
    optimist.showHelp();
  }
}

module.exports = App;
<commit_msg>formatting<commit_after>var optimist = require('optimist'),
    http = require('http'),
    https = require('https'),
    argv = optimist.argv,
    fs = require('fs'),
    path = require('path'),
    zlib = require('zlib'),
    tar = require('tar'),
    url = require('url'),
    prompt = require('prompt'),
    Auth = require('./auth');

var supportedTemplates = {
  'angular': {
    'url': 'https://codeload.github.com/firebase/angularFire-seed/' +
              'legacy.tar.gz/master',
    'public': '.' + path.sep + 'app',
    'rules': '.' + path.sep + 'config' + path.sep + 'security-rules.json',
    'config': './app/js/config.js',
    'configRegex': /INSTANCE/
  }
};

var routes = {
  init: function() {
    this.settingsFile = path.resolve('./firebase.json');
    if (fs.existsSync(this.settingsFile)) {
      console.log('Directory already initialized');
      return;
    }
    var that = this,
        schema = {
          properties: {
            firebase: {
              required: true,
              pattern: /^[a-z0-9]([a-z0-9-]*[a-z0-9]|)$/,
              description: 'Firebase',
              message: 'Please enter the firebase you wish to associate this ' +
                       'app with'
            }
          }
        };
    prompt.get(schema, function(err, result) {
      if (err) {
        return;
      }
      console.log('Initializing app into current directory');
      Auth.checkCanAccess(result.firebase, function(err) {
        if (err) {
          console.log('You do not have permission to use that Firebase');
          return;
        }
        console.log('Writing firebase.json settings file');
        var settings = {
          'firebase': result.firebase,
          'public': '.', // TODO: prompt for public directory?
          'rules': '.' + path.sep + 'rules.json'
        };
        var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
        try {
          fs.writeFileSync(that.settingsFile, settingsJSON);
          console.log('Done')
        } catch(err) {
          console.log('Could not initialize app');
        }
      });
    });
  },
  bootstrap: function() {
    var that = this,
        schema = {
          properties: {
            firebase: {
              required: true,
              pattern: /^[a-z0-9]([a-z0-9-]*[a-z0-9]|)$/,
              description: 'Firebase',
              message: 'Please enter the firebase you wish to associate this ' +
                       'app with'
            },
            template: {
              required: true,
              pattern: /^[a-z]+$/,
              description: 'Template',
              message: 'Please enter a valid template'
            }
          }
        };
    prompt.get(schema, function(err, result) {
      if (err) {
        return;
      }
      if (!supportedTemplates.hasOwnProperty(result.template)) {
        console.log('Template not supported. Available templates are:');
        console.log(Object.keys(supportedTemplates).join(', '));
        return;
      }
      Auth.checkCanAccess(result.firebase, function(err) {
        if (err) {
          console.log('You do not have permission to use that Firebase');
          return;
        }

        var dir = result.firebase;
        var projectDir = path.resolve(dir);
        if (fs.existsSync(projectDir)) {
          var i = 1;
          do {
            dir = result.firebase + '_' + i++;
            projectDir = path.resolve(dir);
          } while (fs.existsSync(projectDir));
        }
        console.log('Creating directory ' + dir);
        try {
          fs.mkdirSync(projectDir, '0755');
        } catch(err) {
          console.log('Could not create new directory');
          return;
        }

        console.log('Downloading and unpacking template');
        var gunzip = zlib.createGunzip();
        var untar = tar.Extract({
          path: projectDir,
          strip: 1
        });
        var urlParts = url.parse(supportedTemplates[result.template].url);
        var protocol, port;
        if (urlParts.protocol === 'https:') {
          protocol = https;
          port = 443;
        } else {
          protocol = http;
          port = 80;
        }
        if (urlParts.port) {
          port = urlParts.port;
        }
        var request = protocol.get({
          host: urlParts.hostname,
          path: urlParts.pathname,
          port: port
        });
        request.on('response', function(response) {
          try {
            response.pipe(gunzip).pipe(untar);
          } catch (err) {
            console.log('Could not download template');
            return
          }
          response.on('end', function() {
            var config = path.join(
                           projectDir,
                           supportedTemplates[result.template].config
                         );
            try {
              var data = fs.readFileSync(config, 'utf8');
              var replaced = data.replace(
                               supportedTemplates[result.template].configRegex,
                               result.firebase
                             );
              fs.writeFileSync(config, replaced);
            } catch (err) {
              console.log(err);
              console.log('Couldn\'t update template with project settings');
              return;
            }

            console.log('Writing firebase.json settings file');
            var settings = {
              'firebase': result.firebase,
              'public': supportedTemplates[result.template]['public'],
              'rules': supportedTemplates[result.template]['rules']
            };
            var settingsJSON = JSON.stringify(settings, null, 2) + "\n";
            var settingsFile = path.join(projectDir, 'firebase.json');
            try {
              fs.writeFileSync(settingsFile, settingsJSON);
            } catch(err) {
              console.log('Could not save settings file');
              return;
            }
            console.log('Done');
          });
        });
      });
    });
  },
  deploy: function() {
    console.log('deploy');
  }
};

function App() {
  var that = this;
  if ((argv._.length > 1) && (routes.hasOwnProperty(argv._[1]))) {
    Auth.requireLogin(function(err) {
      if (err) {
        console.log("Sorry, we couldn't log you in");
        return;
      }
      routes[argv._[1]].bind(that)();
    });
  } else {
    // TODO: Print module level help
    optimist.showHelp();
  }
}

module.exports = App;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var webpack = require('webpack');

module.exports = function(main) {
  var modulePaths = [
    'web_modules',
    'node_modules',
    path.resolve(__dirname, '../web_modules'),
    path.resolve(__dirname, '../node_modules')
  ];

  return {
    devtool: 'cheap-module-source-map ',
    entry: [
        'webpack-dev-server/client?http://0.0.0.0:8080',
        'webpack/hot/only-dev-server',
        path.join(__dirname, 'debug-host.jsx')
    ],
    output: {
      path: __dirname,
      filename: 'bundle.js'
    },
    resolve: {
      extensions: ['', '.js', '.jsx'],
      modulesDirectories: modulePaths,
      alias: {
        'react-pack-debug-root-component': main
      }
    },
    resolveLoader: {
      modulesDirectories: modulePaths
    },
    module: {
      loaders: [
        {
          test: /\.jsx$/,
          loaders: ['react-hot', 'babel-loader']
        },
        {
          test: /\.less$/,
          loader: 'style-loader!css-loader!less-loader'
        },
        {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        }
      ]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('development')
        },
        '__react_build': {
          moduleName: JSON.stringify(path.basename(main, path.extname(main)))
        }
      })
    ]
  };
};
<commit_msg>apply babel transforms to ordinary js<commit_after>'use strict';

var path = require('path');
var webpack = require('webpack');

module.exports = function(main) {
  var modulePaths = [
    'web_modules',
    'node_modules',
    path.resolve(__dirname, '../web_modules'),
    path.resolve(__dirname, '../node_modules')
  ];

  return {
    devtool: 'cheap-module-source-map ',
    entry: [
        'webpack-dev-server/client?http://0.0.0.0:8080',
        'webpack/hot/only-dev-server',
        path.join(__dirname, 'debug-host.jsx')
    ],
    output: {
      path: __dirname,
      filename: 'bundle.js'
    },
    resolve: {
      extensions: ['', '.js', '.jsx'],
      modulesDirectories: modulePaths,
      alias: {
        'react-pack-debug-root-component': main
      }
    },
    resolveLoader: {
      modulesDirectories: modulePaths
    },
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['react-hot', 'babel-loader']
        },
        {
          test: /\.less$/,
          loader: 'style-loader!css-loader!less-loader'
        },
        {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        }
      ]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('development')
        },
        '__react_build': {
          moduleName: JSON.stringify(path.basename(main, path.extname(main)))
        }
      })
    ]
  };
};
<|endoftext|>