<commit_before>/*
*   create by vinc 31 dec 2016
*   canvas tiny process
*   @ cache
*   @
*   @
*   @
*
*/

;(function(root, fn){
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = fn.call(root) :
	typeof define === 'function' && define.amd ? define(function(){ return fn.call(root) }) :
	(root.Meg = fn());
}(this, function(){

    //公共方法
    var util = {
		//query
		find : function(selector){
			return document.querySelector(selector);
		},
		finds : function(selectors){
			return Array.prototype.slice.call(document.querySelectorAll(selectors));
		},

		//raf
		raf : function(){
			return window.requestAnimationFrame || window.webkitRequestAnimationFrame ||  window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback){window.setTimeout(callback, 1000 / 60); };
    		},

		//判断是否数组
		isArray : function(arr){
				return toString.apply(arr) === '[object Array]';
		},

		//判断是否函数 typeof == 'function'
		isFunction : function(f){
				return Object.prototype.toString.call(f) === '[object Function]';
		},

		//一致性
		adler32 : function(data){
					var MOD = 65521;
					var a = 1;
					var b = 0;
					for (var i = 0; i < data.length >>> 0 ; i++) {
						a = (a + data.charCodeAt(i)) % MOD;
						b = (b + a) % MOD;
					}
					return a | (b << 16);
		}

    }

    //常量
    var CONSTANT = {
		//背景图片base64
		BACKIMG :  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAAHmWi9wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAMBJREFUeNpinDFjemBgIAMaePv2zX8MwMSADdBKFCCAGF++fIEuBHQEYb3UFAIIIOwBQWzQEOvVwaMOIICwBDoWRZjRQKaNo4rorQgggBiBCVpISJiBGoCJgXpg1KxRs0aiWQABxPj79+93795SbhAwUxNVLo+G/ahZo2aNmjVq1qhZI8wsgADt1zERADAMAsD6t5B4bRHRgeGj4I8FctKPM3ObLp6fk7w1eSwsLCwsLCwsLCwsrE5WvrHdrTLF8wBDaPAHu14WwgAAAABJRU5ErkJggg=="
    };

    function Meg(options) {
		if ( !(this instanceof Meg)) return new Meg(options);
      	this.init(options);
    }

	var mg = Meg.prototype;

    mg.init = function(options){
	options = options || {};
//        this.methods = {};
//        this.maps = {};
//        this.cache = {};

        var defaults = {
            el: '',         	// 根节点
            maps: {},           // 初始化命中表
            cache: true,        // 是否使用缓存
	    rcWidth: '1000',	// 默认限制最大宽度
	    rcHeight: '600',	// 默认限制最大高度

            //debug: false,       // 如果开启debug模式，则进入自动检索当前目录文件模式
        };

        for (var key in defaults) {
           	this[key] = options.hasOwnProperty(key) ? options[key] : defaults[key];
        }

	//节点
	this.fragment();

        return this;
    }

	mg.fragment = function(){
		var width,height;

		if(!!this.el){
			fragment = util.find(this.el);
			width = fragment.width < this.rcWidth ? fragment.width : this.rcWidth;
			height = fragment.height < this.rcHeight ? fragment.height : this.rcHeight;
		}else{
			fragment = document.createDocumentFragment();
			document.body.style.cssText = "margin:0;padding:0;background-image:url("+ CONSTANT.BACKIMG +");background-position: center center;background-repeat: repeat;background-size: 20px 20px;overflow: hidden";
		}

		var container = document.createElement("div");
				container.id = 'pixel';
				container.style.cssText = window.innerWidth < this.rcWidth ? "margin:0;padding:0;width:100%;height:100%;position:absolute;overflow:hidden"
				:"width:"+ this.rcWidth +"px;height:"+ this.rcHeight +"px;margin:0 auto;top:50%;transform:translate(0,-50%);;position:relative;overflow:hidden";

			var canvas = document.createElement("canvas");
			var ctx = canvas.getContext("2d");  console.log(window.innerWidth,window.innerHeight);
				canvas.width = width || (window.innerWidth < this.rcWidth ? window.innerWidth : this.rcWidth);
				canvas.height = height || (window.innerHeight < this.rcHeight ? window.innerHeight : this.rcHeight);
				container.appendChild(canvas);

			console.log(window.innerWidth,window.innerHeight)

			fragment.appendChild(container);
			document.body.appendChild(fragment);
	};

	return Meg;

}))
<commit_msg>Update meg.js<commit_after>/*
*   create by vinc 31 dec 2016
*   canvas tiny process
*   @ cache
*   @
*   @
*   @
*
*/

;(function(root, fn){
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = fn.call(root) :
	typeof define === 'function' && define.amd ? define(function(){ return fn.call(root) }) :
	(root.Meg = fn());
}(this, function(){

    //公共方法
    var util = {
		//query
		find : function(selector){
			return document.querySelector(selector);
		},
		finds : function(selectors){
			return Array.prototype.slice.call(document.querySelectorAll(selectors));
		},

		//raf
		raf : function(){
			return window.requestAnimationFrame || window.webkitRequestAnimationFrame ||  window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback){window.setTimeout(callback, 1000 / 60); };
    		},

		//判断是否数组
		isArray : function(arr){
				return toString.apply(arr) === '[object Array]';
		},

		//判断是否函数 typeof == 'function'
		isFunction : function(f){
				return Object.prototype.toString.call(f) === '[object Function]';
		},

		//一致性
		adler32 : function(data){
					var MOD = 65521;
					var a = 1;
					var b = 0;
					for (var i = 0; i < data.length >>> 0 ; i++) {
						a = (a + data.charCodeAt(i)) % MOD;
						b = (b + a) % MOD;
					}
					return a | (b << 16);
		}

    }

    //常量
    var CONSTANT = {
		//背景图片base64
		BACKIMG :  "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAAHmWi9wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAMBJREFUeNpinDFjemBgIAMaePv2zX8MwMSADdBKFCCAGF++fIEuBHQEYb3UFAIIIOwBQWzQEOvVwaMOIICwBDoWRZjRQKaNo4rorQgggBiBCVpISJiBGoCJgXpg1KxRs0aiWQABxPj79+93795SbhAwUxNVLo+G/ahZo2aNmjVq1qhZI8wsgADt1zERADAMAsD6t5B4bRHRgeGj4I8FctKPM3ObLp6fk7w1eSwsLCwsLCwsLCwsrE5WvrHdrTLF8wBDaPAHu14WwgAAAABJRU5ErkJggg=="
    };

    function Meg(options) {
		if ( !(this instanceof Meg)) return new Meg(options);
      	this.init(options);
    }

	var mg = Meg.prototype;

    mg.init = function(options){
	options = options || {};
//        this.methods = {};
//        this.maps = {};
//        this.cache = {};

        var defaults = {
            el: '',         	// 根节点
            maps: {},           // 初始化命中表
            cache: true,        // 是否使用缓存
	    rcWidth: '1000',	// 默认限制最大宽度
	    rcHeight: '600',	// 默认限制最大高度

            //debug: false,       // 如果开启debug模式，则进入自动检索当前目录文件模式
        };

        for (var key in defaults) {
           	this[key] = options.hasOwnProperty(key) ? options[key] : defaults[key];
        }

	//节点
	this.fragment();

        return this;
    }

	mg.fragment = function(){
		var width,height;

		if(!!this.el){
			fragment = util.find(this.el);
			width = fragment.width < this.rcWidth ? fragment.width : this.rcWidth;
			height = fragment.height < this.rcHeight ? fragment.height : this.rcHeight;
		}else{
			fragment = document.createDocumentFragment();
			document.body.style.cssText = "margin:0;padding:0;background-image:url("+ CONSTANT.BACKIMG +");background-position: center center;background-repeat: repeat;background-size: 20px 20px;overflow: hidden";
		}

		var container = document.createElement("div");
				container.id = 'pixel';
				container.style.cssText = window.innerWidth < this.rcWidth ? "margin:0;padding:0;width:100%;height:100%;position:absolute;overflow:hidden"
				:"width:"+ this.rcWidth +"px;height:"+ this.rcHeight +"px;margin:0 auto;top:50%;transform:translate(0,-50%);;position:relative;overflow:hidden";

			var canvas = document.createElement("canvas");
			var ctx = canvas.getContext("2d");  console.log(window.innerWidth,window.innerHeight);
				canvas.width = width || (window.innerWidth < this.rcWidth ? window.innerWidth : this.rcWidth);
				canvas.height = height || (window.innerHeight < this.rcHeight ? window.innerHeight : this.rcHeight);
				container.appendChild(canvas);

			console.log(window.innerWidth,window.innerHeight)

			fragment.appendChild(container);
			document.body.appendChild(fragment);
	};

	return Meg;

}))

//暂存代码
;(function(root, fn){
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = fn :
	typeof define === 'function' && define.amd ? define(function(){ return fn }) :
	(root.Meg = fn );
}(this, new function(){
	var element = Element.prototype;
	var array = Array.prototype;
	var node = Node.prototype;
	var nodelist = NodeList.prototype;

	var set_to = function(obj1, obj2, key, alias) {
		obj2[key] = obj1[key];
		if (alias) {
			obj2[alias] = obj1[alias] = obj1[key];
		}
	}

	var set_alias = function(obj, key, alias) {
		obj[alias] = obj[key];
	}

	/** 方法别名 ***/
	set_alias(element, 'querySelectorAll','find');
	set_alias(document, 'querySelectorAll', 'find');
	set_to(array, nodelist, 'forEach', 'each');
	set_to(array, nodelist, 'map');
	set_to(array, nodelist, 'fliter');
	set_to(array, nodelist, 'connect');
	set_to(array, nodelist, 'join');
	set_to(array, nodelist, 'every');
	set_to(array, nodelist, 'reduce');
	set_to(array, nodelist, 'reduceRight');
	set_to(array, nodelist, 'slice');
	set_to(array, nodelist, 'some');
	set_to(array, nodelist, 'splice');

	/** 串操作 **/
	element.html = function(html) {
		if(!html) return this.innerHTML;
		this.innerHTML = html;
		return this;
	}

	//	创建一个空的对象常量, 便于内部共享使用
    var bracket = {};
	//	初始配置
	var defaults = {
            el: '',         	// 根节点
            maps: {},           // 初始化命中表
            cache: true,        // 是否使用缓存
			rcWidth: '1000',	// 默认限制最大宽度
			rcHeight: '600',	// 默认限制最大高度

            //debug: false,     // 如果开启debug模式，则进入自动检索当前目录文件模式
    };

	this.ctx = function(opt){
		opt= opt || {};
		for (var key in defaults) {
           	bracket[key] = opt.hasOwnProperty(key) ? opt[key] : defaults[key];
        }
		return bracket;
	}

	//	根节点

}));
<|endoftext|>


<commit_before>var CheckEvent = require('../../models/checkEvent');
var PagerDuty = require('pagerduty');

//Convert to Set implementation
var activeAlerts = [];

exports.initWebApp = function(options) {
  	var config = options.config.pagerduty;
	var pager = new PagerDuty({serviceKey:config.serviceKey});

	var addAlert = function(incident){
		activeAlerts.push(incident);
	}

	var getIncident = function(newId){
		var foundIncident;

		activeAlerts.forEach(function(incident){
			if(JSON.stringify(incident._id) === JSON.stringify(newId.toString())) {
				foundIncident = incident;
			}
		});

		return foundIncident;
	}

	var incidentExists = function(newId){
		return getIncident(newId) === undefined ? false : true;
	}

 	CheckEvent.on('afterInsert', function(checkEvent) {
	    checkEvent.findCheck(function(findErr, check) {
	      	if(!check.isUp){
			    pager.create({
					incidentKey: checkEvent._id,
					description: 'Uptime down: ' + check.name,
					details:'Automatic alert generated by Uptime: ' + checkEvent.message,
					callback: function(err,response){
						if(err){
							console.log(err);
						} else {
							console.log(response);
							addAlert({ _id : check._id, incident_key : response.incident_key});
						}
					}
				});
			} else if(check.isUp && config.autoresolve){
				if(incidentExists(check._id)){
					var incident = getIncident(check._id);
					var incident_key = incident.incident_key;
					pager.resolve({
						incidentKey : incident_key,
						description: 'Uptime up: ' + check.name,
						details:'Automatic alert generated by Uptime: ' + checkEvent.message,
						callback: function(err,response){
							if(err){
								console.log(err);
							} else {
								console.log(response);
							}
						}
					});
				}
			}
    	});
  });
}<commit_msg>use spaces for whitespace not tabs<commit_after>var CheckEvent = require('../../models/checkEvent');
var PagerDuty = require('pagerduty');

//Convert to Set implementation
var activeAlerts = [];

exports.initWebApp = function(options) {
    var config = options.config.pagerduty;
    var pager = new PagerDuty({serviceKey:config.serviceKey});

    var addAlert = function(incident){
        activeAlerts.push(incident);
    }

    var getIncident = function(newId){
        var foundIncident;

        activeAlerts.forEach(function(incident){
            if(JSON.stringify(incident._id) === JSON.stringify(newId.toString())) {
                foundIncident = incident;
            }
        });

        return foundIncident;
    }

    var incidentExists = function(newId){
        return getIncident(newId) === undefined ? false : true;
    }

    CheckEvent.on('afterInsert', function(checkEvent) {
        checkEvent.findCheck(function(findErr, check) {
            if(!check.isUp){
                pager.create({
                    incidentKey: checkEvent._id,
                    description: 'Uptime down: ' + check.name,
                    details:'Automatic alert generated by Uptime: ' + checkEvent.message,
                    callback: function(err,response){
                        if(err){
                            console.log(err);
                        } else {
                            console.log(response);
                            addAlert({ _id : check._id, incident_key : response.incident_key});
                        }
                    }
                });
            } else if(check.isUp && config.autoresolve){
                if(incidentExists(check._id)){
                    var incident = getIncident(check._id);
                    var incident_key = incident.incident_key;
                    pager.resolve({
                        incidentKey : incident_key,
                        description: 'Uptime up: ' + check.name,
                        details:'Automatic alert generated by Uptime: ' + checkEvent.message,
                        callback: function(err,response){
                            if(err){
                                console.log(err);
                            } else {
                                console.log(response);
                            }
                        }
                    });
                }
            }
        });
  });
}<|endoftext|>


<commit_before>/**
 * Created by narendra on 15/3/15.
 */

(function() {
  "use strict";
  pitana.nodeToViewMapping = new pitana.ObjectMap();

  pitana.register = function(elementProto) {
    if (elementProto.initialize === undefined) {
      elementProto.initialize = function() {
        pitana.HTMLElement.apply(this, arguments);
      };
    }
    pitana.registerElement(pitana.HTMLElement.extend(elementProto));
  };
  pitana.registerElement = function(ViewConstructor) {
    var ElementPrototype = Object.create(HTMLElement.prototype);
    ElementPrototype.createdCallback = function() {
      var view = new ViewConstructor({
        ele: this
      });
      pitana.nodeToViewMapping.add(this, view);
      if (view !==undefined && typeof view.createdCallback === "function") {
        try{
          view.createdCallback.apply(view, arguments);
        } catch (e){
          console.error("pitana:createdCallback:exception",e);
        }
      }

    };
    ElementPrototype.attachedCallback = function() {
      var view = pitana.nodeToViewMapping.get(this);
      if (view !==undefined && typeof view.attachedCallback === "function") {
        try{
          view.attachedCallback.apply(view, arguments);
        } catch (e){
          console.error("pitana:attachedCallback:exception",e);
        }
      }
    };
    ElementPrototype.detachedCallback = function() {
      var view = pitana.nodeToViewMapping.get(this);
      if (view !== undefined) {
        if (typeof view.detachedCallback === "function") {
          try{
            view.detachedCallback.apply(view, arguments);
          } catch (e){
            console.error("pitana:detachedCallback:exception",e);
          }
        }
        view._endModule();
        pitana.nodeToViewMapping.remove(this);
      }
    };

    if (ViewConstructor.prototype.methods !== undefined) {
      ElementPrototype._commonMethod = function(methodName, args) {
        var view = pitana.nodeToViewMapping.get(this);
        var f = view[methodName];
        if (typeof f === "function") {
          return f.apply(view, args);
        }
      };
      //Append method on EP
      ViewConstructor.prototype.methods.map(function(methodName, i) {
        ElementPrototype[methodName] = function() {
          return ElementPrototype._commonMethod.call(this, methodName, arguments);
        };
      });
    }

    ElementPrototype.attributeChangedCallback = function(attrName) {
      var view = pitana.nodeToViewMapping.get(this);
      var mainArgs = arguments;
      pitana.util.for(view.accessors, function(config, name) {
        if (name.toLowerCase() === attrName && typeof config.onChange === "string") {
          view[config.onChange].apply(view, mainArgs);
        }
      });
      if (typeof view.attributeChangedCallback === "function") {
        view.attributeChangedCallback.apply(view, arguments);
      }

    };

    if (ViewConstructor.prototype.accessors !== undefined) {
      pitana.util.for(ViewConstructor.prototype.accessors, function(attrObj, attrName) {
        if (attrObj.type === undefined) {
          attrObj.type = "string";
        }
        var Prop = {};
        Prop[attrName] = {
          get: function() {
            if (pitana.accessorType[attrObj.type] !== undefined && typeof pitana.accessorType[attrObj.type].get === "function") {
              return pitana.accessorType[attrObj.type].get.call(this, attrName, attrObj);
            }
          },
          set: function(newVal) {
            if (pitana.accessorType[attrObj.type] !== undefined && typeof pitana.accessorType[attrObj.type].set === "function") {
              pitana.accessorType[attrObj.type].set.call(this, attrName, newVal, attrObj);
            }
          }
        };
        Object.defineProperties(ElementPrototype, Prop);
      });
    }
    if (typeof document.registerElement === "function") {
      var elementName = ViewConstructor.prototype.tagName.split("-").map(function(v) {
        return v.charAt(0).toUpperCase() + v.slice(1);
      }).join("") + "Element";
      window[elementName] = document.registerElement(ViewConstructor.prototype.tagName, {
        extends : ViewConstructor.prototype.extends,
        prototype: ElementPrototype
      });
    } else {
      throw "document.registerElement not found, make sure you can included WebComponents Polyfill";
    }
  };
})();
<commit_msg>check if view exists for attribute changed call back<commit_after>/**
 * Created by narendra on 15/3/15.
 */

(function() {
  "use strict";
  pitana.nodeToViewMapping = new pitana.ObjectMap();

  pitana.register = function(elementProto) {
    if (elementProto.initialize === undefined) {
      elementProto.initialize = function() {
        pitana.HTMLElement.apply(this, arguments);
      };
    }
    pitana.registerElement(pitana.HTMLElement.extend(elementProto));
  };
  pitana.registerElement = function(ViewConstructor) {
    var ElementPrototype = Object.create(HTMLElement.prototype);
    ElementPrototype.createdCallback = function() {
      var view = new ViewConstructor({
        ele: this
      });
      pitana.nodeToViewMapping.add(this, view);
      if (view !==undefined && typeof view.createdCallback === "function") {
        try{
          view.createdCallback.apply(view, arguments);
        } catch (e){
          console.error("pitana:createdCallback:exception",e);
        }
      }

    };
    ElementPrototype.attachedCallback = function() {
      var view = pitana.nodeToViewMapping.get(this);
      if (view !==undefined && typeof view.attachedCallback === "function") {
        try{
          view.attachedCallback.apply(view, arguments);
        } catch (e){
          console.error("pitana:attachedCallback:exception",e);
        }
      }
    };
    ElementPrototype.detachedCallback = function() {
      var view = pitana.nodeToViewMapping.get(this);
      if (view !== undefined) {
        if (typeof view.detachedCallback === "function") {
          try{
            view.detachedCallback.apply(view, arguments);
          } catch (e){
            console.error("pitana:detachedCallback:exception",e);
          }
        }
        view._endModule();
        pitana.nodeToViewMapping.remove(this);
      }
    };

    if (ViewConstructor.prototype.methods !== undefined) {
      ElementPrototype._commonMethod = function(methodName, args) {
        var view = pitana.nodeToViewMapping.get(this);
        var f = view[methodName];
        if (typeof f === "function") {
          return f.apply(view, args);
        }
      };
      //Append method on EP
      ViewConstructor.prototype.methods.map(function(methodName, i) {
        ElementPrototype[methodName] = function() {
          return ElementPrototype._commonMethod.call(this, methodName, arguments);
        };
      });
    }

    ElementPrototype.attributeChangedCallback = function(attrName) {
      var view = pitana.nodeToViewMapping.get(this);
      var mainArgs = arguments;
      if(view!==undefined){
        pitana.util.for(view.accessors, function(config, name) {
          if (name.toLowerCase() === attrName && typeof config.onChange === "string") {
            view[config.onChange].apply(view, mainArgs);
          }
        });
        if (typeof view.attributeChangedCallback === "function") {
          view.attributeChangedCallback.apply(view, arguments);
        }
      }
    };

    if (ViewConstructor.prototype.accessors !== undefined) {
      pitana.util.for(ViewConstructor.prototype.accessors, function(attrObj, attrName) {
        if (attrObj.type === undefined) {
          attrObj.type = "string";
        }
        var Prop = {};
        Prop[attrName] = {
          get: function() {
            if (pitana.accessorType[attrObj.type] !== undefined && typeof pitana.accessorType[attrObj.type].get === "function") {
              return pitana.accessorType[attrObj.type].get.call(this, attrName, attrObj);
            }
          },
          set: function(newVal) {
            if (pitana.accessorType[attrObj.type] !== undefined && typeof pitana.accessorType[attrObj.type].set === "function") {
              pitana.accessorType[attrObj.type].set.call(this, attrName, newVal, attrObj);
            }
          }
        };
        Object.defineProperties(ElementPrototype, Prop);
      });
    }
    if (typeof document.registerElement === "function") {
      var elementName = ViewConstructor.prototype.tagName.split("-").map(function(v) {
        return v.charAt(0).toUpperCase() + v.slice(1);
      }).join("") + "Element";
      window[elementName] = document.registerElement(ViewConstructor.prototype.tagName, {
        extends : ViewConstructor.prototype.extends,
        prototype: ElementPrototype
      });
    } else {
      throw "document.registerElement not found, make sure you can included WebComponents Polyfill";
    }
  };
})();
<|endoftext|>


<commit_before>describe("CSVParser", function() {
  var parser, data, fieldSeparator, rowSeparator;

  describe("output", function(){
    beforeEach(function(){
      data = ['url,username,password,extra,name,grouping,fav', 'https://www.example.com,username,password,,example.com,,1', ',,,,,,'].join("\n");
    });
    it("should exclude empty rows by default", function(){
      parser = new CSVParser(data);
      parser.parse();
      expect(parser.numberOfRows()).toEqual(2);
    });
    it("should exclude empty rows with explicit true option", function(){
      parser = new CSVParser(data, {ignoreEmpty: true});
      parser.parse();
      expect(parser.numberOfRows()).toEqual(2);
    });
    it("should not exclude empty rows with explicit false option", function(){
      parser = new CSVParser(data, {ignoreEmpty: false});
      parser.parse();
      expect(parser.numberOfRows()).toEqual(3);
    });
  });

  describe("separators", function(){
    beforeEach(function(){
      data = ['url,"username",password,extra,name,grouping,fav', 'https://www.example.com,myUsername,"abcdé""4j+<+G9\n3$6,6,+z:(b?g\\",,example.com,,1'].join("\n");
      parser = new CSVParser(data);
    });

    it("uses comma as the default field separator", function(){
      expect(parser.fieldSeparator).toEqual(",");
    });

    it("uses newline as the default row separator", function(){
      parser = new CSVParser(data);
      expect(parser.rowSeparator).toEqual("\n");
    });
    it("accepts a custom field separator", function(){
      parser = new CSVParser(data, {fieldSeparator: "|"});
      expect(parser.fieldSeparator).toEqual("|");
    });
    it("accepts a custom row separator", function(){
      parser = new CSVParser(data, {fieldSeparator: ",", rowSeparator: "|"});
      expect(parser.rowSeparator).toEqual("|");
    });
  });

  describe("parsing", function(){
    describe("basic", function(){
      it("parses rows with default separators", function(){
        data = ['url,username,password,extra,name,grouping,fav', 'https://www.example.com,myUsername,mypassword,,example.com,,1'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
      });
      it("parses rows with custom row separator", function(){
        data = ['url,username,password,extra,name,grouping,fav', 'https://www.example.com,myUsername,mypassword,,example.com,,1'].join('|');
        parser = new CSVParser(data, {fieldSeparator: ",", rowSeparator: "|"});
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
      });
      it("parses rows with custom field separator", function(){
        data = ['url|username|password|extra|name|grouping|fav', 'https://www.example.com|myUsername|mypassword||example.com||1'].join("\n");
        parser = new CSVParser(data, {fieldSeparator: "|"});
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
      });
    });
    describe("advanced", function(){
      it("handles rows with quoted fields", function(){
        data = ['"url","username","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","example.com","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual("url");
      });
      it("handles fields with newlines", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","example.com","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][1]).toEqual("user\nname");
      });
      it("handles fields with escaped double quotes", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","""example.com""","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[1][4]).toEqual('"example.com"');
      });
      it("handles fields with escaped backslashes", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","\\example.com\\","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[1][4]).toEqual('\\example.com\\');
      });
      it("handles fields with tricky backslashes", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","""example.com\\","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[1][4]).toEqual('"example.com\\');
      });
      it("handles quoted fields with commas", function(){
        data = ['"u,r,l","username","password","extra","name","grouping","fav"', '"https://www.example.com","myUser,name","mypassword","","""example.com","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual('u,r,l');
        expect(parser.rows[1][1]).toEqual('myUser,name');
      });
      it("handles quoted fields with trailing escaped quotes", function(){
        data = ['"u,r,l""","username","password","extra","name","grouping","fav"', '"https://www.example.com","myUser,name","mypassword","","""example.com\\""""","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual('u,r,l"');
        expect(parser.rows[1][4]).toEqual('"example.com\\""');
      });
      it("can parse data with trailing empty field", function(){
        data = ['"u,r,l""","user\nname","password","extra","name","grouping","fav","empty column"', '"https://www.example.com","myUser,name","mypassword","","""example.com\\","","1",'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual('u,r,l"');
      });
    });
  });

});<commit_msg>issue #1 Cleanup test spec since backslashes are no longer escaped<commit_after>describe("CSVParser", function() {
  var parser, data, fieldSeparator, rowSeparator;

  describe("output", function(){
    beforeEach(function(){
      data = ['url,username,password,extra,name,grouping,fav', 'https://www.example.com,username,password,,example.com,,1', ',,,,,,'].join("\n");
    });
    it("should exclude empty rows by default", function(){
      parser = new CSVParser(data);
      parser.parse();
      expect(parser.numberOfRows()).toEqual(2);
    });
    it("should exclude empty rows with explicit true option", function(){
      parser = new CSVParser(data, {ignoreEmpty: true});
      parser.parse();
      expect(parser.numberOfRows()).toEqual(2);
    });
    it("should not exclude empty rows with explicit false option", function(){
      parser = new CSVParser(data, {ignoreEmpty: false});
      parser.parse();
      expect(parser.numberOfRows()).toEqual(3);
    });
  });

  describe("separators", function(){
    beforeEach(function(){
      data = ['url,"username",password,extra,name,grouping,fav', 'https://www.example.com,myUsername,"abcdé""4j+<+G9\n3$6,6,+z:(b?g\\",,example.com,,1'].join("\n");
      parser = new CSVParser(data);
    });

    it("uses comma as the default field separator", function(){
      expect(parser.fieldSeparator).toEqual(",");
    });

    it("uses newline as the default row separator", function(){
      parser = new CSVParser(data);
      expect(parser.rowSeparator).toEqual("\n");
    });
    it("accepts a custom field separator", function(){
      parser = new CSVParser(data, {fieldSeparator: "|"});
      expect(parser.fieldSeparator).toEqual("|");
    });
    it("accepts a custom row separator", function(){
      parser = new CSVParser(data, {fieldSeparator: ",", rowSeparator: "|"});
      expect(parser.rowSeparator).toEqual("|");
    });
  });

  describe("parsing", function(){
    describe("basic", function(){
      it("parses rows with default separators", function(){
        data = ['url,username,password,extra,name,grouping,fav', 'https://www.example.com,myUsername,mypassword,,example.com,,1'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
      });
      it("parses rows with custom row separator", function(){
        data = ['url,username,password,extra,name,grouping,fav', 'https://www.example.com,myUsername,mypassword,,example.com,,1'].join('|');
        parser = new CSVParser(data, {fieldSeparator: ",", rowSeparator: "|"});
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
      });
      it("parses rows with custom field separator", function(){
        data = ['url|username|password|extra|name|grouping|fav', 'https://www.example.com|myUsername|mypassword||example.com||1'].join("\n");
        parser = new CSVParser(data, {fieldSeparator: "|"});
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
      });
    });
    describe("advanced", function(){
      it("handles rows with quoted fields", function(){
        data = ['"url","username","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","example.com","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual("url");
      });
      it("handles fields with newlines", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","example.com","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][1]).toEqual("user\nname");
      });
      it("handles fields with escaped double quotes", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","""example.com""","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[1][4]).toEqual('"example.com"');
      });
      it("handles fields with backslashes", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","\\example.com\\","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[1][4]).toEqual('\\example.com\\');
      });
      it("handles fields with tricky backslashes", function(){
        data = ['"url","user\nname","password","extra","name","grouping","fav"', '"https://www.example.com","myUsername","mypassword","","""example.com\\","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[1][4]).toEqual('"example.com\\');
      });
      it("handles quoted fields with commas", function(){
        data = ['"u,r,l","username","password","extra","name","grouping","fav"', '"https://www.example.com","myUser,name","mypassword","","""example.com","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual('u,r,l');
        expect(parser.rows[1][1]).toEqual('myUser,name');
      });
      it("handles quoted fields with trailing escaped quotes", function(){
        data = ['"u,r,l""","username","password","extra","name","grouping","fav"', '"https://www.example.com","myUser,name","mypassword","","""example.com\\""""","","1"'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual('u,r,l"');
        expect(parser.rows[1][4]).toEqual('"example.com\\""');
      });
      it("can parse data with trailing empty field", function(){
        data = ['"u,r,l""","user\nname","password","extra","name","grouping","fav","empty column"', '"https://www.example.com","myUser,name","mypassword","","""example.com\\","","1",'].join("\n");
        parser = new CSVParser(data);
        parser.parse();
        expect(parser.numberOfRows()).toEqual(2);
        expect(parser.rows[0][0]).toEqual('u,r,l"');
      });
    });
  });

});<|endoftext|>


<commit_before>import { expect } from 'chai';

import { dialogModes, actionTypes } from '../../../src/assets/constants';
import createDialogs from '../../../src/assets/dialogs';
import defaults from '../../fixtures/default';
import MockUI from '../../mocks/UI';

describe('Tour', function() {
	var stats = {}, dialogs,
		Tour, ui;

	before(() => {
		Tour = require('../../../src/lib/Tour').default;
		dialogs = createDialogs(defaults);
	});

	beforeEach(() => {
		ui = new MockUI();

		// stats is defined as an object above so it is passed to the mock UI by reference
		// its values are then reset before each test
		stats._showDialog = [];
		stats._hideDialog = 0;
		stats.dispatches = [];

		ui.__set_test_stats(stats);
	});

	afterEach(() => {
		ui = null;
	});

	it('Should instantiate', function() {
		var tour = new Tour(ui);
		expect(tour).to.be.an.instanceof(Tour);
	});

	describe('#intro', function() {
		it('Should show an intro', function() {
			ui.__set_showDialog_resolver(function(resolve) {
				resolve();
			});

			var tour = new Tour(ui);

			return tour.intro()
				.then(() => {
					expect(ui.__test_stats._showDialog[0].mode).to.equal(dialogModes.GENERAL);
					expect(ui.__test_stats._showDialog[0].data).to.eql(dialogs.intro);
					expect(ui.__test_stats._hideDialog).to.equal(1);
				});
		});
	});

	describe('start', function() {
		it('Should start the tour', function() {
			ui.__set_showDialog_resolver(function(resolve) {
				// pause the tour so only the first dialog is shown
				resolve({
					action: 'pause'
				});
			});

			var tour = new Tour(ui);

			return tour.start()
				.then(() => {
					expect(stats._showDialog[0].mode).to.equal(dialogModes.TOUR);
					expect(stats._showDialog[0].data).to.eql(dialogs.tour[0]);
					expect(stats._showDialog).to.have.lengthOf(1);
				});
		});
	});

	describe('_setTourStage', function() {
		it('Should set the tour stage to 1', function() {
			var tour = new Tour(ui);
			tour._setTourStage(1);

			expect(stats.dispatches[0]).to.eql({
				type: actionTypes.SET_TOUR_STAGE,
				stage: 1
			});
		});

		it('Should only set the tour stage once', function() {
			var tour = new Tour(ui);
			tour._setTourStage(1);

			expect(stats.dispatches).to.have.lengthOf(1);
		});
	});
});<commit_msg>fix tour test<commit_after>import { expect } from 'chai';

import { dialogModes, actionTypes } from '../../../src/assets/constants';
import createDialogs from '../../../src/assets/dialogs';
import defaults from '../../fixtures/defaults';
import MockUI from '../../mocks/UI';

describe('Tour', function() {
	var stats = {}, dialogs,
		Tour, ui;

	before(() => {
		Tour = require('../../../src/lib/Tour').default;
		dialogs = createDialogs(defaults);
	});

	beforeEach(() => {
		ui = new MockUI();

		// stats is defined as an object above so it is passed to the mock UI by reference
		// its values are then reset before each test
		stats._showDialog = [];
		stats._hideDialog = 0;
		stats.dispatches = [];

		ui.__set_test_stats(stats);
	});

	afterEach(() => {
		ui = null;
	});

	it('Should instantiate', function() {
		var tour = new Tour(ui);
		expect(tour).to.be.an.instanceof(Tour);
	});

	describe('#intro', function() {
		it('Should show an intro', function() {
			ui.__set_showDialog_resolver(function(resolve) {
				resolve();
			});

			var tour = new Tour(ui);

			return tour.intro()
				.then(() => {
					expect(ui.__test_stats._showDialog[0].mode).to.equal(dialogModes.GENERAL);
					expect(ui.__test_stats._showDialog[0].data).to.eql(dialogs.intro);
					expect(ui.__test_stats._hideDialog).to.equal(1);
				});
		});
	});

	describe('start', function() {
		it('Should start the tour', function() {
			ui.__set_showDialog_resolver(function(resolve) {
				// pause the tour so only the first dialog is shown
				resolve({
					action: 'pause'
				});
			});

			var tour = new Tour(ui);

			return tour.start()
				.then(() => {
					expect(stats._showDialog[0].mode).to.equal(dialogModes.TOUR);
					expect(stats._showDialog[0].data).to.eql(dialogs.tour[0]);
					expect(stats._showDialog).to.have.lengthOf(1);
				});
		});
	});

	describe('_setTourStage', function() {
		it('Should set the tour stage to 1', function() {
			var tour = new Tour(ui);
			tour._setTourStage(1);

			expect(stats.dispatches[0]).to.eql({
				type: actionTypes.SET_TOUR_STAGE,
				stage: 1
			});
		});

		it('Should only set the tour stage once', function() {
			var tour = new Tour(ui);
			tour._setTourStage(1);

			expect(stats.dispatches).to.have.lengthOf(1);
		});
	});
});<|endoftext|>


<commit_before>
goog.require('goog.debug.Console');
goog.require('goog.testing.jsunit');

goog.require('ydn.db.Storage');

var reachedFinalContinuation, basic_schema;
var table_name = 't1';

var setUp = function() {
  var c = new goog.debug.Console();
  c.setCapturing(true);
  //goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.FINE);
  //goog.debug.Logger.getLogger('ydn.gdata.MockServer').setLevel(goog.debug.Logger.Level.FINEST);
  //goog.debug.Logger.getLogger('ydn.db').setLevel(goog.debug.Logger.Level.FINEST);
  goog.debug.Logger.getLogger('ydn.db.con.IndexedDb').setLevel(goog.debug.Logger.Level.FINEST);
  goog.debug.Logger.getLogger('ydn.db.IndexedDb').setLevel(goog.debug.Logger.Level.FINEST);
  //ydn.db.con.IndexedDb.DEBUG = true;
  //ydn.db.req.IndexedDb.DEBUG = true;

	basic_schema = new ydn.db.DatabaseSchema(1);
	basic_schema.addStore(new ydn.db.StoreSchema(table_name, 'id'));
};

var tearDown = function() {
  assertTrue('The final continuation was not reached', reachedFinalContinuation);
};

var do_test_multiEntry = function (db_type) {
  var options = {preference: [db_type]};
  var store_name = 'st';
  var db_name = 'test_51_multiEntry_2';
  var indexSchema = new ydn.db.IndexSchema('tag', ydn.db.DataType.TEXT, false, true);
  var store_schema = new ydn.db.StoreSchema(store_name, 'id', false,
    ydn.db.DataType.TEXT, [indexSchema]);
  var schema = new ydn.db.DatabaseSchema(1, [store_schema]);
  var db = new ydn.db.Storage(db_name, schema, options);
  console.log('db ' + db);

  var objs = [
    {id:'qs0', value: 0, tag: ['a', 'b']},
    {id:'qs1', value: 1, tag: 'a'},
    {id:'at2', value: 2, tag: ['a', 'b']},
    {id:'bs1', value: 3, tag: 'b'},
    {id:'bs2', value: 4, tag: ['a', 'c', 'd']},
    {id:'bs3', value: 5, tag: 'c'},
    {id:'st3', value: 6}
  ];

  var tags = ['d', 'b', 'c', 'a', 'e'];
  var exp_counts = [1, 3, 2, 4, 0];
  var counts = [];
  var total = tags.length;
  var done = 0;

  waitForCondition(
    // Condition
    function () {
      return done == total;
    },
    // Continuation
    function () {

      for (var i = 0; i < total; i++) {
        assertEquals(db_type + ' ' + tags[i] + ' count', exp_counts[i], counts[i]);
      }

      reachedFinalContinuation = true;
    },
    100, // interval
    1000); // maxTimeout

  db.put(store_name, objs).addCallback(function (value) {
    console.log([db + ' receiving put callback.', value]);

    var count_for = function (tag_name, idx) {
      var keyRange = ydn.db.KeyRange.only(tag_name);
      var q = db.query(store_name, 'tag', 'next', keyRange);

      q.fetch().addBoth(function (value) {
        console.log(db + ' fetch value: ' + JSON.stringify(value));
        counts[idx] = value.length;
        done++;
      });
    };

    for (var i = 0; i < total; i++) {
      count_for(tags[i], i);
    }

  });

};

var test_11_multiEntry_idb = function () {
  do_test_multiEntry('indexeddb');
};

//var test_51_multiEntry_websql = function () {
//  do_test_multiEntry('websql');
//};

var testCase = new goog.testing.ContinuationTestCase();
testCase.autoDiscoverTests();
G_testRunner.initialize(testCase);

<commit_msg>add oauth2-postmessage-profile  project<commit_after>
goog.require('goog.debug.Console');
goog.require('goog.testing.jsunit');

goog.require('ydn.db.Storage');

var reachedFinalContinuation, basic_schema;
var table_name = 't1';

var setUp = function() {
  var c = new goog.debug.Console();
  c.setCapturing(true);
  //goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.FINE);
  //goog.debug.Logger.getLogger('ydn.gdata.MockServer').setLevel(goog.debug.Logger.Level.FINEST);
  //goog.debug.Logger.getLogger('ydn.db').setLevel(goog.debug.Logger.Level.FINEST);
  goog.debug.Logger.getLogger('ydn.db.con.IndexedDb').setLevel(goog.debug.Logger.Level.FINEST);
  goog.debug.Logger.getLogger('ydn.db.IndexedDb').setLevel(goog.debug.Logger.Level.FINEST);
  //ydn.db.con.IndexedDb.DEBUG = true;
  //ydn.db.req.IndexedDb.DEBUG = true;

	basic_schema = new ydn.db.DatabaseSchema(1);
	basic_schema.addStore(new ydn.db.StoreSchema(table_name, 'id'));
};

var tearDown = function() {
  assertTrue('The final continuation was not reached', reachedFinalContinuation);
};

var do_test_multiEntry = function (db_type) {
  var options = {preference: [db_type]};
  var store_name = 'st';
  var db_name = 'test_51_multiEntry_2';
  var indexSchema = new ydn.db.IndexSchema('tag', ydn.db.DataType.TEXT, false, true);
  var store_schema = new ydn.db.StoreSchema(store_name, 'id', false,
    ydn.db.DataType.TEXT, [indexSchema]);
  var schema = new ydn.db.DatabaseSchema(1, [store_schema]);
  var db = new ydn.db.Storage(db_name, schema, options);
  console.log('db ' + db);

  var objs = [
    {id:'qs0', value: 0, tag: ['a', 'b']},
    {id:'qs1', value: 1, tag: 'a'},
    {id:'at2', value: 2, tag: ['a', 'b']},
    {id:'bs1', value: 3, tag: 'b'},
    {id:'bs2', value: 4, tag: ['a', 'c', 'd']},
    {id:'bs3', value: 5, tag: 'c'},
    {id:'st3', value: 6}
  ];

  goog.scope()

  var tags = ['d', 'b', 'c', 'a', 'e'];
  var exp_counts = [1, 3, 2, 4, 0];
  var counts = [];
  var total = tags.length;
  var done = 0;

  waitForCondition(
    // Condition
    function () {
      return done == total;
    },
    // Continuation
    function () {

      for (var i = 0; i < total; i++) {
        assertEquals(db_type + ' ' + tags[i] + ' count', exp_counts[i], counts[i]);
      }

      reachedFinalContinuation = true;
    },
    100, // interval
    1000); // maxTimeout

  db.put(store_name, objs).addCallback(function (value) {
    console.log([db + ' receiving put callback.', value]);

    var count_for = function (tag_name, idx) {
      var keyRange = ydn.db.KeyRange.only(tag_name);
      var q = db.query(store_name, 'tag', 'next', keyRange);

      q.fetch().addBoth(function (value) {
        console.log(db + ' fetch value: ' + JSON.stringify(value));
        counts[idx] = value.length;
        done++;
      });
    };

    for (var i = 0; i < total; i++) {
      count_for(tags[i], i);
    }

  });

};

var test_11_multiEntry_idb = function () {
  do_test_multiEntry('indexeddb');
};

//var test_12_multiEntry_websql = function () {
//  do_test_multiEntry('websql');
//};

var testCase = new goog.testing.ContinuationTestCase();
testCase.autoDiscoverTests();
G_testRunner.initialize(testCase);

<|endoftext|>


<commit_before>'use strict';

var setTimeout = require('timers').setTimeout;

var allocCluster = require('./lib/alloc-cluster.js');

allocCluster.test('end response with error frame', {
    numPeers: 2
}, function t(cluster, assert) {
    var client = cluster.channels[0];
    var server = cluster.channels[1];

    server.makeSubChannel({
        serviceName: 'stream'
    }).register('stream', {
        streamed: true
    }, streamHandler);

    var req = client.request({
        serviceName: 'stream',
        host: server.hostPort,
        streamed: true
    });

    req.arg1.end('stream');
    req.arg2.end();
    req.arg3.end();

    req.on('response', onResponse);
    req.on('error', onError);

    function onResponse(resp) {
        assert.ok(resp);

        resp.on('finish', onResponseFinished);
        resp.on('error', onResponseError);

        function onResponseFinished() {
            assert.ok(false, 'expected no finished event');
        }

        function onResponseError(err) {
            assert.equal(err.message, 'oops');

            assert.end();
        }
    }

    function onError(err) {
        assert.ifError(err);
        assert.ok(false, 'expected no req error event');
    }

    function streamHandler(inreq, buildRes) {
        var res = buildRes({
            streamed: true
        });

        res.arg1.end();
        res.arg2.end();

        res.arg3.write('a message');

        setTimeout(function datTime() {
            res.sendError('UnexpectedError', 'oops');
        }, 500);
    }
});
<commit_msg>copyright: add blurb<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var setTimeout = require('timers').setTimeout;

var allocCluster = require('./lib/alloc-cluster.js');

allocCluster.test('end response with error frame', {
    numPeers: 2
}, function t(cluster, assert) {
    var client = cluster.channels[0];
    var server = cluster.channels[1];

    server.makeSubChannel({
        serviceName: 'stream'
    }).register('stream', {
        streamed: true
    }, streamHandler);

    var req = client.request({
        serviceName: 'stream',
        host: server.hostPort,
        streamed: true
    });

    req.arg1.end('stream');
    req.arg2.end();
    req.arg3.end();

    req.on('response', onResponse);
    req.on('error', onError);

    function onResponse(resp) {
        assert.ok(resp);

        resp.on('finish', onResponseFinished);
        resp.on('error', onResponseError);

        function onResponseFinished() {
            assert.ok(false, 'expected no finished event');
        }

        function onResponseError(err) {
            assert.equal(err.message, 'oops');

            assert.end();
        }
    }

    function onError(err) {
        assert.ifError(err);
        assert.ok(false, 'expected no req error event');
    }

    function streamHandler(inreq, buildRes) {
        var res = buildRes({
            streamed: true
        });

        res.arg1.end();
        res.arg2.end();

        res.arg3.write('a message');

        setTimeout(function datTime() {
            res.sendError('UnexpectedError', 'oops');
        }, 500);
    }
});
<|endoftext|>


<commit_before>/*
 * grunt-bintray-deploy
 * https://github.com/shayke/grunt-bintray-deploy
 *
 * Copyright (c) 2013 Shay Yaakov
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {
    var Bintray = require('bintray');
    var Q = require('q');

    grunt.registerMultiTask('bintrayDeploy', 'Deploy to Bintray', function () {
        var finished = this.async();

        var pkg = grunt.file.readJSON('package.json');
        var options = this.options({
            pkgName: pkg.name,
            pkgVersion: pkg.version
        });

        var bintray = new Bintray({
            username: options.username,
            apikey: options.apikey,
            organization: options.subject,
            repository: options.repo
        });

        var filesDestination = "https://bintray.com/" + bintray.endpointBase + "/" + options.pkgName + "/" + options.pkgVersion + "/files";
        grunt.log.ok("Deploying files to '" + filesDestination + "'");

        var promises = [];
        this.files.forEach(function (file) {
            file.src.forEach(function (srcPath) {
                options.filePath = srcPath;
                options.remotePath = file.dest.replace(/^\/|\/$/g, '');
                var uploadFile = bintray.uploadPackage(options.pkgName, options.pkgVersion, options.filePath, options.remotePath);
                promises.push(uploadFile.then(function () {
                    grunt.log.ok("Successfully deployed '" + srcPath + "'");
                }));
            });
        });

        Q.all(promises).then(function() {
            finished();
        }).fail(function (error) {
            grunt.log.error(error.data);
            finished(false);
        });
    });
};
<commit_msg>auto create package if not existed<commit_after>/*
 * grunt-bintray-deploy
 * https://github.com/shayke/grunt-bintray-deploy
 *
 * Copyright (c) 2013 Shay Yaakov
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {
    var Bintray = require('bintray');
    var Q = require('q');

    grunt.registerMultiTask('bintrayDeploy', 'Deploy to Bintray', function () {
        var finished = this.async();

        var projectPackage = grunt.file.readJSON('package.json');
        var options = this.options({
            user: null,
            apikey: null,
            pkg: {
                repo: null,
                userOrg: null,
                name: null,
                version: null,
                desc: null,
                licenses: null,
                labels: null
            }
        });

        // These don't work when specifying directly inside pkg above
        options.pkg.userOrg = options.pkg.userOrg || options.user;
        options.pkg.name = options.pkg.name || projectPackage.name;
        options.pkg.version = options.pkg.version || projectPackage.version;
        options.pkg.desc = options.pkg.desc || 'Automatically created GruntJS package';
        options.pkg.licenses = options.pkg.licenses || ['MIT'];

        var bintray = new Bintray({
            username: options.user,
            apikey: options.apikey,
            organization: options.pkg.userOrg,
            repository: options.pkg.repo
        });

        function checkAndCreatePackage(name) {
            var deferred = Q.defer();
            bintray.getPackage(name).then(function(res) {
                grunt.log.ok("Package '" + res.data.name + "' already exists.");
                deferred.resolve(true);
            }, function(res) {
                if(res.code === 404) {
                    bintray.createPackage(newPackage).then(function(res) {
                        grunt.log.ok("Successfully created new package '" + res.data.name + "'.");
                        deferred.resolve(true);
                    }, function(error) {
                        deferred.reject(new Error(error));
                    });
                }
            });

            return deferred.promise;
        }

        var newPackage = {
            name: options.pkg.name,
            desc: options.pkg.desc,
            licenses: options.pkg.licenses,
            labels: options.pkg.labels
        };

        function uploadFiles(files) {
            var filesDestination = "https://bintray.com/" + bintray.endpointBase + "/" + options.pkg.name + "/" + options.pkg.version + "/files";
            grunt.log.ok("Deploying files to '" + filesDestination + "'");

            var promises = [];
            files.forEach(function (file) {
                file.src.forEach(function (srcPath) {
                    var remotePath = file.dest.replace(/^\/|\/$/g, '');
                    promises.push(bintray.uploadPackage(options.pkg.name, options.pkg.version, srcPath, remotePath).then(function() {
                        grunt.log.ok("Successfully deployed '" + srcPath + "'");
                    }, function(error) {
                        grunt.log.error("Failed deploying " + srcPath + ": " + error.data);
                        finished(false);
                    }));
                });
            });

            return Q.all(promises);
        }

        var files = this.files;
        checkAndCreatePackage(newPackage.name)
            .then(function() { uploadFiles(files).then(function() { finished() }) })
            .fail(function(err) {
                grunt.log.error(err);
                finished(false);
            })
            .done();
    });
};
<|endoftext|>


<commit_before>'use strict';

import axios from 'axios';
import resolveResponse from 'contentful-resolve-response';
import querystring from 'querystring';

export function createClient (options) {
  return new Client(options || {});
};

class Client {
  constructor ({accessToken, space, secure, host}) {
    if (!accessToken) {
      throw new TypeError('Expected property accessToken');
    }

    if (!space) {
      throw new TypeError('Expected property space');
    }

    const insecure = secure === false;
    var [hostname, port] = (host && host.split(':')) || [];

    hostname = hostname || 'cdn.contentful.com';
    port = port || (insecure ? 80 : 443);

    this.options = {
      baseUrl: `${insecure ? 'http' : 'https'}://${hostname}:${port}/spaces/${space}`,
      accessToken: accessToken
    };
  }

  _request (path, query) {
    if (!query) {
      query = {}
    };

    query.access_token = this.options.accessToken;

    const params = {
      headers: {},
      method: 'get',
      url: `${this.options.baseUrl}${path}?${querystring.stringify(query)}`
    };

    params.headers['Content-Type'] = 'application/vnd.contentful.delivery.v1+json';

    return axios(params)
      .then(function (response) {
        return response.data;
      })
      .catch(function (error) {
        throw error.data;
      });
  }

  asset (id, callback) {
    return nodeify(
      this._request('/assets/' + id).then(parseResource),
      callback
    );
  }

  assets (object, callback) {
    const query = new Query(object);
    const deferred = this._request('/assets', query).then(parseSearchResult);
    return nodeify(deferred, callback);
  }

  contentType (id, callback) {
    const deferred = this._request('/content_types/' + id).then(ContentType.parse);
    return nodeify(deferred, callback);
  }

  contentTypes (object, callback) {
    const query = new Query(object);
    const deferred = this._request('/content_types', query).then(parseSearchResult);
    return nodeify(deferred, callback);
  }

  entry (id, callback) {
    const deferred = this._request('/entries/' + id)
                   .then(Entry.parse);
    return nodeify(deferred, callback);
  }

  entries (object, callback) {
    const query = new Query(object);
    const deferred = this._request('/entries', query).then(parseSearchResult);
    return nodeify(deferred, callback);
  }

  space (callback) {
    return nodeify(this._request(''), callback);
  }

  _pagedSync (sync) {
    const self = this;
    return this._request('/sync', sync.query)
               .then(function (data) {
                 sync.append(data);

                 if (!sync.done) {
                   return self._pagedSync(sync);
                 } else {
                   return {
                     items: sync.items,
                     nextSyncToken: sync.nextSyncToken
                   };
                 }
               });
  }

  sync (object, callback) {
    if (!object || (!object.initial && !object.nextSyncToken)) {
      throw new Error('Please provide either the initial flag or a nextSyncToken for syncing');
    }
    const query = new Query(object);
    const deferred = this._pagedSync(new Sync(query)).then(function (response) {
      response.items = parseSearchResult(response);
      return response;
    });
    return nodeify(deferred, callback);
  }
}

class Asset {
  constructor ({sys, fields}) {
    this.sys = new Sys(sys);
    this.fields = fields;
  }

  static parse (object) {
    return new Asset(object);
  }
}

class Entry {
  constructor ({sys, fields}) {
    this.sys = new Sys(sys);
    this.fields = fields;
  }

  static parse (object) {
    return new Entry(object);
  }
}

class ContentType {
  constructor ({sys, fields, name, displayField}) {
    this.sys = new Sys(sys);
    this.name = name;
    this.displayField = displayField;
    this.fields = fields && fields.map(Field.parse);
  }

  static parse (object) {
    return new ContentType(object);
  }
}

class Field {
  constructor (object) {
    for (var k in object) {
      this[k] = object[k];
    }
  }

  static parse (object) {
    return new Field(object);
  }
}

class Query {
  constructor (object) {
    for (var k in object) {
      this[k] = object[k];
    }
  }

  toQueryString () {
    return querystring.stringify(this);
  }

  static parse (object) {
    return new Query(stringifyArrayValues(object));
  }
}

class Space {
  static parse (object) {
    return new Space(object);
  }

  constructor (props = {}) {
    for (let k in props) {
      this[k] = props[k]
    }
  }
}

class Sys {
  constructor ({id, revision, type, locale, contentType, createdAt, linkType, updatedAt, space}) {
    this.id = id;
    this.revision = revision;
    this.type = type;
    this.locale = locale;
    this.space = space && Link.parse(space);
    this.contentType = contentType && new Link(contentType);
    this.createdAt = createdAt && new Date(createdAt);
    this.updatedAt = updatedAt && new Date(updatedAt);
  }

  static parse (object) {
    return new Sys(object);
  }
}

class Link {
  constructor ({sys}) {
    this.sys = new Sys(sys);
  }

  static parse (object) {
    return new Link(object);
  }
}

class Sync {
  constructor (query) {
    this.query = query;
    this.items = [];
    this.done = false;
  }

  append (data) {
    this.items = this.items.concat(data.items);

    if (data.nextPageUrl) {
      const nextPageUrl = data.nextPageUrl.split('?');
      this.query = Object.keys(this.query).reduce((query, key) => {
        if (key !== 'initial' && key !== 'type' && key !== 'sync_token') {
          query[key] = this.query[key]
        }
        return query
      }, {})
      this.query.sync_token = querystring.parse(nextPageUrl[1]).sync_token;
    } else if (data.nextSyncUrl) {
      const nextSyncUrl = data.nextSyncUrl.split('?');
      this.nextSyncToken = querystring.parse(nextSyncUrl[1]).sync_token;
      this.done = true;
    }
  }
}

const parseableResourceTypes = {
  Asset: Asset,
  ContentType: ContentType,
  Entry: Entry,
  Space: Space
};

function isParseableResource (object) {
  return object && object.sys && object.sys.type in parseableResourceTypes;
}

function parseResource (resource) {
  var Type = parseableResourceTypes[resource.sys.type];
  return Type.parse(resource);
}

function parseSearchResult (object) {
  walkMutate(object, isParseableResource, parseResource);
  const items = resolveResponse(object);
  Object.defineProperties(items, {
    limit: { value: object.limit, enumerable: false },
    skip:  { value: object.skip,  enumerable: false },
    total: { value: object.total, enumerable: false }
  });
  return items;
}

function stringifyArrayValues (object) {
  return keys(object).reduce(function (result, key) {
    const value = object[key];
    result[key] = Array.isArray(value) ? value.join(',') : value;
    return result;
  }, {});
}

function walkMutate (input, pred, mutator) {
  if (pred(input)) {
    return mutator(input);
  }

  if (input && typeof input === 'object') {
    for (var key in input) {
      input[key] = walkMutate(input[key], pred, mutator);
    }
  }

  return input;
}

function nodeify (deferred, callback) {
  if (callback) {
    return deferred
    .then(function (response) {
      callback(null, response);
      return response;
    })
    .catch(function (error) {
      callback(error);
      throw error;
    });
  }
  return deferred;
}
<commit_msg>Allow defining custom headers<commit_after>'use strict';

import axios from 'axios';
import resolveResponse from 'contentful-resolve-response';
import querystring from 'querystring';

export function createClient (options) {
  return new Client(options || {});
};

class Client {
  constructor ({accessToken, space, secure, host, headers}) {
    if (!accessToken) {
      throw new TypeError('Expected property accessToken');
    }

    if (!space) {
      throw new TypeError('Expected property space');
    }

    const insecure = secure === false;
    var [hostname, port] = (host && host.split(':')) || [];

    hostname = hostname || 'cdn.contentful.com';
    port = port || (insecure ? 80 : 443);

    this.options = {
      baseUrl: `${insecure ? 'http' : 'https'}://${hostname}:${port}/spaces/${space}`,
      accessToken: accessToken,
      headers: headers || {}
    };
  }

  _request (path, query) {
    if (!query) {
      query = {}
    };

    query.access_token = this.options.accessToken;

    const params = {
      headers: this.options.headers,
      method: 'get',
      url: `${this.options.baseUrl}${path}?${querystring.stringify(query)}`
    };

    params.headers['Content-Type'] = 'application/vnd.contentful.delivery.v1+json';

    return axios(params)
      .then(function (response) {
        return response.data;
      })
      .catch(function (error) {
        throw error.data;
      });
  }

  asset (id, callback) {
    return nodeify(
      this._request('/assets/' + id).then(parseResource),
      callback
    );
  }

  assets (object, callback) {
    const query = new Query(object);
    const deferred = this._request('/assets', query).then(parseSearchResult);
    return nodeify(deferred, callback);
  }

  contentType (id, callback) {
    const deferred = this._request('/content_types/' + id).then(ContentType.parse);
    return nodeify(deferred, callback);
  }

  contentTypes (object, callback) {
    const query = new Query(object);
    const deferred = this._request('/content_types', query).then(parseSearchResult);
    return nodeify(deferred, callback);
  }

  entry (id, callback) {
    const deferred = this._request('/entries/' + id)
                   .then(Entry.parse);
    return nodeify(deferred, callback);
  }

  entries (object, callback) {
    const query = new Query(object);
    const deferred = this._request('/entries', query).then(parseSearchResult);
    return nodeify(deferred, callback);
  }

  space (callback) {
    return nodeify(this._request(''), callback);
  }

  _pagedSync (sync) {
    const self = this;
    return this._request('/sync', sync.query)
               .then(function (data) {
                 sync.append(data);

                 if (!sync.done) {
                   return self._pagedSync(sync);
                 } else {
                   return {
                     items: sync.items,
                     nextSyncToken: sync.nextSyncToken
                   };
                 }
               });
  }

  sync (object, callback) {
    if (!object || (!object.initial && !object.nextSyncToken)) {
      throw new Error('Please provide either the initial flag or a nextSyncToken for syncing');
    }
    const query = new Query(object);
    const deferred = this._pagedSync(new Sync(query)).then(function (response) {
      response.items = parseSearchResult(response);
      return response;
    });
    return nodeify(deferred, callback);
  }
}

class Asset {
  constructor ({sys, fields}) {
    this.sys = new Sys(sys);
    this.fields = fields;
  }

  static parse (object) {
    return new Asset(object);
  }
}

class Entry {
  constructor ({sys, fields}) {
    this.sys = new Sys(sys);
    this.fields = fields;
  }

  static parse (object) {
    return new Entry(object);
  }
}

class ContentType {
  constructor ({sys, fields, name, displayField}) {
    this.sys = new Sys(sys);
    this.name = name;
    this.displayField = displayField;
    this.fields = fields && fields.map(Field.parse);
  }

  static parse (object) {
    return new ContentType(object);
  }
}

class Field {
  constructor (object) {
    for (var k in object) {
      this[k] = object[k];
    }
  }

  static parse (object) {
    return new Field(object);
  }
}

class Query {
  constructor (object) {
    for (var k in object) {
      this[k] = object[k];
    }
  }

  toQueryString () {
    return querystring.stringify(this);
  }

  static parse (object) {
    return new Query(stringifyArrayValues(object));
  }
}

class Space {
  static parse (object) {
    return new Space(object);
  }

  constructor (props = {}) {
    for (let k in props) {
      this[k] = props[k]
    }
  }
}

class Sys {
  constructor ({id, revision, type, locale, contentType, createdAt, linkType, updatedAt, space}) {
    this.id = id;
    this.revision = revision;
    this.type = type;
    this.locale = locale;
    this.space = space && Link.parse(space);
    this.contentType = contentType && new Link(contentType);
    this.createdAt = createdAt && new Date(createdAt);
    this.updatedAt = updatedAt && new Date(updatedAt);
  }

  static parse (object) {
    return new Sys(object);
  }
}

class Link {
  constructor ({sys}) {
    this.sys = new Sys(sys);
  }

  static parse (object) {
    return new Link(object);
  }
}

class Sync {
  constructor (query) {
    this.query = query;
    this.items = [];
    this.done = false;
  }

  append (data) {
    this.items = this.items.concat(data.items);

    if (data.nextPageUrl) {
      const nextPageUrl = data.nextPageUrl.split('?');
      this.query = Object.keys(this.query).reduce((query, key) => {
        if (key !== 'initial' && key !== 'type' && key !== 'sync_token') {
          query[key] = this.query[key]
        }
        return query
      }, {})
      this.query.sync_token = querystring.parse(nextPageUrl[1]).sync_token;
    } else if (data.nextSyncUrl) {
      const nextSyncUrl = data.nextSyncUrl.split('?');
      this.nextSyncToken = querystring.parse(nextSyncUrl[1]).sync_token;
      this.done = true;
    }
  }
}

const parseableResourceTypes = {
  Asset: Asset,
  ContentType: ContentType,
  Entry: Entry,
  Space: Space
};

function isParseableResource (object) {
  return object && object.sys && object.sys.type in parseableResourceTypes;
}

function parseResource (resource) {
  var Type = parseableResourceTypes[resource.sys.type];
  return Type.parse(resource);
}

function parseSearchResult (object) {
  walkMutate(object, isParseableResource, parseResource);
  const items = resolveResponse(object);
  Object.defineProperties(items, {
    limit: { value: object.limit, enumerable: false },
    skip:  { value: object.skip,  enumerable: false },
    total: { value: object.total, enumerable: false }
  });
  return items;
}

function stringifyArrayValues (object) {
  return keys(object).reduce(function (result, key) {
    const value = object[key];
    result[key] = Array.isArray(value) ? value.join(',') : value;
    return result;
  }, {});
}

function walkMutate (input, pred, mutator) {
  if (pred(input)) {
    return mutator(input);
  }

  if (input && typeof input === 'object') {
    for (var key in input) {
      input[key] = walkMutate(input[key], pred, mutator);
    }
  }

  return input;
}

function nodeify (deferred, callback) {
  if (callback) {
    return deferred
    .then(function (response) {
      callback(null, response);
      return response;
    })
    .catch(function (error) {
      callback(error);
      throw error;
    });
  }
  return deferred;
}
<|endoftext|>


<commit_before>module.exports = {

  // Core unit tests
  core: {
    options: {
      reporter: "spec"
    },
    src: ["tests/server/*.js"]
  }

};<commit_msg>Make sur init.js file is loaded before unit tests<commit_after>module.exports = {

  // Core unit tests
  core: {
    options: {
      reporter: "spec"
    },
    src: ["tests/server/init.js", "tests/server/*.js"]
  }

};<|endoftext|>


<commit_before>var frameModule = require("ui/frame");
var Contact = require("./contact-model");
var KnownLabel = require("./known-label");

var CustomCNContactPickerViewControllerDelegate = NSObject.extend({
    initWithResolveReject: function(resolve, reject) {
        var self = this.super.init();
        if(self) {
            this.resolve = resolve;
            this.reject = reject;
        }
        return self;
    },
    contactPickerDidCancel: function(controller){
        this.resolve({
           data: null,
           response: "cancelled",
           ios: null,
           android: null
        });
    },
    contactPickerDidSelectContact: function(controller, contact) {
        controller.dismissModalViewControllerAnimated(true);

        //Convert the native contact object
        var contactModel = new Contact();
        contactModel.initializeFromNative(contact);

        this.resolve({
            data: contactModel,
            response: "selected",
            ios: contact,
            android: null
        });
        CFRelease(controller.delegate);
    }
}, {
    protocols: [CNContactPickerDelegate]
});

exports.getContact = function (){
    return new Promise(function (resolve, reject) {
        var controller = CNContactPickerViewController.alloc().init();
        var delegate = CustomCNContactPickerViewControllerDelegate.alloc().initWithResolveReject(resolve, reject);

        CFRetain(delegate);
        controller.delegate = delegate;

        var page = frameModule.topmost().ios.controller;
        page.presentModalViewControllerAnimated(controller, true);
    });
};
exports.fetchContactsByName = function(searchPredicate){
    return new Promise(function (resolve, reject){
        var store = new CNContactStore(),
        error,
        keysToFetch = [
                "givenName",
                "familyName",
                "middleName",
                "namePrefix",
                "nameSuffix",
                "phoneticGivenName",
                "phoneticMiddleName",
                "phoneticFamilyName",
                "nickname",
                "jobTitle",
                "departmentName",
                "organizationName",
                "notes",
                "phoneNumbers",
                "emailAddresses",
                "postalAddresses",
                "urlAddresses",
                "imageData",
                "imageDataAvailable"
        ], // All Properties that we are using in the Model
        foundContacts = store.unifiedContactsMatchingPredicateKeysToFetchError(CNContact.predicateForContactsMatchingName(searchPredicate), keysToFetch, error);

        if(error){
            reject(error.localizedDescription);
        }

        if (foundContacts.count > 0) {
            var cts = [];
            for(var i=0; i<foundContacts.count; i++){
                var contactModel = new Contact();
                contactModel.initializeFromNative(foundContacts[i]);
                cts.push(contactModel);
            }
            resolve({
                data: cts,
                response: "fetch"
            });
        }
        else{
            resolve({
                data: null,
                response: "fetch"
            });
        }
    });
};
exports.fetchAllContacts = function(){
    return new Promise(function (resolve, reject){
        var store = new CNContactStore(),
        error,
        keysToFetch = [
                "givenName",
                "familyName",
                "middleName",
                "namePrefix",
                "nameSuffix",
                "phoneticGivenName",
                "phoneticMiddleName",
                "phoneticFamilyName",
                "nickname",
                "jobTitle",
                "departmentName",
                "organizationName",
                "notes",
                "phoneNumbers",
                "emailAddresses",
                "postalAddresses",
                "urlAddresses",
                "imageData",
                "imageDataAvailable"
        ], // All Properties that we are using in the Model
        fetch = CNContactFetchRequest.alloc().initWithKeysToFetch(keysToFetch),
        cts = [];

        fetch.unifyResults = true;
        fetch.predicate = null;

        store.enumerateContactsWithFetchRequestErrorUsingBlock(fetch, error, function(c,s){
            var contactModel = new Contact();
            contactModel.initializeFromNative(c);
            cts.push(contactModel);
        });

        if(error){
            reject(error.localizedDescription);
        }

        if(cts.length > 0){
            resolve({
                data: cts,
                response: "fetch"
            });
        }
        else{
            resolve({
                data: null,
                response: "fetch"
            });
        }
    });
};

exports.Contact = Contact;
exports.KnownLabel = KnownLabel;
<commit_msg>Update index.ios.js<commit_after>var frameModule = require("ui/frame");
var Contact = require("./contact-model");
var KnownLabel = require("./known-label");

var CustomCNContactPickerViewControllerDelegate = NSObject.extend({
    initWithResolveReject: function(resolve, reject) {
        var self = this.super.init();
        if(self) {
            this.resolve = resolve;
            this.reject = reject;
        }
        return self;
    },
    contactPickerDidCancel: function(controller){
        this.resolve({
           data: null,
           response: "cancelled",
           ios: null,
           android: null
        });
    },
    contactPickerDidSelectContact: function(controller, contact) {
        controller.dismissModalViewControllerAnimated(true);

        //Convert the native contact object
        var contactModel = new Contact();
        contactModel.initializeFromNative(contact);

        this.resolve({
            data: contactModel,
            response: "selected",
            ios: contact,
            android: null
        });
        CFRelease(controller.delegate);
    }
}, {
    protocols: [CNContactPickerDelegate]
});

exports.getContact = function (){
    return new Promise(function (resolve, reject) {
        var controller = CNContactPickerViewController.alloc().init();
        var delegate = CustomCNContactPickerViewControllerDelegate.alloc().initWithResolveReject(resolve, reject);

        CFRetain(delegate);
        controller.delegate = delegate;

        var page = frameModule.topmost().ios.controller;
        page.presentModalViewControllerAnimated(controller, true);
    });
};
exports.getContactsByName = function(searchPredicate){
    return new Promise(function (resolve, reject){
        var store = new CNContactStore(),
        error,
        keysToFetch = [
                "givenName",
                "familyName",
                "middleName",
                "namePrefix",
                "nameSuffix",
                "phoneticGivenName",
                "phoneticMiddleName",
                "phoneticFamilyName",
                "nickname",
                "jobTitle",
                "departmentName",
                "organizationName",
                "notes",
                "phoneNumbers",
                "emailAddresses",
                "postalAddresses",
                "urlAddresses",
                "imageData",
                "imageDataAvailable"
        ], // All Properties that we are using in the Model
        foundContacts = store.unifiedContactsMatchingPredicateKeysToFetchError(CNContact.predicateForContactsMatchingName(searchPredicate), keysToFetch, error);

        if(error){
            reject(error.localizedDescription);
        }

        if (foundContacts.count > 0) {
            var cts = [];
            for(var i=0; i<foundContacts.count; i++){
                var contactModel = new Contact();
                contactModel.initializeFromNative(foundContacts[i]);
                cts.push(contactModel);
            }
            resolve({
                data: cts,
                response: "fetch"
            });
        }
        else{
            resolve({
                data: null,
                response: "fetch"
            });
        }
    });
};
exports.fetchAllContacts = function(){
    return new Promise(function (resolve, reject){
        var store = new CNContactStore(),
        error,
        keysToFetch = [
                "givenName",
                "familyName",
                "middleName",
                "namePrefix",
                "nameSuffix",
                "phoneticGivenName",
                "phoneticMiddleName",
                "phoneticFamilyName",
                "nickname",
                "jobTitle",
                "departmentName",
                "organizationName",
                "notes",
                "phoneNumbers",
                "emailAddresses",
                "postalAddresses",
                "urlAddresses",
                "imageData",
                "imageDataAvailable"
        ], // All Properties that we are using in the Model
        fetch = CNContactFetchRequest.alloc().initWithKeysToFetch(keysToFetch),
        cts = [];

        fetch.unifyResults = true;
        fetch.predicate = null;

        store.enumerateContactsWithFetchRequestErrorUsingBlock(fetch, error, function(c,s){
            var contactModel = new Contact();
            contactModel.initializeFromNative(c);
            cts.push(contactModel);
        });

        if(error){
            reject(error.localizedDescription);
        }

        if(cts.length > 0){
            resolve({
                data: cts,
                response: "fetch"
            });
        }
        else{
            resolve({
                data: null,
                response: "fetch"
            });
        }
    });
};

exports.Contact = Contact;
exports.KnownLabel = KnownLabel;
<|endoftext|>


<commit_before>/*
 * grunt-generate-config
 * https://github.com/gmodev/grunt-generate-config
 *
 * Copyright (c) 2013 Jason Gill
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

	grunt.registerMultiTask('generateConfig', 'A Grunt plugin to generate configs from templates', function() {

		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({ });
		var target = this.target;
		var input = grunt.file.readJSON(options.input);

		var pattern = /\$(.*)\$/g;
		options.templates.forEach(function(template) {

			var templateInput = grunt.file.read(template);
			var output = templateInput;

			var match;
			while (match = pattern.exec(templateInput)) {

				var replaceMe = match[0];
				var parts = match[1].split("|");
				var sectionConfigEntry = parts[0].split(":");
				var iterator = parts[1];

				var section = sectionConfigEntry[0];
				var configEntry = sectionConfigEntry[1];

				if(input[section] == null) {
					grunt.fail.fatal("Missing section: '" + section + "' from input: '" + options.input + "'");
				}

				var configEntryValue;
				if (typeof input[section][configEntry] === "object" && !(input[section][configEntry] instanceof Array) ) {

					if(input[section][configEntry][target] == null) {
						grunt.fail.fatal("Missing section: '" + section + "' config entry: '" + configEntry + "' target: '" + target + "' from input: '" + options.input + "'");
					}
					configEntryValue = input[section][configEntry][target];
				}
				else {

					if(input[section][configEntry] == null) {
						grunt.fail.fatal("Missing section: '" + section + "' config entry: '" + configEntry + "' from input: '" + options.input + "'");
					}
					configEntryValue = input[section][configEntry];
				}

				var replaceWith = "";
				if (iterator !== undefined) {
					for( var i = 0; i < configEntryValue.length; i++) {
						var value = configEntryValue[i];
						var temp = replaceWith + iterator.replace("{value}", value);

						var j = i + 1;
						if( j === configEntryValue.length ) {
							temp = temp.replace("{newline}", "");
							temp = temp.replace("{comma}", "");
						}
						else {
							temp = temp.replace("{newline}", "\n");
							temp = temp.replace("{comma}", ",");
						}

						replaceWith = temp;
					}
				}
				else {
					replaceWith = configEntryValue;
				}

				output = output.replace(replaceMe, replaceWith);
			}

			var configFile = template.replace(".template", "");
			grunt.log.writeln("Generating config: " + configFile);
			grunt.file.write(configFile, output);
		});

	});

};
<commit_msg>Add support for {value:json} to json encode values<commit_after>/*
 * grunt-generate-config
 * https://github.com/gmodev/grunt-generate-config
 *
 * Copyright (c) 2013 Jason Gill
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

	grunt.registerMultiTask('generateConfig', 'A Grunt plugin to generate configs from templates', function() {

		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({ });
		var target = this.target;
		var input = grunt.file.readJSON(options.input);

		var pattern = /\$(.*)\$/g;
		options.templates.forEach(function(template) {

			var templateInput = grunt.file.read(template);
			var output = templateInput;

			var match;
			while (match = pattern.exec(templateInput)) {

				var replaceMe = match[0];
				var parts = match[1].split("|");
				var sectionConfigEntry = parts[0].split(":");
				var iterator = parts[1];

				var section = sectionConfigEntry[0];
				var configEntry = sectionConfigEntry[1];

				if(input[section] == null) {
					grunt.fail.fatal("Missing section: '" + section + "' from input: '" + options.input + "'");
				}

				var configEntryValue;
				if (typeof input[section][configEntry] === "object" && !(input[section][configEntry] instanceof Array) ) {

					if(input[section][configEntry][target] == null) {
						grunt.fail.fatal("Missing section: '" + section + "' config entry: '" + configEntry + "' target: '" + target + "' from input: '" + options.input + "'");
					}
					configEntryValue = input[section][configEntry][target];
				}
				else {

					if(input[section][configEntry] == null) {
						grunt.fail.fatal("Missing section: '" + section + "' config entry: '" + configEntry + "' from input: '" + options.input + "'");
					}
					configEntryValue = input[section][configEntry];
				}

				var replaceWith = "";
				if (iterator !== undefined) {
					for( var i = 0; i < configEntryValue.length; i++) {
						var value = configEntryValue[i];
						var temp = replaceWith + iterator.replace("{value}", value);
						temp = temp.replace("{value:json}", JSON.stringify(value));

						var j = i + 1;
						if( j === configEntryValue.length ) {
							temp = temp.replace("{newline}", "");
							temp = temp.replace("{comma}", "");
						}
						else {
							temp = temp.replace("{newline}", "\n");
							temp = temp.replace("{comma}", ",");
						}

						replaceWith = temp;
					}
				}
				else {
					replaceWith = configEntryValue;
				}

				output = output.replace(replaceMe, replaceWith);
			}

			var configFile = template.replace(".template", "");
			grunt.log.writeln("Generating config: " + configFile);
			grunt.file.write(configFile, output);
		});

	});

};
<|endoftext|>


<commit_before>/**
 * React Native Playground
 * https://github.com/jsierles/rnplay
 */

'use strict';

var React = require('react-native');
var qs = require('qs');
var LinkingIOS = require('LinkingIOS');
var AppReloader = require('NativeModules').AppReloader;
var Login = require('./App/Screens/Login');
var Signup = require('./App/Screens/Signup');
var Home = require('./App/Screens/Home');
var Guest = require('./App/Screens/Guest');
var ProfileStore = require('./App/Stores/ProfileStore');
var LocalStorage = require('./App/Stores/LocalStorage');
var _ = require('lodash');

var {
  AppRegistry,
  Navigator,
  StyleSheet,
  Text,
  View,
  StatusBarIOS
} = React;

// globals are bad, we make an exception here for now
var RN_VERSION = require('./package.json').dependencies['react-native'];
var githubPrefix = 'facebook/react-native#';
if (RN_VERSION.indexOf(githubPrefix) === 0) {
  RN_VERSION = RN_VERSION.replace(githubPrefix, '');
} else {
  RN_VERSION = RN_VERSION.replace(/\./g,'').replace(/-/g, '')
}
global.RN_VERSION = RN_VERSION;

var RNPlayNative = React.createClass({

  getInitialState() {
    return {
      bootstrapped: false
    };
  },

  componentDidMount() {
    StatusBarIOS.setStyle(StatusBarIOS.Style.lightContent);
    LocalStorage.bootstrap(() => this.setState({bootstrapped: true}));
    LinkingIOS.addEventListener('url', this._processURL);

    var url = LinkingIOS.popInitialURL();
    if (url) {
      this._processURL({url});
    }
  },

  componentWillUnmount() {
    LinkingIOS.removeEventListener('url', this._processURL);
  },

  _processURL(e) {
    var url = e.url.replace('rnplay://', '');
    var {bundle_url, module_name} = qs.parse(url);

    if (bundle_url && module_name) {
      AppReloader.reloadAppWithURLString(bundle_url, module_name);
    }
  },

  render() {
    if (this.state.bootstrapped === false) {
      return <View />;
    }
    return <Home />;
  }
});

AppRegistry.registerComponent('RNPlayNative', () => RNPlayNative);
<commit_msg>use our fork to generate packager URLs<commit_after>/**
 * React Native Playground
 * https://github.com/jsierles/rnplay
 */

'use strict';

var React = require('react-native');
var qs = require('qs');
var LinkingIOS = require('LinkingIOS');
var AppReloader = require('NativeModules').AppReloader;
var Login = require('./App/Screens/Login');
var Signup = require('./App/Screens/Signup');
var Home = require('./App/Screens/Home');
var Guest = require('./App/Screens/Guest');
var ProfileStore = require('./App/Stores/ProfileStore');
var LocalStorage = require('./App/Stores/LocalStorage');
var _ = require('lodash');

var {
  AppRegistry,
  Navigator,
  StyleSheet,
  Text,
  View,
  StatusBarIOS
} = React;

// globals are bad, we make an exception here for now
var RN_VERSION = require('./package.json').dependencies['react-native'];
var githubPrefix = 'rnplay/react-native#';
if (RN_VERSION.indexOf(githubPrefix) === 0) {
  RN_VERSION = RN_VERSION.replace(githubPrefix, '');
} else {
  RN_VERSION = RN_VERSION.replace(/\./g,'').replace(/-/g, '')
}
global.RN_VERSION = RN_VERSION;

var RNPlayNative = React.createClass({

  getInitialState() {
    return {
      bootstrapped: false
    };
  },

  componentDidMount() {
    StatusBarIOS.setStyle(StatusBarIOS.Style.lightContent);
    LocalStorage.bootstrap(() => this.setState({bootstrapped: true}));
    LinkingIOS.addEventListener('url', this._processURL);

    var url = LinkingIOS.popInitialURL();
    if (url) {
      this._processURL({url});
    }
  },

  componentWillUnmount() {
    LinkingIOS.removeEventListener('url', this._processURL);
  },

  _processURL(e) {
    var url = e.url.replace('rnplay://', '');
    var {bundle_url, module_name} = qs.parse(url);

    if (bundle_url && module_name) {
      AppReloader.reloadAppWithURLString(bundle_url, module_name);
    }
  },

  render() {
    if (this.state.bootstrapped === false) {
      return <View />;
    }
    return <Home />;
  }
});

AppRegistry.registerComponent('RNPlayNative', () => RNPlayNative);
<|endoftext|>