text:
namespace mojo {
namespace {

internal::ThreadLocalPointer<RunLoop> current_run_loop;

const MojoTimeTicks kInvalidTimeTicks = static_cast<MojoTimeTicks>(0);

}  // namespace

// State needed for one iteration of WaitMany().
struct RunLoop::WaitState {
  WaitState() : deadline(MOJO_DEADLINE_INDEFINITE) {}

  std::vector<Handle> handles;
  std::vector<MojoHandleSignals> handle_signals;
  MojoDeadline deadline;
};

struct RunLoop::RunState {
  RunState() : should_quit(false) {}

  bool should_quit;
};

RunLoop::RunLoop()
    : run_state_(NULL), next_handler_id_(0), next_sequence_number_(0) {
  assert(!current());
  current_run_loop.Set(this);
}

RunLoop::~RunLoop() {
  assert(current() == this);
  NotifyHandlers(MOJO_RESULT_ABORTED, IGNORE_DEADLINE);
  current_run_loop.Set(NULL);
}

// static
void RunLoop::SetUp() {
  current_run_loop.Allocate();
}

// static
void RunLoop::TearDown() {
  assert(!current());
  current_run_loop.Free();
}

// static
RunLoop* RunLoop::current() {
  return current_run_loop.Get();
}

void RunLoop::AddHandler(RunLoopHandler* handler,
                         const Handle& handle,
                         MojoHandleSignals handle_signals,
                         MojoDeadline deadline) {
  assert(current() == this);
  assert(handler);
  assert(handle.is_valid());
  // Assume it's an error if someone tries to reregister an existing handle.
  assert(0u == handler_data_.count(handle));
  HandlerData handler_data;
  handler_data.handler = handler;
  handler_data.handle_signals = handle_signals;
  handler_data.deadline = (deadline == MOJO_DEADLINE_INDEFINITE) ?
      kInvalidTimeTicks :
      GetTimeTicksNow() + static_cast<MojoTimeTicks>(deadline);
  handler_data.id = next_handler_id_++;
  handler_data_[handle] = handler_data;
}

void RunLoop::RemoveHandler(const Handle& handle) {
  assert(current() == this);
  handler_data_.erase(handle);
}

bool RunLoop::HasHandler(const Handle& handle) const {
  return handler_data_.find(handle) != handler_data_.end();
}

void RunLoop::Run() {
  RunInternal(UNTIL_EMPTY);
}

void RunLoop::RunUntilIdle() {
  RunInternal(UNTIL_IDLE);
}

void RunLoop::RunInternal(RunMode run_mode) {
  assert(current() == this);
  RunState* old_state = run_state_;
  RunState run_state;
  run_state_ = &run_state;
  for (;;) {
    bool did_work = DoDelayedWork();
    if (run_state.should_quit)
      break;
    did_work |= Wait(run_mode == UNTIL_IDLE);
    if (run_state.should_quit)
      break;
    if (!did_work && run_mode == UNTIL_IDLE)
      break;
  }
  run_state_ = old_state;
}

bool RunLoop::DoDelayedWork() {
  MojoTimeTicks now = GetTimeTicksNow();
  if (!delayed_tasks_.empty() && delayed_tasks_.top().run_time <= now) {
    PendingTask task = delayed_tasks_.top();
    delayed_tasks_.pop();
    task.task.Run();
    return true;
  }
  return false;
}

void RunLoop::Quit() {
  assert(current() == this);
  if (run_state_)
    run_state_->should_quit = true;
}

void RunLoop::PostDelayedTask(const Closure& task, MojoTimeTicks delay) {
  assert(current() == this);
  MojoTimeTicks run_time = delay + GetTimeTicksNow();
  delayed_tasks_.push(PendingTask(task, run_time, next_sequence_number_++));
}

bool RunLoop::Wait(bool non_blocking) {
  const WaitState wait_state = GetWaitState(non_blocking);
  if (wait_state.handles.empty() && delayed_tasks_.empty()) {
    Quit();
    return false;
  }

  const MojoResult result = WaitMany(wait_state.handles,
                                     wait_state.handle_signals,
                                     wait_state.deadline);
  if (result >= 0) {
    const size_t index = static_cast<size_t>(result);
    assert(handler_data_.find(wait_state.handles[index]) !=
           handler_data_.end());
    handler_data_[wait_state.handles[index]].handler->OnHandleReady(
        wait_state.handles[index]);
    return true;
  }

  switch (result) {
    case MOJO_RESULT_INVALID_ARGUMENT:
    case MOJO_RESULT_FAILED_PRECONDITION:
      return RemoveFirstInvalidHandle(wait_state);
    case MOJO_RESULT_DEADLINE_EXCEEDED:
      return NotifyHandlers(MOJO_RESULT_DEADLINE_EXCEEDED, CHECK_DEADLINE);
  }

  assert(false);
  return false;
}

bool RunLoop::NotifyHandlers(MojoResult error, CheckDeadline check) {
  bool notified = false;

  // Make a copy in case someone tries to add/remove new handlers as part of
  // notifying.
  const HandleToHandlerData cloned_handlers(handler_data_);
  const MojoTimeTicks now(GetTimeTicksNow());
  for (HandleToHandlerData::const_iterator i = cloned_handlers.begin();
       i != cloned_handlers.end(); ++i) {
    // Only check deadline exceeded if that's what we're notifying.
    if (check == CHECK_DEADLINE && (i->second.deadline == kInvalidTimeTicks ||
                                    i->second.deadline > now)) {
      continue;
    }

    // Since we're iterating over a clone of the handlers, verify the handler
    // is still valid before notifying.
    if (handler_data_.find(i->first) == handler_data_.end() ||
        handler_data_[i->first].id != i->second.id) {
      continue;
    }

    RunLoopHandler* handler = i->second.handler;
    handler_data_.erase(i->first);
    handler->OnHandleError(i->first, error);
    notified = true;
  }

  return notified;
}

bool RunLoop::RemoveFirstInvalidHandle(const WaitState& wait_state) {
  for (size_t i = 0; i < wait_state.handles.size(); ++i) {
    const MojoResult result =
        mojo::Wait(wait_state.handles[i], wait_state.handle_signals[i],
                   static_cast<MojoDeadline>(0));
    if (result == MOJO_RESULT_INVALID_ARGUMENT ||
        result == MOJO_RESULT_FAILED_PRECONDITION) {
      // Remove the handle first, this way if OnHandleError() tries to remove
      // the handle our iterator isn't invalidated.
      assert(handler_data_.find(wait_state.handles[i]) != handler_data_.end());
      RunLoopHandler* handler =
          handler_data_[wait_state.handles[i]].handler;
      handler_data_.erase(wait_state.handles[i]);
      handler->OnHandleError(wait_state.handles[i], result);
      return true;
    }
    assert(MOJO_RESULT_DEADLINE_EXCEEDED == result);
  }
  return false;
}

RunLoop::WaitState RunLoop::GetWaitState(bool non_blocking) const {
  WaitState wait_state;
  MojoTimeTicks min_time = kInvalidTimeTicks;
  for (HandleToHandlerData::const_iterator i = handler_data_.begin();
       i != handler_data_.end(); ++i) {
    wait_state.handles.push_back(i->first);
    wait_state.handle_signals.push_back(i->second.handle_signals);
    if (!non_blocking && i->second.deadline != kInvalidTimeTicks &&
        (min_time == kInvalidTimeTicks || i->second.deadline < min_time)) {
      min_time = i->second.deadline;
    }
  }
  if (!delayed_tasks_.empty()) {
    MojoTimeTicks delayed_min_time = delayed_tasks_.top().run_time;
    if (min_time == kInvalidTimeTicks)
      min_time = delayed_min_time;
    else
      min_time = std::min(min_time, delayed_min_time);
  }
  if (non_blocking) {
    wait_state.deadline = static_cast<MojoDeadline>(0);
  } else if (min_time != kInvalidTimeTicks) {
    const MojoTimeTicks now = GetTimeTicksNow();
    if (min_time < now)
      wait_state.deadline = static_cast<MojoDeadline>(0);
    else
      wait_state.deadline = static_cast<MojoDeadline>(min_time - now);
  }
  return wait_state;
}

RunLoop::PendingTask::PendingTask(const Closure& task,
                                  MojoTimeTicks run_time,
                                  uint64_t sequence_number)
    : task(task), run_time(run_time), sequence_number(sequence_number) {
}

RunLoop::PendingTask::~PendingTask() {
}

bool RunLoop::PendingTask::operator<(const RunLoop::PendingTask& other) const {
  if (run_time != other.run_time) {
    // std::priority_queue<> puts the least element at the end of the queue. We
    // want the soonest eligible task to be at the head of the queue, so
    // run_times further in the future are considered lesser.
    return run_time > other.run_time;
  }

  return sequence_number > other.sequence_number;
}

}  // namespace mojo


text:
.class public Lcom/android/systemui/recents/model/TaskLockPreference;
.super Ljava/lang/Object;
.source "TaskLockPreference.java"

# instance fields
.field private mContext:Landroid/content/Context;

.field private mDefaultPrefs:Landroid/content/SharedPreferences;

.field private mPrefs:Landroid/content/SharedPreferences;

# direct methods
.method public constructor <init>(Landroid/content/Context;)V
    .locals 2

    const/4 v1, 0x0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mContext:Landroid/content/Context;

    const-string/jumbo v0, "TaskLockPreferencePlus"

    invoke-virtual {p1, v0, v1}, Landroid/content/Context;->getSharedPreferences(Ljava/lang/String;I)Landroid/content/SharedPreferences;

    move-result-object v0

    iput-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mPrefs:Landroid/content/SharedPreferences;

    const-string/jumbo v0, "DefaultLockPreference"

    invoke-virtual {p1, v0, v1}, Landroid/content/Context;->getSharedPreferences(Ljava/lang/String;I)Landroid/content/SharedPreferences;

    move-result-object v0

    iput-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    invoke-direct {p0}, Lcom/android/systemui/recents/model/TaskLockPreference;->cleanupDefaultPrefIfNeeded()V

    return-void
.end method

.method private cleanupDefaultPrefIfNeeded()V
    .locals 2

    const/4 v1, 0x0

    iget-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    if-eqz v0, :cond_1

    iget-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v0}, Landroid/content/SharedPreferences;->getAll()Ljava/util/Map;

    move-result-object v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v0}, Landroid/content/SharedPreferences;->getAll()Ljava/util/Map;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Map;->size()I

    move-result v0

    if-nez v0, :cond_1

    :cond_0
    iput-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    :cond_1
    return-void
.end method

.method private getAffinityName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;
    .locals 3

    const/4 v2, 0x0

    invoke-static {}, Lcom/android/systemui/recents/Recents;->getTaskLoader()Lcom/android/systemui/recents/model/RecentsTaskLoader;

    move-result-object v1

    invoke-virtual {v1, p1}, Lcom/android/systemui/recents/model/RecentsTaskLoader;->getAndUpdateActivityInfo(Lcom/android/systemui/recents/model/Task$TaskKey;)Landroid/content/pm/ActivityInfo;

    move-result-object v0

    if-eqz v0, :cond_0

    iget-object v1, v0, Landroid/content/pm/ActivityInfo;->taskAffinity:Ljava/lang/String;

    return-object v1

    :cond_0
    return-object v2
.end method

.method private getComponentName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;
    .locals 1

    iget-object v0, p1, Lcom/android/systemui/recents/model/Task$TaskKey;->baseIntent:Landroid/content/Intent;

    invoke-virtual {v0}, Landroid/content/Intent;->getComponent()Landroid/content/ComponentName;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/ComponentName;->flattenToShortString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method private getKey(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;
    .locals 2

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-direct {p0, p1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getComponentName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p1, Lcom/android/systemui/recents/model/Task$TaskKey;->userId:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

# virtual methods
.method public dump(Ljava/lang/String;Ljava/io/PrintWriter;)V
    .locals 6

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v4, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string/jumbo v5, "  "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {p2, p1}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-virtual {p0}, Lcom/android/systemui/recents/model/TaskLockPreference;->getClass()Ljava/lang/Class;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/Class;->getSimpleName()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {p2, v4}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-virtual {p2}, Ljava/io/PrintWriter;->println()V

    iget-object v4, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v4}, Landroid/content/SharedPreferences;->getAll()Ljava/util/Map;

    move-result-object v3

    invoke-interface {v3}, Ljava/util/Map;->entrySet()Ljava/util/Set;

    move-result-object v4

    invoke-interface {v4}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v1

    :goto_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v4

    if-eqz v4, :cond_0

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/util/Map$Entry;

    invoke-virtual {p2, v2}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    const-string/jumbo v4, " key="

    invoke-virtual {p2, v4}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-interface {v0}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v4

    check-cast v4, Ljava/lang/String;

    invoke-virtual {p2, v4}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    const-string/jumbo v4, " value="

    invoke-virtual {p2, v4}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-interface {v0}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {p2, v4}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    invoke-virtual {p2}, Ljava/io/PrintWriter;->println()V

    goto :goto_0

    :cond_0
    return-void
.end method

.method public getLockedTasksCount()I
    .locals 1

    iget-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v0}, Landroid/content/SharedPreferences;->getAll()Ljava/util/Map;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Map;->size()I

    move-result v0

    return v0
.end method

.method public isDefaultLockedPackage(Ljava/lang/String;)Z
    .locals 2

    const/4 v1, 0x0

    iget-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    if-nez v0, :cond_0

    return v1

    :cond_0
    iget-object v0, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v0, p1, v1}, Landroid/content/SharedPreferences;->getBoolean(Ljava/lang/String;Z)Z

    move-result v0

    if-eqz v0, :cond_1

    const/4 v0, 0x1

    return v0

    :cond_1
    return v1
.end method

.method public isTaskLocked(Lcom/android/systemui/recents/model/Task$TaskKey;)Z
    .locals 6

    const/4 v5, 0x0

    const/4 v4, 0x1

    const/4 v3, 0x0

    iget-object v1, p1, Lcom/android/systemui/recents/model/Task$TaskKey;->baseIntent:Landroid/content/Intent;

    invoke-virtual {v1}, Landroid/content/Intent;->getComponent()Landroid/content/ComponentName;

    move-result-object v1

    invoke-virtual {v1}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {p0, v1}, Lcom/android/systemui/recents/model/TaskLockPreference;->isDefaultLockedPackage(Ljava/lang/String;)Z

    move-result v1

    if-eqz v1, :cond_0

    return v4

    :cond_0
    iget-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mPrefs:Landroid/content/SharedPreferences;

    invoke-direct {p0, p1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getKey(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v2

    invoke-interface {v1, v2, v5}, Landroid/content/SharedPreferences;->getStringSet(Ljava/lang/String;Ljava/util/Set;)Ljava/util/Set;

    move-result-object v0

    if-eqz v0, :cond_1

    invoke-interface {v0}, Ljava/util/Set;->isEmpty()Z

    move-result v1

    if-eqz v1, :cond_2

    :cond_1
    return v3

    :cond_2
    invoke-direct {p0, p1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getComponentName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_3

    invoke-direct {p0, p1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getAffinityName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v1}, Ljava/util/Set;->contains(Ljava/lang/Object;)Z

    move-result v1

    if-eqz v1, :cond_3

    return v4

    :cond_3
    return v3
.end method

.method public removeLockedTask(Lcom/android/systemui/recents/model/Task;)V
    .locals 3

    iget-object v2, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v2}, Landroid/content/SharedPreferences;->edit()Landroid/content/SharedPreferences$Editor;

    move-result-object v1

    iget-object v2, p1, Lcom/android/systemui/recents/model/Task;->key:Lcom/android/systemui/recents/model/Task$TaskKey;

    invoke-direct {p0, v2}, Lcom/android/systemui/recents/model/TaskLockPreference;->getKey(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v2

    invoke-interface {v1, v2}, Landroid/content/SharedPreferences$Editor;->remove(Ljava/lang/String;)Landroid/content/SharedPreferences$Editor;

    invoke-interface {v1}, Landroid/content/SharedPreferences$Editor;->apply()V

    iget-object v2, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    if-eqz v2, :cond_0

    iget-object v2, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v2}, Landroid/content/SharedPreferences;->edit()Landroid/content/SharedPreferences$Editor;

    move-result-object v0

    iget-object v2, p1, Lcom/android/systemui/recents/model/Task;->key:Lcom/android/systemui/recents/model/Task$TaskKey;

    iget-object v2, v2, Lcom/android/systemui/recents/model/Task$TaskKey;->baseIntent:Landroid/content/Intent;

    invoke-virtual {v2}, Landroid/content/Intent;->getComponent()Landroid/content/ComponentName;

    move-result-object v2

    invoke-virtual {v2}, Landroid/content/ComponentName;->getPackageName()Ljava/lang/String;

    move-result-object v2

    invoke-interface {v0, v2}, Landroid/content/SharedPreferences$Editor;->remove(Ljava/lang/String;)Landroid/content/SharedPreferences$Editor;

    invoke-interface {v0}, Landroid/content/SharedPreferences$Editor;->apply()V

    invoke-direct {p0}, Lcom/android/systemui/recents/model/TaskLockPreference;->cleanupDefaultPrefIfNeeded()V

    :cond_0
    return-void
.end method

.method public saveDefaultLockedPackage(Ljava/lang/String;)V
    .locals 4

    iget-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    if-nez v1, :cond_0

    iget-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mContext:Landroid/content/Context;

    const-string/jumbo v2, "DefaultLockPreference"

    const/4 v3, 0x0

    invoke-virtual {v1, v2, v3}, Landroid/content/Context;->getSharedPreferences(Ljava/lang/String;I)Landroid/content/SharedPreferences;

    move-result-object v1

    iput-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    :cond_0
    iget-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mDefaultPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v1}, Landroid/content/SharedPreferences;->edit()Landroid/content/SharedPreferences$Editor;

    move-result-object v0

    const/4 v1, 0x1

    invoke-interface {v0, p1, v1}, Landroid/content/SharedPreferences$Editor;->putBoolean(Ljava/lang/String;Z)Landroid/content/SharedPreferences$Editor;

    invoke-interface {v0}, Landroid/content/SharedPreferences$Editor;->apply()V

    return-void
.end method

.method public saveLockedTask(Lcom/android/systemui/recents/model/Task;)V
    .locals 3

    new-instance v0, Ljava/util/HashSet;

    invoke-direct {v0}, Ljava/util/HashSet;-><init>()V

    iget-object v1, p1, Lcom/android/systemui/recents/model/Task;->key:Lcom/android/systemui/recents/model/Task$TaskKey;

    invoke-direct {p0, v1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getComponentName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    iget-object v1, p1, Lcom/android/systemui/recents/model/Task;->key:Lcom/android/systemui/recents/model/Task$TaskKey;

    invoke-direct {p0, v1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getAffinityName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v1}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    iget-object v1, p1, Lcom/android/systemui/recents/model/Task;->key:Lcom/android/systemui/recents/model/Task$TaskKey;

    invoke-direct {p0, v1}, Lcom/android/systemui/recents/model/TaskLockPreference;->getComponentName(Lcom/android/systemui/recents/model/Task$TaskKey;)Ljava/lang/String;

    move-result-object v1

    iget-object v2, p1, Lcom/android/systemui/recents/model/Task;->key:Lcom/android/systemui/recents/model/Task$TaskKey;

    iget v2, v2, Lcom/android/systemui/recents/model/Task$TaskKey;->userId:I

    invoke-virtual {p0, v1, v2, v0}, Lcom/android/systemui/recents/model/TaskLockPreference;->saveLockedTask(Ljava/lang/String;ILjava/util/Set;)V

    return-void
.end method

.method public saveLockedTask(Ljava/lang/String;ILjava/util/Set;)V
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "I",
            "Ljava/util/Set",
            "<",
            "Ljava/lang/String;",
            ">;)V"
        }
    .end annotation

    iget-object v1, p0, Lcom/android/systemui/recents/model/TaskLockPreference;->mPrefs:Landroid/content/SharedPreferences;

    invoke-interface {v1}, Landroid/content/SharedPreferences;->edit()Landroid/content/SharedPreferences$Editor;

    move-result-object v0

    const/16 v1, -0x2710

    if-eq p2, v1, :cond_0

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-interface {v0, v1, p3}, Landroid/content/SharedPreferences$Editor;->putStringSet(Ljava/lang/String;Ljava/util/Set;)Landroid/content/SharedPreferences$Editor;

    :goto_0
    invoke-interface {v0}, Landroid/content/SharedPreferences$Editor;->apply()V

    return-void

    :cond_0
    invoke-interface {v0, p1, p3}, Landroid/content/SharedPreferences$Editor;->putStringSet(Ljava/lang/String;Ljava/util/Set;)Landroid/content/SharedPreferences$Editor;

    goto :goto_0
.end method

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#ifndef ZORBA_XERCES_XMLCHARRAY_H
#define ZORBA_XERCES_XMLCHARRAY_H

#ifndef ZORBA_NO_XMLSCHEMA

#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XercesDefs.hpp>
//daniel: this is to make cygwin work; xerces defines WIN32 in case of cygwin, which is wrong
#ifdef CYGWIN
#undef WIN32
#endif // ifdef CYGWIN

#include <zorba/config.h>
#include <zorbatypes/zstring.h>

XERCES_CPP_NAMESPACE_USE

namespace zorba
{

class XMLChArray
{
private:
  XMLCh * buf;

 public:
  XMLChArray(XMLCh* buf_) : buf(buf_) {}

  XMLChArray(const zstring& str)
    :
    buf(XMLString::transcode(str.c_str()))
  {
  }

  ~XMLChArray() { XMLString::release(&buf); }

  XMLCh* get() { return buf; }

  const XMLCh* get () const { return buf; }

  operator XMLCh* () { return get(); }

  operator const XMLCh* () const { return get(); }

  friend std::ostream& operator<<(std::ostream& out, const XMLChArray& xmlChArray)
  {
    out << XMLString::transcode(xmlChArray.get());
    return out;
  }
};

}

#endif // ifndef ZORBA_NO_XMLSCHEMA
#endif // ifndef ZORBA_XERCES_XMLCHARRAY_H

/*
 * Local variables:
 * mode: c++
 * End:
 */
/* vim:set et sw=2 ts=2: */


text:
package org.hibernate.test.annotations.inheritance.joined;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "CLIENT")
public class Client extends Person implements Serializable {
	private static final long serialVersionUID = 1L;

	private String street;

	private String code;

	private String city;

	@ManyToOne(fetch = FetchType.EAGER)
	@JoinTable(name = "CLIENT_ACCOUNT",
			joinColumns = {@JoinColumn(name = "FK_CLIENT", referencedColumnName = "ID")},
			inverseJoinColumns = {@JoinColumn(name = "FK_ACCOUNT", referencedColumnName = "ID")})
	private Account account;

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public Client() {
		super();
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}


text:
package rest

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"path/filepath"
	"testing"

	"github.com/aws/aws-lambda-go/events"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestEndpoint(t *testing.T) {
	var endpoint *Endpoint
	var acceptor *EndpointAcceptor
	var builder *EndpointBuilder

	t.Run("Constructor", func(t *testing.T) {
		id := "the-id"
		method := http.MethodGet
		baseURL := new(url.URL)
		handler := HandlerFunc(func(ctx context.Context, evt events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
			return Respond(http.StatusOK, nil)
		})

		endpoint, acceptor = newEndpoint(id, method, baseURL, handler)
		builder = newEndpointBuilder(endpoint)

		assert.Equal(t, id, acceptor.ID())
		assert.Equal(t, method, acceptor.Method())
		assert.NotNil(t, acceptor.Handler())
		assert.Nil(t, acceptor.Hooks().Pre())
		assert.Nil(t, acceptor.Hooks().Post())

		t.Run("Panics", func(t *testing.T) {
			t.Run("on invalid ID", func(t *testing.T) {
				assert.Panics(t, func() { newEndpoint("", method, baseURL, handler) })
				assert.Panics(t, func() { newEndpoint("invalid ID", method, baseURL, handler) })
			})
			t.Run("on blank method", func(t *testing.T) {
				assert.Panics(t, func() { newEndpoint(id, "", baseURL, handler) })
			})
			t.Run("on nil handler", func(t *testing.T) {
				assert.Panics(t, func() { newEndpoint(id, method, baseURL, nil) })
			})
		})
	})

	t.Run("Type", func(t *testing.T) {
		typ := acceptor.Type()
		assert.Equal(t, "endpoint", typ.ID)
		assert.Equal(t, "Endpoint", typ.Discriminator)
		assert.Equal(t, "E", typ.Short)
	})

	t.Run("Headers", func(t *testing.T) {
		id := "the-header"

		builder.Header(id, true)

		require.Len(t, acceptor.Headers(), 1)

		header := acceptor.Headers()[0]
		assert.Equal(t, id, header.ID())
		assert.True(t, header.Required())

		t.Run("Panics", func(t *testing.T) {
			t.Run("on invalid ID", func(t *testing.T) {
				assert.Panics(t, func() { builder.Header("", true) })
				assert.Panics(t, func() { builder.Header("invalid ID", true) })
			})
			t.Run("on duplicate ID", func(t *testing.T) {
				assert.Panics(t, func() { builder.Header(id, true) })
			})
		})
	})

	t.Run("Query Parameters", func(t *testing.T) {
		id := "the-parameter"

		builder.Query(id, true)

		require.Len(t, acceptor.Query(), 1)

		parameter := acceptor.Query()[0]
		assert.Equal(t, id, parameter.ID())
		assert.True(t, parameter.Required())

		t.Run("Panics", func(t *testing.T) {
			t.Run("on invalid ID", func(t *testing.T) {
				assert.Panics(t, func() { builder.Query("", true) })
				assert.Panics(t, func() { builder.Query("invalid ID", true) })
			})
			t.Run("on duplicate ID", func(t *testing.T) {
				assert.Panics(t, func() { builder.Query(id, true) })
			})
		})
	})

	t.Run("Response", func(t *testing.T) {
		status := http.StatusOK

		builder.Response(status)

		require.Len(t, acceptor.Responses(), 1)

		response := acceptor.Responses()[0]
		assert.Equal(t, "200", response.Status())

		t.Run("Panics", func(t *testing.T) {
			t.Run("on invalid status code", func(t *testing.T) {
				assert.Panics(t, func() { builder.Response(99) })
				assert.Panics(t, func() { builder.Response(600) })
			})
			t.Run("on duplicate status code", func(t *testing.T) {
				assert.Panics(t, func() { builder.Response(status) })
			})
		})
	})

	t.Run("Regular Expression Response", func(t *testing.T) {
		status := "the-status"

		builder.ResponseRE(status)

		require.Len(t, acceptor.Responses(), 2)

		response := acceptor.Responses()[1]
		assert.Equal(t, status, response.Status())

		t.Run("Panics", func(t *testing.T) {
			t.Run("on duplicate ID", func(t *testing.T) {
				assert.Panics(t, func() { builder.ResponseRE(status) })
			})
		})
	})

	t.Run("Call", func(t *testing.T) {
		ctx := context.Background()
		method := http.MethodGet
		path := "/the/path"

		server := httptest.NewServer(
			http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				assert.Equal(t, method, r.Method)
				assert.Equal(t, path, r.URL.Path)
			}),
		)
		defer server.Close()

		baseURL, err := url.Parse(server.URL)
		require.NoError(t, err)

		endpoint, _ := newEndpoint("the-id", method, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
			return Respond(http.StatusOK, nil)
		}))
		endpoint.route = path

		_, err = endpoint.Call(ctx, nil)
		assert.NoError(t, err)

		t.Run("passes headers", func(t *testing.T) {
			id := "the-header"
			normalized := "The-Header"
			value := "header-value"

			server := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					assert.Contains(t, r.Header, normalized)
					assert.Equal(t, value, r.Header.Get(normalized))
				}),
			)
			defer server.Close()

			baseURL, err := url.Parse(server.URL)
			require.NoError(t, err)

			endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
				return Respond(http.StatusOK, nil)
			}), func(endpoint *EndpointBuilder) {
				endpoint.Header(id, true)
			})
			endpoint.route = path

			_, err = endpoint.Call(ctx, nil, func(request *RequestBuilder) {
				request.Header(id, value)
			})
			assert.NoError(t, err)
		})

		t.Run("encodes path parameters", func(t *testing.T) {
			id := "the-param"
			value := "param-value"

			server := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					assert.Equal(t, "/the/path/param-value", r.URL.Path)
				}),
			)
			defer server.Close()

			baseURL, err := url.Parse(server.URL)
			require.NoError(t, err)

			endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
				return Respond(http.StatusOK, nil)
			}))
			endpoint.route = fmt.Sprintf("/the/path/{%s}", id)
			endpoint.pathParameters = append(endpoint.pathParameters, newParameter(id, true))

			_, err = endpoint.Call(ctx, nil, func(request *RequestBuilder) {
				request.Path(id, value)
			})
			assert.NoError(t, err)
		})

		t.Run("passes query parameters", func(t *testing.T) {
			id := "the-param"
			value := "param-value"

			server := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					query := r.URL.Query()

					require.Len(t, query, 1)
					assert.Contains(t, query, id)
					assert.Equal(t, value, query.Get(id))
				}),
			)
			defer server.Close()

			baseURL, err := url.Parse(server.URL)
			require.NoError(t, err)

			endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
				return Respond(http.StatusOK, nil)
			}), func(endpoint *EndpointBuilder) {
				endpoint.Query(id, true)
			})
			endpoint.route = "/the/path"

			_, err = endpoint.Call(ctx, nil, func(request *RequestBuilder) {
				request.Query(id, value)
			})
			assert.NoError(t, err)
		})

		t.Run("encodes body", func(t *testing.T) {
			body := map[string]interface{}{
				"Foo": "bar",
			}

			server := httptest.NewServer(
				http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					assert.Contains(t, r.Header, "Content-Type")
					assert.Equal(t, "application/json", r.Header.Get("Content-Type"))

					var b map[string]interface{}
					defer r.Body.Close()
					require.NoError(t, json.NewDecoder(r.Body).Decode(&b))
					assert.Equal(t, body, b)
				}),
			)
			defer server.Close()

			baseURL, err := url.Parse(server.URL)
			require.NoError(t, err)

			endpoint, _ := newEndpoint("the-id", http.MethodPost, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
				return Respond(http.StatusOK, nil)
			}))
			endpoint.route = "/the/path"

			_, err = endpoint.Call(ctx, body)
			assert.NoError(t, err)

			t.Run("Panics", func(t *testing.T) {
				t.Run("when body is passed to HEAD endpoint", func(t *testing.T) {
					endpoint, _ := newEndpoint("the-id", http.MethodHead, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
						return Respond(http.StatusOK, nil)
					}))
					endpoint.route = path

					assert.Panics(t, func() { endpoint.Call(ctx, body) })
				})
				t.Run("when body is passed to GET endpoint", func(t *testing.T) {
					endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
						return Respond(http.StatusOK, nil)
					}))
					endpoint.route = path

					assert.Panics(t, func() { endpoint.Call(ctx, body) })
				})
			})
		})

		t.Run("strips prefix", func(t *testing.T) {

			server := httptest.NewServer(
				http.StripPrefix("/prefix", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
					assert.Equal(t, path, r.URL.Path)
				})),
			)
			defer server.Close()

			baseURL, err := url.Parse(server.URL)
			assert.NoError(t, err)

			baseURL.Path = filepath.Join(baseURL.Path, "prefix")

			endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
				return Respond(http.StatusOK, nil)
			}))
			endpoint.route = "/the/path"

			_, err = endpoint.Call(ctx, nil)
			assert.NoError(t, err)
		})

		t.Run("Returns error", func(t *testing.T) {
			t.Run("on invalid method", func(t *testing.T) {
				endpoint, _ := newEndpoint("the-id", "invalid method", baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
					return Respond(http.StatusOK, nil)
				}))
				endpoint.route = "/the/path"

				_, err := endpoint.Call(ctx, nil)
				assert.Error(t, err)
			})
			t.Run("on invalid path", func(t *testing.T) {
				endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
					return Respond(http.StatusOK, nil)
				}))
				endpoint.route = "%%"

				_, err := endpoint.Call(ctx, nil)
				assert.Error(t, err)
			})
			t.Run("on unmarshalable body", func(t *testing.T) {
				endpoint, _ := newEndpoint("the-id", http.MethodPost, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
					return Respond(http.StatusOK, nil)
				}))
				endpoint.route = "/the/path"

				_, err := endpoint.Call(ctx, make(chan int))
				assert.Error(t, err)
			})
			t.Run("on HTTP error", func(t *testing.T) {
				baseURL := &url.URL{Scheme: "http", Host: "i-dont-exist.foo"}
				endpoint, _ := newEndpoint("the-id", http.MethodGet, baseURL, HandlerFunc(func(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
					return Respond(http.StatusOK, nil)
				}))
				endpoint.route = "/the/path"

				_, err := endpoint.Call(ctx, nil)
				assert.Error(t, err)
			})
		})
	})
}

func TestRequest(t *testing.T) {
	baseURL := new(url.URL)

	var acceptor *RequestAcceptor

	t.Run("Constructor", func(t *testing.T) {
		acceptor = newRequest(baseURL)

		assert.Equal(t, baseURL, acceptor.URL())
		assert.NotNil(t, acceptor.Header())
		assert.Empty(t, acceptor.Header())
	})

	t.Run("Header", func(t *testing.T) {
		id := "The-Header"
		value := "the-value"

		acceptor := newRequest(baseURL, func(request *RequestBuilder) {
			request.Header(id, value)
		})
		assert.Equal(t, value, acceptor.Header().Get(id))

		t.Run("Panics", func(t *testing.T) {
			t.Run("on duplicate headers", func(t *testing.T) {
				assert.Panics(t, func() {
					newRequest(baseURL, func(request *RequestBuilder) {
						request.Header(id, "a-value")
						request.Header(id, "another-value")
					})
				})
			})
		})
	})

	t.Run("Path Parameter", func(t *testing.T) {
		id := "param"
		value := "the-value"

		acceptor := newRequest(baseURL, func(request *RequestBuilder) {
			request.request.url.Path = fmt.Sprintf("/foo/{%s}/bar", id)
			request.Path(id, value)
		})
		assert.Equal(t, fmt.Sprintf("/foo/%s/bar", value), acceptor.URL().Path)

		t.Run("Panics", func(t *testing.T) {
			t.Run("on duplicate path parameter", func(t *testing.T) {
				assert.Panics(t, func() {
					newRequest(baseURL, func(request *RequestBuilder) {
						request.request.url.Path = fmt.Sprintf("/foo/{%s}/bar", id)
						request.Path(id, "a-value")
						request.Path(id, "another-value")
					})
				})
			})
			t.Run("on unknown path parameter", func(t *testing.T) {
				assert.Panics(t, func() {
					newRequest(baseURL, func(request *RequestBuilder) {
						request.request.url.Path = fmt.Sprintf("/foo/{%s}/bar", id)
						request.Path("not-a-path-parameter", value)
					})
				})
			})
		})
	})

	t.Run("Query Parameter", func(t *testing.T) {
		id := "the-param"
		value := "the-value"

		acceptor := newRequest(baseURL, func(request *RequestBuilder) {
			request.Query(id, value)
		})
		assert.Equal(t, value, acceptor.URL().Query().Get(id))

		t.Run("Panics", func(t *testing.T) {
			t.Run("on duplicate parameters", func(t *testing.T) {
				assert.Panics(t, func() {
					newRequest(baseURL, func(request *RequestBuilder) {
						request.Query(id, "a-value")
						request.Query(id, "another-value")
					})
				})
			})
		})
	})
}


text:
extract:
	${tooldir}/ecore2bgf api2mol.ecore grammar.bgf

get:
	wget http://modelum.es/trac/api2mol/raw-attachment/wiki/WikiStart/api2mol.ecore

include ../../Makefile.grammar


text:
package stroom.app.client.gin;

import stroom.help.client.HelpPlugin;

import com.google.gwt.inject.client.AsyncProvider;

public interface PluginsGinjector {

    AsyncProvider<HelpPlugin> getHelpPlugin();
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SM2Core.Visualization {
	public interface CombatView: Infobox {
	}
}


text:
<?php

namespace Example\Composite\Value;

class ValueHolder implements Validator {
    function isValid($value) {
        return true;
    }
}


text:
<template name="visWordCloud">

</template>

<template name="visWordCloudForm">

      Text Field
      {{> dropdown name="textField" value=settings.textField items=fields}}

      Value Field
      {{> dropdown name="valueField" value=settings.valueField items=fields}}

      Min font size
      <input type="number" name="minSize" value={{settings.minSize}}>

      Max font size
      <input type="number" name="maxSize" value={{settings.maxSize}}>

      Exponent
      <input type="number" name="exponent" value={{settings.exponent}}>

</template>


text:
#include "static_histogram.h"

#include <algorithm>
#include <cmath>
#ifndef NDEBUG
#include <iostream>
#endif

namespace leveldb {

StaticHistogram::StaticHistogram(std::vector<std::pair<Slice,Slice>>* bs,
                                 const Comparator* key_cmp)
  : key_cmp_(key_cmp),
    max_bucket_(nullptr),
    total_(0),
    dirty_heap_(false) {
  buckets_.reserve(bs->size());
  for (uint32_t i = 0; i < bs->size(); i++) {
    buckets_.emplace_back((*bs)[i].first, (*bs)[i].second);
    min_bucket_heap_.push_back(&buckets_.back());
  }
  // make heap for min buckets
  //std::make_heap(min_bucket_heap_.begin(), min_bucket_heap_.end(), BySmallestBucketCount(key_cmp_));
  // max bucket is (arbitrarily) the last element since they all have a zero count
  max_bucket_.store(&buckets_.back());
}

StaticHistogram::StaticHistogram(std::vector<FileMetaData*>* files,
                                 Histogram* base,
                                 const Comparator* key_cmp)
  : key_cmp_(key_cmp),
    max_bucket_(nullptr),
    total_(0),
    dirty_heap_(true) {
  buckets_.reserve(files->size());
  Bucket* m = nullptr;
  for (uint32_t i = 0; i < files->size(); i++) {
    Slice smallest = (*files)[i]->smallest.user_key();
    Slice largest = (*files)[i]->largest.user_key();
    uint64_t count = base ? base->EstimateCountForRange(smallest, largest) : 0;
    buckets_.emplace_back(smallest, largest, count);
    min_bucket_heap_.push_back(&buckets_.back());
    total_ += count;
    if (m == nullptr || count > m->count) {
      m = &buckets_.back();
    }
  }
  // create heap for min buckets
  std::make_heap(min_bucket_heap_.begin(), min_bucket_heap_.end(), BySmallestBucketCount(key_cmp_));
  dirty_heap_ = false;

  // set max bucket
  max_bucket_.store(m);
}

StaticHistogram::StaticHistogram(std::vector<FileMetaData*>* files,
                                 const Comparator* key_cmp)
  : StaticHistogram(files, nullptr, key_cmp)
{}

uint32_t StaticHistogram::IndexOf(const Slice& k) {
  Bucket b(k, k);
  auto fn = [&](const Bucket& a, const Bucket& b) {
    return key_cmp_->Compare(a.largest, b.largest) <= 0;
  };
  auto iter = std::upper_bound(buckets_.begin(), buckets_.end(), b, fn);
  return iter - buckets_.begin();
}

StaticHistogram::Bucket& StaticHistogram::BucketFor(const Slice& k) {
  auto idx = IndexOf(k);
#ifndef NDEBUG
  /*
  assert(key_cmp_->Compare(buckets_[idx].smallest, k) <= 0
         && key_cmp_->Compare(k, buckets_[idx].largest) <= 0);
  */
#endif
  return buckets_[idx];
}

void StaticHistogram::MaybeUpdateMin(Bucket* updated) {
  MutexLock l(&min_bucket_mutex_);
  if (!dirty_heap_ && min_bucket_heap_.front() == updated) {
    dirty_heap_ = true;
  }
}

void StaticHistogram::MaybeUpdateMax(Bucket* updated) {
  for (;;) {
    Bucket* curr_max = max_bucket_.load();
    if (curr_max->count > updated->count ||
        max_bucket_.compare_exchange_strong(curr_max, updated)) {
      return;
    }
  }
}

uint64_t StaticHistogram::AddCount(const Slice& key, uint64_t c) {
  Bucket& bucket = BucketFor(key);
  bucket.count += c;
  MaybeUpdateMin(&bucket);
  MaybeUpdateMax(&bucket);
  total_ += c;
  return bucket.count;
}

uint64_t StaticHistogram::AddCountForRange(const Slice& first, const Slice& last, uint64_t c) {
  uint32_t start = IndexOf(first);
  uint32_t end = IndexOf(last);

  uint64_t count_for_range = 0;
  uint32_t num_buckets = end - start + 1;
  uint64_t add_per_bucket = c / num_buckets;
  for (uint32_t i = start; i <= end; i++) {
    buckets_[i].count += add_per_bucket;
    count_for_range += buckets_[i].count;
    MaybeUpdateMin(&buckets_[i]);
    MaybeUpdateMax(&buckets_[i]);
  }
  total_ += c;
  return count_for_range;
}

uint64_t StaticHistogram::EstimateCount(const Slice& key) {
  if (buckets_.empty()) {
    return 0;
  }
  Bucket& bucket = BucketFor(key);
  return bucket.count;
}

uint64_t StaticHistogram::EstimateCountForRange(const Slice& first, const Slice& last) {
#ifndef NDEBUG
  assert(key_cmp_->Compare(first, last) <= 1);
#endif
  if (buckets_.empty()) {
    // no buckets means no counts
    return 0;
  } else if (key_cmp_->Compare(last, buckets_.front().smallest) < 0) {
    // requested key range is entirely before what this histogram tracks
    return 0;
  } else if (key_cmp_->Compare(buckets_.back().largest, first) < 0) {
    // requested key range is entirely after what this histogram tracks
    return 0;
  }
  uint32_t start = IndexOf(first);
  uint32_t end = IndexOf(last);
  if (end >= buckets_.size()) {
    end = buckets_.size() - 1;
  }
#ifndef NDEBUG
  assert(start <= end);
#endif
  if (start == end) {
    if (key_cmp_->Compare(last, buckets_[start].smallest) < 0 ||
        key_cmp_->Compare(buckets_[end].largest, first) < 0) {
      // first/last falls into a gap between buckets start and start-1
      return 0;
    } else {
      // buckets[start].smallest < first < last < buckets[start].largest
      return buckets_[start].count;
    }
  }
  uint64_t count = buckets_[start].count / 2 + buckets_[end].count / 2;
  for (unsigned i = start + 1; i <= end - 1; i++) {
    count += buckets_[i].count;
  }
  return count;
}

uint64_t StaticHistogram::GetBucketCount(const Slice& key) {
  if (buckets_.empty()) {
    return 0;
  }
  Bucket& bucket = BucketFor(key);
  return bucket.count;
}

void StaticHistogram::Merge(Histogram* other) {
  std::vector<Bucket> new_buckets;
  new_buckets.reserve(buckets_.size());
  uint64_t new_total = 0;
  for (auto& b : buckets_) {
    uint64_t new_count = other->EstimateCountForRange(b.smallest, b.largest);
    new_buckets.emplace_back(b.smallest, b.largest, new_count);
    new_total += new_count;
  }
  buckets_ = std::move(new_buckets);
  total_.store(new_total);
}

uint64_t StaticHistogram::GetAverageBucketCount() {
    if (buckets_.size() > 0){
        return total_.load() / buckets_.size();
    }
    else{
        return 0;
    }
}

uint64_t StaticHistogram::GetMedianBucketCount() {
  if (buckets_.empty()) {
    return 0;
  }
  return buckets_[buckets_.size() / 2].count;
}

uint64_t StaticHistogram::GetMaxBucketCount(std::pair<Slice,Slice>* p) {
  if (buckets_.empty()) {
    return 0;
  }
  Bucket* max = max_bucket_.load();
  if (p != nullptr) {
    p->first = max->smallest;
    p->second = max->largest;
  }
  return max->count;
}

uint64_t StaticHistogram::GetMinBucketCount(std::pair<Slice,Slice>* p) {
  if (buckets_.empty()) {
    return 0;
  }
  Bucket* min = nullptr;
  {
    MutexLock l(&min_bucket_mutex_);
    if (dirty_heap_) {
      BySmallestBucketCount cmp(key_cmp_);
      std::make_heap(min_bucket_heap_.begin(), min_bucket_heap_.end(), cmp);
      dirty_heap_ = false;
    }
    min = min_bucket_heap_.front();
  }
  if (p != nullptr) {
    p->first = min->smallest;
    p->second = min->largest;
  }
  return min->count;
}

uint64_t StaticHistogram::LowestNAverageCount(double pct) {
  if (buckets_.empty()) {
    return 0;
  } else if (pct < 0.0 || pct > 1.0) {
    return 0;
  }

  MutexLock l(&min_bucket_mutex_);
  BySmallestBucketCount cmp(key_cmp_);
  if (dirty_heap_) {
    std::make_heap(min_bucket_heap_.begin(), min_bucket_heap_.end(), cmp);
  }
  uint32_t n = static_cast<uint32_t>(pct * buckets_.size());
  uint64_t total = 0;
  for (uint32_t i = 0; i < n; i++) {
    total += min_bucket_heap_.front()->count;
    std::pop_heap(min_bucket_heap_.begin(), min_bucket_heap_.end()-i, cmp);
  }
  dirty_heap_ = true;

  return total / n;
}

// TEST ONLY
void StaticHistogram::Display()  {
#ifndef NDEBUG
  uint64_t num_buckets = 0;
  uint64_t curr_total = 0;
  for (auto& b : buckets_) {
    curr_total += b.count.load();
    double pct = static_cast<double>(curr_total) / static_cast<double>(GetTotal());
    double key_pct = static_cast<double>(++num_buckets) / static_cast<double>(buckets_.size());
    std::cout << "[" << b.smallest.ToString() << "-" << b.largest.ToString();
    std::cout << ", " << (key_pct * 100) << " ==> " << b.count.load();
    std::cout << " (" << curr_total << ", " << (pct * 100) << "%)" << std::endl;
  }
#endif
}

} // namespace leveldb


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Azure.Core.TestFramework;

namespace Microsoft.Azure.Storage.File.Perf
{
    /// <summary>
    /// Represents the ambient environment in which the test suite is being run, offering access to information such as environment variables.
    /// </summary>
    internal sealed class PerfTestEnvironment : TestEnvironment
    {
        /// <summary>
        /// The shared instance of the <see cref="PerfTestEnvironment"/> to be used during test runs.
        /// </summary>
        public static PerfTestEnvironment Instance { get; } = new PerfTestEnvironment();

        /// <summary>
        ///   The storage account endpoint suffix of the cloud to use for testing.
        /// </summary>
        public new string StorageEndpointSuffix => base.StorageEndpointSuffix ?? "core.windows.net";

        /// <summary>
        /// The name of the Files Shares storage account to test against.
        /// </summary>
        /// <value>The Files Shares storage account name, read from the "AZURE_STORAGE_ACCOUNT_NAME" environment variable.</value>
        public string FilesSharesAccountName => GetVariable("AZURE_STORAGE_ACCOUNT_NAME");

        /// <summary>
        /// The shared access key of the Files Shares storage account to test against.
        /// </summary>
        /// <value>The Files Shares storage account key, read from the "AZURE_STORAGE_ACCOUNT_KEY" environment variable.</value>
        public string FilesSharesAccountKey => GetVariable("AZURE_STORAGE_ACCOUNT_KEY");

        /// <summary>
        /// The connection string for accessing the Files Shares storage account used for testing.
        /// </summary>
        public string FileShareAddressString { get; }

        /// <summary>
        /// Credentials used to authenticate access to the Microsoft Azure storage account used for testing.
        /// </summary>
        public Auth.StorageCredentials StorageCredentials { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="PerfTestEnvironment"/> class.
        /// </summary>
        public PerfTestEnvironment()
        {
            FileShareAddressString = $"{Uri.UriSchemeHttps}://{FilesSharesAccountName}.file.{StorageEndpointSuffix}";

            StorageCredentials = new Auth.StorageCredentials(FilesSharesAccountName, FilesSharesAccountKey);
        }
    }
}


text:
package algorithms.imageProcessing;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author nichole
 */
public class CurvatureScaleSpaceContourTest {

    public CurvatureScaleSpaceContourTest() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testContour() {

        float sigma = 32;
        float t = 0.5f;

        int x = 123;
        int y = 1290;

        CurvatureScaleSpaceImagePoint point0 = new CurvatureScaleSpaceImagePoint(
            sigma, t, x, y);

        assertTrue(point0.getSigma() == sigma);
        assertTrue(point0.getScaleFreeLength() == t);
        assertTrue(point0.getXCoord() == x);
        assertTrue(point0.getYCoord() == y);

        CurvatureScaleSpaceImagePoint point1 = new CurvatureScaleSpaceImagePoint(
            sigma, t + 0.25f, x + 20, y - 100);

        CurvatureScaleSpaceImagePoint[] points = new
            CurvatureScaleSpaceImagePoint[]{point0, point1};

        CurvatureScaleSpaceContour contour = new CurvatureScaleSpaceContour
            (sigma, t);

        contour.setPeakDetails(points);

        assertTrue(contour.getPeakSigma() == sigma);
        assertTrue(contour.getPeakScaleFreeLength() == t);
        assertTrue(contour.getPeakDetails().length == 2);

        assertTrue(contour.toString().contains("sigma"));
    }

    public static void main(String[] args) {

        try {

            CurvatureScaleSpaceContourTest test =
                new CurvatureScaleSpaceContourTest();

            test.testContour();

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("ERROR: " + e.getMessage());
        }
    }
}


text:
package com.gvenzl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import oracle.jdbc.pool.OracleDataSource;

/**
 * This class demonstrates the difference in throughput when
 * committing data differently to the Oracle Database.
 * @author gvenzl
 *
 */
public class CommittingData {

	/**
	 * Name of the test table.
	 */
	private static String TESTTABLE = "COMMITDATA";
    /**
     * Fixed amount of iterations.
     */
	private static int ITERATIONS = 100000;
	/**
	 * Error logging table for error logging.
	 */
    private static String ERROR_LOG_TABLE = "ERR_LOG_TABLE";
    /**
     * Append hint for direct path inserts.
     */
    private static String APPEND = "";

    /**
     * Input parameter.
     */
    private static String host = "";
    /**
     * Input parameter.
     */
    private static int port = 0;
    /**
     * Input parameter.
     */
    private static String serviceName = "";
    /**
     * Input parameter.
     */
    private static String userName = "";
    /**
     * Input parameter.
     */
    private static String password = "";
    /**
     * Input parameter.
     */
    private static boolean commitEveryRow = false;
    /**
     * Input parameter.
     */
    private static boolean commitAtEnd = false;
    /**
     * Input parameter.
     */
    private static int batchCommit = 0;
    /**
     * Input parameter.
     */
	private static boolean saveExceptions = false;

	/**
	 * Database connection.
	 */
	private Connection myConnection;

	/**
	 * Constructs a CommittingData object.
	 * @throws SQLException Any database error while
	 * opening a database connection
	 */
	public CommittingData() throws SQLException {
		OracleDataSource ods = new OracleDataSource();
		ods.setDriverType("thin");
		ods.setServerName(host);
		ods.setPortNumber(port);
		ods.setServiceName(serviceName);
		ods.setUser(userName);
		ods.setPassword(password);

		myConnection = ods.getConnection();
		myConnection.setAutoCommit(false);
	}
	/**
	 * Main entry point.
	 * @param args Array with various options on how to execute
	 * and which database to connect to
	 * @throws Exception Any error that happens during execution
	 */
	public static void main(final String[] args) throws Exception {

		if (args.length == 0) {
			printHelp();
		} else {

			for (int i = 0; i < args.length; i++) {
				switch (args[i]) {
					case "-host":
						host = args[++i];
						break;
					case "-port":
						port = Integer.valueOf(args[++i]).intValue();
						break;
					case "-srvn":
						serviceName = args[++i];
						break;
					case "-user":
						userName = args[++i];
						break;
					case "-pass":
						password = args[++i];
						break;
					case "-commitEveryRow":
						commitEveryRow = true;
						break;
					case "-commitAtEnd":
						commitAtEnd = true;
						break;
					case "-batchCommit":
						batchCommit = Integer.valueOf(args[++i]).intValue();
						break;
					case "-saveExceptions":
						saveExceptions = true;
						break;
					case "-directPath":
						APPEND = " /*+ APPEND */ ";
						break;
					default: printHelp();
				}
			}

			CommittingData myApp = new CommittingData();
			myApp.setup();
			myApp.runTests();
			myApp.tearDown();
		}
	}

	/**
	 * This method prepares the Database for testing by creating the test table.
	 * @throws SQLException Any Database related error
	 */
	private void setup() throws SQLException {
		final int ALREADYEXISTS = 955;
		try {
			myConnection.prepareStatement(
					"CREATE TABLE " + TESTTABLE
						+ " (ID NUMBER, TXT VARCHAR2(255))").execute();
		} catch (SQLException e) {
			// Ignore "ORA-00955: name is already used by an existing object"
			if (e.getErrorCode() != ALREADYEXISTS) {
				throw e;
			}
		}
		if (saveExceptions) {
			try {
				myConnection.prepareStatement(
						"BEGIN DBMS_ERRLOG.CREATE_ERROR_LOG('" + TESTTABLE
						+ "', '" + ERROR_LOG_TABLE + "'); END;").execute();
			} catch (SQLException e) {
				if (e.getErrorCode() != ALREADYEXISTS) {
					throw e;
				}
			}
		}
	}

	/**
	 * Tears down the setup environment.
	 * @throws SQLException Any database error while tear down.
	 */
	private void tearDown() throws SQLException {
		myConnection.prepareStatement("DROP TABLE " + TESTTABLE).execute();
		if (saveExceptions) {
			myConnection.
				prepareStatement("DROP TABLE " + ERROR_LOG_TABLE).
					execute();
		}
		myConnection.prepareStatement("PURGE USER_RECYCLEBIN").execute();
	}

	/**
	 * Run the tests.
	 * @throws SQLException Any Database error
	 */
	private void runTests() throws SQLException {

		if (commitEveryRow) {
			commitEveryRow();
		} else if (commitAtEnd) {
			commitAtEnd();
		} else if (batchCommit > 0 && saveExceptions) {
			batchCommitSaveExceptions(batchCommit);
		} else if (batchCommit > 0) {
			batchCommit(batchCommit);
		}
	}

	/**
	 * This method loads static data into the test table.
	 * It iterates over a loop as many times as is specified
	 * in the static ITERATIONS variable.
	 * The method commits after every newly inserted row.
	 * @throws SQLException Any Database error that might
	 * occur during the insert
	 */
	private void commitEveryRow() throws SQLException {

		System.out.println("Loading data with committing"
				+ " after every row - " + ITERATIONS + " iterations");

		PreparedStatement stmt = myConnection.
				prepareStatement("INSERT " + APPEND + " INTO "
						+ TESTTABLE + " VALUES (?,?)");

		long startTime = System.currentTimeMillis();
		for (int i = 0; i < ITERATIONS; i++) {
			stmt.setInt(1, i);
			stmt.setString(2, ";ajskfj[wig[ajdfkjaw[oeimakldjalksva;djfashdfjksahdf;lkjasdfoiwejaflkf;smvwlknvoaweijfasdfjasldf;kwlvma;dfjlaksjfowemowaivnoawn");
			stmt.execute();
			myConnection.commit();
		}
		long endTime = System.currentTimeMillis();

		System.out.println("Data loaded in: " + (endTime - startTime) + "ms");
	}

	/**
	 * This method loads static data into the test table.
	 * It iterates over a loop as many times as is specified
	 * in the static ITERATIONS variable.
	 * The method commits only once after all the data is fully loaded.
	 * @throws SQLException Any database error that may occurs during the insert
	 */
	private void commitAtEnd() throws SQLException {

		System.out.println("Loading data with committing after"
				+ " the entire set is loaded - " + ITERATIONS + " iterations");

		PreparedStatement stmt = myConnection.prepareStatement(
				"INSERT " + APPEND + " INTO " + TESTTABLE + " VALUES (?,?)");

		long startTime = System.currentTimeMillis();
		for (int i = 0; i < ITERATIONS; i++) {
			stmt.setInt(1, i);
			stmt.setString(2, ";ajskfj[wig[ajdfkjaw[oeimakldjalksva;djfashdfjksahdf;lkjasdfoiwejaflkf;smvwlknvoaweijfasdfjasldf;kwlvma;dfjlaksjfowemowaivnoawn");
			stmt.execute();
		}
		myConnection.commit();
		long endTime = System.currentTimeMillis();

		System.out.println("Data loaded in: " + (endTime - startTime) + "ms");

	}

	/**
	 * This method loads static data into the test table.
	 * It used the JDBC batching functionality and iterates over a loop
	 * as many times as is specified in the static ITERATIONS variable.
	 * @param batchSize The size of the batch before executing it.
	 * @throws SQLException Any database error that may occurs during the insert
	 */
	private void batchCommit(final int batchSize) throws SQLException {

		System.out.println("Batch loading data with committing "
				+ "after the entire set is loaded - "
				+ ITERATIONS + " iterations");

		PreparedStatement stmt = myConnection.prepareStatement(
				"INSERT " + APPEND + " INTO " + TESTTABLE + " VALUES (?,?)");

		long startTime = System.currentTimeMillis();
		for (int i = 0; i < ITERATIONS; i++) {
			stmt.setInt(1, i);
			stmt.setString(2, ";ajskfj[wig[ajdfkjaw[oeimakldjalksva;djfashdfjksahdf;lkjasdfoiwejaflkf;smvwlknvoaweijfasdfjasldf;kwlvma;dfjlaksjfowemowaivnoawn");
			stmt.addBatch();
			// Execute batch if batch size is reached
			if ((i % batchSize) == 0) {
				try {
					stmt.executeBatch();
				} catch (SQLException e) {
					e.printStackTrace(System.err);
				}
			}
		}
		try {
			stmt.executeBatch();
		} catch (SQLException e) {
			e.printStackTrace(System.err);
		}
		myConnection.commit();
		long endTime = System.currentTimeMillis();

		System.out.println("Data loaded in: " + (endTime - startTime) + "ms");

	}

	/**
	 * This method loads static data into the test table.
	 * It used the JDBC batching functionality and iterates over a loop
	 * as many times as is specified in the static ITERATIONS variable.
	 * It also uses the LOG ERRORS clause that will prevent the
	 * execution from failing if any exception occurs within the batch.
	 * @param batchSize The size of the batch before executing it.
	 * @throws SQLException Any database error that may occurs during the insert
	 */
	private void batchCommitSaveExceptions(final int batchSize)
			throws SQLException {

		System.out.println("Batch loading data (save exceptions)"
				+ " with committing after the entire set is loaded - "
				+ ITERATIONS + " iterations");

		PreparedStatement stmt = myConnection.prepareStatement(
				"INSERT " + APPEND + " INTO " + TESTTABLE
				+ " VALUES (?,?) LOG ERRORS INTO " + ERROR_LOG_TABLE
				+ " REJECT LIMIT UNLIMITED");

		long startTime = System.currentTimeMillis();
		for (int i = 0; i < ITERATIONS; i++) {
			stmt.setInt(1, i);
			stmt.setString(2, ";ajskfj[wig[ajdfkjaw[oeimakldjalksva;djfashdfjksahdf;lkjasdfoiwejaflkf;smvwlknvoaweijfasdfjasldf;kwlvma;dfjlaksjfowemowaivnoawn");
			stmt.addBatch();
			// Execute batch if batch size is reached
			if ((i % batchSize) == 0) {
				stmt.executeBatch();
			}
		}
		stmt.executeBatch();
		myConnection.commit();
		long endTime = System.currentTimeMillis();

		System.out.println("Data loaded in: " + (endTime - startTime) + "ms");

	}
	/**
	 * Prints the help and exits the program.
	 */
	private static void printHelp() {
		System.out.println("Committing data to the Oracle Database - Usage:");
		System.out.println();
		System.out.println("java com.gvenzl.CommittingData -host [host]"
				+ " -port [port] -srvn [service name] -user [username]"
				+ " -pass [password] -commitEveryRow -commitAtEnd"
				+ " -batchCommit [batch size] -saveExceptions -directPath");
		System.out.println();
		System.out.println("host: 		The database host name");
		System.out.println("port: 		The database listener port");
		System.out.println("service name: 	The database service name");
		System.out.println("username: 	The database username");
		System.out.println("password: 	The database user password");
		System.out.println("commitEveryRow: Commit data after every row");
		System.out.println("commitAtEnd: 	Commit data only once at"
				+ " the end of a load");
		System.out.println("batch size: 	The size of the loading batch"
				+ " to execute at once");
		System.out.println("saveExceptions: Specify whether you would like"
				+ " to save exceptions during batch loading");
		System.out.println("directPath: 	Specify whether you would like"
				+ " to use DIRECT PATH loading");

		System.exit(0);
	}

}


text:
package org.broadinstitute.dsde.rawls.metrics

import akka.http.scaladsl.model.{HttpMethod, StatusCode, Uri}

import java.util.UUID
import scala.annotation.implicitNotFound

/**
  * Typeclass for something that can be converted into a metric name fragment.
  * Metric name fragments can be combined via ExpandedMetricBuilder to generate an "expanded" metric name.
  * By default this just calls toString on the object of type A, but this can be overridden.
  */
@implicitNotFound(msg = "Cannot expand instances of type ${A}")
trait Expansion[A] {
  def makeName(a: A): String = a.toString

  final def makeNameWithKey(key: String, a: A) =
    s"$key.${makeName(a)}"
}

object Expansion {

  // Typeclass instances:

  /**
    * Implicit expansion for UUID using the default makeName.
    */
  implicit object UUIDExpansion extends Expansion[UUID]

  /**
    * Implicit expansion for HttpMethod.
    */
  implicit object HttpMethodExpansion extends Expansion[HttpMethod] {
    override def makeName(m: HttpMethod): String = m.value.toLowerCase
  }

  /**
    * Implicit expansion for Uri.
    * Statsd doesn't allow slashes in metric names, so we override makeName to override
    * the default toString based implementation.
    */
  implicit object UriExpansion extends Expansion[Uri] {
    override def makeName(uri: Uri): String = {
      val path = if (uri.path.startsWithSlash) uri.path.tail.toString else uri.path
      path.toString.replace('/', '.')
    }
  }

  /**
    * Implicit expansion for a StatusCode.
    */
  implicit object StatusCodeExpansion extends Expansion[StatusCode] {
    override def makeName(statusCode: StatusCode): String = statusCode.intValue.toString
  }

  /**
    * Expand exceptions into their simple class name.
    */
  implicit def ThrowableExpansion[T <: Throwable] = new Expansion[T] {
    override def makeName(a: T): String = a.getClass.getSimpleName
  }

  // Implicit expansions for String and Int.
  // It's preferable to use more specific types when possible, but sometimes expanding
  // primitive types into metric names is needed.
  implicit object StringExpansion extends Expansion[String]
  implicit object IntExpansion extends Expansion[Int]
}


text:
'use strict'

var la = require('lazy-ass')
var check = require('check-more-types')
var log = require('debug')('next-update')
const R = require('ramda')

var request = require('request')
var verify = check.verify
var semver = require('semver')
var q = require('q')
var localVersion = require('./local-module-version')
var isUrl = require('npm-utils').isUrl
var _ = require('lodash')
const {isPrerelease} = require('./utils')

var _registryUrl = require('npm-utils').registryUrl
la(check.fn(_registryUrl), 'expected registry url function')
var registryUrl = _.once(_registryUrl)

const notPrerelease = R.complement(isPrerelease)

function cleanVersion (version, name) {
  var originalVersion = version
  verify.unemptyString(version, 'missing version string' + version)
  verify.unemptyString(name, 'missing name string' + name)

  if (isUrl(version)) {
        // version = version.substr(version.indexOf('#') + 1);

        // hmm, because we don't have a way to fetch git tags yet
        // just skip these dependencies
    console.log('Cannot handle git repos, skipping', name, 'at', version)
    return
  }
  if (version === 'original' ||
        version === 'modified' ||
        version === 'created') {
    return
  }

  version = version.replace('~', '').replace('^', '')
  var twoDigitVersion = /^\d+\.\d+$/
  if (twoDigitVersion.test(version)) {
    version += '.0'
  }
  if (version === 'latest' || version === '*') {
    console.log('Module', name, 'uses version', version)
    console.log('It is recommented to list a specific version number')
    version = localVersion(name)
    if (!version) {
      version = '0.0.1'
    }
    console.log('module', name, 'local version', version)
  }
  try {
    version = semver.clean(version)
  } catch (err) {
    console.error('exception when cleaning version', version)
    return
  }
  if (!version) {
    log('could not clean version ' + originalVersion + ' for ' + name)
    return
  }
  console.assert(version, 'missing clean version ' + originalVersion + ' for ' + name)
  return version
}

// eslint-disable-next-line no-unused-vars
function cleanVersionPair (nameVersion) {
  check.verify.array(nameVersion, 'expected an array')
  console.assert(nameVersion.length === 2,
        'expected 2 items, name and version ' + nameVersion)
  var name = nameVersion[0]
  check.verify.string(name, 'could not get module name from ' + nameVersion)

  var version = nameVersion[1]
  check.verify.string(version, 'could not get module version from ' + nameVersion)
  version = cleanVersion(version, name)
  if (!version) {
    return
  }

  nameVersion[1] = version
  return nameVersion
}

function cleanVersionObject (info) {
  check.verify.object(info, 'expected info')
  var name = info.name
  check.verify.string(name, 'could not get module name from ' + info)

  var version = info.version
  check.verify.string(version, 'could not get module version from ' + info)
  version = cleanVersion(version, name)

  if (!version) {
    return
  }

  info.version = version
  return info
}

function cleanVersions (nameVersionPairs) {
  check.verify.array(nameVersionPairs, 'expected array')
  var cleaned = nameVersionPairs
        .map(cleanVersionObject)
        .filter(check.object)
  return cleaned
}

function formNpmErrorMessage (name, info) {
  var reason = info.reason || info.error || JSON.stringify(info)
  var str = 'ERROR in npm info for ' + name + ' reason ' + reason
  return str
}

function cleanVersionFor (name, version) {
  return cleanVersion(version, name)
}

function extractVersions (info) {
  if (info.time) {
    return Object.keys(info.time)
  }
  if (info.versions) {
    return Object.keys(info.versions)
  }
}

function is404 (response) {
  return response && response.statusCode === 404
}

function isNotFound (str) {
  var moduleNotFound = (/not found/).test(str)
  var cannotConnect = (/ENOTFOUND/).test(str)
  var errorInNpm = (/ERROR in npm/).test(str)
  var couldNotFetch = (/could not fetch/i).test(str)
  return moduleNotFound || cannotConnect || errorInNpm || couldNotFetch
}

// fetching versions inspired by
// https://github.com/jprichardson/npm-latest
// returns a promise
function fetchVersions (options, nameVersion) {
    // console.log(nameVersion);
    // TODO use check.schema
  check.verify.object(nameVersion, 'expected name, version object')
  var name = nameVersion.name
  var version = nameVersion.version
  check.verify.string(name, 'missing name string')
  check.verify.string(version, 'missing version string')

  var cleanVersionForName = _.partial(cleanVersionFor, name)
  function isLaterVersion (ver) {
    var later = semver.gt(ver, version)
    return later
  }

    // console.log('fetching versions for', name, 'current version', version);
  var MAX_WAIT_TIMEOUT = options.checkVersionTimeout || 25000
  var deferred = q.defer()

  function rejectOnTimeout () {
    var msg = 'timed out waiting for NPM for package ' + name +
            ' after ' + MAX_WAIT_TIMEOUT + 'ms'
    console.error(msg)
    deferred.reject(msg)
  }

  function escapeName (str) {
    return str.replace('/', '%2F')
  }

  registryUrl().then(function (npmUrl) {
    log('NPM registry url', npmUrl)
    la(check.webUrl(npmUrl), 'need npm registry url, got', npmUrl)

    npmUrl = npmUrl.replace(/^https:/, 'http:').trim()
    var url = (options.registry || npmUrl) + escapeName(name)

        // TODO how to detect if the registry is not responding?

    log('getting url', url)
    request.get(url, onNPMversions)
    var timer = setTimeout(rejectOnTimeout, MAX_WAIT_TIMEOUT)

    function onNPMversions (err, response, body) {
      log('got response for', url)
      clearTimeout(timer)

      if (err) {
        console.error('ERROR when fetching info for package', name)
        deferred.reject(err.message)
        return
      }

      if (is404(response)) {
        log('404 response for', url)
        deferred.resolve({
          name: name,
          versions: []
        })
        return
      }

      try {
        log('parsing response body')
        var info = JSON.parse(body)
        log('parsed response, error?', info.error)
        if (info.error) {
          log('error parsing\n' + body + '\n')
          var str = formNpmErrorMessage(name, info)
          console.error(str)

          if (isNotFound(info.error)) {
            deferred.resolve({
              name: name,
              versions: []
            })
            return
          }

          deferred.reject(str)
          return
        }
        log('extracting versions')
        var versions = extractVersions(info)
        log('%d versions', versions.length)

        if (!Array.isArray(versions)) {
          throw new Error('Could not get versions for ' + name +
                        ' from ' + JSON.stringify(info) +
                        ' response ' + JSON.stringify(response, null, 2))
        }

        var validVersions = versions.filter(cleanVersionForName)
        var newerVersions = validVersions.filter(isLaterVersion)
        log('%d valid versions', validVersions.length)
        if (validVersions.length) {
          log('last version %s', R.last(validVersions))
        }
        if (newerVersions.length) {
          log('%d newer versions', newerVersions.length)
          log('from %s to %s', R.head(newerVersions), R.last(newerVersions))
        }

        deferred.resolve({
          name: name,
          versions: newerVersions
        })
        return
      } catch (err) {
        console.error(err)
        deferred.reject('Could not fetch versions for ' + name)
      }
    }
  })

  return deferred.promise
}

const verboseLog = (options) => options.tldr ? _.noop : console.log

function logFetched (fetched) {
  fetched.forEach(individual => {
    log('%s - %d versions', individual.name, individual.versions.length)
  })
}

const hasVersions = nameNewVersions =>
  nameNewVersions &&
    check.array(nameNewVersions.versions) &&
    check.unempty(nameNewVersions.versions)

const filterVersions = R.evolve({
  versions: R.filter(notPrerelease)
})

function filterFetchedVersions (checkLatestOnly, results) {
  la(arguments.length === 2, 'expected two arguments', arguments)
  checkLatestOnly = Boolean(checkLatestOnly)
  check.verify.array(results, 'expected list of results')
  log('fetch all new version results')
  logFetched(results)

  let available = results
    .map(filterVersions)
    .filter(hasVersions)

  if (checkLatestOnly) {
    available = available.map(function (nameVersions) {
      if (nameVersions.versions.length > 1) {
        nameVersions.versions = nameVersions.versions.slice(-1)
      }
      return nameVersions
    })
  } else {
    verboseLog('checking ALL versions')
  }
  return available
}

// returns a promise with available new versions
function nextVersions (options, nameVersionPairs, checkLatestOnly) {
  check.verify.object(options, 'expected object with options')
  check.verify.array(nameVersionPairs, 'expected array')
  nameVersionPairs = cleanVersions(nameVersionPairs)

  const verbose = verboseLog(options)
  verbose('checking NPM registry')
  var MAX_CHECK_TIMEOUT = options.checkVersionTimeout || 10000

  var fetchPromises = nameVersionPairs.map(fetchVersions.bind(null, options))
  var fetchAllPromise = q.all(fetchPromises)
        .timeout(MAX_CHECK_TIMEOUT, 'timed out waiting for NPM after ' + MAX_CHECK_TIMEOUT + 'ms')

  return fetchAllPromise.then(
    _.partial(filterFetchedVersions, checkLatestOnly),
    q.reject
  )
}

module.exports = {
  isUrl,
  cleanVersion,
  cleanVersions,
  fetchVersions,
  nextVersions,
  filterFetchedVersions,
  hasVersions
}


text:
<!DOCTYPE html>

        <title>CES NewsHub - Brands</title>

        <link href="lib/bootstrap.css/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link href="style.css" rel="stylesheet" media="screen">

        <link href="lib/streamhub-backbone/main.css" rel="stylesheet" media="screen">

        <meta property="og:title" content="Livefyre CES NewsHub"/>
        <meta property="og:type" content="website"/>
        <meta property="og:image"  content="http://ces.livefyre.com/media/newshub-screenshot.png"/>
        <meta property="og:url" content="http://ces.livefyre.com"/>
        <meta property="og:site_name" content="Livefyre CES NewsHub"/>
        <meta property="og:description"
            content="Your real-time news source for the latest tweets, photos
            and articles coming from the Las Vegas show." />
        <meta property="fb:admins" content="820265486" />

        Real-time news and social curation, get your own NewsHub at Livefyre.com

Powered by Livefyre StreamHub

Real-time news and social curation, get your own NewsHub @ Livefyre.com

Close X

                C
                E
                S
                2
                0
                1
                3

Home

Media

News

Brands

Products

Samsung

Google

Microsoft

Canonical

Sony

Apple

LG

Sharp

Lenovo

Qualcomm

Nvidia

Intel

Cisco

Ford

Samsung

Google

Microsoft

Canonical

Sony

Apple

LG

Sharp

Lenovo

Qualcomm

Nvidia

Intel

Cisco

Ford


text:
package mcjty.rftools.village;

import cpw.mods.fml.common.registry.VillagerRegistry;
import mcjty.lib.varia.WeightedRandomSelector;
import mcjty.rftools.GeneralConfiguration;
import mcjty.rftools.blocks.dimletconstruction.DimletConstructionSetup;
import mcjty.rftools.blocks.dimlets.DimletSetup;
import mcjty.rftools.items.dimlets.DimletEntry;
import mcjty.rftools.items.dimlets.DimletKey;
import mcjty.rftools.items.dimlets.DimletRandomizer;
import mcjty.rftools.items.dimlets.KnownDimletConfiguration;
import mcjty.rftools.items.parts.StructureEssenceItem;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.village.MerchantRecipe;
import net.minecraft.village.MerchantRecipeList;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RFToolsTradeHandler implements VillagerRegistry.IVillageTradeHandler {

    public static RFToolsTradeHandler INSTANCE = new RFToolsTradeHandler();

    public void load() {
        VillagerRegistry.instance().registerVillageTradeHandler(GeneralConfiguration.villagerId, this);
    }

    @Override
    public void manipulateTradesForVillager(EntityVillager villager, MerchantRecipeList recipeList, Random random) {
        switch (random.nextInt(4)) {
            case 0:
                getRandomBuyEssence(recipeList, random);
                break;
            case 1:
                getRandomSellEssence(recipeList, random);
                break;
            case 2:
                recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1), new ItemStack(DimletSetup.unknownDimlet, 2 + random.nextInt(3))));
                break;
            case 3:
                getRandomBuyDimlet(villager, recipeList, random, 1);
                break;
        }

        switch (random.nextInt(5)) {
            case 0:
                getRandomBuyEssence(recipeList, random);
                break;
            case 1:
                getRandomSellEssence(recipeList, random);
                break;
            case 2:
                recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1), new ItemStack(DimletSetup.unknownDimlet, 3 + random.nextInt(6))));
                break;
            case 3:
                getRandomBuyDimlet(villager, recipeList, random, 2);
                break;
            case 4:
                getRandomSellDimlet(villager, recipeList, random, 0.15f);
                break;
        }

        switch (random.nextInt(2)) {
            case 0:
                getRandomSellDimlet(villager, recipeList, random, 1.0f);
                break;
            case 1:
                recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 2 + random.nextInt(2)), new ItemStack(DimletSetup.dimensionalShard, 4 + random.nextInt(8))));
                break;
        }
    }

    private void getRandomBuyEssence(MerchantRecipeList recipeList, Random random) {
        List<Integer> keys = new ArrayList<Integer>(StructureEssenceItem.structures.keySet());
        int structureType = keys.get(random.nextInt(keys.size()));
        recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, 1 + random.nextInt(2)), new ItemStack(DimletConstructionSetup.structureEssenceItem, 1, structureType)));
    }

    private void getRandomSellEssence(MerchantRecipeList recipeList, Random random) {
        List<Integer> keys = new ArrayList<Integer>(StructureEssenceItem.structures.keySet());
        int structureType = keys.get(random.nextInt(keys.size()));
        recipeList.add(new MerchantRecipe(new ItemStack(DimletConstructionSetup.structureEssenceItem, 1, structureType), new ItemStack(Items.emerald, 2 + random.nextInt(3))));
    }

    private void getRandomSellDimlet(EntityVillager villager, MerchantRecipeList recipeList, Random random, float dimletBonus) {
        WeightedRandomSelector.Distribution<Integer> distribution = DimletRandomizer.randomDimlets.createDistribution(dimletBonus);
        DimletKey dimlet = DimletRandomizer.getRandomDimlet(distribution, random);
        if (dimlet != null) {
            DimletEntry entry = KnownDimletConfiguration.idToDimletEntry.get(dimlet);
            if (entry != null) {
                int rarity = entry.getRarity();
                ItemStack dimletStack = KnownDimletConfiguration.makeKnownDimlet(dimlet, villager.worldObj);
                recipeList.add(new MerchantRecipe(new ItemStack(Items.emerald, (1 + random.nextInt(2)) * (rarity/2 + 1)), dimletStack));
            }
        }
    }

    private void getRandomBuyDimlet(EntityVillager villager, MerchantRecipeList recipeList, Random random, int bonus) {
        DimletKey dimlet = DimletRandomizer.getRandomDimlet(random);
        if (dimlet != null) {
            DimletEntry entry = KnownDimletConfiguration.idToDimletEntry.get(dimlet);
            if (entry != null) {
                int rarity = entry.getRarity();
                ItemStack dimletStack = KnownDimletConfiguration.makeKnownDimlet(dimlet, villager.worldObj);
                recipeList.add(new MerchantRecipe(dimletStack, new ItemStack(Items.emerald, (bonus + random.nextInt(2)) * (rarity/2 + 1))));
            }
        }
    }
}


text:
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
font,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td {
  font-size: 100%;
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  background: transparent;
}
html,
body {
  width: 100%;
  height: 100%;
}
body {
  background: #fff;
}
.dx-viewport {
  width: 100%;
  height: 100%;
}
blockquote,
q {
  quotes: none;
}
a {
  color: #818181;
}
:focus {
  outline: 0;
}
ins {
  text-decoration: none;
}
del {
  text-decoration: line-through;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}
.dx-full-height {
  height: 100%;
}
.dx-transition {
  position: relative;
}
.dx-transition-absolute .dx-transition-inner-wrapper {
  position: absolute;
  height: 100%;
  width: 100%;
}
.dx-hidden {
  display: none !important;
}
.dx-fast-hidden,
.dx-inactive-view {
  position: absolute !important;
  top: -99999px !important;
  left: -99999px !important;
}
.dx-skip-animation,
.dx-fast-hidden,
.dx-inactive-view {
  -moz-transition-property: none !important;
  -o-transition-property: none !important;
  -webkit-transition-property: none !important;
  transition-property: none !important;
  -moz-transition-delay: 0 !important;
  -o-transition-delay: 0 !important;
  -webkit-transition-delay: 0 !important;
  transition-delay: 0 !important;
  -moz-transition-duration: 0 !important;
  -o-transition-duration: 0 !important;
  -webkit-transition-duration: 0 !important;
  transition-duration: 0 !important;
}
.dx-transition-absolute .dx-active-view {
  left: 0;
  height: 100%;
  position: absolute;
}
.dx-layout.dx-animating.dx-leave,
.dx-layout.dx-animating.dx-enter {
  position: absolute;
  top: 0;
  left: 0;
}


text:
{% extends 'email.server.view.html' %}

{% block content %}

{{name}},

Thank you very much for signing up with us.

Confirm your email address ({{email}}) to complete your Trustroots account.

It's easy — just click on the button below.

  {% include 'partials/button.server.view.html' with {'buttonUrl': urlConfirm, 'buttonTitle': 'Confirm now'} %}

  {% include 'partials/copypasteurl.server.view.html' with {'url': urlConfirmPlainText} %}

{% endblock %}


text:
package com.vk.api.sdk.queries.market;

import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.market.responses.GetAlbumByIdResponse;

import java.util.Arrays;
import java.util.List;

/**
 * Query for Market.getAlbumById method
 */
public class MarketGetAlbumByIdQuery extends AbstractQueryBuilder<MarketGetAlbumByIdQuery, GetAlbumByIdResponse> {
    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client   VK API client
     * @param actor    actor with access token
     * @param ownerId  value of "owner id" parameter.
     * @param albumIds value of "album ids" parameter.
     */
    public MarketGetAlbumByIdQuery(VkApiClient client, UserActor actor, int ownerId, int... albumIds) {
        super(client, "market.getAlbumById", GetAlbumByIdResponse.class);
        accessToken(actor.getAccessToken());
        ownerId(ownerId);
        albumIds(albumIds);
    }

    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client   VK API client
     * @param actor    actor with access token
     * @param ownerId  value of "owner id" parameter.
     * @param albumIds value of "album ids" parameter.
     */
    public MarketGetAlbumByIdQuery(VkApiClient client, UserActor actor, int ownerId, List<Integer> albumIds) {
        super(client, "market.getAlbumById", GetAlbumByIdResponse.class);
        accessToken(actor.getAccessToken());
        ownerId(ownerId);
        albumIds(albumIds);
    }

    /**
     * Identifier of an album owner community
     * Note that community id in the 'owner_id' parameter should be negative number.
     * For example 'owner_id'=-1 matches the [vk.com/apiclub|VK API] community
     *
     * @param value value of "owner id" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    protected MarketGetAlbumByIdQuery ownerId(int value) {
        return unsafeParam("owner_id", value);
    }

    /**
     * Collections identifiers to obtain data from
     *
     * @param value value of "album ids" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    protected MarketGetAlbumByIdQuery albumIds(int... value) {
        return unsafeParam("album_ids", value);
    }

    /**
     * Collections identifiers to obtain data from
     *
     * @param value value of "album ids" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    protected MarketGetAlbumByIdQuery albumIds(List<Integer> value) {
        return unsafeParam("album_ids", value);
    }

    @Override
    protected MarketGetAlbumByIdQuery getThis() {
        return this;
    }

    @Override
    protected List<String> essentialKeys() {
        return Arrays.asList("album_ids", "owner_id", "access_token");
    }
}


text: module.exports = "This is some content.";


text:
@interface OCMockRecorderTests : SenTestCase
{
	NSInvocation *testInvocation;
}

@end


text:
#include <iostream>
#include <math.h>

Directional_light::Directional_light() : Light()
{
    m_angle = 0;
    m_opening_angle = 0;
}

Directional_light::Directional_light(sf::Vector2f position, float intensity, float radius, float angle, float opening_angle, sf::Color colo)
    : Light(position, intensity, radius, 0, colo), m_angle(angle), m_opening_angle(opening_angle)
{
}

Directional_light::~Directional_light()
{
    //dtor
}

void Directional_light::Generate(std::vector<Wall> &m_wall)
{
    m_shape.clear();

    float angle     = m_angle * M_PI / 180;
    float o_angle   = m_opening_angle * M_PI / 180;

    AddTriangle(sf::Vector2f((m_radius*cos(angle + o_angle * 0.5))
                            ,(m_radius*sin(angle + o_angle * 0.5))) ,
                sf::Vector2f((m_radius*cos(angle - o_angle * 0.5))
                            ,(m_radius*sin(angle - o_angle * 0.5))),0,m_wall);
}

void Directional_light::SetAngle(float angle)
{
    m_angle = angle;
}

void Directional_light::SetOpeningAngle(float angle)
{
    m_opening_angle = angle;
}

void Directional_light::SetOtherParameter(unsigned n, float v)
{
    if(n == ANGLE)
        SetAngle(v);
    else if(n == OPENING_ANGLE)
        SetOpeningAngle(v);
}


text:
import numpy as np
import functools
import operator

a = np.ones(10000)
for i in np.arange(1000):
    b = functools.reduce(operator.mul, a)

print(b)