text:
'use strict';

//     Underscore.js 1.5.2
//     http://underscorejs.org
//     (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};

// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype;

// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
    toString = ObjProto.toString,
    hasOwnProperty = ObjProto.hasOwnProperty;

// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
    nativeForEach      = ArrayProto.forEach,
    nativeKeys         = Object.keys,
    nativeIsArray      = Array.isArray;

// Create a safe reference to the Underscore object for use below.
var _ = function() {};

// Collection Functions
// --------------------

// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
  if (obj == null) return;
  if (nativeForEach && obj.forEach === nativeForEach) {
    obj.forEach(iterator, context);
  } else if (obj.length === +obj.length) {
    for (var i = 0, length = obj.length; i < length; i++) {
      if (iterator.call(context, obj[i], i, obj) === breaker) return;
    }
  } else {
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
    }
  }
};

// Object Functions
// ----------------

// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
      if (obj !== Object(obj)) throw new TypeError('Invalid object');
      var keys = [];
      for (var key in obj) if (_.has(obj, key)) keys.push(key);
      return keys;
    };

// Fill in a given object with default properties.
_.defaults = function(obj) {
  each(slice.call(arguments, 1), function(source) {
    if (source) {
      for (var prop in source) {
        if (obj[prop] === void 0) obj[prop] = source[prop];
      }
    }
  });
  return obj;
};

// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
  return toString.call(obj) === '[object Array]';
};

// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, path) {
  if (!_.isArray(path)) {
    return obj != null && hasOwnProperty.call(obj, path);
  }
  var length = path.length;
  for (var i = 0; i < length; i++) {
    var key = path[i];
    if (obj == null || !hasOwnProperty.call(obj, key)) {
      return false;
    }
    obj = obj[key];
  }
  return !!length;
};

// List of HTML entities for escaping.
var entityMap = {
  escape: {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": '''
  }
};

// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
  escape:   new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g')
};

// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape'], function(method) {
  _[method] = function(string) {
    if (string == null) return '';
    return ('' + string).replace(entityRegexes[method], function(match) {
      return entityMap[method][match];
    });
  };
});

// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
  evaluate    : /<%([\s\S]+?)%>/g,
  interpolate : /<%=([\s\S]+?)%>/g,
  escape      : /<%-([\s\S]+?)%>/g
};

// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;

// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
  "'":      "'",
  '\\':     '\\',
  '\r':     'r',
  '\n':     'n',
  '\t':     't',
  '\u2028': 'u2028',
  '\u2029': 'u2029'
};

var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;

// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
  var render;
  settings = _.defaults({}, settings, _.templateSettings);

  // Combine delimiters into one regular expression via alternation.
  var matcher = new RegExp([
        (settings.escape || noMatch).source,
        (settings.interpolate || noMatch).source,
        (settings.evaluate || noMatch).source
      ].join('|') + '|$', 'g');

  // Compile the template source, escaping string literals appropriately.
  var index = 0;
  var source = "__p+='";
  text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
    source += text.slice(index, offset)
        .replace(escaper, function(match) { return '\\' + escapes[match]; });

    if (escape) {
      source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
    }
    if (interpolate) {
      source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
    }
    if (evaluate) {
      source += "';\n" + evaluate + "\n__p+='";
    }
    index = offset + match.length;
    return match;
  });
  source += "';\n";

  // If a variable is not specified, place data values in local scope.
  if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

  source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + "return __p;\n";

  try {
    render = new Function(settings.variable || 'obj', '_', source);
  } catch (e) {
    e.source = source;
    throw e;
  }

  if (data) return render(data, _);
  var template = function(data) {
    return render.call(this, data, _);
  };

  // Provide the compiled function source as a convenience for precompilation.
  template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';

  return template;
};

module.exports = _;


text:
import Ember from 'ember-metal/core';
import isEnabled from 'ember-metal/features';
import run from 'ember-metal/run_loop';
import EmberObject from 'ember-runtime/system/object';
import RSVP from 'ember-runtime/ext/rsvp';
import EmberView from 'ember-views/views/view';
import jQuery from 'ember-views/system/jquery';

import Test from 'ember-testing/test';
import 'ember-testing/helpers';  // ensure that the helpers are loaded
import 'ember-testing/initializers'; // ensure the initializer is setup
import setupForTesting from 'ember-testing/setup_for_testing';
import EmberRouter from 'ember-routing/system/router';
import EmberRoute from 'ember-routing/system/route';
import EmberApplication from 'ember-application/system/application';
import compile from 'ember-template-compiler/system/compile';

var App;
var originalAdapter = Test.adapter;

function cleanup() {
  // Teardown setupForTesting

  Test.adapter = originalAdapter;
  run(function() {
    jQuery(document).off('ajaxSend');
    jQuery(document).off('ajaxComplete');
  });
  Test.pendingAjaxRequests = null;
  Test.waiters = null;

  // Other cleanup

  if (App) {
    run(App, App.destroy);
    App.removeTestHelpers();
    App = null;
  }

  Ember.TEMPLATES = {};
}

function assertHelpers(application, helperContainer, expected) {
  if (!helperContainer) { helperContainer = window; }
  if (expected === undefined) { expected = true; }

  function checkHelperPresent(helper, expected) {
    var presentInHelperContainer = !!helperContainer[helper];
    var presentInTestHelpers = !!application.testHelpers[helper];

    ok(presentInHelperContainer === expected, 'Expected \'' + helper + '\' to be present in the helper container (defaults to window).');
    ok(presentInTestHelpers === expected, 'Expected \'' + helper + '\' to be present in App.testHelpers.');
  }

  checkHelperPresent('visit', expected);
  checkHelperPresent('click', expected);
  checkHelperPresent('keyEvent', expected);
  checkHelperPresent('fillIn', expected);
  checkHelperPresent('wait', expected);
  checkHelperPresent('triggerEvent', expected);

  if (isEnabled('ember-testing-checkbox-helpers')) {
    checkHelperPresent('check', expected);
    checkHelperPresent('uncheck', expected);
  }
}

function assertNoHelpers(application, helperContainer) {
  assertHelpers(application, helperContainer, false);
}

function currentRouteName(app) {
  return app.testHelpers.currentRouteName();
}

function currentPath(app) {
  return app.testHelpers.currentPath();
}

function currentURL(app) {
  return app.testHelpers.currentURL();
}

function setupApp() {
  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();

    App.injectTestHelpers();
  });
}

QUnit.module('ember-testing: Helper setup', {
  setup() { cleanup(); },
  teardown() { cleanup(); }
});

QUnit.test('Ember.Application#injectTestHelpers/#removeTestHelpers', function() {
  App = run(EmberApplication, EmberApplication.create);
  assertNoHelpers(App);

  App.injectTestHelpers();
  assertHelpers(App);

  App.removeTestHelpers();
  assertNoHelpers(App);
});

QUnit.test('Ember.Application#setupForTesting', function() {
  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  equal(App.__container__.lookup('router:main').location, 'none');
});

QUnit.test('Ember.Application.setupForTesting sets the application to `testing`.', function() {
  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  equal(App.testing, true, 'Application instance is set to testing.');
});

QUnit.test('Ember.Application.setupForTesting leaves the system in a deferred state.', function() {
  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  equal(App._readinessDeferrals, 1, 'App is in deferred state after setupForTesting.');
});

QUnit.test('App.reset() after Application.setupForTesting leaves the system in a deferred state.', function() {
  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  equal(App._readinessDeferrals, 1, 'App is in deferred state after setupForTesting.');

  App.reset();
  equal(App._readinessDeferrals, 1, 'App is in deferred state after setupForTesting.');
});

QUnit.test('Ember.Application#setupForTesting attaches ajax listeners', function() {
  var documentEvents;

  documentEvents = jQuery._data(document, 'events');

  if (!documentEvents) {
    documentEvents = {};
  }

  ok(documentEvents['ajaxSend'] === undefined, 'there are no ajaxSend listers setup prior to calling injectTestHelpers');
  ok(documentEvents['ajaxComplete'] === undefined, 'there are no ajaxComplete listers setup prior to calling injectTestHelpers');

  run(function() {
    setupForTesting();
  });

  documentEvents = jQuery._data(document, 'events');

  equal(documentEvents['ajaxSend'].length, 1, 'calling injectTestHelpers registers an ajaxSend handler');
  equal(documentEvents['ajaxComplete'].length, 1, 'calling injectTestHelpers registers an ajaxComplete handler');
});

QUnit.test('Ember.Application#setupForTesting attaches ajax listeners only once', function() {
  var documentEvents;

  documentEvents = jQuery._data(document, 'events');

  if (!documentEvents) {
    documentEvents = {};
  }

  ok(documentEvents['ajaxSend'] === undefined, 'there are no ajaxSend listeners setup prior to calling injectTestHelpers');
  ok(documentEvents['ajaxComplete'] === undefined, 'there are no ajaxComplete listeners setup prior to calling injectTestHelpers');

  run(function() {
    setupForTesting();
  });
  run(function() {
    setupForTesting();
  });

  documentEvents = jQuery._data(document, 'events');

  equal(documentEvents['ajaxSend'].length, 1, 'calling injectTestHelpers registers an ajaxSend handler');
  equal(documentEvents['ajaxComplete'].length, 1, 'calling injectTestHelpers registers an ajaxComplete handler');
});

QUnit.test('Ember.Application#injectTestHelpers calls callbacks registered with onInjectHelpers', function() {
  var injected = 0;

  Test.onInjectHelpers(function() {
    injected++;
  });

  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  equal(injected, 0, 'onInjectHelpers are not called before injectTestHelpers');

  App.injectTestHelpers();

  equal(injected, 1, 'onInjectHelpers are called after injectTestHelpers');
});

QUnit.test('Ember.Application#injectTestHelpers adds helpers to provided object.', function() {
  var helpers = {};

  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  App.injectTestHelpers(helpers);
  assertHelpers(App, helpers);

  App.removeTestHelpers();
  assertNoHelpers(App, helpers);
});

QUnit.test('Ember.Application#removeTestHelpers resets the helperContainer\'s original values', function() {
  var helpers = { visit: 'snazzleflabber' };

  run(function() {
    App = EmberApplication.create();
    App.setupForTesting();
  });

  App.injectTestHelpers(helpers);

  ok(helpers.visit !== 'snazzleflabber', 'helper added to container');
  App.removeTestHelpers();

  ok(helpers.visit === 'snazzleflabber', 'original value added back to container');
});

QUnit.module('ember-testing: Helper methods', {
  setup() {
    setupApp();
  },
  teardown() {
    cleanup();
  }
});

QUnit.test('`wait` respects registerWaiters', function() {
  expect(3);

  var counter = 0;
  function waiter() {
    return ++counter > 2;
  }

  var other = 0;
  function otherWaiter() {
    return ++other > 2;
  }

  run(App, App.advanceReadiness);
  Test.registerWaiter(waiter);
  Test.registerWaiter(otherWaiter);

  App.testHelpers.wait().then(function() {
    equal(waiter(), true, 'should not resolve until our waiter is ready');
    Test.unregisterWaiter(waiter);
    equal(Test.waiters.length, 1, 'should not leave the waiter registered');
    other = 0;
    return App.testHelpers.wait();
  }).then(function() {
    equal(otherWaiter(), true, 'other waiter is still registered');
  });
});

QUnit.test('`visit` advances readiness.', function() {
  expect(2);

  equal(App._readinessDeferrals, 1, 'App is in deferred state after setupForTesting.');

  App.testHelpers.visit('/').then(function() {
    equal(App._readinessDeferrals, 0, 'App\'s readiness was advanced by visit.');
  });
});

QUnit.test('`wait` helper can be passed a resolution value', function() {
  expect(4);

  var promise, wait;

  promise = new RSVP.Promise(function(resolve) {
    run(null, resolve, 'promise');
  });

  run(App, App.advanceReadiness);

  wait = App.testHelpers.wait;

  wait('text').then(function(val) {
    equal(val, 'text', 'can resolve to a string');
    return wait(1);
  }).then(function(val) {
    equal(val, 1, 'can resolve to an integer');
    return wait({ age: 10 });
  }).then(function(val) {
    deepEqual(val, { age: 10 }, 'can resolve to an object');
    return wait(promise);
  }).then(function(val) {
    equal(val, 'promise', 'can resolve to a promise resolution value');
  });
});

QUnit.test('`click` triggers appropriate events in order', function() {
  expect(5);

  var click, wait, events;

  App.IndexView = EmberView.extend({
    classNames: 'index-view',

    didInsertElement() {
      this.$().on('mousedown focusin mouseup click', function(e) {
        events.push(e.type);
      });
    },

    Checkbox: Ember.Checkbox.extend({
      click() {
        events.push('click:' + this.get('checked'));
      },

      change() {
        events.push('change:' + this.get('checked'));
      }
    })
  });

  Ember.TEMPLATES.index = compile('{{input type="text"}} {{view view.Checkbox}} {{textarea}}

');

  run(App, App.advanceReadiness);

  click = App.testHelpers.click;
  wait  = App.testHelpers.wait;

  wait().then(function() {
    events = [];
    return click('.index-view');
  }).then(function() {
    deepEqual(events,
      ['mousedown', 'mouseup', 'click'],
      'fires events in order');
  }).then(function() {
    events = [];
    return click('.index-view input[type=text]');
  }).then(function() {
    deepEqual(events,
      ['mousedown', 'focusin', 'mouseup', 'click'],
      'fires focus events on inputs');
  }).then(function() {
    events = [];
    return click('.index-view textarea');
  }).then(function() {
    deepEqual(events,
      ['mousedown', 'focusin', 'mouseup', 'click'],
      'fires focus events on textareas');
  }).then(function() {
    events = [];
    return click('.index-view div');
  }).then(function() {
    deepEqual(events,
      ['mousedown', 'focusin', 'mouseup', 'click'],
      'fires focus events on contenteditable');
  }).then(function() {
    // In IE (< 8), the change event only fires when the value changes before element focused.
    jQuery('.index-view input[type=checkbox]').focus();
    events = [];
    return click('.index-view input[type=checkbox]');
  }).then(function() {
    // i.e. mousedown, mouseup, change:true, click, click:true
    // Firefox differs so we can't assert the exact ordering here.
    // See https://bugzilla.mozilla.org/show_bug.cgi?id=843554.
    equal(events.length, 5, 'fires click and change on checkboxes');
  });
});

QUnit.test('`wait` waits for outstanding timers', function() {
  expect(1);

  var wait_done = false;

  run(App, App.advanceReadiness);

  run.later(this, function() {
    wait_done = true;
  }, 500);

  App.testHelpers.wait().then(function() {
    equal(wait_done, true, 'should wait for the timer to be fired.');
  });
});

QUnit.test('`wait` respects registerWaiters with optional context', function() {
  expect(3);

  var obj = {
    counter: 0,
    ready() {
      return ++this.counter > 2;
    }
  };

  var other = 0;
  function otherWaiter() {
    return ++other > 2;
  }

  run(App, App.advanceReadiness);
  Test.registerWaiter(obj, obj.ready);
  Test.registerWaiter(otherWaiter);

  App.testHelpers.wait().then(function() {
    equal(obj.ready(), true, 'should not resolve until our waiter is ready');
    Test.unregisterWaiter(obj, obj.ready);
    equal(Test.waiters.length, 1, 'should not leave the waiter registered');
    return App.testHelpers.wait();
  }).then(function() {
    equal(otherWaiter(), true, 'other waiter should still be registered');
  });
});

QUnit.test('`wait` does not error if routing has not begun', function() {
  expect(1);

  App.testHelpers.wait().then(function() {
    ok(true, 'should not error without `visit`');
  });
});

QUnit.test('`triggerEvent accepts an optional options hash without context', function() {
  expect(3);

  var triggerEvent, wait, event;

  App.IndexView = EmberView.extend({
    template: compile('{{input type="text" id="scope" class="input"}}'),

    didInsertElement() {
      this.$('.input').on('blur change', function(e) {
        event = e;
      });
    }
  });

  run(App, App.advanceReadiness);

  triggerEvent = App.testHelpers.triggerEvent;
  wait         = App.testHelpers.wait;

  wait().then(function() {
    return triggerEvent('.input', 'blur', { keyCode: 13 });
  }).then(function() {
    equal(event.keyCode, 13, 'options were passed');
    equal(event.type, 'blur', 'correct event was triggered');
    equal(event.target.getAttribute('id'), 'scope', 'triggered on the correct element');
  });
});

QUnit.test('`triggerEvent can limit searching for a selector to a scope', function() {
  expect(2);

  var triggerEvent, wait, event;

  App.IndexView = EmberView.extend({
    template: compile('{{input type="text" id="outside-scope" class="input"}}
{{input type="text" id="inside-scope" class="input"}}
'),

    didInsertElement() {
      this.$('.input').on('blur change', function(e) {
        event = e;
      });
    }
  });

  run(App, App.advanceReadiness);

  triggerEvent = App.testHelpers.triggerEvent;
  wait         = App.testHelpers.wait;

  wait().then(function() {
    return triggerEvent('.input', '#limited', 'blur');
  }).then(function() {
    equal(event.type, 'blur', 'correct event was triggered');
    equal(event.target.getAttribute('id'), 'inside-scope', 'triggered on the correct element');
  });
});

QUnit.test('`triggerEvent` can be used to trigger arbitrary events', function() {
  expect(2);

  var triggerEvent, wait, event;

  App.IndexView = EmberView.extend({
    template: compile('{{input type="text" id="foo"}}'),

    didInsertElement() {
      this.$('#foo').on('blur change', function(e) {
        event = e;
      });
    }
  });

  run(App, App.advanceReadiness);

  triggerEvent = App.testHelpers.triggerEvent;
  wait         = App.testHelpers.wait;

  wait().then(function() {
    return triggerEvent('#foo', 'blur');
  }).then(function() {
    equal(event.type, 'blur', 'correct event was triggered');
    equal(event.target.getAttribute('id'), 'foo', 'triggered on the correct element');
  });
});

QUnit.test('`fillIn` takes context into consideration', function() {
  expect(2);
  var fillIn, find, visit, andThen;

  App.IndexView = EmberView.extend({
    template: compile('
{{input type="text" id="first" class="current"}}
{{input type="text" id="second" class="current"}}')
  });

  run(App, App.advanceReadiness);

  fillIn = App.testHelpers.fillIn;
  find = App.testHelpers.find;
  visit = App.testHelpers.visit;
  andThen = App.testHelpers.andThen;

  visit('/');
  fillIn('.current', '#parent', 'current value');
  andThen(function() {
    equal(find('#first').val(), 'current value');
    equal(find('#second').val(), '');
  });
});

QUnit.test('`fillIn` focuses on the element', function() {
  expect(2);
  var fillIn, find, visit, andThen;

  App.ApplicationRoute = Ember.Route.extend({
    actions: {
      wasFocused() {
        ok(true, 'focusIn event was triggered');
      }
    }
  });

  App.IndexView = EmberView.extend({
    template: compile('
{{input type="text" id="first" focus-in="wasFocused"}}
')
  });

  run(App, App.advanceReadiness);

  fillIn = App.testHelpers.fillIn;
  find = App.testHelpers.find;
  visit = App.testHelpers.visit;
  andThen = App.testHelpers.andThen;

  visit('/');
  fillIn('#first', 'current value');
  andThen(function() {
    equal(find('#first').val(), 'current value');
  });
});

QUnit.test('`fillIn` fires `input` and `change` events in the proper order', function() {
  expect(1);

  var fillIn, visit, andThen;
  var events = [];
  App.IndexController = Ember.Controller.extend({
    actions: {
      oninputHandler(e) {
        events.push(e.type);
      },
      onchangeHanlders(e) {
        events.push(e.type);
      }
    }
  });

  App.IndexView = EmberView.extend({
    template: compile('<input type="text" id="first" oninput={{action "oninputHandler"}} onchange={{action "onchangeHanlders"}}>')
  });

  run(App, App.advanceReadiness);

  fillIn = App.testHelpers.fillIn;
  visit = App.testHelpers.visit;
  andThen = App.testHelpers.andThen;

  visit('/');
  fillIn('#first', 'current value');
  andThen(function() {
    deepEqual(events, ['input', 'change'], '`input` and `change` events are fired in the proper order');
  });
});

if (isEnabled('ember-testing-checkbox-helpers')) {
  QUnit.test('`check` ensures checkboxes are `checked` state for checkboxes', function() {
    expect(2);
    var check, find, visit, andThen;

    App.IndexView = EmberView.extend({
      template: compile('<input type="checkbox" id="unchecked"><input type="checkbox" id="checked" checked>')
    });

    run(App, App.advanceReadiness);

    check = App.testHelpers.check;
    find = App.testHelpers.find;
    visit = App.testHelpers.visit;
    andThen = App.testHelpers.andThen;

    visit('/');
    check('#unchecked');
    check('#checked');
    andThen(function() {
      equal(find('#unchecked').is(':checked'), true, 'can check an unchecked checkbox');
      equal(find('#checked').is(':checked'), true, 'can check a checked checkbox');
    });
  });

  QUnit.test('`uncheck` ensures checkboxes are not `checked`', function() {
    expect(2);
    var uncheck, find, visit, andThen;

    App.IndexView = EmberView.extend({
      template: compile('<input type="checkbox" id="unchecked"><input type="checkbox" id="checked" checked>')
    });

    run(App, App.advanceReadiness);

    uncheck = App.testHelpers.uncheck;
    find = App.testHelpers.find;
    visit = App.testHelpers.visit;
    andThen = App.testHelpers.andThen;

    visit('/');
    uncheck('#unchecked');
    uncheck('#checked');
    andThen(function() {
      equal(find('#unchecked').is(':checked'), false, 'can uncheck an unchecked checkbox');
      equal(find('#checked').is(':checked'), false, 'can uncheck a checked checkbox');
    });
  });

  QUnit.test('`check` asserts the selected inputs are checkboxes', function() {
    var check, visit;

    App.IndexView = EmberView.extend({
      template: compile('<input type="text" id="text">')
    });

    run(App, App.advanceReadiness);

    check = App.testHelpers.check;
    visit = App.testHelpers.visit;

    visit('/').then(function() {
      check('#text').catch(function(error) {
        ok(/must be a checkbox/.test(error.message));
      });
    });
  });

  QUnit.test('`uncheck` asserts the selected inputs are checkboxes', function() {
    var visit, uncheck;

    App.IndexView = EmberView.extend({
      template: compile('<input type="text" id="text">')
    });

    run(App, App.advanceReadiness);

    visit = App.testHelpers.visit;
    uncheck = App.testHelpers.uncheck;

    visit('/').then(function() {
      uncheck('#text').catch(function(error) {
        ok(/must be a checkbox/.test(error.message));
      });
    });
  });
}

QUnit.test('`triggerEvent accepts an optional options hash and context', function() {
  expect(3);

  var triggerEvent, wait, event;

  App.IndexView = EmberView.extend({
    template: compile('{{input type="text" id="outside-scope" class="input"}}
{{input type="text" id="inside-scope" class="input"}}
'),

    didInsertElement() {
      this.$('.input').on('blur change', function(e) {
        event = e;
      });
    }
  });

  run(App, App.advanceReadiness);

  triggerEvent = App.testHelpers.triggerEvent;
  wait         = App.testHelpers.wait;

  wait().then(function() {
    return triggerEvent('.input', '#limited', 'blur', { keyCode: 13 });
  }).then(function() {
    equal(event.keyCode, 13, 'options were passed');
    equal(event.type, 'blur', 'correct event was triggered');
    equal(event.target.getAttribute('id'), 'inside-scope', 'triggered on the correct element');
  });
});

QUnit.module('ember-testing debugging helpers', {
  setup() {
    setupApp();

    run(function() {
      App.Router = EmberRouter.extend({
        location: 'none'
      });
    });

    run(App, 'advanceReadiness');
  },

  teardown() {
    cleanup();
  }
});

QUnit.test('pauseTest pauses', function() {
  expect(1);
  function fakeAdapterAsyncStart() {
    ok(true, 'Async start should be called');
  }

  Test.adapter.asyncStart = fakeAdapterAsyncStart;

  App.testHelpers.pauseTest();
});

QUnit.module('ember-testing routing helpers', {
  setup() {
    run(function() {
      App = EmberApplication.create();
      App.setupForTesting();

      App.injectTestHelpers();

      App.Router = EmberRouter.extend({
        location: 'none'
      });

      App.Router.map(function() {
        this.route('posts', { resetNamespace: true }, function() {
          this.route('new');
        });
      });
    });

    run(App, 'advanceReadiness');
  },

  teardown() {
    cleanup();
  }
});

QUnit.test('currentRouteName for \'/\'', function() {
  expect(3);

  App.testHelpers.visit('/').then(function() {
    equal(App.testHelpers.currentRouteName(), 'index', 'should equal \'index\'.');
    equal(App.testHelpers.currentPath(), 'index', 'should equal \'index\'.');
    equal(App.testHelpers.currentURL(), '/', 'should equal \'/\'.');
  });
});

QUnit.test('currentRouteName for \'/posts\'', function() {
  expect(3);

  App.testHelpers.visit('/posts').then(function() {
    equal(App.testHelpers.currentRouteName(), 'posts.index', 'should equal \'posts.index\'.');
    equal(App.testHelpers.currentPath(), 'posts.index', 'should equal \'posts.index\'.');
    equal(App.testHelpers.currentURL(), '/posts', 'should equal \'/posts\'.');
  });
});

QUnit.test('currentRouteName for \'/posts/new\'', function() {
  expect(3);

  App.testHelpers.visit('/posts/new').then(function() {
    equal(App.testHelpers.currentRouteName(), 'posts.new', 'should equal \'posts.new\'.');
    equal(App.testHelpers.currentPath(), 'posts.new', 'should equal \'posts.new\'.');
    equal(App.testHelpers.currentURL(), '/posts/new', 'should equal \'/posts/new\'.');
  });
});

QUnit.module('ember-testing pendingAjaxRequests', {
  setup() {
    setupApp();
  },

  teardown() {
    cleanup();
  }
});

QUnit.test('pendingAjaxRequests is maintained for ajaxSend and ajaxComplete events', function() {
  equal(Test.pendingAjaxRequests, 0);
  var xhr = { some: 'xhr' };
  jQuery(document).trigger('ajaxSend', xhr);
  equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests was incremented');
  jQuery(document).trigger('ajaxComplete', xhr);
  equal(Test.pendingAjaxRequests, 0, 'Ember.Test.pendingAjaxRequests was decremented');
});

QUnit.test('pendingAjaxRequests is ignores ajaxComplete events from past setupForTesting calls', function() {
  equal(Test.pendingAjaxRequests, 0);
  var xhr = { some: 'xhr' };
  jQuery(document).trigger('ajaxSend', xhr);
  equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests was incremented');

  run(function() {
    setupForTesting();
  });
  equal(Test.pendingAjaxRequests, 0, 'Ember.Test.pendingAjaxRequests was reset');

  var altXhr = { some: 'more xhr' };
  jQuery(document).trigger('ajaxSend', altXhr);
  equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests was incremented');
  jQuery(document).trigger('ajaxComplete', xhr);
  equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests is not impressed with your unexpected complete');
});

QUnit.test('pendingAjaxRequests is reset by setupForTesting', function() {
  Test.pendingAjaxRequests = 1;
  run(function() {
    setupForTesting();
  });
  equal(Test.pendingAjaxRequests, 0, 'pendingAjaxRequests is reset');
});

QUnit.module('ember-testing async router', {
  setup() {
    cleanup();

    run(function() {
      App = EmberApplication.create();
      App.Router = EmberRouter.extend({
        location: 'none'
      });

      App.Router.map(function() {
        this.route('user', { resetNamespace: true }, function() {
          this.route('profile');
          this.route('edit');
        });
      });

      App.UserRoute = EmberRoute.extend({
        model() {
          return resolveLater();
        }
      });

      App.UserProfileRoute = EmberRoute.extend({
        beforeModel() {
          var self = this;
          return resolveLater().then(function() {
            self.transitionTo('user.edit');
          });
        }
      });

      // Emulates a long-running unscheduled async operation.
      function resolveLater() {
        var promise;

        run(function() {
          promise = new RSVP.Promise(function(resolve) {
            // The wait() helper has a 10ms tick. We should resolve() after at least one tick
            // to test whether wait() held off while the async router was still loading. 20ms
            // should be enough.
            setTimeout(function() {
              run(function() {
                resolve(EmberObject.create({ firstName: 'Tom' }));
              });
            }, 20);
          });
        });

        return promise;
      }

      App.setupForTesting();
    });

    App.injectTestHelpers();
    run(App, 'advanceReadiness');
  },

  teardown() {
    cleanup();
  }
});

QUnit.test('currentRouteName for \'/user\'', function() {
  expect(4);

  App.testHelpers.visit('/user').then(function() {
    equal(currentRouteName(App), 'user.index', 'should equal \'user.index\'.');
    equal(currentPath(App), 'user.index', 'should equal \'user.index\'.');
    equal(currentURL(App), '/user', 'should equal \'/user\'.');
    equal(App.__container__.lookup('route:user').get('controller.model.firstName'), 'Tom', 'should equal \'Tom\'.');
  });
});

QUnit.test('currentRouteName for \'/user/profile\'', function() {
  expect(4);

  App.testHelpers.visit('/user/profile').then(function() {
    equal(currentRouteName(App), 'user.edit', 'should equal \'user.edit\'.');
    equal(currentPath(App), 'user.edit', 'should equal \'user.edit\'.');
    equal(currentURL(App), '/user/edit', 'should equal \'/user/edit\'.');
    equal(App.__container__.lookup('route:user').get('controller.model.firstName'), 'Tom', 'should equal \'Tom\'.');
  });
});

var originalVisitHelper, originalFindHelper, originalWaitHelper;

QUnit.module('can override built-in helpers', {
  setup() {
    originalVisitHelper = Test._helpers.visit;
    originalFindHelper  = Test._helpers.find;
    originalWaitHelper  = Test._helpers.wait;

    jQuery('').appendTo('head');
    jQuery('

').appendTo('body');
    run(function() {
      App = Ember.Application.create({
        rootElement: '#ember-testing'
      });

      App.setupForTesting();
    });
  },

  teardown() {
    App.removeTestHelpers();
    jQuery('#ember-testing-container, #ember-testing').remove();
    run(App, App.destroy);
    App = null;

    Test._helpers.visit = originalVisitHelper;
    Test._helpers.find  = originalFindHelper;
    Test._helpers.wait  = originalWaitHelper;
  }
});

QUnit.test('can override visit helper', function() {
  expect(1);

  Test.registerHelper('visit', function() {
    ok(true, 'custom visit helper was called');
  });

  App.injectTestHelpers();
  App.testHelpers.visit();
});

QUnit.test('can override find helper', function() {
  expect(1);

  Test.registerHelper('find', function() {
    ok(true, 'custom find helper was called');

    return ['not empty array'];
  });

  App.injectTestHelpers();
  App.testHelpers.findWithAssert('.who-cares');
});

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class Action_Spawn : MonoBehaviour {

	public void PerformAction()
	{
		Debug.Log ("Action Spawn");
	}
}


text:
module Azure::DataMigration::Mgmt::V2018_07_15_preview
  module Models
    #
    # Defines metadata for table to be migrated
    #
    class NonSqlDataMigrationTable

      include MsRestAzure

      # @return [String] Source table name
      attr_accessor :source_name

      #
      # Mapper for NonSqlDataMigrationTable class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'NonSqlDataMigrationTable',
          type: {
            name: 'Composite',
            class_name: 'NonSqlDataMigrationTable',
            model_properties: {
              source_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'sourceName',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package org.hisp.dhis.common;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import org.hisp.dhis.analytics.AggregationType;
import org.hisp.dhis.common.view.DetailedView;
import org.hisp.dhis.common.view.DimensionalView;
import org.hisp.dhis.common.view.ExportView;
import org.hisp.dhis.legend.LegendSet;

/**
 * @author Lars Helge Overland
 */
public class BaseDimensionalItemObject
    extends BaseNameableObject
    implements DimensionalItemObject
{
    /**
     * The dimension type.
     */
    private DimensionItemType dimensionItemType;

    /**
     * The legend set for this dimension.
     */
    protected LegendSet legendSet;

    /**
     * The aggregation type for this dimension.
     */
    protected AggregationType aggregationType;

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    public BaseDimensionalItemObject()
    {
    }

    public BaseDimensionalItemObject( String dimensionItem )
    {
        this.uid = dimensionItem;
        this.code = dimensionItem;
        this.name = dimensionItem;
    }

    // -------------------------------------------------------------------------
    // Logic
    // -------------------------------------------------------------------------

    @Override
    public boolean hasLegendSet()
    {
        return getLegendSet() != null;
    }

    @Override
    public boolean hasAggregationType()
    {
        return getAggregationType() != null;
    }

    // -------------------------------------------------------------------------
    // Get and set methods
    // -------------------------------------------------------------------------

    @Override
    @JsonProperty
    @JsonView( { DimensionalView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public String getDimensionItem()
    {
        return uid;
    }

    public void setDimensionItem( String dimensionItem )
    {
        this.uid = dimensionItem;
    }

    @Override
    @JsonProperty
    @JsonView( { DimensionalView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public DimensionItemType getDimensionItemType()
    {
        return dimensionItemType;
    }

    public void setDimensionItemType( DimensionItemType dimensionItemType )
    {
        this.dimensionItemType = dimensionItemType;
    }

    @Override
    @JsonProperty
    @JsonSerialize( as = BaseIdentifiableObject.class )
    @JsonView( { DimensionalView.class, DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public LegendSet getLegendSet()
    {
        return legendSet;
    }

    public void setLegendSet( LegendSet legendSet )
    {
        this.legendSet = legendSet;
    }

    @Override
    @JsonProperty
    @JsonView( { DimensionalView.class, DetailedView.class, ExportView.class } )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public AggregationType getAggregationType()
    {
        return aggregationType;
    }

    public void setAggregationType( AggregationType aggregationType )
    {
        this.aggregationType = aggregationType;
    }

    // -------------------------------------------------------------------------
    // Merge
    // -------------------------------------------------------------------------

    @Override
    public void mergeWith( IdentifiableObject other, MergeMode mergeMode )
    {
        super.mergeWith( other, mergeMode );

        if ( other.getClass().isInstance( this ) )
        {
            DimensionalItemObject object = (DimensionalItemObject) other;

            if ( mergeMode.isReplace() )
            {
                legendSet = object.getLegendSet();
                aggregationType = object.getAggregationType();
            }
            else if ( mergeMode.isMerge() )
            {
                legendSet = object.getLegendSet() == null ? legendSet : object.getLegendSet();
                aggregationType = object.getAggregationType() == null ? aggregationType : object.getAggregationType();
            }
        }
    }
}


text:
package com.cowthan.collection;

public class Delete {

}


text:
namespace ui {

// static
NativeTheme* NativeTheme::instance() {
  return NativeThemeEmbedded::instance();
}

// static
NativeThemeEmbedded* NativeThemeEmbedded::instance() {
  CR_DEFINE_STATIC_LOCAL(NativeThemeEmbedded, s_native_theme, ());
  return &s_native_theme;
}

SkColor NativeThemeEmbedded::GetSystemColor(ColorId color_id) const {
  NOTIMPLEMENTED();
  return SK_ColorBLACK;
}

NativeThemeEmbedded::NativeThemeEmbedded() {
}

NativeThemeEmbedded::~NativeThemeEmbedded() {
}

}  // namespace ui


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2015-2020 QuartzDesk.com.
  ~ Licensed under the MIT license (https://opensource.org/licenses/MIT).
  -->

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="com.quartzdesk.executor.domain.model.db.SchemaUpdate"
         table="qd_schema_update">

    <id name="id" type="QD_LONG">
      <column name="schema_update_id"/>
      <generator class="native">
        <!--
          Fall-back sequence name for DBs that do not support identity columns (Oracle,...).
        -->
        <param name="sequence_name">seq_qd_schema_update</param>
      </generator>
    </id>

    <property name="major" type="QD_INTEGER">
      <column name="major" not-null="true"/>
    </property>

    <property name="minor" type="QD_INTEGER">
      <column name="minor" not-null="true"/>
    </property>

    <property name="maintenance" type="QD_INTEGER">
      <column name="maintenance" not-null="true"/>
    </property>

    <property name="appliedAt" type="QD_TIMESTAMP_WITH_TZ">
      <column name="applied_at" not-null="true"/>
    </property>

  </class>
</hibernate-mapping>


text:
layout: leaf-node
title: "Hello Ruby"
title-url: "http://www.helloruby.com/"
author: "n.a."
groups: broader-issues
categories: computer-science-education
topics: ongoing-projects
summary: >
    Hello Ruby started as a book on Kickstarter. It teaches uses play
    to teach logic required to write code. The main character in the
    book is a girl named Ruby.
pub-date:
added-date: 2017-04-30
resource-type: external-page
---


text:
                <csf-button-component-picker on-added="insert(chosenComponent, 0)"></csf-button-component-picker>

                Drop here...

                <csf-abstract-container-item
                        component="item"
                        can-i="canI"
                        on-removed="remove($index)"
                        class="ui vertical segment">
                </csf-abstract-container-item>

                    Drop here...


text:
using System.Collections.Generic;

namespace Microsoft.AspNetCore.Http.Connections;

/// <summary>
/// A response to a '/negotiate' request.
/// </summary>
public class NegotiationResponse
{
    /// <summary>
    /// An optional Url to redirect the client to another endpoint.
    /// </summary>
    public string? Url { get; set; }

    /// <summary>
    /// An optional access token to go along with the Url.
    /// </summary>
    public string? AccessToken { get; set; }

    /// <summary>
    /// The public ID for the connection.
    /// </summary>
    public string? ConnectionId { get; set; }

    /// <summary>
    /// The private ID for the connection.
    /// </summary>
    public string? ConnectionToken { get; set; }

    /// <summary>
    /// The minimum value between the version the client sends and the maximum version the server supports.
    /// </summary>
    public int Version { get; set; }

    /// <summary>
    /// A list of transports the server supports.
    /// </summary>
    public IList<AvailableTransport>? AvailableTransports { get; set; }

    /// <summary>
    /// An optional error during the negotiate. If this is not null the other properties on the response can be ignored.
    /// </summary>
    public string? Error { get; set; }
}


text:
<?php

	class salesforce
	{
		// populating error properties
		public $errors = array();
		public $errorCount = 0;

		public static $httpErrors = Array(
			"400 Bad Request" => "The request could not be understood by the Salesforce due to malformed syntax.",
			"401 Unauthorized" => "Salesforce authentication failed.",
			"403 Forbidden" => "Salesforce understood the request, but is refusing to fulfill it.",
			"404 Not Found" => "The report or page specified could not be found.",
			"405 Method Not Allowed" => "Salesforce understood the request, but cannot fulfill it.",
			"408 Request Timeout" => "Salesforce did not respond within the time that Greyskull was prepaired to wait.",
			"500 Internal Server Error" => "Salesforce encountered an unexpected condition which prevented it from fulfilling the request.",
			"502 Bad Gateway" => "",
			"504 Gateway Timeout" => ""
		);

		// Constructor logs into salesforce
		function __construct($username = "default@default.com", $password = "default")
		{
			$loginURL = 'https://login.salesforce.com/';
			$this->partition = "na12";

			// Setting up POST data
			$postFeilds = array(
				'username' => $username,
				'un' => $username,
				'pw' => $password,
				'useSecure' => true,
				'it' => 'standard'
			);

			// setting up cURL and designating the cookie file
			$this -> curl = curl_init();

			// Feeding the cURL object
			curl_setopt($this -> curl, CURLOPT_URL, $loginURL);
			curl_setopt($this -> curl, CURLOPT_CONNECTTIMEOUT, 30);
			curl_setopt($this -> curl, CURLOPT_TIMEOUT, 10);
			curl_setopt($this -> curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.6 (KHTML, like Gecko) Chrome/16.0.897.0 Safari/535.6");
			curl_setopt($this -> curl, CURLOPT_HEADER, 30);
			curl_setopt($this -> curl, CURLOPT_POST, true);
			curl_setopt($this -> curl, CURLOPT_POSTFIELDS, $postFeilds);
			curl_setopt($this -> curl, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($this -> curl, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($this -> curl, CURLOPT_COOKIESESSION, true);
			curl_setopt($this -> curl, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($this -> curl, CURLOPT_TIMEOUT, 300);

			// Fire cURL and report any errors
			$answer = curl_exec($this -> curl);
			if (curl_error($this -> curl))
			{
				$this -> errorCount++;
				$this -> errors[] = curl_error($this -> curl);
			}
			$this -> captureCookie($answer);

			// Get the login result, Salesforce will redirect on sucess
			$status = curl_getinfo($this -> curl);
			$this -> loginResult = $status['url'] !== 'https://login.salesforce.com/';

			if (!$this -> loginResult)
			{
				$this -> errorCount++;
				$this -> errors[] = 'Failed to login to Salesforce, please verify your login information.';
			}

		}

		function report($reportId)
		{
			if ($this -> loginResult)
			{
				// Construct the url
				$partition = $this->partition
				$url[0] = "https://$partition.salesforce.com/";
				$url[1] = trim($reportId);
				$url[2] = '?export=1&enc=UTF-8&xf=csv';

				$url = implode($url);

				// Feed the cURL object some more
				curl_setopt($this -> curl, CURLOPT_URL, $url);
				curl_setopt($this -> curl, CURLOPT_POST, false);
				curl_setopt($this -> curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($this -> curl, CURLOPT_FOLLOWLOCATION, true);
				curl_setopt($this -> curl, CURLOPT_COOKIE, $this -> cookies);

				// Fire cURL, report errors
				$answer = curl_exec($this -> curl);
				if (curl_error($this -> curl))
				{
					$this -> errorCount++;
					$this -> errors[] = curl_error($this -> curl);
				}

				if (strpos($answer, 'Content-Type: text/csv') !== false)
				{
					// Remove the header info
					$csv = preg_replace('/HTTP[\s\S]*chunked/', '', $answer);

					// Break the string into rows
					$rows = explode("\n", $csv);

					if (is_array($rows))
					{
						foreach ($rows as $i => $row)
						{
							$row = trim($row);

							if (strlen($row) > 0)
							{
								$array[] = str_getcsv($row);
							}
						}

						if (is_array($array))
						{
							$colums = $array[0];

							// $result[] = $colums;

							foreach ($array as $i => $row)
							{
								$hasCols = array_keys($colums) === array_keys($row);

								if ($hasCols)
								{
									foreach ($row as $col => $val)
									{
										if ($i == 0)
										{
											$result[$i][$col] = trim($val);
										}
										else
										{
											$result[$i][$col] = trim($val);
										}
									}
								}
							}
						}
					}

					return $result;
				}
				else
				{
					$this -> errorCount++;
					$this -> errors[] = 'Failed to aquire report ' . $reportId;
				}

			}
			else
			{
				$this -> errorCount++;
				$this -> errors[] = 'Failed to login to Salesforce, please verify your login information.';
			}
		}

		public function reportDetailed($reportId, $searchParam = FALSE)
		{
			if ($this -> loginResult)
			{
				// Construct the url
				$partition = $this->partition
				$urlPart[0] = "https://$partition.salesforce.com/";
				$urlPart[1] = trim($reportId);
				$urlPart[2] = '?export=1&enc=UTF-8&xf=csv';
				if (is_array($searchParam))
				{
					foreach ($searchParam as $i => $val)
					{
						$prams[] = "&$i=$val";
					}

					$urlPart[3] = implode('', $prams);
				}
				else
				{
					$urlPart[3] = $searchParam == FALSE ? '' : '&pv0=' . trim($searchParam);
				}

				$url = implode($urlPart);
				//echo $url.'

';

				$this -> urlString = $url;

				// Feed the cURL object some more
				curl_setopt($this -> curl, CURLOPT_URL, $url);
				curl_setopt($this -> curl, CURLOPT_POST, false);
				curl_setopt($this -> curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($this -> curl, CURLOPT_FOLLOWLOCATION, true);
				curl_setopt($this -> curl, CURLOPT_COOKIE, $this -> cookies);

				// Fire cURL, report errors
				$answer = curl_exec($this -> curl);
				if (curl_error($this -> curl))
				{
					$this -> errorCount++;
					$this -> errors[] = curl_error($this -> curl);
				}

				if (strpos($answer, 'Content-Type: text/csv') !== false)
				{
					// Remove the header info
					$csv = preg_replace('/HTTP[\s\S]*chunked/', '', $answer);

					// Break the string into rows
					$rows = explode("\n", $csv);
					$this -> testParse = $this -> parse($csv, ',', true);

					if (is_array($rows))
					{
						foreach ($rows as $i => $row)
						{
							$row = trim($row);

							if (strlen($row) > 0)
							{
								$array[] = str_getcsv($row);
							}
						}

						if (is_array($array))
						{

							// Lot's of looping to get the report in the right format

							$colums = $array[0];

							foreach ($array as $i => $row)
							{
								$hasCols = array_keys($colums) === array_keys($row);

								if ($hasCols)
								{
									foreach ($row as $col => $val)
									{
										if ($i == 0)
										{
											$result[$i][$col] = trim($val);
										}
										else
										{
											$result[$i][$col] = trim($val);
										}
									}
								}
							}
						}
					}

					return $result;
				}
				else
				{
					$this -> errorCount++;
					$this -> errors[] = 'Failed to aquire report ' . $reportId;

					$this -> errors[] = 'Invalid response: ' . $answer;
				}

			}
			else
			{
				$this -> errorCount++;
				$this -> errors[] = 'Failed to login to Salesforce, please verify your login information.';
			}
		}

		// Accepts a cURL response that contains the header and stores the session
		// cookies in $this->cookies.
		private function captureCookie($answer)
		{
			$headerSize = curl_getinfo($this -> curl, CURLINFO_HEADER_SIZE);
			$header = substr($answer, 0, $headerSize);
			preg_match_all("/^Set-cookie: (.*?);/ism", $header, $cookieCrumbs);

			if (is_array($cookieCrumbs[1]))
			{
				$this -> cookies = implode(';', $cookieCrumbs[1]);
			}
		}

		public function __deconstructor()
		{
			$partition = $this->partition
			$url = 'https://$partition.salesforce.com/secur/logout.jsp';
			curl_setopt($this -> curl, CURLOPT_URL, $url);
			curl_setopt($this -> curl, CURLOPT_FOLLOWLOCATION, true);
			$answer = curl_exec($this -> curl);

			curl_close($this -> curl);
		}

		private function parse($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
		{
			$enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
			$enc = preg_replace_callback('/"(.*?)"/s', function($field)
			{
				return urlencode(utf8_encode($field[1]));
			}, $enc);
			$lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
			return array_map(function($line) use ($delimiter, $trim_fields)
			{
				$fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
				return array_map(function($field)
				{
					return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
				}, $fields);
			}, $lines);
		}

	}
?>


text:
package com.amazonaws.services.backupgateway.model;

import javax.annotation.Generated;

/**
 *

 * The operation did not succeed because a validation error occurred.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ValidationException extends com.amazonaws.services.backupgateway.model.AWSBackupGatewayException {
    private static final long serialVersionUID = 1L;

    /**
     *

     * A description of what caused the validation error.
     *

     */
    private String errorCode;

    /**
     * Constructs a new ValidationException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public ValidationException(String message) {
        super(message);
    }

    /**
     *

     * A description of what caused the validation error.
     *

     *
     * @param errorCode
     *        A description of what caused the validation error.
     */

    @com.fasterxml.jackson.annotation.JsonProperty("ErrorCode")
    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    /**
     *

     * A description of what caused the validation error.
     *

     *
     * @return A description of what caused the validation error.
     */

    @com.fasterxml.jackson.annotation.JsonProperty("ErrorCode")
    public String getErrorCode() {
        return this.errorCode;
    }

    /**
     *

     * A description of what caused the validation error.
     *

     *
     * @param errorCode
     *        A description of what caused the validation error.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ValidationException withErrorCode(String errorCode) {
        setErrorCode(errorCode);
        return this;
    }

}


text:
package com.clockwork.terrain.geomipmap.lodcalc;

import com.clockwork.export.InputCapsule;
import com.clockwork.export.CWExporter;
import com.clockwork.export.CWImporter;
import com.clockwork.export.OutputCapsule;
import com.clockwork.math.Vector3f;
import com.clockwork.terrain.geomipmap.TerrainPatch;
import com.clockwork.terrain.geomipmap.UpdatedTerrainPatch;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

/**
 * Calculates the LOD of the terrain based on its distance from the
 * cameras. Taking the minimum distance from all cameras.
 *
 */
public class DistanceLodCalculator implements LodCalculator {

    private int size; // size of a terrain patch
    private float lodMultiplier = 2;
    private boolean turnOffLod = false;

    public DistanceLodCalculator() {
    }

    public DistanceLodCalculator(int patchSize, float multiplier) {
        this.size = patchSize;
        this.lodMultiplier = multiplier;
    }

    public boolean calculateLod(TerrainPatch terrainPatch, List<Vector3f> locations, HashMap<String, UpdatedTerrainPatch> updates) {
        if (locations == null || locations.isEmpty())
            return false;// no camera yet
        float distance = getCenterLocation(terrainPatch).distance(locations.get(0));

        if (turnOffLod) {
            // set to full detail
            int prevLOD = terrainPatch.getLod();
            UpdatedTerrainPatch utp = updates.get(terrainPatch.getName());
            if (utp == null) {
                utp = new UpdatedTerrainPatch(terrainPatch);
                updates.put(utp.getName(), utp);
            }
            utp.setNewLod(0);
            utp.setPreviousLod(prevLOD);
            //utp.setReIndexNeeded(true);
            return true;
        }

        // go through each lod level to find the one we are in
        for (int i = 0; i <= terrainPatch.getMaxLod(); i++) {
            if (distance < getLodDistanceThreshold() * (i + 1)*terrainPatch.getWorldScaleCached().x || i == terrainPatch.getMaxLod()) {
                boolean reIndexNeeded = false;
                if (i != terrainPatch.getLod()) {
                    reIndexNeeded = true;
                    //System.out.println("lod change: "+lod+" > "+i+"    dist: "+distance);
                }
                int prevLOD = terrainPatch.getLod();

                UpdatedTerrainPatch utp = updates.get(terrainPatch.getName());
                if (utp == null) {
                    utp = new UpdatedTerrainPatch(terrainPatch);//save in here, do not update actual variables
                    updates.put(utp.getName(), utp);
                }
                utp.setNewLod(i);
                utp.setPreviousLod(prevLOD);
                //utp.setReIndexNeeded(reIndexNeeded);

                return reIndexNeeded;
            }
        }

        return false;
    }

    protected Vector3f getCenterLocation(TerrainPatch terrainPatch) {
        Vector3f loc = terrainPatch.getWorldTranslationCached();
        loc.x += terrainPatch.getSize()*terrainPatch.getWorldScaleCached().x / 2;
        loc.z += terrainPatch.getSize()*terrainPatch.getWorldScaleCached().z / 2;
        return loc;
    }

    public void write(CWExporter ex) throws IOException {
        OutputCapsule oc = ex.getCapsule(this);
        oc.write(size, "patchSize", 32);
        oc.write(lodMultiplier, "lodMultiplier", 32);
    }

    public void read(CWImporter im) throws IOException {
        InputCapsule ic = im.getCapsule(this);
        size = ic.readInt("patchSize", 32);
        lodMultiplier = ic.readFloat("lodMultiplier", 2.7f);
    }

    @Override
    public LodCalculator clone() {
        DistanceLodCalculator clone = new DistanceLodCalculator(size, lodMultiplier);
        return clone;
    }

    @Override
    public String toString() {
        return "DistanceLodCalculator "+size+"*"+lodMultiplier;
    }

    /**
     * Gets the camera distance where the LOD level will change
     */
    protected float getLodDistanceThreshold() {
        return size*lodMultiplier;
    }

    /**
     * Does this calculator require the terrain to have the difference of
     * LOD levels of neighbours to be more than 1.
     */
    public boolean usesVariableLod() {
        return false;
    }

    public float getLodMultiplier() {
        return lodMultiplier;
    }

    public void setLodMultiplier(float lodMultiplier) {
        this.lodMultiplier = lodMultiplier;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void turnOffLod() {
        turnOffLod = true;
    }

    public boolean isLodOff() {
        return turnOffLod;
    }

    public void turnOnLod() {
        turnOffLod = false;
    }

}


text:
/**
 * @test
 * @summary test String.split()
 */
import java.util.regex.*;

public class Split {

    public static void main(String[] args) throws Exception {
        String source = "0123456789";
        for (int limit=-2; limit<3; limit++) {
            for (int x=0; x<10; x++) {
                String[] result = source.split(Integer.toString(x), limit);
                int expectedLength = limit < 1 ? 2 : limit;

                if ((limit == 0) && (x == 9)) {
                    // expected dropping of ""
                    if (result.length != 1)
                        throw new RuntimeException("String.split failure 1");
                    if (!result[0].equals("012345678")) {
                        throw new RuntimeException("String.split failure 2");
                    }
                } else {
                    if (result.length != expectedLength) {
                        throw new RuntimeException("String.split failure 3");
                    }
                    if (!result[0].equals(source.substring(0,x))) {
                        if (limit != 1) {
                            throw new RuntimeException(
                                "String.split failure 4");
                        } else {
                            if (!result[0].equals(source.substring(0,10))) {
                            throw new RuntimeException(
                                "String.split failure 10");
                            }
                        }
                    }
                    if (expectedLength > 1) { // Check segment 2
                       if (!result[1].equals(source.substring(x+1,10)))
                          throw new RuntimeException("String.split failure 5");
                    }
                }
            }
        }
        // Check the case for no match found
        for (int limit=-2; limit<3; limit++) {
            String[] result = source.split("e", limit);
            if (result.length != 1)
                throw new RuntimeException("String.split failure 6");
            if (!result[0].equals(source))
                throw new RuntimeException("String.split failure 7");
        }
        // Check the case for limit == 0, source = "";
        source = "";
        String[] result = source.split("e", 0);
        if (result.length != 1)
            throw new RuntimeException("String.split failure 8");
        if (!result[0].equals(source))
            throw new RuntimeException("String.split failure 9");
    }
}


text:
var log = require('xqnode-logger');

module.exports = function(app) {
	'use strict';

	log.sys('Connecting to Database!');

	return Promise.resolve();
};


text:
When an application tries to set the `ConnectionString` property of the `SqlConnection` object to an empty string or null value, a `NullReferenceException` is thrown. This exception occurs when .NET Framework 4.7.2 is installed on the OS hosting the application.

## Cause

.NET Framework 4.7.2 includes a change that increases the default connection retry count for connections to Azure SQL Database to two.
This change sets the internal value of the retry count without validating if the `ConnectionString` is a non-null or non-empty value,
which results in the `NullReferenceException`.

## Impact

The impact is limited to applications using the `SqlConnection.ConnectionString` API to set an empty connection string, which now throws an  exception.

## Workarounds

No known workarounds with .NET Framework 4.7.2.

## Resolution

This issue has been fixed in the [latest update to .NET Framework 4.7.2](https://go.microsoft.com/fwlink/?LinkId=2005309) for all platforms except Windows 10 April 2018 Update.

For Windows 10 April 2018 Update, the fix will be available in the upcoming Cumulative Update.


text:
'use strict'

const Routes = require('./routes')

exports.register = (server, options, next) => {
  server.route(Routes)
  server.log('info', 'Plugin registered: test hapi handles by injecting requests')

  next()
}

exports.register.attributes = {
  name: 'hapi-testing-1',
  version: '1.0.0'
}


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewComponents;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MusicStore.Controllers;
using MusicStore.Models;
using Xunit;

namespace MusicStore.Components
{
    public class CartSummaryComponentTest
    {
        private readonly IServiceProvider _serviceProvider;

        public CartSummaryComponentTest()
        {
            var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();

            var services = new ServiceCollection();

            services.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));

            _serviceProvider = services.BuildServiceProvider();
        }

        [Fact]
        public async Task CartSummaryComponent_Returns_CartedItems()
        {
            // Arrange
            var viewContext = new ViewContext()
            {
                HttpContext = new DefaultHttpContext()
            };

            // Session initialization
            var cartId = "CartId_A";
            viewContext.HttpContext.Session = new TestSession();
            viewContext.HttpContext.Session.SetString("Session", cartId);

            // DbContext initialization
            var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
            PopulateData(dbContext, cartId, albumTitle: "AlbumA", itemCount: 10);

            // CartSummaryComponent initialization
            var cartSummaryComponent = new CartSummaryComponent(dbContext)
            {
                ViewComponentContext = new ViewComponentContext() { ViewContext = viewContext }
            };

            // Act
            var result = await cartSummaryComponent.InvokeAsync();

            // Assert
            Assert.NotNull(result);
            var viewResult = Assert.IsType<ViewViewComponentResult>(result);
            Assert.Null(viewResult.ViewName);
            Assert.Null(viewResult.ViewData.Model);
            Assert.Equal(10, cartSummaryComponent.ViewBag.CartCount);
            Assert.Equal("AlbumA", cartSummaryComponent.ViewBag.CartSummary);
        }

        private static void PopulateData(MusicStoreContext context, string cartId, string albumTitle, int itemCount)
        {
            var album = new Album()
            {
                AlbumId = 1,
                Title = albumTitle,
            };

            var cartItems = Enumerable.Range(1, itemCount).Select(n =>
                new CartItem()
                {
                    AlbumId = 1,
                    Album = album,
                    Count = 1,
                    CartId = cartId,
                }).ToArray();

            context.AddRange(cartItems);
            context.SaveChanges();
        }
    }
}