text:
using WebKit::WebCanvas;
using WebKit::WebMediaPlayer;
using WebKit::WebRect;
using WebKit::WebSize;
using WebKit::WebString;
using media::PipelineStatus;

namespace {

// Amount of extra memory used by each player instance reported to V8.
// It is not exact number -- first, it differs on different platforms,
// and second, it is very hard to calculate. Instead, use some arbitrary
// value that will cause garbage collection from time to time. We don't want
// it to happen on every allocation, but don't want 5k players to sit in memory
// either. Looks that chosen constant achieves both goals, at least for audio
// objects. (Do not worry about video objects yet, JS programs do not create
// thousands of them...)
const int kPlayerExtraMemory = 1024 * 1024;

// Limits the range of playback rate.
//
// TODO(kylep): Revisit these.
//
// Vista has substantially lower performance than XP or Windows7.  If you speed
// up a video too much, it can't keep up, and rendering stops updating except on
// the time bar. For really high speeds, audio becomes a bottleneck and we just
// use up the data we have, which may not achieve the speed requested, but will
// not crash the tab.
//
// A very slow speed, ie 0.00000001x, causes the machine to lock up. (It seems
// like a busy loop). It gets unresponsive, although its not completely dead.
//
// Also our timers are not very accurate (especially for ogg), which becomes
// evident at low speeds and on Vista. Since other speeds are risky and outside
// the norms, we think 1/16x to 16x is a safe and useful range for now.
const double kMinRate = 0.0625;
const double kMaxRate = 16.0;

// Prefix for histograms related to Encrypted Media Extensions.
const char* kMediaEme = "Media.EME.";
}  // namespace

namespace webkit_media {

#define COMPILE_ASSERT_MATCHING_ENUM(name) \
  COMPILE_ASSERT(static_cast<int>(WebMediaPlayer::CORSMode ## name) == \
                 static_cast<int>(BufferedResourceLoader::k ## name), \
                 mismatching_enums)
COMPILE_ASSERT_MATCHING_ENUM(Unspecified);
COMPILE_ASSERT_MATCHING_ENUM(Anonymous);
COMPILE_ASSERT_MATCHING_ENUM(UseCredentials);
#undef COMPILE_ASSERT_MATCHING_ENUM

#define BIND_TO_RENDER_LOOP(function) \
  media::BindToLoop(main_loop_, base::Bind(function, AsWeakPtr()))

#define BIND_TO_RENDER_LOOP_1(function, arg1) \
  media::BindToLoop(main_loop_, base::Bind(function, AsWeakPtr(), arg1))

#define BIND_TO_RENDER_LOOP_2(function, arg1, arg2) \
  media::BindToLoop(main_loop_, base::Bind(function, AsWeakPtr(), arg1, arg2))

static void LogMediaSourceError(const scoped_refptr<media::MediaLog>& media_log,
                                const std::string& error) {
  media_log->AddEvent(media_log->CreateMediaSourceErrorEvent(error));
}

WebMediaPlayerImpl::WebMediaPlayerImpl(
    WebKit::WebFrame* frame,
    WebKit::WebMediaPlayerClient* client,
    base::WeakPtr<WebMediaPlayerDelegate> delegate,
    const WebMediaPlayerParams& params)
    : frame_(frame),
      network_state_(WebMediaPlayer::NetworkStateEmpty),
      ready_state_(WebMediaPlayer::ReadyStateHaveNothing),
      main_loop_(base::MessageLoopProxy::current()),
      media_loop_(params.message_loop_proxy()),
      paused_(true),
      seeking_(false),
      playback_rate_(0.0f),
      pending_seek_(false),
      pending_seek_seconds_(0.0f),
      client_(client),
      delegate_(delegate),
      media_log_(params.media_log()),
      accelerated_compositing_reported_(false),
      incremented_externally_allocated_memory_(false),
      gpu_factories_(params.gpu_factories()),
      is_local_source_(false),
      supports_save_(true),
      starting_(false),
      chunk_demuxer_(NULL),
      pending_repaint_(false),
      pending_size_change_(false),
      video_frame_provider_client_(NULL),
      text_track_index_(0) {
  media_log_->AddEvent(
      media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_CREATED));

  pipeline_.reset(new media::Pipeline(media_loop_, media_log_.get()));

  // Let V8 know we started new thread if we did not do it yet.
  // Made separate task to avoid deletion of player currently being created.
  // Also, delaying GC until after player starts gets rid of starting lag --
  // collection happens in parallel with playing.
  //
  // TODO(enal): remove when we get rid of per-audio-stream thread.
  main_loop_->PostTask(
      FROM_HERE,
      base::Bind(&WebMediaPlayerImpl::IncrementExternallyAllocatedMemory,
                 AsWeakPtr()));

  // Also we want to be notified of |main_loop_| destruction.
  base::MessageLoop::current()->AddDestructionObserver(this);

  if (WebKit::WebRuntimeFeatures::isLegacyEncryptedMediaEnabled()) {
    decryptor_.reset(new ProxyDecryptor(
        client,
        frame,
        BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyAdded),
        BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyError),
        BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnKeyMessage),
        BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnNeedKey)));
  }

  // Use the null sink if no sink was provided.
  audio_source_provider_ = new WebAudioSourceProviderImpl(
      params.audio_renderer_sink().get()
          ? params.audio_renderer_sink()
          : new media::NullAudioSink(media_loop_));
}

WebMediaPlayerImpl::~WebMediaPlayerImpl() {
  SetVideoFrameProviderClient(NULL);
  GetClient()->setWebLayer(NULL);

  DCHECK(main_loop_->BelongsToCurrentThread());
  media_log_->AddEvent(
      media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_DESTROYED));

  if (delegate_.get())
    delegate_->PlayerGone(this);

  Destroy();

  // Remove destruction observer if we're being destroyed but the main thread is
  // still running.
  if (base::MessageLoop::current())
    base::MessageLoop::current()->RemoveDestructionObserver(this);
}

namespace {

// Helper enum for reporting scheme histograms.
enum URLSchemeForHistogram {
  kUnknownURLScheme,
  kMissingURLScheme,
  kHttpURLScheme,
  kHttpsURLScheme,
  kFtpURLScheme,
  kChromeExtensionURLScheme,
  kJavascriptURLScheme,
  kFileURLScheme,
  kBlobURLScheme,
  kDataURLScheme,
  kFileSystemScheme,
  kMaxURLScheme = kFileSystemScheme  // Must be equal to highest enum value.
};

URLSchemeForHistogram URLScheme(const GURL& url) {
  if (!url.has_scheme()) return kMissingURLScheme;
  if (url.SchemeIs("http")) return kHttpURLScheme;
  if (url.SchemeIs("https")) return kHttpsURLScheme;
  if (url.SchemeIs("ftp")) return kFtpURLScheme;
  if (url.SchemeIs("chrome-extension")) return kChromeExtensionURLScheme;
  if (url.SchemeIs("javascript")) return kJavascriptURLScheme;
  if (url.SchemeIs("file")) return kFileURLScheme;
  if (url.SchemeIs("blob")) return kBlobURLScheme;
  if (url.SchemeIs("data")) return kDataURLScheme;
  if (url.SchemeIs("filesystem")) return kFileSystemScheme;
  return kUnknownURLScheme;
}

}  // anonymous namespace

void WebMediaPlayerImpl::load(const WebKit::WebURL& url, CORSMode cors_mode) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  LoadSetup(url);

  // Otherwise it's a regular request which requires resolving the URL first.
  GURL gurl(url);
  data_source_.reset(new BufferedDataSource(
      main_loop_,
      frame_,
      media_log_.get(),
      base::Bind(&WebMediaPlayerImpl::NotifyDownloading, AsWeakPtr())));
  data_source_->Initialize(
      url, static_cast<BufferedResourceLoader::CORSMode>(cors_mode),
      base::Bind(
          &WebMediaPlayerImpl::DataSourceInitialized,
          AsWeakPtr(), gurl));

  is_local_source_ = !gurl.SchemeIs("http") && !gurl.SchemeIs("https");
}

void WebMediaPlayerImpl::load(const WebKit::WebURL& url,
                              WebKit::WebMediaSource* media_source,
                              CORSMode cors_mode) {
  LoadSetup(url);

  // Media source pipelines can start immediately.
  supports_save_ = false;
  StartPipeline(media_source);
}

void WebMediaPlayerImpl::LoadSetup(const WebKit::WebURL& url) {
  GURL gurl(url);
  UMA_HISTOGRAM_ENUMERATION("Media.URLScheme", URLScheme(gurl), kMaxURLScheme);

  // Set subresource URL for crash reporting.
  base::debug::SetCrashKeyValue("subresource_url", gurl.spec());

  // Handle any volume/preload changes that occurred before load().
  setVolume(GetClient()->volume());
  setPreload(GetClient()->preload());

  SetNetworkState(WebMediaPlayer::NetworkStateLoading);
  SetReadyState(WebMediaPlayer::ReadyStateHaveNothing);
  media_log_->AddEvent(media_log_->CreateLoadEvent(url.spec()));
}

void WebMediaPlayerImpl::play() {
  DCHECK(main_loop_->BelongsToCurrentThread());

  paused_ = false;
  pipeline_->SetPlaybackRate(playback_rate_);

  media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PLAY));

  if (delegate_.get())
    delegate_->DidPlay(this);
}

void WebMediaPlayerImpl::pause() {
  DCHECK(main_loop_->BelongsToCurrentThread());

  paused_ = true;
  pipeline_->SetPlaybackRate(0.0f);
  paused_time_ = pipeline_->GetMediaTime();

  media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PAUSE));

  if (delegate_.get())
    delegate_->DidPause(this);
}

bool WebMediaPlayerImpl::supportsFullscreen() const {
  DCHECK(main_loop_->BelongsToCurrentThread());
  return true;
}

bool WebMediaPlayerImpl::supportsSave() const {
  DCHECK(main_loop_->BelongsToCurrentThread());
  return supports_save_;
}

void WebMediaPlayerImpl::seek(double seconds) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  if (starting_ || seeking_) {
    pending_seek_ = true;
    pending_seek_seconds_ = seconds;
    if (chunk_demuxer_)
      chunk_demuxer_->CancelPendingSeek();
    return;
  }

  media_log_->AddEvent(media_log_->CreateSeekEvent(seconds));

  base::TimeDelta seek_time = ConvertSecondsToTimestamp(seconds);

  // Update our paused time.
  if (paused_)
    paused_time_ = seek_time;

  seeking_ = true;

  if (chunk_demuxer_)
    chunk_demuxer_->StartWaitingForSeek();

  // Kick off the asynchronous seek!
  pipeline_->Seek(
      seek_time,
      BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineSeek));
}

void WebMediaPlayerImpl::setRate(double rate) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  // TODO(kylep): Remove when support for negatives is added. Also, modify the
  // following checks so rewind uses reasonable values also.
  if (rate < 0.0)
    return;

  // Limit rates to reasonable values by clamping.
  if (rate != 0.0) {
    if (rate < kMinRate)
      rate = kMinRate;
    else if (rate > kMaxRate)
      rate = kMaxRate;
  }

  playback_rate_ = rate;
  if (!paused_) {
    pipeline_->SetPlaybackRate(rate);
  }
}

void WebMediaPlayerImpl::setVolume(double volume) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  pipeline_->SetVolume(volume);
}

#define COMPILE_ASSERT_MATCHING_ENUM(webkit_name, chromium_name) \
    COMPILE_ASSERT(static_cast<int>(WebMediaPlayer::webkit_name) == \
                   static_cast<int>(webkit_media::chromium_name), \
                   mismatching_enums)
COMPILE_ASSERT_MATCHING_ENUM(PreloadNone, NONE);
COMPILE_ASSERT_MATCHING_ENUM(PreloadMetaData, METADATA);
COMPILE_ASSERT_MATCHING_ENUM(PreloadAuto, AUTO);
#undef COMPILE_ASSERT_MATCHING_ENUM

void WebMediaPlayerImpl::setPreload(WebMediaPlayer::Preload preload) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  if (data_source_)
    data_source_->SetPreload(static_cast<webkit_media::Preload>(preload));
}

bool WebMediaPlayerImpl::hasVideo() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  return pipeline_->HasVideo();
}

bool WebMediaPlayerImpl::hasAudio() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  return pipeline_->HasAudio();
}

WebKit::WebSize WebMediaPlayerImpl::naturalSize() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  gfx::Size size;
  pipeline_->GetNaturalVideoSize(&size);
  return WebKit::WebSize(size);
}

bool WebMediaPlayerImpl::paused() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  return pipeline_->GetPlaybackRate() == 0.0f;
}

bool WebMediaPlayerImpl::seeking() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
    return false;

  return seeking_;
}

double WebMediaPlayerImpl::duration() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
    return std::numeric_limits<double>::quiet_NaN();

  if (chunk_demuxer_)
    return chunk_demuxer_->GetDuration();

  return GetPipelineDuration();
}

double WebMediaPlayerImpl::currentTime() const {
  DCHECK(main_loop_->BelongsToCurrentThread());
  return (paused_ ? paused_time_ : pipeline_->GetMediaTime()).InSecondsF();
}

WebMediaPlayer::NetworkState WebMediaPlayerImpl::networkState() const {
  DCHECK(main_loop_->BelongsToCurrentThread());
  return network_state_;
}

WebMediaPlayer::ReadyState WebMediaPlayerImpl::readyState() const {
  DCHECK(main_loop_->BelongsToCurrentThread());
  return ready_state_;
}

const WebKit::WebTimeRanges& WebMediaPlayerImpl::buffered() {
  DCHECK(main_loop_->BelongsToCurrentThread());
  WebKit::WebTimeRanges web_ranges(
      ConvertToWebTimeRanges(pipeline_->GetBufferedTimeRanges()));
  buffered_.swap(web_ranges);
  return buffered_;
}

double WebMediaPlayerImpl::maxTimeSeekable() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  // If we haven't even gotten to ReadyStateHaveMetadata yet then just
  // return 0 so that the seekable range is empty.
  if (ready_state_ < WebMediaPlayer::ReadyStateHaveMetadata)
    return 0.0;

  // We don't support seeking in streaming media.
  if (data_source_ && data_source_->IsStreaming())
    return 0.0;
  return duration();
}

bool WebMediaPlayerImpl::didLoadingProgress() const {
  DCHECK(main_loop_->BelongsToCurrentThread());
  return pipeline_->DidLoadingProgress();
}

void WebMediaPlayerImpl::paint(WebCanvas* canvas,
                               const WebRect& rect,
                               unsigned char alpha) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  if (!accelerated_compositing_reported_) {
    accelerated_compositing_reported_ = true;
    // Normally paint() is only called in non-accelerated rendering, but there
    // are exceptions such as webgl where compositing is used in the WebView but
    // video frames are still rendered to a canvas.
    UMA_HISTOGRAM_BOOLEAN(
        "Media.AcceleratedCompositingActive",
        frame_->view()->isAcceleratedCompositingActive());
  }

  // Avoid locking and potentially blocking the video rendering thread while
  // painting in software.
  scoped_refptr<media::VideoFrame> video_frame;
  {
    base::AutoLock auto_lock(lock_);
    video_frame = current_frame_;
  }
  gfx::Rect gfx_rect(rect);
  skcanvas_video_renderer_.Paint(video_frame.get(), canvas, gfx_rect, alpha);
}

bool WebMediaPlayerImpl::hasSingleSecurityOrigin() const {
  if (data_source_)
    return data_source_->HasSingleOrigin();
  return true;
}

bool WebMediaPlayerImpl::didPassCORSAccessCheck() const {
  if (data_source_)
    return data_source_->DidPassCORSAccessCheck();
  return false;
}

double WebMediaPlayerImpl::mediaTimeForTimeValue(double timeValue) const {
  return ConvertSecondsToTimestamp(timeValue).InSecondsF();
}

unsigned WebMediaPlayerImpl::decodedFrameCount() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  media::PipelineStatistics stats = pipeline_->GetStatistics();
  return stats.video_frames_decoded;
}

unsigned WebMediaPlayerImpl::droppedFrameCount() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  media::PipelineStatistics stats = pipeline_->GetStatistics();
  return stats.video_frames_dropped;
}

unsigned WebMediaPlayerImpl::audioDecodedByteCount() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  media::PipelineStatistics stats = pipeline_->GetStatistics();
  return stats.audio_bytes_decoded;
}

unsigned WebMediaPlayerImpl::videoDecodedByteCount() const {
  DCHECK(main_loop_->BelongsToCurrentThread());

  media::PipelineStatistics stats = pipeline_->GetStatistics();
  return stats.video_bytes_decoded;
}

void WebMediaPlayerImpl::SetVideoFrameProviderClient(
    cc::VideoFrameProvider::Client* client) {
  // This is called from both the main renderer thread and the compositor
  // thread (when the main thread is blocked).
  if (video_frame_provider_client_)
    video_frame_provider_client_->StopUsingProvider();
  video_frame_provider_client_ = client;
}

scoped_refptr<media::VideoFrame> WebMediaPlayerImpl::GetCurrentFrame() {
  base::AutoLock auto_lock(lock_);
  return current_frame_;
}

void WebMediaPlayerImpl::PutCurrentFrame(
    const scoped_refptr<media::VideoFrame>& frame) {
  if (!accelerated_compositing_reported_) {
    accelerated_compositing_reported_ = true;
    DCHECK(frame_->view()->isAcceleratedCompositingActive());
    UMA_HISTOGRAM_BOOLEAN("Media.AcceleratedCompositingActive", true);
  }
}

bool WebMediaPlayerImpl::copyVideoTextureToPlatformTexture(
    WebKit::WebGraphicsContext3D* web_graphics_context,
    unsigned int texture,
    unsigned int level,
    unsigned int internal_format,
    unsigned int type,
    bool premultiply_alpha,
    bool flip_y) {
  scoped_refptr<media::VideoFrame> video_frame;
  {
    base::AutoLock auto_lock(lock_);
    video_frame = current_frame_;
  }
  if (video_frame.get() &&
      video_frame->format() == media::VideoFrame::NATIVE_TEXTURE &&
      video_frame->texture_target() == GL_TEXTURE_2D) {
    uint32 source_texture = video_frame->texture_id();
    // The video is stored in a unmultiplied format, so premultiply
    // if necessary.
    web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
        premultiply_alpha);
    // Application itself needs to take care of setting the right flip_y
    // value down to get the expected result.
    // flip_y==true means to reverse the video orientation while
    // flip_y==false means to keep the intrinsic orientation.
    web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, flip_y);
    web_graphics_context->copyTextureCHROMIUM(GL_TEXTURE_2D,
        source_texture, texture, level, internal_format, type);
    web_graphics_context->pixelStorei(GL_UNPACK_FLIP_Y_CHROMIUM, false);
    web_graphics_context->pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
        false);
    // The flush() operation is not necessary here. It is kept since the
    // performance will be better when it is added than not.
    web_graphics_context->flush();
    return true;
  }
  return false;
}

// Helper functions to report media EME related stats to UMA. They follow the
// convention of more commonly used macros UMA_HISTOGRAM_ENUMERATION and
// UMA_HISTOGRAM_COUNTS. The reason that we cannot use those macros directly is
// that UMA_* macros require the names to be constant throughout the process'
// lifetime.
static void EmeUMAHistogramEnumeration(const std::string& key_system,
                                       const std::string& method,
                                       int sample,
                                       int boundary_value) {
  base::LinearHistogram::FactoryGet(
      kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
      1, boundary_value, boundary_value + 1,
      base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
}

static void EmeUMAHistogramCounts(const std::string& key_system,
                                  const std::string& method,
                                  int sample) {
  // Use the same parameters as UMA_HISTOGRAM_COUNTS.
  base::Histogram::FactoryGet(
      kMediaEme + KeySystemNameForUMA(key_system) + "." + method,
      1, 1000000, 50, base::Histogram::kUmaTargetedHistogramFlag)->Add(sample);
}

// Helper enum for reporting generateKeyRequest/addKey histograms.
enum MediaKeyException {
  kUnknownResultId,
  kSuccess,
  kKeySystemNotSupported,
  kInvalidPlayerState,
  kMaxMediaKeyException
};

static MediaKeyException MediaKeyExceptionForUMA(
    WebMediaPlayer::MediaKeyException e) {
  switch (e) {
    case WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported:
      return kKeySystemNotSupported;
    case WebMediaPlayer::MediaKeyExceptionInvalidPlayerState:
      return kInvalidPlayerState;
    case WebMediaPlayer::MediaKeyExceptionNoError:
      return kSuccess;
    default:
      return kUnknownResultId;
  }
}

// Helper for converting |key_system| name and exception |e| to a pair of enum
// values from above, for reporting to UMA.
static void ReportMediaKeyExceptionToUMA(
    const std::string& method,
    const WebString& key_system,
    WebMediaPlayer::MediaKeyException e) {
  MediaKeyException result_id = MediaKeyExceptionForUMA(e);
  DCHECK_NE(result_id, kUnknownResultId) << e;
  EmeUMAHistogramEnumeration(
      key_system.utf8(), method, result_id, kMaxMediaKeyException);
}

WebMediaPlayer::MediaKeyException
WebMediaPlayerImpl::generateKeyRequest(const WebString& key_system,
                                       const unsigned char* init_data,
                                       unsigned init_data_length) {
  WebMediaPlayer::MediaKeyException e =
      GenerateKeyRequestInternal(key_system, init_data, init_data_length);
  ReportMediaKeyExceptionToUMA("generateKeyRequest", key_system, e);
  return e;
}

WebMediaPlayer::MediaKeyException
WebMediaPlayerImpl::GenerateKeyRequestInternal(
    const WebString& key_system,
    const unsigned char* init_data,
    unsigned init_data_length) {
  if (!IsSupportedKeySystem(key_system))
    return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;

  // We do not support run-time switching between key systems for now.
  if (current_key_system_.isEmpty())
    current_key_system_ = key_system;
  else if (key_system != current_key_system_)
    return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;

  DVLOG(1) << "generateKeyRequest: " << key_system.utf8().data() << ": "
           << std::string(reinterpret_cast<const char*>(init_data),
                          static_cast<size_t>(init_data_length));

  // TODO(xhwang): We assume all streams are from the same container (thus have
  // the same "type") for now. In the future, the "type" should be passed down
  // from the application.
  if (!decryptor_->GenerateKeyRequest(key_system.utf8(),
                                      init_data_type_,
                                      init_data, init_data_length)) {
    current_key_system_.reset();
    return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;
  }

  return WebMediaPlayer::MediaKeyExceptionNoError;
}

WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::addKey(
    const WebString& key_system,
    const unsigned char* key,
    unsigned key_length,
    const unsigned char* init_data,
    unsigned init_data_length,
    const WebString& session_id) {
  WebMediaPlayer::MediaKeyException e = AddKeyInternal(
      key_system, key, key_length, init_data, init_data_length, session_id);
  ReportMediaKeyExceptionToUMA("addKey", key_system, e);
  return e;
}

WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::AddKeyInternal(
    const WebString& key_system,
    const unsigned char* key,
    unsigned key_length,
    const unsigned char* init_data,
    unsigned init_data_length,
    const WebString& session_id) {
  DCHECK(key);
  DCHECK_GT(key_length, 0u);

  if (!IsSupportedKeySystem(key_system))
    return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;

  if (current_key_system_.isEmpty() || key_system != current_key_system_)
    return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;

  DVLOG(1) << "addKey: " << key_system.utf8().data() << ": "
           << std::string(reinterpret_cast<const char*>(key),
                          static_cast<size_t>(key_length)) << ", "
           << std::string(reinterpret_cast<const char*>(init_data),
                          static_cast<size_t>(init_data_length))
           << " [" << session_id.utf8().data() << "]";

  decryptor_->AddKey(key_system.utf8(), key, key_length,
                     init_data, init_data_length, session_id.utf8());
  return WebMediaPlayer::MediaKeyExceptionNoError;
}

WebMediaPlayer::MediaKeyException WebMediaPlayerImpl::cancelKeyRequest(
    const WebString& key_system,
    const WebString& session_id) {
  WebMediaPlayer::MediaKeyException e =
      CancelKeyRequestInternal(key_system, session_id);
  ReportMediaKeyExceptionToUMA("cancelKeyRequest", key_system, e);
  return e;
}

WebMediaPlayer::MediaKeyException
WebMediaPlayerImpl::CancelKeyRequestInternal(
    const WebString& key_system,
    const WebString& session_id) {
  if (!IsSupportedKeySystem(key_system))
    return WebMediaPlayer::MediaKeyExceptionKeySystemNotSupported;

  if (current_key_system_.isEmpty() || key_system != current_key_system_)
    return WebMediaPlayer::MediaKeyExceptionInvalidPlayerState;

  decryptor_->CancelKeyRequest(key_system.utf8(), session_id.utf8());
  return WebMediaPlayer::MediaKeyExceptionNoError;
}

void WebMediaPlayerImpl::WillDestroyCurrentMessageLoop() {
  Destroy();
}

void WebMediaPlayerImpl::Repaint() {
  DCHECK(main_loop_->BelongsToCurrentThread());

  bool size_changed = false;
  {
    base::AutoLock auto_lock(lock_);
    std::swap(pending_size_change_, size_changed);
    pending_repaint_ = false;
  }

  if (size_changed)
    GetClient()->sizeChanged();

  GetClient()->repaint();
}

void WebMediaPlayerImpl::OnPipelineSeek(PipelineStatus status) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  starting_ = false;
  seeking_ = false;
  if (pending_seek_) {
    pending_seek_ = false;
    seek(pending_seek_seconds_);
    return;
  }

  if (status != media::PIPELINE_OK) {
    OnPipelineError(status);
    return;
  }

  // Update our paused time.
  if (paused_)
    paused_time_ = pipeline_->GetMediaTime();

  GetClient()->timeChanged();
}

void WebMediaPlayerImpl::OnPipelineEnded() {
  DCHECK(main_loop_->BelongsToCurrentThread());
  GetClient()->timeChanged();
}

void WebMediaPlayerImpl::OnPipelineError(PipelineStatus error) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DCHECK_NE(error, media::PIPELINE_OK);

  if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing) {
    // Any error that occurs before reaching ReadyStateHaveMetadata should
    // be considered a format error.
    SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
    Repaint();
    return;
  }

  SetNetworkState(PipelineErrorToNetworkState(error));

  if (error == media::PIPELINE_ERROR_DECRYPT)
    EmeUMAHistogramCounts(current_key_system_.utf8(), "DecryptError", 1);

  // Repaint to trigger UI update.
  Repaint();
}

void WebMediaPlayerImpl::OnPipelineBufferingState(
    media::Pipeline::BufferingState buffering_state) {
  DVLOG(1) << "OnPipelineBufferingState(" << buffering_state << ")";

  switch (buffering_state) {
    case media::Pipeline::kHaveMetadata:
      SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);

      if (hasVideo() && GetClient()->needsWebLayerForVideo()) {
        DCHECK(!video_weblayer_);
        video_weblayer_.reset(
            new webkit::WebLayerImpl(cc::VideoLayer::Create(this)));
        GetClient()->setWebLayer(video_weblayer_.get());
      }
      break;
    case media::Pipeline::kPrerollCompleted:
      SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
      break;
  }

  // Repaint to trigger UI update.
  Repaint();
}

void WebMediaPlayerImpl::OnDemuxerOpened(
    scoped_ptr<WebKit::WebMediaSource> media_source) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  media_source->open(new WebMediaSourceClientImpl(
      chunk_demuxer_, base::Bind(&LogMediaSourceError, media_log_)));
}

void WebMediaPlayerImpl::OnKeyAdded(const std::string& key_system,
                                    const std::string& session_id) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  EmeUMAHistogramCounts(key_system, "KeyAdded", 1);
  GetClient()->keyAdded(WebString::fromUTF8(key_system),
                        WebString::fromUTF8(session_id));
}

void WebMediaPlayerImpl::OnNeedKey(const std::string& key_system,
                                   const std::string& session_id,
                                   const std::string& type,
                                   scoped_ptr<uint8[]> init_data,
                                   int init_data_size) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  // Do not fire NeedKey event if encrypted media is not enabled.
  if (!decryptor_)
    return;

  UMA_HISTOGRAM_COUNTS(kMediaEme + std::string("NeedKey"), 1);

  DCHECK(init_data_type_.empty() || type.empty() || type == init_data_type_);
  if (init_data_type_.empty())
    init_data_type_ = type;

  GetClient()->keyNeeded(WebString::fromUTF8(key_system),
                         WebString::fromUTF8(session_id),
                         init_data.get(),
                         init_data_size);
}

scoped_ptr<media::TextTrack>
WebMediaPlayerImpl::OnTextTrack(media::TextKind kind,
                                const std::string& label,
                                const std::string& language) {
  typedef WebInbandTextTrackImpl::Kind webkind_t;
  const webkind_t webkind = static_cast<webkind_t>(kind);
  const WebKit::WebString weblabel = WebKit::WebString::fromUTF8(label);
  const WebKit::WebString weblanguage = WebKit::WebString::fromUTF8(language);

  WebInbandTextTrackImpl* const text_track =
    new WebInbandTextTrackImpl(webkind, weblabel, weblanguage,
                               text_track_index_++);
  GetClient()->addTextTrack(text_track);

  return scoped_ptr<media::TextTrack>(new TextTrackImpl(text_track));
}

#define COMPILE_ASSERT_MATCHING_ENUM(name) \
  COMPILE_ASSERT( \
  static_cast<int>(WebKit::WebMediaPlayerClient::MediaKeyErrorCode ## name) == \
  static_cast<int>(media::MediaKeys::k ## name ## Error), \
  mismatching_enums)
COMPILE_ASSERT_MATCHING_ENUM(Unknown);
COMPILE_ASSERT_MATCHING_ENUM(Client);
COMPILE_ASSERT_MATCHING_ENUM(Service);
COMPILE_ASSERT_MATCHING_ENUM(Output);
COMPILE_ASSERT_MATCHING_ENUM(HardwareChange);
COMPILE_ASSERT_MATCHING_ENUM(Domain);
#undef COMPILE_ASSERT_MATCHING_ENUM

void WebMediaPlayerImpl::OnKeyError(const std::string& key_system,
                                    const std::string& session_id,
                                    media::MediaKeys::KeyError error_code,
                                    int system_code) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  EmeUMAHistogramEnumeration(
      key_system, "KeyError", error_code, media::MediaKeys::kMaxKeyError);

  GetClient()->keyError(
      WebString::fromUTF8(key_system),
      WebString::fromUTF8(session_id),
      static_cast<WebKit::WebMediaPlayerClient::MediaKeyErrorCode>(error_code),
      system_code);
}

void WebMediaPlayerImpl::OnKeyMessage(const std::string& key_system,
                                      const std::string& session_id,
                                      const std::string& message,
                                      const std::string& default_url) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  const GURL default_url_gurl(default_url);
  DLOG_IF(WARNING, !default_url.empty() && !default_url_gurl.is_valid())
      << "Invalid URL in default_url: " << default_url;

  GetClient()->keyMessage(WebString::fromUTF8(key_system),
                          WebString::fromUTF8(session_id),
                          reinterpret_cast<const uint8*>(message.data()),
                          message.size(),
                          default_url_gurl);
}

void WebMediaPlayerImpl::SetOpaque(bool opaque) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  GetClient()->setOpaque(opaque);
}

void WebMediaPlayerImpl::DataSourceInitialized(const GURL& gurl, bool success) {
  DCHECK(main_loop_->BelongsToCurrentThread());

  if (!success) {
    SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
    Repaint();
    return;
  }

  StartPipeline(NULL);
}

void WebMediaPlayerImpl::NotifyDownloading(bool is_downloading) {
  if (!is_downloading && network_state_ == WebMediaPlayer::NetworkStateLoading)
    SetNetworkState(WebMediaPlayer::NetworkStateIdle);
  else if (is_downloading && network_state_ == WebMediaPlayer::NetworkStateIdle)
    SetNetworkState(WebMediaPlayer::NetworkStateLoading);
  media_log_->AddEvent(
      media_log_->CreateBooleanEvent(
          media::MediaLogEvent::NETWORK_ACTIVITY_SET,
          "is_downloading_data", is_downloading));
}

void WebMediaPlayerImpl::StartPipeline(WebKit::WebMediaSource* media_source) {
  const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  bool increase_preroll_on_underflow = true;

  // Keep track if this is a MSE or non-MSE playback.
  UMA_HISTOGRAM_BOOLEAN("Media.MSE.Playback", (media_source != NULL));

  // Figure out which demuxer to use.
  if (!media_source) {
    DCHECK(!chunk_demuxer_);
    DCHECK(data_source_);

    demuxer_.reset(new media::FFmpegDemuxer(
        media_loop_, data_source_.get(),
        BIND_TO_RENDER_LOOP_2(&WebMediaPlayerImpl::OnNeedKey, "", "")));
  } else {
    DCHECK(!chunk_demuxer_);
    DCHECK(!data_source_);

    scoped_ptr<WebKit::WebMediaSource> ms(media_source);
    chunk_demuxer_ = new media::ChunkDemuxer(
        BIND_TO_RENDER_LOOP_1(&WebMediaPlayerImpl::OnDemuxerOpened,
                              base::Passed(&ms)),
        BIND_TO_RENDER_LOOP_2(&WebMediaPlayerImpl::OnNeedKey, "", ""),
        base::Bind(&WebMediaPlayerImpl::OnTextTrack, base::Unretained(this)),
        base::Bind(&LogMediaSourceError, media_log_));
    demuxer_.reset(chunk_demuxer_);

    // Disable GpuVideoDecoder creation until it supports codec config changes.
    // TODO(acolwell): Remove this once http://crbug.com/151045 is fixed.
    gpu_factories_ = NULL;

    // Disable preroll increases on underflow since the web application has no
    // way to detect that this is happening and runs the risk of triggering
    // unwanted garbage collection if it is to aggressive about appending data.
    // TODO(acolwell): Remove this once http://crbug.com/144683 is fixed.
    increase_preroll_on_underflow = false;
  }

  scoped_ptr<media::FilterCollection> filter_collection(
      new media::FilterCollection());
  filter_collection->SetDemuxer(demuxer_.get());

  // Figure out if EME is enabled.
  media::SetDecryptorReadyCB set_decryptor_ready_cb;
  if (decryptor_) {
    set_decryptor_ready_cb = base::Bind(&ProxyDecryptor::SetDecryptorReadyCB,
                                        base::Unretained(decryptor_.get()));
  }

  // Create our audio decoders and renderer.
  ScopedVector<media::AudioDecoder> audio_decoders;
  audio_decoders.push_back(new media::FFmpegAudioDecoder(media_loop_));
  if (cmd_line->HasSwitch(switches::kEnableOpusPlayback)) {
    audio_decoders.push_back(new media::OpusAudioDecoder(media_loop_));
  }

  scoped_ptr<media::AudioRenderer> audio_renderer(
      new media::AudioRendererImpl(media_loop_,
                                   audio_source_provider_.get(),
                                   audio_decoders.Pass(),
                                   set_decryptor_ready_cb,
                                   increase_preroll_on_underflow));
  filter_collection->SetAudioRenderer(audio_renderer.Pass());

  // Create our video decoders and renderer.
  ScopedVector<media::VideoDecoder> video_decoders;

  if (gpu_factories_.get()) {
    video_decoders.push_back(new media::GpuVideoDecoder(
        media_loop_, gpu_factories_));
  }

  // TODO(phajdan.jr): Remove ifdefs when libvpx with vp9 support is released
  // (http://crbug.com/174287) .
#if !defined(MEDIA_DISABLE_LIBVPX)
  video_decoders.push_back(new media::VpxVideoDecoder(media_loop_));
#endif  // !defined(MEDIA_DISABLE_LIBVPX)

  video_decoders.push_back(new media::FFmpegVideoDecoder(media_loop_));

  scoped_ptr<media::VideoRenderer> video_renderer(
      new media::VideoRendererBase(
          media_loop_,
          video_decoders.Pass(),
          set_decryptor_ready_cb,
          base::Bind(&WebMediaPlayerImpl::FrameReady, base::Unretained(this)),
          BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::SetOpaque),
          true));
  filter_collection->SetVideoRenderer(video_renderer.Pass());

  // ... and we're ready to go!
  starting_ = true;
  pipeline_->Start(
      filter_collection.Pass(),
      BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineEnded),
      BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineError),
      BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineSeek),
      BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnPipelineBufferingState),
      BIND_TO_RENDER_LOOP(&WebMediaPlayerImpl::OnDurationChange));
}

void WebMediaPlayerImpl::SetNetworkState(WebMediaPlayer::NetworkState state) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "SetNetworkState: " << state;
  network_state_ = state;
  // Always notify to ensure client has the latest value.
  GetClient()->networkStateChanged();
}

void WebMediaPlayerImpl::SetReadyState(WebMediaPlayer::ReadyState state) {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DVLOG(1) << "SetReadyState: " << state;

  if (state == WebMediaPlayer::ReadyStateHaveEnoughData &&
      is_local_source_ &&
      network_state_ == WebMediaPlayer::NetworkStateLoading)
    SetNetworkState(WebMediaPlayer::NetworkStateLoaded);

  ready_state_ = state;
  // Always notify to ensure client has the latest value.
  GetClient()->readyStateChanged();
}

void WebMediaPlayerImpl::Destroy() {
  DCHECK(main_loop_->BelongsToCurrentThread());

  // Abort any pending IO so stopping the pipeline doesn't get blocked.
  if (data_source_)
    data_source_->Abort();
  if (chunk_demuxer_) {
    chunk_demuxer_->Shutdown();
    chunk_demuxer_ = NULL;
  }

  if (gpu_factories_.get()) {
    gpu_factories_->Abort();
    gpu_factories_ = NULL;
  }

  // Make sure to kill the pipeline so there's no more media threads running.
  // Note: stopping the pipeline might block for a long time.
  base::WaitableEvent waiter(false, false);
  pipeline_->Stop(base::Bind(
      &base::WaitableEvent::Signal, base::Unretained(&waiter)));
  waiter.Wait();

  // Let V8 know we are not using extra resources anymore.
  if (incremented_externally_allocated_memory_) {
    v8::V8::AdjustAmountOfExternalAllocatedMemory(-kPlayerExtraMemory);
    incremented_externally_allocated_memory_ = false;
  }

  // Release any final references now that everything has stopped.
  pipeline_.reset();
  demuxer_.reset();
  data_source_.reset();
}

WebKit::WebMediaPlayerClient* WebMediaPlayerImpl::GetClient() {
  DCHECK(main_loop_->BelongsToCurrentThread());
  DCHECK(client_);
  return client_;
}

WebKit::WebAudioSourceProvider* WebMediaPlayerImpl::audioSourceProvider() {
  return audio_source_provider_.get();
}

void WebMediaPlayerImpl::IncrementExternallyAllocatedMemory() {
  DCHECK(main_loop_->BelongsToCurrentThread());
  incremented_externally_allocated_memory_ = true;
  v8::V8::AdjustAmountOfExternalAllocatedMemory(kPlayerExtraMemory);
}

double WebMediaPlayerImpl::GetPipelineDuration() const {
  base::TimeDelta duration = pipeline_->GetMediaDuration();

  // Return positive infinity if the resource is unbounded.
  // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
  if (duration == media::kInfiniteDuration())
    return std::numeric_limits<double>::infinity();

  return duration.InSecondsF();
}

void WebMediaPlayerImpl::OnDurationChange() {
  if (ready_state_ == WebMediaPlayer::ReadyStateHaveNothing)
    return;

  GetClient()->durationChanged();
}

void WebMediaPlayerImpl::FrameReady(
    const scoped_refptr<media::VideoFrame>& frame) {
  base::AutoLock auto_lock(lock_);

  if (current_frame_.get() &&
      current_frame_->natural_size() != frame->natural_size() &&
      !pending_size_change_) {
    pending_size_change_ = true;
  }

  current_frame_ = frame;

  if (pending_repaint_)
    return;

  pending_repaint_ = true;
  main_loop_->PostTask(FROM_HERE, base::Bind(
      &WebMediaPlayerImpl::Repaint, AsWeakPtr()));
}

}  // namespace webkit_media


text:
package org.s1.cluster.dds.beans;

import org.s1.objects.Objects;

import java.util.Map;

/**
 * Command bean
 */
public class Id extends CollectionId {
    private String entity;

    /**
     *
     */
    public Id() {
    }

    /**
     *
     * @param database
     * @param collection
     * @param entity
     */
    public Id(String database, String collection, String entity) {
        super(database,collection);
        this.entity = entity;
    }

    public Id(Map<String,Object> m) {
        this.fromMap(m);
    }

   /**
     *
     * @return
     */
    public String getEntity() {
        return entity;
    }

    /**
     *
     * @param entity
     */
    public void setEntity(String entity) {
        this.entity = entity;
    }

    /**
     *
     * @return
     */
    public String toString(){
        String s = super.toString()+", entity: "+getEntity();
        return s;
    }

    public void fromMap(Map<String,Object> m){
        super.fromMap(m);
        setEntity(Objects.get(String.class,m,"id"));
    }

    public Map<String,Object> toMap(){
        Map<String,Object> m = super.toMap();
        m.put("id",getEntity());
        return m;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.1
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

namespace RakNet {

using System;
using System.Runtime.InteropServices;

public class ConnectionGraph2 : PluginInterface2 {
  private HandleRef swigCPtr;

  internal ConnectionGraph2(IntPtr cPtr, bool cMemoryOwn) : base(RakNetPINVOKE.ConnectionGraph2_SWIGUpcast(cPtr), cMemoryOwn) {
    swigCPtr = new HandleRef(this, cPtr);
  }

  internal static HandleRef getCPtr(ConnectionGraph2 obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  ~ConnectionGraph2() {
    Dispose();
  }

  public override void Dispose() {
    lock(this) {
      if (swigCPtr.Handle != IntPtr.Zero) {
        if (swigCMemOwn) {
          swigCMemOwn = false;
          RakNetPINVOKE.delete_ConnectionGraph2(swigCPtr);
        }
        swigCPtr = new HandleRef(null, IntPtr.Zero);
      }
      GC.SuppressFinalize(this);
      base.Dispose();
    }
  }

    public bool GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress[] saOut, RakNetGUID[] guidOut, ref uint inOutLength)
    {
        uint minLength = inOutLength;
        if (guidOut.Length < minLength)
        { minLength = (uint)guidOut.Length; }

        if (saOut.Length < minLength)
        { minLength = (uint)saOut.Length; }

        RakNetListRakNetGUID passListGUID = new RakNetListRakNetGUID();
        RakNetListSystemAddress passListSystemAddress = new RakNetListSystemAddress();

        bool returnVal = GetConnectionListForRemoteSystemHelper(remoteSystemGuid, passListSystemAddress, passListGUID, ref inOutLength);

        if (inOutLength< minLength)
        { minLength = (uint)inOutLength;}

        for (int i = 0; i < minLength; i++)
        {
            guidOut[i] = passListGUID[i];
            saOut[i] = passListSystemAddress[i];
        }
        return returnVal;
    }

    public void GetParticipantList(RakNetGUID[] participantList)
    {
			RakNetListRakNetGUID passListGUID = new RakNetListRakNetGUID();
			GetParticipantListHelper(passListGUID);
			for (int i = 0; i < participantList.Length && i < passListGUID.Size(); i++)
			{
			  participantList[i] = passListGUID[i];
			}
    }

  public static ConnectionGraph2 GetInstance() {
    IntPtr cPtr = RakNetPINVOKE.ConnectionGraph2_GetInstance();
    ConnectionGraph2 ret = (cPtr == IntPtr.Zero) ? null : new ConnectionGraph2(cPtr, false);
    return ret;
  }

  public static void DestroyInstance(ConnectionGraph2 i) {
    RakNetPINVOKE.ConnectionGraph2_DestroyInstance(ConnectionGraph2.getCPtr(i));
  }

  public ConnectionGraph2() : this(RakNetPINVOKE.new_ConnectionGraph2(), true) {
  }

  public bool GetConnectionListForRemoteSystem(RakNetGUID remoteSystemGuid, SystemAddress saOut, RakNetGUID guidOut, out uint outLength) {
    bool ret = RakNetPINVOKE.ConnectionGraph2_GetConnectionListForRemoteSystem(swigCPtr, RakNetGUID.getCPtr(remoteSystemGuid), SystemAddress.getCPtr(saOut), RakNetGUID.getCPtr(guidOut), out outLength);
    if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

  public bool ConnectionExists(RakNetGUID g1, RakNetGUID g2) {
    bool ret = RakNetPINVOKE.ConnectionGraph2_ConnectionExists(swigCPtr, RakNetGUID.getCPtr(g1), RakNetGUID.getCPtr(g2));
    if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

  public ushort GetPingBetweenSystems(RakNetGUID g1, RakNetGUID g2) {
    ushort ret = RakNetPINVOKE.ConnectionGraph2_GetPingBetweenSystems(swigCPtr, RakNetGUID.getCPtr(g1), RakNetGUID.getCPtr(g2));
    if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

  public RakNetGUID GetLowestAveragePingSystem() {
    RakNetGUID ret = new RakNetGUID(RakNetPINVOKE.ConnectionGraph2_GetLowestAveragePingSystem(swigCPtr), true);
    return ret;
  }

  public void SetAutoProcessNewConnections(bool b) {
    RakNetPINVOKE.ConnectionGraph2_SetAutoProcessNewConnections(swigCPtr, b);
  }

  public bool GetAutoProcessNewConnections() {
    bool ret = RakNetPINVOKE.ConnectionGraph2_GetAutoProcessNewConnections(swigCPtr);
    return ret;
  }

  public void AddParticipant(SystemAddress systemAddress, RakNetGUID rakNetGUID) {
    RakNetPINVOKE.ConnectionGraph2_AddParticipant(swigCPtr, SystemAddress.getCPtr(systemAddress), RakNetGUID.getCPtr(rakNetGUID));
    if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
  }

  private bool GetConnectionListForRemoteSystemHelper(RakNetGUID remoteSystemGuid, RakNetListSystemAddress saOut, RakNetListRakNetGUID guidOut, ref uint inOutLength) {
    bool ret = RakNetPINVOKE.ConnectionGraph2_GetConnectionListForRemoteSystemHelper(swigCPtr, RakNetGUID.getCPtr(remoteSystemGuid), RakNetListSystemAddress.getCPtr(saOut), RakNetListRakNetGUID.getCPtr(guidOut), ref inOutLength);
    if (RakNetPINVOKE.SWIGPendingException.Pending) throw RakNetPINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

  private void GetParticipantListHelper(RakNetListRakNetGUID guidOut) {
    RakNetPINVOKE.ConnectionGraph2_GetParticipantListHelper(swigCPtr, RakNetListRakNetGUID.getCPtr(guidOut));
  }

}

}


text:
namespace budget {

void init_logging(int& argc, char** argv);

} // end of budget namespace


text:
/*
 * 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 com.addthis.hydra.data.filter.value;

import javax.annotation.Syntax;

import java.io.IOException;

import com.addthis.bundle.value.ValueFactory;
import com.addthis.codec.config.Configs;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

public class TestValueFilterGrepTags {

    @Test
    public void basic() throws IOException {
        @Syntax("HTML") String html =
                "  <meta charset=\"UTF-8\" /> <title>Peacock</title> " +
                "<LINK href=\"lib/bootstrap/bootstrap.css\" rel=\"stylesheet\" type=\"text/css\"> " +
                " " +
                " " +
                " " +
                " " +
                " " +
                "

 " +
                "  ";

        ValueFilterGrepTags grepTags = Configs.decodeObject(
                ValueFilterGrepTags.class, "values = [bootstrap, jquery], tagAttrs = src, tagName = script");
        assertNotNull(grepTags.filterValue(ValueFactory.create(html)));

        ValueFilterGrepTags failGrepTags = Configs.decodeObject(
                ValueFilterGrepTags.class, "values = [foo, bar], tagAttrs = src, tagName = script");
        assertNull(failGrepTags.filterValue(ValueFactory.create(html)));
    }
}


text:
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;

namespace System.Reflection
{
    // This file defines an internal class used to throw exceptions. The main purpose is to reduce code size.
    // Also it improves the likelihood that callers will be inlined.
    internal static class Throw
    {
        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidCast()
        {
            throw new InvalidCastException();
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void LitteEndianArchitectureRequired()
        {
            throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidArgument_OffsetForVirtualHeapHandle()
        {
            throw new ArgumentException(SR.CantGetOffsetForVirtualHeapHandle, "handle");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
        {
            throw new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static Exception InvalidArgument_Handle(string parameterName)
        {
            throw new ArgumentException(SR.Format(SR.InvalidHandle), parameterName);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void SignatureNotVarArg()
        {
            throw new InvalidOperationException(SR.SignatureNotVarArg);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void BranchBuilderNotAvailable()
        {
            throw new InvalidOperationException(SR.BranchBuilderNotAvailable);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidOperationBuilderAlreadyLinked()
        {
            throw new InvalidOperationException(SR.BuilderAlreadyLinked);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void LabelDoesntBelongToBuilder(string parameterName)
        {
            throw new ArgumentException(SR.LabelDoesntBelongToBuilder, parameterName);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void HeapHandleRequired()
        {
            throw new ArgumentException(SR.NotMetadataHeapHandle, "handle");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void EntityOrUserStringHandleRequired()
        {
            throw new ArgumentException(SR.NotMetadataTableOrUserStringHandle, "handle");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidToken()
        {
            throw new ArgumentException(SR.InvalidToken, "token");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ArgumentNull(string parameterName)
        {
            throw new ArgumentNullException(parameterName);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ArgumentEmptyString(string parameterName)
        {
            throw new ArgumentException(SR.ExpectedNonEmptyString, parameterName);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ValueArgumentNull()
        {
            throw new ArgumentNullException("value");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void BuilderArgumentNull()
        {
            throw new ArgumentNullException("builder");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ArgumentOutOfRange(string parameterName)
        {
            throw new ArgumentOutOfRangeException(parameterName);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void BlobTooLarge(string parameterName)
        {
            throw new ArgumentOutOfRangeException(parameterName, SR.BlobTooLarge);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void IndexOutOfRange()
        {
            throw new ArgumentOutOfRangeException("index");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void TableIndexOutOfRange()
        {
            throw new ArgumentOutOfRangeException("tableIndex");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ValueArgumentOutOfRange()
        {
            throw new ArgumentOutOfRangeException("value");
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void OutOfBounds()
        {
            throw new BadImageFormatException(SR.OutOfBoundsRead);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void WriteOutOfBounds()
        {
            throw new InvalidOperationException(SR.OutOfBoundsWrite);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidCodedIndex()
        {
            throw new BadImageFormatException(SR.InvalidCodedIndex);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidHandle()
        {
            throw new BadImageFormatException(SR.InvalidHandle);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidCompressedInteger()
        {
            throw new BadImageFormatException(SR.InvalidCompressedInteger);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void InvalidSerializedString()
        {
            throw new BadImageFormatException(SR.InvalidSerializedString);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ImageTooSmall()
        {
            throw new BadImageFormatException(SR.ImageTooSmall);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
        {
            throw new BadImageFormatException(SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ReferenceOverflow()
        {
            throw new BadImageFormatException(SR.RowIdOrHeapOffsetTooLarge);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void TableNotSorted(TableIndex tableIndex)
        {
            throw new BadImageFormatException(SR.Format(SR.MetadataTableNotSorted, (int)tableIndex));
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void TooManySubnamespaces()
        {
            throw new BadImageFormatException(SR.TooManySubnamespaces);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void ValueOverflow()
        {
            throw new BadImageFormatException(SR.ValueTooLarge);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void SequencePointValueOutOfRange()
        {
            throw new BadImageFormatException(SR.SequencePointValueOutOfRange);
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal static void HeapSizeLimitExceeded(HeapIndex heap)
        {
            throw new ImageFormatLimitationException(SR.Format(SR.HeapSizeLimitExceeded, heap));
        }
    }
}


text:
"""Test for the ee.deserializer module."""

import json

import unittest

import ee
from ee import apitestcase
from ee import deserializer
from ee import serializer

class DeserializerTest(apitestcase.ApiTestCase):

  def testLegacyRoundTrip(self):
    """Verifies a round trip of a comprehensive serialization case."""
    encoded = apitestcase.ENCODED_JSON_SAMPLE
    decoded = deserializer.decode(encoded)
    re_encoded = json.loads(serializer.toJSON(decoded, for_cloud_api=False))
    self.assertEqual(encoded, re_encoded)
    # Round-trip the decoded object through the Cloud API
    cloud_encoded = json.loads(serializer.toJSON(decoded, for_cloud_api=True))
    cloud_decoded = deserializer.decode(cloud_encoded)  # Supports both formats
    cloud_re_encoded = json.loads(
        serializer.toJSON(cloud_decoded, for_cloud_api=True))
    self.assertEqual(cloud_encoded, cloud_re_encoded)

  def testCloudRoundTrip(self):
    """Verifies a round trip of a comprehensive serialization case."""
    cloud_encoded = apitestcase.ENCODED_CLOUD_API_JSON_SAMPLE
    cloud_decoded = deserializer.decode(cloud_encoded)  # Supports both formats
    cloud_re_encoded = json.loads(
        serializer.toJSON(cloud_decoded, for_cloud_api=True))
    self.assertEqual(cloud_encoded, cloud_re_encoded)
    # Round-trip the decoded object through the legacy API
    encoded = json.loads(serializer.toJSON(cloud_decoded, for_cloud_api=False))
    decoded = deserializer.decode(encoded)
    re_encoded = json.loads(serializer.toJSON(decoded, for_cloud_api=False))
    self.assertEqual(encoded, re_encoded)

  def testCast(self):
    """Verifies that decoding casts the result to the right class."""
    input_image = ee.Image(13).addBands(42)
    output = deserializer.fromJSON(serializer.toJSON(input_image))
    self.assertIsInstance(output, ee.Image)
    cloud_output = deserializer.fromCloudApiJSON(
        serializer.toJSON(input_image, for_cloud_api=True))
    self.assertIsInstance(cloud_output, ee.Image)

  def testReuse(self):
    """Verifies that decoding results can be used and re-encoded."""
    input_image = ee.Image(13)
    output = deserializer.fromJSON(serializer.toJSON(input_image))
    self.assertEqual(
        output.addBands(42).serialize(),
        input_image.addBands(42).serialize())
    cloud_output = deserializer.fromCloudApiJSON(
        serializer.toJSON(input_image, for_cloud_api=True))
    self.assertEqual(
        cloud_output.addBands(42).serialize(),
        input_image.addBands(42).serialize())

  def testImageExpression(self):
    """Verifies that ee.Image.expression results can be re-encoded."""
    image = ee.Image(13)
    expression = image.expression('x', {'x': image})
    expression_encoded = serializer.toJSON(expression)
    expression_decoded = deserializer.decode(json.loads(expression_encoded))
    expression_re_encoded = serializer.toJSON(expression_decoded)
    self.assertEqual(expression_encoded, expression_re_encoded)

if __name__ == '__main__':
  unittest.main()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.cassandra.io.sstable.metadata</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.cassandra.io.sstable.metadata

Interface Summary

Interface
Description

IMetadataComponentSerializer<T extends MetadataComponent>

Metadata component serializer

IMetadataSerializer

Interface for SSTable metadata serializer

Class Summary

Class
Description

CompactionMetadata

Compaction related SSTable metadata.

CompactionMetadata.CompactionMetadataSerializer

LegacyMetadataSerializer
Deprecated

MetadataCollector

MetadataComponent

MetadataComponent is a component for SSTable metadata and serialized to Stats.db.

MetadataSerializer

Metadata serializer for SSTables version >= 'k'.

MetadataSerializerTest

StatsMetadata

SSTable metadata that always stay on heap.

StatsMetadata.StatsMetadataSerializer

ValidationMetadata

SSTable metadata component used only for validating SSTable.

ValidationMetadata.ValidationMetadataSerializer

Enum Summary

Enum
Description

MetadataType

Defines Metadata component type.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
//
//  NSObject+YJSafeKVO.h
//  YJKit
//
//  Created by huang-kun on 16/4/3.
//  Copyright © 2016年 huang-kun. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "YJKVOPort.h"

NS_ASSUME_NONNULL_BEGIN

/**
 By using YJSafeKVO, the observers will be generated implicitly and it's safe for not removing observers explicitly because eventually observers
 will be removed before observed target gets deallocated. It's vaild to use it multiple times for applying different changes block with same key path.

 If you don't call -unobserve... method when finish key value observing, all implicit generated observers will be removed from observed target before receiver is deallocated. This will automatically happend to avoid the general KVO crash. When the receiver is deallocated before observerd target, the internal observers which related to the receiver will be removed safely as well.
 */
@interface NSObject (YJSafeKVO)

/* ------------------------------------------------------------------------------------------------------------ */
//                                      APIs for using PACK(target, keyPath)
/* ------------------------------------------------------------------------------------------------------------ */

/**
 @brief The receiver observe the target with key path by using Key-Value Observing mechanism with block based callback.

 @param targetAndKeyPath    The YJKVOPort object for wrapping object and its key path, using PACK(target, keyPath).
 @param updates             The block of code will be performed both immediately and when observed value changes.
 */
- (void)observe:(PACK)targetAndKeyPath updates:(void(^)(id receiver, id target, id _Nullable newValue))updates;

/**
 @brief The receiver observe the target with key path by using Key-Value Observing mechanism with block based callback.

 @param targetsAndKeyPaths  The array of YJKVOPort object for wrapping object and its key path, using PACK(target, keyPath).
 @param updates             The block of code will be performed both immediately and when observed value changes.
 */
- (void)observeGroup:(NSArray <PACK> *)targetsAndKeyPaths
             updates:(void(^)(/* id _Nullable newValue1, id _Nullable newValue2, ... */))updates;

/**
 @brief The receiver observe the target with key path by using Key-Value Observing mechanism with block based callback.

 @param targetAndKeyPath    The YJKVOPort object for wrapping object and its key path, using PACK(target, keyPath).
 @param options             A combination of the NSKeyValueObservingOptions values that specifies what is included in observation notifications.
 @param queue               The operation queue to which block should be added.
 @param changes             The block of code will be performed when observed value changes.
 */
- (void)observe:(PACK)targetAndKeyPath
        options:(NSKeyValueObservingOptions)options
          queue:(nullable NSOperationQueue *)queue
        changes:(void(^)(id receiver, id target, id _Nullable newValue, NSDictionary *change))changes;

/**
 @brief Manually stop observing the key path when you finish the job.

 @param targetAndKeyPath    The YJKVOPort object for wrapping object and its key path, using PACK(target, keyPath).
 */
- (void)unobserve:(PACK)targetAndKeyPath;

/* ------------------------------------------------------------------------------------------------------------ */
//                             APIs for manually set target and key path parameters
/* ------------------------------------------------------------------------------------------------------------ */

/**
 @brief The receiver observe the target with key path by using Key-Value Observing mechanism with block based callback.

 @param target      The object which receiver wants to observe.
 @param keyPath     The key path, relative to the target, of the property to observe. This value must not be nil.
 @param updates     The block of code will be performed both immediately and when observed value changes.
 */
- (void)observeTarget:(__kindof NSObject *)target
              keyPath:(NSString *)keyPath
              updates:(void(^)(id receiver, id target, id _Nullable newValue))updates
                NS_SWIFT_NAME(observe(target:keyPath:updates:));

/**
 @brief The receiver observe the target with key path by using Key-Value Observing mechanism with block based callback.

 @param target      The object which receiver wants to observe.
 @param keyPath     The key path, relative to the target, of the property to observe. This value must not be nil.
 @param options     A combination of the NSKeyValueObservingOptions values that specifies what is included in observation notifications.
 @param queue       The operation queue to which block should be added.
 @param changes     The block of code will be performed when observed value changes.
 */
- (void)observeTarget:(__kindof NSObject *)target
              keyPath:(NSString *)keyPath
              options:(NSKeyValueObservingOptions)options
                queue:(nullable NSOperationQueue *)queue
              changes:(void(^)(id receiver, id target, id _Nullable newValue, NSDictionary *change))changes
                NS_SWIFT_NAME(observe(target:keyPath:options:queue:changes:));

/**
 @brief Manually stop observing the key path when you finish the job.

 @param target      The object which receiver wants to observe.
 @param keyPath     The key path, relative to the target, of the property to observe. This value must not be nil.
 */
- (void)unobserveTarget:(__kindof NSObject *)target keyPath:(NSString *)keyPath NS_SWIFT_NAME(unobserve(target:keyPath:));

/* ------------------------------------------------------------------------------------------------------------ */
//                                                General APIs
/* ------------------------------------------------------------------------------------------------------------ */

/**
 @brief Manually stop observing all keyPaths when you finish the job.

 @param target      The object which receiver observed.
 */
- (void)unobserveAll;

@end

NS_ASSUME_NONNULL_END


text:
<?php

namespace Application\Controller\Factory;

use Application\Controller\AccountController;
use Application\Repository\AccountRepositoryInterface;
use Application\Repository\AccountDataRepositoryInterface;
use Application\Repository\FolderRepositoryInterface;
use Application\Service\FaviconService;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class AccountControllerFactory implements FactoryInterface
{

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $folders     = $container->get(FolderRepositoryInterface::class);
        $accounts    = $container->get(AccountRepositoryInterface::class);
        $data        = $container->get(AccountDataRepositoryInterface::class);
        $iconService = $container->get(FaviconService::class);

        return new AccountController($folders, $accounts, $data, $iconService);
    }

}


text:
package com.inmobi.samples.nativeads;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.inmobi.ads.InMobiAdRequestStatus;
import com.inmobi.ads.InMobiNative;
import com.inmobi.samples.R;
import com.inmobi.samples.utils.DataFetcher;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsHeadlinesFragment extends ListFragment {

    public static final String ARGS_PLACE_NATIVE_ADS = "should_place_native_ads";

    private static final String TAG = NewsHeadlinesFragment.class.getSimpleName();
    private static final int MAX_ADS = 50;

    @NonNull private final Handler mHandler = new Handler();
    private Map<NewsSnippet, WeakReference<InMobiNative>> mNativeAdMap = new HashMap<>();
    private List<NewsSnippet> mItemList = new ArrayList<>();
    private InMobiNative[] mNativeAds = new InMobiNative[MAX_ADS];
    private FeedAdapter mAdapter;

    private static final String FEED_URL = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=30&q=http://rss.nytimes.com/services/xml/rss/nyt/World.xml";
    private static final String FALLBACK_IMAGE_URL = "http://www.darrickbynum.com/wp-content/uploads/2014/07/News729x6581.jpg";
    private static final int[] AD_PLACEMENT_POSITIONS = new int[]{2, 4, 8, 13, 18};
    private static final long YOUR_PLACEMENT_ID = 1442498043574L;

    private OnHeadlineSelectedListener mCallback;

    public interface OnHeadlineSelectedListener {
        void onArticleSelected(int position);
    }

    static final class NewsSnippet {
        String title;
        String imageUrl;
        String content;
        String landingUrl;
    }

    @Override
    public void onResume() {
        super.onResume();
        for (InMobiNative nativeAd : mNativeAds) {
            if (nativeAd != null) {
                nativeAd.resume();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mAdapter = new FeedAdapter(getActivity(), mItemList);
        setListAdapter(mAdapter);
        getHeadlines();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    private void getHeadlines() {
        new DataFetcher().getFeed(FEED_URL, new DataFetcher.OnFetchCompletedListener() {
            @Override
            public void onFetchCompleted(@Nullable final String data, @Nullable final String message) {
                if (null == data) {
                    Log.e(TAG, "Fetching headlines failed with error: " + message);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            // finish();
                        }
                    });
                } else {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            loadHeadlines(data);
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, final View view, final int position, final long id) {
                AlertDialog.Builder confirmationDialog = new AlertDialog.Builder(getActivity());
                confirmationDialog.setTitle("Delete Item?");

                confirmationDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        NewsSnippet newsSnippet = mItemList.get(position);
                        mItemList.remove(newsSnippet);
                        WeakReference<InMobiNative> nativeAdRef = mNativeAdMap.remove(newsSnippet);
                        if (nativeAdRef != null) {
                            InMobiNative nativeAd = nativeAdRef.get();
                            if (nativeAd != null) {
                                InMobiNative.unbind(view);
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                });
                confirmationDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                confirmationDialog.show();

                return true;
            }
        });
    }

    private void loadHeadlines(String data) {
        try {
            JSONArray feed = new JSONObject(data).
                    getJSONObject("responseData").
                    getJSONObject("feed").
                    getJSONArray("entries");
            for (int i = 0; i < feed.length(); i++) {
                JSONObject item = feed.getJSONObject(i);
                Log.v(TAG, item.toString());
                NewsSnippet feedEntry = new NewsSnippet();
                try {
                    feedEntry.title = item.getString("title");
                    if (item.isNull("mediaGroups")) {
                        feedEntry.imageUrl = FALLBACK_IMAGE_URL;
                    } else {
                        feedEntry.imageUrl = item.getJSONArray("mediaGroups").getJSONObject(0).getJSONArray("contents").getJSONObject(0).getString("url");
                    }
                    feedEntry.landingUrl = item.getString("link");
                    feedEntry.content = item.getString("contentSnippet");
                    mItemList.add(feedEntry);
                } catch (JSONException e) {
                    Log.e(TAG, e.toString());
                }
            }

            mAdapter.notifyDataSetChanged();
            Bundle args = getArguments();
            boolean shouldPlaceNativeAds = args.getBoolean(ARGS_PLACE_NATIVE_ADS, false);
            if (shouldPlaceNativeAds) {
                placeNativeAds();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void placeNativeAds() {
        for (int i = 0; i < AD_PLACEMENT_POSITIONS.length; i++) {
            final int position = AD_PLACEMENT_POSITIONS[i];
            InMobiNative nativeAd = new InMobiNative(YOUR_PLACEMENT_ID, new InMobiNative.NativeAdListener() {
                @Override
                public void onAdLoadSucceeded(final InMobiNative inMobiNative) {
                    try {
                        JSONObject content = new JSONObject((String) inMobiNative.getAdContent());
                        NewsSnippet item = new NewsSnippet();
                        item.title = content.getString("title");
                        item.landingUrl = content.getString("click_url");
                        item.imageUrl = content.getJSONObject("image_xhdpi").getString("url");
                        mItemList.add(position, item);
                        mNativeAdMap.put(item, new WeakReference<>(inMobiNative));
                        mAdapter.notifyDataSetChanged();
                        Log.d(TAG, "Placed ad unit (" + inMobiNative.hashCode() +
                                ") at position " + position);
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }

                @Override
                public void onAdLoadFailed(InMobiNative inMobiNative, InMobiAdRequestStatus inMobiAdRequestStatus) {
                    Log.e(TAG, "Failed to load ad. " + inMobiAdRequestStatus.getMessage());
                }

                @Override
                public void onAdDismissed(InMobiNative inMobiNative) {

                }

                @Override
                public void onAdDisplayed(InMobiNative inMobiNative) {

                }

                @Override
                public void onUserLeftApplication(InMobiNative inMobiNative) {

                }
            });
            nativeAd.load();
            mNativeAds[i] = nativeAd;
        }
    }

    @Override
    public void onPause() {
        for (InMobiNative nativeAd: mNativeAds) {
            if (nativeAd != null) {
                nativeAd.pause();
            }
        }
        super.onPause();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnSettingsSavedListener");
        }
    }

    @Override
    public void onDetach() {
        mCallback = null;
        mNativeAdMap.clear();
        mItemList.clear();

        super.onDetach();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // if the item at this position is an ad handle this
        NewsSnippet newsSnippet = mItemList.get(position);
        final WeakReference<InMobiNative> nativeAdRef = mNativeAdMap.get(newsSnippet);
        if (nativeAdRef != null && nativeAdRef.get() != null) {
            nativeAdRef.get().reportAdClickAndOpenLandingPage(null);
        }

        mCallback.onArticleSelected(position);
        getListView().setItemChecked(position, true);
    }

    class ViewHolder {
        TextView headline;
        TextView content;
        TextView tag;
        SimpleDraweeView icon;
    }

    public class FeedAdapter extends ArrayAdapter<NewsSnippet> {

        private Context mContext;
        private LayoutInflater mInflater;
        private List<NewsSnippet> mItems;

        public FeedAdapter(Context context, List<NewsSnippet> items) {
            super(context, R.layout.news_headline_view, items);
            mContext = context;
            mInflater = LayoutInflater.from(context);
            mItems = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View rowView = convertView;
            if (null == rowView) {
                rowView = mInflater.inflate(R.layout.news_headline_view, parent, false);
                ViewHolder viewHolder = new ViewHolder();
                viewHolder.headline = (TextView) rowView.findViewById(R.id.caption);
                viewHolder.content = (TextView) rowView.findViewById(R.id.content);
                viewHolder.icon = (SimpleDraweeView) rowView.findViewById(R.id.photo);
                viewHolder.tag = (TextView) rowView.findViewById(R.id.sponsored);
                rowView.setTag(viewHolder);
            }

            final NewsSnippet newsSnippet = mItems.get(position);
            ViewHolder holder = (ViewHolder) rowView.getTag();
            holder.headline.setText(newsSnippet.title);
            holder.content.setText(newsSnippet.content);
            holder.icon.setImageURI(Uri.parse(newsSnippet.imageUrl));

            WeakReference<InMobiNative> nativeAdRef = mNativeAdMap.get(newsSnippet);
            if (null == nativeAdRef) {
                holder.tag.setVisibility(View.GONE);
                InMobiNative.unbind(rowView);
            } else {
                // we have an ad at this position
                InMobiNative nativeAd = nativeAdRef.get();
                if (nativeAd != null) {
                    holder.tag.setVisibility(View.VISIBLE);
                    holder.tag.setText("Sponsored");
                    InMobiNative.bind(rowView, nativeAd);
                }
            }

            return rowView;
        }
    }
}


text:
package org.apache.hadoop.hive.ql.parse;

import java.io.Serializable;
import java.util.List;

import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.hooks.Hook;

/**
 * HiveSemanticAnalyzerHook allows Hive to be extended with custom
 * logic for semantic analysis of QL statements.  This interface
 * and any Hive internals it exposes are currently
 * "limited private and evolving" (unless otherwise stated elsewhere)
 * and intended mainly for use by the Howl project.
 *
 *<p>
 *
 * Note that the lifetime of an instantiated hook object is scoped to
 * the analysis of a single statement; hook instances are never reused.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public interface HiveSemanticAnalyzerHook extends Hook {
  /**
   * Invoked before Hive performs its own semantic analysis on
   * a statement.  The implementation may inspect the statement AST and
   * prevent its execution by throwing a SemanticException.
   * Optionally, it may also augment/rewrite the AST, but must produce
   * a form equivalent to one which could have
   * been returned directly from Hive's own parser.
   *
   * @param context context information for semantic analysis
   *
   * @param ast AST being analyzed and optionally rewritten
   *
   * @return replacement AST (typically the same as the original AST unless the
   * entire tree had to be replaced; must not be null)
   */
  public ASTNode preAnalyze(
    HiveSemanticAnalyzerHookContext context,
    ASTNode ast) throws SemanticException;

  /**
   * Invoked after Hive performs its own semantic analysis on a
   * statement (including optimization).
   * Hive calls postAnalyze on the same hook object
   * as preAnalyze, so the hook can maintain state across the calls.
   *
   * @param context context information for semantic analysis
   * @param rootTasks root tasks produced by semantic analysis;
   * the hook is free to modify this list or its contents
   */
  public void postAnalyze(
    HiveSemanticAnalyzerHookContext context,
    List<Task<? extends Serializable>> rootTasks) throws SemanticException;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.management.SubResource;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** SSL certificates of an application gateway. */
@Fluent
public final class ApplicationGatewaySslCertificateInner extends SubResource {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ApplicationGatewaySslCertificateInner.class);

    /*
     * Properties of SSL certificates of an application gateway.
     */
    @JsonProperty(value = "properties")
    private ApplicationGatewaySslCertificatePropertiesFormat innerProperties;

    /*
     * Name of the SSL certificate that is unique within an Application
     * Gateway.
     */
    @JsonProperty(value = "name")
    private String name;

    /*
     * A unique read-only string that changes whenever the resource is updated.
     */
    @JsonProperty(value = "etag")
    private String etag;

    /*
     * Type of the resource.
     */
    @JsonProperty(value = "type")
    private String type;

    /**
     * Get the innerProperties property: Properties of SSL certificates of an application gateway.
     *
     * @return the innerProperties value.
     */
    private ApplicationGatewaySslCertificatePropertiesFormat innerProperties() {
        return this.innerProperties;
    }

    /**
     * Get the name property: Name of the SSL certificate that is unique within an Application Gateway.
     *
     * @return the name value.
     */
    public String name() {
        return this.name;
    }

    /**
     * Set the name property: Name of the SSL certificate that is unique within an Application Gateway.
     *
     * @param name the name value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the etag property: A unique read-only string that changes whenever the resource is updated.
     *
     * @return the etag value.
     */
    public String etag() {
        return this.etag;
    }

    /**
     * Set the etag property: A unique read-only string that changes whenever the resource is updated.
     *
     * @param etag the etag value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withEtag(String etag) {
        this.etag = etag;
        return this;
    }

    /**
     * Get the type property: Type of the resource.
     *
     * @return the type value.
     */
    public String type() {
        return this.type;
    }

    /**
     * Set the type property: Type of the resource.
     *
     * @param type the type value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withType(String type) {
        this.type = type;
        return this;
    }

    /** {@inheritDoc} */
    @Override
    public ApplicationGatewaySslCertificateInner withId(String id) {
        super.withId(id);
        return this;
    }

    /**
     * Get the data property: Base-64 encoded pfx certificate. Only applicable in PUT Request.
     *
     * @return the data value.
     */
    public String data() {
        return this.innerProperties() == null ? null : this.innerProperties().data();
    }

    /**
     * Set the data property: Base-64 encoded pfx certificate. Only applicable in PUT Request.
     *
     * @param data the data value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withData(String data) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ApplicationGatewaySslCertificatePropertiesFormat();
        }
        this.innerProperties().withData(data);
        return this;
    }

    /**
     * Get the password property: Password for the pfx file specified in data. Only applicable in PUT request.
     *
     * @return the password value.
     */
    public String password() {
        return this.innerProperties() == null ? null : this.innerProperties().password();
    }

    /**
     * Set the password property: Password for the pfx file specified in data. Only applicable in PUT request.
     *
     * @param password the password value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withPassword(String password) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ApplicationGatewaySslCertificatePropertiesFormat();
        }
        this.innerProperties().withPassword(password);
        return this;
    }

    /**
     * Get the publicCertData property: Base-64 encoded Public cert data corresponding to pfx specified in data. Only
     * applicable in GET request.
     *
     * @return the publicCertData value.
     */
    public String publicCertData() {
        return this.innerProperties() == null ? null : this.innerProperties().publicCertData();
    }

    /**
     * Set the publicCertData property: Base-64 encoded Public cert data corresponding to pfx specified in data. Only
     * applicable in GET request.
     *
     * @param publicCertData the publicCertData value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withPublicCertData(String publicCertData) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ApplicationGatewaySslCertificatePropertiesFormat();
        }
        this.innerProperties().withPublicCertData(publicCertData);
        return this;
    }

    /**
     * Get the keyVaultSecretId property: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate'
     * object stored in KeyVault.
     *
     * @return the keyVaultSecretId value.
     */
    public String keyVaultSecretId() {
        return this.innerProperties() == null ? null : this.innerProperties().keyVaultSecretId();
    }

    /**
     * Set the keyVaultSecretId property: Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate'
     * object stored in KeyVault.
     *
     * @param keyVaultSecretId the keyVaultSecretId value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withKeyVaultSecretId(String keyVaultSecretId) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ApplicationGatewaySslCertificatePropertiesFormat();
        }
        this.innerProperties().withKeyVaultSecretId(keyVaultSecretId);
        return this;
    }

    /**
     * Get the provisioningState property: Provisioning state of the SSL certificate resource Possible values are:
     * 'Updating', 'Deleting', and 'Failed'.
     *
     * @return the provisioningState value.
     */
    public String provisioningState() {
        return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
    }

    /**
     * Set the provisioningState property: Provisioning state of the SSL certificate resource Possible values are:
     * 'Updating', 'Deleting', and 'Failed'.
     *
     * @param provisioningState the provisioningState value to set.
     * @return the ApplicationGatewaySslCertificateInner object itself.
     */
    public ApplicationGatewaySslCertificateInner withProvisioningState(String provisioningState) {
        if (this.innerProperties() == null) {
            this.innerProperties = new ApplicationGatewaySslCertificatePropertiesFormat();
        }
        this.innerProperties().withProvisioningState(provisioningState);
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}


text:
package com.adhwari.teenpattiscorer;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void startNewGame(View view) {
        Intent intent = new Intent(this, NewGameActivity.class);
        startActivity(intent);
    }

    public void onClickShowConfig(View view){
        Intent configIntent = new Intent(this, setupConfiguration.class);
        startActivity(configIntent);
    }

    public void onClickExit(View view){
        clearAllData();
        finish();
    }

    private void clearAllData() {
        PlayerInfoList.clearPlayerData();

    }
}


text:
package io.rainfall.ehcache2;

import net.sf.ehcache.Ehcache;

/**
 * @author Aurelien Broszniowski
 */

public class CacheDefinition {

  private String name;
  private Ehcache cache;

  public CacheDefinition(final String name, final Ehcache cache) {
    this.name = name;
    this.cache = cache;
  }

  public static CacheDefinition cache(String name, Ehcache cache) {
    return new CacheDefinition(name, cache);
  }

  public String getName() {
    return name;
  }

  public Ehcache getCache() {
    return cache;
  }
}


text:
/**
 * Adds a new validator for Boolean fields, based on Form.validators.required
 */

module.exports = function (options) {
  var err = {
    type: 'required',
    message: _t('components.backbone-forms.required-boolean-error')
  };

  return function required (value) {
    if (value === undefined) return err;
  };
};


text:
//
//  indigo_struct.h
//  indigo
//
//  Created by zhang on 11/8/15.
//  Copyright © 2015 yourcompany. All rights reserved.
//

#import <Foundation/Foundation.h>

#include "lua.h"

//NOTE: keep struct type definition same as `IndigoObjectUserdata`!!!
typedef struct{
    void *cptr;//pointer to the wrapped struct
    char *ctype;
    bool isPtr;//Is this object a pointer to an object, such as `NSError **`
    bool isStruct;
    bool isInSuperMethodContext;
    bool isInClassMethodContext;
}IndigoStructUserdata;

int luaopen_indigo_struct(lua_State *L);

IndigoStructUserdata *indigo_check_struct_userdata(lua_State *s, int stackIndex);

/*
    Usually ptr is of type `Struct Foo *`(such as CGRect *).
    When isPointer is true, ptr then is of type 'Struct Foo **'
 */
void push_struct(lua_State *s, void *ptr, const char *structTypeDescription, bool isPointer);


text:
using Content.Server.Nutrition.EntitySystems;

namespace Content.Server.Nutrition.Components
{
    /// <summary>
    ///     A disposable, single-use smokable.
    /// </summary>
    [RegisterComponent, Access(typeof(SmokingSystem))]
    public sealed class CigarComponent : Component
    {
    }
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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.

=cut

package Bio::EnsEMBL::Production::Pipeline::Production::SnpCount;

use strict;
use warnings;

use base qw/Bio::EnsEMBL::Production::Pipeline::Production::StatsGenerator/;

sub run {
  my ($self) = @_;
  my $species    = $self->param('species');

  $self->dbc()->disconnect_if_idle() if defined $self->dbc();

  my $dba = Bio::EnsEMBL::Registry->get_DBAdaptor($species, 'core');
  my $aa  = Bio::EnsEMBL::Registry->get_adaptor($species, 'core', 'attribute');

  my %attrib_codes = $self->get_attrib_codes();
  $self->delete_old_attrib($dba, %attrib_codes);
  $self->delete_old_stats($dba, %attrib_codes);

  my $count;
  my $alt_count;

  my %stats_hash;
  my %stats_attrib;

  my @all_sorted_slices =
   sort( { $a->coord_system()->rank() <=> $b->coord_system()->rank()
           || $b->seq_region_length() <=> $a->seq_region_length() } @{$self->get_all_slices($species)}) ;
  while (my $slice = shift @all_sorted_slices) {
    next unless $slice->is_reference; # no alt attribs ATMO

    foreach my $ref_code (keys %attrib_codes) {
      $count = $self->get_feature_count($slice, $ref_code, $attrib_codes{$ref_code});
      $self->store_attrib($slice, $count, $ref_code) if $count > 0;
      $stats_hash{$ref_code} += $count;
    }
  }

  $self->store_statistics($species, \%stats_hash, \%stats_attrib);

  # disconnecting from the registry
  $dba->dbc->disconnect_if_idle();
  my $prod_dba    = $self->get_production_DBAdaptor();
  $prod_dba->dbc()->disconnect_if_idle();
}

sub get_feature_count {
  my ($self, $slice, $key) = @_;
  my $variation_adaptor = Bio::EnsEMBL::Registry->get_DBAdaptor($self->param('species'), 'variation');
  my $helper = $variation_adaptor->dbc()->sql_helper();
  my $sql = q{
     SELECT count(*) FROM variation_feature
     WHERE seq_region_id = ? };
  my @params = [$slice->get_seq_region_id];
  my $count = $helper->execute_single_result(-SQL => $sql, -PARAMS => @params);
  return $count;
}

sub get_total {
  my ($self) = @_;
  my $variation_adaptor = Bio::EnsEMBL::Registry->get_DBAdaptor($self->param('species'), 'variation');
  my $helper = $variation_adaptor->dbc()->sql_helper();
  my $sql = q{
     SELECT count(*) FROM variation_feature };
  my $count = $helper->execute_single_result(-SQL => $sql);
  return $count;
}

sub get_slices {
  my ($self, $species) = @_;
  my @slices;
  my $dba = Bio::EnsEMBL::Registry->get_DBAdaptor($species, 'variation');
  my $sa = Bio::EnsEMBL::Registry->get_adaptor($species, 'core', 'slice');
  my $helper = $dba->dbc()->sql_helper();
  my $sql = q{
    SELECT DISTINCT seq_region_id FROM variation_feature };
  my @ids = @{ $helper->execute_simple(-SQL => $sql) };
  foreach my $id(@ids) {
    push @slices, $sa->fetch_by_seq_region_id($id);
  }
  return \@slices;
}

sub get_attrib_codes {
  my ($self) = @_;
  my $prod_dba   = $self->get_production_DBAdaptor();
  my $prod_helper     = $prod_dba->dbc()->sql_helper();
  my $sql = q{
    SELECT code, name
    FROM attrib_type
    WHERE code = 'SNPCount' };
  my %attrib_codes = %{ $prod_helper->execute_into_hash(-SQL => $sql) };
  return %attrib_codes;
}

1;