<commit_before>var ffi = require('ffi'),
  ref = require('ref'),
  Struct = require('ref-struct'),
  hWnd = new Buffer(8);

var ICCx = Struct({
  'dwSize': 'int32',
  'dwICC': 'int32'
});
var ICCxPtr = ref.refType(ICCx);
var comctl32 = ffi.Library('comctl32', {
  'InitCommonControlsEx': ['int32', [ICCxPtr]]
});

var WndClassEx = Struct({
  'cbSize': 'uint32',
  'style': 'uint32',
  'lpfnWndProc': 'pointer', // callback 'int32', ['pointer', 'uint32', 'int32', 'uint32']
  'cbClsExtra': 'int32',
  'cbWndExtra': 'int32',
  'hInstance': 'pointer', // can be 0?
  'hIcon': 'pointer',
  'hCursor': 'pointer',
  'hbrBackground': 'pointer',
  'lpszMenuName': 'pointer',
  'lpszClassName': 'pointer',
  'hIconSm': 'pointer'
});
var WndClassExPtr = ref.refType(WndClassEx);
var user32 = ffi.Library('user32', {
  'RegisterClassExW': ['int32', [WndClassExPtr]],
  'CreateWindowExW': ['pointer', [
    'int32', 'pointer', 'pointer', 'int32',    // style, name, name, style
    'int32', 'int32', 'int32', 'int32',        // x, y, w, h
    'pointer', 'pointer', 'pointer', 'pointer' // handles
  ]],
  'DefWindowProcW': ['uint32', ['pointer', 'uint32', 'int32', 'pointer']],
  'ShowWindow': ['bool', ['pointer', 'int32']],
  'UpdateWindow': ['bool', ['pointer']],
  'GetMessageW': ['bool', ['pointer', 'pointer', 'uint32', 'uint32']],
  'TranslateMessageEx': ['bool', ['pointer']],
  'DispatchMessageW': ['uint32', ['pointer']],
  'PostQuitMessage': ['void', ['int32']]
});

var kernel32 = ffi.Library('kernel32', {
  'GetModuleHandleExW': ['bool', [
    'int32', 'pointer', 'pointer' // flags, optional LPCTSTR name, ref hModule
  ]], // etc... / kernel32 is your friend!
});
var gdi32 = ffi.Library('gdi32', {
  'CreateSolidBrush': ['pointer', [
    'int32'
  ]],
});

var Msg = Struct({
  'hwnd': 'pointer',
  'message': 'uint32',
  'wParam': 'int32',
  'lParam': 'pointer',
  'time': 'int32',
  'pX': 'int32',
  'pY': 'int32'
});

// App-specific

// Names
var className = new Buffer('Node.js WinForms Class\0', 'ucs-2');
var windowName = new Buffer('Node.js WinForms App\0', 'ucs-2');

// hInstance
var hInstance = new Buffer(8);
kernel32.GetModuleHandleExW(0, null, hInstance);

// WndProc
var WndProc = ffi.Callback('uint32',
  ['pointer', 'uint32', 'int32', 'pointer'],
  function(hwnd, uMsg, wParam, lParam) {
    console.log('Got Message: ' + uMsg + ' /', hwnd.deref());
    var result = 0; // ref.alloc('int32');
    switch(uMsg) {
      case 2:
        user32.PostQuitMessage(0);
        return 0;
      default:
        result = user32.DefWindowProcW(hwnd, uMsg, wParam, lParam);
        console.log('DefWindowProc LRESULT: ' + result);
        return result;
    }
    console.log('Sending LRESULT: ' + result.deref())
    return result;
  }
);

// Common Controls
var icc = new ICCx;
icc.dwSize = 8;
icc.dwICC = 0x40ff;
comctl32.InitCommonControlsEx(icc.ref());

// Window Class
var wClass = new WndClassEx;
wClass.cbSize = 48; //80; // x86 = 48
wClass.style = 3;
wClass.lpfnWndProc = WndProc;
wClass.cbClsExtra = 0;
wClass.cbWndExtra = 0;
wClass.hInstance = hInstance;
wClass.hIcon = null;
wClass.hCursor = null;
wClass.hbrBackground = gdi32.CreateSolidBrush(0xff8000);//null;
wClass.lpszMenuName = null;
wClass.lpszClassName = className;
wClass.hIconSm = null;

if (!user32.RegisterClassExW(wClass.ref()))
  throw 'Error registering class';

hWnd = user32.CreateWindowExW(
  0,
  className,
  windowName,
  0xcf0000, // overlapped window
  1 << 31, // use default
  1 << 31,
  320,
  200,
  null, null, hInstance, null
);

console.log(hWnd);

user32.ShowWindow(hWnd, 1);
user32.UpdateWindow(hWnd);

// message loop
var msg = new Msg;
var getMsgRes = 0;
while (user32.GetMessageW(msg.ref(), null, 0, 0)) {
  user32.TranslateMessageEx(msg.ref());
  user32.DispatchMessageW(msg.ref());
}

return msg.wParam;<commit_msg>add control<commit_after>var ffi = require('ffi'),
  ref = require('ref'),
  os = require('os'),
  Struct = require('ref-struct'),
  hWnd = new Buffer(8);

var ICCx = Struct({
  'dwSize': 'int32',
  'dwICC': 'int32'
});
var ICCxPtr = ref.refType(ICCx);
var comctl32 = ffi.Library('comctl32', {
  'InitCommonControlsEx': ['int32', [ICCxPtr]]
});

var WndClassEx = Struct({
  'cbSize': 'uint32',
  'style': 'uint32',
  'lpfnWndProc': 'pointer', // callback 'int32', ['pointer', 'uint32', 'int32', 'uint32']
  'cbClsExtra': 'int32',
  'cbWndExtra': 'int32',
  'hInstance': 'pointer', // can be 0?
  'hIcon': 'pointer',
  'hCursor': 'pointer',
  'hbrBackground': 'pointer',
  'lpszMenuName': 'pointer',
  'lpszClassName': 'pointer',
  'hIconSm': 'pointer'
});
var WndClassExPtr = ref.refType(WndClassEx);
var user32 = ffi.Library('user32', {
  'RegisterClassExW': ['int32', [WndClassExPtr]],
  'CreateWindowExW': ['pointer', [
    'int32', 'pointer', 'pointer', 'int32',    // style, name, name, style
    'int32', 'int32', 'int32', 'int32',        // x, y, w, h
    'pointer', 'pointer', 'pointer', 'pointer' // handles
  ]],
  'DefWindowProcW': ['uint32', ['pointer', 'uint32', 'int32', 'pointer']],
  'ShowWindow': ['bool', ['pointer', 'int32']],
  'UpdateWindow': ['bool', ['pointer']],
  'GetMessageW': ['bool', ['pointer', 'pointer', 'uint32', 'uint32']],
  'TranslateMessageEx': ['bool', ['pointer']],
  'DispatchMessageW': ['uint32', ['pointer']],
  'PostQuitMessage': ['void', ['int32']],
  'GetWindowLongW' : ['pointer', ['pointer','int32']],
  'SendMessageW':['uint32', ['pointer','uint32','int32','pointer']]
});

var kernel32 = ffi.Library('kernel32', {
  'GetModuleHandleExW': ['bool', [
    'int32', 'pointer', 'pointer' // flags, optional LPCTSTR name, ref hModule
  ]], // etc... / kernel32 is your friend!

  'GetCurrentProcess': ['pointer', [
  ]],
  'IsWow64Process': ['bool', [
    'pointer', 'pointer'
  ]]
});
var gdi32 = ffi.Library('gdi32', {
  'CreateSolidBrush': ['pointer', [ 'int32' ]],
  'SetBkColor': ['int32', [ 'pointer','int32' ]],
  'SetTextColor': ['int32', [ 'pointer','int32' ]],
});

var Msg = Struct({
  'hwnd': 'pointer',
  'message': 'uint32',
  'wParam': 'int32',
  'lParam': 'pointer',
  'time': 'int32',
  'pX': 'int32',
  'pY': 'int32'
});

// test os bit
var cbSize = 48;
var pthread = new Buffer(8);
var bf = new Buffer(1);
pthread = kernel32.GetCurrentProcess();
console.log("pthread => "+pthread);
var r = kernel32.IsWow64Process(pthread,bf);
console.log("IsWow64Process => "+r + "," + bf[0]);
if(r && !bf[0] && os.arch()=='x64') cbSize = 80;

// App-specific

// Names
var className = new Buffer('Node.js WinForms Class\0', 'ucs-2');
var windowName = new Buffer('Node.js WinForms App\0', 'ucs-2');

// hInstance
var hInstance = new Buffer(8);
kernel32.GetModuleHandleExW(0, null, hInstance);

// WndProc
var WndProc = ffi.Callback('uint32',
  ['pointer', 'uint32', 'int32', 'pointer'],
  function(hwnd, uMsg, wParam, lParam) {
    console.log('Got Message: ' + uMsg + ' /', hwnd.deref());
    var result = 0; // ref.alloc('int32');
    switch(uMsg) {
      case 2:
        user32.PostQuitMessage(0);
        console.log("quit hWnd=> " + hwnd.length);
        return 0;
      case 0x0133: // WM_CTLCOLOREDIT
        //gdi32.SetTextColor(wParam,0x0080ff);
        //gdi32.SetBkColor  (wParam,0xffff00);
        return 0;
        // WM_CTLCOLORLISTBOX 134 WM_CTLCOLORBTN 135
      case 0x0138: // WM_CTLCOLORSTATIC
        //gdi32.SetTextColor(wParam,0xffff00);
        //gdi32.SetBkColor  (wParam,0x0080ff);
        return 0;
      default:
        result = user32.DefWindowProcW(hwnd, uMsg, wParam, lParam);
        if(result) console.log('DefWindowProc LRESULT: ' + result );
        return result;
    }
    //console.log('Sending LRESULT: ' + result.deref())
    return result;
  }
);

// Common Controls
var icc = new ICCx;
icc.dwSize = 8;
icc.dwICC = 0x40ff;
comctl32.InitCommonControlsEx(icc.ref());

// Window Class
var wClass = new WndClassEx;
wClass.cbSize = cbSize;//48; //80; // x86 = 48
wClass.style = 3;
wClass.lpfnWndProc = WndProc;
wClass.cbClsExtra = 0;
wClass.cbWndExtra = 0;
wClass.hInstance = hInstance;
wClass.hIcon = null;
wClass.hCursor = null;
wClass.hbrBackground = gdi32.CreateSolidBrush(0xf0800f);//null;
wClass.lpszMenuName = null;
wClass.lpszClassName = className;
wClass.hIconSm = null;

if (!user32.RegisterClassExW(wClass.ref()))
  throw 'Error registering class';

hWnd = user32.CreateWindowExW(
  0,
  className,
  windowName,
  0xcf0000, // overlapped window
  1 << 31, // use default
  1 << 31,
  320,
  200,
  null, null, hInstance, null
);

var btnClassName = new Buffer('BUTTON\0', 'ucs-2');
var btnWindowName = new Buffer('Button\0', 'ucs-2');
var hInst = user32.GetWindowLongW(hWnd, -6);

var hWndButton = user32.CreateWindowExW(
  0,
  btnClassName,   // Predefined class; Unicode assumed.
  btnWindowName,       // Button text.
  1342242817, //WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles.
  10,         // x position.
  10,         // y position.
  100,        // Button width.
  30,        // Button height.
  hWnd,       // Parent window.
  null,       // No menu.
  hInst,
  null);      // Pointer not needed.

var hWndText = user32.CreateWindowExW(
  0,
  new Buffer('EDIT\0', 'ucs-2'),   // Predefined class; Unicode assumed.
  new Buffer('TextBox\0', 'ucs-2'),       // Button text.
  1342242817,
  130,
  10,
  100,
  16,
  hWnd,
  null,
  hInst,
  null);

var hWndStatic = user32.CreateWindowExW(
  0,
  new Buffer('STATIC\0', 'ucs-2'),   // Predefined class; Unicode assumed.
  new Buffer('Label\0', 'ucs-2'),       // Button text.
  1342242817,
  10,
  70,
  100,
  20,
  hWnd,
  null,
  hInst,
  null);

var hWndComboBox = user32.CreateWindowExW(
  0,
  new Buffer('COMBOBOX\0', 'ucs-2'),   // Predefined class; Unicode assumed.
  new Buffer('ComboBox\0', 'ucs-2'),
  1344274947,
  10,
  100,
  100,
  30,
  hWnd,
  null,
  hInst,
  null);

var hWndListBox = user32.CreateWindowExW(
  0,
  new Buffer('LISTBOX\0', 'ucs-2'),   // Predefined class; Unicode assumed.
  new Buffer('ListBox1\0', 'ucs-2'),
  1342242817,
  150,
  50,
  100,
  80,
  hWnd,
  null,
  hInst,
  null);

console.log("handles=> "+hWnd+"[btn="+hWndButton+"]");

var flag = user32.ShowWindow(hWnd, 1);
//console.log("ShowWindow => " + flag);
flag = user32.UpdateWindow(hWnd);
//console.log("UpdateWindow => " + flag);

// var someBuffer = new Buffer('whatever');
// var buf = ref.alloc('pointer');
// ref.writePointer(buf, 0, someBuffer);

user32.SendMessageW(hWndComboBox,0x0143,0,new Buffer('大漠穷秋\0', 'ucs-2'));
user32.SendMessageW(hWndComboBox,0x0143,0,new Buffer('太空飞猪\0', 'ucs-2'));
user32.SendMessageW(hWndComboBox,0x014e,0,null);

user32.SendMessageW(hWndListBox,0x0180,0,new Buffer('大漠穷秋\0', 'ucs-2'));
user32.SendMessageW(hWndListBox,0x0180,0,new Buffer('太空飞猪\0', 'ucs-2'));
user32.SendMessageW(hWndListBox,0x0186,1,null);

// message loop
var msg = new Msg;
var getMsgRes = 0;
while (user32.GetMessageW(msg.ref(), null, 0, 0)) {
  user32.TranslateMessageEx(msg.ref());
  user32.DispatchMessageW(msg.ref());
}

return msg.wParam;<|endoftext|>


<commit_before>import NodeModelComponent from './NodeModelComponent'
import LicenseEditor from './LicenseEditor'

export default class FigureMetadataComponent extends NodeModelComponent {
  _getClassNames () {
    return `sc-figure-metadata sc-node-model`
  }

  _renderHeader ($$) {
    const model = this.props.model
    let header = $$('div').addClass('se-header')
    header.append(
      $$('div').addClass('se-label').text(model.getLabel())
    )
    return header
  }

  // overriding this to get spawn a special editor for the content
  _getPropertyEditorClass (property) {
    // skip 'label' here, as it is shown 'read-only' in the header instead
    if (property.name === 'label') {
      return null
    // special editor to pick license type
    } else if (property.name === 'license') {
      return LicenseEditor
    } else {
      return super._getPropertyEditorClass(property)
    }
  }

  _showLabelForProperty (prop) {
    // Don't render a label for content property to use up the full width
    if (prop === 'content') {
      return false
    }
    return true
  }
}
<commit_msg>Prevent removal of figures from MetadataEditor.<commit_after>import NodeModelComponent from './NodeModelComponent'
import LicenseEditor from './LicenseEditor'

export default class FigureMetadataComponent extends NodeModelComponent {
  _getClassNames () {
    return `sc-figure-metadata sc-node-model`
  }

  _renderHeader ($$) {
    const model = this.props.model
    let header = $$('div').addClass('se-header')
    header.append(
      $$('div').addClass('se-label').text(model.getLabel())
    )
    return header
  }

  // overriding this to get spawn a special editor for the content
  _getPropertyEditorClass (property) {
    // skip 'label' here, as it is shown 'read-only' in the header instead
    if (property.name === 'label') {
      return null
    // special editor to pick license type
    } else if (property.name === 'license') {
      return LicenseEditor
    } else {
      return super._getPropertyEditorClass(property)
    }
  }

  _showLabelForProperty (prop) {
    // Don't render a label for content property to use up the full width
    if (prop === 'content') {
      return false
    }
    return true
  }

  get isRemovable () {
    return false
  }
}
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-13 18:39:04<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var Lang = A.Lang,
	isArray = Lang.isArray,
	isString = Lang.isString,

	getClassName = A.ClassNameManager.getClassName,

	NAME = 'creoleplugin',
	CREOLE_PLUGIN = 'creole',

	TPL_HTML_ELEMENTS = '(<[a-z][a-z0-9]*[^>]*>|</[a-z][a-z0-9]*>)',

	REGEX_HTML_ELEMENTS = new RegExp(TPL_HTML_ELEMENTS, 'gi');

if (!YUI.AUI.defaults.EditorToolbar) {
	YUI.AUI.defaults.EditorToolbar = {
		STRINGS: {}
	};
}

var EditorCreoleCode = A.Component.create(
	{
		NAME: NAME,

		NS: CREOLE_PLUGIN,

		EXTENDS: A.Plugin.Base,

		ATTRS: {
			interwiki: {
				value: {
					WikiCreole: 'http://www.wikicreole.org/wiki/',
					Wikipedia: 'http://en.wikipedia.org/wiki/'
				}
			},

			host: {
				value: false
			},

			linkFormat: {
				value: ''
			},

			strict: {
				value: false
			}
		},

		prototype: {
			html2creole: null,

			initializer: function() {
				var instance = this;

				this._creole = new A.CreoleParser({
					forIE: A.UA.os === 'windows',
					interwiki: this.get('interwiki'),
					linkFormat: this.get('linkFormat'),
					strict: this.get('strict')
				});

				var host = instance.get('host');

				instance.afterHostMethod('getContent', instance.getCreoleCode, instance);
				host.on('contentChange', instance._contentChange, instance);
			},

			_convertHTML2Creole: function(data) {
				var instance = this;

				if (!instance.html2creole) {
					instance.html2creole = new A.HTML2CreoleConvertor({
						data: data
					});
				} else {
					instance.html2creole.set('data', data);
				}

				return instance.html2creole.convert();
			},

			getCreoleCode: function() {
				var instance = this;

				var content = A.Do.originalRetVal;

				content = instance._convertHTML2Creole(content);

				content = content.replace(REGEX_HTML_ELEMENTS, '');

				return new A.Do.AlterReturn(null, content);
			},

			getContentAsHtml: function() {
				var instance = this;

				var host = instance.get('host');

				return host.constructor.prototype.getContent.apply(host, arguments);
			},

			setContentAsCreoleCode: function(creoleCode) {
				var instance = this;

				var host = instance.get('host');

				host.set('content', creoleCode);
			},

			_contentChange: function(event) {
				var instance = this;

				event.newVal = instance._parseCreoleCode(event.newVal);

				event.stopImmediatePropagation();
			},

			_parseCreoleCode: function(creoleCode) {
				var instance = this;

				var div = A.config.doc.createElement('div');

				instance._creole.parse(div, creoleCode);

				var data = div.innerHTML;

				return data;
			}
		}
	}
);

A.namespace('Plugin').EditorCreoleCode = EditorCreoleCode;
<commit_msg>AUI-291 - normalize output from Creole parser for Gecko and WebKit based browsers.<commit_after>var Lang = A.Lang,
	isArray = Lang.isArray,
	isString = Lang.isString,

	getClassName = A.ClassNameManager.getClassName,

	NAME = 'creoleplugin',
	CREOLE_PLUGIN = 'creole',

	TPL_HTML_ELEMENTS = '(<[a-z][a-z0-9]*[^>]*>|</[a-z][a-z0-9]*>)',

	REGEX_HTML_ELEMENTS = new RegExp(TPL_HTML_ELEMENTS, 'gi'),
	REGEX_BOLD = /<(\/?)strong>/gi,
	REGEX_ITALIC = /<(\/?)em>/gi,

	SPAN_TAG_END = '';

if (!YUI.AUI.defaults.EditorToolbar) {
	YUI.AUI.defaults.EditorToolbar = {
		STRINGS: {}
	};
}

var EditorCreoleCode = A.Component.create(
	{
		NAME: NAME,

		NS: CREOLE_PLUGIN,

		EXTENDS: A.Plugin.Base,

		ATTRS: {
			interwiki: {
				value: {
					WikiCreole: 'http://www.wikicreole.org/wiki/',
					Wikipedia: 'http://en.wikipedia.org/wiki/'
				}
			},

			host: {
				value: false
			},

			linkFormat: {
				value: ''
			},

			strict: {
				value: false
			}
		},

		prototype: {
			html2creole: null,

			initializer: function() {
				var instance = this;

				this._creole = new A.CreoleParser({
					forIE: A.UA.os === 'windows',
					interwiki: this.get('interwiki'),
					linkFormat: this.get('linkFormat'),
					strict: this.get('strict')
				});

				var host = instance.get('host');

				instance.afterHostMethod('getContent', instance.getCreoleCode, instance);
				host.on('contentChange', instance._contentChange, instance);
			},

			_convertHTML2Creole: function(data) {
				var instance = this;

				if (!instance.html2creole) {
					instance.html2creole = new A.HTML2CreoleConvertor({
						data: data
					});
				} else {
					instance.html2creole.set('data', data);
				}

				return instance.html2creole.convert();
			},

			getCreoleCode: function() {
				var instance = this;

				var content = A.Do.originalRetVal;

				content = instance._convertHTML2Creole(content);

				content = content.replace(REGEX_HTML_ELEMENTS, '');

				return new A.Do.AlterReturn(null, content);
			},

			getContentAsHtml: function() {
				var instance = this;

				var host = instance.get('host');

				return host.constructor.prototype.getContent.apply(host, arguments);
			},

			setContentAsCreoleCode: function(creoleCode) {
				var instance = this;

				var host = instance.get('host');

				host.set('content', creoleCode);
			},

			_contentChange: function(event) {
				var instance = this;

				event.newVal = instance._parseCreoleCode(event.newVal);

				event.stopImmediatePropagation();
			},

			_normalizeParsedData: function(data){
				var instance = this;

				if (A.UA.gecko) {
					data = instance._normalizeParsedDataGecko(data);
				}
				else if (A.UA.webkit) {
					data = instance._normalizeParsedDataWebKit(data);
				}

				return data;
			},

			_normalizeParsedDataGecko: function(data) {
				// Mozilla stores text which is both bold and italic in one span element.
				// For simplicity we will ignore that for now and we will create always two span elements.
				data = data.replace(REGEX_BOLD, function(str, p1, offset, s) {
					if (!p1) {
						return '';
					}
					else {
						return SPAN_TAG_END;
					}
				});

				data = data.replace(REGEX_ITALIC, function(str, p1, offset, s) {
					if (!p1) {
						return '';
					}
					else {
						return SPAN_TAG_END;
					}
				});

				return data;
			},

			_normalizeParsedDataWebKit: function(data) {
				data = data.replace(REGEX_BOLD, '<$1b>');
				data = data.replace(REGEX_ITALIC, '<$1b>');

				return data;
			},

			_parseCreoleCode: function(creoleCode) {
				var instance = this;

				var div = A.config.doc.createElement('div');

				instance._creole.parse(div, creoleCode);

				var data = div.innerHTML;

				data = instance._normalizeParsedData(data);

				return data;
			}
		}
	}
);

A.namespace('Plugin').EditorCreoleCode = EditorCreoleCode;
<|endoftext|>


<commit_before>var sys = require('sys');
var expat = require('./build/default/node-expat');
var Buffer = require('buffer').Buffer;

function collapseTexts(evs) {
    var r = [];
    var t = "";
    evs.forEach(function(ev) {
	if (ev[0] == 'text')
	    t += ev[1];
	else {
	    if (t != "")
		r.push(['text', t]);
	    t = "";
	    r.push(ev);
	}
    });
    if (t != "")
	r.push(['text', t]);
    return r;
}

var tests = 0, iterations = 0, fails = 0;
function expect(s, evs_expected) {
    tests++;
    for(var step = s.length; step > 0; step--) {
	iterations++;
	var evs_received = [];
	var p = new expat.Parser("UTF-8");
	//p.setEncoding("UTF-8");
	p.addListener('startElement', function(name, attrs) {
	    evs_received.push(['startElement', name, attrs]);
	});
	p.addListener('endElement', function(name) {
	    evs_received.push(['endElement', name]);
	});
	p.addListener('text', function(s) {
	    evs_received.push(['text', s]);
	});
	p.addListener('processingInstruction', function(target, data) {
	    evs_received.push(['processingInstruction', target, data]);
	});
	p.addListener('comment', function(s) {
	    evs_received.push(['comment', s]);
	});
	p.addListener('xmlDecl', function(version, encoding, standalone) {
	    evs_received.push(['xmlDecl', version, encoding, standalone]);
	});
	p.addListener('startCdata', function() {
	    evs_received.push(['startCdata']);
	});
	p.addListener('endCdata', function() {
	    evs_received.push(['endCdata']);
	});
	for(var l = 0; l < s.length; l += step)
	{
	    var end = l + step;
	    if (end > s.length)
		end = s.length;

	    if (!p.parse(s.slice(l, end), false))
		evs_received.push(['error']);
	}

	var expected = JSON.stringify(evs_expected);
	var received = JSON.stringify(collapseTexts(evs_received));
	if (expected != received) {
	    fails++;
	    sys.puts("Fail for: " + s + " (step=" + step + ")");
	    sys.puts("Expected: " + expected);
	    sys.puts("Received: " + received);
	    return;  // don't try with smaller step size
	}
    }
}

expect("<r/>",
       [['startElement', 'r', {}],
	['endElement', 'r']]);
expect("<r foo='bar'/>",
       [['startElement', 'r', {foo: 'bar'}],
	['endElement', 'r']]);
expect("<r foo='bar' baz=\"quux\" test=\"tset\"/>",
       [['startElement', 'r', {foo: 'bar', baz: 'quux', test: 'tset'}],
	['endElement', 'r']]);
expect("<r xmlns='http://localhost/' xmlns:x=\"http://example.com/\"></r>",
       [['startElement', 'r', {xmlns: 'http://localhost/', 'xmlns:x': 'http://example.com/'}],
	['endElement', 'r']]);
expect("<r>foo</r>",
       [['startElement', 'r', {}],
	['text', "foo"],
	['endElement', 'r']]);
expect("<r>foo\nbar</r>",
       [['startElement', 'r', {}],
	['text', "foo\nbar"],
	['endElement', 'r']]);
expect("<r><![CDATA[<greeting>Hello, world!</greeting>]]></r>",
       [['startElement', 'r', {}],
	['startCdata'],
	['text', "<greeting>Hello, world!</greeting>"],
	['endCdata'],
	['endElement', 'r']]);
expect("<r>foo&bar</r>",
       [['startElement', 'r', {}],
	['text', "foo&bar"],
	['endElement', 'r']]);
expect("<r>ß</r>",
       [['startElement', 'r', {}],
	['text', "ß"],
	['endElement', 'r']]);
expect("<?i like xml?>",
       [['processingInstruction', 'i', 'like xml']]);
expect("<?dragons?>",
       [['processingInstruction', 'dragons', '']]);
expect("<!-- no comment -->",
       [['comment', ' no comment ']]);
expect("<&", [['error']]);
expect("<?xml version='1.0' encoding='UTF-8'?>",
       [['xmlDecl', '1.0', 'UTF-8', true]]);
expect("<?xml version='1.0'?>",
       [['xmlDecl', '1.0', null, true]]);
expect(new Buffer('<foo>bar</foo>'),
       [['startElement', 'foo', {}],
	['text', 'bar'],
	['endElement', 'foo']]);
expect(new Buffer('<foo><![CDATA[bar]]></foo>'),
       [['startElement', 'foo', {}],
	['startCdata'],
	['text', 'bar'],
	['endCdata'],
	['endElement', 'foo']]);

sys.puts("Ran "+tests+" tests with "+iterations+" iterations: "+fails+" failures.");
<commit_msg>test for start/stop<commit_after>var sys = require('sys');
var expat = require('./build/default/node-expat');
var Buffer = require('buffer').Buffer;

function collapseTexts(evs) {
    var r = [];
    var t = "";
    evs.forEach(function(ev) {
	if (ev[0] == 'text')
	    t += ev[1];
	else {
	    if (t != "")
		r.push(['text', t]);
	    t = "";
	    r.push(ev);
	}
    });
    if (t != "")
	r.push(['text', t]);
    return r;
}

var tests = 0, iterations = 0, fails = 0;
function expect(s, evs_expected) {
    tests++;
    for(var step = s.length; step > 0; step--) {
	iterations++;
	var evs_received = [];
	var p = new expat.Parser("UTF-8");
	//p.setEncoding("UTF-8");
	p.addListener('startElement', function(name, attrs) {
	    evs_received.push(['startElement', name, attrs]);
	});
	p.addListener('endElement', function(name) {
	    evs_received.push(['endElement', name]);
	});
	p.addListener('text', function(s) {
	    evs_received.push(['text', s]);
	});
	p.addListener('processingInstruction', function(target, data) {
	    evs_received.push(['processingInstruction', target, data]);
	});
	p.addListener('comment', function(s) {
	    evs_received.push(['comment', s]);
	});
	p.addListener('xmlDecl', function(version, encoding, standalone) {
	    evs_received.push(['xmlDecl', version, encoding, standalone]);
	});
	p.addListener('startCdata', function() {
	    evs_received.push(['startCdata']);
	});
	p.addListener('endCdata', function() {
	    evs_received.push(['endCdata']);
	});
	for(var l = 0; l < s.length; l += step)
	{
	    var end = l + step;
	    if (end > s.length)
		end = s.length;

	    if (!p.parse(s.slice(l, end), false))
		evs_received.push(['error']);
	}

	var expected = JSON.stringify(evs_expected);
	var received = JSON.stringify(collapseTexts(evs_received));
	if (expected != received) {
	    fails++;
	    sys.puts("Fail for: " + s + " (step=" + step + ")");
	    sys.puts("Expected: " + expected);
	    sys.puts("Received: " + received);
	    return;  // don't try with smaller step size
	}
    }
}

function testStopResume(cb)
{
	var p = new expat.Parser("UTF-8");

	var input = '\
		<wrap> \
			<short /> \
			<short></short> \
			<long /> \
			<short /> \
			<long>foo</long> \
		</wrap>';

	var expected = ['wrap', 'short', 'short', 'long', 'short', 'long'];
	var received = [];

	var tolerance = 10/100;
	var expectedRuntime = 1000;
	var start = new Date();

	p.addListener('startElement', function(name, attrs) {
		received.push(name);

		// suspend parser for 1/2 second
		if(name == 'long') {
			p.stop();

			setTimeout(function() {
				p.resume();
			}, 500);
		}
	})

	p.addListener('endElement', function(name) {
		// finished parsing
		if(name == 'wrap') {
			// test elements received (count. naming, order)
			if(JSON.stringify(expected) != JSON.stringify(received)) {
				sys.puts("Failed Stop/Resume test");
				sys.puts("Expected: " + expected);
				sys.puts("Received: " + received);
				return cb(false);
			}

			// test timing (+-5%)
			var now = new Date();
			var diff = now.getTime() - start.getTime();
			var max = expectedRuntime + expectedRuntime * tolerance,
				min = expectedRuntime - expectedRuntime * tolerance;

			if(diff > max) {
				sys.puts("Failed Stop/Resume test");
				sys.puts("Expected Runtime < " + max);
				sys.puts("Taken Runtime: " + diff);
				return cb(false);
			}

			if(diff < min) {
				sys.puts("Failed Stop/Resume test");
				sys.puts("Expected Runtime > " + min);
				sys.puts("Taken Runtime: " + diff);
				return cb(false);
			}

			sys.puts("Completed Stop/Resume test");
			return cb(true);
		}
	});

	if(!p.parse(input)) {
		sys.puts("Failed Stop/Resume test: parse returned error: "+p.getError());
		return cb(false);
	}
}

expect("<r/>",
       [['startElement', 'r', {}],
	['endElement', 'r']]);
expect("<r foo='bar'/>",
       [['startElement', 'r', {foo: 'bar'}],
	['endElement', 'r']]);
expect("<r foo='bar' baz=\"quux\" test=\"tset\"/>",
       [['startElement', 'r', {foo: 'bar', baz: 'quux', test: 'tset'}],
	['endElement', 'r']]);
expect("<r xmlns='http://localhost/' xmlns:x=\"http://example.com/\"></r>",
       [['startElement', 'r', {xmlns: 'http://localhost/', 'xmlns:x': 'http://example.com/'}],
	['endElement', 'r']]);
expect("<r>foo</r>",
       [['startElement', 'r', {}],
	['text', "foo"],
	['endElement', 'r']]);
expect("<r>foo\nbar</r>",
       [['startElement', 'r', {}],
	['text', "foo\nbar"],
	['endElement', 'r']]);
expect("<r><![CDATA[<greeting>Hello, world!</greeting>]]></r>",
       [['startElement', 'r', {}],
	['startCdata'],
	['text', "<greeting>Hello, world!</greeting>"],
	['endCdata'],
	['endElement', 'r']]);
expect("<r>foo&bar</r>",
       [['startElement', 'r', {}],
	['text', "foo&bar"],
	['endElement', 'r']]);
expect("<r>ß</r>",
       [['startElement', 'r', {}],
	['text', "ß"],
	['endElement', 'r']]);
expect("<?i like xml?>",
       [['processingInstruction', 'i', 'like xml']]);
expect("<?dragons?>",
       [['processingInstruction', 'dragons', '']]);
expect("<!-- no comment -->",
       [['comment', ' no comment ']]);
expect("<&", [['error']]);
expect("<?xml version='1.0' encoding='UTF-8'?>",
       [['xmlDecl', '1.0', 'UTF-8', true]]);
expect("<?xml version='1.0'?>",
       [['xmlDecl', '1.0', null, true]]);
expect(new Buffer('<foo>bar</foo>'),
       [['startElement', 'foo', {}],
	['text', 'bar'],
	['endElement', 'foo']]);
expect(new Buffer('<foo><![CDATA[bar]]></foo>'),
       [['startElement', 'foo', {}],
	['startCdata'],
	['text', 'bar'],
	['endCdata'],
	['endElement', 'foo']]);

sys.puts("Ran "+tests+" tests with "+iterations+" iterations: "+fails+" failures.");

sys.puts("Starting async StartStop (wait for result...)");
testStopResume(function(success) {
	sys.puts("StartStop Test "+(success ? 'succeeded' : 'failed'));
});

<|endoftext|>


<commit_before>var fs = require("fs");
var assert = require("assert");
var mask = require("./mask");

function readToArrayBuffer (path, callback) {
  var rs = fs.createReadStream(path);
  rs.on("readable", function () {
    var buffer = rs.read();
    var ab = new ArrayBuffer(buffer.length);
    var u8 = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; i++) {
      u8[i] = buffer[i];
    };
    callback(ab);
  });
};

var pbm = [ "test-data/bullet-ascii.pbm",
            "test-data/frame-ascii.pbm",
            "test-data/bullet-binary.pbm",
            "test-data/frame-binary.pbm" ];

describe("mask.Mask", function () {
  describe("#fromPBM()", function () {
    it("exists.", function () {
      assert.notEqual(mask.Mask.fromPBM, undefined);
    });
    function assertReads (path) {
      it("reads " + path + ".", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.fromPBM(ab, function (mask) {
            done();
          });
        });
      });
    };
    function assertSize (path, width, height) {
      it("gets the size of " + path + " right.", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.fromPBM(ab, function (mask) {
            assert.equal(mask.size.x, width);
            assert.equal(mask.size.y, height);
            done();
          });
        });
      });
    };
    pbm.forEach(function (img) {
      assertReads(img);
      assertSize(img, 10, 10);
    });
    function assertDataEqual (a, b) {
      it("gets the same data for " + a + " and " + b, function (done) {
        readToArrayBuffer(a, function (abA) {
          mask.Mask.fromPBM(abA, function (maskA) {
            readToArrayBuffer(b, function (abB) {
              mask.Mask.fromPBM(abB, function (maskB) {
                assert.equal(maskA.size.x, maskB.size.x);
                assert.equal(maskA.size.y, maskB.size.y);
                for (var x = 0; x < maskA.size.x; x++) {
                  for (var y = 0; y < maskA.size.y; y++) {
                    assert.equal(maskA.data[x][y], maskB.data[x][y]);
                  };
                };
                done();
              });
            });
          });
        });
      });
    };
    assertDataEqual("test-data/bullet-binary.pbm",
                    "test-data/bullet-ascii.pbm");
    assertDataEqual("test-data/frame-binary.pbm",
                    "test-data/frame-ascii.pbm");
  });
  describe(".collidesWith()", function () {
    function assertCollidesWithSelf (path) {
      it ("says " + path + " collides with itself.", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.fromPBM(ab, function (m) {
            assert.equal(mask.Mask.collision(m, m), true);
            done();
          });
        });
      });
    };
    assertCollidesWithSelf("test-data/bullet-ascii.pbm");
  });
});
<commit_msg>tell whether things collide with themselves translated (they shouldn't)<commit_after>var fs = require("fs");
var assert = require("assert");
var mask = require("./mask");

function readToArrayBuffer (path, callback) {
  var rs = fs.createReadStream(path);
  rs.on("readable", function () {
    var buffer = rs.read();
    var ab = new ArrayBuffer(buffer.length);
    var u8 = new Uint8Array(ab);
    for (var i = 0; i < buffer.length; i++) {
      u8[i] = buffer[i];
    };
    callback(ab);
  });
};

var pbm = [ "test-data/bullet-ascii.pbm",
            "test-data/frame-ascii.pbm",
            "test-data/bullet-binary.pbm",
            "test-data/frame-binary.pbm" ];

describe("mask.Mask", function () {
  describe("#fromPBM()", function () {
    it("exists.", function () {
      assert.notEqual(mask.Mask.fromPBM, undefined);
    });
    function assertReads (path) {
      it("reads " + path + ".", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.fromPBM(ab, function (mask) {
            done();
          });
        });
      });
    };
    function assertSize (path, width, height) {
      it("gets the size of " + path + " right.", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.fromPBM(ab, function (mask) {
            assert.equal(mask.size.x, width);
            assert.equal(mask.size.y, height);
            done();
          });
        });
      });
    };
    pbm.forEach(function (img) {
      assertReads(img);
      assertSize(img, 10, 10);
    });
    function assertDataEqual (a, b) {
      it("gets the same data for " + a + " and " + b, function (done) {
        readToArrayBuffer(a, function (abA) {
          mask.Mask.fromPBM(abA, function (maskA) {
            readToArrayBuffer(b, function (abB) {
              mask.Mask.fromPBM(abB, function (maskB) {
                assert.equal(maskA.size.x, maskB.size.x);
                assert.equal(maskA.size.y, maskB.size.y);
                for (var x = 0; x < maskA.size.x; x++) {
                  for (var y = 0; y < maskA.size.y; y++) {
                    assert.equal(maskA.data[x][y], maskB.data[x][y]);
                  };
                };
                done();
              });
            });
          });
        });
      });
    };
    assertDataEqual("test-data/bullet-binary.pbm",
                    "test-data/bullet-ascii.pbm");
    assertDataEqual("test-data/frame-binary.pbm",
                    "test-data/frame-ascii.pbm");
  });
  describe(".collidesWith()", function () {
    function assertCollidesWithSelf (path) {
      it ("says " + path + " collides with itself.", function (done) {
        readToArrayBuffer(path, function (ab) {
          mask.Mask.fromPBM(ab, function (m) {
            assert.equal(mask.Mask.collision(m, m), true);
            done();
          });
        });
      });
    };
    function assertDoesNotCollideWithTranslatedSelf (path) {
      it("says" + path + "doesn't collide with itself, translated",
         function (done) {
           readToArrayBuffer(path, function (ab) {
             mask.Mask.fromPBM(ab, function (m) {
               var o = m.at(m.size.x, m.size.y);
               assert.equal(mask.Mask.collision(m, o), false);
               done();
             });
           });
         });
    };
    pbm.forEach(function (img) {
      assertCollidesWithSelf(img);
      assertDoesNotCollideWithTranslatedSelf(img);
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var inherits = require('util').inherits;

var createFunction = require('./');
var invoke = require('./invoke');

function Type (name, length) {
  if (typeof this !== 'function')
    return createFunction(name, length, Type, arguments);

  this.count = 0;
}
inherits(Type, Function);

Type.prototype[invoke] = function (val) {
  this.count += val;
};

var t1 = new Type('nate', 6);
assert.ok(t1 instanceof Type);
assert.ok(t1 instanceof Function);
assert.ok(t1 instanceof Object);
assert.equal(t1.name, 'nate');
assert.equal(t1.length, 6);
assert.equal(t1.count, 0);
t1(5);
assert.equal(t1.count, 5);

var t2 = new Type('foo', 6);
assert.ok(t2 instanceof Type);
assert.ok(t2 instanceof Function);
assert.ok(t2 instanceof Object);
assert.equal(t2.name, 'foo');
assert.equal(t2.length, 6);
assert.equal(t2.count, 0);
t2(-1);
assert.equal(t2.count, -1);

function Subclass (init) {
  if (typeof this !== 'function')
    return createFunction('sub', 100, Subclass, arguments);
  Type.call(this);
  this.count = init;
}
inherits(Subclass, Type);

var s1 = new Subclass(6);
assert.ok(s1 instanceof Subclass);
assert.ok(s1 instanceof Type);
assert.ok(s1 instanceof Function);
assert.ok(s1 instanceof Object);
assert.equal(s1.name, 'sub');
assert.equal(s1.length, 100);
assert.equal(s1.count, 6);
s1(-1);
assert.equal(s1.count, 5);

// one off instance
var oneOff = createFunction('oneOff', 1);
var oneOffCalled = false;
assert.ok(oneOff instanceof Function);
assert.ok(oneOff instanceof Object);
assert.equal(oneOff.name, 'oneOff');
assert.equal(oneOff.length, 1);
assert.throws(function () {
  oneOff();
});
oneOff[invoke] = function () {
  oneOffCalled = true;
  return [].slice.apply(arguments);
};
assert.ok(!oneOffCalled);
assert.deepEqual(oneOff('foo', 'bar'), [ 'foo', 'bar' ]);
assert.ok(oneOffCalled);

// unicode and otherwise invalid JS idenifiers may be used as the name
var snowman = createFunction('⌛', 30);
assert.equal(snowman.name, '⌛');
assert.equal(snowman.length, 30);

// `this` arg
var thisArg = createFunction();
thisArg[invoke] = function () {
  return this;
};
assert.equal(thisArg(), thisArg);
assert.equal(thisArg()()(), thisArg());
assert.equal(thisArg.call(global), global);
assert.equal(thisArg.call(1).valueOf(), 1);
assert.equal(thisArg.call(true).valueOf(), true);
<commit_msg>test: add "bind()" test<commit_after>var assert = require('assert');
var inherits = require('util').inherits;

var createFunction = require('./');
var invoke = require('./invoke');

function Type (name, length) {
  if (typeof this !== 'function')
    return createFunction(name, length, Type, arguments);

  this.count = 0;
}
inherits(Type, Function);

Type.prototype[invoke] = function (val) {
  this.count += val;
};

var t1 = new Type('nate', 6);
assert.ok(t1 instanceof Type);
assert.ok(t1 instanceof Function);
assert.ok(t1 instanceof Object);
assert.equal(t1.name, 'nate');
assert.equal(t1.length, 6);
assert.equal(t1.count, 0);
t1(5);
assert.equal(t1.count, 5);

var t2 = new Type('foo', 6);
assert.ok(t2 instanceof Type);
assert.ok(t2 instanceof Function);
assert.ok(t2 instanceof Object);
assert.equal(t2.name, 'foo');
assert.equal(t2.length, 6);
assert.equal(t2.count, 0);
t2(-1);
assert.equal(t2.count, -1);

function Subclass (init) {
  if (typeof this !== 'function')
    return createFunction('sub', 100, Subclass, arguments);
  Type.call(this);
  this.count = init;
}
inherits(Subclass, Type);

var s1 = new Subclass(6);
assert.ok(s1 instanceof Subclass);
assert.ok(s1 instanceof Type);
assert.ok(s1 instanceof Function);
assert.ok(s1 instanceof Object);
assert.equal(s1.name, 'sub');
assert.equal(s1.length, 100);
assert.equal(s1.count, 6);
s1(-1);
assert.equal(s1.count, 5);

// one off instance
var oneOff = createFunction('oneOff', 1);
var oneOffCalled = false;
assert.ok(oneOff instanceof Function);
assert.ok(oneOff instanceof Object);
assert.equal(oneOff.name, 'oneOff');
assert.equal(oneOff.length, 1);
assert.throws(function () {
  oneOff();
});
oneOff[invoke] = function () {
  oneOffCalled = true;
  return [].slice.apply(arguments);
};
assert.ok(!oneOffCalled);
assert.deepEqual(oneOff('foo', 'bar'), [ 'foo', 'bar' ]);
assert.ok(oneOffCalled);

// unicode and otherwise invalid JS idenifiers may be used as the name
var snowman = createFunction('⌛', 30);
assert.equal(snowman.name, '⌛');
assert.equal(snowman.length, 30);

// `this` arg
var thisArg = createFunction();
thisArg[invoke] = function () {
  return this;
};
assert.equal(thisArg(), thisArg);
assert.equal(thisArg()()(), thisArg());
assert.equal(thisArg.call(global), global);
assert.equal(thisArg.call(1).valueOf(), 1);
assert.equal(thisArg.call(true).valueOf(), true);

var that = { foo: 'bar' };
var thatArg = thisArg.bind(that);
assert.equal(thatArg(), that);
assert.equal(thatArg().foo, 'bar');
assert.equal(thatArg.call(global), that);
<|endoftext|>


<commit_before>/**
  @module ember-ui-components
*/
import Ember from 'ember';
import ClickOutsideMixin from 'ember-ui-components/mixins/click-outside';
import layout from '../templates/components/uic-context-menu-container';
import { getDimensions, getMousePosition, calculatePosition } from 'ember-ui-components/lib/fn';

const { alias } = Ember.computed;

/**
  @class ContextMenuContainerComponent
  @namespace Components
*/
export default Ember.Component.extend(ClickOutsideMixin, {
  layout,

  /**
    Injected `contextMenu` service
    @property contextMenuService
    @type {Object}
    @private
  */
  contextMenuService: Ember.inject.service('context-menu'),

  /**
    @property tagName
    @type {String}
    @private
    @default 'menu'
  */
  tagName: 'menu',

  /**
    @property classNames
    @type {Array}
    @private
    @default `['uic-context-menu-container', 'uic-menu-container']`
  */
  classNames: ['uic-context-menu-container', 'uic-menu-container'],

  /**
    @property classNameBindings
    @type {Array}
    @private
    @default `['hideOutline:no-outline']`
  */
  classNameBindings: ['hideOutline:no-outline'],

  /**
    @property attributeBindings
    @type {Array}
    @private
    @default `['tabindex']`
  */
  attributeBindings: ['tabindex'],

  /**
    @property tabindex
    @type {Integer}
    @private
    @default `1`
  */
  tabindex: 1,

  /**
    If this property is true the element will be given the `no-outline` css class
    which will hide the outline that an element is given when it is focused.

    @property hideOutline
    @type {Boolean}
    @private
    @default `true`
  */
  hideOutline: true,

  /**
    @property contextMenuParams
    @type {Object}
    @private
  */
  contextMenuParams: alias('contextMenuService.contextMenuParams'),

  /**
    ## setPosition

    Set the left/top css properties of an element.

    `element` should be a reference to an HTML element.  Either a string selector
    that can be used with jQuery, or a jQuery selection object.

    If `position` is not specified, then the current mouse position will be used.

    `position` should be an Ember.Object with `x` and `y` properties.
    Both `x` and `y` should be numbers

    @method setPosition
    @param {String|Object} element
    @param {Object} position
  */
  setPosition(element, position) {
    let margin = 5;
    if (typeof element === 'string') {
      element = Ember.$(element);
    }
    if (!position) {
      position = getMousePosition(window.event || window._event);
    }
    let scrollBarWidth = (window.innerWidth - Ember.$(window).width());
    let el = getDimensions(element);
    element.css({
      'left': calculatePosition( position.get('x') + 2, el.width, window.innerWidth - ( margin + scrollBarWidth)),
      'top': calculatePosition( position.get('y'), el.height, window.innerHeight - margin)
    });
  },

  /**
    @method handleClickOutside
    @private
  */
  handleClickOutside() {
    this.sendAction();
  },

  /**
    @method didInsertElement
    @private
  */
  didInsertElement() {
    this._super(...arguments);
    this.setPosition(this.$(), getMousePosition(this.get('contextMenuParams.event')));
    this.$().focus();
  },

  /**
    @event keyDown
    @param {Object} event
    @private
  */
  keyDown(event) {
    switch(event.keyCode) {
      case 13: // enter
        this.sendAction();
        break;
      case 27: // escape
        this.sendAction();
        break;
    }
  },

  /**
    @event click
    @private
  */
  click() {
    this.sendAction();
  }
});
<commit_msg>update context-menu-container<commit_after>/**
  @module ember-ui-components
*/
import Ember from 'ember';
import ClickOutsideMixin from 'ember-ui-components/mixins/click-outside';
import layout from '../templates/components/uic-context-menu-container';
import setPosition from 'ember-ui-components/utils/set-position';
import getMousePosition from 'ember-ui-components/utils/get-mouse-position';

const { alias } = Ember.computed;

/**
  @class ContextMenuContainerComponent
  @namespace Components
*/
export default Ember.Component.extend(ClickOutsideMixin, {
  layout,

  /**
    Injected `contextMenu` service
    @property contextMenuService
    @type {Object}
    @private
  */
  contextMenuService: Ember.inject.service('context-menu'),

  /**
    @property tagName
    @type {String}
    @private
    @default 'menu'
  */
  tagName: 'menu',

  /**
    @property classNames
    @type {Array}
    @private
    @default `['uic-context-menu-container', 'uic-menu-container']`
  */
  classNames: ['uic-context-menu-container', 'uic-menu-container'],

  /**
    @property classNameBindings
    @type {Array}
    @private
    @default `['hideOutline:no-outline']`
  */
  classNameBindings: ['hideOutline:no-outline'],

  /**
    @property attributeBindings
    @type {Array}
    @private
    @default `['tabindex']`
  */
  attributeBindings: ['tabindex'],

  /**
    @property tabindex
    @type {Integer}
    @private
    @default `1`
  */
  tabindex: 1,

  /**
    If this property is true the element will be given the `no-outline` css class
    which will hide the outline that an element is given when it is focused.

    @property hideOutline
    @type {Boolean}
    @private
    @default `true`
  */
  hideOutline: true,

  /**
    @property contextMenuParams
    @type {Object}
    @private
  */
  contextMenuParams: alias('contextMenuService.contextMenuParams'),

  /**
    ## setPosition

    Set the left/top css properties of an element.

    `element` should be a reference to an HTML element.  Either a string selector
    that can be used with jQuery, or a jQuery selection object.

    If `position` is not specified, then the current mouse position will be used.

    `position` should be an Ember.Object with `x` and `y` properties.
    Both `x` and `y` should be numbers

    @method setPosition
    @param {String|Object} element
    @param {Object} position
  */
  setPosition,

  /**
    @method handleClickOutside
    @private
  */
  handleClickOutside() {
    this.sendAction();
  },

  /**
    @method didInsertElement
    @private
  */
  didInsertElement() {
    this._super(...arguments);
    this.setPosition(this.$(), getMousePosition(this.get('contextMenuParams.event')));
    this.$().focus();
  },

  /**
    @event keyDown
    @param {Object} event
    @private
  */
  keyDown(event) {
    switch(event.keyCode) {
      case 13: // enter
        this.sendAction();
        break;
      case 27: // escape
        this.sendAction();
        break;
    }
  },

  /**
    @event click
    @private
  */
  click() {
    this.sendAction();
  }
});
<|endoftext|>


<commit_before>odoo.define('web.local_storage', function (require) {
'use strict';

var RamStorage = require('web.RamStorage');
var mixins = require('web.mixins');

// use a fake localStorage in RAM if the native localStorage is unavailable
// (e.g. private browsing in Safari)
var storage;
var localStorage = window.localStorage;
try {
    var uid = new Date();
    localStorage.setItem(uid, uid);
    localStorage.removeItem(uid);

    /*
     * We create an intermediate object in order to triggered the storage on
     * this object. the localStorage. This simplifies testing and usage as
     * starages are commutable in services without change. Also, objects
     * that use storage do not have to know that events go through window,
     * it's not up to them to handle these cases.
     */
    storage = (function () {
        var storage = Object.create(_.extend({
                getItem: localStorage.getItem.bind(localStorage),
                setItem: localStorage.setItem.bind(localStorage),
                removeItem: localStorage.removeItem.bind(localStorage),
                clear: localStorage.clear.bind(localStorage),
            },
            mixins.EventDispatcherMixin
        ));
        storage.init();
        $(window).on('storage', function (e) {
            var key = e.originalEvent.key;
            var newValue = e.originalEvent.newValue;
            try {
                JSON.parse(newValue);
                if (localStorage.getItem(key) === newValue) {
                    storage.trigger('storage', {
                        key: key,
                        newValue: newValue,
                    });
                }
            } catch (error) {}
        });
        return storage;
    })();

} catch (exception) {
	console.warn('Fail to load localStorage');
    storage = new RamStorage();
}

return storage;

});
<commit_msg>[FIX] bus: background slave tabs should not loose notifications<commit_after>odoo.define('web.local_storage', function (require) {
'use strict';

var RamStorage = require('web.RamStorage');
var mixins = require('web.mixins');

// use a fake localStorage in RAM if the native localStorage is unavailable
// (e.g. private browsing in Safari)
var storage;
var localStorage = window.localStorage;
try {
    var uid = new Date();
    localStorage.setItem(uid, uid);
    localStorage.removeItem(uid);

    /*
     * We create an intermediate object in order to triggered the storage on
     * this object. the localStorage. This simplifies testing and usage as
     * starages are commutable in services without change. Also, objects
     * that use storage do not have to know that events go through window,
     * it's not up to them to handle these cases.
     */
    storage = (function () {
        var storage = Object.create(_.extend({
                getItem: localStorage.getItem.bind(localStorage),
                setItem: localStorage.setItem.bind(localStorage),
                removeItem: localStorage.removeItem.bind(localStorage),
                clear: localStorage.clear.bind(localStorage),
            },
            mixins.EventDispatcherMixin
        ));
        storage.init();
        $(window).on('storage', function (e) {
            var key = e.originalEvent.key;
            var newValue = e.originalEvent.newValue;
            try {
                JSON.parse(newValue);
                storage.trigger('storage', {
                    key: key,
                    newValue: newValue,
                });
            } catch (error) {}
        });
        return storage;
    })();

} catch (exception) {
	console.warn('Fail to load localStorage');
    storage = new RamStorage();
}

return storage;

});
<|endoftext|>


<commit_before>//(Rule-based sentence boundary segmentation) - chop given text into its proper sentences.
// Ignore periods/questions/exclamations used in acronyms/abbreviations/numbers, etc.
// @spencermountain 2017 MIT

//proper nouns with exclamation marks
// const blacklist = {
//   yahoo: true,
//   joomla: true,
//   jeopardy: true,
// }

//regs-
const initSplit = /(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g
const hasSomething = /\S/

const isAcronym = /[ .][A-Z]\.? *$/i
const hasEllipse = /(?:\u2026|\.{2,}) *$/
const newLine = /((?:\r?\n|\r)+)/ // Match different new-line formats
const hasLetter = /[a-z0-9\u00C0-\u00FF\u00a9\u00ae\u2000-\u3300\ud000-\udfff]/i

const startWhitespace = /^\s+/

// Start with a regex:
const naiive_split = function (text) {
  let all = []
  //first, split by newline
  let lines = text.split(newLine)
  for (let i = 0; i < lines.length; i++) {
    //split by period, question-mark, and exclamation-mark
    let arr = lines[i].split(initSplit)
    for (let o = 0; o < arr.length; o++) {
      all.push(arr[o])
    }
  }
  return all
}

/** does this look like a sentence? */
const isSentence = function (str, abbrevs) {
  // check for 'F.B.I.'
  if (isAcronym.test(str) === true) {
    return false
  }
  //check for '...'
  if (hasEllipse.test(str) === true) {
    return false
  }
  // must have a letter
  if (hasLetter.test(str) === false) {
    return false
  }

  let txt = str.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/, '')
  let words = txt.split(' ')
  let lastWord = words[words.length - 1].toLowerCase()
  // check for 'Mr.'
  if (abbrevs.hasOwnProperty(lastWord)) {
    return false
  }
  // //check for jeopardy!
  // if (blacklist.hasOwnProperty(lastWord)) {
  //   return false
  // }
  return true
}

const splitSentences = function (text, world) {
  let abbrevs = world.cache.abbreviations

  text = text || ''
  text = String(text)
  let sentences = []
  // First do a greedy-split..
  let chunks = []
  // Ensure it 'smells like' a sentence
  if (!text || typeof text !== 'string' || hasSomething.test(text) === false) {
    return sentences
  }
  // cleanup unicode-spaces
  text = text.replace('\xa0', ' ')
  // Start somewhere:
  let splits = naiive_split(text)
  // Filter-out the crap ones
  for (let i = 0; i < splits.length; i++) {
    let s = splits[i]
    if (s === undefined || s === '') {
      continue
    }
    //this is meaningful whitespace
    if (hasSomething.test(s) === false) {
      //add it to the last one
      if (chunks[chunks.length - 1]) {
        chunks[chunks.length - 1] += s
        continue
      } else if (splits[i + 1]) {
        //add it to the next one
        splits[i + 1] = s + splits[i + 1]
        continue
      }
    }
    //else, only whitespace, no terms, no sentence
    chunks.push(s)
  }

  //detection of non-sentence chunks:
  //loop through these chunks, and join the non-sentence chunks back together..
  for (let i = 0; i < chunks.length; i++) {
    let c = chunks[i]
    //should this chunk be combined with the next one?
    if (chunks[i + 1] && isSentence(c, abbrevs) === false) {
      chunks[i + 1] = c + (chunks[i + 1] || '')
    } else if (c && c.length > 0) {
      //&& hasLetter.test(c)
      //this chunk is a proper sentence..
      sentences.push(c)
    }
    chunks[i] = ''
  }
  //if we never got a sentence, return the given text
  if (sentences.length === 0) {
    return [text]
  }

  //move whitespace to the ends of sentences, when possible
  //['hello',' world'] -> ['hello ','world']
  for (let i = 1; i < sentences.length; i += 1) {
    let ws = sentences[i].match(startWhitespace)
    if (ws !== null) {
      sentences[i - 1] += ws[0]
      sentences[i] = sentences[i].replace(startWhitespace, '')
    }
  }
  return sentences
}

module.exports = splitSentences
// console.log(sentence_parser('john f. kennedy'));
<commit_msg>Add early exits for tests in isSentence to improve speed for case when long string contains no sentence/letters<commit_after>//(Rule-based sentence boundary segmentation) - chop given text into its proper sentences.
// Ignore periods/questions/exclamations used in acronyms/abbreviations/numbers, etc.
// @spencermountain 2017 MIT

//proper nouns with exclamation marks
// const blacklist = {
//   yahoo: true,
//   joomla: true,
//   jeopardy: true,
// }

//regs-
const initSplit = /(\S.+?[.!?\u203D\u2E18\u203C\u2047-\u2049])(?=\s+|$)/g
const hasSomething = /\S/

const isAcronym = /[ .][A-Z]\.? *$/i
const hasEllipse = /(?:\u2026|\.{2,}) *$/
const newLine = /((?:\r?\n|\r)+)/ // Match different new-line formats
const hasLetter = /[a-z0-9\u00C0-\u00FF\u00a9\u00ae\u2000-\u3300\ud000-\udfff]/i

const startWhitespace = /^\s+/

// Start with a regex:
const naiive_split = function (text) {
  let all = []
  //first, split by newline
  let lines = text.split(newLine)
  for (let i = 0; i < lines.length; i++) {
    //split by period, question-mark, and exclamation-mark
    let arr = lines[i].split(initSplit)
    for (let o = 0; o < arr.length; o++) {
      all.push(arr[o])
    }
  }
  return all
}

const testIsAcronym = function (str, suffix) {
  // early exit
  if (suffix.indexOf('.') === -1) {
    return false
  }
  return isAcronym.test(str);
}

const testHasEllipse = function (str, suffix) {
  // early exit
  if (suffix.indexOf('.') === -1) {
    return false
  }
  return hasEllipse.test(str);
}

const testHasLetter = function (str, suffix, prefixHasLetter) {
  return prefixHasLetter || hasLetter.test(suffix)
}

/** does this look like a sentence? */
const isSentence = function (str, suffix, abbrevs, prefixContext) {
  // must have a letter
  prefixContext.hasLetter = testHasLetter(str, suffix, prefixContext.hasLetter)
  if (!prefixContext.hasLetter) {
    return false
  }
  // check for 'F.B.I.'
  if (testIsAcronym(str, suffix)) {
    return false;
  }
  //check for '...'
  if (testHasEllipse(str, suffix)) {
    return false;
  }

  let txt = str.replace(/[.!?\u203D\u2E18\u203C\u2047-\u2049] *$/, '')
  let words = txt.split(' ')
  let lastWord = words[words.length - 1].toLowerCase()
  // check for 'Mr.'
  if (abbrevs.hasOwnProperty(lastWord)) {
    return false
  }
  // //check for jeopardy!
  // if (blacklist.hasOwnProperty(lastWord)) {
  //   return false
  // }
  return true
}

const splitSentences = function (text, world) {
  let abbrevs = world.cache.abbreviations

  text = text || ''
  text = String(text)
  let sentences = []
  // First do a greedy-split..
  let chunks = []
  // Ensure it 'smells like' a sentence
  if (!text || typeof text !== 'string' || hasSomething.test(text) === false) {
    return sentences
  }
  // cleanup unicode-spaces
  text = text.replace('\xa0', ' ')
  // Start somewhere:
  let splits = naiive_split(text)
  // Filter-out the crap ones
  for (let i = 0; i < splits.length; i++) {
    let s = splits[i]
    if (s === undefined || s === '') {
      continue
    }
    //this is meaningful whitespace
    if (hasSomething.test(s) === false) {
      //add it to the last one
      if (chunks[chunks.length - 1]) {
        chunks[chunks.length - 1] += s
        continue
      } else if (splits[i + 1]) {
        //add it to the next one
        splits[i + 1] = s + splits[i + 1]
        continue
      }
    }
    //else, only whitespace, no terms, no sentence
    chunks.push(s)
  }

  //detection of non-sentence chunks:
  //loop through these chunks, and join the non-sentence chunks back together..
  let suffix = chunks[0] || ''
  const prefixContext = { hasLetter: false }
  for (let i = 0; i < chunks.length; i++) {
    let c = chunks[i]
    //should this chunk be combined with the next one?
    if (chunks[i + 1] && isSentence(c, suffix, abbrevs, prefixContext) === false) {
      suffix = chunks[i + 1] || ''
      chunks[i + 1] = c + suffix
    } else if (c && c.length > 0) {
      //&& hasLetter.test(c)
      //this chunk is a proper sentence..
      sentences.push(c)
      suffix = chunks[i + 1] || ''
      prefixContext.hasLetter = false
    }
    chunks[i] = ''
  }
  //if we never got a sentence, return the given text
  if (sentences.length === 0) {
    return [text]
  }

  //move whitespace to the ends of sentences, when possible
  //['hello',' world'] -> ['hello ','world']
  for (let i = 1; i < sentences.length; i += 1) {
    let ws = sentences[i].match(startWhitespace)
    if (ws !== null) {
      sentences[i - 1] += ws[0]
      sentences[i] = sentences[i].replace(startWhitespace, '')
    }
  }
  return sentences
}

module.exports = splitSentences
// console.log(sentence_parser('john f. kennedy'));
<|endoftext|>


<commit_before>var request = require('request')
var asciify = require('asciify')
var fs = require('fs')

var addContributor = require('./contributors.js')

var baseURL = 'https://api.github.com/repos/jlord/patchwork/'
var stats = {}

module.exports = function(pullreq, callback) {
  if (pullreq.pull_request) pullreq = pullreq.pull_request
  // if branch name doesn't include username, it may be
  // a non git-it related, normal PR
  if (!pullreq.head.ref.toLowerCase().match(pullreq.user.login.toLowerCase()) && pullreq.user.login != "reporobot")
    return callback(new Error("Id\'d via branch to not be a Git-it submission or test"))

  stats.prNum = pullreq.number

  var options = {
      url: baseURL +'pulls/' + stats.prNum,
      json: true,
      headers: { 'User-Agent': 'request',
                 'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
        }
  }

  function getTime(error, response, body) {
    if (error) return callback(error, "Error in request on PR via number")
    // if a test pr is coming in
    if (!error && response.statusCode == 200 && pullreq.user.login === "reporobot") {
      var info = body
      stats.time = info.created_at
      // RR is PRing on behalf of:
      stats.username = info.head.user.login
      console.log(new Date(), "PR " ,  stats.prNum , "Reporobot Pull Request on behalf of " , stats.username)
      return getFile(stats.prNum)
    }

    if (!error && response.statusCode == 200 && pullreq.user.login != "reporobot") {
      var info = body
      stats.time = info.created_at
      stats.username = info.user.login
      return getFile(stats.prNum)
    }

    callback(body)
  }

  request(options, getTime)

  function getFile(prNum) {

    var options = {
        url: baseURL + 'pulls/' + prNum + '/files',
        json: true,
        headers: {
            'User-Agent': 'request',
            'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
        }
    }

    request(options, function returnFiles(error, response, body) {
      if (error || body.length === 0) return callback(error, "Error finding file in PR")

      if (!error && response.statusCode == 200) {
        var prInfo = body[0]
        return verifyFilename(prInfo)
      }

      callback(body)
    })
  }

  function verifyFilename(prInfo) {
    var filename = prInfo.filename
    if (filename.match('contributors/add-' + stats.username + '.txt')) {
      console.log(new Date(), "PR " , stats.prNum , "Filename: MATCH " , stats.username)
      return verifyContent(prInfo)
    }
    else {
      var message = 'Filename is different than expected: contributors/add-' + stats.username + '.txt. Close the pull request, rename your file and try again!'
      return writeComment(message, stats.prNum)
    }
  }

  function verifyContent(prInfo) {
    // pull out the actual pr content
    var patchArray = prInfo.patch.split('@@')
    var patch = patchArray.pop()
    // generate the expected content
    asciify(stats.username, {font:'isometric2'}, function(err, res){
      if (err) return callback(err, "Error generating ascii art to test against")
      console.log(patch)
      console.log(res)
      if (patch !== stats.username) {
        stats.userArt = res
        console.log(new Date(), "PR " , stats.prNum , "Content: MATCH " , stats.username)
        return setTimeout(mergePR(stats.prNum), 5000)
      }
      else {
        var message = "Ascii art wasn't as expected, did something change? Close and re-open please."
        return writeComment(message, stats.prNum)
      }
    })
  }

  function writeComment(message, prNum) {
    console.log(new Date(), "PR " +  prNum + "Uh oh, writing comment for " + stats.username)
     var options = {
        url: baseURL + 'issues/' + prNum + '/comments',
        headers: {
            'User-Agent': 'request',
            'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
        },
        json: {'body': message}
    }

    request.post(options, function doneWriteComment(error, response, body) {
      if (error) return callback(error, "Error writing comment on PR")
      callback()
    })
  }

  function mergePR(prNum) {
    var message = "Merging PR from @" + stats.username
    var options = {
       url: baseURL + 'pulls/' + prNum + '/merge',
       headers: {
           'User-Agent': 'request',
           'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
       },
       json: {'commit_message': message}
   }

    request.put(options, function doneMerge(error, response, body) {
      if (error) return callback(error, "Error merging PR")
      if (response.statusCode != 200) {
        console.log(new Date(), prNum, "ERROR MERGING", response.statusCode, body.message)
        console.log(new Date(), prNum, "TRYING AGAIN")
        return setTimeout(mergePR(prNum), 3000)
      }
      if (!error && response.statusCode == 200) {
        console.log(new Date(), "PR " , prNum , "MERGED" , stats.username)
        // add contributor to file and then rebuild page
        return addContributor(stats, callback)
      } else {
       callback(error, body)
      }
    })
  }
}
<commit_msg>change date format<commit_after>var request = require('request')
var asciify = require('asciify')
var fs = require('fs')

var addContributor = require('./contributors.js')

var baseURL = 'https://api.github.com/repos/jlord/patchwork/'
var stats = {}

module.exports = function(pullreq, callback) {
  if (pullreq.pull_request) pullreq = pullreq.pull_request
  // if branch name doesn't include username, it may be
  // a non git-it related, normal PR
  if (!pullreq.head.ref.toLowerCase().match(pullreq.user.login.toLowerCase()) && pullreq.user.login != "reporobot")
    return callback(new Error("Id\'d via branch to not be a Git-it submission or test"))

  stats.prNum = pullreq.number

  var options = {
      url: baseURL +'pulls/' + stats.prNum,
      json: true,
      headers: { 'User-Agent': 'request',
                 'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
        }
  }

  function getTime(error, response, body) {
    if (error) return callback(error, "Error in request on PR via number")
    // if a test pr is coming in
    if (!error && response.statusCode == 200 && pullreq.user.login === "reporobot") {
      var info = body
      stats.time = info.created_at.toLocaleString()
      // RR is PRing on behalf of:
      stats.username = info.head.user.login
      console.log(new Date(), "PR " ,  stats.prNum , "Reporobot Pull Request on behalf of " , stats.username)
      return getFile(stats.prNum)
    }

    if (!error && response.statusCode == 200 && pullreq.user.login != "reporobot") {
      var info = body
      stats.time = info.created_at
      stats.username = info.user.login
      return getFile(stats.prNum)
    }

    callback(body)
  }

  request(options, getTime)

  function getFile(prNum) {

    var options = {
        url: baseURL + 'pulls/' + prNum + '/files',
        json: true,
        headers: {
            'User-Agent': 'request',
            'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
        }
    }

    request(options, function returnFiles(error, response, body) {
      if (error || body.length === 0) return callback(error, "Error finding file in PR")

      if (!error && response.statusCode == 200) {
        var prInfo = body[0]
        return verifyFilename(prInfo)
      }

      callback(body)
    })
  }

  function verifyFilename(prInfo) {
    var filename = prInfo.filename
    if (filename.match('contributors/add-' + stats.username + '.txt')) {
      console.log(new Date(), "PR " , stats.prNum , "Filename: MATCH " , stats.username)
      return verifyContent(prInfo)
    }
    else {
      var message = 'Filename is different than expected: contributors/add-' + stats.username + '.txt. Close the pull request, rename your file and try again!'
      return writeComment(message, stats.prNum)
    }
  }

  function verifyContent(prInfo) {
    // pull out the actual pr content
    var patchArray = prInfo.patch.split('@@')
    var patch = patchArray.pop()
    // generate the expected content
    asciify(stats.username, {font:'isometric2'}, function(err, res){
      if (err) return callback(err, "Error generating ascii art to test against")
      console.log(patch)
      console.log(res)
      if (patch !== stats.username) {
        stats.userArt = res
        console.log(new Date(), "PR " , stats.prNum , "Content: MATCH " , stats.username)
        return setTimeout(mergePR(stats.prNum), 5000)
      }
      else {
        var message = "Ascii art wasn't as expected, did something change? Close and re-open please."
        return writeComment(message, stats.prNum)
      }
    })
  }

  function writeComment(message, prNum) {
    console.log(new Date(), "PR " +  prNum + "Uh oh, writing comment for " + stats.username)
     var options = {
        url: baseURL + 'issues/' + prNum + '/comments',
        headers: {
            'User-Agent': 'request',
            'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
        },
        json: {'body': message}
    }

    request.post(options, function doneWriteComment(error, response, body) {
      if (error) return callback(error, "Error writing comment on PR")
      callback()
    })
  }

  function mergePR(prNum) {
    var message = "Merging PR from @" + stats.username
    var options = {
       url: baseURL + 'pulls/' + prNum + '/merge',
       headers: {
           'User-Agent': 'request',
           'Authorization': 'token ' + process.env['REPOROBOT_TOKEN']
       },
       json: {'commit_message': message}
   }

    request.put(options, function doneMerge(error, response, body) {
      if (error) return callback(error, "Error merging PR")
      if (response.statusCode != 200) {
        console.log(new Date(), prNum, "ERROR MERGING", response.statusCode, body.message)
        console.log(new Date(), prNum, "TRYING AGAIN")
        return setTimeout(mergePR(prNum), 3000)
      }
      if (!error && response.statusCode == 200) {
        console.log(new Date(), "PR " , prNum , "MERGED" , stats.username)
        // add contributor to file and then rebuild page
        return addContributor(stats, callback)
      } else {
       callback(error, body)
      }
    })
  }
}
<|endoftext|>


<commit_before>var Promise = require("bluebird");

var RowInserter = module.exports = function() {};

RowInserter.prototype.end = function() {};

RowInserter.prototype.connect = function(callback) {
  if(callback) {
    callback();
  }
};

module.exports = RowInserter;<commit_msg>removing unneeded bluebird import<commit_after>var RowInserter = module.exports = function() {};

RowInserter.prototype.end = function() {};

RowInserter.prototype.connect = function(callback) {
  if(callback) {
    callback();
  }
};

module.exports = RowInserter;<|endoftext|>


<commit_before>'use strict';

var njwt = require('njwt');

var OauthAccessTokenAuthenticator = require('../authc/OauthAccessTokenAuthenticator');
var ApiAuthRequestError = require('../error/ApiAuthRequestError');
var JwtAuthenticationResult = require('./jwt-authentication-result');

function JwtAuthenticator(application) {
  if (!(this instanceof JwtAuthenticator)) {
    return new JwtAuthenticator(application);
  }

  this.application = application;
}

JwtAuthenticator.prototype.defaultCookieName = 'access_token';

JwtAuthenticator.prototype.localValidation = false;

JwtAuthenticator.prototype.withLocalValidation = function withLocalValidation() {
  this.localValidation = true;
  return this;
};

JwtAuthenticator.prototype.withCookie = function withCookie(cookieName){
  this.configuredCookieName = cookieName;
  return this;
};

JwtAuthenticator.prototype.unauthenticated = function unauthenticated(){
  return new ApiAuthRequestError({userMessage:'Unauthorized', statusCode: 401});
};

JwtAuthenticator.prototype.authenticate = function authenticate(token,cb){
  var self = this;

  var secret = self.application.dataStore.requestExecutor.options.client.apiKey.secret;

  try {
    njwt.verify(token,secret,function(err,jwt){
      if(err){
        err.statusCode = 401;
        cb(err);
      }else{
        if(self.localValidation){
          cb(null, new JwtAuthenticationResult(self.application,{
            jwt: token,
            expandedJwt: jwt,
            localValidation: true,
            account: {
              href: jwt.body.sub
            }
          }));
        }else if(jwt.header.kid){
          // If the KID exists, this was issued by our API
          var href = self.application.href + '/authTokens/' + token;
          self.application.dataStore.getResource(href,function(err,response){
            if(err){
              cb(err);
            }else{
              cb(null, new JwtAuthenticationResult(self.application,response));
            }
          });
        }else{

          // If there is no KID, this means it was
          // issued by the SDK (not the API) so we have
          // to do remote validation in a different way
          var authenticator = new OauthAccessTokenAuthenticator(self.application, token);
          authenticator.authenticate(cb);
        }
      }
    });
  } catch (err) {
    cb(err);
  }

  return this;
};

module.exports = JwtAuthenticator;
<commit_msg>Fix: local validation forced on client-credential tokens<commit_after>'use strict';

var njwt = require('njwt');

var OauthAccessTokenAuthenticator = require('../authc/OauthAccessTokenAuthenticator');
var ApiAuthRequestError = require('../error/ApiAuthRequestError');
var JwtAuthenticationResult = require('./jwt-authentication-result');

function JwtAuthenticator(application) {
  if (!(this instanceof JwtAuthenticator)) {
    return new JwtAuthenticator(application);
  }

  this.application = application;
}

JwtAuthenticator.prototype.defaultCookieName = 'access_token';

JwtAuthenticator.prototype.localValidation = false;

JwtAuthenticator.prototype.withLocalValidation = function withLocalValidation() {
  this.localValidation = true;
  return this;
};

JwtAuthenticator.prototype.withCookie = function withCookie(cookieName){
  this.configuredCookieName = cookieName;
  return this;
};

JwtAuthenticator.prototype.unauthenticated = function unauthenticated(){
  return new ApiAuthRequestError({userMessage:'Unauthorized', statusCode: 401});
};

JwtAuthenticator.prototype.authenticate = function authenticate(token,cb){
  var self = this;

  var secret = self.application.dataStore.requestExecutor.options.client.apiKey.secret;

  try {
    njwt.verify(token,secret,function(err,jwt){
      if(err){
        err.statusCode = 401;
        cb(err);
      }else{

        // If the KID exists, this was issued by our API from a password grant

        if(jwt.header.kid){
          if(self.localValidation){
            return cb(null, new JwtAuthenticationResult(self.application,{
              jwt: token,
              expandedJwt: jwt,
              localValidation: true,
              account: {
                href: jwt.body.sub
              }
            }));
          }
          var href = self.application.href + '/authTokens/' + token;
          self.application.dataStore.getResource(href,function(err,response){
            if(err){
              cb(err);
            }else{
              cb(null, new JwtAuthenticationResult(self.application,response));
            }
          });
        }else{

          // If there is no KID, this means it was issued by the SDK (not the
          // API) from a client credentials grant so we have to do remote
          // validation in a different way.
          var authenticator = new OauthAccessTokenAuthenticator(self.application, token);
          authenticator.authenticate(cb);
        }
      }
    });
  } catch (err) {
    cb(err);
  }

  return this;
};

module.exports = JwtAuthenticator;
<|endoftext|>