<commit_before>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

function getEnumerableKeys(obj) {
  var result = [];
  for (var name in obj) {
    result.push(name);
  }
  return result;
}

////////////////////////////////////////////////////////////////////////
// registerTestSuite
////////////////////////////////////////////////////////////////////////

function RegisterTestSuiteTest() {
  // Make a copy of the real object; we will replace it later. Then clear it for
  // the duration of this test.
  this.originalTestConstructors_ = gjstest.internal.testSuites;
  gjstest.internal.testSuites = [];
}
registerTestSuite(RegisterTestSuiteTest);

RegisterTestSuiteTest.prototype.tearDown = function() {
  gjstest.internal.testSuites = this.originalTestConstructors_;
};

RegisterTestSuiteTest.prototype.NotAFunction = function() {
  expectThat(function() {
    registerTestSuite({});
  }, throwsError(/TypeError.*registerTestSuite.*function/));
};

RegisterTestSuiteTest.prototype.StoresConstructors = function() {
  function TestSuite1() {}
  function TestSuite2() {}

  registerTestSuite(TestSuite1);
  registerTestSuite(TestSuite2);

  expectThat(gjstest.internal.testSuites,
             elementsAre([TestSuite1, TestSuite2]));
};

RegisterTestSuiteTest.prototype.AlreadyRegistered = function() {
  function TestSuite() {}

  expectThat(function() {
    registerTestSuite(TestSuite);
    registerTestSuite(TestSuite);
  }, throwsError(/already registered.*TestSuite/));
};

////////////////////////////////////////////////////////////////////////
// addTest
////////////////////////////////////////////////////////////////////////

function AddTestTest() {
  // Make a copy of the real object; we will replace it later. Then clear it for
  // the duration of this test.
  this.originalTestConstructors_ = gjstest.internal.testSuites;
  gjstest.internal.testSuites = [];

  // Register a fake test suite for use in our tests.
  this.someSuite_ = function SomeSuite() {};
  registerTestSuite(this.someSuite_);
}
registerTestSuite(AddTestTest);

AddTestTest.prototype.tearDown = function() {
  gjstest.internal.testSuites = this.originalTestConstructors_;
};

AddTestTest.prototype.TestSuiteIsNull = function() {
  expectThat(function() {
    addTest(null, function Foo() {});
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestSuiteIsNotFunction = function() {
  expectThat(function() {
    addTest(17, function Foo() {});
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestSuiteNotRegistered = function() {
  function UnregisteredSuite() {}

  expectThat(function() {
    addTest(UnregisteredSuite, function Foo() {});
  }, throwsError(/not.*registered.*UnregisteredSuite/));
};

AddTestTest.prototype.TestFuncIsNull = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, null);
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestFuncNotFunction = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, 17);
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestFuncHasNoName = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, function() {});
  }, throwsError(/function.*must have.*name/));
};

AddTestTest.prototype.TestFuncNameEndsInUnderscore = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, function foo_() {});
  }, throwsError(/Error.*Illegal.*name.*foo_/));
};

AddTestTest.prototype.TestFuncNameIstearDown = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, function tearDown() {});
  }, throwsError(/Error.*Illegal.*name.*tearDown/));
};

AddTestTest.prototype.TestFuncNameAlreadyPresentFromBareRegistration =
    function() {
  var someSuite = this.someSuite_;
  someSuite.prototype.DoesFoo = function() {};
  someSuite.prototype.DoesBar = function() {};

  // Make sure that the code doesn't use mucked-around-with properties.
  someSuite.prototype.hasOwnProperty = null;
  someSuite.prototype.propertyIsEnumerable = null;

  expectThat(function() {
    addTest(someSuite, function DoesFoo() {});
  }, throwsError(/already.*registered.*DoesFoo/));
};

AddTestTest.prototype.TestFuncNameAlreadyPresentFromAddTest = function() {
  var someSuite = this.someSuite_;
  addTest(someSuite, function DoesFoo() {});
  addTest(someSuite, function DoesBar() {});

  // Make sure that the code doesn't use mucked-around-with properties.
  someSuite.prototype.hasOwnProperty = null;
  someSuite.prototype.propertyIsEnumerable = null;

  expectThat(function() {
    addTest(someSuite, function DoesFoo() {});
  }, throwsError(/already.*registered.*DoesFoo/));
};

AddTestTest.prototype.RegistersTestFunctions = function() {
  var someSuite = this.someSuite_;
  addTest(someSuite, function constructor() {});
  addTest(someSuite, function hasOwnProperty() {});
  addTest(someSuite, function propertyIsEnumerable() {});
  addTest(someSuite, function prototype() {});
  addTest(someSuite, function DoesFoo() {});
  addTest(someSuite, function DoesBar() {});

  expectThat(getEnumerableKeys(someSuite.prototype),
             elementsAre([
                 'constructor',
                 'hasOwnProperty',
                 'propertyIsEnumerable',
                 'prototype',
                 'DoesFoo',
                 'DoesBar',
             ]));
};

////////////////////////////////////////////////////////////////////////
// getTestFunctions
////////////////////////////////////////////////////////////////////////

function GetTestFunctionsTest() {}
registerTestSuite(GetTestFunctionsTest);

GetTestFunctionsTest.prototype.TestNames = function() {
  function TestSuite() {}
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.someOtherName = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result),
             elementsAre([
               'TestSuite.someName',
               'TestSuite.someOtherName'
             ]));
};

GetTestFunctionsTest.prototype.IgnoresTrailingUnderscores = function() {
  function TestSuite() {}
  TestSuite.prototype.harmless_underscores = function() {};
  TestSuite.prototype.ignoredName_ = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result),
             elementsAre(['TestSuite.harmless_underscores']));
};

GetTestFunctionsTest.prototype.IgnoresTearDown = function() {
  function TestSuite() {}
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.tearDown = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result), elementsAre(['TestSuite.someName']));
};

GetTestFunctionsTest.prototype.IgnoresInheritedFunctions = function() {
  function ParentSuite() {}
  ParentSuite.prototype.overridden = function() {};
  ParentSuite.prototype.nonOverridden = function() {};

  function TestSuite() {}
  TestSuite.prototype = new ParentSuite;
  TestSuite.prototype.overridden = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result), elementsAre(['TestSuite.overridden']));
};

GetTestFunctionsTest.prototype.IgnoresNonFunctions = function() {
  function TestSuite() {}
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.ignoredName = {};
  TestSuite.prototype.constructor = {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result), elementsAre(['TestSuite.someName']));
};

GetTestFunctionsTest.prototype.Execution = function() {
  // Create two test functions that record 'this'.
  var testAThis = null;
  var testBThis = null;

  function TestSuite() {}
  TestSuite.prototype.someName = function() { testAThis = this; };
  TestSuite.prototype.someOtherName = function() { testBThis = this; };

  // Get test functions and run them in order.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);

  testFunctions['TestSuite.someName']();
  testFunctions['TestSuite.someOtherName']();

  // Each 'this' value should have been a different instance of TestSuite.
  expectNe(testAThis, testBThis);
  expectTrue(testAThis instanceof TestSuite);
  expectTrue(testBThis instanceof TestSuite);
};

GetTestFunctionsTest.prototype.ExecutionWithTearDown = function() {
  // A test suite whose tearDown method records the 'this' values it sees.
  var tearDownThisValues = [];

  function TestSuite() {}
  TestSuite.prototype.tearDown = function() { tearDownThisValues.push(this); };

  // Two test functions.
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.someOtherName = function() {};

  // Run the tests.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  var foo = testFunctions['TestSuite.someName'];
  testFunctions['TestSuite.someName']();
  testFunctions['TestSuite.someOtherName']();

  // Each 'this' value should have been a different instance of TestSuite.
  expectEq(2, tearDownThisValues.length);
  expectNe(tearDownThisValues[0], tearDownThisValues[1]);
  expectTrue(tearDownThisValues[0] instanceof TestSuite);
  expectTrue(tearDownThisValues[1] instanceof TestSuite);
};

GetTestFunctionsTest.prototype.ErrorWithoutTearDown = function() {
  // Register a test that throws an error.
  function TestSuite() {}
  TestSuite.prototype.someName = function() { throw new Error('taco'); };

  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(testFunctions['TestSuite.someName'],
             throwsError(/Error: taco/));
};

GetTestFunctionsTest.prototype.ErrorWithTearDown = function() {
  // A suite with a tearDown method.
  var tearDownThis = null;
  function TestSuite() {}
  TestSuite.prototype.tearDown = function() { tearDownThis = this; };

  // Register a test that throws an error.
  TestSuite.prototype.someName = function() { throw new Error('taco'); };

  // Run the test. The error should make its way through, but tearDown should
  // still be run.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(testFunctions['TestSuite.someName'],
             throwsError(/Error: taco/));
  expectTrue(tearDownThis instanceof TestSuite);
};

GetTestFunctionsTest.prototype.ErrorInConstructor = function() {
  // Register a test whose constructor throws an error.
  function TestSuite() { throw new Error('taco'); }
  TestSuite.prototype.someName = function() {};

  // Run the test. The error should make its way through.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(testFunctions['TestSuite.someName'],
             throwsError(/Error: taco/));
};
<commit_msg>Removed an extra comma.<commit_after>// Copyright 2010 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

function getEnumerableKeys(obj) {
  var result = [];
  for (var name in obj) {
    result.push(name);
  }
  return result;
}

////////////////////////////////////////////////////////////////////////
// registerTestSuite
////////////////////////////////////////////////////////////////////////

function RegisterTestSuiteTest() {
  // Make a copy of the real object; we will replace it later. Then clear it for
  // the duration of this test.
  this.originalTestConstructors_ = gjstest.internal.testSuites;
  gjstest.internal.testSuites = [];
}
registerTestSuite(RegisterTestSuiteTest);

RegisterTestSuiteTest.prototype.tearDown = function() {
  gjstest.internal.testSuites = this.originalTestConstructors_;
};

RegisterTestSuiteTest.prototype.NotAFunction = function() {
  expectThat(function() {
    registerTestSuite({});
  }, throwsError(/TypeError.*registerTestSuite.*function/));
};

RegisterTestSuiteTest.prototype.StoresConstructors = function() {
  function TestSuite1() {}
  function TestSuite2() {}

  registerTestSuite(TestSuite1);
  registerTestSuite(TestSuite2);

  expectThat(gjstest.internal.testSuites,
             elementsAre([TestSuite1, TestSuite2]));
};

RegisterTestSuiteTest.prototype.AlreadyRegistered = function() {
  function TestSuite() {}

  expectThat(function() {
    registerTestSuite(TestSuite);
    registerTestSuite(TestSuite);
  }, throwsError(/already registered.*TestSuite/));
};

////////////////////////////////////////////////////////////////////////
// addTest
////////////////////////////////////////////////////////////////////////

function AddTestTest() {
  // Make a copy of the real object; we will replace it later. Then clear it for
  // the duration of this test.
  this.originalTestConstructors_ = gjstest.internal.testSuites;
  gjstest.internal.testSuites = [];

  // Register a fake test suite for use in our tests.
  this.someSuite_ = function SomeSuite() {};
  registerTestSuite(this.someSuite_);
}
registerTestSuite(AddTestTest);

AddTestTest.prototype.tearDown = function() {
  gjstest.internal.testSuites = this.originalTestConstructors_;
};

AddTestTest.prototype.TestSuiteIsNull = function() {
  expectThat(function() {
    addTest(null, function Foo() {});
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestSuiteIsNotFunction = function() {
  expectThat(function() {
    addTest(17, function Foo() {});
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestSuiteNotRegistered = function() {
  function UnregisteredSuite() {}

  expectThat(function() {
    addTest(UnregisteredSuite, function Foo() {});
  }, throwsError(/not.*registered.*UnregisteredSuite/));
};

AddTestTest.prototype.TestFuncIsNull = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, null);
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestFuncNotFunction = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, 17);
  }, throwsError(/TypeError.*addTest.*function/));
};

AddTestTest.prototype.TestFuncHasNoName = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, function() {});
  }, throwsError(/function.*must have.*name/));
};

AddTestTest.prototype.TestFuncNameEndsInUnderscore = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, function foo_() {});
  }, throwsError(/Error.*Illegal.*name.*foo_/));
};

AddTestTest.prototype.TestFuncNameIstearDown = function() {
  var someSuite = this.someSuite_;

  expectThat(function() {
    addTest(someSuite, function tearDown() {});
  }, throwsError(/Error.*Illegal.*name.*tearDown/));
};

AddTestTest.prototype.TestFuncNameAlreadyPresentFromBareRegistration =
    function() {
  var someSuite = this.someSuite_;
  someSuite.prototype.DoesFoo = function() {};
  someSuite.prototype.DoesBar = function() {};

  // Make sure that the code doesn't use mucked-around-with properties.
  someSuite.prototype.hasOwnProperty = null;
  someSuite.prototype.propertyIsEnumerable = null;

  expectThat(function() {
    addTest(someSuite, function DoesFoo() {});
  }, throwsError(/already.*registered.*DoesFoo/));
};

AddTestTest.prototype.TestFuncNameAlreadyPresentFromAddTest = function() {
  var someSuite = this.someSuite_;
  addTest(someSuite, function DoesFoo() {});
  addTest(someSuite, function DoesBar() {});

  // Make sure that the code doesn't use mucked-around-with properties.
  someSuite.prototype.hasOwnProperty = null;
  someSuite.prototype.propertyIsEnumerable = null;

  expectThat(function() {
    addTest(someSuite, function DoesFoo() {});
  }, throwsError(/already.*registered.*DoesFoo/));
};

AddTestTest.prototype.RegistersTestFunctions = function() {
  var someSuite = this.someSuite_;
  addTest(someSuite, function constructor() {});
  addTest(someSuite, function hasOwnProperty() {});
  addTest(someSuite, function propertyIsEnumerable() {});
  addTest(someSuite, function prototype() {});
  addTest(someSuite, function DoesFoo() {});
  addTest(someSuite, function DoesBar() {});

  expectThat(getEnumerableKeys(someSuite.prototype),
             elementsAre([
                 'constructor',
                 'hasOwnProperty',
                 'propertyIsEnumerable',
                 'prototype',
                 'DoesFoo',
                 'DoesBar'
             ]));
};

////////////////////////////////////////////////////////////////////////
// getTestFunctions
////////////////////////////////////////////////////////////////////////

function GetTestFunctionsTest() {}
registerTestSuite(GetTestFunctionsTest);

GetTestFunctionsTest.prototype.TestNames = function() {
  function TestSuite() {}
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.someOtherName = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result),
             elementsAre([
               'TestSuite.someName',
               'TestSuite.someOtherName'
             ]));
};

GetTestFunctionsTest.prototype.IgnoresTrailingUnderscores = function() {
  function TestSuite() {}
  TestSuite.prototype.harmless_underscores = function() {};
  TestSuite.prototype.ignoredName_ = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result),
             elementsAre(['TestSuite.harmless_underscores']));
};

GetTestFunctionsTest.prototype.IgnoresTearDown = function() {
  function TestSuite() {}
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.tearDown = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result), elementsAre(['TestSuite.someName']));
};

GetTestFunctionsTest.prototype.IgnoresInheritedFunctions = function() {
  function ParentSuite() {}
  ParentSuite.prototype.overridden = function() {};
  ParentSuite.prototype.nonOverridden = function() {};

  function TestSuite() {}
  TestSuite.prototype = new ParentSuite;
  TestSuite.prototype.overridden = function() {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result), elementsAre(['TestSuite.overridden']));
};

GetTestFunctionsTest.prototype.IgnoresNonFunctions = function() {
  function TestSuite() {}
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.ignoredName = {};
  TestSuite.prototype.constructor = {};

  var result = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(getEnumerableKeys(result), elementsAre(['TestSuite.someName']));
};

GetTestFunctionsTest.prototype.Execution = function() {
  // Create two test functions that record 'this'.
  var testAThis = null;
  var testBThis = null;

  function TestSuite() {}
  TestSuite.prototype.someName = function() { testAThis = this; };
  TestSuite.prototype.someOtherName = function() { testBThis = this; };

  // Get test functions and run them in order.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);

  testFunctions['TestSuite.someName']();
  testFunctions['TestSuite.someOtherName']();

  // Each 'this' value should have been a different instance of TestSuite.
  expectNe(testAThis, testBThis);
  expectTrue(testAThis instanceof TestSuite);
  expectTrue(testBThis instanceof TestSuite);
};

GetTestFunctionsTest.prototype.ExecutionWithTearDown = function() {
  // A test suite whose tearDown method records the 'this' values it sees.
  var tearDownThisValues = [];

  function TestSuite() {}
  TestSuite.prototype.tearDown = function() { tearDownThisValues.push(this); };

  // Two test functions.
  TestSuite.prototype.someName = function() {};
  TestSuite.prototype.someOtherName = function() {};

  // Run the tests.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  var foo = testFunctions['TestSuite.someName'];
  testFunctions['TestSuite.someName']();
  testFunctions['TestSuite.someOtherName']();

  // Each 'this' value should have been a different instance of TestSuite.
  expectEq(2, tearDownThisValues.length);
  expectNe(tearDownThisValues[0], tearDownThisValues[1]);
  expectTrue(tearDownThisValues[0] instanceof TestSuite);
  expectTrue(tearDownThisValues[1] instanceof TestSuite);
};

GetTestFunctionsTest.prototype.ErrorWithoutTearDown = function() {
  // Register a test that throws an error.
  function TestSuite() {}
  TestSuite.prototype.someName = function() { throw new Error('taco'); };

  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(testFunctions['TestSuite.someName'],
             throwsError(/Error: taco/));
};

GetTestFunctionsTest.prototype.ErrorWithTearDown = function() {
  // A suite with a tearDown method.
  var tearDownThis = null;
  function TestSuite() {}
  TestSuite.prototype.tearDown = function() { tearDownThis = this; };

  // Register a test that throws an error.
  TestSuite.prototype.someName = function() { throw new Error('taco'); };

  // Run the test. The error should make its way through, but tearDown should
  // still be run.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(testFunctions['TestSuite.someName'],
             throwsError(/Error: taco/));
  expectTrue(tearDownThis instanceof TestSuite);
};

GetTestFunctionsTest.prototype.ErrorInConstructor = function() {
  // Register a test whose constructor throws an error.
  function TestSuite() { throw new Error('taco'); }
  TestSuite.prototype.someName = function() {};

  // Run the test. The error should make its way through.
  var testFunctions = gjstest.internal.getTestFunctions(TestSuite);
  expectThat(testFunctions['TestSuite.someName'],
             throwsError(/Error: taco/));
};
<|endoftext|>


<commit_before>// Core javascript helper functions

// basic browser identification & version
var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion);
var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]);

// Cross-browser event handlers.
function addEvent(obj, evType, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, false);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        return false;
    }
}

function removeEvent(obj, evType, fn) {
    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, false);
        return true;
    } else if (obj.detachEvent) {
        obj.detachEvent("on" + evType, fn);
        return true;
    } else {
        return false;
    }
}

// quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]);
function quickElement() {
    var obj = document.createElement(arguments[0]);
    if (arguments[2] != '' && arguments[2] != null) {
        var textNode = document.createTextNode(arguments[2]);
        obj.appendChild(textNode);
    }
    var len = arguments.length;
    for (var i = 3; i < len; i += 2) {
        obj.setAttribute(arguments[i], arguments[i+1]);
    }
    arguments[1].appendChild(obj);
    return obj;
}

// ----------------------------------------------------------------------------
// Cross-browser xmlhttp object
// from http://jibbering.com/2002/4/httprequest.html
// ----------------------------------------------------------------------------
var xmlhttp;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
@else
    xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
  xmlhttp = new XMLHttpRequest();
}

// ----------------------------------------------------------------------------
// Find-position functions by PPK
// See http://www.quirksmode.org/js/findpos.html
// ----------------------------------------------------------------------------
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft);
            obj = obj.offsetParent;
        }
        // IE offsetParent does not include the top-level
        if (isIE && obj.parentElement){
            curleft += obj.offsetLeft - obj.scrollLeft;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop);
            obj = obj.offsetParent;
        }
        // IE offsetParent does not include the top-level
        if (isIE && obj.parentElement){
            curtop += obj.offsetTop - obj.scrollTop;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

//-----------------------------------------------------------------------------
// Date object extensions
// ----------------------------------------------------------------------------
Date.prototype.getCorrectYear = function() {
    // Date.getYear() is unreliable --
    // see http://www.quirksmode.org/js/introdate.html#year
    var y = this.getYear() % 100;
    return (y < 38) ? y + 2000 : y + 1900;
}

Date.prototype.getTwelveHours = function() {
    return (this.getHours() <= 12) ? this.getHours() : 24 - this.getHours();
}

Date.prototype.getTwoDigitMonth = function() {
    return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1);
}

Date.prototype.getTwoDigitDate = function() {
    return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate();
}

Date.prototype.getTwoDigitTwelveHour = function() {
    return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours();
}

Date.prototype.getTwoDigitHour = function() {
    return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours();
}

Date.prototype.getTwoDigitMinute = function() {
    return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes();
}

Date.prototype.getTwoDigitSecond = function() {
    return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds();
}

Date.prototype.getISODate = function() {
    return this.getCorrectYear() + '-' + this.getTwoDigitMonth() + '-' + this.getTwoDigitDate();
}

Date.prototype.getHourMinute = function() {
    return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute();
}

Date.prototype.getHourMinuteSecond = function() {
    return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond();
}

Date.prototype.strftime = function(format) {
    var fields = {
        c: this.toString(),
        d: this.getTwoDigitDate(),
        H: this.getTwoDigitHour(),
        I: this.getTwoDigitTwelveHour(),
        m: this.getTwoDigitMonth(),
        M: this.getTwoDigitMinute(),
        p: (this.getHours() >= 12) ? 'PM' : 'AM',
        S: this.getTwoDigitSecond(),
        w: '0' + this.getDay(),
        x: this.toLocaleDateString(),
        X: this.toLocaleTimeString(),
        y: ('' + this.getFullYear()).substr(2, 4),
        Y: '' + this.getFullYear(),
        '%' : '%'
    };
    var result = '', i = 0;
    while (i < format.length) {
        if (format[i] === '%') {
            result = result + fields[format[i + 1]];
            ++i;
        }
        else {
            result = result + format[i];
        }
        ++i;
    }
    return result;
}

// ----------------------------------------------------------------------------
// String object extensions
// ----------------------------------------------------------------------------
String.prototype.pad_left = function(pad_length, pad_string) {
    var new_string = this;
    for (var i = 0; new_string.length < pad_length; i++) {
        new_string = pad_string + new_string;
    }
    return new_string;
}

// ----------------------------------------------------------------------------
// Get the computed style for and element
// ----------------------------------------------------------------------------
function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}
<commit_msg>Fixed #12748 - Use charAt instead of array-like access to format string to please IE. Thanks, yedpodtrzitko.<commit_after>// Core javascript helper functions

// basic browser identification & version
var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion);
var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]);

// Cross-browser event handlers.
function addEvent(obj, evType, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, false);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        return false;
    }
}

function removeEvent(obj, evType, fn) {
    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, false);
        return true;
    } else if (obj.detachEvent) {
        obj.detachEvent("on" + evType, fn);
        return true;
    } else {
        return false;
    }
}

// quickElement(tagType, parentReference, textInChildNode, [, attribute, attributeValue ...]);
function quickElement() {
    var obj = document.createElement(arguments[0]);
    if (arguments[2] != '' && arguments[2] != null) {
        var textNode = document.createTextNode(arguments[2]);
        obj.appendChild(textNode);
    }
    var len = arguments.length;
    for (var i = 3; i < len; i += 2) {
        obj.setAttribute(arguments[i], arguments[i+1]);
    }
    arguments[1].appendChild(obj);
    return obj;
}

// ----------------------------------------------------------------------------
// Cross-browser xmlhttp object
// from http://jibbering.com/2002/4/httprequest.html
// ----------------------------------------------------------------------------
var xmlhttp;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
@else
    xmlhttp = false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
  xmlhttp = new XMLHttpRequest();
}

// ----------------------------------------------------------------------------
// Find-position functions by PPK
// See http://www.quirksmode.org/js/findpos.html
// ----------------------------------------------------------------------------
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft);
            obj = obj.offsetParent;
        }
        // IE offsetParent does not include the top-level
        if (isIE && obj.parentElement){
            curleft += obj.offsetLeft - obj.scrollLeft;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop);
            obj = obj.offsetParent;
        }
        // IE offsetParent does not include the top-level
        if (isIE && obj.parentElement){
            curtop += obj.offsetTop - obj.scrollTop;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

//-----------------------------------------------------------------------------
// Date object extensions
// ----------------------------------------------------------------------------
Date.prototype.getCorrectYear = function() {
    // Date.getYear() is unreliable --
    // see http://www.quirksmode.org/js/introdate.html#year
    var y = this.getYear() % 100;
    return (y < 38) ? y + 2000 : y + 1900;
}

Date.prototype.getTwelveHours = function() {
    return (this.getHours() <= 12) ? this.getHours() : 24 - this.getHours();
}

Date.prototype.getTwoDigitMonth = function() {
    return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1);
}

Date.prototype.getTwoDigitDate = function() {
    return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate();
}

Date.prototype.getTwoDigitTwelveHour = function() {
    return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours();
}

Date.prototype.getTwoDigitHour = function() {
    return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours();
}

Date.prototype.getTwoDigitMinute = function() {
    return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes();
}

Date.prototype.getTwoDigitSecond = function() {
    return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds();
}

Date.prototype.getISODate = function() {
    return this.getCorrectYear() + '-' + this.getTwoDigitMonth() + '-' + this.getTwoDigitDate();
}

Date.prototype.getHourMinute = function() {
    return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute();
}

Date.prototype.getHourMinuteSecond = function() {
    return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond();
}

Date.prototype.strftime = function(format) {
    var fields = {
        c: this.toString(),
        d: this.getTwoDigitDate(),
        H: this.getTwoDigitHour(),
        I: this.getTwoDigitTwelveHour(),
        m: this.getTwoDigitMonth(),
        M: this.getTwoDigitMinute(),
        p: (this.getHours() >= 12) ? 'PM' : 'AM',
        S: this.getTwoDigitSecond(),
        w: '0' + this.getDay(),
        x: this.toLocaleDateString(),
        X: this.toLocaleTimeString(),
        y: ('' + this.getFullYear()).substr(2, 4),
        Y: '' + this.getFullYear(),
        '%' : '%'
    };
    var result = '', i = 0;
    while (i < format.length) {
        if (format.charAt(i) === '%') {
            result = result + fields[format.charAt(i + 1)];
            ++i;
        }
        else {
            result = result + format.charAt(i);
        }
        ++i;
    }
    return result;
}

// ----------------------------------------------------------------------------
// String object extensions
// ----------------------------------------------------------------------------
String.prototype.pad_left = function(pad_length, pad_string) {
    var new_string = this;
    for (var i = 0; new_string.length < pad_length; i++) {
        new_string = pad_string + new_string;
    }
    return new_string;
}

// ----------------------------------------------------------------------------
// Get the computed style for and element
// ----------------------------------------------------------------------------
function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}
<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
var request = require('superagent');

// TODO: remove test data
var TEST_DATA = {
  nodes: [
    {
      name: 'dog',
      group: 1,
    },
    {
      name: 'wolf',
      group: 2,
    },
    {
      name: 'fox',
      group: 3,
    },
    {
      name: 'hound',
      group: 4,
    },
  ],
  links: [
    {
      source: 0,
      target: 1,
      score: 50,
    },
    {
      source: 0,
      target: 2,
      score: 100,
    },
    {
      source: 0,
      target: 3,
      score: 150,
    },
  ]
};

var WordInput = React.createClass({
  getInitialState: function() {
    return {
      value: 'Hello!',
    };
  },
  handleChange: function(e) {
    this.setState({value: e.target.value});
  },
  handleSubmit: function(word, e) {
    e.preventDefault();
    this.props.submitWord(word);
  },
  render: function() {
    return (
      <form onSubmit={this.handleSubmit.bind(this, this.state.value)}>
        <input type="text"
          value={this.state.value}
          onChange={this.handleChange} />
        <input type="submit" value="Submit" />
      </form>
    );
  }
});

var WordList = React.createClass({
  getInitialState: function() {
    return {
      associatedWords: this.props.associatedWords,
    }
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      associatedWords: nextProps.associatedWords,
    });
  },
  renderWords: function() {
    return this.state.associatedWords.map(function(word) {
      return (

{word}

      );
    });
  },
  render: function() {
    return (

          {this.renderWords()}

    );
  },
});

var color = d3.scale.category20();

var Node = React.createClass({
  render: function() {
    return (
      <circle
        r={5}
        cx={this.props.x}
        cy={this.props.y}
        style={{
          "fill": color(this.props.group),
          "stroke":"#fff",
          "strokeWidth":"1.5px"
        }}/>
    );
  }
});

var Link = React.createClass({
  render: function() {
    return (
      <line
        x1={this.props.datum.source.x}
        y1={this.props.datum.source.y}
        x2={this.props.datum.target.x}
        y2={this.props.datum.target.y}
        style={{
          "stroke":"#999",
          "strokeOpacity":".6",
          "strokeWidth": "2"
        }}/>
    );
  }
})

var Graph = React.createClass({
  // mixins: [Radium.StyleResolverMixin, Radium.BrowserStateMixin],
  getInitialState: function() {

  var svgWidth = 900;
  var svgHeight = 900;
  var force = d3.layout.force()
    .charge(-120)
    .linkDistance(function(d) {
      return d.score;
    })
    .size([svgWidth, svgHeight]);

    return {
      svgWidth: svgWidth,
      svgHeight: svgHeight,
      force: force,
      nodes: null,
      links: null
    };
  },
  componentDidMount: function() {
    var self = this;
    // refactor entire graph into sub component - force layout shouldn't be
    // manipulating props, though this works
    this.state.force
              .nodes(this.props.graphData.nodes)
              .links(this.props.graphData.links)
              .start();
    this.state.force.on("tick", function (tick, b, c) {
      self.forceUpdate();
    });
  },
  componentWillReceiveProps: function(nextProps) {
    var self = this;
    this.state.force
              .nodes(nextProps.graphData.nodes)
              .links(nextProps.graphData.links)
              .start();
    this.state.force.on("tick", function (tick, b, c) {
      self.forceUpdate();
    });
  },
  drawLinks: function() {
    var links = this.props.graphData.links.map(function (link, index) {
      return (<Link datum={link} key={index} />)
    });
    return (
      <g>
        {links}
      </g>
    );
  },
  drawNodes: function() {
    var nodes = this.props.graphData.nodes.map(function (node, index) {
      return (
        <Node
          key={index}
          x={node.x}
          y={node.y}
          group={node.group}/>
      );
    });
    return nodes;
  },
  render: function() {
    return (

        <svg
          style={{"border": "2px solid black", "margin": "20px"}}
          width={this.state.svgWidth}
          height={this.state.svgHeight}>
          {this.drawLinks()}
          {this.drawNodes()}
        </svg>

    );
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      associatedWords: [],
      graphData: TEST_DATA,
    }
  },
  submitWord: function (word) {
    // post word to server
    console.log('post ' + word + ' to server...');
    var self = this;

    request
      .post('/word')
      .send({word: word})
      .end(function(err, data) {
        if (err || !data.ok){
          console.log('post request for ' + word + ' failed');
        } else {
          console.log('post request successful: ' + JSON.stringify(data.body));
          var associatedWords = data.body.associations_array;
          var associatedScores = data.body.associations_scored;

          // init new graph data object with source word
          var vizData = {nodes:[{name: word, group: 0}], links:[]};

          // create a node and a link to source word for each associated word
          for (var i = 0; i < associatedWords.length; i++) {
            var node = {
              name: associatedWords[i],
              group: i + 1,
            };
            var link = {
              source: 0,
              target: i + 1,
              score: associatedScores[associatedWords[i]] * 300,
            };

            vizData.nodes.push(node);
            vizData.links.push(link);
            // console.log('NODE:', node, 'LINK:', link);
          }

          self.setState({
            associatedWords: associatedWords,
            graphData: vizData,
          });
        }
      });
  },
  render: function() {
    return (

        <WordInput
          submitWord={this.submitWord}/>
        <WordList
          associatedWords={this.state.associatedWords}/>
        <Graph graphData={this.state.graphData}/>

    );
  },
});

ReactDOM.render(<App/>, document.getElementById('app'));
<commit_msg>(feat) Render labels for d3 nodes with react [Closes #13]<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var request = require('superagent');

// TODO: remove test data
var TEST_DATA = {
  nodes: [
    {
      name: 'dog',
      group: 1,
    },
    {
      name: 'wolf',
      group: 2,
    },
    {
      name: 'fox',
      group: 3,
    },
    {
      name: 'hound',
      group: 4,
    },
  ],
  links: [
    {
      source: 0,
      target: 1,
      score: 50,
    },
    {
      source: 0,
      target: 2,
      score: 100,
    },
    {
      source: 0,
      target: 3,
      score: 150,
    },
  ]
};

var WordInput = React.createClass({
  getInitialState: function() {
    return {
      value: 'Hello!',
    };
  },
  handleChange: function(e) {
    this.setState({value: e.target.value});
  },
  handleSubmit: function(word, e) {
    e.preventDefault();
    this.props.submitWord(word);
  },
  render: function() {
    return (
      <form onSubmit={this.handleSubmit.bind(this, this.state.value)}>
        <input type="text"
          value={this.state.value}
          onChange={this.handleChange} />
        <input type="submit" value="Submit" />
      </form>
    );
  }
});

var WordList = React.createClass({
  getInitialState: function() {
    return {
      associatedWords: this.props.associatedWords,
    }
  },
  componentWillReceiveProps: function(nextProps) {
    this.setState({
      associatedWords: nextProps.associatedWords,
    });
  },
  renderWords: function() {
    return this.state.associatedWords.map(function(word) {
      return (

{word}

      );
    });
  },
  render: function() {
    return (

          {this.renderWords()}

    );
  },
});

var color = d3.scale.category20();

var Node = React.createClass({
  render: function() {
    return (
      <circle
        r={5}
        cx={this.props.x}
        cy={this.props.y}
        style={{
          "fill": color(this.props.group),
          "stroke":"#fff",
          "strokeWidth":"1.5px"
        }}/>
    );
  }
});

var Link = React.createClass({
  render: function() {
    return (
      <line
        x1={this.props.datum.source.x}
        y1={this.props.datum.source.y}
        x2={this.props.datum.target.x}
        y2={this.props.datum.target.y}
        style={{
          "stroke":"#999",
          "strokeOpacity":".6",
          "strokeWidth": "2"
        }}/>
    );
  }
});

var NodeLabel = React.createClass({
  render: function() {
    return (
      <text
        x={this.props.x}
        y={this.props.y}>
        {this.props.text}
      </text>
    );
  }
});

var Graph = React.createClass({
  // mixins: [Radium.StyleResolverMixin, Radium.BrowserStateMixin],
  getInitialState: function() {

  var svgWidth = 900;
  var svgHeight = 900;
  var force = d3.layout.force()
    .charge(-120)
    .linkDistance(function(d) {
      return d.score;
    })
    .size([svgWidth, svgHeight]);

    return {
      svgWidth: svgWidth,
      svgHeight: svgHeight,
      force: force,
      nodes: null,
      links: null
    };
  },
  componentDidMount: function() {
    var self = this;
    // refactor entire graph into sub component - force layout shouldn't be
    // manipulating props, though this works
    this.state.force
              .nodes(this.props.graphData.nodes)
              .links(this.props.graphData.links)
              .start();
    this.state.force.on("tick", function (tick, b, c) {
      self.forceUpdate();
    });
  },
  componentWillReceiveProps: function(nextProps) {
    var self = this;
    this.state.force
              .nodes(nextProps.graphData.nodes)
              .links(nextProps.graphData.links)
              .start();
    this.state.force.on("tick", function (tick, b, c) {
      self.forceUpdate();
    });
  },
  drawLinks: function() {
    var links = this.props.graphData.links.map(function (link, index) {
      return (<Link datum={link} key={index} />)
    });
    return (
      <g>
        {links}
      </g>
    );
  },
  drawNodes: function() {
    var nodes = this.props.graphData.nodes.map(function (node, index) {
      return (
        <Node
          key={index}
          x={node.x}
          y={node.y}
          group={node.group}/>
      );
    });
    return nodes;
  },
  drawLabels: function() {
    var labels = this.props.graphData.nodes.map(function(node, index) {
      return (
        <NodeLabel
          key={index}
          x={node.x + 10}
          y={node.y - 10}
          text={node.name}/>
      );
    });
    return labels;
  },
  render: function() {
    return (

        <svg
          style={{"border": "2px solid black", "margin": "20px"}}
          width={this.state.svgWidth}
          height={this.state.svgHeight}>
          {this.drawLinks()}
          {this.drawNodes()}
          {this.drawLabels()}
        </svg>

    );
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      associatedWords: [],
      graphData: TEST_DATA,
    }
  },
  submitWord: function (word) {
    // post word to server
    console.log('post ' + word + ' to server...');
    var self = this;

    request
      .post('/word')
      .send({word: word})
      .end(function(err, data) {
        if (err || !data.ok){
          console.log('post request for ' + word + ' failed');
        } else {
          console.log('post request successful: ' + JSON.stringify(data.body));
          var associatedWords = data.body.associations_array;
          var associatedScores = data.body.associations_scored;

          // init new graph data object with source word
          var vizData = {nodes:[{name: word, group: 0}], links:[]};

          // create a node and a link to source word for each associated word
          for (var i = 0; i < associatedWords.length; i++) {
            var node = {
              name: associatedWords[i],
              group: i + 1,
            };
            var link = {
              source: 0,
              target: i + 1,
              score: associatedScores[associatedWords[i]] * 300,
            };

            vizData.nodes.push(node);
            vizData.links.push(link);
            // console.log('NODE:', node, 'LINK:', link);
          }

          self.setState({
            associatedWords: associatedWords,
            graphData: vizData,
          });
        }
      });
  },
  render: function() {
    return (

        <WordInput
          submitWord={this.submitWord}/>
        <WordList
          associatedWords={this.state.associatedWords}/>
        <Graph graphData={this.state.graphData}/>

    );
  },
});

ReactDOM.render(<App/>, document.getElementById('app'));
<|endoftext|>


<commit_before>module.exports = {
  'bind-address': 'localhost',

  'dataModule': 'data.js',
  'appModule': 'app-server.js',

  'opentok-api-token': '45090862',
  'opentok-session': '1_MX4xMTI3fn4xNDE3MDQ4NzAyNTg2fjhVTmNHb3QxN3ZJVWx0NUx6TzVmMHU4UX5-',
  'opentok-token': 'T1==cGFydG5lcl9pZD0xMTI3JnNpZz1jZTYxYTVmNTA5MWJiOTA2ODE4N2Y2NDBmN2MyYmZlNmYzODQ5MzhlOnNlc3Npb25faWQ9MV9NWDR4TVRJM2ZuNHhOREUzTURRNE56QXlOVGcyZmpoVlRtTkhiM1F4TjNaSlZXeDBOVXg2VHpWbU1IVTRVWDUtJmNyZWF0ZV90aW1lPTE0MTcwNDg3MzAmbm9uY2U9MjcwNzEzJnJvbGU9cHVibGlzaGVy',

  'session-host': '',

  mozilla: {
    'namespace-dir': './servers/mozilla',
    'opentok-session': '2_MX40NTA5MDg2Mn5-MTQxNzExMTc3NDczN345QTg2bUxPRy9Xb0ptdjUveHBQR3F2Q0d-fg',
    'opentok-token-caller': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9Nzg3OGFhNTQ1MWRjNWE2NDcyNmRjODdkYjM2ZmViZWNmNTlkOTMwNTpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTJfTVg0ME5UQTVNRGcyTW41LU1UUXhOekV4TVRjM05EY3pOMzQ1UVRnMmJVeFBSeTlYYjBwdGRqVXZlSEJRUjNGMlEwZC1mZyZjcmVhdGVfdGltZT0xNDE3MTExODgxJm5vbmNlPTAuNDkzOTQyNzY3OTE5MDczJmV4cGlyZV90aW1lPTE0MTk3MDM3MDg=',
    'opentok-token-callee': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9YTM3NGQxYWQ2MDRkMzcwOGRjZGFiMGFmOWRhMzQwMzUwNWZhYmQzMjpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTJfTVg0ME5UQTVNRGcyTW41LU1UUXhOekV4TVRjM05EY3pOMzQ1UVRnMmJVeFBSeTlYYjBwdGRqVXZlSEJRUjNGMlEwZC1mZyZjcmVhdGVfdGltZT0xNDE3MTExOTE0Jm5vbmNlPTAuNzQwNjQ0MTc4NzAzODI5NCZleHBpcmVfdGltZT0xNDE5NzAzNzA4',
  },

  hello: {
    'namespace-dir': './servers/hello',
    'opentok-session': '2_MX40NTA5MDg2Mn5-MTQxNzExMTc3NDczN345QTg2bUxPRy9Xb0ptdjUveHBQR3F2Q0d-fg',
    'opentok-token-caller': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9Nzg3OGFhNTQ1MWRjNWE2NDcyNmRjODdkYjM2ZmViZWNmNTlkOTMwNTpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTJfTVg0ME5UQTVNRGcyTW41LU1UUXhOekV4TVRjM05EY3pOMzQ1UVRnMmJVeFBSeTlYYjBwdGRqVXZlSEJRUjNGMlEwZC1mZyZjcmVhdGVfdGltZT0xNDE3MTExODgxJm5vbmNlPTAuNDkzOTQyNzY3OTE5MDczJmV4cGlyZV90aW1lPTE0MTk3MDM3MDg=',
    'opentok-token-callee': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9YTM3NGQxYWQ2MDRkMzcwOGRjZGFiMGFmOWRhMzQwMzUwNWZhYmQzMjpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTJfTVg0ME5UQTVNRGcyTW41LU1UUXhOekV4TVRjM05EY3pOMzQ1UVRnMmJVeFBSeTlYYjBwdGRqVXZlSEJRUjNGMlEwZC1mZyZjcmVhdGVfdGltZT0xNDE3MTExOTE0Jm5vbmNlPTAuNzQwNjQ0MTc4NzAzODI5NCZleHBpcmVfdGltZT0xNDE5NzAzNzA4',
  },

  owncloud: {
    'namespace-dir': './servers/owncloud',
    'opentok-session': '2_MX40NTA5MDg2Mn5-MTQxNzExMTc3NDczN345QTg2bUxPRy9Xb0ptdjUveHBQR3F2Q0d-fg',
    'opentok-token-caller': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9Nzg3OGFhNTQ1MWRjNWE2NDcyNmRjODdkYjM2ZmViZWNmNTlkOTMwNTpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTJfTVg0ME5UQTVNRGcyTW41LU1UUXhOekV4TVRjM05EY3pOMzQ1UVRnMmJVeFBSeTlYYjBwdGRqVXZlSEJRUjNGMlEwZC1mZyZjcmVhdGVfdGltZT0xNDE3MTExODgxJm5vbmNlPTAuNDkzOTQyNzY3OTE5MDczJmV4cGlyZV90aW1lPTE0MTk3MDM3MDg=',
    'opentok-token-callee': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9YTM3NGQxYWQ2MDRkMzcwOGRjZGFiMGFmOWRhMzQwMzUwNWZhYmQzMjpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTJfTVg0ME5UQTVNRGcyTW41LU1UUXhOekV4TVRjM05EY3pOMzQ1UVRnMmJVeFBSeTlYYjBwdGRqVXZlSEJRUjNGMlEwZC1mZyZjcmVhdGVfdGltZT0xNDE3MTExOTE0Jm5vbmNlPTAuNzQwNjQ0MTc4NzAzODI5NCZleHBpcmVfdGltZT0xNDE5NzAzNzA4',
  }
}<commit_msg>Changed out the opentok secrets. It didn't work.<commit_after>module.exports = {
  'bind-address': 'localhost',

  'dataModule': 'data.js',
  'appModule': 'app-server.js',

  'opentok-api-token': '45090862',
  'opentok-session': '1_MX40NTA5MDg2Mn5-MTQxNzM2MTczMDYzOX5WaG13dW5jV2lDdHd2WWtuNFlseS8wc1l-fg',
  'opentok-token': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9ODJmZTZiNGQwNzQ3NmJiY2U3OTkwNWFlMjE1ZmIyYTNhNzg3NDMzYzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxNzkyJm5vbmNlPTAuNDMzNzc3NzMwMDIyMjM5NiZleHBpcmVfdGltZT0xNDE5OTUzNzIw',

  'session-host': '',

  mozilla: {
    'namespace-dir': './servers/mozilla',
    'opentok-session': '2_MX40NTA5MDg2Mn5-MTQxNzExMTc3NDczN345QTg2bUxPRy9Xb0ptdjUveHBQR3F2Q0d-fg',
    'opentok-token-caller': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9ODJmZTZiNGQwNzQ3NmJiY2U3OTkwNWFlMjE1ZmIyYTNhNzg3NDMzYzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxNzkyJm5vbmNlPTAuNDMzNzc3NzMwMDIyMjM5NiZleHBpcmVfdGltZT0xNDE5OTUzNzIw',
    'opentok-token-callee': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9YjlkNmNhNjQyZTZjMzVmMzFlNjczMGYxMjA5NDhkOGJiOTcyZjE0Nzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxODMxJm5vbmNlPTAuNTU1NzQzNjA2NzMwODEyNSZleHBpcmVfdGltZT0xNDE5OTUzNzIw',
  },

  hello: {
    'namespace-dir': './servers/hello',
    'opentok-session': '2_MX40NTA5MDg2Mn5-MTQxNzExMTc3NDczN345QTg2bUxPRy9Xb0ptdjUveHBQR3F2Q0d-fg',
    'opentok-token-caller': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9ODJmZTZiNGQwNzQ3NmJiY2U3OTkwNWFlMjE1ZmIyYTNhNzg3NDMzYzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxNzkyJm5vbmNlPTAuNDMzNzc3NzMwMDIyMjM5NiZleHBpcmVfdGltZT0xNDE5OTUzNzIw',
    'opentok-token-callee': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9YjlkNmNhNjQyZTZjMzVmMzFlNjczMGYxMjA5NDhkOGJiOTcyZjE0Nzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxODMxJm5vbmNlPTAuNTU1NzQzNjA2NzMwODEyNSZleHBpcmVfdGltZT0xNDE5OTUzNzIw',
  },

  owncloud: {
    'namespace-dir': './servers/owncloud',
    'opentok-session': '2_MX40NTA5MDg2Mn5-MTQxNzExMTc3NDczN345QTg2bUxPRy9Xb0ptdjUveHBQR3F2Q0d-fg',
    'opentok-token-caller': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9ODJmZTZiNGQwNzQ3NmJiY2U3OTkwNWFlMjE1ZmIyYTNhNzg3NDMzYzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxNzkyJm5vbmNlPTAuNDMzNzc3NzMwMDIyMjM5NiZleHBpcmVfdGltZT0xNDE5OTUzNzIw',
    'opentok-token-callee': 'T1==cGFydG5lcl9pZD00NTA5MDg2MiZzaWc9YjlkNmNhNjQyZTZjMzVmMzFlNjczMGYxMjA5NDhkOGJiOTcyZjE0Nzpyb2xlPXB1Ymxpc2hlciZzZXNzaW9uX2lkPTFfTVg0ME5UQTVNRGcyTW41LU1UUXhOek0yTVRjek1EWXpPWDVXYUcxM2RXNWpWMmxEZEhkMldXdHVORmxzZVM4d2MxbC1mZyZjcmVhdGVfdGltZT0xNDE3MzYxODMxJm5vbmNlPTAuNTU1NzQzNjA2NzMwODEyNSZleHBpcmVfdGltZT0xNDE5OTUzNzIw',
  }
}<|endoftext|>


<commit_before>function unique(arr) {
	var result = [],
		hash = {};
	for (var i = 0, elem;
		(elem = arr[i]) != null; i++) {
		if (!hash[elem]) {
			result.push(elem);
			hash[elem] = true;
		}
	}
	return result;
	//http://www.cnblogs.com/sosoft/
}
$(document).ready(function ($) {

	var clear = function () {
		$('#clientname').val('');
		$('#clienttype').val('');
		$('#interface').val('');
		$('#telephone').val('');
		$('#phone').val('');
		$('#group').val('');
		$('#comment').val('');
		$('#place').val('');
		$('#clientname').focus();
		$('#clientname').select();
	}

	clear();

	var val = function (intxt, obj, objname) {
		return intxt.replace(new RegExp('{' + objname + '}', 'ig'), obj.get(objname) || "无记录");
	}
	// console.log(result);
	var dataitem = $('#dataitem').text();
	var appendNewItem = function (data) {
		var di = dataitem;
		di = val(di, data, 'client');
		di = val(di, data, 'asktype');
		di = val(di, data, 'telephone');
		di = val(di, data, 'mobile');
		di = val(di, data, 'handletype');
		di = di.replace(/{memo}/g, data.get('memo'));
		di = di.replace(/{place}/g, data.get('place'));
		di = val(di, data, 'contact');
		di = di.replace(/{time}/g, data.createdAt.toLocaleString());
		$('#hisdata').append(di);

	}

	$('#insert').click(function () {
		var r = new record();

		r.client = $('#clientname').val();
		r.asktype = $('#clienttype').val();
		r.contact = $('#interface').val();
		r.telephone = $('#telephone').val();
		r.mobile = $('#phone').val();
		r.handletype = $('#group').val();
		r.memo = $('#comment').val();
		r.place = $('#place').val();
		insertRecord(r, function (ret) {
			appendNewItem(ret);
			clear();
			// $('#myModal').modal();

		}
		);
	});

	// console.log(dataitem);
	/*
	getRecord(function (result) {
		for (var i = 0; i < result.length; i++) {
			appendNewItem(result[i]);
		}
	});
	*/

	var regions = []
	var pos = [];
	var eachsub = function (item) {
		var prefix = pos.join('')
		// console.log(prefix + item.name);
		if (item.name == '请选择') return;
		if (item.name == '其他') return;
		regions.push(prefix +'/'+ item.name);
		pos.push(item.name);
		if (item.sub)
			item.sub.forEach(eachsub);
		pos.pop();
	}
	city_regions.forEach(eachsub);
	var commentPart = {};
	var typeaheads =
		[
			[regions, 'place'],
			['client.json', 'clientname', {
				source: function (data) {
					var retdata = [];
					// commentPart = {};
					// console.log(data);
					data.forEach(function (itemx) {
						// console.log(itemx);

						var item = [itemx, itemx];
						retdata.push(item[0])
						if (!commentPart[item[0]])
							commentPart[item[0]] = [];

						if (item[1].length) {
							var ci = commentPart[item[0]];
							if (ci.length < 5) {
								ci.push(item[1]);
								ci = unique(ci);
								commentPart[item[0]] = ci;
							}
						}

					});
					var retdata = unique(retdata).concat(regions);
					return retdata;
				},
				highlighter: function (item, val) {
					var retHtml = '

' + val + '
'
					var head = val;
					var comment = commentPart[item];
					// console.log(comment);
					if (!comment) return val;
					// comment = unique(comment);
					// console.log(commentPart);
					comment.forEach(function (it) {
						retHtml += '
' + it + '</d>';
						// head = "";
					});
					retHtml += "
";
					// console.log(retHtml);
					return retHtml;
				}
			}],
			// ['client.json', 'clientname'],

			['type.json', 'clienttype'],
			['interface.json', 'interface'],
			['tel.json', 'telephone'],
			['phone.json', 'phone'],
			['group.json', 'group']

		];

	typeaheads.forEach(function (tah) {
		// console.log(tah);
		var ahead=function(data){
			// data = data.replace('\n', '');
			// data = data.replace('\r', '');
			$('#' + tah[1]).typeahead({
				source: function (query, process) {
					// console.log(query);
					if (tah[2] && tah[2].source)
						return tah[2].source(data)
					return data;
				},
				matcher: function (item) {
					return ~(pinyin.getCamelChars(item).indexOf(this.query.toUpperCase())) ||
						~(item.toUpperCase().indexOf(this.query.toUpperCase()));
				},
				highlighter: function (item) {
					var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
					var val = item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
						return '' + match + ''
					});
					if (tah[2] && tah[2].highlighter)
						return tah[2].highlighter(item, val);
					return val;
				},
				updater: function (item) {
					return item
				}
			});
		}
		if(typeof tah[0] == 'object'){
			ahead(tah[0]);
		}else{
			$.get('data/' + tah[0], '', ahead);
		}
	});

	// $('#his').append('
' + new Date().toLocaleDateString() + '
');
	var valserver = function (intxt, obj, objname) {
		var v = intxt.replace(new RegExp('{' + objname + '}', 'ig'), obj[objname] || "无记录");
		// console.log(v);
		return v;
	}
	var appendServerItem = function (data) {

		var di = dataitem;
		di = valserver(di, data, 'client');
		di = valserver(di, data, 'asktype');
		di = valserver(di, data, 'telephone');
		di = valserver(di, data, 'mobile');
		di = valserver(di, data, 'handletype');
		di = di.replace(/{memo}/g, data.memo);
		di = di.replace(/{place}/g, data.place);
		di = valserver(di, data, 'contact');
		di = di.replace(/{time}/g, data.createdAt.toLocaleString());
		// console.log(di);
		$('#hisdata').append(di);
	}
	server.lastdate(function (date) {
		console.log(date);
		var now = new Date();
		var count = now.getDate() - date.getDate() + 1;
		console.log(count);
		// count = 5;
		for (var i = 0; i < count; i++) {
			var d = new Date();
			d.setDate(now.getDate() - i);
			var datev = d.toLocaleDateString();
			$('#his').append('
' + datev + '
');
		}
		$('[mark]').on('click', function () {
			var c = $('.hisdata').length;
			for (var i = 0; i < c; i++) {
				$('.hisdata')[0].remove();
			}
			// query data

			server.items(parseInt(this.getAttribute('mark')), function (result) {
				// console.log(result);
				for (var i = 0; i < result.items.length; i++) {
					appendServerItem(result.items[i]);
				}
			});
		});
	});
	server.items(0, function (result) {
		// console.log(result);
		for (var i = 0; i < result.items.length; i++) {
			appendServerItem(result.items[i]);
		}
	})
});
// $('#clientname').attr('data-original-title', '{{error}}')
// $('#clientname').attr('data-toggle', 'tooltip')
// $('#clientname').tooltip('show')
<commit_msg>add place<commit_after>function unique(arr) {
	var result = [],
		hash = {};
	for (var i = 0, elem;
		(elem = arr[i]) != null; i++) {
		if (!hash[elem]) {
			result.push(elem);
			hash[elem] = true;
		}
	}
	return result;
	//http://www.cnblogs.com/sosoft/
}
$(document).ready(function ($) {

	var clear = function () {
		$('#clientname').val('');
		$('#clienttype').val('');
		$('#interface').val('');
		$('#telephone').val('');
		$('#phone').val('');
		$('#group').val('');
		$('#comment').val('');
		$('#place').val('');
		$('#clientname').focus();
		$('#clientname').select();
	}

	clear();

	var val = function (intxt, obj, objname) {
		return intxt.replace(new RegExp('{' + objname + '}', 'ig'), obj.get(objname) || "无记录");
	}
	// console.log(result);
	var dataitem = $('#dataitem').text();
	var appendNewItem = function (data) {
		var di = dataitem;
		di = val(di, data, 'client');
		di = val(di, data, 'asktype');
		di = val(di, data, 'telephone');
		di = val(di, data, 'mobile');
		di = val(di, data, 'handletype');
		di = di.replace(/{memo}/g, data.get('memo'));
		di = di.replace(/{place}/g, data.get('place'));
		di = val(di, data, 'contact');
		di = di.replace(/{time}/g, data.createdAt.toLocaleString());
		$('#hisdata').append(di);

	}

	$('#insert').click(function () {
		var r = new record();

		r.client = $('#clientname').val();
		r.asktype = $('#clienttype').val();
		r.contact = $('#interface').val();
		r.telephone = $('#telephone').val();
		r.mobile = $('#phone').val();
		r.handletype = $('#group').val();
		r.memo = $('#comment').val();
		r.place = $('#place').val();
		insertRecord(r, function (ret) {
			appendNewItem(ret);
			clear();
			// $('#myModal').modal();

		}
		);
	});

	// console.log(dataitem);
	/*
	getRecord(function (result) {
		for (var i = 0; i < result.length; i++) {
			appendNewItem(result[i]);
		}
	});
	*/

	var regions = []
	var pos = [];
	var eachsub = function (item) {
		var prefix = pos.join('')
		// console.log(prefix + item.name);
		if (item.name == '请选择') return;
		if (item.name == '其他') return;
		regions.push(prefix +'/'+ item.name);
		pos.push(item.name);
		if (item.sub)
			item.sub.forEach(eachsub);
		pos.pop();
	}
	city_regions.forEach(eachsub);
	var commentPart = {};
	var typeaheads =
		[
			[regions, 'place'],
			['client.json', 'clientname', {
				source: function (data) {
					var retdata = [];
					// commentPart = {};
					// console.log(data);
					data.forEach(function (itemx) {
						// console.log(itemx);

						var item = [itemx, itemx];
						retdata.push(item[0])
						if (!commentPart[item[0]])
							commentPart[item[0]] = [];

						if (item[1].length) {
							var ci = commentPart[item[0]];
							if (ci.length < 5) {
								ci.push(item[1]);
								ci = unique(ci);
								commentPart[item[0]] = ci;
							}
						}

					});
					var retdata = unique(retdata);
					return retdata;
				},
				highlighter: function (item, val) {
					var retHtml = '

' + val + '
'
					var head = val;
					var comment = commentPart[item];
					// console.log(comment);
					if (!comment) return val;
					// comment = unique(comment);
					// console.log(commentPart);
					comment.forEach(function (it) {
						retHtml += '
' + it + '</d>';
						// head = "";
					});
					retHtml += "
";
					// console.log(retHtml);
					return retHtml;
				}
			}],
			// ['client.json', 'clientname'],

			['type.json', 'clienttype'],
			['interface.json', 'interface'],
			['tel.json', 'telephone'],
			['phone.json', 'phone'],
			['group.json', 'group']

		];

	typeaheads.forEach(function (tah) {
		// console.log(tah);
		var ahead=function(data){
			// data = data.replace('\n', '');
			// data = data.replace('\r', '');
			$('#' + tah[1]).typeahead({
				source: function (query, process) {
					// console.log(query);
					if (tah[2] && tah[2].source)
						return tah[2].source(data)
					return data;
				},
				matcher: function (item) {
					return ~(pinyin.getCamelChars(item).indexOf(this.query.toUpperCase())) ||
						~(item.toUpperCase().indexOf(this.query.toUpperCase()));
				},
				highlighter: function (item) {
					var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
					var val = item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
						return '' + match + ''
					});
					if (tah[2] && tah[2].highlighter)
						return tah[2].highlighter(item, val);
					return val;
				},
				updater: function (item) {
					return item
				}
			});
		}
		if(typeof tah[0] == 'object'){
			ahead(tah[0]);
		}else{
			$.get('data/' + tah[0], '', ahead);
		}
	});

	// $('#his').append('
' + new Date().toLocaleDateString() + '
');
	var valserver = function (intxt, obj, objname) {
		var v = intxt.replace(new RegExp('{' + objname + '}', 'ig'), obj[objname] || "无记录");
		// console.log(v);
		return v;
	}
	var appendServerItem = function (data) {

		var di = dataitem;
		di = valserver(di, data, 'client');
		di = valserver(di, data, 'asktype');
		di = valserver(di, data, 'telephone');
		di = valserver(di, data, 'mobile');
		di = valserver(di, data, 'handletype');
		di = di.replace(/{memo}/g, data.memo);
		di = di.replace(/{place}/g, data.place);
		di = valserver(di, data, 'contact');
		di = di.replace(/{time}/g, data.createdAt.toLocaleString());
		// console.log(di);
		$('#hisdata').append(di);
	}
	server.lastdate(function (date) {
		console.log(date);
		var now = new Date();
		var count = now.getDate() - date.getDate() + 1;
		console.log(count);
		// count = 5;
		for (var i = 0; i < count; i++) {
			var d = new Date();
			d.setDate(now.getDate() - i);
			var datev = d.toLocaleDateString();
			$('#his').append('
' + datev + '
');
		}
		$('[mark]').on('click', function () {
			var c = $('.hisdata').length;
			for (var i = 0; i < c; i++) {
				$('.hisdata')[0].remove();
			}
			// query data

			server.items(parseInt(this.getAttribute('mark')), function (result) {
				// console.log(result);
				for (var i = 0; i < result.items.length; i++) {
					appendServerItem(result.items[i]);
				}
			});
		});
	});
	server.items(0, function (result) {
		// console.log(result);
		for (var i = 0; i < result.items.length; i++) {
			appendServerItem(result.items[i]);
		}
	})
});
// $('#clientname').attr('data-original-title', '{{error}}')
// $('#clientname').attr('data-toggle', 'tooltip')
// $('#clientname').tooltip('show')
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ace ' + chalk.red('Drupal Package') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'name',
        message: 'Your project name?',
        default : this.appname // Default to current folder name
      }
    ];

    this.prompt(prompts, function (props) {
      var name = props.name.replace(/[^a-zA-Z0-9 ]/g, "");
      this.projectMachineName = name.toLowerCase().replace(/\s/g, '_');
      this.projectName = name;
      done();
    }.bind(this));
  },

  scaffoldFolders: function(){
    this.mkdir("test");
    this.mkdir("src");
    this.mkdir("src/modules");
    this.mkdir("src/features");
    this.mkdir("src/profiles");
    this.mkdir("src/sites");
    this.mkdir("src/sites/default");
    this.mkdir("src/static");
    this.mkdir("src/scripts");
  },

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
      this.fs.copyTpl(
        this.templatePath('_Gruntconfig.json'),
        this.destinationPath('Gruntconfig.json'),
        { projectName: this.projectMachineName }
      );
      this.fs.copy(
        this.templatePath('_gruntfile.js'),
        this.destinationPath('gruntfile.js')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
      this.fs.copy(
        this.templatePath('_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('_project.make'),
        this.destinationPath('src/project.make')
      );
    },

    profile: function () {
      this.mkdir("src/profiles/" + this.projectMachineName);
      this.fs.copyTpl(
        this.templatePath('profile/info'),
        this.destinationPath('src/profiles/' + this.projectMachineName + '/' + this.projectMachineName + '.info'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/install'),
        this.destinationPath('src/profiles/' + this.projectMachineName + '/' + this.projectMachineName + '.install'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/profile'),
        this.destinationPath('src/profiles/' + this.projectMachineName + '/' + this.projectMachineName + '.profile'),
        { projectName: this.projectMachineName }
      );
    },

    tasks: function () {
      this.bulkDirectory('tasks', 'tasks');
    },

    theme: function() {
      this.bulkDirectory('sass/abstractions', 'src/sass/abstractions');
      this.bulkDirectory('sass/base', 'src/sass/base');
      this.bulkDirectory('sass/components', 'src/sass/components');
      this.bulkDirectory('sass/variables', 'src/sass/variables');

      this.fs.copy(
        this.templatePath('sass/hacks.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.hacks.scss')
      );
      this.fs.copyTpl(
        this.templatePath('sass/no-query.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.no-query.scss'),
        { projectName: this.projectMachineName }
      );
      this.fs.copy(
        this.templatePath('sass/normalize.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.normalize.scss')
      );
      this.fs.copy(
        this.templatePath('sass/styles.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.styles.scss')
      );

      this.bulkDirectory("theme", "src/themes/" + this.projectMachineName);

      this.fs.copyTpl(
        this.templatePath('theme_tpl/_page.preprocess.inc'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/preprocess/page.preprocess.inc'),
        { projectName: this.projectMachineName }
      );

      this.fs.copyTpl(
        this.templatePath('theme_tpl/_page.process.inc'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/process/page.process.inc'),
        { projectName: this.projectMachineName }
      );

      this.fs.copyTpl(
        this.templatePath('theme_tpl/info'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/' + this.projectMachineName + '.info'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_template.php'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/template.php'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_theme-settings.php'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/theme-settings.php'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('_config.rb'),
        this.destinationPath('config.rb'),
        { projectName: this.projectMachineName }
      );
      this.fs.copy(
        this.templatePath('_Gemfile'),
        this.destinationPath('Gemfile')
      );
    }

  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<commit_msg>Update Project name.<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ace ' + chalk.red('Drupal Package') + ' generator!'
    ));

    var prompts = [
      {
        type: 'input',
        name: 'name',
        message: 'Your project name?',
        default : this._.camelize(this._.slugify(this._.humanize(this.appname))) // Default to current folder name
      }
    ];

    this.prompt(prompts, function (props) {
      var name = props.name.replace(/[^a-zA-Z0-9 ]/g, "");
      this.projectMachineName = name.toLowerCase().replace(/\s/g, '_');
      this.projectName = name;
      done();
    }.bind(this));
  },

  scaffoldFolders: function(){
    this.mkdir("test");
    this.mkdir("src");
    this.mkdir("src/modules");
    this.mkdir("src/features");
    this.mkdir("src/profiles");
    this.mkdir("src/sites");
    this.mkdir("src/sites/default");
    this.mkdir("src/static");
    this.mkdir("src/scripts");
  },

  writing: {
    app: function () {
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
      this.fs.copy(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json')
      );
      this.fs.copyTpl(
        this.templatePath('_Gruntconfig.json'),
        this.destinationPath('Gruntconfig.json'),
        { projectName: this.projectMachineName }
      );
      this.fs.copy(
        this.templatePath('_gruntfile.js'),
        this.destinationPath('gruntfile.js')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
      this.fs.copy(
        this.templatePath('_gitignore'),
        this.destinationPath('.gitignore')
      );
      this.fs.copy(
        this.templatePath('_project.make'),
        this.destinationPath('src/project.make')
      );
    },

    profile: function () {
      this.mkdir("src/profiles/" + this.projectMachineName);
      this.fs.copyTpl(
        this.templatePath('profile/info'),
        this.destinationPath('src/profiles/' + this.projectMachineName + '/' + this.projectMachineName + '.info'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/install'),
        this.destinationPath('src/profiles/' + this.projectMachineName + '/' + this.projectMachineName + '.install'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('profile/profile'),
        this.destinationPath('src/profiles/' + this.projectMachineName + '/' + this.projectMachineName + '.profile'),
        { projectName: this.projectMachineName }
      );
    },

    tasks: function () {
      this.bulkDirectory('tasks', 'tasks');
    },

    theme: function() {
      this.bulkDirectory('sass/abstractions', 'src/sass/abstractions');
      this.bulkDirectory('sass/base', 'src/sass/base');
      this.bulkDirectory('sass/components', 'src/sass/components');
      this.bulkDirectory('sass/variables', 'src/sass/variables');

      this.fs.copy(
        this.templatePath('sass/hacks.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.hacks.scss')
      );
      this.fs.copyTpl(
        this.templatePath('sass/no-query.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.no-query.scss'),
        { projectName: this.projectMachineName }
      );
      this.fs.copy(
        this.templatePath('sass/normalize.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.normalize.scss')
      );
      this.fs.copy(
        this.templatePath('sass/styles.scss'),
        this.destinationPath('src/sass/' + this.projectMachineName + '.styles.scss')
      );

      this.bulkDirectory("theme", "src/themes/" + this.projectMachineName);

      this.fs.copyTpl(
        this.templatePath('theme_tpl/_page.preprocess.inc'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/preprocess/page.preprocess.inc'),
        { projectName: this.projectMachineName }
      );

      this.fs.copyTpl(
        this.templatePath('theme_tpl/_page.process.inc'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/process/page.process.inc'),
        { projectName: this.projectMachineName }
      );

      this.fs.copyTpl(
        this.templatePath('theme_tpl/info'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/' + this.projectMachineName + '.info'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_template.php'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/template.php'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('theme_tpl/_theme-settings.php'),
        this.destinationPath('src/themes/' + this.projectMachineName + '/theme-settings.php'),
        { projectName: this.projectMachineName }
      );
      this.fs.copyTpl(
        this.templatePath('_config.rb'),
        this.destinationPath('config.rb'),
        { projectName: this.projectMachineName }
      );
      this.fs.copy(
        this.templatePath('_Gemfile'),
        this.destinationPath('Gemfile')
      );
    }

  },

  install: function () {
    this.installDependencies({
      skipInstall: this.options['skip-install']
    });
  }
});
<|endoftext|>