<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 getKeys(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.*TestSuite/));
};

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(/Error.*addTest.*function.*name/));
};

AddTestTest.prototype.TestFuncNameEndsInUnderscore = function() {
  expectEq('TODO', '');
};

AddTestTest.prototype.TestFuncNameIstearDown = function() {
  expectEq('TODO', '');
};

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

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

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

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

AddTestTest.prototype.RegistersTestFunctions = function() {
  expectEq('TODO', '');
};

////////////////////////////////////////////////////////////////////////
// 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(getKeys(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(getKeys(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(getKeys(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(getKeys(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(getKeys(result), elementsAre(['TestSuite.someName']));
};

GetTestFunctionsTest.prototype.TestConstructorName = function() {
  function TestSuite() {}
  TestSuite.prototype.constructor = function() {};

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

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>AddTestTest.TestFuncNameIstearDown<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 getKeys(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.*TestSuite/));
};

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(/Error.*addTest.*function.*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() {};

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

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

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

AddTestTest.prototype.RegistersTestFunctions = function() {
  expectEq('TODO', '');
};

////////////////////////////////////////////////////////////////////////
// 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(getKeys(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(getKeys(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(getKeys(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(getKeys(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(getKeys(result), elementsAre(['TestSuite.someName']));
};

GetTestFunctionsTest.prototype.TestConstructorName = function() {
  function TestSuite() {}
  TestSuite.prototype.constructor = function() {};

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

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>/**
 * Storybook config.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import cloneDeep from 'lodash/cloneDeep';
import { addDecorator, configure } from '@storybook/react';

/**
 * Internal dependencies
 */
import '../assets/sass/wpdashboard.scss';
import '../assets/sass/adminbar.scss';
import '../assets/sass/admin.scss';
import './assets/sass/wp-admin.scss';
import { bootstrapFetchMocks } from './fetch-mocks';
import { disableFeature } from '../stories/utils/features';
// TODO: Remove when legacy data API is removed.
import { googlesitekit as dashboardData } from '../.storybook/data/wp-admin-admin.php-page=googlesitekit-dashboard-googlesitekit';

bootstrapFetchMocks();

const resetFeatures = () => {
	disableFeature( 'widgets.adminBar' );
	disableFeature( 'widgets.dashboard' );
	disableFeature( 'widgets.pageDashboard' );
	disableFeature( 'widgets.wpDashboard' );
	disableFeature( 'userInput' );
	disableFeature( 'storeErrorNotifications' );
	disableFeature( 'serviceSetupV2' );
};
const resetGlobals = () => {
	global._googlesitekitLegacyData = cloneDeep( dashboardData );
	global._googlesitekitLegacyData.admin.assetsRoot = '';
	global._googlesitekitLegacyData.isStorybook = true;
	global._googlesitekitBaseData = {
		homeURL: 'http://example.com/',
		referenceSiteURL: 'http://example.com/',
		userIDHash: 'storybook',
		adminURL: 'http://example.com/wp-admin/',
		assetsURL: 'http://example.com/wp-content/plugins/google-site-kit/dist/assets/',
		blogPrefix: 'wp_',
		ampMode: false,
		isNetworkMode: false,
		isFirstAdmin: true,
		isOwner: true,
		splashURL: 'http://example.com/wp-admin/admin.php?page=googlesitekit-splash',
		proxySetupURL: 'https://sitekit.withgoogle.com/site-management/setup/?scope=openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsiteverification%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fwebmasters%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.manage.users%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.edit&supports=credentials_retrieval%20short_verification_token%20file_verification&nonce=&site_id=storybooksiteid.apps.sitekit.withgoogle.com',
		proxyPermissionsURL: 'https://sitekit.withgoogle.com/site-management/permissions/?token=storybooktoken&site_id=storybooksiteid.apps.sitekit.withgoogle.com',
		trackingEnabled: false,
		trackingID: 'UA-000000000-1',
	};
	global._googlesitekitEntityData = {
		currentEntityURL: null,
		currentEntityType: null,
		currentEntityTitle: null,
		currentEntityID: null,
	};
};
resetGlobals();

addDecorator( ( story ) => {
	resetGlobals();
	resetFeatures();
	return story();
} );

// Global Decorator.
addDecorator( ( story ) => (

{ story() }

) );

const req = require.context( '../stories', true, /\.stories\.js$/ );

function loadStories() {
	req.keys().forEach( ( filename ) => req( filename ) );
}

configure( loadStories, module );

// TODO Would be nice if this wrote to a file. This logs our Storybook data to the browser console. Currently it gets put in .storybook/storybook-data and used in tests/backstop/scenarios.js.
// eslint-disable-next-line no-console
console.log( '__STORYBOOK_CLIENT_API__.raw()', global.__STORYBOOK_CLIENT_API__.raw() );
<commit_msg>Update storybook default globals with user data.<commit_after>/**
 * Storybook config.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import cloneDeep from 'lodash/cloneDeep';
import { addDecorator, configure } from '@storybook/react';

/**
 * Internal dependencies
 */
import '../assets/sass/wpdashboard.scss';
import '../assets/sass/adminbar.scss';
import '../assets/sass/admin.scss';
import './assets/sass/wp-admin.scss';
import { bootstrapFetchMocks } from './fetch-mocks';
import { disableFeature } from '../stories/utils/features';
// TODO: Remove when legacy data API is removed.
import { googlesitekit as dashboardData } from '../.storybook/data/wp-admin-admin.php-page=googlesitekit-dashboard-googlesitekit';

bootstrapFetchMocks();

const resetFeatures = () => {
	disableFeature( 'widgets.adminBar' );
	disableFeature( 'widgets.dashboard' );
	disableFeature( 'widgets.pageDashboard' );
	disableFeature( 'widgets.wpDashboard' );
	disableFeature( 'userInput' );
	disableFeature( 'storeErrorNotifications' );
	disableFeature( 'serviceSetupV2' );
};
const resetGlobals = () => {
	global._googlesitekitLegacyData = cloneDeep( dashboardData );
	global._googlesitekitLegacyData.admin.assetsRoot = '';
	global._googlesitekitLegacyData.isStorybook = true;
	global._googlesitekitBaseData = {
		homeURL: 'http://example.com/',
		referenceSiteURL: 'http://example.com/',
		userIDHash: 'storybook',
		adminURL: 'http://example.com/wp-admin/',
		assetsURL: 'http://example.com/wp-content/plugins/google-site-kit/dist/assets/',
		blogPrefix: 'wp_',
		ampMode: false,
		isNetworkMode: false,
		isFirstAdmin: true,
		isOwner: true,
		splashURL: 'http://example.com/wp-admin/admin.php?page=googlesitekit-splash',
		proxySetupURL: 'http://example.com/wp-admin/index.php?action=googlesitekit_proxy_setup&nonce=abc123',
		proxyPermissionsURL: 'http://example.com/wp-admin/index.php?action=googlesitekit_proxy_permissions&nonce=abc123',
		trackingEnabled: false,
		trackingID: 'UA-000000000-1',
	};
	global._googlesitekitEntityData = {
		currentEntityURL: null,
		currentEntityType: null,
		currentEntityTitle: null,
		currentEntityID: null,
	};
	global._googlesitekitUserData = {
		user: {
			id: 1,
			name: 'Wapuu WordPress',
			email: 'wapuu.wordpress@gmail.com',
			picture: 'https://wapu.us/wp-content/uploads/2017/11/WapuuFinal-100x138.png',
		},
		connectURL: 'http://example.com/wp-admin/admin.php?page=googlesitekit-splash&googlesitekit_connect=1&nonce=abc123',
		verified: true,
		userInputState: 'completed',
		permissions: {
			googlesitekit_authenticate: true,
			googlesitekit_setup: true,
			googlesitekit_view_posts_insights: true,
			googlesitekit_view_dashboard: true,
			googlesitekit_view_module_details: true,
			googlesitekit_manage_options: true,
			googlesitekit_publish_posts: true,
		},
	};
};
resetGlobals();

addDecorator( ( story ) => {
	resetGlobals();
	resetFeatures();
	return story();
} );

// Global Decorator.
addDecorator( ( story ) => (

{ story() }

) );

const req = require.context( '../stories', true, /\.stories\.js$/ );

function loadStories() {
	req.keys().forEach( ( filename ) => req( filename ) );
}

configure( loadStories, module );

// TODO Would be nice if this wrote to a file. This logs our Storybook data to the browser console. Currently it gets put in .storybook/storybook-data and used in tests/backstop/scenarios.js.
// eslint-disable-next-line no-console
console.log( '__STORYBOOK_CLIENT_API__.raw()', global.__STORYBOOK_CLIENT_API__.raw() );
<|endoftext|>


<commit_before>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

var sys = require("sys");
var posix = require("posix");

var file_name = process.ARGV[2];
var file_contents = null;

var i = 0;
var line = "";
var incident = null;
var tmp = null;

posix.cat(file_name).addCallback(function(contents) {
    file_contents = contents.split("\n");
}).wait();

var output = [];

output.push('<checkstyle version="1.1.0">');

var last_file_name = null;

for (i = 0; i < file_contents.length; i++) {
    line = file_contents[i];

    if (line.length > 0) {
        tmp = /(.*)\((\d+)\)\: (.*)/.exec(line);

        incident = {
            file_name: tmp[1],
            line: tmp[2],
            description: tmp[3],
            severity: "error"
        };

        if (incident.description.match(/^SyntaxError/)) {
            incident.severity = "error";
        }

        if (incident.description.match(/^lint warning/)) {
            incident.severity = "warning";
        }

        if (last_file_name !== incident.file_name) {
            if (last_file_name !== null) {
                output.push('</file>');
            }
            output.push('<file name="' + incident.file_name + '">');
        }

        output.push('<error line="' + incident.line + '" column="0" severity="');
        output.push(incident.severity + '" message="' + incident.description + '"/>');
    }
}

if (last_file_name !== null) {
    output.push('</file>');
}

output.push('</checkstyle>');
sys.puts(output.join(""));
<commit_msg>Fixed issue with closing file tag.<commit_after>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

var sys = require("sys");
var posix = require("posix");

var file_name = process.ARGV[2];
var file_contents = null;

var i = 0;
var line = "";
var incident = null;
var tmp = null;

posix.cat(file_name).addCallback(function(contents) {
    file_contents = contents.split("\n");
}).wait();

var output = [];

output.push('<checkstyle version="1.1.0">');

var last_file_name = null;

for (i = 0; i < file_contents.length; i++) {
    line = file_contents[i];

    if (line.length > 0) {
        tmp = /(.*)\((\d+)\)\: (.*)/.exec(line);

        incident = {
            file_name: tmp[1],
            line: tmp[2],
            description: tmp[3],
            severity: "error"
        };

        if (incident.description.match(/^SyntaxError/)) {
            incident.severity = "error";
        }

        if (incident.description.match(/^lint warning/)) {
            incident.severity = "warning";
        }

        if (last_file_name !== incident.file_name) {
            if (last_file_name !== null) {
                output.push('</file>');
            }
            output.push('<file name="' + incident.file_name + '">');
        }

        output.push('<error line="' + incident.line + '" column="0" severity="');
        output.push(incident.severity + '" message="' + incident.description + '"/>');

        last_file_name = incident.file_name;
    }
}

if (last_file_name !== null) {
    output.push('</file>');
}

output.push('</checkstyle>');
sys.puts(output.join(""));
<|endoftext|>


<commit_before>const express = require('express'),
      fileRouter = express.Router(),
      formidable = require('formidable'),
      path = require('path'),
      fs = require('fs');

// TODO: Discuss use upload/download on uri
// TODO: Get File by _id
// TODO: Delete File by _id
/*
  To delete a single file, we have to pass two parameters: user._id
  and file._id. We have to create a query string that comes with
  both parameters. userId and fileId
*/
const routes = function (User) {
  fileRouter.route('/')
    .post((req, res) => {
      let userFile = {
        userId: null,
        fileName: null,
        fileSize: null,
        fileType: null
      };

      let form = new formidable.IncomingForm();
      form.multiples = true;
      form.uploadDir = path.join(__dirname, '../uploads');

      form.on('file', function(field, file) {
        fs.rename(file.path, path.join(form.uploadDir, file.name));
        userFile.fileName = file.name;
        userFile.fileSize = file.size;
        userFile.fileType = file.type;
      });

      // More info: http://stackoverflow.com/questions/30128701/parse-form-value-with-formidable-to-filename
      form.on('field', function(name, field) {
        if (name === 'userId') {
          userFile.userId = field;
        }
      });

      form.on('error', function(err) {
        console.log(`An error has occured: ${err}`);
      });

      form.on('end', function() {
        User.findById(userFile.userId, function(err, doc) {
          console.log(doc);
          doc.files.push({
            name: userFile.fileName.toString(),
            //type: userFile.fileType.toString(),
            size: userFile.fileSize
          });
          doc.save();
          res.end('success');
        });
      });
      // TODO: Use callback on parse and onParts.
      form.parse(req);
    })
    .get((req, res) => {
      let query = {};

      if(req.query.fileId) {
        query.files._id = req.query.fileId;
      }

      User.find(query, function(err, users) {
        if(err) {
          res.status(500).send(err);
        } else {
          res.json(users);
        }
      });
    });

  return fileRouter;
};

module.exports = routes;
<commit_msg>Added comments.<commit_after>const express = require('express'),
      fileRouter = express.Router(),
      formidable = require('formidable'),
      path = require('path'),
      fs = require('fs');

// TODO: Discuss use upload/download on uri
// TODO: Get File by _id
// TODO: Delete File by _id
/*
  To delete a single file, we have to pass two parameters: user._id
  and file._id. We have to create a query string that comes with
  both parameters. userId and fileId

  On client:
  // Delete a user
  var url = "http://localhost:8080/api/v1/users";
  var xhr = new XMLHttpRequest();
  xhr.open("DELETE", url+'/12', true);
  xhr.onload = function () {
    var users = JSON.parse(xhr.responseText);
    if (xhr.readyState == 4 && xhr.status == "200") {
      console.table(users);
    } else {
      console.error(users);
    }
  }
  xhr.send(null);
*/
const routes = function (User) {
  fileRouter.route('/')
    .post((req, res) => {
      let userFile = {
        userId: null,
        fileName: null,
        fileSize: null,
        fileType: null
      };

      let form = new formidable.IncomingForm();
      form.multiples = true;
      form.uploadDir = path.join(__dirname, '../uploads');

      form.on('file', function(field, file) {
        fs.rename(file.path, path.join(form.uploadDir, file.name));
        userFile.fileName = file.name;
        userFile.fileSize = file.size;
        userFile.fileType = file.type;
      });

      // More info: http://stackoverflow.com/questions/30128701/parse-form-value-with-formidable-to-filename
      form.on('field', function(name, field) {
        if (name === 'userId') {
          userFile.userId = field;
        }
      });

      form.on('error', function(err) {
        console.log(`An error has occured: ${err}`);
      });

      form.on('end', function() {
        User.findById(userFile.userId, function(err, doc) {
          console.log(doc);
          doc.files.push({
            name: userFile.fileName.toString(),
            //type: userFile.fileType.toString(),
            size: userFile.fileSize
          });
          doc.save();
          res.end('success');
        });
      });
      // TODO: Use callback on parse and onParts.
      form.parse(req);
    })
    .get((req, res) => {
      let query = {};

      if(req.query.fileId) {
        query.files._id = req.query.fileId;
      }

      User.find(query, function(err, users) {
        if(err) {
          res.status(500).send(err);
        } else {
          res.json(users);
        }
      });
    });

  return fileRouter;
};

module.exports = routes;
<|endoftext|>


<commit_before>/*
 * This script is bootstrapped by the bookmarklet gaget code.
 */

javascript:(function() {

	var head = document.getElementsByTagName('head')[0];

	var pollRetries = 10;
	var pollWait = 200;

	var versionToUse = "trunk";
	/*var versionToUse = "tags/0.6"; */

	var svnRoot = "http://ufd.googlecode.com/svn/" + versionToUse;
	var googRoot = "http://ajax.googleapis.com/ajax/libs";

	var cssLoaded = false;
	getCSS(svnRoot + "/css/ufd-base.css");
	getCSS(svnRoot + "/css/plain/plain.css");

	var itemCount = 3;
	getScript(googRoot + "/jquery/1.4.2/jquery.min.js");
	getScript(googRoot + "/jqueryui/1.7.2/jquery-ui.min.js");
	getScript(svnRoot + "/src/jquery.ui.ufd.js");

	/* helpers */

	function getCSS(url) {
		var css = document.createElement('LINK');
		css.rel = 'stylesheet';
		css.type = 'text/css';
		css.media = 'screen';
		css.href = url;
		head.appendChild(css);
	}

	function getScript(url) {
		var script = document.createElement('script');
		script.src = url;
		script.type = 'text/javascript';
		script.onload = script.onreadystatechange = load;
		head.appendChild(script);
	}

	function load() {
		if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') && !this.visited) {
			this.visited = true;
			if(--itemCount) return; /* haven't loaded all yet. */

			setTimeout(poll, 1); /* straight away first time */
		}
	}

	function poll() {
		alert("damn you ie");
		if(!cssLoaded) { /* chck if both css has loaded */
			var base = false, plain = false;
			var ss = document.styleSheets;
			for (var i = 0; i < ss.length; i++) {
			    var url = ss[i].href || "";
			    base = base || (url.search("ufd-base.css") > 0);
			    plain = plain || (url.search("plain.css") > 0);
			}
			cssLoaded = (base && plain);
		}

		if (cssLoaded == true &&
			typeof jQuery != 'undefined' &&
			typeof jQuery.ui != 'undefined' &&
			typeof jQuery.ui.ufd != 'undefined' ) {
			/* don't re-wrap existing ufds! */
			jQuery(":not(span.ufd) > select:not([multiple])").ufd({addEmphasis: true});
			jQuery.noConflict(true); 	/* the injected jquery, ui and ufd no longer are available via window.jQuery or window.$ */

		} else if(--pollRetries) {
			setTimeout(poll, pollWait);

		} else {
			alert("Sorry, UFD didn't manage to initalize properly.");
		}
	}
})();

<commit_msg><commit_after>/*
 * This script is bootstrapped by the bookmarklet gaget code.
 */

javascript:(function() {

	var head = document.getElementsByTagName('head')[0];

	var pollRetries = 10;
	var pollWait = 200;

	var versionToUse = "trunk";
	/*var versionToUse = "tags/0.6"; */

	var svnRoot = "http://ufd.googlecode.com/svn/" + versionToUse;
	var googRoot = "http://ajax.googleapis.com/ajax/libs";

	var cssLoaded = false;
	getCSS(svnRoot + "/css/ufd-base.css");
	getCSS(svnRoot + "/css/plain/plain.css");

	var itemCount = 3;
	getScript(googRoot + "/jquery/1.4.2/jquery.min.js");
	getScript(googRoot + "/jqueryui/1.7.2/jquery-ui.min.js");
	getScript(svnRoot + "/src/jquery.ui.ufd.js");

	/* helpers */

	function getCSS(url) {
		var css = document.createElement('LINK');
		css.rel = 'stylesheet';
		css.type = 'text/css';
		css.media = 'screen';
		css.href = url;
		head.appendChild(css);
	}

	function getScript(url) {
		var script = document.createElement('script');
		script.src = url;
		script.type = 'text/javascript';
		script.onload = script.onreadystatechange = load;
		head.appendChild(script);
	}

	function load() {
		if ((!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') && !this.visited) {
			this.visited = true;
			if(--itemCount) return; /* haven't loaded all yet. */

			setTimeout(poll, 1); /* straight away first time */
		}
	}

	function poll() {
		if(!cssLoaded) { /* chck if both css has loaded */
			var base = false, plain = false;
			var ss = document.styleSheets;
			for (var i = 0; i < ss.length; i++) {
			    var url = ss[i].href || "";
			    base = base || (url.search("ufd-base.css") > 0);
			    plain = plain || (url.search("plain.css") > 0);
			}
			cssLoaded = (base && plain);
		}

		if (cssLoaded == true &&
			typeof jQuery != 'undefined' &&
			typeof jQuery.ui != 'undefined' &&
			typeof jQuery.ui.ufd != 'undefined' ) {
			/* don't re-wrap existing ufds! */
			jQuery(":not(span.ufd) > select:not([multiple])").ufd({addEmphasis: true});
			jQuery.noConflict(true); 	/* the injected jquery, ui and ufd no longer are available via window.jQuery or window.$ */

		} else if(--pollRetries) {
			setTimeout(poll, pollWait);

		} else {
			alert("Sorry, UFD didn't manage to initalize properly.");
		}
	}
})();

<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    nowSwitch = thenSwitch;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Ubuntu";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
  ctx.fillText("Lives : " + lives, 365, 32);
  ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
  document.write("Game Over. Kitties only have nine lives.");
};

var main = function () {
  now = Date.now();
  var delta = now - then;

  var nowSwitch = Date.now();
  countDown = nowSwitch - thenSwitch;

  update(delta / 1000);
  if (countDown >= 5000) {
    lives--;
    if (lives ==  0) {
      gameOver();
    }
    thenSwitch = nowSwitch;
    reset();
  }
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  countDown = 0;
  lives = 9;
  kittyCaught = 0;
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    thenSwitch = nowSwitch;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Ubuntu";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
  ctx.fillText("Lives : " + lives, 365, 32);
  ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
  document.write("Game Over. Kitties only have nine lives.");
};

var main = function () {
  now = Date.now();
  var delta = now - then;

  var nowSwitch = Date.now();
  countDown = nowSwitch - thenSwitch;

  update(delta / 1000);
  if (countDown >= 5000) {
    lives--;
    if (lives ==  0) {
      gameOver();
    }
    thenSwitch = nowSwitch;
    reset();
  }
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  countDown = 0;
  lives = 9;
  kittyCaught = 0;
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<|endoftext|>


<commit_before>/** @module deliteful/list/Renderer */
define([
	"dcl/dcl",
	"requirejs-dplugins/jquery!attributes/classes",
	"delite/register",
	"delite/Widget"
], function (dcl, $, register, Widget) {

	/**
	 * The base class for a widget that render an item or its category inside a deliteful/list/List widget.
	 *
	 * This base class provide all the infrastructure that a deliteful/list/List widget
	 * expect from a renderer, including keyboard navigation support.
	 *
	 * Focusability and Keyboard navigation order for a renderer instance is defined using
	 * the navindex attribute on the rendered nodes:
	 * - no navindex attribute value means that the node is not focusable
	 * - a navindex attribute means that the node is focusable. When navigating
	 *  the renderer instance using arrow keys, the traversal order is the following:
	 *  - the nodes with the lowest navindex value comes first
	 *  - if two nodes have the same navindex value, the one that is before the other one in the DOM
	 *  comes first.
	 * @class module:deliteful/list/Renderer
	 * @augments module:delite/Widget
	 */
	return dcl([Widget], /** @lends module:deliteful/list/Renderer# */ {
		/**
		 * The list item to render.
		 * @member {Object}
		 * @default {}
		 */
		item: {}, // must be initialized to an empty object because it is expected by the template

		/**
		 * Contains all the renderer nodes that can be focused, in the same order
		 * that they are to be focused during keyboard navigation with the left and right arrow
		 * keys.
		 * @member {Node[]}
		 * @private
		 */
		_focusableChildren: null,

		/**
		 * The ARIA role of the parent.  Renderer role will be adjusted based on its parent's role.
		 */
		parentRole: "",

		//////////// PROTECTED METHODS ///////////////////////////////////////

		render: dcl.after(function () {
			if (!this.renderNode) {
				throw new Error("render must define a renderNode property on the Renderer."
						+ " Example using attach-point in a template: "
						+ "<template>

</template>");
			}
			this.renderNode.tabIndex = -1;
			$(this.renderNode).addClass("d-list-cell");
			this.updateFocusableChildren();
		}),

		// Interface from List to Renderer to navigate fields

		/**
		 * Retrieves the first focusable child.
		 * @returns {Element}
		 * @protected
		 */
		getFirst: function () {
			if (this._focusableChildren && this._focusableChildren.length) {
				return this._focusableChildren[0];
			} else {
				return null;
			}
		},

		/**
		 * Retrieves the last focusable child.
		 * @returns {Element}
		 * @protected
		 */
		getLast: function () {
			if (this._focusableChildren && this._focusableChildren.length) {
				return this._focusableChildren[this._focusableChildren.length - 1];
			} else {
				return null;
			}
		},

		/**
		 * Retrieves the next focusable child after another child.
		 * @param {Element} child the child from which to retrieve the next focusable child
		 * @returns {Element}
		 * @protected
		 */
		getNext: function (child) {
			return this.getNextFocusableChild(child, 1);
		},

		/**
		 * Retrieves the previous focusable child before another child.
		 * @param {Element} child the child from which to retrieve the previous focusable child
		 * @returns {Element}
		 * @protected
		 */
		getPrev: function (child) {
			return this.getNextFocusableChild(child, -1);
		},

		/**
		 * This method update the list of children of the renderer that can
		 * be focused during keyboard navigation.
		 * If the list of navigable children of the renderer is updated after the
		 * render step has been executed, this method must be
		 * called to take into account the new list.
		 * If the list of navigable children is defined during the render
		 * step, there is no need to call this method.
		 */
		updateFocusableChildren: function () {
			if (this._focusableChildren) {
				for (var i = 0; i < this._focusableChildren.length; i++) {
					delete this._focusableChildren[i].tabIndex;
				}
			}
			// parse the renderNode content to retrieve the ordered list of focusable children
			var nodes = Array.prototype.slice.call(this.renderNode.querySelectorAll("[navindex]"), 0);
			this._focusableChildren = nodes.slice(0).sort(function (a, b) {
				var navindexA = parseInt(a.getAttribute("navindex"), 10);
				var navindexB = parseInt(b.getAttribute("navindex"), 10);
				if (navindexA === navindexB) {
					return nodes.indexOf(a) - nodes.indexOf(b);
				} else {
					return navindexA - navindexB;

				}
			});
			// update the focusable children nodes
			for (i = 0; i < this._focusableChildren.length; i++) {
				var node = this._focusableChildren[i];
				node.tabIndex = -1;
				if (!node.id) {
					node.id = this.id + "-cell-" + i;
				}
			}
		},

		/**
		 * Get the next renderer child that can be focused using arrow keys.
		 * @param {Element} fromChild The child from which the next focusable child is requested
		 * @param {number} dir The direction, from fromChild, of the next child: 1 for the child that
		 * comes after in the focusable order, -1 for the child that comes before.
		 * @returns {Element} The next focusable child if there is one.
		 * @protected
		 */
		getNextFocusableChild: function (fromChild, dir) {
			if (this._focusableChildren && fromChild !== this) {
				// retrieve the position of the from node
				var fromChildIndex = fromChild ? this._focusableChildren.indexOf(fromChild) : -1;
				var nextChildIndex = fromChildIndex + dir;
				if (nextChildIndex >= 0 && nextChildIndex < this._focusableChildren.length) {
					return this._focusableChildren[nextChildIndex]; // Widget
				} else {
					return null;
				}
			}
		}

	});

});
<commit_msg>Remove apparently unneeded code to set ids on navigable children. Fixes #609.<commit_after>/** @module deliteful/list/Renderer */
define([
	"dcl/dcl",
	"requirejs-dplugins/jquery!attributes/classes",
	"delite/register",
	"delite/Widget"
], function (dcl, $, register, Widget) {

	/**
	 * The base class for a widget that render an item or its category inside a deliteful/list/List widget.
	 *
	 * This base class provide all the infrastructure that a deliteful/list/List widget
	 * expect from a renderer, including keyboard navigation support.
	 *
	 * Focusability and Keyboard navigation order for a renderer instance is defined using
	 * the navindex attribute on the rendered nodes:
	 * - no navindex attribute value means that the node is not focusable
	 * - a navindex attribute means that the node is focusable. When navigating
	 *  the renderer instance using arrow keys, the traversal order is the following:
	 *  - the nodes with the lowest navindex value comes first
	 *  - if two nodes have the same navindex value, the one that is before the other one in the DOM
	 *  comes first.
	 * @class module:deliteful/list/Renderer
	 * @augments module:delite/Widget
	 */
	return dcl([Widget], /** @lends module:deliteful/list/Renderer# */ {
		/**
		 * The list item to render.
		 * @member {Object}
		 * @default {}
		 */
		item: {}, // must be initialized to an empty object because it is expected by the template

		/**
		 * Contains all the renderer nodes that can be focused, in the same order
		 * that they are to be focused during keyboard navigation with the left and right arrow
		 * keys.
		 * @member {Node[]}
		 * @private
		 */
		_focusableChildren: null,

		/**
		 * The ARIA role of the parent.  Renderer role will be adjusted based on its parent's role.
		 */
		parentRole: "",

		//////////// PROTECTED METHODS ///////////////////////////////////////

		render: dcl.after(function () {
			if (!this.renderNode) {
				throw new Error("render must define a renderNode property on the Renderer."
						+ " Example using attach-point in a template: "
						+ "<template>

</template>");
			}
			this.renderNode.tabIndex = -1;
			$(this.renderNode).addClass("d-list-cell");
			this.updateFocusableChildren();
		}),

		// Interface from List to Renderer to navigate fields

		/**
		 * Retrieves the first focusable child.
		 * @returns {Element}
		 * @protected
		 */
		getFirst: function () {
			if (this._focusableChildren && this._focusableChildren.length) {
				return this._focusableChildren[0];
			} else {
				return null;
			}
		},

		/**
		 * Retrieves the last focusable child.
		 * @returns {Element}
		 * @protected
		 */
		getLast: function () {
			if (this._focusableChildren && this._focusableChildren.length) {
				return this._focusableChildren[this._focusableChildren.length - 1];
			} else {
				return null;
			}
		},

		/**
		 * Retrieves the next focusable child after another child.
		 * @param {Element} child the child from which to retrieve the next focusable child
		 * @returns {Element}
		 * @protected
		 */
		getNext: function (child) {
			return this.getNextFocusableChild(child, 1);
		},

		/**
		 * Retrieves the previous focusable child before another child.
		 * @param {Element} child the child from which to retrieve the previous focusable child
		 * @returns {Element}
		 * @protected
		 */
		getPrev: function (child) {
			return this.getNextFocusableChild(child, -1);
		},

		/**
		 * This method updates the list of children of the renderer that can
		 * be focused during keyboard navigation.
		 * If the list of navigable children of the renderer is updated after the
		 * render step has been executed, this method must be
		 * called to take into account the new list.
		 * If the list of navigable children is defined during the render
		 * step, there is no need to call this method.
		 */
		updateFocusableChildren: function () {
			if (this._focusableChildren) {
				for (var i = 0; i < this._focusableChildren.length; i++) {
					delete this._focusableChildren[i].tabIndex;
				}
			}
			// parse the renderNode content to retrieve the ordered list of focusable children
			var nodes = Array.prototype.slice.call(this.renderNode.querySelectorAll("[navindex]"), 0);
			this._focusableChildren = nodes.slice(0).sort(function (a, b) {
				var navindexA = parseInt(a.getAttribute("navindex"), 10);
				var navindexB = parseInt(b.getAttribute("navindex"), 10);
				if (navindexA === navindexB) {
					return nodes.indexOf(a) - nodes.indexOf(b);
				} else {
					return navindexA - navindexB;

				}
			});
			// update the focusable children nodes
			for (i = 0; i < this._focusableChildren.length; i++) {
				var node = this._focusableChildren[i];
				node.tabIndex = -1;
			}
		},

		/**
		 * Get the next renderer child that can be focused using arrow keys.
		 * @param {Element} fromChild The child from which the next focusable child is requested
		 * @param {number} dir The direction, from fromChild, of the next child: 1 for the child that
		 * comes after in the focusable order, -1 for the child that comes before.
		 * @returns {Element} The next focusable child if there is one.
		 * @protected
		 */
		getNextFocusableChild: function (fromChild, dir) {
			if (this._focusableChildren && fromChild !== this) {
				// retrieve the position of the from node
				var fromChildIndex = fromChild ? this._focusableChildren.indexOf(fromChild) : -1;
				var nextChildIndex = fromChildIndex + dir;
				if (nextChildIndex >= 0 && nextChildIndex < this._focusableChildren.length) {
					return this._focusableChildren[nextChildIndex]; // Widget
				} else {
					return null;
				}
			}
		}

	});

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
var bencode = require('bencode')
var JSONB = require('json-buffer')
var crypto = require('crypto')

import { DhtStore, dht, opts, sha1 } from '../api/DhtStore'

export default class Tweet extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tweet: ''
    }
  }
  componentDidMount() {

  }

  onTweetChange(e) {
    this.setState({ tweet: e.target.value })
  }

  findNext(head) {
    // it has to be 1 hop, 2 hops, 4 hops and 8 hops away
    var arr = []
    var curr = head
    while (curr.v.next && arr.length <= 8) {
      // curr.next is a buffer of many bytes, only get the first 20
      var next = curr.v.next.slice(0, 20)
      arr.push(next)
      curr = JSONB.parse(localStorage[next.toString('hex')])
    }
    // return max 4 items arrays
    var retArr = []
    if (arr[0])
      retArr.push(arr[0]) // 1 hop away
    if (arr[1])
      retArr.push(arr[1]) // 2 hops
    if (arr[3])
      retArr.push(arr[3]) // 4 hops
    if (arr[7])
      retArr.push(arr[7]) // 8 hops

    var tot = 0
    for (var i=0; i<retArr.length; i++) {
      tot += retArr[i].length
    }

    //console.log(retArr, tot)

    return Buffer.concat(retArr, tot)
  }

  findNextHead(bHash) {
    // it has to be the first 4 items
    var arr = []
    var curr = JSONB.parse(localStorage[bHash.toString('hex')])
    arr.push(bHash) // first hash
    while (curr.v.next && arr.length <= 3) {
      // curr.next is a buffer of many bytes, only get the first 20
      var next = curr.v.next.slice(0, 20)
      arr.push(next)
      curr = JSONB.parse(localStorage[next.toString('hex')])
    }

    var tot = 0
    for (var i=0; i<arr.length; i++) {
      tot += arr[i].length
    }
    console.log(arr, tot)

    return Buffer.concat(arr, tot)
  }

  getCurrentTimestamp() {
    // get millis in UTC
    //var now = new Date()
    //var millis = now.getTime() + (now.getTimezoneOffset() * 60000)
    var dateInMinutes = Math.floor(Math.floor(Date.now() / 1000) / 60)
    var length = Math.ceil((Math.log(dateInMinutes)/Math.log(2))/8);
    var buff = new Buffer(length)
    buff.writeUIntBE(dateInMinutes, 0, length);
    return buff;
  }

  tweet(type) {
    var myHash = DhtStore.myHash()
    var myFeed = localStorage[myHash]
    var timestamp = this.getCurrentTimestamp()

    var iopts = {}
    if (type == 'tweet') {
      iopts.v = {
        t: new Buffer(this.state.tweet)
      }
    } else if (type == 'follow') {
      var followHash = DhtStore.base58toHash(this.state.tweet)
      if (followHash == myHash) {
        return console.error('cant follow yourself!');
      }
      iopts.v = {
        // f is a hash
        f: new Buffer(followHash, 'hex')
      }
    }

    iopts.v.d = timestamp

    // figure out what `next` is and our `seq`
    if (!myFeed) { // we have nothing locally
      opts.seq = 0 // it's the first tweet
      opts.v = {}
    } else {
      var head = JSONB.parse(myFeed)
      if (!head.v.next) { // we updated our profile before posting first tweet
        opts.seq = 0 // it's the first tweet
        opts.v = head.v
      } else {
        // replace opts with our head
        opts.v = head.v

        opts.seq = head.seq + 1
        // it has to be 1 hop, 2 hops, 4 hops and 8 hops away
        iopts.v.next = this.findNext(head)
      }
    }
    console.log('tweet', opts)

    // create immutable tweet
    // and have head point to it
    var bHash = sha1(bencode.encode(iopts.v))
    var hash = bHash.toString('hex')
    localStorage[hash] = JSONB.stringify(iopts)

    // now change my head
    opts.v.d = timestamp
    opts.v.next = this.findNextHead(bHash)
    localStorage[myHash] = JSONB.stringify(opts);

    this.props.onTweetOrFollow()
  }

  tweetDHT() {
    // first get my hash to get the seq number
    var myHash = DhtStore.myHash()
    dht.get(myHash, (err, res) => {
      console.log('got my hash', res)
      if (!res) { // either it's first time posting or head expired from DHT

        // create first immutable tweet with no "next"
        // and have head point to it
        dht.put({ v: { t: this.state.tweet } }, (err, hash) => {
          console.log('put immutabile tweet', hash)

          // write head, and point next to this hash
          // must be a concatenated list of 3 Buffers
          // each being a hash of the next items in the skip list
          opts.v = {
            n: '@lmatteis',
            next: hash
          }
          opts.seq = 0 // it's the first tweet
          dht.put(opts, (err, res) => {
            console.log('put mutable head', res)

          })

        })
      } else { // we have already a head
        // still put the tweet, but now use the head's next value
        dht.put({ v: { t: this.state.tweet, next: res.v.next } }, (err, hash) => {
          console.log('put immutabile tweet', hash)

          // write head, and point next to this hash
          // must be a concatenated list of 3 Buffers
          // each being a hash of the next items in the skip list
          opts.v = {
            n: '@lmatteis',
            next: hash
          }
          opts.seq = res.seq + 1
          dht.put(opts, (err, res) => {
            console.log('put mutable head', res)

          })

        })

      }

      // create the immutable tweet
    })

  }

  render() {
    return (

        <input type="text" onChange={::this.onTweetChange} maxLength="140" />
        <button onClick={this.tweet.bind(this, 'tweet')}>Tweet</button>
        <button onClick={this.tweet.bind(this, 'follow')}>Follow</button>

    );
  }
}
<commit_msg>When tweeting it immediately publishes new item<commit_after>import React, { Component } from 'react';
var bencode = require('bencode')
var JSONB = require('json-buffer')
var crypto = require('crypto')

import { DhtStore, dht, opts, sha1 } from '../api/DhtStore'

export default class Tweet extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tweet: ''
    }
  }
  componentDidMount() {

  }

  onTweetChange(e) {
    this.setState({ tweet: e.target.value })
  }

  findNext(head) {
    // it has to be 1 hop, 2 hops, 4 hops and 8 hops away
    var arr = []
    var curr = head
    while (curr.v.next && arr.length <= 8) {
      // curr.next is a buffer of many bytes, only get the first 20
      var next = curr.v.next.slice(0, 20)
      arr.push(next)
      curr = JSONB.parse(localStorage[next.toString('hex')])
    }
    // return max 4 items arrays
    var retArr = []
    if (arr[0])
      retArr.push(arr[0]) // 1 hop away
    if (arr[1])
      retArr.push(arr[1]) // 2 hops
    if (arr[3])
      retArr.push(arr[3]) // 4 hops
    if (arr[7])
      retArr.push(arr[7]) // 8 hops

    var tot = 0
    for (var i=0; i<retArr.length; i++) {
      tot += retArr[i].length
    }

    //console.log(retArr, tot)

    return Buffer.concat(retArr, tot)
  }

  findNextHead(bHash) {
    // it has to be the first 4 items
    var arr = []
    var curr = JSONB.parse(localStorage[bHash.toString('hex')])
    arr.push(bHash) // first hash
    while (curr.v.next && arr.length <= 3) {
      // curr.next is a buffer of many bytes, only get the first 20
      var next = curr.v.next.slice(0, 20)
      arr.push(next)
      curr = JSONB.parse(localStorage[next.toString('hex')])
    }

    var tot = 0
    for (var i=0; i<arr.length; i++) {
      tot += arr[i].length
    }
    console.log(arr, tot)

    return Buffer.concat(arr, tot)
  }

  getCurrentTimestamp() {
    // get millis in UTC
    //var now = new Date()
    //var millis = now.getTime() + (now.getTimezoneOffset() * 60000)
    var dateInMinutes = Math.floor(Math.floor(Date.now() / 1000) / 60)
    var length = Math.ceil((Math.log(dateInMinutes)/Math.log(2))/8);
    var buff = new Buffer(length)
    buff.writeUIntBE(dateInMinutes, 0, length);
    return buff;
  }

  tweet(type) {
    var myHash = DhtStore.myHash()
    var myFeed = localStorage[myHash]
    var timestamp = this.getCurrentTimestamp()

    var iopts = {}
    if (type == 'tweet') {
      iopts.v = {
        t: new Buffer(this.state.tweet)
      }
    } else if (type == 'follow') {
      var followHash = DhtStore.base58toHash(this.state.tweet)
      if (followHash == myHash) {
        return console.error('cant follow yourself!');
      }
      iopts.v = {
        // f is a hash
        f: new Buffer(followHash, 'hex')
      }
    }

    iopts.v.d = timestamp

    // figure out what `next` is and our `seq`
    if (!myFeed) { // we have nothing locally
      opts.seq = 0 // it's the first tweet
      opts.v = {}
    } else {
      var head = JSONB.parse(myFeed)
      if (!head.v.next) { // we updated our profile before posting first tweet
        opts.seq = 0 // it's the first tweet
        opts.v = head.v
      } else {
        // replace opts with our head
        opts.v = head.v

        opts.seq = head.seq + 1
        // it has to be 1 hop, 2 hops, 4 hops and 8 hops away
        iopts.v.next = this.findNext(head)
      }
    }
    console.log('tweet', opts)

    // create immutable tweet
    // and have head point to it
    var bHash = sha1(bencode.encode(iopts.v))
    var hash = bHash.toString('hex')
    localStorage[hash] = JSONB.stringify(iopts)

    // now change my head
    opts.v.d = timestamp
    opts.v.next = this.findNextHead(bHash)
    localStorage[myHash] = JSONB.stringify(opts);

    // now publish to DHT both head and immutable tweet
    dht.put(opts, (err, res) => { // published head
      if (err) return console.error(res);
      dht.put(iopts, (err, res) => { // published tweet
        if (err) return console.error(res);
      })
    })
    this.props.onTweetOrFollow()

  }

  tweetDHT() {
    // first get my hash to get the seq number
    var myHash = DhtStore.myHash()
    dht.get(myHash, (err, res) => {
      console.log('got my hash', res)
      if (!res) { // either it's first time posting or head expired from DHT

        // create first immutable tweet with no "next"
        // and have head point to it
        dht.put({ v: { t: this.state.tweet } }, (err, hash) => {
          console.log('put immutabile tweet', hash)

          // write head, and point next to this hash
          // must be a concatenated list of 3 Buffers
          // each being a hash of the next items in the skip list
          opts.v = {
            n: '@lmatteis',
            next: hash
          }
          opts.seq = 0 // it's the first tweet
          dht.put(opts, (err, res) => {
            console.log('put mutable head', res)

          })

        })
      } else { // we have already a head
        // still put the tweet, but now use the head's next value
        dht.put({ v: { t: this.state.tweet, next: res.v.next } }, (err, hash) => {
          console.log('put immutabile tweet', hash)

          // write head, and point next to this hash
          // must be a concatenated list of 3 Buffers
          // each being a hash of the next items in the skip list
          opts.v = {
            n: '@lmatteis',
            next: hash
          }
          opts.seq = res.seq + 1
          dht.put(opts, (err, res) => {
            console.log('put mutable head', res)

          })

        })

      }

      // create the immutable tweet
    })

  }

  render() {
    return (

        <input type="text" onChange={::this.onTweetChange} maxLength="140" />
        <button onClick={this.tweet.bind(this, 'tweet')}>Tweet</button>
        <button onClick={this.tweet.bind(this, 'follow')}>Follow</button>

    );
  }
}
<|endoftext|>


<commit_before>var vom = require('vom');
module.exports = {
  tryDecode: tryDecode,
};

function tryDecode(hex) {
  var reader = new vom.ByteArrayMessageReader(vom.Util.hex2Bytes(hex));
  var decoder = new vom.Decoder(reader);
  return decoder.decode();
}
<commit_msg>TBR Recursively unwrap all decoded values<commit_after>var vom = require('vom');
module.exports = {
  tryDecode: tryDecode,
};

function tryDecode(hex) {
  var reader = new vom.ByteArrayMessageReader(vom.Util.hex2Bytes(hex));
  var decoder = new vom.Decoder(reader);
  var decoded = decoder.decode();
  // TODO(bprosnitz) Remove unwrapping.
  var unwrapped = vom.TypeUtil.recursiveUnwrap(decoded);
  return unwrapped;
}
<|endoftext|>


<commit_before>angular.module('86cup.profile', [])
  .controller('ProfileController', function ($scope, $window, $location, $window, Racers) {
    $("body").scrollTop(0);
    if(!$window.localStorage.racepro){
      $location.path('/')
    }
    var user = $window.localStorage.username.toLowerCase();
    $scope.username = {name: user};
    $scope.modPts = 0;
    $scope.modList = {};
    $scope.class;
    $scope.avatar = "../assets/car-placeholder.png";

    //fetch a user's information from db
    $scope.getModList = function() {
      //fetch user modlist data
      console.log('username === ', $scope.username);
      Racers.getModList($scope.username)
        .then(function(resp){
          console.log('resp === ', resp.data)
          // if(resp.data.avatar !== "../assets/car-placeholder.png") {
          //   $scope.avatar = resp.data.avatar;
          // }
          $scope.avatar = resp.data.avatar;
          $scope.modList.mods = resp.data.modList;
          $scope.modPts = resp.data.modPts;
        })
        .then(function() {
          _.forEach($scope.modList.mods.drivetrain, function(mod, i) {
            if(mod.active === true) {
              setTimeout(function() {
                $('.'+i).prop('checked', 'checked')
              }, 10)
            }
          })
        })
        .then(function() {
          $scope.determineClass();
        })
    };

    if($window.localStorage.username !== 'admin') {
      console.log("not admin so go get mod list")
      $scope.getModList()
    }else{
      $scope.avatar = "../assets/zeus.jpg";
      alert("You are currently in admin mode. Only regular users can set a profile.");
    }

    //user clicks on mod and toggles it active/not active
    $scope.toggleActiveDrivetrain = function(i, e) {
      if($scope.modList.mods.drivetrain[i].active === false) {
        $scope.modPts += $scope.modList.mods.drivetrain[i].value;
        console.log($scope.modPts);
      }else{
        $scope.modPts -= $scope.modList.mods.drivetrain[i].value;
      }
      $scope.modList.mods.drivetrain[i].active = !$scope.modList.mods.drivetrain[i].active;
      $scope.determineClass();
    };

    $scope.toggleActiveWheels = function(i) {
      if($scope.modList.mods.wheels[i].active === false) {
        $scope.modPts += $scope.modList.mods.wheels[i].value;
        console.log($scope.modPts);
      }else{
        $scope.modPts -= $scope.modList.mods.wheels[i].value;
      }
      $scope.modList.mods.wheels[i].active = !$scope.modList.mods.wheels[i].active;
      $scope.determineClass();
    };

    $scope.toggleActiveAero = function(i) {
      if($scope.modList.mods.aero[i].active === false) {
        $scope.modPts += $scope.modList.mods.aero[i].value;
      }else{
        $scope.modPts -= $scope.modList.mods.aero[i].value;
      }
      $scope.modList.mods.aero[i].active = !$scope.modList.mods.aero[i].active;
      $scope.determineClass();
    };

    $scope.toggleActiveSuspension = function(i) {
      if($scope.modList.mods.suspension[i].active === false) {
        $scope.modPts += $scope.modList.mods.suspension[i].value;
      }else{
        $scope.modPts -= $scope.modList.mods.suspension[i].value;
      }
      $scope.modList.mods.suspension[i].active = !$scope.modList.mods.suspension[i].active;
      $scope.determineClass();
    };

    //A function to determine a user's class
    $scope.determineClass = function() {
      if($scope.modPts <= 0.5) {
        $scope.class = 'stock';
      }
      if($scope.modPts > 0.5 && $scope.modPts <= 4.0) {
        $scope.class = 'street';
      }
      if($scope.modPts > 4.0 && $scope.modPts <= 7.0) {
        $scope.class = 'limited';
      }
      if($scope.modPts > 7.0) {
        $scope.class = 'unlimited';
      }
      console.log($scope.class)
    };

    //upload a photo to be used as an avatar
    $scope.add = function() {
      var file = document.getElementById('file').files[0];
      // var preview = document.getElementById('pic');
      var fileType = file.type;
      var reader = new FileReader();

      reader.onloadend = function(e) {
        var image = new Image();
        image.src = reader.result;
        // preview.src = e.target.result;
        image.onload = function() {
          var maxWidth = 100,
              maxHeight = 75,
              imageWidth = image.width,
              imageHeight = image.height;

          if (imageWidth > imageHeight) {
            if (imageWidth > maxWidth) {
              imageHeight *= maxWidth / imageWidth;
              imageWidth = maxWidth;
            }
          }
          else {
            if (imageHeight > maxHeight) {
              imageWidth *= maxHeight / imageHeight;
              imageHeight = maxHeight;
            }
          }

          var canvas = document.createElement('canvas');
          canvas.width = imageWidth;
          canvas.height = imageHeight;

          var ctx = canvas.getContext("2d");
          ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

          // The resized file ready for upload
          var finalFile = canvas.toDataURL(fileType);
          console.log("finalFile === ", finalFile);
          $scope.avatar = finalFile;
        }
      }
    //   var dataurl = null;
    //   var preview = document.getElementById('pic');
    //   var f = document.getElementById('file').files[0];
    //   var img = document.createElement("img");

    //   var r = new FileReader();

    //   r.onloadend = function(e){
    //     preview.src = e.target.result;
    //     img.src = e.target.result;
    //       console.log("img", img)
    //       var canvas = document.createElement("canvas");
    //       var ctx = canvas.getContext("2d");
    //       ctx.drawImage(img, 0, 0);

    //       var MAX_WIDTH = 400;
    //       var MAX_HEIGHT = 300;
    //       var width = img.width;
    //       var height = img.height;

    //       if (width > height) {
    //         if (width > MAX_WIDTH) {
    //           height *= MAX_WIDTH / width;
    //           width = MAX_WIDTH;
    //         }
    //       } else {
    //         if (height > MAX_HEIGHT) {
    //           width *= MAX_HEIGHT / height;
    //           height = MAX_HEIGHT;
    //         }
    //       }
    //       canvas.width = width;
    //       canvas.height = height;
    //       var ctx = canvas.getContext("2d");
    //       ctx.drawImage(img, 0, 0, width, height);

    //       dataurl = canvas.toDataURL("image/jpeg");
    //     $scope.avatar = dataurl;
    //     console.log("dataurl === ", dataurl)
    //   };
      reader.readAsDataURL( file );
    }; //adds image data to $scope.avatar

    $scope.updateMods = function() {
      Racers.updateModListAndPts({racer: $scope.username, avatar: "https://www.petfinder.com/wp-content/uploads/2012/11/140272627-grooming-needs-senior-cat-632x475.jpg", modList: $scope.modList, modPts: $scope.modPts}).then(function(resp){
        console.log("modlist and pts updated!");
      })
      $("body").scrollTop(0);

    };

    // var $window = $(window),
    //    $stickyEl = $('.userinfo'),
    //    elTop = $stickyEl.offset().top;

    // $window.scroll(function() {
    //     $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    // });
    $('#profile').click(function() {
      $('.vertical_nav').removeClass('vertical_nav__opened');
    })
//////////////////////////////////////////////////////////////////////////////////////////

  })

 <commit_msg>fix auth 12<commit_after>angular.module('86cup.profile', [])
  .controller('ProfileController', function ($scope, $window, $location, $window, Racers) {
    $("body").scrollTop(0);
    if(!$window.localStorage.racepro){
      $location.path('/')
    }
    var user = $window.localStorage.username.toLowerCase();
    $scope.username = {name: user};
    $scope.modPts = 0;
    $scope.modList = {};
    $scope.class;
    $scope.avatar = "../assets/car-placeholder.png";

    //fetch a user's information from db
    $scope.getModList = function() {
      //fetch user modlist data
      console.log('username === ', $scope.username);
      Racers.getModList($scope.username)
        .then(function(resp){
          console.log('resp === ', resp.data)
          if(resp.data.avatar !== "../assets/car-placeholder.png") {
            $scope.avatar = resp.data.avatar;
          }
          $scope.modList.mods = resp.data.modList;
          $scope.modPts = resp.data.modPts;
        })
        .then(function() {
          _.forEach($scope.modList.mods.drivetrain, function(mod, i) {
            if(mod.active === true) {
              setTimeout(function() {
                $('.'+i).prop('checked', 'checked')
              }, 10)
            }
          })
        })
        .then(function() {
          $scope.determineClass();
        })
    };

    if($window.localStorage.username !== 'admin') {
      console.log("not admin so go get mod list")
      $scope.getModList()
    }else{
      $scope.avatar = "../assets/zeus.jpg";
      alert("You are currently in admin mode. Only regular users can set a profile.");
    }

    //user clicks on mod and toggles it active/not active
    $scope.toggleActiveDrivetrain = function(i, e) {
      if($scope.modList.mods.drivetrain[i].active === false) {
        $scope.modPts += $scope.modList.mods.drivetrain[i].value;
        console.log($scope.modPts);
      }else{
        $scope.modPts -= $scope.modList.mods.drivetrain[i].value;
      }
      $scope.modList.mods.drivetrain[i].active = !$scope.modList.mods.drivetrain[i].active;
      $scope.determineClass();
    };

    $scope.toggleActiveWheels = function(i) {
      if($scope.modList.mods.wheels[i].active === false) {
        $scope.modPts += $scope.modList.mods.wheels[i].value;
        console.log($scope.modPts);
      }else{
        $scope.modPts -= $scope.modList.mods.wheels[i].value;
      }
      $scope.modList.mods.wheels[i].active = !$scope.modList.mods.wheels[i].active;
      $scope.determineClass();
    };

    $scope.toggleActiveAero = function(i) {
      if($scope.modList.mods.aero[i].active === false) {
        $scope.modPts += $scope.modList.mods.aero[i].value;
      }else{
        $scope.modPts -= $scope.modList.mods.aero[i].value;
      }
      $scope.modList.mods.aero[i].active = !$scope.modList.mods.aero[i].active;
      $scope.determineClass();
    };

    $scope.toggleActiveSuspension = function(i) {
      if($scope.modList.mods.suspension[i].active === false) {
        $scope.modPts += $scope.modList.mods.suspension[i].value;
      }else{
        $scope.modPts -= $scope.modList.mods.suspension[i].value;
      }
      $scope.modList.mods.suspension[i].active = !$scope.modList.mods.suspension[i].active;
      $scope.determineClass();
    };

    //A function to determine a user's class
    $scope.determineClass = function() {
      if($scope.modPts <= 0.5) {
        $scope.class = 'stock';
      }
      if($scope.modPts > 0.5 && $scope.modPts <= 4.0) {
        $scope.class = 'street';
      }
      if($scope.modPts > 4.0 && $scope.modPts <= 7.0) {
        $scope.class = 'limited';
      }
      if($scope.modPts > 7.0) {
        $scope.class = 'unlimited';
      }
      console.log($scope.class)
    };

    $scope.add = function() {
        var preview = document.getElementById('pic');
        var f = document.getElementById('file').files[0];
        var r = new FileReader();
        r.onloadend = function(e){
          preview.src = e.target.result;
          $scope.avatar = e.target.result;
        };
        r.readAsDataURL( f );
      };

    //upload a photo to be used as an avatar
    // $scope.add = function() {
    //   var file = document.getElementById('file').files[0];
    //   // var preview = document.getElementById('pic');
    //   var fileType = file.type;
    //   var reader = new FileReader();

    //   reader.onloadend = function(e) {
    //     var image = new Image();
    //     image.src = reader.result;
    //     // preview.src = e.target.result;
    //     image.onload = function() {
    //       var maxWidth = 100,
    //           maxHeight = 75,
    //           imageWidth = image.width,
    //           imageHeight = image.height;

    //       if (imageWidth > imageHeight) {
    //         if (imageWidth > maxWidth) {
    //           imageHeight *= maxWidth / imageWidth;
    //           imageWidth = maxWidth;
    //         }
    //       }
    //       else {
    //         if (imageHeight > maxHeight) {
    //           imageWidth *= maxHeight / imageHeight;
    //           imageHeight = maxHeight;
    //         }
    //       }

    //       var canvas = document.createElement('canvas');
    //       canvas.width = imageWidth;
    //       canvas.height = imageHeight;

    //       var ctx = canvas.getContext("2d");
    //       ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

    //       // The resized file ready for upload
    //       var finalFile = canvas.toDataURL(fileType);
    //       console.log("finalFile === ", finalFile);
    //       $scope.avatar = finalFile;
    //     }
    //   }
    //   reader.readAsDataURL( file );
    // }; //adds image data to $scope.avatar

    $scope.updateMods = function() {
      Racers.updateModListAndPts({racer: $scope.username, avatar: $scope.avatar, modList: $scope.modList, modPts: $scope.modPts}).then(function(resp){
        console.log("modlist and pts updated!");
      })
      $("body").scrollTop(0);

    };

    // var $window = $(window),
    //    $stickyEl = $('.userinfo'),
    //    elTop = $stickyEl.offset().top;

    // $window.scroll(function() {
    //     $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    // });
    $('#profile').click(function() {
      $('.vertical_nav').removeClass('vertical_nav__opened');
    })
//////////////////////////////////////////////////////////////////////////////////////////

  })

 <|endoftext|>