text:
package goryachev.memsafecrypto.bc;

/**
 * Ciphers producing a key stream which can be reset to particular points in the stream implement this.
 */
public interface SkippingCipher
{
	/**
	 * Skip numberOfBytes forwards, or backwards.
	 *
	 * @param numberOfBytes the number of bytes to skip (positive forward, negative backwards).
	 * @return the number of bytes actually skipped.
	 * @throws java.lang.IllegalArgumentException if numberOfBytes is an invalid value.
	 */
	long skip(long numberOfBytes);

	/**
	 * Reset the cipher and then skip forward to a given position.
	 *
	 * @param position the number of bytes in to set the cipher state to.
	 * @return the byte position moved to.
	 */
	long seekTo(long position);

	/**
	 * Return the current "position" of the cipher
	 *
	 * @return the current byte position.
	 */
	long getPosition();
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import Link from 'next/link';

// Utils
import { substitution } from 'utils/utils';

class EditAction extends React.Component {
  getParsedParams() {
    const { data, action } = this.props;

    return JSON.parse(substitution(JSON.stringify(action.params), [{ key: 'id', value: data.id }]));
  }

  render() {
    const { action } = this.props;

    const {
      tab,
      subtab,
      id,
    } = this.getParsedParams(action.params);

    return (
      <Link href={`/admin/faqs/${tab}/${id}/${subtab}`}>
        Edit
      </Link>
    );
  }
}

EditAction.propTypes = {
  data: PropTypes.object,
  action: PropTypes.object,
};

export default EditAction;

redpajama_set_name: RedPajamaGithub


text:
class AddVoteCounterCacheForQuestions < ActiveRecord::Migration
  def self.up
    add_column :questions , :votes_average , :integer , :default => 0
  end

  def self.down
    remove_column :questions , :votes_average
  end
end


text:
require File.expand_path('../../../../conf/rorc', __FILE__)
require 'ro_helper/misc'
module ::RoCell
  module Cmd
    class KlsOpt
      include ::RoHelper::Misc

      def initialize(name, *args, &blk)
        @name = name.to_s
        set_opts(*args, &blk)
      end

      attr_accessor :name, :default, :alias_name, :val

      def val
        @val ||= default
      end

    end
  end
end


text:
<?php

namespace Kelunik\Acme;

use Amp\Dns\DnsException;
use Amp\Dns\NoRecordException;
use Amp\Dns\Record;
use Amp\Dns\Resolver;
use Amp\Failure;
use Amp\PHPUnit\AsyncTestCase;
use Amp\Success;

class Dns01VerificationTest extends AsyncTestCase
{
    private $resolver;

    /**
     * @var Verifiers\Dns01
     */
    private $verifier;

    public function setUp(): void
    {
        parent::setUp();

        $this->resolver = $this->getMockBuilder(Resolver::class)->getMock();
        $this->verifier = new Verifiers\Dns01($this->resolver);
    }

    /**
     * @test
     */
    public function failsOnDnsNotFound(): \Generator
    {
        $this->expectException(AcmeException::class);
        $this->expectExceptionMessage('Verification failed, no TXT record found for \'_acme-challenge.example.com\'.');

        $this->resolver->method("query")->willReturn(new Failure(new NoRecordException));
        yield $this->verifier->verifyChallenge("example.com", "foobar");
    }

    /**
     * @test
     */
    public function failsOnGeneralDnsIssue(): \Generator
    {
        $this->expectException(AcmeException::class);
        $this->expectExceptionMessage('Verification failed, couldn\'t query TXT record of \'_acme-challenge.example.com\'');

        $this->resolver->method("query")->willReturn(new Failure(new DnsException));
        yield $this->verifier->verifyChallenge("example.com", "foobar");
    }

    /**
     * @test
     */
    public function failsOnWrongPayload(): \Generator
    {
        $this->expectException(AcmeException::class);
        $this->expectExceptionMessage("Verification failed, please check DNS record for '_acme-challenge.example.com'.");

        $this->resolver->method("query")->willReturn(new Success([new Record("xyz", Record::TXT, 300)]));
        yield $this->verifier->verifyChallenge("example.com", "foobar");
    }

    /**
     * @test
     */
    public function succeedsOnRightPayload(): \Generator
    {
        $this->expectNotToPerformAssertions();

        $this->resolver->method("query")->willReturn(new Success([new Record("foobar", Record::TXT, 300)]));
        yield $this->verifier->verifyChallenge("example.com", "foobar");
    }

    /**
     * @test
     */
    public function failsWithDomainNotString(): \Generator
    {
        $this->expectException(\TypeError::class);

        yield $this->verifier->verifyChallenge(null, "");
    }

    /**
     * @test
     */
    public function failsWithPayloadNotString(): \Generator
    {
        $this->expectException(\TypeError::class);

        yield $this->verifier->verifyChallenge("example.com", null);
    }
}


text:
/*
 * Export Configuration
 */

quarry.config(['$stateProvider', function($stateProvider) {

    // make sure we have a user before allowing access to the rest of the app
    if (!window.user) {
        return
    }

    // Set up them states
    $stateProvider

        //
        // Export States
        //

        .state('export', {
            url: '/export',
            templateUrl: '/static/app/export/partials/base.html',
        })

        //
        // Wizard States
        //

        .state('export.saved', {
            url: '/saved',
            templateUrl: '/static/app/export/partials/saved.html',
            controller: 'ExportSavedController'
        })
        .state('export.wizard', {
            url: '/wizard',
            templateUrl: '/static/app/export/partials/wizard.html',
            controller: 'ExportWizardController'
        })
        .state('export.wizard-database', {
            url: '/wizard-database',
            templateUrl: '/static/app/export/partials/database.html',
            controller: 'ExportWizardDatabaseController'
        })
        .state('export.wizard-mysql', {
            url: '/wizard-mysql',
            templateUrl: '/static/app/export/partials/mysql/export.html',
            controller: 'ExportWizardMySQLController'
        })
        .state('export.history', {
            url: '/history',
            templateUrl: '/static/app/export/partials/history.html',
            controller: 'ExportHistoryController'
        })

}])

/*
 * Import Controllers
 */

quarry.controller('ExportWizardController', ["$scope", function($scope) {
    // nothing to see here
}])

quarry.controller('ExportWizardDatabaseController', ["$scope", function($scope) {
    // nothing to see here
}])

quarry.controller('ExportWizardMySQLController', ["$scope", "Jaunt", "RedShirt", "Notifications", function($scope, Jaunt, RedShirt, Notifications) {

    $scope.step = "cluster"

    /*
     * Errors
     */

    $scope.dismissErrors = function() {
        delete $scope.errors
    }

    /*
     * Clusters
     */

    $scope.selectedCluster = function(cluster) {
        $scope.cluster = cluster
    }

    $scope.chooseCluster = function() {
        Jaunt.setCluster($scope.cluster)
        fetchDatasets()
    }

    /*
     * Choose Dataset Step
     */

    var fetchDatasets = function() {

        $scope.status = "Getting list of available datasets..."
        Jaunt.datasets()
            .success(function(res) {
                delete $scope.status
                $scope.step = "datasets"
                $scope.datasets = res.datasets
            })
            .error(function(res) {
                $scope.status = "Failed to load datasets. Please retry..."
            })

        $scope.chooseDataset = function(dataset) {

            delete $scope.errors

            $scope.dataset = dataset
            $scope.step = "connect"

        }

    }

    /*
     * Connect Step
     */

    $scope.connectDatabase = function(address, username, password) {

        delete $scope.errors

        $scope.address = address
        $scope.username = username
        $scope.password = password

        $scope.status = "Testing connection to database..."
        Jaunt.inspect('mysql', {
            host: address,
            dbuser: username,
            password: password
        })
            .success(function(res) {
                $scope.step = "exportOptions"
            })
            .error(function(res) {
                $scope.errors = res.errors
            })
            .finally(function() {
                delete $scope.status
            })

    }

    /*
     * Import Options Step
     */

    $scope.beginExport = function(database, table, save) {

        delete $scope.errors

        $scope.database = database
        $scope.table = table

        var errors = []
        if (!database) {
            errors.push("You must enter a MySQL database name.")
        }
        if (!table) {
            errors.push("You must enter a MySQL table name.")
        }

        if (errors.length != 0) {
            $scope.errors = errors
            return
        }

        var options = {
            host: $scope.address,
            dbuser: $scope.username,
            password: $scope.password,
            dataset: $scope.dataset,
            database: $scope.database,
            table: $scope.table,
        }

        if (save) {

            $scope.status = "Saving job..."

            Jaunt.saveExport('mysql', options)
                .success(function() {
                    Notifications.local({
                        message: 'Export Job Saved'
                    })
                })
                .finally(function() {
                    delete $scope.status
                })

        } else {

            $scope.status = "Exporting data from '" + $scope.dataset +
                            "into " + database + "." + table + "..."

            Jaunt.export(
                'mysql',
                options,
                function(currentProgress) {
                    if (currentProgress.running) {
                        if (Object.keys(currentProgress.progress).length && currentProgress.progress.currentStage) {
                                var progress = currentProgress.progress
                                currentStage = progress.currentStage
                                $scope.status = '' + currentStage.completeTasks + " of " + currentStage.totalTasks + " tasks complete on stage " +
                                                (progress.completeStages+1) + " of " + progress.totalStages + " total stages..."
                                $scope.stageProgress = progress.stageProgress * 97 + 3
                                $scope.taskProgress = currentStage.taskProgress * 97 + 3
                        } else {
                            $scope.status = "Running export..."
                        }
                    } else {
                        $scope.status = "Export finished..."
                    }
                },
                function(res) {
                    delete $scope.status
                    $scope.step = "success"
                },
                function(err) {
                    delete $scope.status
                    $scope.error = err.message
                }
            )

        }

    }

}])

quarry.controller("ExportSavedController", ["$scope", "Jaunt", function($scope, Jaunt) {

    $scope.loadingExports = true

    Jaunt.getSavedExports()
        .success(function(res) {
            $scope.datajobs = res.datajobs
        })
        .finally(function() {
            $scope.loadingExports = false
        })

}])

quarry.controller("ExportHistoryController", ["$scope", "$state", function($scope, $state) {

    $scope.actions = {
        "job_complete": {
            "name": "View Results",
            "action": function(history) {
                $state.go(
                    'spark.results',
                    {
                        jobName: history.data.jobName,
                        handle: history.job_handle

                    }
                )
            }
        }
    }

}])


text:
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Between;
using ::testing::DoAll;
using ::testing::NotNull;
using ::testing::Return;
using base::win::ScopedCOMInitializer;

namespace media {

static const size_t kMaxDeltaSamples = 1000;
static const char kDeltaTimeMsFileName[] = "unified_delta_times_ms.txt";

// Verify that the delay estimate in the OnMoreIOData() callback is larger
// than an expected minumum value.
MATCHER_P(DelayGreaterThan, value, "") {
  return (arg.hardware_delay_bytes > value.hardware_delay_bytes);
}

// Used to terminate a loop from a different thread than the loop belongs to.
// |loop| should be a MessageLoopProxy.
ACTION_P(QuitLoop, loop) {
  loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
}

class MockUnifiedSourceCallback
    : public AudioOutputStream::AudioSourceCallback {
 public:
  MOCK_METHOD2(OnMoreData, int(AudioBus* audio_bus,
                               AudioBuffersState buffers_state));
  MOCK_METHOD3(OnMoreIOData, int(AudioBus* source,
                                 AudioBus* dest,
                                 AudioBuffersState buffers_state));
  MOCK_METHOD1(OnError, void(AudioOutputStream* stream));
};

// AudioOutputStream::AudioSourceCallback implementation which enables audio
// play-through. It also creates a text file that contains times between two
// successive callbacks. Units are in milliseconds. This file can be used for
// off-line analysis of the callback sequence.
class UnifiedSourceCallback : public AudioOutputStream::AudioSourceCallback {
 public:
  explicit UnifiedSourceCallback()
      : previous_call_time_(base::TimeTicks::Now()),
        text_file_(NULL),
        elements_to_write_(0) {
    delta_times_.reset(new int[kMaxDeltaSamples]);
  }

  virtual ~UnifiedSourceCallback() {
    base::FilePath file_name;
    EXPECT_TRUE(PathService::Get(base::DIR_EXE, &file_name));
    file_name = file_name.AppendASCII(kDeltaTimeMsFileName);

    EXPECT_TRUE(!text_file_);
    text_file_ = base::OpenFile(file_name, "wt");
    DLOG_IF(ERROR, !text_file_) << "Failed to open log file.";
    VLOG(0) << ">> Output file " << file_name.value() << " has been created.";

    // Write the array which contains delta times to a text file.
    size_t elements_written = 0;
    while (elements_written < elements_to_write_) {
      fprintf(text_file_, "%d\n", delta_times_[elements_written]);
      ++elements_written;
    }
    base::CloseFile(text_file_);
  }

  virtual int OnMoreData(AudioBus* dest,
                         AudioBuffersState buffers_state) {
    NOTREACHED();
    return 0;
  };

  virtual int OnMoreIOData(AudioBus* source,
                           AudioBus* dest,
                           AudioBuffersState buffers_state) {
    // Store time between this callback and the previous callback.
    const base::TimeTicks now_time = base::TimeTicks::Now();
    const int diff = (now_time - previous_call_time_).InMilliseconds();
    previous_call_time_ = now_time;
    if (elements_to_write_ < kMaxDeltaSamples) {
      delta_times_[elements_to_write_] = diff;
      ++elements_to_write_;
    }

    // Play out the recorded audio samples in loop back. Perform channel mixing
    // if required using a channel mixer which is created only if needed.
    if (source->channels() == dest->channels()) {
      source->CopyTo(dest);
    } else {
      // A channel mixer is required for converting audio between two different
      // channel layouts.
      if (!channel_mixer_) {
        // Guessing the channel layout will work OK for this unit test.
        // Main thing is that the number of channels is correct.
        ChannelLayout input_layout = GuessChannelLayout(source->channels());
        ChannelLayout output_layout = GuessChannelLayout(dest->channels());
        channel_mixer_.reset(new ChannelMixer(input_layout, output_layout));
        DVLOG(1) << "Remixing channel layout from " << input_layout
                 << " to " << output_layout << "; from "
                 << source->channels() << " channels to "
                 << dest->channels() << " channels.";
      }
      if (channel_mixer_)
        channel_mixer_->Transform(source, dest);
    }
    return source->frames();
  };

  virtual void OnError(AudioOutputStream* stream) {
    NOTREACHED();
  }

 private:
  base::TimeTicks previous_call_time_;
  scoped_ptr<int[]> delta_times_;
  FILE* text_file_;
  size_t elements_to_write_;
  scoped_ptr<ChannelMixer> channel_mixer_;
};

// Convenience method which ensures that we fulfill all required conditions
// to run unified audio tests on Windows.
static bool CanRunUnifiedAudioTests(AudioManager* audio_man) {
  if (!CoreAudioUtil::IsSupported()) {
    LOG(WARNING) << "This tests requires Windows Vista or higher.";
    return false;
  }

  if (!audio_man->HasAudioOutputDevices()) {
    LOG(WARNING) << "No output devices detected.";
    return false;
  }

  if (!audio_man->HasAudioInputDevices()) {
    LOG(WARNING) << "No input devices detected.";
    return false;
  }

  return true;
}

// Convenience class which simplifies creation of a unified AudioOutputStream
// object.
class AudioUnifiedStreamWrapper {
 public:
  explicit AudioUnifiedStreamWrapper(AudioManager* audio_manager)
      : com_init_(ScopedCOMInitializer::kMTA),
        audio_man_(audio_manager) {
    // We open up both both sides (input and output) using the preferred
    // set of audio parameters. These parameters corresponds to the mix format
    // that the audio engine uses internally for processing of shared-mode
    // output streams.
    AudioParameters out_params;
    EXPECT_TRUE(SUCCEEDED(CoreAudioUtil::GetPreferredAudioParameters(
        eRender, eConsole, &out_params)));

    // WebAudio is the only real user of unified audio and it always asks
    // for stereo.
    // TODO(henrika): extend support to other input channel layouts as well.
    const int kInputChannels = 2;

    params_.Reset(out_params.format(),
                  out_params.channel_layout(),
                  out_params.channels(),
                  kInputChannels,
                  out_params.sample_rate(),
                  out_params.bits_per_sample(),
                  out_params.frames_per_buffer());
  }

  ~AudioUnifiedStreamWrapper() {}

  // Creates an AudioOutputStream object using default parameters.
  WASAPIUnifiedStream* Create() {
    return static_cast<WASAPIUnifiedStream*>(CreateOutputStream());
  }

  // Creates an AudioOutputStream object using default parameters but a
  // specified input device.
  WASAPIUnifiedStream* Create(const std::string device_id) {
    return static_cast<WASAPIUnifiedStream*>(CreateOutputStream(device_id));
  }

  AudioParameters::Format format() const { return params_.format(); }
  int channels() const { return params_.channels(); }
  int bits_per_sample() const { return params_.bits_per_sample(); }
  int sample_rate() const { return params_.sample_rate(); }
  int frames_per_buffer() const { return params_.frames_per_buffer(); }
  int bytes_per_buffer() const { return params_.GetBytesPerBuffer(); }
  int input_channels() const { return params_.input_channels(); }

 private:
  AudioOutputStream* CreateOutputStream() {
    // Get the unique device ID of the default capture device instead of using
    // AudioManagerBase::kDefaultDeviceId since it provides slightly better
    // test coverage and will utilize the same code path as if a non default
    // input device was used.
    ScopedComPtr<IMMDevice> audio_device =
      CoreAudioUtil::CreateDefaultDevice(eCapture, eConsole);
    AudioDeviceName name;
    EXPECT_TRUE(SUCCEEDED(CoreAudioUtil::GetDeviceName(audio_device, &name)));
    const std::string& input_device_id = name.unique_id;
    EXPECT_TRUE(CoreAudioUtil::DeviceIsDefault(eCapture, eConsole,
        input_device_id));

    // Create the unified audio I/O stream using the default input device.
    AudioOutputStream* aos = audio_man_->MakeAudioOutputStream(params_,
        "", input_device_id);
    EXPECT_TRUE(aos);
    return aos;
  }

  AudioOutputStream* CreateOutputStream(const std::string& input_device_id) {
    // Create the unified audio I/O stream using the specified input device.
    AudioOutputStream* aos = audio_man_->MakeAudioOutputStream(params_,
        "", input_device_id);
    EXPECT_TRUE(aos);
    return aos;
  }

  ScopedCOMInitializer com_init_;
  AudioManager* audio_man_;
  AudioParameters params_;
};

// Convenience method which creates a default WASAPIUnifiedStream object.
static WASAPIUnifiedStream* CreateDefaultUnifiedStream(
    AudioManager* audio_manager) {
  AudioUnifiedStreamWrapper aosw(audio_manager);
  return aosw.Create();
}

// Convenience method which creates a default WASAPIUnifiedStream object but
// with a specified audio input device.
static WASAPIUnifiedStream* CreateDefaultUnifiedStream(
    AudioManager* audio_manager, const std::string& device_id) {
  AudioUnifiedStreamWrapper aosw(audio_manager);
  return aosw.Create(device_id);
}

// Test Open(), Close() calling sequence.
TEST(WASAPIUnifiedStreamTest, OpenAndClose) {
  scoped_ptr<AudioManager> audio_manager(AudioManager::CreateForTesting());
  if (!CanRunUnifiedAudioTests(audio_manager.get()))
    return;

  WASAPIUnifiedStream* wus = CreateDefaultUnifiedStream(audio_manager.get());
  EXPECT_TRUE(wus->Open());
  wus->Close();
}

// Test Open(), Close() calling sequence for all available capture devices.
TEST(WASAPIUnifiedStreamTest, OpenAndCloseForAllInputDevices) {
  scoped_ptr<AudioManager> audio_manager(AudioManager::CreateForTesting());
  if (!CanRunUnifiedAudioTests(audio_manager.get()))
    return;

  AudioDeviceNames device_names;
  audio_manager->GetAudioInputDeviceNames(&device_names);
  for (AudioDeviceNames::iterator i = device_names.begin();
       i != device_names.end(); ++i) {
    WASAPIUnifiedStream* wus = CreateDefaultUnifiedStream(
        audio_manager.get(), i->unique_id);
    EXPECT_TRUE(wus->Open());
    wus->Close();
  }
}

// Test Open(), Start(), Close() calling sequence.
TEST(WASAPIUnifiedStreamTest, OpenStartAndClose) {
  scoped_ptr<AudioManager> audio_manager(AudioManager::CreateForTesting());
  if (!CanRunUnifiedAudioTests(audio_manager.get()))
    return;

  MockUnifiedSourceCallback source;
  AudioUnifiedStreamWrapper ausw(audio_manager.get());
  WASAPIUnifiedStream* wus = ausw.Create();

  EXPECT_TRUE(wus->Open());
  EXPECT_CALL(source, OnError(wus))
      .Times(0);
  EXPECT_CALL(source, OnMoreIOData(NotNull(), NotNull(), _))
      .Times(Between(0, 1))
      .WillOnce(Return(ausw.frames_per_buffer()));
  wus->Start(&source);
  wus->Close();
}

// Verify that IO callbacks starts as they should.
TEST(WASAPIUnifiedStreamTest, StartLoopbackAudio) {
  scoped_ptr<AudioManager> audio_manager(AudioManager::CreateForTesting());
  if (!CanRunUnifiedAudioTests(audio_manager.get()))
    return;

  base::MessageLoopForUI loop;
  MockUnifiedSourceCallback source;
  AudioUnifiedStreamWrapper ausw(audio_manager.get());
  WASAPIUnifiedStream* wus = ausw.Create();

  // Set up expected minimum delay estimation where we use a minium delay
  // which is equal to the sum of render and capture sizes. We can never
  // reach a delay lower than this value.
  AudioBuffersState min_total_audio_delay(0, 2 * ausw.bytes_per_buffer());

  EXPECT_TRUE(wus->Open());
  EXPECT_CALL(source, OnError(wus))
      .Times(0);
  EXPECT_CALL(source, OnMoreIOData(
      NotNull(), NotNull(), DelayGreaterThan(min_total_audio_delay)))
      .Times(AtLeast(2))
      .WillOnce(Return(ausw.frames_per_buffer()))
      .WillOnce(DoAll(
          QuitLoop(loop.message_loop_proxy()),
          Return(ausw.frames_per_buffer())));
  wus->Start(&source);
  loop.PostDelayedTask(FROM_HERE, base::MessageLoop::QuitClosure(),
                       TestTimeouts::action_timeout());
  loop.Run();
  wus->Stop();
  wus->Close();
}

// Perform a real-time test in loopback where the recorded audio is echoed
// back to the speaker. This test allows the user to verify that the audio
// sounds OK. A text file with name |kDeltaTimeMsFileName| is also generated.
TEST(WASAPIUnifiedStreamTest, DISABLED_RealTimePlayThrough) {
  scoped_ptr<AudioManager> audio_manager(AudioManager::CreateForTesting());
  if (!CanRunUnifiedAudioTests(audio_manager.get()))
    return;

  base::MessageLoopForUI loop;
  UnifiedSourceCallback source;
  WASAPIUnifiedStream* wus = CreateDefaultUnifiedStream(audio_manager.get());

  EXPECT_TRUE(wus->Open());
  wus->Start(&source);
  loop.PostDelayedTask(FROM_HERE, base::MessageLoop::QuitClosure(),
                       base::TimeDelta::FromMilliseconds(10000));
  loop.Run();
  wus->Close();
}

}  // namespace media


text:
package com.twitter.finagle.http

import org.jboss.netty.handler.codec.http.HttpResponseStatus

/** Scala aliases for HttpResponseStatus.  Java users should use Netty's HttpResponseStatus. */
object Status {
  val Continue                     = HttpResponseStatus.CONTINUE
  val Processing                   = HttpResponseStatus.PROCESSING
  val Ok                           = HttpResponseStatus.OK
  val Created                      = HttpResponseStatus.CREATED
  val Accepted                     = HttpResponseStatus.ACCEPTED
  val NonAuthoritativeInformation  = HttpResponseStatus.NON_AUTHORITATIVE_INFORMATION
  val NoContent                    = HttpResponseStatus.NO_CONTENT
  val ResetContent                 = HttpResponseStatus.RESET_CONTENT
  val PartialContent               = HttpResponseStatus.PARTIAL_CONTENT
  val MultiStatus                  = HttpResponseStatus.MULTI_STATUS
  val MultipleChoices              = HttpResponseStatus.MULTIPLE_CHOICES
  val MovedPermanently             = HttpResponseStatus.MOVED_PERMANENTLY
  val Found                        = HttpResponseStatus.FOUND
  val SeeOther                     = HttpResponseStatus.SEE_OTHER
  val NotModified                  = HttpResponseStatus.NOT_MODIFIED
  val UseProxy                     = HttpResponseStatus.USE_PROXY
  val TemporaryRedirect            = HttpResponseStatus.TEMPORARY_REDIRECT
  val BadRequest                   = HttpResponseStatus.BAD_REQUEST
  val Unauthorized                 = HttpResponseStatus.UNAUTHORIZED
  val PaymentRequired              = HttpResponseStatus.PAYMENT_REQUIRED
  val Forbidden                    = HttpResponseStatus.FORBIDDEN
  val NotFound                     = HttpResponseStatus.NOT_FOUND
  val MethodNotAllowed             = HttpResponseStatus.METHOD_NOT_ALLOWED
  val NotAcceptable                = HttpResponseStatus.NOT_ACCEPTABLE
  val ProxyAuthenticationRequired  = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED
  val RequestTimeout               = HttpResponseStatus.REQUEST_TIMEOUT
  val Conflict                     = HttpResponseStatus.CONFLICT
  val Gone                         = HttpResponseStatus.GONE
  val LengthRequired               = HttpResponseStatus.LENGTH_REQUIRED
  val PreconditionFailed           = HttpResponseStatus.PRECONDITION_FAILED
  val RequestEntityTooLarge        = HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE
  val RequestUriTooLong            = HttpResponseStatus.REQUEST_URI_TOO_LONG
  val UnsupportedMediaType         = HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE
  val RequestedRangeNotSatisfiable = HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE
  val ExpectationFailed            = HttpResponseStatus.EXPECTATION_FAILED
  val UnprocessableEntity          = HttpResponseStatus.UNPROCESSABLE_ENTITY
  val Locked                       = HttpResponseStatus.LOCKED
  val FailedDependency             = HttpResponseStatus.FAILED_DEPENDENCY
  val UnorderedCollection          = HttpResponseStatus.UNORDERED_COLLECTION
  val UpgradeRequired              = HttpResponseStatus.UPGRADE_REQUIRED
  val InternalServerError          = HttpResponseStatus.INTERNAL_SERVER_ERROR
  val NotImplemented               = HttpResponseStatus.NOT_IMPLEMENTED
  val BadGateway                   = HttpResponseStatus.BAD_GATEWAY
  val ServiceUnavailable           = HttpResponseStatus.SERVICE_UNAVAILABLE
  val GatewayTimeout               = HttpResponseStatus.GATEWAY_TIMEOUT
  val HttpVersionNotSupported      = HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED
  val VariantAlsoNegotiates        = HttpResponseStatus.VARIANT_ALSO_NEGOTIATES
  val InsufficientStorage          = HttpResponseStatus.INSUFFICIENT_STORAGE
  val NotExtended                  = HttpResponseStatus.NOT_EXTENDED
}


text:
const path       = require('path');
const express    = require('express');

const puppeteer = require('puppeteer')

const rootUrl = "http://localhost:3000/";

jest.setTimeout(500000);

const server = new Promise( resolve => {
    let app = require( '../src/server' )({ directory: path.join( __dirname, '..' ) });
    let server;
    server = app.listen( 3000, () => resolve(server) );
}).catch( e => console.log(e) );

const browser = puppeteer.launch({ headless: false });

beforeAll( async () => { await server; await browser }, 10000 );
afterAll( async () => {
    ( await server ).close();
    ( await browser ).close();
} );

test( 'basic', async () => {
    const page = await ( await browser ).newPage();

    await page.goto(  rootUrl + '/integration/widget/basic.html' );

    await page.waitForSelector('iframe');

    let frames = await page.frames();

    await page.waitFor(2000);

    let title = await frames[1].evaluate(
        () => document.querySelector('.title').innerText
    );

    expect(title).toEqual( 'Product set' );

});


text:
import { Recipe, RecipeContainer } from '../class/recipe';
import { Items as i } from '../constants/items';
import { Equipment as e } from '../class/equipment';
import { Categories as c } from '../constants/categories';
import { Units as u } from '../constants/units';
import { Text as text } from '../class/text';

export class MealRecipe extends RecipeContainer {
    constructor() {
        super();
        this.recipeGroup = c.meal;
        this.recipeName = 'Grinding Meat'
        this.variations = [
            Sausage, Chicken
        ]
    }
}

export class Sausage extends Recipe {
    constructor() {
        super();
        this.steps = [
            text.set(['Seasoning for 1 lb of pork']),
            e.bowl().add([
                i.parsley(2, u.tsp),
                //i.italianSeasoning(2, u.tsp),
                i.marjoram(1, u.tsp),
                i.blackPepper(1.5, u.tsp),
                i.wholeFennelSeeds(.5, u.tsp),
                i.paprika(.5, u.tsp),
                i.redPepperFlakes(1, u.tsp),
                // i.salt(2, u.tsp),
                i.salt(.5, u.tsp),
                i.garlicClove(1, u.tsp),
                i.onionGranules(1, u.tsp),
            ]),
            text.set(['Air tight 8 ounces into freezer safe bags'])
        ];
    }
}

export class Chicken extends Recipe {
    constructor() {
        super();
        this.steps = [
            text.set(['Seasoning for Add 1/3 of 14 oz tofu to every 1.5 lb of chicken']),
            text.set(['Seasoning for 1.5 lb of chicken']),
            e.bowl().add([
                i.chilliPowder(3, u.tsp),
                i.onionGranules(2, u.tsp),
                i.paprika(1, u.tsp),
                i.garlicGranules(1, u.tsp),
                i.cumin(1, u.tsp),
                i.blackPepper(10, u.crack),
            ]),
            text.set(['Air tight 8 ounces into freezer safe bags'])
        ];
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';

import './task-filters.css';

const TaskFilters = ({filter}) => (

<NavLink isActive={() => !filter} to="/">All</NavLink>

<NavLink isActive={() => filter === 'kitchen'} to={{pathname: '/', search: '?filter=kitchen'}}>Kitchen</NavLink>

<NavLink isActive={() => filter === 'garage'} to={{pathname: '/', search: '?filter=garage'}}>Garage</NavLink>

<NavLink isActive={() => filter === 'empty'} to={{pathname: '/', search: '?filter=empty'}}>Out of Stock</NavLink>

<NavLink isActive={() => filter === 'basket'} to={{pathname: '/', search: '?filter=basket'}}>Shopping List</NavLink>

);

TaskFilters.propTypes = {
  filter: PropTypes.string
};

export default TaskFilters;


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:orientation="vertical">

    <include layout="@layout/layout_toolbar" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <GridView
            android:id="@+id/id_gridView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:cacheColorHint="@android:color/transparent"
            android:clipChildren="true"
            android:gravity="center"
            android:horizontalSpacing="3dip"
            android:listSelector="@android:color/transparent"
            android:numColumns="3"
            android:stretchMode="columnWidth"
            android:verticalSpacing="3dip" />

        <View
            android:id="@+id/home_view_cover"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#71000000"
            android:visibility="gone" />
    </FrameLayout>

    <RelativeLayout
        android:id="@+id/bottom_layout"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_alignParentBottom="true"
        android:background="#373A3F">

        <TextView
            android:id="@+id/id_choose_dir"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="16dp"
            android:text="@string/text_photos"
            android:textColor="@color/btn_selector_color"
            android:textSize="16sp" />

        <ImageView
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_alignBottom="@id/id_choose_dir"
            android:layout_marginLeft="8dp"
            android:layout_toRightOf="@id/id_choose_dir"
            android:src="@mipmap/ic_dropdown" />

        <TextView
            android:id="@+id/id_total_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="16dp"
            android:text="@string/text_preview"
            android:textColor="@color/btn_selector_color"
            android:textSize="16sp" />

    </RelativeLayout>

</LinearLayout>


text:
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using System.Text;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http.Authentication;

namespace BooksOnline.middleware
{
    public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
    {
        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            try
            {
                var authHeader = Context.Request.Headers["Authorization"][0];
                var token = authHeader.Substring("Basic ".Length).Trim();
                var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
                var credentials = credentialstring.Split(':');
                var validate = Options.ValidateCredentials;
                if (validate != null && validate(credentials[0], credentials[1]))
                {
                    var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
                    var identity = new ClaimsIdentity(claims, "Basic");
                    Context.User = new ClaimsPrincipal(identity);
                    var properties = new AuthenticationProperties();
                    var ticket = new AuthenticationTicket(Context.User, properties, "Basic");
                    return await Task.FromResult(AuthenticateResult.Success(ticket));
                }

                return await Fail();
            }
            catch
            {
                return await Fail();
            }
        }

        private async Task<AuthenticateResult> Fail()
        {
            var realm = Options.Realm;
            Context.Response.StatusCode = 401;
            if (string.IsNullOrWhiteSpace(realm))
            {
                realm = "My Realm";
            }

            Context.Response.Headers.Add("WWW-Authenticate", $"Basic realm=\"{realm}\"");
            return await Task.FromResult(AuthenticateResult.Fail("Authentication credentials are missing or invalid."));
        }
    }
}


text:
"""Given a SEQ(Text, Text) input file to use as a pair RDD (key1,
valu1), where the SEQ value field (value1) is supposed to be a (key2,
value2) dictionary in JSON, extract all dictionary values (value2) for
a specific key (key2).  Return a a new pair RDD of (key1, value2).
Print the count of records extracted."""

import argparse
import json
import sys
from pyspark import SparkContext

def main(argv=None):
    '''this is called if run from command line'''

    parser = argparse.ArgumentParser()
    parser.add_argument('-c','--count', help="Optionally report a count of records extracted.", required=False, action='store_true')
    parser.add_argument('-i','--input', help="Required Seq input file on cluster.", required=True)
    parser.add_argument('-k','--key', help="Required extraction key.", required=True)
    parser.add_argument('-s','--sample', type=int, default=0, help="Optionally print a sample of results.", required=False)
    args = parser.parse_args()

    extractionKey = args.key

    def extractValues(value):
        try:
            d = json.loads(value)
            if extractionKey in d:
                return iter([d[extractionKey]])
            else:
                return iter([])
        except:
            return iter([])

    sc = SparkContext()
    data = sc.sequenceFile(args.input, "org.apache.hadoop.io.Text", "org.apache.hadoop.io.Text")
    extractedValuePairs = data.flatMapValues(extractValues)

    if args.count:
        recordCount = extractedValuePairs.count()
        print "========================================"
        print recordCount
        print "========================================"

    if args.sample > 0:
        sampleSet = extractedValuePairs.take(args.sample)
        print "========================================"
        for record in sampleSet:
            print record
        print "========================================"

# call main() if this is run as standalone
if __name__ == "__main__":
    sys.exit(main())


text:
<法規>
<法規性質>命令</法規性質>
<英文法規名稱>The Rules Governing the Functions and Assignments of the National Immigration Agency, Ministry of the Interior</英文法規名稱>
<中文法規名稱>內政部移民署處務規程</中文法規名稱>
<法規網址>https://law.moj.gov.tw/Eng/LawClass/LawAll.aspx?pcode=D0010055</法規網址>
<最新英文異動日期>20080528</最新英文異動日期>
<廢止註記>
</廢止註記>
<附件 />
<沿革內容><![CDATA[1.Promulgated on August 17, 2006
2.Amended on March 09, 2007
3.Article 4, 18 amended by Decree of Ministry of the Interior Tai-Nei-Yi-Tzu No. 0971036020 on 28, May, 2008 and took effective on the same day]]></沿革內容>
<前言><![CDATA[]]></前言>
<法規內容>
  <條文>
    <條號>Article 1</條號>
    <條文內容><![CDATA[The National Immigration Agency of the Ministry of the Interior (hereinafter referred to as the Agency), in order to divide work among and to assign functions to its internal units, has formulated the following rules.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 2</條號>
    <條文內容><![CDATA[The Director General is in charge of the general affairs of the Agency and directs and supervises the personnel of the Agency; The Deputy Director Generals assist the Director General in handling the affairs of the Agency.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 3</條號>
    <條文內容><![CDATA[The Chief Secretary is in charge of the following affairs:
(1) Examining and approving official papers and making decisions on behalf of the Director General;
(2)Dealing with confidential and important papers;
(3) Coordinating units and delegating responsibility and authority;
(4) Organizing important meetings; and
(5) Dealing with other assignments.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 4</條號>
    <條文內容><![CDATA[The NIA consists of the following divisions, offices, and corps:
(1) Entry & Exit Affairs Division with 5 subordinate sections;
(2) Immigration Affairs Division with 6 subordinate sections;
(3) International Affairs Division with 4 subordinate sections;
(4) Immigration Information Division with 5 subordinate sections;
(5) Secretariat with 6 subordinate sections;
(6) Personnel Office with 3 subordinate sections;
(7) Accounting Office with 3 subordinate sections;
(8) Civil Service Ethics Office with 2 subordinate sections;
(9) First Specialized Operations Corps commanding 13 brigades and 36 squads;
(10) Second Specialized Operations Corps commanding 12 brigades and 39 squads;
(11) Border Affairs Corps commanding 16 brigades and 42 squads.
(12) Service Affairs Corps commanding 25 service centers; and
(13) Detention Affairs Corps commanding 7 detention centers, 9 brigades, and 50 squads.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 5</條號>
    <條文內容><![CDATA[The Entry & Exit Affairs Division is in charge of the following operations:
(1) Formulating entry and exit policies, laws and decrees;
(2) Researching, developing, overseeing, and evaluating administrative plans and important projects;
(3) Formulating and executing plans for the people of the Taiwan Area to enter and exit the Taiwan Area and to enter the Mainland China Area;
(4) Administering visit affairs for the people of the Mainland China Area, residents of Hong Kong and Macau, nationals without household registration in the Taiwan Area, and foreign nationals;
(5) Formulating and executing plans for entry and exit control;
(6) Planning and overseeing the administration of service centers; and
(7) Dealing with other matters related to entry and exit.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 6</條號>
    <條文內容><![CDATA[The Immigration Affairs Division is in charge of the following operations:
(1) Formulating and enforcing immigration policies, laws and decrees;
(2) Formulating plans for the establishment of a fingerprint database and to collect, calculate, and analyze data related to immigration;
(3) Planning, coordinating, and executing consultations for immigrants;
(4) Planning, coordinating, and executing the protection of immigrants' human rights;
(5) Regulating the advertisement over the matchmaking service providers targeting those who seek for marriage with people of the mainland China Area;
(6) Licensing and controlling immigration service agencies and training immigration service agents;
(7) Administering border entry, residency, permanent residency, or household registration affairs of people of the mainland China Area, Hong Kong and Macao residents, nationals without household registration and foreign nationals;
(8) Planning and supervising the detention and repatriation of offenders against entry, exit and immigration laws or regulations; and
(9) Other matters related to immigration affairs.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 7</條號>
    <條文內容><![CDATA[The International Affairs Division is in charge of the following operations:
(1) Promoting cooperation and communication with other countries in entry, exit, and immigration affairs;
(2) Planning and supervising the Agency's oversea office operations;
(3) Formulating laws and regulations governing refugees, and to identify, safeguard, settle, and manage refugees;
(4) Coordinating the handling of cases involving foreign nationals;
(5) Collecting, integrating and checking information concerning entry and exit security and immigration;
(6) Dealing with major, sudden, and emergency cases;, to direct, control, oversee and assist in operations; and to communicate and coordinate with other related departments; and
(7) Other matters related to international affairs.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 8</條號>
    <條文內容><![CDATA[The Immigration Information Division is in charge of the following operations:
(1) Integrating the planning and coordination of information related to entry, exit and immigration affairs;
(2) Ensuring information and communication security in entry, exit and immigration affairs;
(3) Managing and operating the information systems;
(4) Planning, coordinating and executing the transfer and exchanges of related information with other governmental agencies;
(5) Managing and applying the computerized database;
(6) Maintaining and managing equipment related to the computer systems;
(7) Researching, planning, and promoting computer education and training; and
(8) Other matters related to immigration information.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 9</條號>
    <條文內容><![CDATA[The Secretariat is in charge of the following operations:
(1) Preparing penal joint reports and organizing meetings;
(2) Managing public relations and press releases;
(3) Safekeeping official seals and prepare official papers;
(4) Managing files;
(5) Researching, arranging, and compiling laws and decrees and providing legal advice;
(6) Dealing with requests for national compensation;
(7) Managing the receipt and payment of money, property, facility construction and maintenance, procurement and other affairs; and
(8) Other matters related to secretarial affairs.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 10</條號>
    <條文內容><![CDATA[The Personnel Office is in charge of the personnel affairs of the Agency.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 11</條號>
    <條文內容><![CDATA[The Accounting Office is in charge of the annual budget, accounting, and statistics of the Agency.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 12</條號>
    <條文內容><![CDATA[The Civil Service Ethics Office is in charge of the ethical affairs of the Agency.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 13</條號>
    <條文內容><![CDATA[The Service Affairs Corps is in charge of the following affairs:
(1) The entry and exit services provided to nationals with household registration;
(2) The review and approval of entry, exit, visits, residence or residence for naturalization of nationals without household registration;
(3) The review and approval of entry, exit, visits, or residence of people of the mainland China Area and the review of their permanent residence for naturalization;
(4) The review and approval of entry, exit, visits, residence or household registration for residents of Hong Kong and Macao;
(5) The review and approval of visits extensions, residency, permanent residency or re-entry of foreign nationals;
(6) The implementation of immigrant assistance and guidance;
(7) The reporting of violations against laws related to entry, exit and immigration;
(8) The meting out of penalties for holders of overstayed resident or visitor visas;
(9) The administration of immigration service agencies;
(10) The implementation of immigration management and enforcement of regulations on advertisements solicited by service providers of matchmaking marriages between people of the Taiwan Area and the mainland China Area.
(11) Other affairs related to entry, exit and immigration services.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 14</條號>
    <條文內容><![CDATA[The Specialized Operation Corps is in charge of the following affairs:
(1) Planning for and conducting interviews within the State;
(2) Coordinating, communicating and implementing inspection visits of the foreign populations;
(3) Investigating, apprehending, temporarily detaining, referring, forcibly deporting and repatriating offenders of laws related to entry, exit and immigration; and
(4) Other affairs related to specialized operation.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 15</條號>
    <條文內容><![CDATA[The Border Affairs Corps is in charge of the following affairs:
(1) Inspecting, examining and approving required entry and exit documents;
(2) Implementing security control and interviews at the borders;
(3) Issuing certificates, collecting fingerprints and administering entry and exit services at the borders;
(4) Investigating, providing protective transit to, apprehending, temporarily detaining, referring, and administering escorted repatriation of offenders of laws related to entry, exit and immigration at the borders;
(5) Conducting education and training on certificate authentication and inspection of travel documents; and
(6) Other matters related to border affairs.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 16</條號>
    <條文內容><![CDATA[The Detention Affairs Corps is in charge of the detention and forcible deportation of people violating laws related to entry, exit and immigration.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 17</條號>
    <條文內容><![CDATA[The Agency, in order to fulfill its functions, has adopted a decentralized responsibility system that delegates power level by level so that decisions are made according to an itemized list of duties.]]></條文內容>
  </條文>
  <條文>
    <條號>Article 18</條號>
    <條文內容><![CDATA[The Rules shall be effective from the day when the Organic Law of the Agency is enforced.
Amended articles take effect on the day of the publication.]]></條文內容>
  </條文>
</法規內容>
</法規>


text:
module Court.Utils
  ( createPipeHandles
  ) where

import System.IO
import System.Posix.IO

createPipeHandles :: IO (Handle, Handle)
createPipeHandles = do
  (r, w) <- createPipe
  r' <- fdToHandle r
  w' <- fdToHandle w
  return (r', w')


text:
require 'rails_helper'

RSpec.describe UsersController, type: :controller do

  describe "GET #index" do
    it "returns http success" do
      get :index
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET #info" do
    it "returns http success" do
      get :info
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET #new" do
    it "returns http success" do
      get :new
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET #create" do
    it "returns http success" do
      get :create
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET #update" do
    it "returns http success" do
      get :update
      expect(response).to have_http_status(:success)
    end
  end

  describe "GET #delete" do
    it "returns http success" do
      get :delete
      expect(response).to have_http_status(:success)
    end
  end

end


text:
package org.commonjava.indy.pkg.npm.content.group;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.io.IOUtils;
import org.commonjava.indy.IndyWorkflowException;
import org.commonjava.indy.model.core.Group;
import org.commonjava.indy.model.core.StoreKey;
import org.commonjava.indy.model.core.io.IndyObjectMapper;
import org.commonjava.indy.pkg.npm.model.PackageMetadata;
import org.commonjava.indy.pkg.npm.model.io.PackageSerializerModule;
import org.commonjava.maven.galley.model.Transfer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.commonjava.indy.util.LocationUtils.getKey;

@ApplicationScoped
public class PackageMetadataMerger
{

    @Inject
    private Instance<PackageMetadataProvider> metadataProviderInstances;

    @Inject
    private PackageSerializerModule packageSerializerModule;

    @Inject
    private IndyObjectMapper mapper;

    private List<PackageMetadataProvider> metadataProviders;

    public PackageMetadataMerger()
    {
    }

    public PackageMetadataMerger( Iterable<PackageMetadataProvider> providers, IndyObjectMapper mapper )
    {
        metadataProviders = new ArrayList<>();
        providers.forEach( provider -> metadataProviders.add( provider ) );

        this.mapper = mapper;
    }

    @PostConstruct
    public void setupCDI()
    {
        metadataProviders = new ArrayList<>();
        if ( metadataProviderInstances != null )
        {
            metadataProviderInstances.forEach( provider -> metadataProviders.add( provider ) );
        }

        mapper.registerModule( packageSerializerModule );
    }

    public byte[] merge( final Collection<Transfer> sources, final Group group, final String path )
    {
        Logger logger = LoggerFactory.getLogger( getClass() );
        logger.debug( "Generating merged metadata in: {}:{}", group.getKey(), path );

        InputStream stream = null;

        boolean merged = false;

        final PackageMetadata packageMetadata = new PackageMetadata();

        for ( final Transfer src : sources )
        {
            if ( !src.exists() )
            {
                continue;
            }

            try
            {
                stream = src.openInputStream();
                String content = IOUtils.toString( stream );
                logger.debug( "Adding in metadata content from: {}\n\n{}\n\n", src, content );

                PackageMetadata md = mapper.readValue( content, PackageMetadata.class );

                merged = packageMetadata.merge( md, true ) || merged;
            }
            catch ( final IOException e )
            {
                final StoreKey key = getKey( src );
                logger.error( String.format( "Cannot read metadata: %s from artifact-store: %s. Reason: %s",
                                             src.getPath(), key, e.getMessage() ), e );
            }
            finally
            {
                closeQuietly( stream );
            }
        }

        if ( metadataProviders != null )
        {
            for ( PackageMetadataProvider provider : metadataProviders )
            {
                try
                {
                    PackageMetadata toMerge = provider.getMetadata( group.getKey(), path );
                    if ( toMerge != null )
                    {
                        merged = packageMetadata.merge( toMerge, true ) || merged;
                    }
                }
                catch ( IndyWorkflowException e )
                {
                    logger.error( String.format( "Cannot read metadata: %s from metadata provider: %s. Reason: %s",
                                                 path, provider.getClass().getSimpleName(), e.getMessage() ), e );
                }
            }
        }

        if ( merged )
        {

            String output = null;
            try
            {
                output = mapper.writeValueAsString( packageMetadata );
            }
            catch ( JsonProcessingException e )
            {
                logger.error( String.format( "Cannot convert from metadata: %s to String. Reason: %s", packageMetadata,
                                             e.getMessage() ), e );
            }
            return output.getBytes();
        }

        return null;
    }

    public InputStream merge( final Transfer... sources )
    {
        Logger logger = LoggerFactory.getLogger( getClass() );
        logger.debug( "[NPM] Generating merged metadata when publish" );

        InputStream stream = null;

        final PackageMetadata packageMetadata = new PackageMetadata();

        for ( final Transfer src : sources )
        {
            if ( !src.exists() )
            {
                continue;
            }

            try
            {
                stream = src.openInputStream();
                String content = IOUtils.toString( stream );
                logger.debug( "[NPM] Adding in metadata content from: {}\n\n{}\n\n", src, content );

                PackageMetadata md = mapper.readValue( content, PackageMetadata.class );

                packageMetadata.merge( md, false );
            }
            catch ( final IOException e )
            {
                final StoreKey key = getKey( src );
                logger.error( String.format( "[NPM] Cannot read metadata: %s from artifact-store: %s. Reason: %s",
                                             src.getPath(), key, e.getMessage() ), e );
            }
            finally
            {
                closeQuietly( stream );
            }
        }

        String output = null;
        try
        {
            output = mapper.writeValueAsString( packageMetadata );
        }
        catch ( JsonProcessingException e )
        {
            logger.error(
                    String.format( "[NPM] Cannot convert from metadata: %s to String. Reason: %s", packageMetadata,
                                   e.getMessage() ), e );
        }

        if ( output != null )
        {
            return IOUtils.toInputStream( output );
        }

        return null;
    }

}


text:
package com.intellij.codeInsight.navigation;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.TargetElementUtil;
import com.intellij.codeInsight.documentation.DocumentationManager;
import com.intellij.codeInsight.documentation.DocumentationManagerProtocol;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.hint.HintManagerImpl;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction;
import com.intellij.codeInsight.navigation.actions.GotoTypeDeclarationAction;
import com.intellij.ide.util.EditSourceUtil;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.documentation.DocumentationProvider;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.util.ProgressIndicatorBase;
import com.intellij.openapi.progress.util.ProgressIndicatorUtils;
import com.intellij.openapi.progress.util.ReadTask;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.searches.DefinitionsScopedSearch;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.HintListener;
import com.intellij.ui.LightweightHint;
import com.intellij.ui.ScreenUtil;
import com.intellij.usageView.UsageViewShortNameLocation;
import com.intellij.usageView.UsageViewTypeLocation;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EventObject;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

public class CtrlMouseHandler {
  private static final Logger LOG = Logger.getInstance(CtrlMouseHandler.class);

  private final Project myProject;
  private final EditorColorsManager myEditorColorsManager;

  private HighlightersSet myHighlighter;
  @JdkConstants.InputEventMask private int myStoredModifiers = 0;
  private TooltipProvider myTooltipProvider = null;
  private final FileEditorManager myFileEditorManager;
  private final DocumentationManager myDocumentationManager;
  @Nullable private Point myPrevMouseLocation;
  private LightweightHint myHint;

  public enum BrowseMode {None, Declaration, TypeDeclaration, Implementation}

  private final KeyListener myEditorKeyListener = new KeyAdapter() {
    @Override
    public void keyPressed(final KeyEvent e) {
      handleKey(e);
    }

    @Override
    public void keyReleased(final KeyEvent e) {
      handleKey(e);
    }

    private void handleKey(final KeyEvent e) {
      int modifiers = e.getModifiers();
      if (modifiers == myStoredModifiers) {
        return;
      }

      BrowseMode browseMode = getBrowseMode(modifiers);

      if (browseMode == BrowseMode.None) {
        disposeHighlighter();
        cancelPreviousTooltip();
      }
      else {
        TooltipProvider tooltipProvider = myTooltipProvider;
        if (tooltipProvider != null) {
          if (browseMode != tooltipProvider.getBrowseMode()) {
            disposeHighlighter();
          }
          myStoredModifiers = modifiers;
          cancelPreviousTooltip();
          myTooltipProvider = new TooltipProvider(tooltipProvider.myHostEditor, tooltipProvider.myHostPosition);
          myTooltipProvider.execute(browseMode);
        }
      }
    }
  };

  private final FileEditorManagerListener myFileEditorManagerListener = new FileEditorManagerListener() {
    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent e) {
      disposeHighlighter();
      cancelPreviousTooltip();
    }
  };

  private final VisibleAreaListener myVisibleAreaListener = new VisibleAreaListener() {
    @Override
    public void visibleAreaChanged(@NotNull VisibleAreaEvent e) {
      disposeHighlighter();
      cancelPreviousTooltip();
    }
  };

  private final EditorMouseListener myEditorMouseAdapter = new EditorMouseListener() {
    @Override
    public void mouseReleased(@NotNull EditorMouseEvent e) {
      disposeHighlighter();
      cancelPreviousTooltip();
    }
  };

  private final EditorMouseMotionListener myEditorMouseMotionListener = new EditorMouseMotionListener() {
    @Override
    public void mouseMoved(@NotNull final EditorMouseEvent e) {
      if (e.isConsumed() || !myProject.isInitialized() || myProject.isDisposed()) {
        return;
      }
      MouseEvent mouseEvent = e.getMouseEvent();

      Point prevLocation = myPrevMouseLocation;
      myPrevMouseLocation = mouseEvent.getLocationOnScreen();
      if (isMouseOverTooltip(mouseEvent.getLocationOnScreen())
          || ScreenUtil.isMovementTowards(prevLocation, mouseEvent.getLocationOnScreen(), getHintBounds())) {
        return;
      }
      cancelPreviousTooltip();

      myStoredModifiers = mouseEvent.getModifiers();
      BrowseMode browseMode = getBrowseMode(myStoredModifiers);

      if (browseMode == BrowseMode.None || e.getArea() != EditorMouseEventArea.EDITING_AREA) {
        disposeHighlighter();
        return;
      }

      Editor editor = e.getEditor();
      if (editor.getProject() != null && editor.getProject() != myProject) return;
      Point point = new Point(mouseEvent.getPoint());
      if (editor.getInlayModel().getElementAt(point) != null) {
        disposeHighlighter();
        return;
      }
      myTooltipProvider = new TooltipProvider(editor, editor.xyToLogicalPosition(point));
      myTooltipProvider.execute(browseMode);
    }
  };

  private void cancelPreviousTooltip() {
    if (myTooltipProvider != null) {
      myTooltipProvider.dispose();
      myTooltipProvider = null;
    }
  }

  public CtrlMouseHandler(final Project project,
                          StartupManager startupManager,
                          EditorColorsManager colorsManager,
                          FileEditorManager fileEditorManager,
                          @NotNull DocumentationManager documentationManager,
                          @NotNull final EditorFactory editorFactory) {
    myProject = project;
    myEditorColorsManager = colorsManager;
    startupManager.registerPostStartupActivity(new DumbAwareRunnable() {
      @Override
      public void run() {
        EditorEventMulticaster eventMulticaster = editorFactory.getEventMulticaster();
        eventMulticaster.addEditorMouseListener(myEditorMouseAdapter, project);
        eventMulticaster.addEditorMouseMotionListener(myEditorMouseMotionListener, project);
        eventMulticaster.addCaretListener(new CaretListener() {
          @Override
          public void caretPositionChanged(@NotNull CaretEvent e) {
            if (myHint != null) {
              myDocumentationManager.updateToolwindowContext();
            }
          }
        }, project);
      }
    });
    myFileEditorManager = fileEditorManager;
    myDocumentationManager = documentationManager;
  }

  private boolean isMouseOverTooltip(@NotNull Point mouseLocationOnScreen) {
    Rectangle bounds = getHintBounds();
    return bounds != null && bounds.contains(mouseLocationOnScreen);
  }

  @Nullable
  private Rectangle getHintBounds() {
    LightweightHint hint = myHint;
    if (hint == null) {
      return null;
    }
    JComponent hintComponent = hint.getComponent();
    if (!hintComponent.isShowing()) {
      return null;
    }
    return new Rectangle(hintComponent.getLocationOnScreen(), hintComponent.getSize());
  }

  @NotNull
  private static BrowseMode getBrowseMode(@JdkConstants.InputEventMask int modifiers) {
    if (modifiers != 0) {
      final Keymap activeKeymap = KeymapManager.getInstance().getActiveKeymap();
      if (KeymapUtil.matchActionMouseShortcutsModifiers(activeKeymap, modifiers, IdeActions.ACTION_GOTO_DECLARATION)) return BrowseMode.Declaration;
      if (KeymapUtil.matchActionMouseShortcutsModifiers(activeKeymap, modifiers, IdeActions.ACTION_GOTO_TYPE_DECLARATION)) return BrowseMode.TypeDeclaration;
      if (KeymapUtil.matchActionMouseShortcutsModifiers(activeKeymap, modifiers, IdeActions.ACTION_GOTO_IMPLEMENTATION)) return BrowseMode.Implementation;
    }
    return BrowseMode.None;
  }

  @Nullable
  @TestOnly
  public static String getInfo(PsiElement element, PsiElement atPointer) {
    return generateInfo(element, atPointer, true).text;
  }

  @Nullable
  @TestOnly
  public static String getInfo(@NotNull Editor editor, BrowseMode browseMode) {
    Project project = editor.getProject();
    if (project == null) return null;
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) return null;
    Info info = getInfoAt(project, editor, file, editor.getCaretModel().getOffset(), browseMode);
    return info == null ? null : info.getInfo().text;
  }

  @NotNull
  private static DocInfo generateInfo(PsiElement element, PsiElement atPointer, boolean fallbackToBasicInfo) {
    final DocumentationProvider documentationProvider = DocumentationManager.getProviderFromElement(element, atPointer);
    String result = documentationProvider.getQuickNavigateInfo(element, atPointer);
    if (result == null && fallbackToBasicInfo) {
      result = doGenerateInfo(element);
    }
    return result == null ? DocInfo.EMPTY : new DocInfo(result, documentationProvider);
  }

  @Nullable
  private static String doGenerateInfo(@NotNull PsiElement element) {
    if (element instanceof PsiFile) {
      final VirtualFile virtualFile = ((PsiFile)element).getVirtualFile();
      if (virtualFile != null) {
        return virtualFile.getPresentableUrl();
      }
    }

    String info = getQuickNavigateInfo(element);
    if (info != null) {
      return info;
    }

    if (element instanceof NavigationItem) {
      final ItemPresentation presentation = ((NavigationItem)element).getPresentation();
      if (presentation != null) {
        return presentation.getPresentableText();
      }
    }

    return null;
  }

  @Nullable
  private static String getQuickNavigateInfo(PsiElement element) {
    final String name = ElementDescriptionUtil.getElementDescription(element, UsageViewShortNameLocation.INSTANCE);
    if (StringUtil.isEmpty(name)) return null;
    final String typeName = ElementDescriptionUtil.getElementDescription(element, UsageViewTypeLocation.INSTANCE);
    final PsiFile file = element.getContainingFile();
    final StringBuilder sb = new StringBuilder();
    if (StringUtil.isNotEmpty(typeName)) sb.append(typeName).append(" ");
    sb.append("\"").append(name).append("\"");
    if (file != null && file.isPhysical()) {
      sb.append(" [").append(file.getName()).append("]");
    }
    return sb.toString();
  }

  public abstract static class Info {
    @NotNull protected final PsiElement myElementAtPointer;
    @NotNull private final List<TextRange> myRanges;

    public Info(@NotNull PsiElement elementAtPointer, @NotNull List<TextRange> ranges) {
      myElementAtPointer = elementAtPointer;
      myRanges = ranges;
    }

    public Info(@NotNull PsiElement elementAtPointer) {
      this(elementAtPointer, getReferenceRanges(elementAtPointer));
    }

    @NotNull
    private static List<TextRange> getReferenceRanges(@NotNull PsiElement elementAtPointer) {
      if (!elementAtPointer.isPhysical()) return Collections.emptyList();
      int textOffset = elementAtPointer.getTextOffset();
      final TextRange range = elementAtPointer.getTextRange();
      if (range == null) {
        throw new AssertionError("Null range for " + elementAtPointer + " of " + elementAtPointer.getClass());
      }
      if (textOffset < range.getStartOffset() || textOffset < 0) {
        LOG.error("Invalid text offset " + textOffset + " of element " + elementAtPointer + " of " + elementAtPointer.getClass());
        textOffset = range.getStartOffset();
      }
      return Collections.singletonList(new TextRange(textOffset, range.getEndOffset()));
    }

    boolean isSimilarTo(@NotNull Info that) {
      return Comparing.equal(myElementAtPointer, that.myElementAtPointer) && myRanges.equals(that.myRanges);
    }

    @NotNull
    public List<TextRange> getRanges() {
      return myRanges;
    }

    @NotNull
    public abstract DocInfo getInfo();

    public abstract boolean isValid(@NotNull Document document);

    public abstract boolean isNavigatable();

    protected boolean rangesAreCorrect(@NotNull Document document) {
      final TextRange docRange = new TextRange(0, document.getTextLength());
      for (TextRange range : getRanges()) {
        if (!docRange.contains(range)) return false;
      }

      return true;
    }
  }

  private static void showDumbModeNotification(@NotNull Project project) {
    DumbService.getInstance(project).showDumbModeNotification("Element information is not available during index update");
  }

  private static class InfoSingle extends Info {
    @NotNull private final PsiElement myTargetElement;

    InfoSingle(@NotNull PsiElement elementAtPointer, @NotNull PsiElement targetElement) {
      super(elementAtPointer);
      myTargetElement = targetElement;
    }

    InfoSingle(@NotNull PsiReference ref, @NotNull final PsiElement targetElement) {
      super(ref.getElement(), ReferenceRange.getAbsoluteRanges(ref));
      myTargetElement = targetElement;
    }

    @Override
    @NotNull
    public DocInfo getInfo() {
      return areElementsValid() ? generateInfo(myTargetElement, myElementAtPointer, isNavigatable()) : DocInfo.EMPTY;
    }

    private boolean areElementsValid() {
      return myTargetElement.isValid() && myElementAtPointer.isValid();
    }

    @Override
    public boolean isValid(@NotNull Document document) {
      return areElementsValid() && rangesAreCorrect(document);
    }

    @Override
    public boolean isNavigatable() {
      return myTargetElement != myElementAtPointer && myTargetElement != myElementAtPointer.getParent();
    }
  }

  private static class InfoMultiple extends Info {
    InfoMultiple(@NotNull final PsiElement elementAtPointer) {
      super(elementAtPointer);
    }

    InfoMultiple(@NotNull final PsiElement elementAtPointer, @NotNull PsiReference ref) {
      super(elementAtPointer, ReferenceRange.getAbsoluteRanges(ref));
    }

    @Override
    @NotNull
    public DocInfo getInfo() {
      return new DocInfo(CodeInsightBundle.message("multiple.implementations.tooltip"), null);
    }

    @Override
    public boolean isValid(@NotNull Document document) {
      return rangesAreCorrect(document);
    }

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

  @Nullable
  private Info getInfoAt(@NotNull final Editor editor, @NotNull PsiFile file, int offset, @NotNull BrowseMode browseMode) {
    return getInfoAt(myProject, editor, file, offset, browseMode);
  }

  @Nullable
  public static Info getInfoAt(@NotNull Project project, @NotNull final Editor editor, @NotNull PsiFile file, int offset,
                               @NotNull BrowseMode browseMode) {
    PsiElement targetElement = null;

    if (browseMode == BrowseMode.TypeDeclaration) {
      try {
        targetElement = GotoTypeDeclarationAction.findSymbolType(editor, offset);
      }
      catch (IndexNotReadyException e) {
        showDumbModeNotification(project);
      }
    }
    else if (browseMode == BrowseMode.Declaration) {
      final PsiReference ref = TargetElementUtil.findReference(editor, offset);
      final List<PsiElement> resolvedElements = ref == null ? Collections.emptyList() : resolve(ref);
      final PsiElement resolvedElement = resolvedElements.size() == 1 ? resolvedElements.get(0) : null;

      final PsiElement[] targetElements = GotoDeclarationAction.findTargetElementsNoVS(project, editor, offset, false);
      final PsiElement elementAtPointer = file.findElementAt(TargetElementUtil.adjustOffset(file, editor.getDocument(), offset));

      if (targetElements != null) {
        if (targetElements.length == 0) {
          return null;
        }
        else if (targetElements.length == 1) {
          if (targetElements[0] != resolvedElement && elementAtPointer != null && targetElements[0].isPhysical()) {
            return ref != null ? new InfoSingle(ref, targetElements[0]) : new InfoSingle(elementAtPointer, targetElements[0]);
          }
        }
        else {
          return elementAtPointer != null ? new InfoMultiple(elementAtPointer) : null;
        }
      }

      if (resolvedElements.size() == 1) {
        return new InfoSingle(ref, resolvedElements.get(0));
      }
      if (resolvedElements.size() > 1) {
        return elementAtPointer != null ? new InfoMultiple(elementAtPointer, ref) : null;
      }
    }
    else if (browseMode == BrowseMode.Implementation) {
      final PsiElement element = TargetElementUtil.getInstance().findTargetElement(editor, ImplementationSearcher.getFlags(), offset);
      PsiElement[] targetElements = new ImplementationSearcher() {
        @Override
        @NotNull
        protected PsiElement[] searchDefinitions(final PsiElement element, Editor editor) {
          final List<PsiElement> found = new ArrayList<>(2);
          DefinitionsScopedSearch.search(element, getSearchScope(element, editor)).forEach(psiElement -> {
            found.add(psiElement);
            return found.size() != 2;
          });
          return PsiUtilCore.toPsiElementArray(found);
        }
      }.searchImplementations(editor, element, offset);
      if (targetElements == null) {
        return null;
      }
      if (targetElements.length > 1) {
        PsiElement elementAtPointer = file.findElementAt(offset);
        if (elementAtPointer != null) {
          return new InfoMultiple(elementAtPointer);
        }
        return null;
      }
      if (targetElements.length == 1) {
        Navigatable descriptor = EditSourceUtil.getDescriptor(targetElements[0]);
        if (descriptor == null || !descriptor.canNavigate()) {
          return null;
        }
        targetElement = targetElements[0];
      }
    }

    if (targetElement != null && targetElement.isPhysical()) {
      PsiElement elementAtPointer = file.findElementAt(offset);
      if (elementAtPointer != null) {
        return new InfoSingle(elementAtPointer, targetElement);
      }
    }

    final PsiElement element = GotoDeclarationAction.findElementToShowUsagesOf(editor, offset);
    if (element instanceof PsiNameIdentifierOwner) {
      PsiElement identifier = ((PsiNameIdentifierOwner)element).getNameIdentifier();
      if (identifier != null && identifier.isValid()) {
        return new Info(identifier){
          @NotNull
          @Override
          public DocInfo getInfo() {
            String name = UsageViewUtil.getType(element) + " '"+ UsageViewUtil.getShortName(element)+"'";
            return new DocInfo("Show usages of "+name, null);
          }

          @Override
          public boolean isValid(@NotNull Document document) {
            return element.isValid();
          }

          @Override
          public boolean isNavigatable() {
            return true;
          }
        };
      }
    }
    return null;
  }

  @NotNull
  private static List<PsiElement> resolve(@NotNull PsiReference ref) {
    // IDEA-56727 try resolve first as in GotoDeclarationAction
    PsiElement resolvedElement = ref.resolve();

    if (resolvedElement == null && ref instanceof PsiPolyVariantReference) {
      List<PsiElement> result = new ArrayList<>();
      final ResolveResult[] psiElements = ((PsiPolyVariantReference)ref).multiResolve(false);
      for (ResolveResult resolveResult : psiElements) {
        if (resolveResult.getElement() != null) {
          result.add(resolveResult.getElement());
        }
      }
      return result;
    }
    return resolvedElement == null ? Collections.emptyList() : Collections.singletonList(resolvedElement);
  }

  private void disposeHighlighter() {
    if (myHighlighter != null) {
      HighlightersSet highlighter = myHighlighter;
      myHighlighter = null;
      highlighter.uninstall();
      HintManager.getInstance().hideAllHints();
    }
  }

  private void updateText(@NotNull String updatedText,
                          @NotNull Consumer<? super String> newTextConsumer,
                          @NotNull LightweightHint hint,
                          @NotNull Editor editor) {
    UIUtil.invokeLaterIfNeeded(() -> {
      // There is a possible case that quick doc control width is changed, e.g. it contained text
      // like 'public final class String implements java.io.Serializable, java.lang.Comparable<java.lang.String>' and
      // new text replaces fully-qualified class names by hyperlinks with short name.
      // That's why we might need to update the control size. We assume that the hint component is located at the
      // layered pane, so, the algorithm is to find an ancestor layered pane and apply new size for the target component.
      JComponent component = hint.getComponent();
      Dimension oldSize = component.getPreferredSize();
      newTextConsumer.consume(updatedText);

      Dimension newSize = component.getPreferredSize();
      if (newSize.width == oldSize.width) {
        return;
      }
      component.setPreferredSize(new Dimension(newSize.width, newSize.height));

      // We're assuming here that there are two possible hint representation modes: popup and layered pane.
      if (hint.isRealPopup()) {

        TooltipProvider tooltipProvider = myTooltipProvider;
        if (tooltipProvider != null) {
          // There is a possible case that 'raw' control was rather wide but the 'rich' one is narrower. That's why we try to
          // re-show the hint here. Benefits: there is a possible case that we'll be able to show nice layered pane-based balloon;
          // the popup will be re-positioned according to the new width.
          hint.hide();
          tooltipProvider.showHint(new LightweightHint(component), editor);
        }
        else {
          component.setPreferredSize(new Dimension(newSize.width, oldSize.height));
          hint.pack();
        }
        return;
      }

      Container topLevelLayeredPaneChild = null;
      boolean adjustBounds = false;
      for (Container current = component.getParent(); current != null; current = current.getParent()) {
        if (current instanceof JLayeredPane) {
          adjustBounds = true;
          break;
        }
        else {
          topLevelLayeredPaneChild = current;
        }
      }

      if (adjustBounds && topLevelLayeredPaneChild != null) {
        Rectangle bounds = topLevelLayeredPaneChild.getBounds();
        topLevelLayeredPaneChild.setBounds(bounds.x, bounds.y, bounds.width + newSize.width - oldSize.width, bounds.height);
      }
    });
  }

  private class TooltipProvider {
    @NotNull private final Editor myHostEditor;
    @NotNull private final LogicalPosition myHostPosition;
    private BrowseMode myBrowseMode;
    private boolean myDisposed;
    private final ProgressIndicator myProgress = new ProgressIndicatorBase();

    TooltipProvider(@NotNull Editor hostEditor, @NotNull LogicalPosition hostPos) {
      myHostEditor = hostEditor;
      myHostPosition = hostPos;
    }

    void dispose() {
      myDisposed = true;
      myProgress.cancel();
    }

    public BrowseMode getBrowseMode() {
      return myBrowseMode;
    }

    void execute(@NotNull BrowseMode browseMode) {
      myBrowseMode = browseMode;

      if (PsiDocumentManager.getInstance(myProject).getPsiFile(myHostEditor.getDocument()) == null) return;

      if (EditorUtil.inVirtualSpace(myHostEditor, myHostPosition)) {
        disposeHighlighter();
        return;
      }

      final int offset = myHostEditor.logicalPositionToOffset(myHostPosition);

      int selStart = myHostEditor.getSelectionModel().getSelectionStart();
      int selEnd = myHostEditor.getSelectionModel().getSelectionEnd();

      if (offset >= selStart && offset < selEnd) {
        disposeHighlighter();
        return;
      }

      PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(
        () -> ProgressIndicatorUtils.scheduleWithWriteActionPriority(myProgress, new ReadTask() {
          @Nullable
          @Override
          public Continuation performInReadAction(@NotNull ProgressIndicator indicator) throws ProcessCanceledException {
            return doExecute();
          }

          @Override
          public void onCanceled(@NotNull ProgressIndicator indicator) {
            LOG.debug("Highlighting was cancelled");
          }
        }));
    }

    @Nullable
    private ReadTask.Continuation doExecute() {
      if (isTaskOutdated(myHostEditor)) return null;

      Editor editor = getPossiblyInjectedEditor();
      int offset = editor.logicalPositionToOffset(getPosition(editor));

      PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
      if (file == null) return null;

      final Info info;
      final DocInfo docInfo;
      try {
        info = getInfoAt(editor, file, offset, myBrowseMode);
        if (info == null) return null;
        docInfo = info.getInfo();
      }
      catch (IndexNotReadyException e) {
        showDumbModeNotification(myProject);
        return null;
      }

      LOG.debug("Obtained info about element under cursor");
      return new ReadTask.Continuation(() -> {
        if (isTaskOutdated(editor)) return;
        showHint(info, docInfo, editor);
      });
    }

    @NotNull
    private Editor getPossiblyInjectedEditor() {
      final Document document = myHostEditor.getDocument();
      if (PsiDocumentManager.getInstance(myProject).isCommitted(document)) {
        PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
        return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(myHostEditor, psiFile, myHostEditor.logicalPositionToOffset(myHostPosition));
      }
      return myHostEditor;
    }

    private boolean isTaskOutdated(@NotNull Editor editor) {
      return myDisposed || myProject.isDisposed() || editor.isDisposed() || !editor.getComponent().isShowing();
    }

    private LogicalPosition getPosition(@NotNull Editor editor) {
      return editor instanceof EditorWindow ? ((EditorWindow)editor).hostToInjected(myHostPosition) : myHostPosition;
    }

    private void showHint(@NotNull Info info, @NotNull DocInfo docInfo, @NotNull Editor editor) {
      if (myDisposed || editor.isDisposed()) return;
      Component internalComponent = editor.getContentComponent();
      if (myHighlighter != null) {
        if (!info.isSimilarTo(myHighlighter.getStoredInfo())) {
          disposeHighlighter();
        }
        else {
          // highlighter already set
          if (info.isNavigatable()) {
            internalComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          }
          return;
        }
      }

      if (!info.isValid(editor.getDocument()) || !info.isNavigatable() && docInfo.text == null) {
        return;
      }

      myHighlighter = installHighlighterSet(info, editor);

      if (docInfo.text == null) return;

      HyperlinkListener hyperlinkListener = docInfo.docProvider == null
                                   ? null
                                   : new QuickDocHyperlinkListener(docInfo.docProvider, info.myElementAtPointer);
      Ref<Consumer<String>> newTextConsumerRef = new Ref<>();
      JComponent label = HintUtil.createInformationLabel(docInfo.text, hyperlinkListener, null, newTextConsumerRef);
      Consumer<String> newTextConsumer = newTextConsumerRef.get();

      label.setBorder(JBUI.Borders.empty(6, 6, 5, 6));

      final LightweightHint hint = new LightweightHint(label);

      myHint = hint;
      hint.addHintListener(new HintListener() {
        @Override
        public void hintHidden(@NotNull EventObject event) {
          myHint = null;
        }
      });

      showHint(hint, editor);
      if (newTextConsumer != null) {
        updateOnPsiChanges(hint, info, newTextConsumer, docInfo.text, editor);
      }
    }

    private void updateOnPsiChanges(@NotNull LightweightHint hint,
                                    @NotNull Info info,
                                    @NotNull Consumer<? super String> textConsumer,
                                    @NotNull String oldText,
                                    @NotNull Editor editor) {
      if (!hint.isVisible()) return;
      Disposable hintDisposable = Disposer.newDisposable("CtrlMouseHandler.TooltipProvider.updateOnPsiChanges");
      hint.addHintListener(new HintListener() {
        @Override
        public void hintHidden(@NotNull EventObject event) {
          Disposer.dispose(hintDisposable);
        }
      });
      AtomicBoolean updating = new AtomicBoolean(false);
      myProject.getMessageBus().connect(hintDisposable).subscribe(PsiModificationTracker.TOPIC, () -> {
        if (updating.getAndSet(true)) return;
        PsiDocumentManager.getInstance(myProject).performWhenAllCommitted(() -> {
          ProgressIndicatorBase progress = new ProgressIndicatorBase();
          if (Disposer.isDisposed(hintDisposable)) {
            progress.cancel();
          }
          else {
            Disposer.register(hintDisposable, () -> progress.cancel());
          }
          ProgressIndicatorUtils.scheduleWithWriteActionPriority(progress, new ReadTask() {
            @Nullable
            @Override
            public Continuation performInReadAction(@NotNull ProgressIndicator indicator) throws ProcessCanceledException {
              if (!info.isValid(editor.getDocument())) {
                updating.set(false);
                return null;
              }
              DocInfo newDocInfo = info.getInfo();
              return new Continuation(() -> {
                updating.set(false);
                if (newDocInfo.text != null && !oldText.equals(newDocInfo.text)) {
                  updateText(newDocInfo.text, textConsumer, hint, editor);
                }
              });
            }

            @Override
            public void onCanceled(@NotNull ProgressIndicator indicator) {
              updating.set(false);
            }
          });
        });
      });
    }

    public void showHint(@NotNull LightweightHint hint, @NotNull Editor editor) {
      if (editor.isDisposed()) return;
      final HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
      short constraint = HintManager.ABOVE;
      Point p = HintManagerImpl.getHintPosition(hint, editor, getPosition(editor), constraint);
      if (p.y - hint.getComponent().getPreferredSize().height < 0) {
        constraint = HintManager.UNDER;
        p = HintManagerImpl.getHintPosition(hint, editor, getPosition(editor), constraint);
      }
      hintManager.showEditorHint(hint, editor, p,
                                 HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING,
                                 0, false, HintManagerImpl.createHintHint(editor, p, hint, constraint).setContentActive(false));
    }
  }

  @NotNull
  private HighlightersSet installHighlighterSet(@NotNull Info info, @NotNull Editor editor) {
    final JComponent internalComponent = editor.getContentComponent();
    internalComponent.addKeyListener(myEditorKeyListener);
    editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
    final Cursor cursor = internalComponent.getCursor();
    if (info.isNavigatable()) {
      internalComponent.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }
    myFileEditorManager.addFileEditorManagerListener(myFileEditorManagerListener);

    List<RangeHighlighter> highlighters = new ArrayList<>();
    TextAttributes attributes = info.isNavigatable()
                                ? myEditorColorsManager.getGlobalScheme().getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR)
                                : new TextAttributes(null, HintUtil.getInformationColor(), null, null, Font.PLAIN);
    for (TextRange range : info.getRanges()) {
      TextAttributes attr = NavigationUtil.patchAttributesColor(attributes, range, editor);
      final RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(),
                                                                                HighlighterLayer.HYPERLINK,
                                                                                attr,
                                                                                HighlighterTargetArea.EXACT_RANGE);
      highlighters.add(highlighter);
    }

    return new HighlightersSet(highlighters, editor, cursor, info);
  }

  private class HighlightersSet {
    @NotNull private final List<? extends RangeHighlighter> myHighlighters;
    @NotNull private final Editor myHighlighterView;
    @NotNull private final Cursor myStoredCursor;
    @NotNull private final Info myStoredInfo;

    private HighlightersSet(@NotNull List<? extends RangeHighlighter> highlighters,
                            @NotNull Editor highlighterView,
                            @NotNull Cursor storedCursor,
                            @NotNull Info storedInfo) {
      myHighlighters = highlighters;
      myHighlighterView = highlighterView;
      myStoredCursor = storedCursor;
      myStoredInfo = storedInfo;
    }

    public void uninstall() {
      for (RangeHighlighter highlighter : myHighlighters) {
        highlighter.dispose();
      }

      Component internalComponent = myHighlighterView.getContentComponent();
      internalComponent.setCursor(myStoredCursor);
      internalComponent.removeKeyListener(myEditorKeyListener);
      myHighlighterView.getScrollingModel().removeVisibleAreaListener(myVisibleAreaListener);
      myFileEditorManager.removeFileEditorManagerListener(myFileEditorManagerListener);
    }

    @NotNull
    public Info getStoredInfo() {
      return myStoredInfo;
    }
  }

  public static class DocInfo {
    public static final DocInfo EMPTY = new DocInfo(null, null);

    @Nullable public final String text;
    @Nullable public final DocumentationProvider docProvider;

    DocInfo(@Nullable String text, @Nullable DocumentationProvider provider) {
      this.text = text;
      docProvider = provider;
    }
  }

  private class QuickDocHyperlinkListener implements HyperlinkListener {
    @NotNull private final DocumentationProvider myProvider;
    @NotNull private final PsiElement myContext;

    QuickDocHyperlinkListener(@NotNull DocumentationProvider provider, @NotNull PsiElement context) {
      myProvider = provider;
      myContext = context;
    }

    @Override
    public void hyperlinkUpdate(@NotNull HyperlinkEvent e) {
      if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) {
        return;
      }

      String description = e.getDescription();
      if (StringUtil.isEmpty(description) || !description.startsWith(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL)) {
        return;
      }

      String elementName = e.getDescription().substring(DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL.length());

      DumbService.getInstance(myProject).withAlternativeResolveEnabled(() -> {
        PsiElement targetElement = myProvider.getDocumentationElementForLink(PsiManager.getInstance(myProject), elementName, myContext);
        if (targetElement != null) {
          LightweightHint hint = myHint;
          if (hint != null) {
            hint.hide(true);
          }
          myDocumentationManager.showJavaDocInfo(targetElement, myContext, null);
        }
      });
    }
  }
}


text:
using System;
using System.Net;
using System.Net.Sockets;

namespace Rocks.Helpers
{
	public static class IpExtensions
	{
		public static long ToLong (this IPAddress ip)
		{
			if (ip.AddressFamily == AddressFamily.InterNetworkV6)
				ip = ip.MapToIPv4 ();

			var address_bytes = ip.GetAddressBytes ();

			if (BitConverter.IsLittleEndian)
				Array.Reverse (address_bytes);

			var result = BitConverter.ToUInt32 (address_bytes, 0);

			return result;
		}

		public static IPAddress ToIPAddress (this long ip)
		{
			var address_bytes = BitConverter.GetBytes ((uint) ip);

			if (BitConverter.IsLittleEndian)
				Array.Reverse (address_bytes);

			return new IPAddress (address_bytes);
		}
	}
}


text:
'use strict';

Connector.playerSelector = '.holder';

Connector.getArtistTrack = () => {
	let artist = $('#song_info h2').text();
	let track = $('#song_info h3').text();

	if (artist === 'rawPlayer' || artist === 'loading...') {
		return Util.makeEmptyArtistTrack();
	}
	if (track === 'Standard Definition Audio' || track === 'High Definition Audio') {
		return Util.makeEmptyArtistTrack();
	}
	return { artist, track };
};

Connector.isPlaying = () => $('#play1 img').attr('src').includes('stop');


text:
/**
 * returns the timestamp for any date or for now(), also works with browsers that dont support es5 Date.now
 * @param dateString
 */
declare const getTimestamp: (dateString?: string | number) => number;
export { getTimestamp };


text:
<!DOCTYPE html>
<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org">

There should be a green square below.