text:
namespace {

bool SupportsMacSystemFullscreen() {
#if defined(OS_MACOSX)
  return chrome::mac::SupportsSystemFullscreen();
#else
  return false;
#endif
}

}  // namespace

FullscreenControllerStateTest::FullscreenControllerStateTest()
    : state_(STATE_NORMAL),
      last_notification_received_state_(STATE_NORMAL) {
  // Human specified state machine data.
  // For each state, for each event, define the resulting state.
  State transition_table_data[][NUM_EVENTS] = {
    { // STATE_NORMAL:
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event TOGGLE_FULLSCREEN
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event TOGGLE_FULLSCREEN_CHROME
      STATE_TO_TAB_FULLSCREEN,                // Event TAB_FULLSCREEN_TRUE
      STATE_NORMAL,                           // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_NORMAL,                           // Event METRO_SNAP_FALSE
      STATE_NORMAL,                           // Event BUBBLE_EXIT_LINK
      STATE_NORMAL,                           // Event BUBBLE_ALLOW
      STATE_NORMAL,                           // Event BUBBLE_DENY
      STATE_NORMAL,                           // Event WINDOW_CHANGE
    },
    { // STATE_BROWSER_FULLSCREEN_NO_CHROME:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      STATE_TAB_BROWSER_FULLSCREEN,           // Event TAB_FULLSCREEN_TRUE
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event METRO_SNAP_FALSE
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event BUBBLE_ALLOW
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event BUBBLE_DENY
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event WINDOW_CHANGE
    },
    { // STATE_BROWSER_FULLSCREEN_WITH_CHROME:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      STATE_TAB_BROWSER_FULLSCREEN_CHROME,    // Event TAB_FULLSCREEN_TRUE
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event TAB_FULLSCREEN_FALSE
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event METRO_SNAP_TRUE
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event METRO_SNAP_FALSE
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event BUBBLE_ALLOW
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event BUBBLE_DENY
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event WINDOW_CHANGE
    },
    { // STATE_METRO_SNAP:
      STATE_METRO_SNAP,                       // Event TOGGLE_FULLSCREEN
      STATE_METRO_SNAP,                       // Event TOGGLE_FULLSCREEN_CHROME
      STATE_METRO_SNAP,                       // Event TAB_FULLSCREEN_TRUE
      STATE_METRO_SNAP,                       // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_NORMAL,                           // Event METRO_SNAP_FALSE
      STATE_METRO_SNAP,                       // Event BUBBLE_EXIT_LINK
      STATE_METRO_SNAP,                       // Event BUBBLE_ALLOW
      STATE_METRO_SNAP,                       // Event BUBBLE_DENY
      STATE_METRO_SNAP,                       // Event WINDOW_CHANGE
    },
    { // STATE_TAB_FULLSCREEN:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      STATE_TAB_FULLSCREEN,                   // Event TAB_FULLSCREEN_TRUE
      STATE_TO_NORMAL,                        // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_TAB_FULLSCREEN,                   // Event METRO_SNAP_FALSE
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
      STATE_TAB_FULLSCREEN,                   // Event BUBBLE_ALLOW
      STATE_TO_NORMAL,                        // Event BUBBLE_DENY
      STATE_TAB_FULLSCREEN,                   // Event WINDOW_CHANGE
    },
    { // STATE_TAB_BROWSER_FULLSCREEN:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      STATE_TAB_BROWSER_FULLSCREEN,           // Event TAB_FULLSCREEN_TRUE
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_TAB_BROWSER_FULLSCREEN,           // Event METRO_SNAP_FALSE
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event BUBBLE_EXIT_LINK
      STATE_TAB_BROWSER_FULLSCREEN,           // Event BUBBLE_ALLOW
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event BUBBLE_DENY
      STATE_TAB_BROWSER_FULLSCREEN,           // Event WINDOW_CHANGE
    },
    { // STATE_TAB_BROWSER_FULLSCREEN_CHROME:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      STATE_TAB_BROWSER_FULLSCREEN_CHROME,    // Event TAB_FULLSCREEN_TRUE
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_TAB_BROWSER_FULLSCREEN_CHROME,    // Event METRO_SNAP_FALSE
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event BUBBLE_EXIT_LINK
      STATE_TAB_BROWSER_FULLSCREEN_CHROME,    // Event BUBBLE_ALLOW
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event BUBBLE_DENY
      STATE_TAB_BROWSER_FULLSCREEN_CHROME,    // Event WINDOW_CHANGE
    },
    { // STATE_TO_NORMAL:
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event TOGGLE_FULLSCREEN
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event TOGGLE_FULLSCREEN_CHROME
      // TODO(scheib) Should be a route back to TAB. http://crbug.com/154196
      STATE_TO_NORMAL,                        // Event TAB_FULLSCREEN_TRUE
      STATE_TO_NORMAL,                        // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_TO_NORMAL,                        // Event METRO_SNAP_FALSE
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
      STATE_TO_NORMAL,                        // Event BUBBLE_ALLOW
      STATE_TO_NORMAL,                        // Event BUBBLE_DENY
      STATE_NORMAL,                           // Event WINDOW_CHANGE
    },
    { // STATE_TO_BROWSER_FULLSCREEN_NO_CHROME:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      // TODO(scheib) Should be a route to TAB_BROWSER http://crbug.com/154196
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event TAB_FULLSCREEN_TRUE
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event TAB_FULLSCREEN_FALSE
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event METRO_SNAP_FALSE
#if defined(OS_MACOSX)
      // Mac window reports fullscreen immediately and an exit triggers exit.
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
#else
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event BUBBLE_EXIT_LINK
#endif
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event BUBBLE_ALLOW
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event BUBBLE_DENY
      STATE_BROWSER_FULLSCREEN_NO_CHROME,     // Event WINDOW_CHANGE
    },
    { // STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME:
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      // TODO(scheib) Should be a route to TAB_BROWSER http://crbug.com/154196
      STATE_TAB_BROWSER_FULLSCREEN,           // Event TAB_FULLSCREEN_TRUE
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event TAB_FULLSCREEN_FALSE
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event METRO_SNAP_TRUE
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event METRO_SNAP_FALSE
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event BUBBLE_ALLOW
      STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME,// Event BUBBLE_DENY
      STATE_BROWSER_FULLSCREEN_WITH_CHROME,   // Event WINDOW_CHANGE
    },
    { // STATE_TO_TAB_FULLSCREEN:
      // TODO(scheib) Should be a route to TAB_BROWSER http://crbug.com/154196
      STATE_TO_TAB_FULLSCREEN,                // Event TOGGLE_FULLSCREEN
      STATE_TO_NORMAL,                        // Event TOGGLE_FULLSCREEN_CHROME
      STATE_TO_TAB_FULLSCREEN,                // Event TAB_FULLSCREEN_TRUE
#if defined(OS_MACOSX)
      // Mac runs as expected due to a forced NotifyTabOfExitIfNecessary();
      STATE_TO_NORMAL,                        // Event TAB_FULLSCREEN_FALSE
#else
      // TODO(scheib) Should be a route back to NORMAL. http://crbug.com/154196
      STATE_TO_BROWSER_FULLSCREEN_NO_CHROME,  // Event TAB_FULLSCREEN_FALSE
#endif
      STATE_METRO_SNAP,                       // Event METRO_SNAP_TRUE
      STATE_TO_TAB_FULLSCREEN,                // Event METRO_SNAP_FALSE
#if defined(OS_MACOSX)
      // Mac window reports fullscreen immediately and an exit triggers exit.
      STATE_TO_NORMAL,                        // Event BUBBLE_EXIT_LINK
#else
      STATE_TO_TAB_FULLSCREEN,                // Event BUBBLE_EXIT_LINK
#endif
      STATE_TO_TAB_FULLSCREEN,                // Event BUBBLE_ALLOW
#if defined(OS_MACOSX)
      // Mac window reports fullscreen immediately and an exit triggers exit.
      STATE_TO_NORMAL,                        // Event BUBBLE_DENY
#else
      STATE_TO_TAB_FULLSCREEN,                // Event BUBBLE_DENY
#endif
      STATE_TAB_FULLSCREEN,                   // Event WINDOW_CHANGE
    },
  };
  static_assert(sizeof(transition_table_data) == sizeof(transition_table_),
                "transition_table has unexpected size");
  memcpy(transition_table_, transition_table_data,
         sizeof(transition_table_data));

  // Verify that transition_table_ has been completely defined.
  for (int source = 0; source < NUM_STATES; ++source) {
    for (int event = 0; event < NUM_EVENTS; ++event) {
      EXPECT_NE(transition_table_[source][event], STATE_INVALID);
      EXPECT_GE(transition_table_[source][event], 0);
      EXPECT_LT(transition_table_[source][event], NUM_STATES);
    }
  }

  // Copy transition_table_ data into state_transitions_ table.
  for (int source = 0; source < NUM_STATES; ++source) {
    for (int event = 0; event < NUM_EVENTS; ++event) {
      if (ShouldSkipStateAndEventPair(static_cast<State>(source),
                                      static_cast<Event>(event)))
        continue;
      State destination = transition_table_[source][event];
      state_transitions_[source][destination].event = static_cast<Event>(event);
      state_transitions_[source][destination].state = destination;
      state_transitions_[source][destination].distance = 1;
    }
  }
}

FullscreenControllerStateTest::~FullscreenControllerStateTest() {
}

// static
const char* FullscreenControllerStateTest::GetStateString(State state) {
  switch (state) {
    ENUM_TO_STRING(STATE_NORMAL);
    ENUM_TO_STRING(STATE_BROWSER_FULLSCREEN_NO_CHROME);
    ENUM_TO_STRING(STATE_BROWSER_FULLSCREEN_WITH_CHROME);
    ENUM_TO_STRING(STATE_METRO_SNAP);
    ENUM_TO_STRING(STATE_TAB_FULLSCREEN);
    ENUM_TO_STRING(STATE_TAB_BROWSER_FULLSCREEN);
    ENUM_TO_STRING(STATE_TAB_BROWSER_FULLSCREEN_CHROME);
    ENUM_TO_STRING(STATE_TO_NORMAL);
    ENUM_TO_STRING(STATE_TO_BROWSER_FULLSCREEN_NO_CHROME);
    ENUM_TO_STRING(STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME);
    ENUM_TO_STRING(STATE_TO_TAB_FULLSCREEN);
    ENUM_TO_STRING(STATE_INVALID);
    default:
      NOTREACHED() << "No string for state " << state;
      return "State-Unknown";
  }
}

// static
const char* FullscreenControllerStateTest::GetEventString(Event event) {
  switch (event) {
    ENUM_TO_STRING(TOGGLE_FULLSCREEN);
    ENUM_TO_STRING(TOGGLE_FULLSCREEN_CHROME);
    ENUM_TO_STRING(TAB_FULLSCREEN_TRUE);
    ENUM_TO_STRING(TAB_FULLSCREEN_FALSE);
    ENUM_TO_STRING(METRO_SNAP_TRUE);
    ENUM_TO_STRING(METRO_SNAP_FALSE);
    ENUM_TO_STRING(BUBBLE_EXIT_LINK);
    ENUM_TO_STRING(BUBBLE_ALLOW);
    ENUM_TO_STRING(BUBBLE_DENY);
    ENUM_TO_STRING(WINDOW_CHANGE);
    ENUM_TO_STRING(EVENT_INVALID);
    default:
      NOTREACHED() << "No string for event " << event;
      return "Event-Unknown";
  }
}

// static
bool FullscreenControllerStateTest::IsWindowFullscreenStateChangedReentrant() {
#if defined(OS_MACOSX)
  return false;
#else
  return true;
#endif
}

// static
bool FullscreenControllerStateTest::IsPersistentState(State state) {
  switch (state) {
    case STATE_NORMAL:
    case STATE_BROWSER_FULLSCREEN_NO_CHROME:
    case STATE_BROWSER_FULLSCREEN_WITH_CHROME:
    case STATE_METRO_SNAP:
    case STATE_TAB_FULLSCREEN:
    case STATE_TAB_BROWSER_FULLSCREEN:
    case STATE_TAB_BROWSER_FULLSCREEN_CHROME:
      return true;

    case STATE_TO_NORMAL:
    case STATE_TO_BROWSER_FULLSCREEN_NO_CHROME:
    case STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME:
    case STATE_TO_TAB_FULLSCREEN:
      return false;

    default:
      NOTREACHED();
      return false;
  }
}

void FullscreenControllerStateTest::TransitionToState(State final_state) {
  int max_steps = NUM_STATES;
  while (max_steps-- && TransitionAStepTowardState(final_state))
    continue;
  ASSERT_GE(max_steps, 0) << "TransitionToState was unable to achieve desired "
      << "target state. TransitionAStepTowardState iterated too many times."
      << GetAndClearDebugLog();
  ASSERT_EQ(final_state, state_) << "TransitionToState was unable to achieve "
      << "desired target state. TransitionAStepTowardState returned false."
      << GetAndClearDebugLog();
}

bool FullscreenControllerStateTest::TransitionAStepTowardState(
    State destination_state) {
  State source_state = state_;
  if (source_state == destination_state)
    return false;

  StateTransitionInfo next = NextTransitionInShortestPath(source_state,
                                                          destination_state,
                                                          NUM_STATES);
  if (next.state == STATE_INVALID) {
    NOTREACHED() << "TransitionAStepTowardState unable to transition. "
        << "NextTransitionInShortestPath("
        << GetStateString(source_state) << ", "
        << GetStateString(destination_state) << ") returned STATE_INVALID."
        << GetAndClearDebugLog();
    return false;
  }

  return InvokeEvent(next.event);
}

const char* FullscreenControllerStateTest::GetWindowStateString() {
  return NULL;
}

bool FullscreenControllerStateTest::InvokeEvent(Event event) {
  if (!fullscreen_notification_observer_.get()) {
    // Start observing NOTIFICATION_FULLSCREEN_CHANGED. Construct the
    // notification observer here instead of in
    // FullscreenControllerStateTest::FullscreenControllerStateTest() so that we
    // listen to notifications on the proper thread.
    fullscreen_notification_observer_.reset(
        new FullscreenNotificationObserver());
  }

  State source_state = state_;
  State next_state = transition_table_[source_state][event];

  EXPECT_FALSE(ShouldSkipStateAndEventPair(source_state, event))
      << GetAndClearDebugLog();

  // When simulating reentrant window change calls, expect the next state
  // automatically.
  if (IsWindowFullscreenStateChangedReentrant())
    next_state = transition_table_[next_state][WINDOW_CHANGE];

  debugging_log_ << "  InvokeEvent(" << std::left
      << std::setw(kMaxStateNameLength) << GetEventString(event)
      << ") to "
      << std::setw(kMaxStateNameLength) << GetStateString(next_state);

  state_ = next_state;

  switch (event) {
    case TOGGLE_FULLSCREEN:
      GetFullscreenController()->ToggleBrowserFullscreenMode();
      break;

    case TOGGLE_FULLSCREEN_CHROME:
#if defined(OS_MACOSX)
      if (chrome::mac::SupportsSystemFullscreen()) {
        GetFullscreenController()->ToggleBrowserFullscreenWithToolbar();
        break;
      }
#endif
      NOTREACHED() << GetAndClearDebugLog();
      break;

    case TAB_FULLSCREEN_TRUE:
    case TAB_FULLSCREEN_FALSE: {
      content::WebContents* const active_tab =
          GetBrowser()->tab_strip_model()->GetActiveWebContents();
      if (event == TAB_FULLSCREEN_TRUE) {
        GetFullscreenController()->EnterFullscreenModeForTab(active_tab,
                                                             GURL());
      } else {
        GetFullscreenController()->ExitFullscreenModeForTab(active_tab);
      }

      // Activating/Deactivating tab fullscreen on a captured tab should not
      // evoke a state change in the browser window.
      if (active_tab->GetCapturerCount() > 0)
        state_ = source_state;
      break;
    }

    case METRO_SNAP_TRUE:
#if defined(OS_WIN)
      GetFullscreenController()->SetMetroSnapMode(true);
#else
      NOTREACHED() << GetAndClearDebugLog();
#endif
      break;

    case METRO_SNAP_FALSE:
#if defined(OS_WIN)
      GetFullscreenController()->SetMetroSnapMode(false);
#else
      NOTREACHED() << GetAndClearDebugLog();
#endif
      break;

    case BUBBLE_EXIT_LINK:
      GetFullscreenController()->ExitExclusiveAccessToPreviousState();
      break;

    case BUBBLE_ALLOW:
      GetBrowser()
          ->exclusive_access_manager()
          ->OnAcceptExclusiveAccessPermission();
      break;

    case BUBBLE_DENY:
      GetBrowser()
          ->exclusive_access_manager()
          ->OnDenyExclusiveAccessPermission();
      break;

    case WINDOW_CHANGE:
      ChangeWindowFullscreenState();
      break;

    default:
      NOTREACHED() << "InvokeEvent needs a handler for event "
          << GetEventString(event) << GetAndClearDebugLog();
      return false;
  }

  if (GetWindowStateString())
    debugging_log_ << " Window state now " << GetWindowStateString() << "\n";
  else
    debugging_log_ << "\n";

  MaybeWaitForNotification();
  VerifyWindowState();

  return true;
}

void FullscreenControllerStateTest::VerifyWindowState() {
  switch (state_) {
    case STATE_NORMAL:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
                                    FULLSCREEN_FOR_BROWSER_FALSE,
                                    FULLSCREEN_FOR_TAB_FALSE,
                                    IN_METRO_SNAP_FALSE);
      break;
    case STATE_BROWSER_FULLSCREEN_NO_CHROME:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
                                    FULLSCREEN_FOR_BROWSER_TRUE,
                                    FULLSCREEN_FOR_TAB_FALSE,
                                    IN_METRO_SNAP_FALSE);
      break;
    case STATE_BROWSER_FULLSCREEN_WITH_CHROME:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_TRUE,
                                    FULLSCREEN_FOR_BROWSER_TRUE,
                                    FULLSCREEN_FOR_TAB_FALSE,
                                    IN_METRO_SNAP_FALSE);
      break;
    case STATE_METRO_SNAP:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_NO_EXPECTATION,
                                    FULLSCREEN_FOR_BROWSER_NO_EXPECTATION,
                                    FULLSCREEN_FOR_TAB_NO_EXPECTATION,
                                    IN_METRO_SNAP_TRUE);
      break;
    case STATE_TAB_FULLSCREEN:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
                                    FULLSCREEN_FOR_BROWSER_FALSE,
                                    FULLSCREEN_FOR_TAB_TRUE,
                                    IN_METRO_SNAP_FALSE);
      break;
    case STATE_TAB_BROWSER_FULLSCREEN:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
                                    FULLSCREEN_FOR_BROWSER_TRUE,
                                    FULLSCREEN_FOR_TAB_TRUE,
                                    IN_METRO_SNAP_FALSE);
      break;
    case STATE_TAB_BROWSER_FULLSCREEN_CHROME:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
                                    FULLSCREEN_FOR_BROWSER_TRUE,
                                    FULLSCREEN_FOR_TAB_TRUE,
                                    IN_METRO_SNAP_FALSE);
      break;
    case STATE_TO_NORMAL:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
                                    FULLSCREEN_FOR_BROWSER_NO_EXPECTATION,
                                    FULLSCREEN_FOR_TAB_NO_EXPECTATION,
                                    IN_METRO_SNAP_FALSE);
      break;

    case STATE_TO_BROWSER_FULLSCREEN_NO_CHROME:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_FALSE,
#if defined(OS_MACOSX)
                                    FULLSCREEN_FOR_BROWSER_TRUE,
#else
                                    FULLSCREEN_FOR_BROWSER_FALSE,
#endif
                                    FULLSCREEN_FOR_TAB_NO_EXPECTATION,
                                    IN_METRO_SNAP_FALSE);
      break;

    case STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME:
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_TRUE,
#if defined(OS_MACOSX)
                                    FULLSCREEN_FOR_BROWSER_TRUE,
#else
                                    FULLSCREEN_FOR_BROWSER_FALSE,
#endif
                                    FULLSCREEN_FOR_TAB_NO_EXPECTATION,
                                    IN_METRO_SNAP_FALSE);
      break;

    case STATE_TO_TAB_FULLSCREEN:
#if defined(OS_MACOSX)
      // TODO(scheib) InPresentationMode returns false when invoking events:
      // TAB_FULLSCREEN_TRUE, TOGGLE_FULLSCREEN. http://crbug.com/156645
      // It may be that a new testing state TO_TAB_BROWSER_FULLSCREEN
      // would help work around this http://crbug.com/154196
      // Test with: STATE_TO_TAB_FULLSCREEN__TOGGLE_FULLSCREEN
      //
      // EXPECT_TRUE(GetBrowser()->window()->InPresentationMode())
      //     << GetAndClearDebugLog();
#endif
      VerifyWindowStateExpectations(FULLSCREEN_WITH_CHROME_NO_EXPECTATION,
                                    FULLSCREEN_FOR_BROWSER_FALSE,
                                    FULLSCREEN_FOR_TAB_TRUE,
                                    IN_METRO_SNAP_FALSE);
      break;

    default:
      NOTREACHED() << GetAndClearDebugLog();
  }
}

void FullscreenControllerStateTest::MaybeWaitForNotification() {
  // We should get a fullscreen notification each time we get to a new
  // persistent state. If we don't get a notification, the test will
  // fail by timing out.
  if (state_ != last_notification_received_state_ &&
      IsPersistentState(state_)) {
    fullscreen_notification_observer_->Wait();
    last_notification_received_state_ = state_;
    fullscreen_notification_observer_.reset(
        new FullscreenNotificationObserver());
  }
}

void FullscreenControllerStateTest::TestTransitionsForEachState() {
  for (int source_int = 0; source_int < NUM_STATES; ++source_int) {
    for (int event1_int = 0; event1_int < NUM_EVENTS; ++event1_int) {
      State state = static_cast<State>(source_int);
      Event event1 = static_cast<Event>(event1_int);

      // Early out if skipping all tests for this state, reduces log noise.
      if (ShouldSkipTest(state, event1))
        continue;

      for (int event2_int = 0; event2_int < NUM_EVENTS; ++event2_int) {
        for (int event3_int = 0; event3_int < NUM_EVENTS; ++event3_int) {
          Event event2 = static_cast<Event>(event2_int);
          Event event3 = static_cast<Event>(event3_int);

          // Test each state and each event.
          ASSERT_NO_FATAL_FAILURE(TestStateAndEvent(state, event1))
              << GetAndClearDebugLog();

          // Then, add an additional event to the sequence.
          if (ShouldSkipStateAndEventPair(state_, event2))
            continue;
          ASSERT_TRUE(InvokeEvent(event2)) << GetAndClearDebugLog();

          // Then, add an additional event to the sequence.
          if (ShouldSkipStateAndEventPair(state_, event3))
            continue;
          ASSERT_TRUE(InvokeEvent(event3)) << GetAndClearDebugLog();
        }
      }
    }
  }
}

FullscreenControllerStateTest::StateTransitionInfo
    FullscreenControllerStateTest::NextTransitionInShortestPath(
    State source,
    State destination,
    int search_limit) {
  if (search_limit <= 0)
    return StateTransitionInfo();  // Return a default (invalid) state.

  if (state_transitions_[source][destination].state == STATE_INVALID) {
    // Don't know the next state yet, do a depth first search.
    StateTransitionInfo result;

    // Consider all states reachable via each event from the source state.
    for (int event_int = 0; event_int < NUM_EVENTS; ++event_int) {
      Event event = static_cast<Event>(event_int);
      State next_state_candidate = transition_table_[source][event];

      if (ShouldSkipStateAndEventPair(source, event))
        continue;

      // Recurse.
      StateTransitionInfo candidate = NextTransitionInShortestPath(
          next_state_candidate, destination, search_limit - 1);

      if (candidate.distance + 1 < result.distance) {
        result.event = event;
        result.state = next_state_candidate;
        result.distance = candidate.distance + 1;
      }
    }

    // Cache result so that a search is not required next time.
    state_transitions_[source][destination] = result;
  }

  return state_transitions_[source][destination];
}

std::string FullscreenControllerStateTest::GetAndClearDebugLog() {
  debugging_log_ << "(End of Debugging Log)\n";
  std::string output_log = "\nDebugging Log:\n" + debugging_log_.str();
  debugging_log_.str(std::string());
  return output_log;
}

bool FullscreenControllerStateTest::ShouldSkipStateAndEventPair(State state,
                                                                Event event) {
  // TODO(scheib) Toggling Tab fullscreen while pending Tab or
  // Browser fullscreen is broken currently http://crbug.com/154196
  if ((state == STATE_TO_BROWSER_FULLSCREEN_NO_CHROME ||
       state == STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME ||
       state == STATE_TO_TAB_FULLSCREEN) &&
      (event == TAB_FULLSCREEN_TRUE || event == TAB_FULLSCREEN_FALSE))
    return true;
  if (state == STATE_TO_NORMAL && event == TAB_FULLSCREEN_TRUE)
    return true;

  // Skip metro snap state and events when not on windows.
#if !defined(OS_WIN)
  if (state == STATE_METRO_SNAP ||
      event == METRO_SNAP_TRUE ||
      event == METRO_SNAP_FALSE)
    return true;
#endif

  // Skip Mac Lion Fullscreen state and events when not on OSX 10.7+.
  if (!SupportsMacSystemFullscreen()) {
    if (state == STATE_BROWSER_FULLSCREEN_WITH_CHROME ||
        state == STATE_TAB_BROWSER_FULLSCREEN_CHROME ||
        state == STATE_TO_BROWSER_FULLSCREEN_WITH_CHROME ||
        event == TOGGLE_FULLSCREEN_CHROME) {
      return true;
    }
  }

  return false;
}

bool FullscreenControllerStateTest::ShouldSkipTest(State state, Event event) {
  // Quietly skip metro snap tests when not on windows.
#if !defined(OS_WIN)
  if (state == STATE_METRO_SNAP ||
      event == METRO_SNAP_TRUE ||
      event == METRO_SNAP_FALSE) {
    debugging_log_ << "\nSkipping metro snap test on non-Windows.\n";
    return true;
  }
#endif

  // Quietly skip Mac Lion Fullscreen tests when not on OSX 10.7+.
  if (!SupportsMacSystemFullscreen()) {
    if (state == STATE_BROWSER_FULLSCREEN_WITH_CHROME ||
        event == TOGGLE_FULLSCREEN_CHROME) {
      debugging_log_ << "\nSkipping Lion Fullscreen test on non-OSX 10.7+.\n";
      return true;
    }
  }

  // When testing reentrancy there are states the fullscreen controller
  // will be unable to remain in, as they will progress due to the
  // reentrant window change call. Skip states that will be instantly
  // exited by the reentrant call.
  if (IsWindowFullscreenStateChangedReentrant() &&
      (transition_table_[state][WINDOW_CHANGE] != state)) {
    debugging_log_ << "\nSkipping reentrant test for transitory source state "
        << GetStateString(state) << ".\n";
    return true;
  }

  if (ShouldSkipStateAndEventPair(state, event)) {
    debugging_log_ << "\nSkipping test due to ShouldSkipStateAndEventPair("
        << GetStateString(state) << ", "
        << GetEventString(event) << ").\n";
    LOG(INFO) << "Skipping test due to ShouldSkipStateAndEventPair("
        << GetStateString(state) << ", "
        << GetEventString(event) << ").";
    return true;
  }

  return false;
}

void FullscreenControllerStateTest::TestStateAndEvent(State state,
                                                      Event event) {
  if (ShouldSkipTest(state, event))
    return;

  debugging_log_ << "\nTest transition from state "
      << GetStateString(state)
      << (IsWindowFullscreenStateChangedReentrant() ?
          " with reentrant calls.\n" : ".\n");

  // Spaced out text to line up with columns printed in InvokeEvent().
  debugging_log_ << "First,                                               from "
      << GetStateString(state_) << "\n";
  ASSERT_NO_FATAL_FAILURE(TransitionToState(state))
      << GetAndClearDebugLog();

  debugging_log_ << " Then,\n";
  ASSERT_TRUE(InvokeEvent(event)) << GetAndClearDebugLog();
}

void FullscreenControllerStateTest::VerifyWindowStateExpectations(
    FullscreenWithToolbarExpectation fullscreen_with_toolbar,
    FullscreenForBrowserExpectation fullscreen_for_browser,
    FullscreenForTabExpectation fullscreen_for_tab,
    InMetroSnapExpectation in_metro_snap) {
  ExclusiveAccessContext* context =
      GetBrowser()->window()->GetExclusiveAccessContext();
  if (fullscreen_with_toolbar != FULLSCREEN_WITH_CHROME_NO_EXPECTATION &&
      context->SupportsFullscreenWithToolbar()) {
    EXPECT_EQ(context->IsFullscreenWithToolbar(), !!fullscreen_with_toolbar)
        << GetAndClearDebugLog();
  }
  if (fullscreen_for_browser != FULLSCREEN_FOR_BROWSER_NO_EXPECTATION) {
    EXPECT_EQ(GetFullscreenController()->IsFullscreenForBrowser(),
              !!fullscreen_for_browser) << GetAndClearDebugLog();
  }
  if (fullscreen_for_tab != FULLSCREEN_FOR_TAB_NO_EXPECTATION) {
    EXPECT_EQ(GetFullscreenController()->IsWindowFullscreenForTabOrPending(),
              !!fullscreen_for_tab) << GetAndClearDebugLog();
  }

#if defined(OS_WIN)
  if (in_metro_snap != IN_METRO_SNAP_NO_EXPECTATION) {
    EXPECT_EQ(GetFullscreenController()->IsInMetroSnapMode(),
              !!in_metro_snap) << GetAndClearDebugLog();
  }
#endif  // OS_WIN
}

FullscreenController* FullscreenControllerStateTest::GetFullscreenController() {
  return GetBrowser()->exclusive_access_manager()->fullscreen_controller();
}

std::string FullscreenControllerStateTest::GetTransitionTableAsString() const {
  std::ostringstream output;
  output << "transition_table_[NUM_STATES = " << NUM_STATES
      << "][NUM_EVENTS = " << NUM_EVENTS
      << "] =\n";
  for (int state_int = 0; state_int < NUM_STATES; ++state_int) {
    State state = static_cast<State>(state_int);
    output << "    { // " << GetStateString(state) << ":\n";
    for (int event_int = 0; event_int < NUM_EVENTS; ++event_int) {
      Event event = static_cast<Event>(event_int);
      output << "      "
          << std::left << std::setw(kMaxStateNameLength+1)
          << std::string(GetStateString(transition_table_[state][event])) + ","
          << "// Event "
          << GetEventString(event) << "\n";
    }
    output << "    },\n";
  }
  output << "  };\n";
  return output.str();
}

std::string FullscreenControllerStateTest::GetStateTransitionsAsString() const {
  std::ostringstream output;
  output << "state_transitions_[NUM_STATES = " << NUM_STATES
      << "][NUM_STATES = " << NUM_STATES << "] =\n";
  for (int state1_int = 0; state1_int < NUM_STATES; ++state1_int) {
    State state1 = static_cast<State>(state1_int);
    output << "{ // " << GetStateString(state1) << ":\n";
    for (int state2_int = 0; state2_int < NUM_STATES; ++state2_int) {
      State state2 = static_cast<State>(state2_int);
      const StateTransitionInfo& info = state_transitions_[state1][state2];
      output << "  { "
        << std::left << std::setw(kMaxStateNameLength+1)
        << std::string(GetEventString(info.event)) + ","
        << std::left << std::setw(kMaxStateNameLength+1)
        << std::string(GetStateString(info.state)) + ","
        << std::right << std::setw(2)
        << info.distance
        << " }, // "
        << GetStateString(state2) << "\n";
    }
    output << "},\n";
  }
  output << "};";
  return output.str();
}


text:
package org.cagrid.gaards.credentials;

import java.io.File;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.cert.X509Certificate;

import javax.xml.namespace.QName;

import org.apache.axis.utils.ClassUtils;
import org.apache.commons.io.FileUtils;
import org.cagrid.gaards.pki.CertUtil;
import org.cagrid.gaards.pki.KeyUtil;
import org.globus.gsi.GlobusCredential;

public class EncodingUtil {

    public static final String CLIENT_WSDD = "client-config.wsdd";
    public static final QName X509_CREDENTIAL = new QName("http://gaards.cagrid.org/credentials",
        "X509CredentialDescriptor");
    public static final QName DORIAN_USER_CREDENTIAL = new QName("http://gaards.cagrid.org/credentials",
        "DorianUserCredentialDescriptor");

    public static void serialize(File f, X509CredentialDescriptor des) throws Exception {
        String str = serialize(des);
        FileUtils.writeStringToFile(f, str);
    }

    public static String serialize(X509CredentialDescriptor des) throws Exception {
        if (des instanceof DorianUserCredentialDescriptor) {
            return serialize(DORIAN_USER_CREDENTIAL, des);
        } else {
            return serialize(X509_CREDENTIAL, des);
        }
    }

    public static X509CredentialDescriptor deserialize(File f) throws Exception {
        String str = FileUtils.readFileToString(f);
        return deserialize(str);
    }

    public static X509CredentialDescriptor encode(GlobusCredential cred) throws Exception {
        return encode(cred, new X509CredentialDescriptor());
    }

    public static X509CredentialDescriptor encode(GlobusCredential cred, X509CredentialDescriptor des) throws Exception {
        des.setIdentity(cred.getIdentity());
        EncodedCertificates list = new EncodedCertificates();
        X509Certificate[] chain = cred.getCertificateChain();
        if (chain != null) {
            String[] certs = new String[chain.length];
            for (int i = 0; i < chain.length; i++) {
                certs[i] = CertUtil.writeCertificate(chain[i]);
            }
            list.setEncodedCertificate(certs);
        }
        des.setEncodedCertificates(list);
        des.setEncodedKey(KeyUtil.writePrivateKey(cred.getPrivateKey(), (String) null));
        return des;
    }

    public static X509CredentialDescriptor deserialize(String s) throws Exception {
        InputStream resourceAsStream = ClassUtils.getResourceAsStream(EncodingUtil.class, CLIENT_WSDD);
        if (s.indexOf(DORIAN_USER_CREDENTIAL.getLocalPart()) != -1) {
            return gov.nih.nci.cagrid.common.Utils.deserializeObject(new StringReader(s),
                DorianUserCredentialDescriptor.class, resourceAsStream);
        } else {
            return gov.nih.nci.cagrid.common.Utils.deserializeObject(new StringReader(s),
                X509CredentialDescriptor.class, resourceAsStream);
        }
    }

    public static String serialize(QName ns, Object o) throws Exception {
        InputStream resourceAsStream = ClassUtils.getResourceAsStream(EncodingUtil.class, CLIENT_WSDD);
        StringWriter writer = new StringWriter();
        gov.nih.nci.cagrid.common.Utils.serializeObject(o, ns, writer, resourceAsStream);
        return writer.toString();
    }

    public static Object deserialize(String s, Class c) throws Exception {
        InputStream resourceAsStream = ClassUtils.getResourceAsStream(EncodingUtil.class, CLIENT_WSDD);
        return gov.nih.nci.cagrid.common.Utils.deserializeObject(new StringReader(s), c, resourceAsStream);
    }

}

redpajama_set_name: RedPajamaGithub


text:
var path = require('path');
var hapi = require('hapi');

var config = require('./config.js');

var server = new hapi.Server(config.server.host, config.server.port, {
	cors: config.server.cors,
	views: {
		engines: {
			hbs: require('handlebars')
		},
		path: path.resolve(__dirname, 'templates'),
		partialsPath: path.resolve(__dirname, 'templates', 'partials'),
		helpersPath: path.resolve(__dirname, 'templates', 'helpers'),
		layoutPath: path.resolve(__dirname, 'templates', 'layouts'),
		layout: 'default'
	}
});

server.route(require('./routes'));

server.pack.register([
], function () {
	server.start(function () {
		console.log('Server started at', server.info.uri);
	});
});


text:
webtestrunner
=============

Monitor nose tests as you develop


text:
const models = require('../models');

const visibleAttributes = ['id', 'username', 'admin', 'level', 'xp', 'created_at', 'updated_at'];

var routes = [];

//get all
routes.push({
    method: "get",
    path: '/api/v1/users',
    authenticate: false,
    handler: (req, res) => {
        models.User.findAll({ attributes: visibleAttributes }).then((users) =>{
            res.json(users);
        });
    }
});
//get one
routes.push({
    method: "get",
    path: '/api/v1/users/:id',
    authenticate: false,
    handler: (req, res) => {
        models.User.findById(req.params.id, { attributes: visibleAttributes }).then(function(user){
            res.json(user);
        });
    }
});
//register
//TODO
//update
//TODO

module.exports = routes;


text:
package org.apache.arrow.driver.jdbc;

import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;

import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl;

/**
 * {@link ConnectionPoolDataSource} implementation for Arrow Flight JDBC Driver.
 */
public class ArrowFlightJdbcConnectionPoolDataSource extends ArrowFlightJdbcDataSource
    implements ConnectionPoolDataSource, ConnectionEventListener, AutoCloseable {
  private final Map<Properties, Queue<ArrowFlightJdbcPooledConnection>> pool =
      new ConcurrentHashMap<>();

  /**
   * Instantiates a new DataSource.
   *
   * @param properties the properties
   * @param config     the config.
   */
  protected ArrowFlightJdbcConnectionPoolDataSource(final Properties properties,
                                                    final ArrowFlightConnectionConfigImpl config) {
    super(properties, config);
  }

  /**
   * Creates a new {@link ArrowFlightJdbcConnectionPoolDataSource}.
   *
   * @param properties the properties.
   * @return a new data source.
   */
  public static ArrowFlightJdbcConnectionPoolDataSource createNewDataSource(
      final Properties properties) {
    return new ArrowFlightJdbcConnectionPoolDataSource(properties,
        new ArrowFlightConnectionConfigImpl(properties));
  }

  @Override
  public PooledConnection getPooledConnection() throws SQLException {
    final ArrowFlightConnectionConfigImpl config = getConfig();
    return this.getPooledConnection(config.getUser(), config.getPassword());
  }

  @Override
  public PooledConnection getPooledConnection(final String username, final String password)
      throws SQLException {
    final Properties properties = getProperties(username, password);
    Queue<ArrowFlightJdbcPooledConnection> objectPool =
        pool.computeIfAbsent(properties, s -> new ConcurrentLinkedQueue<>());
    ArrowFlightJdbcPooledConnection pooledConnection = objectPool.poll();
    if (pooledConnection == null) {
      pooledConnection = createPooledConnection(new ArrowFlightConnectionConfigImpl(properties));
    } else {
      pooledConnection.reset();
    }
    return pooledConnection;
  }

  private ArrowFlightJdbcPooledConnection createPooledConnection(
      final ArrowFlightConnectionConfigImpl config)
      throws SQLException {
    ArrowFlightJdbcPooledConnection pooledConnection =
        new ArrowFlightJdbcPooledConnection(getConnection(config.getUser(), config.getPassword()));
    pooledConnection.addConnectionEventListener(this);
    return pooledConnection;
  }

  @Override
  public void connectionClosed(ConnectionEvent connectionEvent) {
    final ArrowFlightJdbcPooledConnection pooledConnection =
        (ArrowFlightJdbcPooledConnection) connectionEvent.getSource();
    Queue<ArrowFlightJdbcPooledConnection> connectionQueue =
        pool.get(pooledConnection.getProperties());
    connectionQueue.add(pooledConnection);
  }

  @Override
  public void connectionErrorOccurred(ConnectionEvent connectionEvent) {

  }

  @Override
  public void close() throws Exception {
    SQLException lastException = null;
    for (Queue<ArrowFlightJdbcPooledConnection> connections : this.pool.values()) {
      while (!connections.isEmpty()) {
        PooledConnection pooledConnection = connections.poll();
        try {
          pooledConnection.close();
        } catch (SQLException e) {
          lastException = e;
        }
      }
    }

    if (lastException != null) {
      throw lastException;
    }
  }
}


text:
<yandex>
    <dictionary>
        <name>default.test_dict</name>

        <structure>

            <key>
                <attribute>
                    <name>Nom</name>
                    <type>String</type>
                    <null_value></null_value>
                </attribute>
            </key>

            <attribute>
                <name>Code</name>
                <type>String</type>
                <null_value></null_value>
            </attribute>
            <attribute>
                <name>Cur</name>
                <type>String</type>
                <null_value></null_value>
            </attribute>
        </structure>

        <source>

            <mysql>
                <port>3306</port>
                <user>default</user>
                <password/>
                <replica>
                    <host>127.0.0.1</host>
                    <priority>1</priority>
                </replica>
                <db>default</db>

test

            </mysql>
        </source>

        <layout>

            <complex_key_hashed />
        </layout>

        <lifetime>300</lifetime>
    </dictionary>
</yandex>


text:
#include "tensorflow/cc/framework/gradient_checker.h"
#include "tensorflow/cc/framework/grad_op_registry.h"
#include "tensorflow/cc/framework/testutil.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/util/equal_graph_def.h"

namespace tensorflow {
using namespace ops;  // NOLINT(build/namespaces)

namespace {

TEST(GradientCheckerTest, BasicFloat) {
  Scope scope = Scope::NewRootScope();
  TensorShape shape({2, 4, 3});
  auto x = Placeholder(scope, DT_FLOAT, Placeholder::Shape(shape));
  auto y = Square(scope, x);
  float max_error;
  TF_ASSERT_OK((ComputeGradientError<float, float, float>(
      scope, {x}, {shape}, {y}, {shape}, &max_error)));
  EXPECT_LT(max_error, 1e-4);
}

TEST(GradientCheckerTest, BasicDouble) {
  Scope scope = Scope::NewRootScope();
  TensorShape shape({2, 4, 3});
  auto x = Placeholder(scope, DT_DOUBLE, Placeholder::Shape(shape));
  auto y = Square(scope, x);
  double max_error;
  TF_ASSERT_OK((ComputeGradientError<double, double, double>(
      scope, {x}, {shape}, {y}, {shape}, &max_error)));
  EXPECT_LT(max_error, 1e-10);
}

TEST(GradientCheckerTest, BasicComplex64) {
  Scope scope = Scope::NewRootScope();
  TensorShape shape({2, 4, 3});
  auto x = Placeholder(scope, DT_COMPLEX64, Placeholder::Shape(shape));
  auto y = Square(scope, x);
  float max_error;
  TF_ASSERT_OK((ComputeGradientError<complex64, complex64, float>(
      scope, {x}, {shape}, {y}, {shape}, &max_error)));
  EXPECT_LT(max_error, 1e-4);
}

TEST(GradientCheckerTest, BasicComplex128) {
  Scope scope = Scope::NewRootScope();
  TensorShape shape({2, 4, 3});
  auto x = Placeholder(scope, DT_COMPLEX128, Placeholder::Shape(shape));
  auto y = Square(scope, x);
  double max_error;
  TF_ASSERT_OK((ComputeGradientError<complex128, complex128, double>(
      scope, {x}, {shape}, {y}, {shape}, &max_error)));
  EXPECT_LT(max_error, 1e-10);
}

TEST(GradientCheckerTest, FloatToComplex64) {
  // Test an op whose inputs are real and outputs are complex
  Scope scope = Scope::NewRootScope();
  TensorShape shape({2, 4, 3});
  auto x = Placeholder(scope, DT_FLOAT, Placeholder::Shape(shape));
  auto y = Complex(scope, x, x);
  float max_error;
  TF_ASSERT_OK((ComputeGradientError<float, complex64, float>(
      scope, {x}, {shape}, {y}, {shape}, &max_error)));
  EXPECT_LT(max_error, 1e-4);
}

TEST(GradientCheckerTest, Complex64ToFloat) {
  // Test an op whose inputs are complex and outputs are real
  Scope scope = Scope::NewRootScope();
  TensorShape shape({2, 4, 3});
  auto x = Placeholder(scope, DT_COMPLEX64, Placeholder::Shape(shape));
  auto y = Real(scope, x);
  float max_error;
  TF_ASSERT_OK((ComputeGradientError<complex64, float, float>(
      scope, {x}, {shape}, {y}, {shape}, &max_error)));
  EXPECT_LT(max_error, 1e-4);
}

TEST(GradientCheckerTest, MatMulGrad) {
  Scope scope = Scope::NewRootScope();

  TensorShape x_shape({4, 3});
  TensorShape y_shape({3, 2});
  TensorShape z_shape({4, 2});

  auto x = Placeholder(scope, DT_DOUBLE, Placeholder::Shape(x_shape));
  auto y = Const(scope, {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}, y_shape);
  auto z = MatMul(scope, x, y);
  double max_error;
  TF_ASSERT_OK((ComputeGradientError<double, double, double>(
      scope, {x}, {x_shape}, {z}, {z_shape}, &max_error)));
  EXPECT_LT(max_error, 1e-10);
}

TEST(GradientCheckerTest, SplitGrad) {
  // Split is an op with single inputs and multiple outputs.
  Scope scope = Scope::NewRootScope();
  TensorShape x_shape({5, 2});
  auto x = Placeholder(scope, DT_DOUBLE, Placeholder::Shape(x_shape));
  // Split along the second dimension.
  auto split_dim = Const(scope, 1, {});
  auto y = Split(scope, split_dim, x, /* num_split */ 2);
  TensorShape y_shape = TensorShape({5, 1});
  double max_error;
  TF_ASSERT_OK((ComputeGradientError<double, double, double>(
      scope, {x}, {x_shape}, y.output, {y_shape, y_shape}, &max_error)));
  EXPECT_LT(max_error, 1e-10);
}

TEST(GradientCheckerTest, StackGrad) {
  // Stack is an op with multiple inputs and a single output.
  Scope scope = Scope::NewRootScope();
  TensorShape x_shape({1, 2, 3});
  std::vector<Output> xs;
  xs.push_back(Placeholder(scope, DT_DOUBLE, Placeholder::Shape(x_shape)));
  xs.push_back(Placeholder(scope, DT_DOUBLE, Placeholder::Shape(x_shape)));
  auto y = Stack(scope, xs, Stack::Axis(0));
  TensorShape y_shape({2, 1, 2, 3});
  double max_error;
  TF_ASSERT_OK((ComputeGradientError<double, double, double>(
      scope, xs, {x_shape, x_shape}, {y}, {y_shape}, &max_error)));
  EXPECT_LT(max_error, 1e-10);
}

TEST(GradientCheckerTest, StackUnstackGrad) {
  // Chaining a Stack op to an Unstack op allows us to test the gradient checker
  // in a multiple input/output scenario.
  Scope scope = Scope::NewRootScope();
  TensorShape shape({1, 2, 3});
  std::vector<Output> xs;
  xs.push_back(Placeholder(scope, DT_DOUBLE, Placeholder::Shape(shape)));
  xs.push_back(Placeholder(scope, DT_DOUBLE, Placeholder::Shape(shape)));
  auto tmp = Stack(scope, xs, Stack::Axis(0));
  auto y = Unstack(scope, tmp, 2, Unstack::Axis(0));
  double max_error;
  TF_ASSERT_OK((ComputeGradientError<double, double, double>(
      scope, xs, {shape, shape}, y.output, {shape, shape}, &max_error)));
  EXPECT_LT(max_error, 1e-10);
}

}  // namespace
}  // namespace tensorflow


text:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    if request.env["omniauth.auth"].info.email.blank?
      redirect_to "/users/auth/facebook?auth_type=rerequest&scope=email"
    end

    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

  def twitter
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Twitter") if is_navigational_format?
    else
      session["devise.twitter_uid"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end

  end
end


text:
import Search from '../layout/Search';

export default Search;


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package generic.timer;

import ghidra.util.exception.AssertException;

import java.util.Timer;
import java.util.TimerTask;

/**
 * The GhidraSwinglessTimer is similar to the javax.swing.Timer class.  The big difference is
 * that it does NOT use the swing thread for its callbacks.  Similar to the swing timer, only
 * one timer thread is ever used no matter how many GhidraSwinglessTimers are instantiated.
 *
 * It fires one or more {@code TimerCallback}s at specified
 * intervals.
 * Setting up a timer
 * involves creating a GhidraSwinglessTimer object,
 * registering one or more TimerCallbacks on it,
 * and starting the timer using
 * the start method.
 *
 */
public class GhidraSwinglessTimer implements GhidraTimer {
	private static final long CLEANUP_TIMER_THREAD_DELAY = 60000;
	private static Timer timer;
	private static int taskCount = 0;
	private static CleanupTimerTask cleanupTask = null;

	private static synchronized Timer getTimer() {
		if (timer == null) {
			timer = new Timer("GhidraSwinglessTimer", true);
		}
		return timer;
	}

	private static synchronized void incrementCount() {
		taskCount++;
		if (cleanupTask != null) {
			cleanupTask.cancel();
			cleanupTask = null;
		}
	}

	private static synchronized void decrementCount() {
		taskCount--;
		if (taskCount < 0) {
			throw new AssertException("Timer count out of sync.");
		}
		if (taskCount == 0) {
			cleanupTask = new CleanupTimerTask();
			getTimer().schedule(cleanupTask, CLEANUP_TIMER_THREAD_DELAY);
		}
	}

	private static synchronized void cleanupTimer() {
		cleanupTask = null;
		if (taskCount == 0) {
			timer.cancel();
			timer = null;
		}
	}

	private TimerCallback callback;
	private boolean repeats;
	private int delay;
	private int initialDelay;
	private TimerTask timerTask;

	/**
	 * Creates a new repeating timer with a initial delay of 100ms and a continual delay of 100ms.
	 */
	public GhidraSwinglessTimer() {
		this(100, null);
	}

	/**
	 * Creates a new repeating timer with a initial and continual delay with the given delay.
	 * @param delay the delay to use for the first and subsequent timer callbacks.
	 * @param callback the callback the be called with the timer fires.
	 */
	public GhidraSwinglessTimer(int delay, TimerCallback callback) {
		this(delay,delay,callback);
	}

	/**
	 * Creates a new repeating timer with an initial and continual delay.
	 * @param initialDelay the delay to use for the first timer callbacks.
	 * @param delay the delay to use for subsequent timer callbacks.
	 * @param callback the callback the be called with the timer fires.
	 */
	public GhidraSwinglessTimer(int initialDelay, int delay, TimerCallback callback) {
		this.callback = callback;
		this.delay = delay;
		this.initialDelay = initialDelay;
		this.repeats = true;
	}

	/**
	 * Returns the delay for all callbacks after the first callback.
	 * @return the delay for all callbacks after the first callback.
	 */
	public int getDelay() {
		return delay;
	}

	/**
	 * Returns the delay for the first callback.
	 * @return the delay for the first callback.
	 */
	public int getInitialDelay() {
		return initialDelay;
	}

	/**
	 * Returns true if this timer is set to repeating.
	 * @return true if this timer is set to repeating.
	 */
	public boolean isRepeats() {
		return repeats;
	}

	/**
	 * Sets the delay for all callbacks after the first callback
	 */
	public synchronized void setDelay(int delay) {
		this.delay = delay;
		if (isRunning()) {
			stop();
			start();
		}
	}

	/**
	 * Sets the delay for the first callbacks.
	 */
	public synchronized void setInitialDelay(int initialDelay) {
		this.initialDelay = initialDelay;
	}

	/**
	 * Sets whether this timer repeats.
	 * @param repeats if true, the timer will repeat, if false the timer will only fire once.
	 */
	public synchronized void setRepeats(boolean repeats) {
		this.repeats = repeats;
	}

	/**
	 * Sets the callback to be called when the timer fires.
	 */
	public synchronized void setTimerCallback(TimerCallback callback) {
		this.callback = callback;
	}

	/**
	 * Starts the timer.
	 */
	public synchronized void start() {
		if (timerTask != null) {
			return;
		}
		timerTask = new MyTimerTask();
		incrementCount();
		getTimer().schedule(timerTask, initialDelay, delay);
	}

	/**
	 * Stops the timer.
	 */
	public synchronized void stop() {
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
			decrementCount();
		}
	}

	/**
	 * Returns true if the timer is running.
	 */
	public synchronized boolean isRunning() {
		return timerTask != null;
	}

	class MyTimerTask extends TimerTask {
		@Override
		public void run() {
			TimerCallback c;
			synchronized (GhidraSwinglessTimer.this) {
				c = callback;
				if (!repeats) {
					timerTask.cancel();
					timerTask = null;
					decrementCount();
				}
			}
			if (c != null) {
				c.timerFired();
			}
		}
	}
	static class CleanupTimerTask extends TimerTask {

		@Override
		public void run() {
			cleanupTimer();
		}

	}
	public static void main(String[] args) throws InterruptedException {
		final GhidraTimer t = new GhidraSwinglessTimer(500, null);

		TimerCallback callback1 = new TimerCallback() {
			int i = 0;
			public void timerFired() {
				System.out.println("A: "+i);
				if (++i == 20) {
					t.stop();
				}
			}
		};
		t.setTimerCallback(callback1);
		t.start();

		final GhidraTimer t2 = new GhidraSwinglessTimer(50, null);

		TimerCallback callback2 = new TimerCallback() {
			int i = 0;
			public void timerFired() {
				System.out.println("B: "+i);
				if (++i == 100) {
					t2.stop();
				}
			}
		};
		t2.setInitialDelay(250);
		t2.setTimerCallback(callback2);
		t2.start();

		System.err.println("waiting");
		Thread.sleep(20000);
		synchronized(GhidraSwinglessTimer.class) {
			if (cleanupTask == null) {
				throw new AssertException("cleanup timer is null");
			}
		}

		final GhidraTimer t3 = new GhidraSwinglessTimer(50, null);

		TimerCallback callback3 = new TimerCallback() {
			int i = 0;
			public void timerFired() {
				System.out.println("C: "+i);
				if (++i == 100) {
					t3.stop();
				}
			}
		};
		t3.setInitialDelay(250);
		t3.setTimerCallback(callback3);
		t3.start();

		System.err.println("waiting");
		Thread.sleep(20000);
		synchronized(GhidraSwinglessTimer.class) {
			if (cleanupTask == null) {
				throw new AssertException("cleanup timer is null");
			}
		}

		System.err.println("wait for cleanup;");
		Thread.sleep(CLEANUP_TIMER_THREAD_DELAY);
		synchronized(GhidraSwinglessTimer.class) {
			if (cleanupTask != null) {
				throw new AssertException("cleanup timer did not go away");
			}
		}
		System.err.println("done");
	}

}


text:
var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000;

// route handler for GET /
app.get('/', function(req, res) {
  var data = '
hello world
';
  res.send(data);
});

app.listen(port);

console.log('server started on port %s', port);