text:
'use strict';

import {createEventTarget} from 'dom-event-testing-library';

let React;
let ReactDOM;
let ReactDOMClient;
let ReactDOMServer;
let ReactFeatureFlags;
let Scheduler;
let Suspense;
let act;

let IdleEventPriority;

function dispatchMouseHoverEvent(to, from) {
  if (!to) {
    to = null;
  }
  if (!from) {
    from = null;
  }
  if (from) {
    const mouseOutEvent = document.createEvent('MouseEvents');
    mouseOutEvent.initMouseEvent(
      'mouseout',
      true,
      true,
      window,
      0,
      50,
      50,
      50,
      50,
      false,
      false,
      false,
      false,
      0,
      to,
    );
    from.dispatchEvent(mouseOutEvent);
  }
  if (to) {
    const mouseOverEvent = document.createEvent('MouseEvents');
    mouseOverEvent.initMouseEvent(
      'mouseover',
      true,
      true,
      window,
      0,
      50,
      50,
      50,
      50,
      false,
      false,
      false,
      false,
      0,
      from,
    );
    to.dispatchEvent(mouseOverEvent);
  }
}

function dispatchClickEvent(target) {
  const mouseOutEvent = document.createEvent('MouseEvents');
  mouseOutEvent.initMouseEvent(
    'click',
    true,
    true,
    window,
    0,
    50,
    50,
    50,
    50,
    false,
    false,
    false,
    false,
    0,
    target,
  );
  return target.dispatchEvent(mouseOutEvent);
}

// TODO: There's currently no React DOM API to opt into Idle priority updates,
// and there's no native DOM event that maps to idle priority, so this is a
// temporary workaround. Need something like ReactDOM.unstable_IdleUpdates.
function TODO_scheduleIdleDOMSchedulerTask(fn) {
  ReactDOM.unstable_runWithPriority(IdleEventPriority, () => {
    const prevEvent = window.event;
    window.event = {type: 'message'};
    try {
      fn();
    } finally {
      window.event = prevEvent;
    }
  });
}

describe('ReactDOMServerSelectiveHydration', () => {
  beforeEach(() => {
    jest.resetModuleRegistry();

    ReactFeatureFlags = require('shared/ReactFeatureFlags');
    ReactFeatureFlags.enableCreateEventHandleAPI = true;
    React = require('react');
    ReactDOM = require('react-dom');
    ReactDOMClient = require('react-dom/client');
    ReactDOMServer = require('react-dom/server');
    act = require('jest-react').act;
    Scheduler = require('scheduler');
    Suspense = React.Suspense;

    IdleEventPriority = require('react-reconciler/constants').IdleEventPriority;
  });

  it('hydrates the target boundary synchronously during a click', async () => {
    function Child({text}) {
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const span = container.getElementsByTagName('span')[1];

    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // This should synchronously hydrate the root App and the second suspense
    // boundary.
    const result = dispatchClickEvent(span);

    // The event should have been canceled because we called preventDefault.
    expect(result).toBe(false);

    // We rendered App, B and then invoked the event without rendering A.
    expect(Scheduler).toHaveYielded(['App', 'B', 'Clicked B']);

    // After continuing the scheduler, we finally hydrate A.
    expect(Scheduler).toFlushAndYield(['A']);

    document.body.removeChild(container);
  });

  it('hydrates at higher pri if sync did not work first time', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));

    function Child({text}) {
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanD = container.getElementsByTagName('span')[3];

    suspend = true;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // This click target cannot be hydrated yet because it's suspended.
    await act(async () => {
      const result = dispatchClickEvent(spanD);
      expect(result).toBe(true);
    });
    expect(Scheduler).toHaveYielded([
      'App',
      // Continuing rendering will render B next.
      'B',
      'C',
    ]);

    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });

    if (
      gate(
        flags =>
          flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
      )
    ) {
      expect(Scheduler).toHaveYielded(['D', 'A']);
    } else {
      // After the click, we should prioritize D and the Click first,
      // and only after that render A and C.
      expect(Scheduler).toHaveYielded(['D', 'Clicked D', 'A']);
    }

    document.body.removeChild(container);
  });

  it('hydrates at higher pri for secondary discrete events', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));

    function Child({text}) {
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanA = container.getElementsByTagName('span')[0];
    const spanC = container.getElementsByTagName('span')[2];
    const spanD = container.getElementsByTagName('span')[3];

    suspend = true;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // This click target cannot be hydrated yet because the first is Suspended.
    dispatchClickEvent(spanA);
    dispatchClickEvent(spanC);
    dispatchClickEvent(spanD);

    if (
      gate(
        flags =>
          flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
      )
    ) {
      expect(Scheduler).toHaveYielded(['App', 'C', 'Clicked C']);
    } else {
      expect(Scheduler).toHaveYielded(['App']);
    }

    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });

    if (
      ReactFeatureFlags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
    ) {
      expect(Scheduler).toHaveYielded([
        'A',
        'D',
        // B should render last since it wasn't clicked.
        'B',
      ]);
    } else {
      // We should prioritize hydrating A, C and D first since we clicked in
      // them. Only after they're done will we hydrate B.
      expect(Scheduler).toHaveYielded([
        'A',
        'Clicked A',
        'C',
        'Clicked C',
        'D',
        'Clicked D',
        // B should render last since it wasn't clicked.
        'B',
      ]);
    }

    document.body.removeChild(container);
  });

  // @gate www
  it('hydrates the target boundary synchronously during a click (createEventHandle)', async () => {
    const setClick = ReactDOM.unstable_createEventHandle('click');
    let isServerRendering = true;

    function Child({text}) {
      const ref = React.useRef(null);
      Scheduler.unstable_yieldValue(text);
      if (!isServerRendering) {
        React.useLayoutEffect(() => {
          return setClick(ref.current, () => {
            Scheduler.unstable_yieldValue('Clicked ' + text);
          });
        });
      }

      return {text};
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    isServerRendering = false;

    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    const span = container.getElementsByTagName('span')[1];

    const target = createEventTarget(span);

    // This should synchronously hydrate the root App and the second suspense
    // boundary.
    target.virtualclick();

    // We rendered App, B and then invoked the event without rendering A.
    expect(Scheduler).toHaveYielded(['App', 'B', 'Clicked B']);

    // After continuing the scheduler, we finally hydrate A.
    expect(Scheduler).toFlushAndYield(['A']);

    document.body.removeChild(container);
  });

  // @gate www
  it('hydrates at higher pri if sync did not work first time (createEventHandle)', async () => {
    let suspend = false;
    let isServerRendering = true;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));
    const setClick = ReactDOM.unstable_createEventHandle('click');

    function Child({text}) {
      const ref = React.useRef(null);
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);

      if (!isServerRendering) {
        React.useLayoutEffect(() => {
          return setClick(ref.current, () => {
            Scheduler.unstable_yieldValue('Clicked ' + text);
          });
        });
      }

      return {text};
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanD = container.getElementsByTagName('span')[3];

    suspend = true;
    isServerRendering = false;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // Continuing rendering will render B next.
    await act(async () => {
      const target = createEventTarget(spanD);
      target.virtualclick();
    });
    expect(Scheduler).toHaveYielded(['App', 'B', 'C']);

    // After the click, we should prioritize D and the Click first,
    // and only after that render A and C.
    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });
    if (
      gate(
        flags =>
          flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
      )
    ) {
      // no replay
      expect(Scheduler).toHaveYielded(['D', 'A']);
    } else {
      expect(Scheduler).toHaveYielded(['D', 'Clicked D', 'A']);
    }

    document.body.removeChild(container);
  });

  // @gate www
  it('hydrates at higher pri for secondary discrete events (createEventHandle)', async () => {
    const setClick = ReactDOM.unstable_createEventHandle('click');
    let suspend = false;
    let isServerRendering = true;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));

    function Child({text}) {
      const ref = React.useRef(null);
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);

      if (!isServerRendering) {
        React.useLayoutEffect(() => {
          return setClick(ref.current, () => {
            Scheduler.unstable_yieldValue('Clicked ' + text);
          });
        });
      }
      return {text};
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanA = container.getElementsByTagName('span')[0];
    const spanC = container.getElementsByTagName('span')[2];
    const spanD = container.getElementsByTagName('span')[3];

    suspend = true;
    isServerRendering = false;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // This click target cannot be hydrated yet because the first is Suspended.
    createEventTarget(spanA).virtualclick();
    createEventTarget(spanC).virtualclick();
    createEventTarget(spanD).virtualclick();

    if (
      ReactFeatureFlags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
    ) {
      expect(Scheduler).toHaveYielded(['App', 'C', 'Clicked C']);
    } else {
      expect(Scheduler).toHaveYielded(['App']);
    }
    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });

    if (
      ReactFeatureFlags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
    ) {
      expect(Scheduler).toHaveYielded([
        'A',
        'D',
        // B should render last since it wasn't clicked.
        'B',
      ]);
    } else {
      // We should prioritize hydrating A, C and D first since we clicked in
      // them. Only after they're done will we hydrate B.
      expect(Scheduler).toHaveYielded([
        'A',
        'Clicked A',
        'C',
        'Clicked C',
        'D',
        'Clicked D',
        // B should render last since it wasn't clicked.
        'B',
      ]);
    }

    document.body.removeChild(container);
  });

  it('hydrates the hovered targets as higher priority for continuous events', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));
    function Child({text}) {
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}
          onMouseEnter={e => {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Hover ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }
    const finalHTML = ReactDOMServer.renderToString(<App />);
    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);
    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanB = container.getElementsByTagName('span')[1];
    const spanC = container.getElementsByTagName('span')[2];
    const spanD = container.getElementsByTagName('span')[3];

    suspend = true;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);
    // Click D
    dispatchMouseHoverEvent(spanD, null);
    dispatchClickEvent(spanD);
    // Hover over B and then C.
    dispatchMouseHoverEvent(spanB, spanD);
    dispatchMouseHoverEvent(spanC, spanB);
    expect(Scheduler).toHaveYielded(['App']);
    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });
    if (
      gate(
        flags =>
          flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
      )
    ) {
      // We should prioritize hydrating D first because we clicked it.
      // but event isnt replayed
      expect(Scheduler).toHaveYielded([
        'D',
        'B', // Ideally this should be later.
        'C',
        'Hover C',
        'A',
      ]);
    } else {
      // We should prioritize hydrating D first because we clicked it.
      // Next we should hydrate C since that's the current hover target.
      // To simplify implementation details we hydrate both B and C at
      // the same time since B was already scheduled.
      // This is ok because it will at least not continue for nested
      // boundary. See the next test below.
      expect(Scheduler).toHaveYielded([
        'D',
        'Clicked D',
        'B', // Ideally this should be later.
        'C',
        'Hover C',
        'A',
      ]);
    }

    document.body.removeChild(container);
  });

  it('replays capture phase for continuous events and respects stopPropagation', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));

    function Child({text}) {
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Capture Clicked ' + text);
          }}
          onClick={e => {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}
          onMouseEnter={e => {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Mouse Enter ' + text);
          }}
          onMouseOut={e => {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Mouse Out ' + text);
          }}
          onMouseOutCapture={e => {
            e.preventDefault();
            e.stopPropagation();
            Scheduler.unstable_yieldValue('Mouse Out Capture ' + text);
          }}
          onMouseOverCapture={e => {
            e.preventDefault();
            e.stopPropagation();
            Scheduler.unstable_yieldValue('Mouse Over Capture ' + text);
          }}
          onMouseOver={e => {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Mouse Over ' + text);
          }}>

 {
              e.preventDefault();
              Scheduler.unstable_yieldValue('Mouse Over Capture Inner ' + text);
            }}>
            {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

 {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Capture Clicked Parent');
          }}
          onMouseOverCapture={e => {
            Scheduler.unstable_yieldValue('Mouse Over Capture Parent');
          }}>
          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanB = document.getElementById('B').firstChild;
    const spanC = document.getElementById('C').firstChild;
    const spanD = document.getElementById('D').firstChild;

    suspend = true;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // Click D
    dispatchMouseHoverEvent(spanD, null);
    dispatchClickEvent(spanD);
    // Hover over B and then C.
    dispatchMouseHoverEvent(spanB, spanD);
    dispatchMouseHoverEvent(spanC, spanB);

    expect(Scheduler).toHaveYielded(['App']);

    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });

    if (
      gate(
        flags =>
          flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
      )
    ) {
      // We should prioritize hydrating D first because we clicked it.
      // but event isnt replayed
      expect(Scheduler).toHaveYielded([
        'D',
        'B', // Ideally this should be later.
        'C',
        // Mouse out events aren't replayed
        // 'Mouse Out Capture B',
        // 'Mouse Out B',
        'Mouse Over Capture Parent',
        'Mouse Over Capture C',
        // Stop propagation stops these
        // 'Mouse Over Capture Inner C',
        // 'Mouse Over C',
        'A',
      ]);
    } else {
      // We should prioritize hydrating D first because we clicked it.
      // Next we should hydrate C since that's the current hover target.
      // To simplify implementation details we hydrate both B and C at
      // the same time since B was already scheduled.
      // This is ok because it will at least not continue for nested
      // boundary. See the next test below.
      expect(Scheduler).toHaveYielded([
        'D',
        'Clicked D',
        'B', // Ideally this should be later.
        'C',
        // Capture phase isn't replayed
        // Mouseout isn't replayed
        'Mouse Over C',
        'Mouse Enter C',
        'A',
      ]);
    }

    // This test shows existing quirk where stopPropagation on mouseout
    // prevents mouseEnter from firing
    dispatchMouseHoverEvent(spanC, spanB);
    expect(Scheduler).toHaveYielded([
      'Mouse Out Capture B',
      // stopPropagation stops these
      // 'Mouse Out B',
      // 'Mouse Enter C',
      'Mouse Over Capture Parent',
      'Mouse Over Capture C',
      // Stop propagation stops these
      // 'Mouse Over Capture Inner C',
      // 'Mouse Over C',
    ]);

    document.body.removeChild(container);
  });

  describe('can handle replaying events as part of multiple instances of React', () => {
    let resolveInner;
    let resolveOuter;
    let innerPromise;
    let outerPromise;
    let OuterScheduler;
    let InnerScheduler;
    let innerDiv;

    beforeEach(async () => {
      document.body.innerHTML = '';
      jest.resetModuleRegistry();
      let OuterReactDOMClient;
      let InnerReactDOMClient;
      jest.isolateModules(() => {
        OuterReactDOMClient = require('react-dom/client');
        OuterScheduler = require('scheduler');
      });
      jest.isolateModules(() => {
        InnerReactDOMClient = require('react-dom/client');
        InnerScheduler = require('scheduler');
      });

      expect(OuterReactDOMClient).not.toBe(InnerReactDOMClient);
      expect(OuterScheduler).not.toBe(InnerScheduler);

      const outerContainer = document.createElement('div');
      const innerContainer = document.createElement('div');

      let suspendOuter = false;
      outerPromise = new Promise(res => {
        resolveOuter = () => {
          suspendOuter = false;
          res();
        };
      });

      function Outer() {
        if (suspendOuter) {
          OuterScheduler.unstable_yieldValue('Suspend Outer');
          throw outerPromise;
        }
        OuterScheduler.unstable_yieldValue('Outer');
        const innerRoot = outerContainer.querySelector('#inner-root');
        return (

 {
              Scheduler.unstable_yieldValue('Outer Mouse Enter');
            }}
            dangerouslySetInnerHTML={{
              __html: innerRoot ? innerRoot.innerHTML : '',
            }}
          />
        );
      }
      const OuterApp = () => {
        return (
          <Suspense fallback={
Loading
}>
            <Outer />
          </Suspense>
        );
      };

      let suspendInner = false;
      innerPromise = new Promise(res => {
        resolveInner = () => {
          suspendInner = false;
          res();
        };
      });
      function Inner() {
        if (suspendInner) {
          InnerScheduler.unstable_yieldValue('Suspend Inner');
          throw innerPromise;
        }
        InnerScheduler.unstable_yieldValue('Inner');
        return (

 {
              Scheduler.unstable_yieldValue('Inner Mouse Enter');
            }}
          />
        );
      }
      const InnerApp = () => {
        return (
          <Suspense fallback={
Loading
}>
            <Inner />
          </Suspense>
        );
      };

      document.body.appendChild(outerContainer);
      const outerHTML = ReactDOMServer.renderToString(<OuterApp />);
      outerContainer.innerHTML = outerHTML;

      const innerWrapper = document.querySelector('#inner-root');
      innerWrapper.appendChild(innerContainer);
      const innerHTML = ReactDOMServer.renderToString(<InnerApp />);
      innerContainer.innerHTML = innerHTML;

      expect(OuterScheduler).toHaveYielded(['Outer']);
      expect(InnerScheduler).toHaveYielded(['Inner']);

      suspendOuter = true;
      suspendInner = true;

      OuterReactDOMClient.hydrateRoot(outerContainer, <OuterApp />);
      InnerReactDOMClient.hydrateRoot(innerContainer, <InnerApp />);

      expect(OuterScheduler).toFlushAndYield(['Suspend Outer']);
      expect(InnerScheduler).toFlushAndYield(['Suspend Inner']);

      innerDiv = document.querySelector('#inner');

      dispatchClickEvent(innerDiv);

      await act(async () => {
        jest.runAllTimers();
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      expect(OuterScheduler).toHaveYielded(['Suspend Outer']);
      if (
        gate(
          flags =>
            flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
        )
      ) {
        // InnerApp doesn't see the event because OuterApp calls stopPropagation in
        // capture phase since the event is blocked on suspended component
        expect(InnerScheduler).toHaveYielded([]);
      } else {
        // no stopPropagation
        expect(InnerScheduler).toHaveYielded(['Suspend Inner']);
      }

      expect(Scheduler).toHaveYielded([]);
    });
    afterEach(async () => {
      document.body.innerHTML = '';
    });

    // @gate enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
    it('Inner hydrates first then Outer', async () => {
      dispatchMouseHoverEvent(innerDiv);

      await act(async () => {
        resolveInner();
        await innerPromise;
        jest.runAllTimers();
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      expect(OuterScheduler).toHaveYielded(['Suspend Outer']);
      // Inner App renders because it is unblocked
      expect(InnerScheduler).toHaveYielded(['Inner']);
      // No event is replayed yet
      expect(Scheduler).toHaveYielded([]);

      dispatchMouseHoverEvent(innerDiv);
      expect(OuterScheduler).toHaveYielded([]);
      expect(InnerScheduler).toHaveYielded([]);
      // No event is replayed yet
      expect(Scheduler).toHaveYielded([]);

      await act(async () => {
        resolveOuter();
        await outerPromise;
        jest.runAllTimers();
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      // Nothing happens to inner app yet.
      // Its blocked on the outer app replaying the event
      expect(InnerScheduler).toHaveYielded([]);
      // Outer hydrates and schedules Replay
      expect(OuterScheduler).toHaveYielded(['Outer']);
      // No event is replayed yet
      expect(Scheduler).toHaveYielded([]);

      // fire scheduled Replay
      await act(async () => {
        jest.runAllTimers();
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      // First Inner Mouse Enter fires then Outer Mouse Enter
      expect(Scheduler).toHaveYielded([
        'Inner Mouse Enter',
        'Outer Mouse Enter',
      ]);
    });

    // @gate enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
    it('Outer hydrates first then Inner', async () => {
      dispatchMouseHoverEvent(innerDiv);

      await act(async () => {
        resolveOuter();
        await outerPromise;
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      // Outer resolves and scheduled replay
      expect(OuterScheduler).toHaveYielded(['Outer']);
      // Inner App is still blocked
      expect(InnerScheduler).toHaveYielded([]);

      // Replay outer event
      await act(async () => {
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      // Inner is still blocked so when Outer replays the event in capture phase
      // inner ends up caling stopPropagation
      expect(Scheduler).toHaveYielded([]);
      expect(OuterScheduler).toHaveYielded([]);
      expect(InnerScheduler).toHaveYielded(['Suspend Inner']);

      dispatchMouseHoverEvent(innerDiv);
      expect(OuterScheduler).toHaveYielded([]);
      expect(InnerScheduler).toHaveYielded([]);
      expect(Scheduler).toHaveYielded([]);

      await act(async () => {
        resolveInner();
        await innerPromise;
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      // Inner hydrates
      expect(InnerScheduler).toHaveYielded(['Inner']);
      // Outer was hydrated earlier
      expect(OuterScheduler).toHaveYielded([]);

      await act(async () => {
        Scheduler.unstable_flushAllWithoutAsserting();
        OuterScheduler.unstable_flushAllWithoutAsserting();
        InnerScheduler.unstable_flushAllWithoutAsserting();
      });

      // First Inner Mouse Enter fires then Outer Mouse Enter
      expect(Scheduler).toHaveYielded([
        'Inner Mouse Enter',
        'Outer Mouse Enter',
      ]);
    });
  });

  // @gate enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
  it('replays event with null target when tree is dismounted', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => {
      resolve = () => {
        suspend = false;
        resolvePromise();
      };
    });

    function Child() {
      if (suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue('Child');
      return (

 {
            Scheduler.unstable_yieldValue('on mouse over');
          }}>
          Child

      );
    }

    function App() {
      return (
        <Suspense>
          <Child />
        </Suspense>
      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);
    expect(Scheduler).toHaveYielded(['Child']);

    const container = document.createElement('div');

    document.body.appendChild(container);
    container.innerHTML = finalHTML;
    suspend = true;

    ReactDOMClient.hydrateRoot(container, <App />);

    const childDiv = container.firstElementChild;
    dispatchMouseHoverEvent(childDiv);

    // Not hydrated so event is saved for replay and stopPropagation is called
    expect(Scheduler).toHaveYielded([]);

    resolve();
    Scheduler.unstable_flushNumberOfYields(1);
    expect(Scheduler).toHaveYielded(['Child']);

    Scheduler.unstable_scheduleCallback(
      Scheduler.unstable_ImmediatePriority,
      () => {
        container.removeChild(childDiv);

        const container2 = document.createElement('div');
        container2.addEventListener('mouseover', () => {
          Scheduler.unstable_yieldValue('container2 mouse over');
        });
        container2.appendChild(childDiv);
      },
    );
    Scheduler.unstable_flushAllWithoutAsserting();

    // Even though the tree is remove the event is still dispatched with native event handler
    // on the container firing.
    expect(Scheduler).toHaveYielded(['container2 mouse over']);

    document.body.removeChild(container);
  });

  it('hydrates the last target path first for continuous events', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));

    function Child({text}) {
      if ((text === 'A' || text === 'D') && suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Hover ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">

              <Suspense fallback="Loading...">
                <Child text="B" />
              </Suspense>

            <Child text="C" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="D" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C', 'D']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const spanB = container.getElementsByTagName('span')[1];
    const spanC = container.getElementsByTagName('span')[2];
    const spanD = container.getElementsByTagName('span')[3];

    suspend = true;

    // A and D will be suspended. We'll click on D which should take
    // priority, after we unsuspend.
    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // Hover over B and then C.
    dispatchMouseHoverEvent(spanB, spanD);
    dispatchMouseHoverEvent(spanC, spanB);

    await act(async () => {
      suspend = false;
      resolve();
      await promise;
    });

    // We should prioritize hydrating D first because we clicked it.
    // Next we should hydrate C since that's the current hover target.
    // Next it doesn't matter if we hydrate A or B first but as an
    // implementation detail we're currently hydrating B first since
    // we at one point hovered over it and we never deprioritized it.
    expect(Scheduler).toHaveYielded(['App', 'C', 'Hover C', 'A', 'B', 'D']);

    document.body.removeChild(container);
  });

  it('hydrates the last explicitly hydrated target at higher priority', async () => {
    function Child({text}) {
      Scheduler.unstable_yieldValue(text);
      return {text};
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="C" />
          </Suspense>

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B', 'C']);

    const container = document.createElement('div');
    container.innerHTML = finalHTML;

    const spanB = container.getElementsByTagName('span')[1];
    const spanC = container.getElementsByTagName('span')[2];

    const root = ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // Increase priority of B and then C.
    root.unstable_scheduleHydration(spanB);
    root.unstable_scheduleHydration(spanC);

    // We should prioritize hydrating C first because the last added
    // gets highest priority followed by the next added.
    expect(Scheduler).toFlushAndYield(['App', 'C', 'B', 'A']);
  });

  // @gate experimental || www
  it('hydrates before an update even if hydration moves away from it', async () => {
    function Child({text}) {
      Scheduler.unstable_yieldValue(text);
      return {text};
    }
    const ChildWithBoundary = React.memo(function({text}) {
      return (
        <Suspense fallback="Loading...">
          <Child text={text} />
          <Child text={text.toLowerCase()} />
        </Suspense>
      );
    });

    function App({a}) {
      Scheduler.unstable_yieldValue('App');
      React.useEffect(() => {
        Scheduler.unstable_yieldValue('Commit');
      });
      return (

          <ChildWithBoundary text={a} />
          <ChildWithBoundary text="B" />
          <ChildWithBoundary text="C" />

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App a="A" />);

    expect(Scheduler).toHaveYielded(['App', 'A', 'a', 'B', 'b', 'C', 'c']);

    const container = document.createElement('div');
    container.innerHTML = finalHTML;

    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    const spanA = container.getElementsByTagName('span')[0];
    const spanB = container.getElementsByTagName('span')[2];
    const spanC = container.getElementsByTagName('span')[4];

    act(() => {
      const root = ReactDOMClient.hydrateRoot(container, <App a="A" />);
      // Hydrate the shell.
      expect(Scheduler).toFlushAndYieldThrough(['App', 'Commit']);

      // Render an update at Idle priority that needs to update A.

      TODO_scheduleIdleDOMSchedulerTask(() => {
        root.render(<App a="AA" />);
      });

      // Start rendering. This will force the first boundary to hydrate
      // by scheduling it at one higher pri than Idle.
      expect(Scheduler).toFlushAndYieldThrough([
        'App',

        // Start hydrating A
        'A',
      ]);

      // Hover over A which (could) schedule at one higher pri than Idle.
      dispatchMouseHoverEvent(spanA, null);

      // Before, we're done we now switch to hover over B.
      // This is meant to test that this doesn't cause us to forget that
      // we still have to hydrate A. The first boundary.
      // This also tests that we don't do the -1 down-prioritization of
      // continuous hover events because that would decrease its priority
      // to Idle.
      dispatchMouseHoverEvent(spanB, spanA);

      // Also click C to prioritize that even higher which resets the
      // priority levels.
      dispatchClickEvent(spanC);

      expect(Scheduler).toHaveYielded([
        // Hydrate C first since we clicked it.
        'C',
        'c',
      ]);

      expect(Scheduler).toFlushAndYield([
        // Finish hydration of A since we forced it to hydrate.
        'A',
        'a',
        // Also, hydrate B since we hovered over it.
        // It's not important which one comes first. A or B.
        // As long as they both happen before the Idle update.
        'B',
        'b',
        // Begin the Idle update again.
        'App',
        'AA',
        'aa',
        'Commit',
      ]);
    });

    const spanA2 = container.getElementsByTagName('span')[0];
    // This is supposed to have been hydrated, not replaced.
    expect(spanA).toBe(spanA2);

    document.body.removeChild(container);
  });

  // @gate enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
  it('fires capture event handlers and native events if content is hydratable during discrete event', async () => {
    spyOnDev(console, 'error');
    function Child({text}) {
      Scheduler.unstable_yieldValue(text);
      const ref = React.useRef();
      React.useLayoutEffect(() => {
        if (!ref.current) {
          return;
        }
        ref.current.onclick = () => {
          Scheduler.unstable_yieldValue('Native Click ' + text);
        };
      }, [text]);
      return (
         {
            Scheduler.unstable_yieldValue('Capture Clicked ' + text);
          }}
          onClick={e => {
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Suspense fallback="Loading...">
            <Child text="A" />
          </Suspense>
          <Suspense fallback="Loading...">
            <Child text="B" />
          </Suspense>

      );
    }

    let finalHTML;
    expect(() => {
      finalHTML = ReactDOMServer.renderToString(<App />);
    }).toErrorDev([
      'useLayoutEffect does nothing on the server',
      'useLayoutEffect does nothing on the server',
    ]);

    expect(Scheduler).toHaveYielded(['App', 'A', 'B']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const span = container.getElementsByTagName('span')[1];

    ReactDOMClient.hydrateRoot(container, <App />);

    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    // This should synchronously hydrate the root App and the second suspense
    // boundary.
    dispatchClickEvent(span);

    // We rendered App, B and then invoked the event without rendering A.
    expect(Scheduler).toHaveYielded([
      'App',
      'B',
      'Capture Clicked B',
      'Native Click B',
      'Clicked B',
    ]);

    // After continuing the scheduler, we finally hydrate A.
    expect(Scheduler).toFlushAndYield(['A']);

    document.body.removeChild(container);
  });

  // @gate enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay
  it('does not propagate discrete event if it cannot be synchronously hydrated', async () => {
    let triggeredParent = false;
    let triggeredChild = false;
    let suspend = false;
    const promise = new Promise(() => {});
    function Child() {
      if (suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue('Child');
      return (
         {
            e.stopPropagation();
            triggeredChild = true;
          }}>
          Click me

      );
    }
    function App() {
      const onClick = () => {
        triggeredParent = true;
      };
      Scheduler.unstable_yieldValue('App');
      return (

 {
            if (n) n.onclick = onClick;
          }}
          onClick={onClick}>
          <Suspense fallback={null}>
            <Child />
          </Suspense>

      );
    }
    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'Child']);

    const container = document.createElement('div');
    document.body.appendChild(container);
    container.innerHTML = finalHTML;

    suspend = true;

    ReactDOMClient.hydrateRoot(container, <App />);
    // Nothing has been hydrated so far.
    expect(Scheduler).toHaveYielded([]);

    const span = container.getElementsByTagName('span')[0];
    dispatchClickEvent(span);

    expect(Scheduler).toHaveYielded(['App']);

    dispatchClickEvent(span);

    expect(triggeredParent).toBe(false);
    expect(triggeredChild).toBe(false);
  });

  it('can attempt sync hydration if suspended root is still concurrently rendering', async () => {
    let suspend = false;
    let resolve;
    const promise = new Promise(resolvePromise => (resolve = resolvePromise));
    function Child({text}) {
      if (suspend) {
        throw promise;
      }
      Scheduler.unstable_yieldValue(text);
      return (
         {
            e.preventDefault();
            Scheduler.unstable_yieldValue('Clicked ' + text);
          }}>
          {text}

      );
    }

    function App() {
      Scheduler.unstable_yieldValue('App');
      return (

          <Child text="A" />

      );
    }

    const finalHTML = ReactDOMServer.renderToString(<App />);

    expect(Scheduler).toHaveYielded(['App', 'A']);

    const container = document.createElement('div');
    // We need this to be in the document since we'll dispatch events on it.
    document.body.appendChild(container);

    container.innerHTML = finalHTML;

    const span = container.getElementsByTagName('span')[0];

    // We suspend on the client.
    suspend = true;

    React.startTransition(() => {
      ReactDOMClient.hydrateRoot(container, <App />);
    });
    expect(Scheduler).toFlushAndYieldThrough(['App']);

    // This should attempt to synchronously hydrate the root, then pause
    // because it still suspended
    const result = dispatchClickEvent(span);
    expect(Scheduler).toHaveYielded(['App']);
    // The event should not have been cancelled because we didn't hydrate.
    expect(result).toBe(true);

    // Finish loading the data
    await act(async () => {
      suspend = false;
      await resolve();
    });

    // The app should have successfully hydrated and rendered
    if (
      gate(
        flags =>
          flags.enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
      )
    ) {
      expect(Scheduler).toHaveYielded(['App', 'A']);
    } else {
      expect(Scheduler).toHaveYielded(['App', 'A', 'Clicked A']);
    }

    document.body.removeChild(container);
  });
});


text: A demo console app using Symfony Console

redpajama_set_name: RedPajamaGithub


text:
/*
 * $Log$
 * Revision 1.8  2005/01/12 20:43:21  cargilld
 * Remove warning messages.
 *
 * Revision 1.7  2004/09/08 13:55:33  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.6  2003/05/30 09:36:36  gareth
 * Use new macros for iostream.h and std:: issues.
 *
 * Revision 1.5  2002/02/01 22:41:07  peiyongz
 * sane_include
 *
 * Revision 1.4  2001/08/02 17:10:29  tng
 * Allow DOMCount/SAXCount/IDOMCount/SAX2Count to take a file that has a list of xml file as input.
 *
 * Revision 1.3  2000/03/02 19:53:47  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.2  2000/02/06 07:47:23  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.1.1.1  1999/11/09 01:09:31  twl
 * Initial checkin
 *
 * Revision 1.8  1999/11/08 20:43:40  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include "SAXCount.hpp"
#include <xercesc/sax/AttributeList.hpp>
#include <xercesc/sax/SAXParseException.hpp>
#include <xercesc/sax/SAXException.hpp>

// ---------------------------------------------------------------------------
//  SAXCountHandlers: Constructors and Destructor
// ---------------------------------------------------------------------------
SAXCountHandlers::SAXCountHandlers() :

    fAttrCount(0)
    , fCharacterCount(0)
    , fElementCount(0)
    , fSpaceCount(0)
    , fSawErrors(false)
{
}

SAXCountHandlers::~SAXCountHandlers()
{
}

// ---------------------------------------------------------------------------
//  SAXCountHandlers: Implementation of the SAX DocumentHandler interface
// ---------------------------------------------------------------------------
void SAXCountHandlers::startElement(const   XMLCh* const    /* name */
                                    ,       AttributeList&  attributes)
{
    fElementCount++;
    fAttrCount += attributes.getLength();
}

void SAXCountHandlers::characters(  const   XMLCh* const    /* chars */
								    , const unsigned int    length)
{
    fCharacterCount += length;
}

void SAXCountHandlers::ignorableWhitespace( const   XMLCh* const /* chars */
										    , const unsigned int length)
{
    fSpaceCount += length;
}

void SAXCountHandlers::resetDocument()
{
    fAttrCount = 0;
    fCharacterCount = 0;
    fElementCount = 0;
    fSpaceCount = 0;
}

// ---------------------------------------------------------------------------
//  SAXCountHandlers: Overrides of the SAX ErrorHandler interface
// ---------------------------------------------------------------------------
void SAXCountHandlers::error(const SAXParseException& e)
{
    fSawErrors = true;
    XERCES_STD_QUALIFIER cerr << "\nError at file " << StrX(e.getSystemId())
		 << ", line " << e.getLineNumber()
		 << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
}

void SAXCountHandlers::fatalError(const SAXParseException& e)
{
    fSawErrors = true;
    XERCES_STD_QUALIFIER cerr << "\nFatal Error at file " << StrX(e.getSystemId())
		 << ", line " << e.getLineNumber()
		 << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
}

void SAXCountHandlers::warning(const SAXParseException& e)
{
    XERCES_STD_QUALIFIER cerr << "\nWarning at file " << StrX(e.getSystemId())
		 << ", line " << e.getLineNumber()
		 << ", char " << e.getColumnNumber()
         << "\n  Message: " << StrX(e.getMessage()) << XERCES_STD_QUALIFIER endl;
}

void SAXCountHandlers::resetErrors()
{
    fSawErrors = false;
}


text:
#ifndef ALIANALYSISTASKJETSFINDER_H
#define ALIANALYSISTASKJETSFINDER_H

//----------------------------------------------------------------
// Analysis task for interfacing the jet finders with the analysis framework
//
// Author: magali.estienne@subatech.in2p3.fr
//	   alexandre.shabetai@cern.ch
//----------------------------------------------------------------

#include "AliAnalysisTaskSE.h"
#include "AliJetCalTrk.h"

class AliJetFinder;
class AliJetHistos;
class AliAODExtension;
class TTree;
class TString;

class AliAnalysisTaskJetsFinder : public AliAnalysisTaskSE
{
 public:
  AliAnalysisTaskJetsFinder();
  AliAnalysisTaskJetsFinder(const char* name);
  virtual             ~AliAnalysisTaskJetsFinder();
  // Implementation of interface methods
  virtual void        UserCreateOutputObjects();
  virtual void        Init();
  virtual Bool_t      Notify();
  virtual void        LocalInit() {Init();}
  virtual void        ConnectInputData(Option_t *);
  virtual void        UserExec(Option_t *option);
  virtual void        SetConfigFile(const char *c) {fConfigFile = c;}
  virtual void        SetJetFinder(AliJetFinder *finder) {fJetFinder = finder;}
  virtual void        SetNonStdBranch(const char *c){fNonStdBranch = c;}
  virtual const char* GetNonStdBranch(){return fNonStdBranch.Data();}
  virtual void        SetNonStdOutputFile(const char *c){fNonStdFile = c;}
  virtual const char* GetNonStdOutputFile() {return fNonStdFile.Data();}
  virtual void        SetBookAODBackground(Bool_t b){fUseAODBackground = b;}
  virtual void        Terminate(Option_t *option);
  virtual void        SetFilterPt(Float_t f){fFilterPt = f;}

  AliJetFinder*       GetJetFinder() {return fJetFinder;}

 private:
  AliAnalysisTaskJetsFinder(const AliAnalysisTaskJetsFinder &det);
  AliAnalysisTaskJetsFinder &operator=(const AliAnalysisTaskJetsFinder &det);

  TString             fConfigFile;        //  The name of the ConfigFile
  TString             fNonStdBranch;      //  The name of the non-std branch name
  TString             fNonStdFile;        //  The optional name of the output file the non-std brnach is written to
  AliJetFinder*       fJetFinder;         //  Pointer to the jet finder
  AliJetHistos*       fHistos;            //! Histogram manager class
  AliAODExtension*    fAODExtension;      //  AOD extension in case we write a non-sdt brnach to a separate file and the aod is standard
  TList*              fListOfHistos;      //! Output list of histograms
  TTree*              fTreeI;             //! Input Tree
  AliJetCalTrkEvent*  fEvent;             //! Pointer to jet input objects
  Bool_t              fUseAODBackground;  //  Decide wether we book the backround branch or not
  Float_t             fFilterPt;          //  Use this as a switch for writing the AOD, minium p_T of leading jet

  ClassDef(AliAnalysisTaskJetsFinder, 1)  // Jet Finder Analysis task

};

#endif


text:
package me.lucko.luckperms.nukkit.calculator;

import me.lucko.luckperms.common.cacheddata.result.TristateResult;
import me.lucko.luckperms.common.calculator.processor.AbstractSourceBasedProcessor;
import me.lucko.luckperms.common.calculator.processor.PermissionProcessor;
import me.lucko.luckperms.nukkit.LPNukkitPlugin;

import net.luckperms.api.util.Tristate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Permission Processor for Nukkits "child" permission system.
 */
public class ChildProcessor extends AbstractSourceBasedProcessor implements PermissionProcessor {
    private static final TristateResult.Factory RESULT_FACTORY = new TristateResult.Factory(ChildProcessor.class);

    private final LPNukkitPlugin plugin;
    private final AtomicBoolean needsRefresh = new AtomicBoolean(false);
    private Map<String, TristateResult> childPermissions = Collections.emptyMap();

    public ChildProcessor(LPNukkitPlugin plugin) {
        this.plugin = plugin;
    }

    @Override
    public TristateResult hasPermission(String permission) {
        if (this.needsRefresh.compareAndSet(true, false)) {
            refresh();
        }
        return this.childPermissions.getOrDefault(permission, TristateResult.UNDEFINED);
    }

    @Override
    public void refresh() {
        Map<String, TristateResult> childPermissions = new HashMap<>();
        this.sourceMap.forEach((key, node) -> {
            Map<String, Boolean> children = this.plugin.getPermissionMap().getChildPermissions(key, node.getValue());
            children.forEach((childKey, childValue) -> {
                childPermissions.put(childKey, RESULT_FACTORY.resultWithOverride(node, Tristate.of(childValue)));
            });
        });
        this.childPermissions = childPermissions;
        this.needsRefresh.set(false);
    }

    @Override
    public void invalidate() {
        this.needsRefresh.set(true);
    }
}


text:
class Node(object):
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight

class Solution(object):
    def construct(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: Node
        """
        def dfs(grid, x, y, l):
            if l == 1:
                return Node(grid[x][y] == 1, True, None, None, None, None)
            half = l // 2
            topLeftNode = dfs(grid, x, y, half)
            topRightNode = dfs(grid, x, y+half, half)
            bottomLeftNode = dfs(grid, x+half, y, half)
            bottomRightNode = dfs(grid, x+half, y+half, half)
            if topLeftNode.isLeaf and topRightNode.isLeaf and \
               bottomLeftNode.isLeaf and bottomRightNode.isLeaf and \
               topLeftNode.val == topRightNode.val == bottomLeftNode.val == bottomRightNode.val:
                return Node(topLeftNode.val, True, None, None, None, None)
            return Node(True, False, topLeftNode, topRightNode, bottomLeftNode, bottomRightNode)

        if not grid:
            return None
        return dfs(grid, 0, 0, len(grid))


text:
package net.wasdev.gameon.concierge;

import net.wasdev.gameon.room.common.Room;

public interface PlacementStrategy {
	void placeRoom(Room room);

	String getConnectingRooms(String currentRoomId, String exitName);
}


text:
local shell_blocking_capture_combined = require("shell-games").capture_combined
local status = require "api-umbrella.cli.status"
local time = require "posix.time"

local function stop_perp()
  local running, pid = status()
  if not running then
    print "api-umbrella is already stopped"
    return true
  end

  local _, err = shell_blocking_capture_combined({ "kill", "-s", "TERM", pid })
  if err then
    return false, err
  end

  -- After sending the kill command, wait for everything to actually
  -- shutdown. This allows us to more easily handle restarts (since we can
  -- ensure everything is stopped before calling start).
  --
  -- Wait up to 40 seconds.
  local stopped = false
  for _ = 1, 200 do
    running, _ = status()
    if running then
      -- Sleep for 0.2 seconds.
      time.nanosleep({ tv_sec = 0, tv_nsec = 200000000 })
    else
      stopped = true
      break
    end
  end

  if not stopped then
    return false, "failed to stop"
  end

  return true
end

return function()
  return stop_perp()
end


text:
package ch.huber.typescript.definitions.test;

/**
 * @author christoph.huber
 * @since 08.12.2015
 */
public class TestConstants {
    public static final String TYPESCRIPT_WITHOUT_MODULE = "greeter.ts";
    public static final String TYPESCRIPT_WITH_MODULE = "chart/data.ts";

    public static final String TYPESCRIPT_TEST_MODULE_DEFINITION = "testModule/test.d.ts";
    public static final String TYPESCRIPT_OTHER_DEFINITION = "testModule/dir/_all.d.ts";
    public static final String TYPESCRIPT_TEST_FILE1 = "testModule/dir/file.ts";
    public static final String TYPESCRIPT_TEST_FILE2 = "testModule/dir2/file.ts";
}


text:
var ComName = (function() {
  //private
  var
    config = {},
    win = {},
    toolbar = {};
  //public
  return {
    start: function(_config) {
      // start function
    },
    validate_start: function(_config) {
      // check for all component required fields
    }
  }
}());


text:
import _Ajv from "../ajv"
import {KeywordDefinition, SchemaValidateFunction} from "../../dist/types"
import chai from "../chai"
chai.should()

describe("issue #181, user-defined keyword is not validated in allErrors mode if there were previous error", () => {
  it("should validate user-defined keyword that doesn't create errors", () => {
    testKeywordErrors({
      keyword: "alwaysFails",
      type: "object",
      errors: true,
      validate: function v(/* value */) {
        return false
      },
    })
  })

  it("should validate keyword that creates errors", () => {
    const validate: SchemaValidateFunction = (/* value */) => {
      validate.errors = validate.errors || []
      validate.errors.push({
        keyword: "alwaysFails",
        message: "alwaysFails error",
        params: {
          keyword: "alwaysFails",
        },
      })
      return false
    }

    testKeywordErrors({
      keyword: "alwaysFails",
      type: "object",
      errors: true,
      validate,
    })
  })

  function testKeywordErrors(def: KeywordDefinition): void {
    const ajv = new _Ajv({allErrors: true})

    ajv.addKeyword(def)

    const schema = {
      type: "object",
      required: ["foo"],
      alwaysFails: true,
    }

    const validate: any = ajv.compile(schema)

    validate({foo: 1}).should.equal(false)
    validate.errors.should.have.length(1)
    validate.errors[0].keyword.should.equal("alwaysFails")

    validate({}).should.equal(false)
    validate.errors.should.have.length(2)
    validate.errors[0].keyword.should.equal("required")
    validate.errors[1].keyword.should.equal("alwaysFails")
  }
})


text:
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Defines a simple strategy for parsing text and converting
 * it into a Macro.
 */

import {InputController} from '../input_controller.js';
import {LocaleInfo} from '../locale_info.js';
import {DeletePrevSentMacro} from '../macros/delete_prev_sent_macro.js';
import {HiddenMacroManager} from '../macros/hidden_macro_manager.js';
import {InputTextViewMacro, NewLineMacro} from '../macros/input_text_view_macro.js';
import {ListCommandsMacro} from '../macros/list_commands_macro.js';
import {Macro} from '../macros/macro.js';
import {MacroName} from '../macros/macro_names.js';
import {NavNextSentMacro, NavPrevSentMacro} from '../macros/nav_sent_macro.js';
import * as RepeatableKeyPress from '../macros/repeatable_key_press_macro.js';
import {SmartDeletePhraseMacro} from '../macros/smart_delete_phrase_macro.js';
import {SmartInsertBeforeMacro} from '../macros/smart_insert_before_macro.js';
import {SmartReplacePhraseMacro} from '../macros/smart_replace_phrase_macro.js';
import {SmartSelectBetweenMacro} from '../macros/smart_select_between_macro.js';
import {StopListeningMacro} from '../macros/stop_listening_macro.js';

import {ParseStrategy} from './parse_strategy.js';

/**
 * @typedef {{
 *   messageId: string,
 *   build: !Function,
 * }}
 */
let MacroData;

/**
 * SimpleMacroFactory converts spoken strings into Macros using string matching.
 */
class SimpleMacroFactory {
  /**
   * @param {!MacroName} macroName
   * @param {!InputController} inputController
   */
  constructor(macroName, inputController) {
    if (!SimpleMacroFactory.getData_()[macroName]) {
      throw new Error(
          'Macro is not supported by SimpleMacroFactory: ' + macroName);
    }

    /** @private {!MacroName} */
    this.macroName_ = macroName;
    /** @private {!InputController} */
    this.inputController_ = inputController;

    /** @private {RegExp} */
    this.commandRegex_ = null;
    this.initializeCommandRegex_(this.macroName_);
  }

  /**
   * Builds a RegExp that can be used to parse a command. For example, the
   * SmartReplacePhraseMacro can be parsed with the pattern:
   * /replace (.*) with (.*)/i.
   * @param {!MacroName} macroName
   * @private
   */
  initializeCommandRegex_(macroName) {
    const matchAnythingPattern = '(.*)';
    const args = [];
    switch (macroName) {
      case MacroName.INPUT_TEXT_VIEW:
      case MacroName.SMART_DELETE_PHRASE:
        args.push(matchAnythingPattern);
        break;
      case MacroName.SMART_REPLACE_PHRASE:
      case MacroName.SMART_INSERT_BEFORE:
      case MacroName.SMART_SELECT_BTWN_INCL:
        args.push(matchAnythingPattern, matchAnythingPattern);
        break;
    }
    const message = chrome.i18n.getMessage(
        SimpleMacroFactory.getData_()[macroName].messageId, args);
    const pattern = `^${message}$`;
    if (LocaleInfo.considerSpaces()) {
      this.commandRegex_ = new RegExp(pattern, 'i');
    } else {
      // A regex to be used if the Dictation language doesn't use spaces e.g.
      // Japanese.
      this.commandRegex_ = new RegExp(pattern.replace(/\s+/g, ''), 'i');
    }
  }

  /**
   * @param {string} text
   * @return {Macro|null}
   */
  createMacro(text) {
    // Check whether `text` matches `this.commandRegex_`, ignoring case and
    // whitespace.
    text = text.trim().toLowerCase();
    if (!this.commandRegex_.test(text)) {
      return null;
    }

    const initialArgs = [];
    switch (this.macroName_) {
      case MacroName.NEW_LINE:
      case MacroName.DELETE_PREV_SENT:
      case MacroName.NAV_NEXT_SENT:
      case MacroName.NAV_PREV_SENT:
      case MacroName.SMART_DELETE_PHRASE:
      case MacroName.SMART_REPLACE_PHRASE:
      case MacroName.SMART_INSERT_BEFORE:
      case MacroName.SMART_SELECT_BTWN_INCL:
        initialArgs.push(this.inputController_);
        break;
    }

    const result = this.commandRegex_.exec(text);
    // `result[0]` contains the entire matched text, while all subsequent
    // indices contain text matched by each /(.*)/. We're only interested in
    // text matched by /(.*)/, so ignore `result[0]`.
    const extractedArgs = result.slice(1);
    const finalArgs = initialArgs.concat(extractedArgs);
    const data = SimpleMacroFactory.getData_();
    const macro = new data[this.macroName_].build(...finalArgs);
    if (macro.isSmart() && !LocaleInfo.allowSmartEditing()) {
      return null;
    }

    return macro;
  }

  /**
   * Returns data that is used to create a macro. `messageId` is used to
   * retrieve the macro's command string and `build` is used to construct the
   * macro.
   * @return {Object<MacroName, MacroData>}
   * @private
   */
  static getData_() {
    return {
      [MacroName.DELETE_PREV_CHAR]: {
        messageId: 'dictation_command_delete_prev_char',
        build: RepeatableKeyPress.DeletePreviousCharacterMacro,
      },
      [MacroName.NAV_PREV_CHAR]: {
        messageId: 'dictation_command_nav_prev_char',
        build: RepeatableKeyPress.NavPreviousCharMacro,
      },
      [MacroName.NAV_NEXT_CHAR]: {
        messageId: 'dictation_command_nav_next_char',
        build: RepeatableKeyPress.NavNextCharMacro,
      },
      [MacroName.NAV_PREV_LINE]: {
        messageId: 'dictation_command_nav_prev_line',
        build: RepeatableKeyPress.NavPreviousLineMacro,
      },
      [MacroName.NAV_NEXT_LINE]: {
        messageId: 'dictation_command_nav_next_line',
        build: RepeatableKeyPress.NavNextLineMacro,
      },
      [MacroName.COPY_SELECTED_TEXT]: {
        messageId: 'dictation_command_copy_selected_text',
        build: RepeatableKeyPress.CopySelectedTextMacro,
      },
      [MacroName.PASTE_TEXT]: {
        messageId: 'dictation_command_paste_text',
        build: RepeatableKeyPress.PasteTextMacro,
      },
      [MacroName.CUT_SELECTED_TEXT]: {
        messageId: 'dictation_command_cut_selected_text',
        build: RepeatableKeyPress.CutSelectedTextMacro,
      },
      [MacroName.UNDO_TEXT_EDIT]: {
        messageId: 'dictation_command_undo_text_edit',
        build: RepeatableKeyPress.UndoTextEditMacro,
      },
      [MacroName.REDO_ACTION]: {
        messageId: 'dictation_command_redo_action',
        build: RepeatableKeyPress.RedoActionMacro,
      },
      [MacroName.SELECT_ALL_TEXT]: {
        messageId: 'dictation_command_select_all_text',
        build: RepeatableKeyPress.SelectAllTextMacro,
      },
      [MacroName.UNSELECT_TEXT]: {
        messageId: 'dictation_command_unselect_text',
        build: RepeatableKeyPress.UnselectTextMacro,
      },
      [MacroName.LIST_COMMANDS]: {
        messageId: 'dictation_command_list_commands',
        build: ListCommandsMacro,
      },
      [MacroName.NEW_LINE]:
          {messageId: 'dictation_command_new_line', build: NewLineMacro},
      [MacroName.STOP_LISTENING]: {
        messageId: 'dictation_command_stop_listening',
        build: StopListeningMacro,
      },
      [MacroName.DELETE_PREV_WORD]: {
        messageId: 'dictation_command_delete_prev_word',
        build: RepeatableKeyPress.DeletePrevWordMacro,
      },
      [MacroName.DELETE_PREV_SENT]: {
        messageId: 'dictation_command_delete_prev_sent',
        build: DeletePrevSentMacro,
      },
      [MacroName.NAV_NEXT_WORD]: {
        messageId: 'dictation_command_nav_next_word',
        build: RepeatableKeyPress.NavNextWordMacro,
      },
      [MacroName.NAV_PREV_WORD]: {
        messageId: 'dictation_command_nav_prev_word',
        build: RepeatableKeyPress.NavPrevWordMacro,
      },
      [MacroName.SMART_DELETE_PHRASE]: {
        messageId: 'dictation_command_smart_delete_phrase',
        build: SmartDeletePhraseMacro,
      },
      [MacroName.SMART_REPLACE_PHRASE]: {
        messageId: 'dictation_command_smart_replace_phrase',
        build: SmartReplacePhraseMacro,
      },
      [MacroName.SMART_INSERT_BEFORE]: {
        messageId: 'dictation_command_smart_insert_before',
        build: SmartInsertBeforeMacro,
      },
      [MacroName.SMART_SELECT_BTWN_INCL]: {
        messageId: 'dictation_command_smart_select_btwn_incl',
        build: SmartSelectBetweenMacro,
      },
      [MacroName.NAV_NEXT_SENT]: {
        messageId: 'dictation_command_nav_next_sent',
        build: NavNextSentMacro,
      },
      [MacroName.NAV_PREV_SENT]: {
        messageId: 'dictation_command_nav_prev_sent',
        build: NavPrevSentMacro,
      },
    };
  }
}

/** A parsing strategy that utilizes SimpleMacroFactory. */
export class SimpleParseStrategy extends ParseStrategy {
  /** @param {!InputController} inputController */
  constructor(inputController) {
    super(inputController);

    /**
     * Map of macro names to a factory for that macro.
     * @private {!Map<MacroName, !SimpleMacroFactory>}
     */
    this.macroFactoryMap_ = new Map();

    this.initialize_();
  }

  /** @private */
  initialize_() {
    for (const key in MacroName) {
      const name = MacroName[key];
      if (HiddenMacroManager.isHiddenMacro(name) ||
          name === MacroName.INPUT_TEXT_VIEW ||
          name === MacroName.UNSPECIFIED) {
        continue;
      }

      this.macroFactoryMap_.set(
          name, new SimpleMacroFactory(name, this.getInputController()));
    }
  }

  /** @override */
  async parse(text) {
    const macros = [];
    for (const [name, factory] of this.macroFactoryMap_) {
      const macro = factory.createMacro(text);
      if (macro) {
        macros.push(macro);
      }
    }
    if (macros.length === 1) {
      return macros[0];
    } else if (macros.length === 2) {
      // Pick which macro to use from the list of matched macros.
      // TODO(crbug.com/1288965): Turn this into a disambiguation class as we
      // add more commands. Currently the only ambiguous macro is DELETE_PHRASE
      // which conflicts with other deletion macros. For example, the phrase
      // "Delete the previous word" should be parsed as a DELETE_PREV_WORD
      // instead of SMART_DELETE_PHRASE with phrase "the previous word".
      // Prioritize other deletion macros over SMART_DELETE_PHRASE.
      return macros[0].getMacroName() === MacroName.SMART_DELETE_PHRASE ?
          macros[1] :
          macros[0];
    } else if (macros.length > 2) {
      console.warn(`Unexpected ambiguous macros found for text: ${text}.`);
      return macros[0];
    }

    // The command is simply to input the given text.
    // If `text` starts with `type`, then automatically remove it e.g. convert
    // 'Type testing 123' to 'testing 123'.
    const typePrefix =
        chrome.i18n.getMessage('dictation_command_input_text_view');
    if (text.trim().toLowerCase().startsWith(typePrefix)) {
      text = text.toLowerCase().replace(typePrefix, '').trimStart();
    }

    return new InputTextViewMacro(text, this.getInputController());
  }
}


text:
package com.gemstone.gemfire.internal.cache.wan.concurrent;

@SuppressWarnings("serial")
public class ConcurrentParallelGatewaySenderOffHeapDUnitTest extends
    ConcurrentParallelGatewaySenderDUnitTest {

  public ConcurrentParallelGatewaySenderOffHeapDUnitTest(String name) {
    super(name);
  }

  @Override
  public boolean isOffHeap() {
    return true;
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace _04.Match_Dates
{
    class Program
    {
        public static void Main()
        {
            string pattern = @"(\b\d{2})(\/|-|.)([A-Z][a-z]+)\2(\d{4})";
            string input = Console.ReadLine();

            foreach (Match date in Regex.Matches(input, pattern))
            {
                Console.Write("Day: {0}, ", date.Groups[1]);
                Console.Write("Month: {0}, ", date.Groups[3]);
                Console.WriteLine("Year: {0}", date.Groups[4]);
            }
        }
    }
}


text:
package com.ugg.gdxjam.model.utils;

import com.badlogic.gdx.ai.steer.Steerable;
import com.badlogic.gdx.ai.steer.SteeringBehavior;
import com.badlogic.gdx.ai.steer.behaviors.Arrive;
import com.badlogic.gdx.ai.steer.behaviors.Face;
import com.badlogic.gdx.ai.steer.behaviors.Seek;
import com.badlogic.gdx.math.Vector2;
import com.ugg.gdxjam.model.SteerLocation;

/**
 * Created by Jose Cuellar on 10/01/2016.
 */
public final class BehaviorUtils {

    public static SteerLocation getTarget(SteeringBehavior behavior){
        SteerLocation targetL = null;
        if(behavior instanceof Face) targetL = (SteerLocation)((Face) behavior).getTarget();
        else if(behavior instanceof Arrive) targetL = (SteerLocation)((Arrive) behavior).getTarget();
        else if(behavior instanceof Seek) targetL = (SteerLocation)((Seek) behavior).getTarget();
        return targetL;
    }

    public static Arrive createArrive(float x, float y, Steerable steerable){
        SteerLocation loc = new SteerLocation();
        loc.getPosition().set(x, y);
        Arrive arrive = new Arrive(steerable, loc);
            arrive.setTarget(loc);

        arrive.setOwner(steerable);
        return arrive;
    }
}


text:
<ion-view title="ProspectWise" hide-back-button="true" style="background-color:#6ebde7;">
    <ion-nav-buttons side="left">
        <button menu-toggle="left"class="button button-icon ion-navicon-round"></button>
    </ion-nav-buttons>
    <ion-content class="has-header" style="margin-top:-40px;">
        <ion-slide-box show-pager="false">
            <ion-slide style="background-color:#6ebde7;">

Introducing
A TRUE
 lead generation system

Our taskers collect data by physically visiting the brick and mortar stores

Try 100 of Our Leads Free

Try 100 of our real-time custom leads, free of charge, no obligations, no credit card necessary.

            </ion-slide>
            <ion-slide style="background-color:#6ebde7;">

Using Awesome

Just three steps:

Be awesome

Stay awesome

There is no step 3

            </ion-slide>
        </ion-slide-box>
    </ion-content>
</ion-view>


text:
using System;
using System.Windows.Media;
using Pfz.AnimationManagement.Abstract;

namespace Pfz.AnimationManagement.Wpf
{
    public sealed class ColorSpeedToDurationCalculator:
        SpeedToDurationCalculator<Color>
    {
		static ColorSpeedToDurationCalculator()
        {
            Initializer.Initialize();
        }

        private static readonly ColorSpeedToDurationCalculator _instance = new ColorSpeedToDurationCalculator();
        public static ColorSpeedToDurationCalculator Instance
        {
            get
            {
                return _instance;
            }
        }

        public static void RegisterAsDefault()
        {
            Default = _instance;
        }

        private ColorSpeedToDurationCalculator()
        {
        }

        public override TimeSpan CalculateDuration(Color initialValue, Color finalValue, double speed)
        {
            double a = Math.Abs(finalValue.A - initialValue.A);
            double r = Math.Abs(finalValue.R - initialValue.R);
            double g = Math.Abs(finalValue.G - initialValue.G);
            double b = Math.Abs(finalValue.B - initialValue.B);

            double maxValue = Math.Max(a, Math.Max(r, Math.Max(g, b)));
            return TimeSpan.FromSeconds(maxValue / speed);
        }
    }
}


text:
houses = ["Stark", "Lannister", "Baratheon", "Greyjoy"]
seats = ["Winterfell", "Casterly Rock", "Storm's End", "Pyke"]
sigils = ["A Gray Direwolf", "A Golden Lion",
          "A Crowned Black Stag", "A Golden Kraken"]
words = ["Winter is coming", "Hear me roar !",
         "Our is the fury !", "We do not sow"]

print(f"houses : {houses}")
print(f"seats : {seats}")
print(f"sigils : {sigils}")
print(f"words : {words}")

print("\n###########\n")

print(
    f"zip(houses, seats, sigils, words) en tant que liste : \n{list(zip(houses, seats, sigils, words))}", )
print("\nunpacking de zip(houses, seats, sigils, words) :\n",
      *zip(houses, seats, sigils, words))

print("\n###########\n")

print("Affichage de chacun des éléments de la séquence zip(houses, seats, sigils, words) via un for :")
for got_house_info in zip(houses, seats, sigils, words):
    print(got_house_info)

print("\n###########\n")

print("Utilisation dans une compréhension")
print("\n".join([f"{house} : {word}" for house, _,
                 _, word in zip(houses, seats, sigils, words)]))

print("\n###########\n")

print("Réalisation d'un 'unzip' et retour à la situation initiale")

print("zip(*zip(houses, seats, sigils, words)) comme liste : ",
      list(zip(*zip(houses, seats, sigils, words))))

print("\nunpacking de zip(*zip(houses, seats, sigils, words)) :")
houses_2, seats_2, sigils_2, words_2 = zip(*zip(houses, seats, sigils, words))

print(f"=> houses_2 : {houses_2}")
print(f"=> seats_2 : {seats_2}")
print(f"=> sigils_2 : {sigils_2}")
print(f"=> seats_2 : {words_2}")


text:
"""Test cases for the API stream sensor."""

from homeassistant.bootstrap import async_setup_component

from .test_auth import test_auth_active_with_token

from tests.common import assert_setup_component

async def test_websocket_api(
    hass, no_auth_websocket_client, hass_access_token, legacy_auth
):
    """Test API streams."""
    with assert_setup_component(1):
        await async_setup_component(
            hass, "sensor", {"sensor": {"platform": "websocket_api"}}
        )

    state = hass.states.get("sensor.connected_clients")
    assert state.state == "0"

    await test_auth_active_with_token(hass, no_auth_websocket_client, hass_access_token)

    state = hass.states.get("sensor.connected_clients")
    assert state.state == "1"

    await no_auth_websocket_client.close()
    await hass.async_block_till_done()

    state = hass.states.get("sensor.connected_clients")
    assert state.state == "0"


text:
You need to set your authorization endpoint in a <link> tag on your home page.

You can create your own authorization endpoint, or you can use an existing service such as IndieAuth.com. To delegate to IndieAuth.com, place the markup below on your home page (or at the URL you are using as your web sign-in address).

<link rel="authorization_endpoint"
        href="https://indieauth.com/auth">


text:
package gocbcore

import (
	"encoding/json"
	"fmt"
	"net"
	"strings"
)

// RestPool represents a single pool returned from the pools REST API.
type cfgRestPool struct {
	Name         string `json:"name"`
	StreamingURI string `json:"streamingUri"`
	URI          string `json:"uri"`
}

// A Node is a computer in a cluster running the couchbase software.
type cfgNode struct {
	ClusterCompatibility int                `json:"clusterCompatibility"`
	ClusterMembership    string             `json:"clusterMembership"`
	CouchAPIBase         string             `json:"couchApiBase"`
	Hostname             string             `json:"hostname"`
	InterestingStats     map[string]float64 `json:"interestingStats,omitempty"`
	MCDMemoryAllocated   float64            `json:"mcdMemoryAllocated"`
	MCDMemoryReserved    float64            `json:"mcdMemoryReserved"`
	MemoryFree           float64            `json:"memoryFree"`
	MemoryTotal          float64            `json:"memoryTotal"`
	OS                   string             `json:"os"`
	Ports                map[string]int     `json:"ports"`
	Status               string             `json:"status"`
	Uptime               int                `json:"uptime,string"`
	Version              string             `json:"version"`
	ThisNode             bool               `json:"thisNode,omitempty"`
}

type cfgNodeServices struct {
	Kv      uint16 `json:"kv"`
	Capi    uint16 `json:"capi"`
	Mgmt    uint16 `json:"mgmt"`
	N1ql    uint16 `json:"n1ql"`
	Fts     uint16 `json:"fts"`
	Cbas    uint16 `json:"cbas"`
	KvSsl   uint16 `json:"kvSSL"`
	CapiSsl uint16 `json:"capiSSL"`
	MgmtSsl uint16 `json:"mgmtSSL"`
	N1qlSsl uint16 `json:"n1qlSSL"`
	FtsSsl  uint16 `json:"ftsSSL"`
	CbasSsl uint16 `json:"cbasSSL"`
}

type cfgNodeAltAddress struct {
	Ports    *cfgNodeServices `json:"ports,omitempty"`
	Hostname string           `json:"hostname"`
}
type cfgNodeExt struct {
	Services     cfgNodeServices              `json:"services"`
	Hostname     string                       `json:"hostname"`
	AltAddresses map[string]cfgNodeAltAddress `json:"alternateAddresses"`
}

// VBucketServerMap is the a mapping of vbuckets to nodes.
type cfgVBucketServerMap struct {
	HashAlgorithm string   `json:"hashAlgorithm"`
	NumReplicas   int      `json:"numReplicas"`
	ServerList    []string `json:"serverList"`
	VBucketMap    [][]int  `json:"vBucketMap"`
}

// Bucket is the primary entry point for most data operations.
type cfgBucket struct {
	Rev                 int64 `json:"rev"`
	SourceHostname      string
	Capabilities        []string `json:"bucketCapabilities"`
	CapabilitiesVersion string   `json:"bucketCapabilitiesVer"`
	Name                string   `json:"name"`
	NodeLocator         string   `json:"nodeLocator"`
	URI                 string   `json:"uri"`
	StreamingURI        string   `json:"streamingUri"`
	UUID                string   `json:"uuid"`
	DDocs               struct {
		URI string `json:"uri"`
	} `json:"ddocs,omitempty"`

	// These are used for JSON IO, but isn't used for processing
	// since it needs to be swapped out safely.
	VBucketServerMap       cfgVBucketServerMap `json:"vBucketServerMap"`
	Nodes                  []cfgNode           `json:"nodes"`
	NodesExt               []cfgNodeExt        `json:"nodesExt,omitempty"`
	ClusterCapabilitiesVer []int               `json:"clusterCapabilitiesVer,omitempty"`
	ClusterCapabilities    map[string][]string `json:"clusterCapabilities,omitempty"`
}

// Cluster is an entry point for service level operations.
type cfgCluster struct {
	Rev            int64 `json:"rev"`
	SourceHostname string

	// These are used for JSON IO, but isn't used for processing
	// since it needs to be swapped out safely.
	NodesExt               []cfgNodeExt        `json:"nodesExt,omitempty"`
	ClusterCapabilitiesVer []int               `json:"clusterCapabilitiesVer,omitempty"`
	ClusterCapabilities    map[string][]string `json:"clusterCapabilities,omitempty"`
}

type cfgType uint8

const (
	bktCfgType     = cfgType(0)
	clusterCfgType = cfgType(1)
)

type cfgObj interface {
	Type() cfgType
	BuildRouteConfig(useSsl bool, networkType string, firstConnect bool) *routeConfig
	ClusterCaps() map[string][]string
	ClusterCapsVer() []int
}

func (cfg *cfgCluster) Type() cfgType {
	return clusterCfgType
}

func (cfg *cfgCluster) ClusterCaps() map[string][]string {
	return cfg.ClusterCapabilities
}

func (cfg *cfgCluster) ClusterCapsVer() []int {
	return cfg.ClusterCapabilitiesVer
}

func (cfg *cfgCluster) BuildRouteConfig(useSsl bool, networkType string, firstConnect bool) *routeConfig {
	var kvServerList []string
	var capiEpList []string
	var mgmtEpList []string
	var n1qlEpList []string
	var ftsEpList []string
	var cbasEpList []string

	if cfg.NodesExt != nil {
		for _, node := range cfg.NodesExt {
			hostname := node.Hostname
			ports := node.Services

			if networkType != "default" {
				if altAddr, ok := node.AltAddresses[networkType]; ok {
					hostname = altAddr.Hostname
					if altAddr.Ports != nil {
						ports = *altAddr.Ports
					}
				} else {
					if !firstConnect {
						logDebugf("Invalid config network type %s", networkType)
					}
					continue
				}
			}

			hostname = getHostname(hostname, cfg.SourceHostname)

			endpoints := endpointsFromPorts(useSsl, ports, "", hostname)
			if endpoints.kvServer != "" {
				kvServerList = append(kvServerList, endpoints.kvServer)
			}
			if endpoints.capiEp != "" {
				capiEpList = append(capiEpList, endpoints.capiEp)
			}
			if endpoints.mgmtEp != "" {
				mgmtEpList = append(mgmtEpList, endpoints.mgmtEp)
			}
			if endpoints.n1qlEp != "" {
				n1qlEpList = append(n1qlEpList, endpoints.n1qlEp)
			}
			if endpoints.ftsEp != "" {
				ftsEpList = append(ftsEpList, endpoints.ftsEp)
			}
			if endpoints.cbasEp != "" {
				cbasEpList = append(cbasEpList, endpoints.cbasEp)
			}
		}
	} else {
		if useSsl {
			logErrorf("Received config without nodesExt while for GCCCP config.  Generating invalid config.")
			return &routeConfig{}
		}
	}

	rc := &routeConfig{
		revID:        cfg.Rev,
		kvServerList: kvServerList,
		capiEpList:   capiEpList,
		mgmtEpList:   mgmtEpList,
		n1qlEpList:   n1qlEpList,
		ftsEpList:    ftsEpList,
		cbasEpList:   cbasEpList,
		bktType:      bktTypeNone,
	}

	return rc
}

func (cfg *cfgBucket) Type() cfgType {
	return bktCfgType
}

func (cfg *cfgBucket) supports(needleCap string) bool {
	for _, cap := range cfg.Capabilities {
		if cap == needleCap {
			return true
		}
	}
	return false
}

func (cfg *cfgBucket) supportsCccp() bool {
	return cfg.supports("cccp")
}

func (cfg *cfgBucket) BuildRouteConfig(useSsl bool, networkType string, firstConnect bool) *routeConfig {
	var kvServerList []string
	var capiEpList []string
	var mgmtEpList []string
	var n1qlEpList []string
	var ftsEpList []string
	var cbasEpList []string
	var bktType bucketType

	switch cfg.NodeLocator {
	case "ketama":
		bktType = bktTypeMemcached
	case "vbucket":
		bktType = bktTypeCouchbase
	default:
		logDebugf("Invalid nodeLocator %s", cfg.NodeLocator)
		bktType = bktTypeInvalid
	}

	if cfg.NodesExt != nil {
		lenNodes := len(cfg.Nodes)
		for i, node := range cfg.NodesExt {
			hostname := node.Hostname
			ports := node.Services

			if networkType != "default" {
				if altAddr, ok := node.AltAddresses[networkType]; ok {
					hostname = altAddr.Hostname
					if altAddr.Ports != nil {
						ports = *altAddr.Ports
					}
				} else {
					if !firstConnect {
						logDebugf("Invalid config network type %s", networkType)
					}
					continue
				}
			}

			hostname = getHostname(hostname, cfg.SourceHostname)

			endpoints := endpointsFromPorts(useSsl, ports, cfg.Name, hostname)
			if endpoints.kvServer != "" {
				if i >= lenNodes {
					logDebugf("KV node present in nodesext but not in nodes for %s", endpoints.kvServer)
				} else {
					kvServerList = append(kvServerList, endpoints.kvServer)
				}
			}
			if endpoints.capiEp != "" {
				capiEpList = append(capiEpList, endpoints.capiEp)
			}
			if endpoints.mgmtEp != "" {
				mgmtEpList = append(mgmtEpList, endpoints.mgmtEp)
			}
			if endpoints.n1qlEp != "" {
				n1qlEpList = append(n1qlEpList, endpoints.n1qlEp)
			}
			if endpoints.ftsEp != "" {
				ftsEpList = append(ftsEpList, endpoints.ftsEp)
			}
			if endpoints.cbasEp != "" {
				cbasEpList = append(cbasEpList, endpoints.cbasEp)
			}
		}
	} else {
		if useSsl {
			logErrorf("Received config without nodesExt while SSL is enabled.  Generating invalid config.")
			return &routeConfig{}
		}

		if bktType == bktTypeCouchbase {
			kvServerList = cfg.VBucketServerMap.ServerList
		}

		for _, node := range cfg.Nodes {
			if node.CouchAPIBase != "" {
				// Slice off the UUID as Go's HTTP client cannot handle being passed URL-Encoded path values.
				capiEp := strings.SplitN(node.CouchAPIBase, "%2B", 2)[0]

				capiEpList = append(capiEpList, capiEp)
			}
			if node.Hostname != "" {
				mgmtEpList = append(mgmtEpList, fmt.Sprintf("http://%s", node.Hostname))
			}

			if bktType == bktTypeMemcached {
				// Get the data port. No VBucketServerMap.
				host, err := hostFromHostPort(node.Hostname)
				if err != nil {
					logErrorf("Encountered invalid memcached host/port string. Ignoring node.")
					continue
				}

				curKvHost := fmt.Sprintf("%s:%d", host, node.Ports["direct"])
				kvServerList = append(kvServerList, curKvHost)
			}
		}
	}

	rc := &routeConfig{
		revID:        cfg.Rev,
		uuid:         cfg.UUID,
		kvServerList: kvServerList,
		capiEpList:   capiEpList,
		mgmtEpList:   mgmtEpList,
		n1qlEpList:   n1qlEpList,
		ftsEpList:    ftsEpList,
		cbasEpList:   cbasEpList,
		bktType:      bktType,
	}

	if bktType == bktTypeCouchbase {
		vbMap := cfg.VBucketServerMap.VBucketMap
		numReplicas := cfg.VBucketServerMap.NumReplicas
		rc.vbMap = newVbucketMap(vbMap, numReplicas)
	} else if bktType == bktTypeMemcached {
		rc.ketamaMap = newKetamaContinuum(kvServerList)
	}

	return rc
}

func (cfg *cfgBucket) ClusterCaps() map[string][]string {
	return cfg.ClusterCapabilities
}

func (cfg *cfgBucket) ClusterCapsVer() []int {
	return cfg.ClusterCapabilitiesVer
}

type serverEps struct {
	kvServer string
	capiEp   string
	mgmtEp   string
	n1qlEp   string
	ftsEp    string
	cbasEp   string
}

func getHostname(hostname, sourceHostname string) string {
	// Hostname blank means to use the same one as was connected to
	if hostname == "" {
		// Note that the SourceHostname will already be IPv6 wrapped
		hostname = sourceHostname
	} else {
		// We need to detect an IPv6 address here and wrap it in the appropriate
		// [] block to indicate its IPv6 for the rest of the system.
		if strings.Contains(hostname, ":") {
			hostname = "[" + hostname + "]"
		}
	}

	return hostname
}

func endpointsFromPorts(useSsl bool, ports cfgNodeServices, name, hostname string) *serverEps {
	lists := &serverEps{}

	if useSsl {
		if ports.KvSsl > 0 {
			lists.kvServer = fmt.Sprintf("%s:%d", hostname, ports.KvSsl)
		}
		if ports.Capi > 0 {
			lists.capiEp = fmt.Sprintf("http://%s:%d/%s", hostname, ports.CapiSsl, name)
		}
		if ports.Mgmt > 0 {
			lists.mgmtEp = fmt.Sprintf("http://%s:%d", hostname, ports.MgmtSsl)
		}
		if ports.N1ql > 0 {
			lists.n1qlEp = fmt.Sprintf("http://%s:%d", hostname, ports.N1qlSsl)
		}
		if ports.Fts > 0 {
			lists.ftsEp = fmt.Sprintf("http://%s:%d", hostname, ports.FtsSsl)
		}
		if ports.Cbas > 0 {
			lists.cbasEp = fmt.Sprintf("http://%s:%d", hostname, ports.CbasSsl)
		}
	} else {
		if ports.Kv > 0 {
			lists.kvServer = fmt.Sprintf("%s:%d", hostname, ports.Kv)
		}
		if ports.Capi > 0 {
			lists.capiEp = fmt.Sprintf("http://%s:%d/%s", hostname, ports.Capi, name)
		}
		if ports.Mgmt > 0 {
			lists.mgmtEp = fmt.Sprintf("http://%s:%d", hostname, ports.Mgmt)
		}
		if ports.N1ql > 0 {
			lists.n1qlEp = fmt.Sprintf("http://%s:%d", hostname, ports.N1ql)
		}
		if ports.Fts > 0 {
			lists.ftsEp = fmt.Sprintf("http://%s:%d", hostname, ports.Fts)
		}
		if ports.Cbas > 0 {
			lists.cbasEp = fmt.Sprintf("http://%s:%d", hostname, ports.Cbas)
		}
	}
	return lists
}

func hostFromHostPort(hostport string) (string, error) {
	host, _, err := net.SplitHostPort(hostport)
	if err != nil {
		return "", err
	}

	// If this is an IPv6 address, we need to rewrap it in []
	if strings.Contains(host, ":") {
		return "[" + host + "]", nil
	}

	return host, nil
}

func parseBktConfig(config []byte, srcHost string) (*cfgBucket, error) {
	bk := &cfgBucket{}
	err := parseConfig(config, srcHost, bk)
	if err != nil {
		return nil, err
	}

	bk.SourceHostname = srcHost
	return bk, nil
}

func parseClusterConfig(config []byte, srcHost string) (*cfgCluster, error) {
	bk := &cfgCluster{}
	err := parseConfig(config, srcHost, bk)
	if err != nil {
		return nil, err
	}

	bk.SourceHostname = srcHost
	return bk, nil
}

func parseConfig(config []byte, srcHost string, target cfgObj) error {
	configStr := strings.Replace(string(config), "$HOST", srcHost, -1)

	err := json.Unmarshal([]byte(configStr), target)
	if err != nil {
		return err
	}

	return nil
}


text:
/* iCheck.js Line skin, orange
----------------------------------- */
.icheck_line-orange {
    position: relative;
    display: block;
    margin: 0;
    padding: 5px 15px 5px 38px;
    font-size: 13px;
    line-height: 17px;
    color: #fff;
    background: #f70;
    border: none;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    cursor: pointer;
}
    .icheck_line-orange .icheck_line-icon {
        position: absolute;
        top: 50%;
        left: 13px;
        width: 13px;
        height: 11px;
        margin: -5px 0 0 0;
        padding: 0;
        overflow: hidden;
        background: url(line.png) no-repeat;
        border: none;
    }
    .icheck_line-orange.hover,
    .icheck_line-orange:hover {
        background: #FF9233;
    }
    .icheck_line-orange.static:hover,
    .icheck_line-orange.checked {
        background: #f70;
    }
        .icheck_line-orange.checked .icheck_line-icon {
            background-position: -15px 0;
        }
    .icheck_line-orange.disabled {
        background: #FFD6B3;
        cursor: default;
    }
        .icheck_line-orange.disabled .icheck_line-icon {
            background-position: -30px 0;
        }
    .icheck_line-orange.checked.disabled {
        background: #FFD6B3;
    }
        .icheck_line-orange.checked.disabled .icheck_line-icon {
            background-position: -45px 0;
        }

/* Retina support */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
       only screen and (-moz-min-device-pixel-ratio: 1.5),
       only screen and (-o-min-device-pixel-ratio: 3/2),
       only screen and (min-device-pixel-ratio: 1.5) {
    .icheck_line-orange .icheck_line-icon {
        background-image: url(line@2x.png);
        -webkit-background-size: 60px 13px;
        background-size: 60px 13px;
    }
}


text:
package com.jivesoftware.os.rcvs.api;

/**
 * Helper class to handle bulk operations in RowColumnValueStore
 *
 */
public class KeyedColumnValueCallbackStream<R, C, V, TS> {

    private final R key;
    private final CallbackStream<ColumnValueAndTimestamp<C, V, TS>> callbackStream;

    public KeyedColumnValueCallbackStream(R key, CallbackStream<ColumnValueAndTimestamp<C, V, TS>> callbackStream) {
        this.key = key;
        this.callbackStream = callbackStream;
    }

    public R getKey() {
        return key;
    }

    public CallbackStream<ColumnValueAndTimestamp<C, V, TS>> getCallbackStream() {
        return callbackStream;
    }

    @Override
    public String toString() {
        return "KeyedColumnValueCallbackStream{"
            + "key=" + KeyToStringUtils.keyToString(key)
            + ", callbackStream=" + callbackStream + '}';
    }
}


text:
// Generated source.
// Generator: org.chromium.sdk.internal.wip.tools.protocolgenerator.Generator
// Origin: http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/inspector/Inspector.json@92377

package org.chromium.sdk.internal.wip.protocol.input.debugger;

/**
 Scope description.
 */
@org.chromium.sdk.internal.protocolparser.JsonType
public interface ScopeValue {
  /**
   Scope type.
   */
  Type type();

  /**
   Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties.
   */
  org.chromium.sdk.internal.wip.protocol.input.runtime.RemoteObjectValue object();

  /**
   Scope type.
   */
  public enum Type {
    GLOBAL,
    LOCAL,
    WITH,
    CLOSURE,
    CATCH,
  }
}