text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gabriel;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import gabriel.models.Connection;
import gabriel.models.Index;

/**
 *
 * @author TheDoctor
 */
public class ConnectionManager {

    private ArrayList<Connection> connections = new ArrayList<>();
    private final Integer PORT_NO = 5000;

    Index myIndex = new Index();
    Index networkIndex = new Index();

    public Integer getPORT_NO() {
        return PORT_NO;
    }

    public ConnectionManager() {

    }

    public void addConnection(Connection conn) {
        this.connections.add(conn);
    }

    Boolean startConnection(Connection newConnection) {
        try {
            newConnection.setConnectionSocket(new Socket(newConnection.getConnectionIp(), PORT_NO));

            sendData(newConnection, myIndex);
            addConnection(newConnection);
            return true;
        } catch (IOException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public void sendData(Connection connection, Index myIndex) {
        try {
            try (OutputStream os = connection.getConnectionSocket().getOutputStream()) {
                ObjectOutputStream objectOS = new ObjectOutputStream(os);
                objectOS.writeObject(myIndex);
            }
        } catch (IOException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public Index getMyIndex() {
        return myIndex;
    }

    public void setMyIndex(Index myIndex) {
        this.myIndex = myIndex;
    }

    public Index getNetworkIndex() {
        return networkIndex;
    }

    public void setNetworkIndex(Index networkIndex) {
        this.networkIndex = networkIndex;
    }

    void addToNetworkIndex(Index incomingIndex) {
        this.networkIndex.getFileHeaders().addAll(incomingIndex.getFileHeaders());
    }

    Index getIndex(Socket connectionSocket) {
        Index incomingIndex = null;
        try {
            //Getting the ObjectInputStream to retrive file index
            ObjectInputStream incomingStream = new ObjectInputStream(new BufferedInputStream(connectionSocket.getInputStream()));

            incomingIndex = (Index) incomingStream.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(ConnectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return incomingIndex;
    }

}


text:
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::AtLeast;
using ::testing::AtMost;
using ::testing::Invoke;
using ::testing::InvokeWithoutArgs;
using ::testing::SaveArg;

namespace media {

const char kNullVideoHash[] = "d41d8cd98f00b204e9800998ecf8427e";
const char kNullAudioHash[] = "0.00,0.00,0.00,0.00,0.00,0.00,";

PipelineIntegrationTestBase::PipelineIntegrationTestBase()
    : hashing_enabled_(false),
      clockless_playback_(false),
      pipeline_(new PipelineImpl(message_loop_.task_runner(), new MediaLog())),
      ended_(false),
      pipeline_status_(PIPELINE_OK),
      last_video_frame_format_(PIXEL_FORMAT_UNKNOWN),
      last_video_frame_color_space_(COLOR_SPACE_UNSPECIFIED),
      current_duration_(kInfiniteDuration) {
  ResetVideoHash();
}

PipelineIntegrationTestBase::~PipelineIntegrationTestBase() {
  if (pipeline_->IsRunning())
    Stop();

  pipeline_.reset();
  base::RunLoop().RunUntilIdle();
}

// TODO(xhwang): Method definitions in this file needs to be reordered.

void PipelineIntegrationTestBase::OnSeeked(base::TimeDelta seek_time,
                                           PipelineStatus status) {
  EXPECT_EQ(seek_time, pipeline_->GetMediaTime());
  pipeline_status_ = status;
}

void PipelineIntegrationTestBase::OnStatusCallback(PipelineStatus status) {
  pipeline_status_ = status;
  message_loop_.task_runner()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
}

void PipelineIntegrationTestBase::DemuxerEncryptedMediaInitDataCB(
    EmeInitDataType type,
    const std::vector<uint8_t>& init_data) {
  DCHECK(!init_data.empty());
  CHECK(!encrypted_media_init_data_cb_.is_null());
  encrypted_media_init_data_cb_.Run(type, init_data);
}

void PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB(
    std::unique_ptr<MediaTracks> tracks) {
  CHECK(tracks);
  CHECK_GT(tracks->tracks().size(), 0u);

  // Verify that track ids are unique.
  std::set<MediaTrack::Id> track_ids;
  for (const auto& track : tracks->tracks()) {
    EXPECT_EQ(track_ids.end(), track_ids.find(track->id()));
    track_ids.insert(track->id());
  }
}

void PipelineIntegrationTestBase::OnEnded() {
  DCHECK(!ended_);
  ended_ = true;
  pipeline_status_ = PIPELINE_OK;
  message_loop_.task_runner()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
}

bool PipelineIntegrationTestBase::WaitUntilOnEnded() {
  if (ended_)
    return (pipeline_status_ == PIPELINE_OK);
  base::RunLoop().Run();
  EXPECT_TRUE(ended_);
  return ended_ && (pipeline_status_ == PIPELINE_OK);
}

PipelineStatus PipelineIntegrationTestBase::WaitUntilEndedOrError() {
  if (ended_ || pipeline_status_ != PIPELINE_OK)
    return pipeline_status_;
  base::RunLoop().Run();
  return pipeline_status_;
}

void PipelineIntegrationTestBase::OnError(PipelineStatus status) {
  DCHECK_NE(status, PIPELINE_OK);
  pipeline_status_ = status;
  message_loop_.task_runner()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
}

PipelineStatus PipelineIntegrationTestBase::StartInternal(
    std::unique_ptr<DataSource> data_source,
    CdmContext* cdm_context,
    uint8_t test_type,
    ScopedVector<VideoDecoder> prepend_video_decoders,
    ScopedVector<AudioDecoder> prepend_audio_decoders) {
  hashing_enabled_ = test_type & kHashed;
  clockless_playback_ = test_type & kClockless;

  EXPECT_CALL(*this, OnMetadata(_))
      .Times(AtMost(1))
      .WillRepeatedly(SaveArg<0>(&metadata_));
  EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH))
      .Times(AnyNumber());
  EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_NOTHING))
      .Times(AnyNumber());
  // Permit at most two calls to OnDurationChange.  CheckDuration will make sure
  // that no more than one of them is a finite duration.  This allows the
  // pipeline to call back at the end of the media with the known duration.
  EXPECT_CALL(*this, OnDurationChange())
      .Times(AtMost(2))
      .WillRepeatedly(
          Invoke(this, &PipelineIntegrationTestBase::CheckDuration));
  EXPECT_CALL(*this, OnVideoNaturalSizeChange(_)).Times(AtMost(1));
  EXPECT_CALL(*this, OnVideoOpacityChange(_)).Times(AtMost(1));
  CreateDemuxer(std::move(data_source));

  if (cdm_context) {
    EXPECT_CALL(*this, DecryptorAttached(true));
    pipeline_->SetCdm(
        cdm_context, base::Bind(&PipelineIntegrationTestBase::DecryptorAttached,
                                base::Unretained(this)));
  }

  // Should never be called as the required decryption keys for the encrypted
  // media files are provided in advance.
  EXPECT_CALL(*this, OnWaitingForDecryptionKey()).Times(0);

  pipeline_->Start(
      demuxer_.get(), CreateRenderer(std::move(prepend_video_decoders),
                                     std::move(prepend_audio_decoders)),
      this, base::Bind(&PipelineIntegrationTestBase::OnStatusCallback,
                       base::Unretained(this)));
  base::RunLoop().Run();
  return pipeline_status_;
}

PipelineStatus PipelineIntegrationTestBase::StartWithFile(
    const std::string& filename,
    CdmContext* cdm_context,
    uint8_t test_type,
    ScopedVector<VideoDecoder> prepend_video_decoders,
    ScopedVector<AudioDecoder> prepend_audio_decoders) {
  std::unique_ptr<FileDataSource> file_data_source(new FileDataSource());
  base::FilePath file_path(GetTestDataFilePath(filename));
  CHECK(file_data_source->Initialize(file_path)) << "Is " << file_path.value()
                                                 << " missing?";
  return StartInternal(std::move(file_data_source), cdm_context, test_type,
                       std::move(prepend_video_decoders),
                       std::move(prepend_audio_decoders));
}

PipelineStatus PipelineIntegrationTestBase::Start(const std::string& filename) {
  return StartWithFile(filename, nullptr, kNormal);
}

PipelineStatus PipelineIntegrationTestBase::Start(const std::string& filename,
                                                  CdmContext* cdm_context) {
  return StartWithFile(filename, cdm_context, kNormal);
}

PipelineStatus PipelineIntegrationTestBase::Start(
    const std::string& filename,
    uint8_t test_type,
    ScopedVector<VideoDecoder> prepend_video_decoders,
    ScopedVector<AudioDecoder> prepend_audio_decoders) {
  return StartWithFile(filename, nullptr, test_type,
                       std::move(prepend_video_decoders),
                       std::move(prepend_audio_decoders));
}

PipelineStatus PipelineIntegrationTestBase::Start(const uint8_t* data,
                                                  size_t size,
                                                  uint8_t test_type) {
  return StartInternal(base::MakeUnique<MemoryDataSource>(data, size), nullptr,
                       test_type);
}

void PipelineIntegrationTestBase::Play() {
  pipeline_->SetPlaybackRate(1);
}

void PipelineIntegrationTestBase::Pause() {
  pipeline_->SetPlaybackRate(0);
}

bool PipelineIntegrationTestBase::Seek(base::TimeDelta seek_time) {
  ended_ = false;

  EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH))
      .WillOnce(InvokeWithoutArgs(&message_loop_, &base::MessageLoop::QuitNow));
  pipeline_->Seek(seek_time, base::Bind(&PipelineIntegrationTestBase::OnSeeked,
                                        base::Unretained(this), seek_time));
  base::RunLoop().Run();
  EXPECT_CALL(*this, OnBufferingStateChange(_)).Times(AnyNumber());
  return (pipeline_status_ == PIPELINE_OK);
}

bool PipelineIntegrationTestBase::Suspend() {
  pipeline_->Suspend(base::Bind(&PipelineIntegrationTestBase::OnStatusCallback,
                                base::Unretained(this)));
  base::RunLoop().Run();
  return (pipeline_status_ == PIPELINE_OK);
}

bool PipelineIntegrationTestBase::Resume(base::TimeDelta seek_time) {
  ended_ = false;

  EXPECT_CALL(*this, OnBufferingStateChange(BUFFERING_HAVE_ENOUGH))
      .WillOnce(InvokeWithoutArgs(&message_loop_, &base::MessageLoop::QuitNow));
  pipeline_->Resume(CreateRenderer(), seek_time,
                    base::Bind(&PipelineIntegrationTestBase::OnSeeked,
                               base::Unretained(this), seek_time));
  base::RunLoop().Run();
  return (pipeline_status_ == PIPELINE_OK);
}

void PipelineIntegrationTestBase::Stop() {
  DCHECK(pipeline_->IsRunning());
  pipeline_->Stop();
  base::RunLoop().RunUntilIdle();
}

void PipelineIntegrationTestBase::FailTest(PipelineStatus status) {
  DCHECK_NE(PIPELINE_OK, status);
  OnError(status);
}

void PipelineIntegrationTestBase::QuitAfterCurrentTimeTask(
    const base::TimeDelta& quit_time) {
  if (pipeline_->GetMediaTime() >= quit_time ||
      pipeline_status_ != PIPELINE_OK) {
    message_loop_.QuitWhenIdle();
    return;
  }

  message_loop_.task_runner()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&PipelineIntegrationTestBase::QuitAfterCurrentTimeTask,
                 base::Unretained(this), quit_time),
      base::TimeDelta::FromMilliseconds(10));
}

bool PipelineIntegrationTestBase::WaitUntilCurrentTimeIsAfter(
    const base::TimeDelta& wait_time) {
  DCHECK(pipeline_->IsRunning());
  DCHECK_GT(pipeline_->GetPlaybackRate(), 0);
  DCHECK(wait_time <= pipeline_->GetMediaDuration());

  message_loop_.task_runner()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&PipelineIntegrationTestBase::QuitAfterCurrentTimeTask,
                 base::Unretained(this), wait_time),
      base::TimeDelta::FromMilliseconds(10));
  base::RunLoop().Run();
  return (pipeline_status_ == PIPELINE_OK);
}

void PipelineIntegrationTestBase::CreateDemuxer(
    std::unique_ptr<DataSource> data_source) {
  data_source_ = std::move(data_source);

#if !defined(MEDIA_DISABLE_FFMPEG)
  demuxer_ = std::unique_ptr<Demuxer>(new FFmpegDemuxer(
      message_loop_.task_runner(), data_source_.get(),
      base::Bind(&PipelineIntegrationTestBase::DemuxerEncryptedMediaInitDataCB,
                 base::Unretained(this)),
      base::Bind(&PipelineIntegrationTestBase::DemuxerMediaTracksUpdatedCB,
                 base::Unretained(this)),
      new MediaLog()));
#endif
}

std::unique_ptr<Renderer> PipelineIntegrationTestBase::CreateRenderer(
    ScopedVector<VideoDecoder> prepend_video_decoders,
    ScopedVector<AudioDecoder> prepend_audio_decoders) {
  ScopedVector<VideoDecoder> video_decoders = std::move(prepend_video_decoders);
#if !defined(MEDIA_DISABLE_LIBVPX)
  video_decoders.push_back(new VpxVideoDecoder());
#endif  // !defined(MEDIA_DISABLE_LIBVPX)

// Android does not have an ffmpeg video decoder.
#if !defined(MEDIA_DISABLE_FFMPEG) && !defined(OS_ANDROID)
  video_decoders.push_back(new FFmpegVideoDecoder());
#endif

  // Simulate a 60Hz rendering sink.
  video_sink_.reset(new NullVideoSink(
      clockless_playback_, base::TimeDelta::FromSecondsD(1.0 / 60),
      base::Bind(&PipelineIntegrationTestBase::OnVideoFramePaint,
                 base::Unretained(this)),
      message_loop_.task_runner()));

  // Disable frame dropping if hashing is enabled.
  std::unique_ptr<VideoRenderer> video_renderer(new VideoRendererImpl(
      message_loop_.task_runner(), message_loop_.task_runner().get(),
      video_sink_.get(), std::move(video_decoders), false, nullptr,
      new MediaLog()));

  ScopedVector<AudioDecoder> audio_decoders = std::move(prepend_audio_decoders);

#if !defined(MEDIA_DISABLE_FFMPEG)
  audio_decoders.push_back(
      new FFmpegAudioDecoder(message_loop_.task_runner(), new MediaLog()));
#endif

  if (!clockless_playback_) {
    audio_sink_ = new NullAudioSink(message_loop_.task_runner());
  } else {
    clockless_audio_sink_ = new ClocklessAudioSink(OutputDeviceInfo(
        "", OUTPUT_DEVICE_STATUS_OK,
        // Don't allow the audio renderer to resample buffers if hashing is
        // enabled:
        hashing_enabled_
            ? AudioParameters()
            : AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY,
                              CHANNEL_LAYOUT_STEREO, 44100, 16, 512)));
  }

  std::unique_ptr<AudioRenderer> audio_renderer(new AudioRendererImpl(
      message_loop_.task_runner(),
      (clockless_playback_)
          ? static_cast<AudioRendererSink*>(clockless_audio_sink_.get())
          : audio_sink_.get(),
      std::move(audio_decoders), new MediaLog()));
  if (hashing_enabled_) {
    if (clockless_playback_)
      clockless_audio_sink_->StartAudioHashForTesting();
    else
      audio_sink_->StartAudioHashForTesting();
  }

  std::unique_ptr<RendererImpl> renderer_impl(
      new RendererImpl(message_loop_.task_runner(), std::move(audio_renderer),
                       std::move(video_renderer)));

  // Prevent non-deterministic buffering state callbacks from firing (e.g., slow
  // machine, valgrind).
  renderer_impl->DisableUnderflowForTesting();

  if (clockless_playback_)
    renderer_impl->EnableClocklessVideoPlaybackForTesting();

  return std::move(renderer_impl);
}

void PipelineIntegrationTestBase::OnVideoFramePaint(
    const scoped_refptr<VideoFrame>& frame) {
  last_video_frame_format_ = frame->format();
  int result;
  if (frame->metadata()->GetInteger(VideoFrameMetadata::COLOR_SPACE, &result))
    last_video_frame_color_space_ = static_cast<ColorSpace>(result);
  if (!hashing_enabled_ || last_frame_ == frame)
    return;
  last_frame_ = frame;
  DVLOG(3) << __FUNCTION__ << " pts=" << frame->timestamp().InSecondsF();
  VideoFrame::HashFrameForTesting(&md5_context_, frame);
}

void PipelineIntegrationTestBase::CheckDuration() {
  // Allow the pipeline to specify indefinite duration, then reduce it once
  // it becomes known.
  ASSERT_EQ(kInfiniteDuration, current_duration_);
  base::TimeDelta new_duration = pipeline_->GetMediaDuration();
  current_duration_ = new_duration;
}

base::TimeDelta PipelineIntegrationTestBase::GetStartTime() {
  return demuxer_->GetStartTime();
}

void PipelineIntegrationTestBase::ResetVideoHash() {
  DVLOG(1) << __FUNCTION__;
  base::MD5Init(&md5_context_);
}

std::string PipelineIntegrationTestBase::GetVideoHash() {
  DCHECK(hashing_enabled_);
  base::MD5Digest digest;
  base::MD5Final(&digest, &md5_context_);
  return base::MD5DigestToBase16(digest);
}

std::string PipelineIntegrationTestBase::GetAudioHash() {
  DCHECK(hashing_enabled_);

  if (clockless_playback_)
    return clockless_audio_sink_->GetAudioHashForTesting();
  return audio_sink_->GetAudioHashForTesting();
}

base::TimeDelta PipelineIntegrationTestBase::GetAudioTime() {
  DCHECK(clockless_playback_);
  return clockless_audio_sink_->render_time();
}

base::TimeTicks DummyTickClock::NowTicks() {
  now_ += base::TimeDelta::FromSeconds(60);
  return now_;
}

}  // namespace media

redpajama_set_name: RedPajamaGithub


text:
SOURCE=$(dpkg-parsechangelog --show-field Source)
VERSION=$(git describe --tags --long | cut -c 2-)
SHORT_VERSION=$(echo "$VERSION" | cut -d '-' -f 1,2)
DEBEMAIL="Jerome Quere <jerome.quere@indigen.com>"
DEBEMAIL=$DEBEMAIL dch -v $VERSION "Release $VERSION"
DEBEMAIL=$DEBEMAIL dch -r $VERSION

tar -cJf ../${SOURCE}_${SHORT_VERSION}.orig.tar.xz *

debuild

rm -f ../${SOURCE}_${VERSION}*.build
rm -f ../${SOURCE}_${VERSION}*.changes
rm -f ../${SOURCE}_${VERSION}*.tar.xz
rm -f ../${SOURCE}_${VERSION}*.dsc
rm -f ../${SOURCE}_${SHORT_VERSION}.orig.tar.xz
mv  ../${SOURCE}_${VERSION}_all.deb .

debuild -- clean


text:
<admin-tab state-name="{{$ctrl.stateName}}" inactive-users="$ctrl.inactiveUsers" unregistered-devices="$ctrl.unregisteredDevices" plugin-tabs="$ctrl.pluginTabs"></admin-tab>

    <ui-view
        on-user-activated="$ctrl.userActivated($event)"
        on-device-registered="$ctrl.deviceRegistered($event)"
        on-device-unregistered="$ctrl.deviceUnregistered($event)">
      <admin-dashboard></admin-dashboard>
    </ui-view>


text:
package org.apache.ctakes.ytex.tools;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/*
 * verify db parameters.  takes as input property file
 */
public class DBPing {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		InputStream is = null;
		try {
			is = new FileInputStream(args[0]);
			Properties props = new Properties();
			props.load(is);
			System.exit(ping(props));
		} catch (Exception e) {
			e.printStackTrace();
			System.out
					.println("DBPing: Connection to db failed - please check your settings and try again");
			System.exit(1);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
		}
	}

	public static int ping(Properties props) throws Exception {
		if (props.getProperty("db.driver") == null) {
			System.out.println("DBPing: db.driver not defined");
			return 1;
		}
		if (props.getProperty("db.url") == null) {
			System.out.println("DBPing: db.url not defined");
			return 1;
		}
		Class.forName(props.getProperty("db.driver"));
		Connection c = null;
		try {
			c = DriverManager.getConnection(props.getProperty("db.url"),
					props.getProperty("db.username"),
					props.getProperty("db.password"));
			System.out.println("DBPing: connection succeeded");
		} finally {
			if (c != null) {
				try {
					c.close();
				} catch (Exception e) {
				}
			}
		}
		return 0;
	}

}


text:
#region MIT
//
// Gorgon.
// Copyright (C) 2018 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: October 12, 2018 12:52:19 PM
//
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Gorgon.Diagnostics;
using Gorgon.Editor.Properties;
using Gorgon.PlugIns;

namespace Gorgon.Editor.PlugIns
{
    ///
    /// Extension functionality relating to editor plug ins.
    ///
    public static class EditorPlugInExtensions
    {
        ///
        /// Function to retrieve a friendly description of a <see cref="PlugInType"/> value.
        ///
        /// <param name="pluginType">The plug in type to evaluate.</param>
        /// <returns>The friendly description.</returns>
        public static string GetDescription(this PlugInType pluginType)
        {
            return pluginType switch
            {
                PlugInType.Writer => Resources.GOREDIT_PLUGIN_TYPE_WRITER,
                PlugInType.Content => Resources.GOREDIT_PLUGIN_TYPE_CONTENT,
                PlugInType.Tool => Resources.GOREDIT_PLUGIN_TYPE_TOOL,
                PlugInType.Reader => Resources.GOREDIT_PLUGIN_TYPE_READER,
                PlugInType.ContentImporter => Resources.GOREDIT_PLUGIN_TYPE_IMPORTER,
                _ => Resources.GOREDIT_PLUGIN_TYPE_UNKNOWN,
            };
            ;
        }

        /// Function to load all the specified plug in assemblies.
        /// <param name="pluginCache">The plugin cache that will hold the plug in assembies.</param>
        /// <param name="pluginAssemblyFiles">The list of plug in assembly paths to load.</param>
        /// <param name="log">The application logging interface.</param>
        /// <returns>A list of <see cref="PlugInAssemblyState"/> objects for each plug in assembly loaded.</returns>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="pluginAssemblyFiles" /> parameter is null</exception>
        public static IReadOnlyList<PlugInAssemblyState> ValidateAndLoadAssemblies(this GorgonMefPlugInCache pluginCache, IEnumerable<string> pluginAssemblyFiles, IGorgonLog log)
        {
            if (pluginAssemblyFiles is null)
            {
                throw new ArgumentNullException(nameof(pluginAssemblyFiles));
            }

            var records = new List<PlugInAssemblyState>();

            // We use this to determine whether the plug in can be loaded into the current platform.
            AssemblyPlatformType currentPlatform = Environment.Is64BitProcess ? AssemblyPlatformType.x64 : AssemblyPlatformType.x86;

            foreach (string file in pluginAssemblyFiles.Select(item => Path.GetFullPath(item)))
            {
                string fileName = Path.GetFileName(file);

                // If we've already got the assembly loaded into this cache, then there's no need to try and load it.
                if (pluginCache.PlugInAssemblies?.Any(item => string.Equals(item, file, StringComparison.OrdinalIgnoreCase)) ?? false)
                {
                    continue;
                }

                if (!File.Exists(file))
                {
                    log.Print($"ERROR: Plug in '{file}' was not found.", LoggingLevel.Verbose);
                    records.Add(new PlugInAssemblyState(file, Resources.GOREDIT_PLUGIN_LOAD_FAIL_NOT_FOUND, false));
                    continue;
                }

                (bool isManaged, AssemblyPlatformType platformType) = GorgonMefPlugInCache.IsManagedAssembly(file);

                if ((!isManaged) || (platformType == AssemblyPlatformType.Unknown))
                {
                    log.Print($"WARNING: Skipping '{file}'. Not a valid .NET assembly.", LoggingLevel.Verbose);
                    records.Add(new PlugInAssemblyState(file, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_NOT_DOT_NET, fileName), false));
                    continue;
                }

                // Ensure that our platform type matches (AnyCPU is exempt and will always run, and DLLs don't allow Prefer 32 bit).
                if ((currentPlatform == AssemblyPlatformType.x86) && (platformType == AssemblyPlatformType.x64))
                {
                    log.Print($"ERROR: Cannot load assembly '{file}', currently executing in an x86 environment, but the assembly is x64.", LoggingLevel.Simple);
                    records.Add(new PlugInAssemblyState(file, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_PLATFORM_MISMATCH, fileName, platformType, currentPlatform), true));
                    continue;
                }

                if ((currentPlatform == AssemblyPlatformType.x64) && (platformType == AssemblyPlatformType.x86))
                {
                    log.Print($"ERROR: Cannot load assembly '{file}', currently executing in an x64 environment, but the assembly is x86.", LoggingLevel.Simple);
                    records.Add(new PlugInAssemblyState(file, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_PLATFORM_MISMATCH, fileName, platformType, currentPlatform), true));
                    continue;
                }

                try
                {
                    log.Print($"Loading plug in assembly '{file}'...", LoggingLevel.Simple);
                    pluginCache.LoadPlugInAssemblies(Path.GetDirectoryName(file), fileName);

                    records.Add(new PlugInAssemblyState(file, string.Empty, true));
                }
                catch (Exception ex)
                {
                    log.Print($"ERROR: Cannot load plug in assembly '{file}'.", LoggingLevel.Simple);
                    log.LogException(ex);
                    records.Add(new PlugInAssemblyState(file, string.Format(Resources.GOREDIT_PLUGIN_LOAD_FAIL_EXCEPTION, fileName, ex.Message), true));
                }
            }

            return records;
        }
    }
}


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PadIntroComponent } from './pad-intro/pad-intro.component';

import gridStyle from '../../../../public/typo.css';
import template from './pad.component.html';

@Component({
        selector: 'app-pad',
        template,
        gridStyle,
        directives:[PadIntroComponent]
})
export class PadComponent {
        currentSection: string = '생리컵';
        selectedIndex: Index;

        IndexList = [
            { id:0, name: '생리컵', name_eng: 'intro', endScroll: '#intro' },
            { id:1, name: '생리컵이란?', name_eng: 'intro', endScroll: '#intro' },
            { id:2, name: '제품정보', name_eng: 'purchasing', endScroll: '#purchasing' },
            { id:3, name: '역사', name_eng: 'history', endScroll: '#history' },
            { id:4, name: '장단점', name_eng: 'proscons', endScroll: '#proscons' },
            { id:5, name: '생김새', name_eng: 'shape', endScroll: '#shape' },
            { id:6, name: '사용법', name_eng: 'usage', endScroll: '#usage' }
        ];

        constructor(private router: Router) { }

        ngOnInit(): void{
            this.selectedIndex = { id:0, name: '생리컵', name_eng: 'intro', endScroll: '#intro' };
        }

        onSelect(index):void {
            console.log(index);
            this.selectedIndex = index;
        }

        navigateDir(e: event) {
            console.log(e.target.id);

            let toId: number = (e.target.id === 'goToBefore') ? -1 : 1;
            let toIndex: number = (this.selectedIndex.id + toId);

            this.selectedIndex = this.IndexList.find(index => index.id === toIndex);

        }

}


text:
package com.nonzeroapps.whatisnewdialog.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.viewpager.widget.ViewPager;

import com.nonzeroapps.whatisnewdialog.R;
import com.nonzeroapps.whatisnewdialog.adapter.ImageViewPagerAdapter;
import com.nonzeroapps.whatisnewdialog.object.DialogSettings;
import com.nonzeroapps.whatisnewdialog.object.NewFeatureItem;
import com.nonzeroapps.whatisnewdialog.util.SharedPrefHelper;
import com.nonzeroapps.whatisnewdialog.view.InkPageIndicator;
import com.xgc1986.parallaxPagerTransformer.ParallaxPagerTransformer;

import java.util.ArrayList;

/**
 * Created by berkayturanci on 01/08/2017.
 */

public class WhatIsNewDialogFragment extends DialogFragment {

    private static final String NEW_FEATURE_ITEM_LIST = "newFeatureItemList";
    private static final String DIALOG_SETTINGS = "dialogSettings";

    private ViewPager mImageViewPager;
    private InkPageIndicator mInkPageIndicator;
    private ArrayList<NewFeatureItem> mNewFeatureItemArrayList;
    private DialogInterface.OnClickListener mPositiveButtonListener;
    private DialogInterface.OnClickListener mNeutralButtonListener;

    public static WhatIsNewDialogFragment newInstance(ArrayList<NewFeatureItem> newFeatureItemArrayList, DialogSettings dialogSettings, DialogInterface.OnClickListener positiveButtonListener, DialogInterface.OnClickListener neutralButtonListener) {
        WhatIsNewDialogFragment whatIsNewDialogFragment = new WhatIsNewDialogFragment();

        whatIsNewDialogFragment.setPositiveButtonListener(positiveButtonListener);
        whatIsNewDialogFragment.setNeutralButtonListener(neutralButtonListener);

        Bundle args = new Bundle();
        args.putParcelableArrayList(NEW_FEATURE_ITEM_LIST, newFeatureItemArrayList);
        args.putParcelable(DIALOG_SETTINGS, dialogSettings);
        whatIsNewDialogFragment.setArguments(args);

        return whatIsNewDialogFragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Context context = getContext();

        View view = getActivity().getLayoutInflater().inflate(R.layout.newfeaturedialog, null);

        mNewFeatureItemArrayList = getArguments().getParcelableArrayList(NEW_FEATURE_ITEM_LIST);
        final DialogSettings dialogSettings = getArguments().getParcelable(DIALOG_SETTINGS);
        mImageViewPager = (ViewPager) view.findViewById(R.id.viewPager);
        mInkPageIndicator = (InkPageIndicator) view.findViewById(R.id.indicator);
        mImageViewPager.setPageTransformer(false, new ParallaxPagerTransformer(R.id.imageView));

        initPage(dialogSettings);

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setView(view);

        if (dialogSettings != null) {
            if (dialogSettings.isShowTitle()) {
                builder.setTitle(dialogSettings.getTitleText(context));
            }

            if (dialogSettings.isShowPositiveButton()) {
                builder.setPositiveButton(dialogSettings.getPositiveText(context), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPrefHelper.setSeenBefore(context, dialogSettings.getVersionName(context), true);

                        if (mPositiveButtonListener != null) {
                            mPositiveButtonListener.onClick(dialog, which);
                        }
                    }
                });
            }

            if (dialogSettings.isShowNeutralButton()) {
                builder.setNeutralButton(dialogSettings.getNeutralText(context), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (mNeutralButtonListener != null) {
                            mNeutralButtonListener.onClick(dialog, which);
                        }
                    }
                });
            }

            builder.setCancelable(dialogSettings.isCancelable());
        }

        return builder.create();
    }

    private void initPage(DialogSettings dialogSettings) {
        ImageViewPagerAdapter adapter = new ImageViewPagerAdapter(getContext(), mNewFeatureItemArrayList,
                dialogSettings.usePaletteForDescBackground(),
                dialogSettings.usePaletteForImageBackground());

        mImageViewPager.setAdapter(adapter);
        mInkPageIndicator.setViewPager(mImageViewPager);
    }

    public void setPositiveButtonListener(DialogInterface.OnClickListener positiveButtonListener) {
        mPositiveButtonListener = positiveButtonListener;
    }

    public void setNeutralButtonListener(DialogInterface.OnClickListener neutralButtonListener) {
        mNeutralButtonListener = neutralButtonListener;
    }
}


text:
#ifndef __itktubePDFSegmenterParzen_h
#define __itktubePDFSegmenterParzen_h

#include "itktubePDFSegmenterBase.h"

#include <itkImage.h>
#include <itkListSample.h>

#include <vector>

namespace itk
{

namespace tube
{

#define PARZEN_MAX_NUMBER_OF_FEATURES 4

template< class TImage, class TLabelMap >
class PDFSegmenterParzen : public PDFSegmenterBase< TImage, TLabelMap >
{
public:

  typedef PDFSegmenterParzen                         Self;
  typedef PDFSegmenterBase< TImage, TLabelMap >      Superclass;
  typedef SmartPointer< Self >                       Pointer;
  typedef SmartPointer< const Self >                 ConstPointer;

  itkTypeMacro( PDFSegmenterParzen, PDFSegmenterBase );

  itkNewMacro( Self );

  //
  // Superclass Typedefs
  //
  typedef TImage                               InputImageType;

  itkStaticConstMacro( ImageDimension, unsigned int,
    TImage::ImageDimension );

  typedef FeatureVectorGenerator< InputImageType >
                                               FeatureVectorGeneratorType;
  typedef typename FeatureVectorGeneratorType::FeatureValueType
                                               FeatureValueType;
  typedef typename FeatureVectorGeneratorType::FeatureVectorType
                                               FeatureVectorType;
  typedef typename FeatureVectorGeneratorType::FeatureImageType
                                               FeatureImageType;

  typedef TLabelMap                            LabelMapType;
  typedef typename LabelMapType::PixelType     LabelMapPixelType;

  typedef int                                  ObjectIdType;
  typedef std::vector< ObjectIdType >          ObjectIdListType;

  typedef float                                ProbabilityPixelType;
  typedef Image< ProbabilityPixelType, TImage::ImageDimension >
                                               ProbabilityImageType;

  typedef std::vector< double >                VectorDoubleType;
  typedef std::vector< int >                   VectorIntType;
  typedef std::vector< unsigned int >          VectorUIntType;

  //
  // Custom Typedefs
  //
  typedef float                                HistogramPixelType;

  typedef Image< HistogramPixelType, PARZEN_MAX_NUMBER_OF_FEATURES >
    HistogramImageType;

  typedef HistogramPixelType                   PDFPixelType;
  typedef HistogramImageType                   PDFImageType;

  typedef Image< LabelMapPixelType, PARZEN_MAX_NUMBER_OF_FEATURES >
    LabeledFeatureSpaceType;

  //
  // Methods
  //
  itkSetMacro( HistogramSmoothingStandardDeviation, double );
  itkGetMacro( HistogramSmoothingStandardDeviation, double );
  itkSetMacro( OutlierRejectPortion, double );
  itkGetMacro( OutlierRejectPortion, double );

  typename PDFImageType::Pointer GetClassPDFImage(
    unsigned int classNum ) const;

  void SetClassPDFImage( unsigned int classNum,
    typename PDFImageType::Pointer classPDF );

  const VectorUIntType & GetNumberOfBinsPerFeature( void ) const;
  void             SetNumberOfBinsPerFeature( const VectorUIntType & nBin );
  const VectorDoubleType & GetBinMin( void ) const;
  void             SetBinMin( const VectorDoubleType & binMin );
  const VectorDoubleType & GetBinSize( void ) const;
  void             SetBinSize( const VectorDoubleType & binMin );

  /** Given one PDF per class, generate a labelmap of feature space */
  void GenerateLabeledFeatureSpace( void );

  void SetLabeledFeatureSpace( typename LabeledFeatureSpaceType::Pointer
    labeledFeatureSpace );

  typename LabeledFeatureSpaceType::Pointer GetLabeledFeatureSpace( void )
    const;

  virtual void Update( void );

  //
  // Must overwrite
  //
  virtual ProbabilityPixelType GetClassProbability( unsigned int
    classNum, const FeatureVectorType & fv ) const;

protected:

  PDFSegmenterParzen( void );
  virtual ~PDFSegmenterParzen( void );

  virtual void GeneratePDFs( void );

  void PrintSelf( std::ostream & os, Indent indent ) const;

private:

  PDFSegmenterParzen( const Self & );          // Purposely not implemented
  void operator = ( const Self & );      // Purposely not implemented

  // Superclass typedefs
  typedef std::vector< typename ProbabilityImageType::Pointer >
    ProbabilityImageVectorType;

  typedef std::vector< ProbabilityPixelType > ListVectorType;
  typedef std::vector< ListVectorType >       ListSampleType;
  typedef std::vector< ListSampleType >       ClassListSampleType;

  // Custom typedefs
  typedef std::vector< typename HistogramImageType::Pointer >
    ClassHistogramImageType;

  ClassHistogramImageType         m_InClassHistogram;
  VectorDoubleType                m_HistogramBinMin;
  VectorDoubleType                m_HistogramBinSize;
  VectorUIntType                  m_HistogramNumberOfBin;

  double                          m_OutlierRejectPortion;

  double                          m_HistogramSmoothingStandardDeviation;

  typename LabeledFeatureSpaceType::Pointer m_LabeledFeatureSpace;

}; // End class PDFSegmenterParzen

} // End namespace tube

} // End namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itktubePDFSegmenterParzen.hxx"
#endif

#endif // End !defined(__itktubePDFSegmenterParzen_h)


text:
layout: docs
title: Media object
description: Documentation and examples for Bootstrap's media object to construct highly repetitive components like blog comments, tweets, and the like.
group: layout
toc: true
---

## Example

The [media object](http://www.stubbornella.org/content/2010/06/25/the-media-object-saves-hundreds-of-lines-of-code/) helps build complex and repetitive components where some media is positioned alongside content that doesn't wrap around said media. Plus, it does this with only two required classes thanks to flexbox.

Below is an example of a single media object. Only two classes are required—the wrapping `.media` and the `.media-body` around your content. Optional padding and margin can be controlled through [spacing utilities]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/spacing/).

{% capture example %}

Media heading

    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

{% endcapture %}
{% include example.html content=example %}

{% capture callout %}
##### Flexbug #12: Inline elements aren't treated as flex items

Internet Explorer 10-11 do not render inline elements like links or images (or `::before` and `::after` pseudo-elements) as flex items. The only workaround is to set a non-inline `display` value (e.g., `block`, `inline-block`, or `flex`). We suggest using `.d-flex`, one of our [display utilities]({{ site.baseurl }}/docs/{{ site.docs_version }}/utilities/display/), as an easy fix.

**Source:** [Flexbugs on GitHub](https://github.com/philipwalton/flexbugs#flexbug-12)
{% endcapture %}
{% include callout.html content=callout type="warning" %}

## Nesting

Media objects can be infinitely nested, though we suggest you stop at some point. Place nested `.media` within the `.media-body` of a parent media object.

{% capture example %}

Media heading

    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Media heading

        Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

{% endcapture %}
{% include example.html content=example %}

## Alignment

Media in a media object can be aligned with flexbox utilities to the top (default), middle, or end of your `.media-body` content.

{% capture example %}

Top-aligned media

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

{% endcapture %}
{% include example.html content=example %}

{% capture example %}

Center-aligned media

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

{% endcapture %}
{% include example.html content=example %}

{% capture example %}

Bottom-aligned media

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

{% endcapture %}
{% include example.html content=example %}

## Order

Change the order of content in media objects by modifying the HTML itself, or by adding some custom flexbox CSS to set the `order` property (to an integer of your choosing).

{% capture example %}

Media object

    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

{% endcapture %}
{% include example.html content=example %}

## Media list

Because the media object has so few structural requirements, you can also use these classes on list HTML elements. On your `<ul>` or `<ol>`, add the `.list-unstyled` to remove any browser default list styles, and then apply `.media` to your `<li>`s. As always, use spacing utilities wherever needed to fine tune.

{% capture example %}

List-based media object

      Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

List-based media object

      Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

List-based media object

      Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

{% endcapture %}
{% include example.html content=example %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 1998 Academia Sinica Computing Center -->
<!-- Permission to use and distribute granted under MPL -->
<!-- Email corrections to ricko@gate.sinica.net.tw -->
<test type="io1">
	<name>Chinese Test #1: UTF-8</name>
	<data>This file is the null test. It is a UTF-8 encoded
	file with no non-ASCII characters (i.e. it is also an
	ASCII or iso-8859-n file).
	</data>
	<data>The XML header of this file is
	<?xml encoding="UTF-8"?>.
	</data>
</test>


text:
/**
 * @author Brandon Alexander - baalexander@gmail.com
 */

var ServiceResponse = require('./ServiceResponse');

/**
 * A ROS service client.
 *
 * @constructor
 * @params options - possible keys include:
 *   * ros - the ROSLIB.Ros connection handle
 *   * name - the service name, like /add_two_ints
 *   * serviceType - the service type, like 'rospy_tutorials/AddTwoInts'
 */
function Service(options) {
  options = options || {};
  this.ros = options.ros;
  this.name = options.name;
  this.serviceType = options.serviceType;
}

/**
 * Calls the service. Returns the service response in the callback.
 *
 * @param request - the ROSLIB.ServiceRequest to send
 * @param callback - function with params:
 *   * response - the response from the service request
 * @param failedCallback - the callback function when the service call failed (optional). Params:
 *   * error - the error message reported by ROS
 */
Service.prototype.callService = function(request, callback, failedCallback) {
  var serviceCallId = 'call_service:' + this.name + ':' + (++this.ros.idCounter);

  if (callback || failedCallback) {
    this.ros.once(serviceCallId, function(message) {
      if (message.result !== undefined && message.result === false) {
        if (typeof failedCallback === 'function') {
          failedCallback(message.values);
        }
      } else if (typeof callback === 'function') {
        callback(new ServiceResponse(message.values));
      }
    });
  }

  var call = {
    op : 'call_service',
    id : serviceCallId,
    service : this.name,
    args : request
  };
  this.ros.callOnConnection(call);
};

module.exports = Service;


text:
require 'spec_helper'

describe CsvRowModel::Model::Attributes do
  describe "class" do
    let(:klass) { BasicRowModel }

    describe "::column_names" do
      subject { klass.column_names }
      specify { expect(subject).to eql %i[string1 string2] }
    end

    describe "::format_header" do
      let(:header) { 'user_name' }
      subject { BasicRowModel.format_header(header, nil) }

      it "returns the header" do
        expect(subject).to eql header
      end
    end

    describe "::headers" do
      let(:headers) { [:string1, 'String 2'] }
      subject { klass.headers }

      it "returns an array with header column names" do
        expect(subject).to eql headers
      end
    end

    describe "::format_cell" do
      let(:cell) { "the_cell" }
      subject { BasicRowModel.format_cell(cell, nil, nil) }

      it "returns the cell" do
        expect(subject).to eql cell
      end
    end

    context "with custom class" do
      let(:klass) { Class.new { include CsvRowModel::Model } }

      describe "::column" do
        subject { klass.send(:column, :blah) }

        it "calls ::check_options with the args" do
          expect(klass).to receive(:check_options).with(CsvRowModel::Model::Header,
                                                        CsvRowModel::Import::ParsedModel::Model,
                                                        CsvRowModel::Import::Attribute,
                                                        klass,
                                                        {}).once.and_call_original
          subject
        end

        context "with invalid option" do
          subject { klass.send(:column, :blah, invalid_option: true) }

          it "raises error" do
            expect { subject }.to raise_error("Invalid option(s): [:invalid_option]")
          end
        end
      end

      describe "::merge_options" do
        before { klass.send(:column, :blah, type: Integer) }
        subject { klass.send(:merge_options, :blah, default: 1) }

        it "merges the option" do
          result = { blah: { type: Integer, default: 1 }}

          expect { subject }.to change { klass.columns }.from(blah: { type: Integer }).to(result)
          expect(klass.columns_object.raw_value).to eql(result)
        end

        context "with child class class" do
          let(:child_class) { Class.new(klass) }

          subject do
            klass.send(:merge_options, :blah, default: 1)
            child_class.send(:merge_options, :blah, header: "Blah")
          end

          it "passes merged option to child, but not to parent" do
            expect(klass.columns).to eql(blah: { type: Integer })
            expect(klass.columns_object.raw_value).to eql(blah: { type: Integer })

            expect(child_class.columns).to eql(blah: { type: Integer })
            expect(child_class.columns_object.raw_value).to eql({})

            subject

            expect(klass.columns).to eql(blah: { type: Integer, default: 1 })
            expect(klass.columns_object.raw_value).to eql(blah: { type: Integer, default: 1 })

            expect(child_class.columns).to eql(blah: { type: Integer, default: 1, header: "Blah" })
            expect(child_class.columns_object.raw_value).to eql(blah: { header: "Blah" })
          end

          context "with multiple columns" do
            before { %i[blah1 blah2].each {|column_name| klass.send(:column, column_name, type: Integer) } }
            subject { child_class.send(:merge_options, :blah1, default: 1) }

            it "keeps the column_names in the same order " do
              subject
              expect(child_class.column_names).to eql %i[blah blah1 blah2]
            end
          end
        end
      end

      describe "::class_to_parse_lambda" do
        subject { klass.class_to_parse_lambda }

        it "returns the CLASS_TO_PARSE_LAMBDA" do
          expect(subject).to eql CsvRowModel::Import::Attributes::CLASS_TO_PARSE_LAMBDA
        end
      end

      describe "::custom_check_options" do
        subject { klass.custom_check_options(options) }

        context "with invalid :type Option" do
          let(:options) { { type: Object } }

          it "raises exception" do
            expect { subject }.to raise_error(":type must be Boolean, String, Integer, Float, DateTime, Date")
          end

          context "with ::class_to_parse_lambda overwritten" do
            before do
              _override = override
              klass.define_singleton_method(:class_to_parse_lambda) { super().merge(_override) }
            end
            let(:override) { { Hash => ->(s) { JSON.parse(s) } } }

            it "raises a new type of exception" do
              expect { subject }.to raise_error(":type must be Boolean, String, Integer, Float, DateTime, Date, Hash")
            end
          end
        end
      end
    end
  end
end


text:
(function() {

    'use strict';

    angular.module('myApp.sms').controller('SmsCtrl', SmsCtrl);

    SmsCtrl.$inject = ['smsFactory', '$scope'];

    function SmsCtrl(smsFactory, $scope) {

        var vm = this;

        vm.sendMessage = sendMessage;
        vm.sms = {};

        function sendMessage() {
            smsFactory.send(vm.sms).then(success, error);
        }

        function getMessage() {
            smsFactory.get().then(successGet, errorGet);
        }

        function success() {
            vm.messageSuccessfullySent = true;
        }

        function successGet(data) {
            vm.messageSuccessfullyGot = data;
        }

        function errorGet() {
            vm.messageSendError = true;
        }
    }

})();


text:
wget https://github.com/kubernetes/kubernetes/releases/download/v1.2.0/kubernetes.tar.gz && \
tar xvzf kubernetes.tar.gz


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Leptosphaeria ammophilae (Lasch) Rehm, 1882

### Remarks
null


text:
import json
import string
import re

class JsonHandler(object):

    def __init__(self):
        return

    def strip_message(self, routermsg):
        ''' Remove  <SDN_ANNOUNCE> delimiters from message received
            from the router.
        '''
        msg = re.sub(r'<.+?>', '', routermsg)
        return msg

    def verify_json(self, msg):
        ''' Verify that the message is encoded in JSON '''
        try:
            route_msg = json.loads(msg)
        except ValueError as e:
            return False
        return True

    def determine_action(self, routermsg):
        ''' Determine that the message type.
            'added' - for new routes
            'removed' - for withdrawn routes
        '''
        msg = json.loads(routermsg)
        for action, route_info in msg.items():
            if action == "added":
                route = route_info[0]
                return action, route
            elif action == "removed":
                route = route_info[0]
                return action, route
            else:
                return None, None

    def check_routeinfo(self, route):
        ''' Verify that the message has the information needed for it to be
            processed like Network address, netmask and next-hop address.
        '''
        key_present = False
        value_present = False
        true_values = 0

        if 'prefix' in route and 'mask' in route and 'via' in route:
            key_present = True

        for info, value in route.items():
            # value =  jsonroute[info]
            if type(value) is str:
                if len(value) != 0:
                    true_values += 1
                else:
                    pass
            elif type(value) is list:
                if len(value) != 0:
                    true_values += 1
                else:
                    pass
            elif type(value) is dict:
                if len(value) != 0:
                    true_values += 1
                else:
                    pass
            elif type(value) is int and info == 'mask':
                if value >= 0 and value < 128:
                    true_values += 1
                else:
                    pass
            elif type(value) is int and not info == 'mask':
                if value >= 0:
                    true_values += 1
                else:
                    pass
            else:
                length = len(str(value))
                if length != 0:
                    true_values += 1
                else:
                    pass

        length = len(route)
        if length == true_values:
            value_present = True

        return key_present, value_present

    def fix_route(self, msg):
        ''' Fix received messages that are not properly encoded. '''

        if type(msg) is str:
            info = repr(msg)
            str_len = len(info)
            curly_close_list = []
            curly_start = string.find(info, "{")
            for char in range(0, str_len):
                if info[char] == '}':
                    curly_close_list.append(char)

            if not curly_close_list:
                if curly_start != -1:
                    info = info + "}"
                    curly_end = len(info) + 1
                    routefix_json = info[curly_start:curly_end]
                else:
                    routefix_json = None
            else:
                curly_end = max(curly_close_list) + 1
                routefix_json = info[curly_start:curly_end]

        elif type(msg) is dict:
            routefix_json = json.dumps(msg)

        elif type(msg) is list:
            routefix_json = json.dumps(msg)

        else:
            routefix_json = None

        return routefix_json

    def hand_over_route(self, route):
        list_info = []
        for info, value in route.items():
            list_info.append(value)

        return list_info


text:
using System.Globalization;

namespace Autofac.Configuration.Test;

public static class TestCulture
{
    public static void With(CultureInfo culture, Action test)
    {
        var originalCulture = Thread.CurrentThread.CurrentCulture;
        var originalUICulture = Thread.CurrentThread.CurrentUICulture;
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
        CultureInfo.CurrentCulture.ClearCachedData();
        CultureInfo.CurrentUICulture.ClearCachedData();
        try
        {
            test?.Invoke();
        }
        finally
        {
            Thread.CurrentThread.CurrentCulture = originalCulture;
            Thread.CurrentThread.CurrentUICulture = originalUICulture;
            CultureInfo.CurrentCulture.ClearCachedData();
            CultureInfo.CurrentUICulture.ClearCachedData();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using FsCheck;

namespace Sharper.C.Testing.Laws
{

using static Properties.RelationPropertiesModule;

public static class OrderingLaws
{
    public static Invariant For
      ( Func ltEq
      , Func eq
      , Arbitrary arbA
      )
    =>
        "Ordering Laws"
        .All
          ( IsTotalOrder(ltEq, eq, arbA)
          , EqualityLaws.For(eq, arbA)
          );

    public static Invariant For(Arbitrary arbA)
      where A : IEquatable, IComparable
    =>
        For
          ( (x, y) => x.CompareTo(y) <= 0
          , (x, y) => x.Equals(y)
          , arbA
          );

    public static Invariant For
      ( IComparer comparer
      , IEqualityComparer eqComparer
      , Arbitrary arbA
      )
    =>
        For
          ( (x, y) => comparer.Compare(x, y) <= 0
          , eqComparer.Equals
          , arbA
          );
}

}


text:
package treeton.prosody.mdlcompiler.fsm;

import treeton.core.util.EntryComparator;

import java.awt.*;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.List;

public class MeterStatistics extends AbstractMap {
    class CellInfo {
        double rating;
        double overstressed;
        double unstressed;

        public CellInfo(double rating, double overstressed, double unstressed) {
            this.rating = rating;
            this.overstressed = overstressed;
            this.unstressed = unstressed;
        }

        @Override
        public String toString() {
            String os = df.format(overstressed);
            String us = df.format(unstressed);
            if ("0".equals(os) && "0".equals(us)) {
                return df.format(rating);
            } else {
                return df.format(rating)+"("+ os +","+ us +")";
            }

        }
    }

    class Info {
        Map<Integer,CellInfo> ratingsByNumberOfFoots = new HashMap<Integer, CellInfo>();

        public Info() {
        }

        public Info(Info value) {
            ratingsByNumberOfFoots.putAll(value.ratingsByNumberOfFoots);
        }

        public void merge(Info otherInfo, MergeMode mode) {
            for (Map.Entry<Integer, CellInfo> entry : ratingsByNumberOfFoots.entrySet()) {
                CellInfo d = otherInfo.ratingsByNumberOfFoots.get(entry.getKey());
                if (d != null) {
                    entry.setValue(merge(mode, d, entry.getValue()));
                } else {
                    entry.setValue(merge(mode, new CellInfo(0,0,0), entry.getValue()));
                }
            }
            for (Map.Entry<Integer, CellInfo> entry : otherInfo.ratingsByNumberOfFoots.entrySet()) {
                CellInfo d = ratingsByNumberOfFoots.get(entry.getKey());
                if (d == null) {
                    ratingsByNumberOfFoots.put(entry.getKey(),merge(mode, new CellInfo(0,0,0), entry.getValue()));
                }
            }
        }

        private CellInfo merge(MergeMode mode, CellInfo d, CellInfo v) {
            CellInfo value=new CellInfo(0,0,0);

            if (mode == MergeMode.AVERAGE) {
                value.rating = (v.rating + d.rating) / 2;
                value.overstressed = (v.overstressed + d.overstressed) / 2;
                value.unstressed = (v.unstressed + d.unstressed) / 2;
            } else if (mode == MergeMode.MAX) {
                throw new UnsupportedOperationException();
            }
            return value;
        }
    }

    private Map<Meter,Info> stats = new HashMap<Meter, Info>();

    public void add(Meter meter, int numberOfFoots, double value, double overstressed, double unstressed) {
        Info info = stats.get(meter);
        if (info == null) {
            info = new Info();
            stats.put(meter,info);
        }

        info.ratingsByNumberOfFoots.put(numberOfFoots,new CellInfo(value,overstressed,unstressed));
    }

    public enum MergeMode {
        AVERAGE,
        MAX
    }

    public void merge(MeterStatistics other, MergeMode mode) {
        for (Map.Entry<Meter, Info> entry : stats.entrySet()) {
            Info otherInfo = other.stats.get(entry.getKey());
            if (otherInfo != null) {
                entry.getValue().merge(otherInfo,mode);
            }
        }
        for (Map.Entry<Meter, Info> entry : other.stats.entrySet()) {
            Info info = stats.get(entry.getKey());
            if (info == null) {
                stats.put(entry.getKey(), new Info(entry.getValue()));
            }
        }
    }

    @Override
    public Set entrySet() {
        return stats.entrySet();
    }

    private int toStringFontSize=3;
    static DecimalFormat df = new DecimalFormat();

    static {
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setDecimalSeparator('.');
        df.setDecimalFormatSymbols(dfs);
        df.setMaximumFractionDigits(2);
    }

    public String toString() {
        StringBuffer buf = new StringBuffer();

        TreeSet<Integer> allFoots = new TreeSet<Integer>();

        for (Info info : stats.values()) {
            allFoots.addAll(info.ratingsByNumberOfFoots.keySet());
        }

        buf.append("\n
\n");
        buf.append("
\n");
        buf.append("    ").
                append("Метр\\Стопность	\n");
        for (Integer allFoot : allFoots) {
            buf.append("    ").append(allFoot).append("	\n");
        }
        buf.append("
");

        List<Map.Entry<Meter, Info>> entries = new ArrayList<Entry<Meter, Info>>(stats.entrySet());
        //noinspection unchecked
        Collections.sort(entries, new EntryComparator());

        for (Map.Entry<Meter, Info> entry : entries) {
            buf.append("
\n");
            buf.append("    ").
                    append(entry.getKey().getName()).append("	\n");
            for (Integer allFoot : allFoots) {
                CellInfo d = entry.getValue().ratingsByNumberOfFoots.get(allFoot);
                if (d == null) {
                    d = new CellInfo(0,0,0);
                }
                buf.append("    ").
                        append(d).append("	\n");
            }
            buf.append("
");
        }
        buf.append("
\n");

        return buf.toString();
    }

    private String getColor(Meter meter) {
        int p = meter.getPriority();

        Color c = Color.WHITE;

        while ( p > 0 ) {
            c = c.darker();
            p--;
        }

        return "rgb("+c.getRed()+","+c.getGreen()+","+c.getBlue()+")";
    }

    public void setToStringFontSize(int toStringFontSize) {
        this.toStringFontSize = toStringFontSize;
    }

    public Map<Meter,Set<Integer>> findMetersAboveThreshold() {
        Map<Meter,Set<Integer>> result = new HashMap<Meter, Set<Integer>>();

        for (Entry<Meter, Info> entry : stats.entrySet()) {
            Meter m = entry.getKey();

            for (Entry<Integer, CellInfo> e : entry.getValue().ratingsByNumberOfFoots.entrySet()) {
                if (e.getValue().rating >= m.getThreshold()) {
                    Set<Integer> set = result.get(m);
                    if (set == null) {
                        set = new HashSet<Integer>();
                        result.put(m,set);
                    }
                    set.add(e.getKey());
                }
            }
        }

        return result;
    }

    public Map<Meter,Set<Integer>> findBestMeters() {
        Map<Meter,Set<Integer>> result = new HashMap<Meter, Set<Integer>>();

        double max = 0;

        for (Entry<Meter, Info> entry : stats.entrySet()) {
            for (Entry<Integer, CellInfo> e : entry.getValue().ratingsByNumberOfFoots.entrySet()) {
                if (max < e.getValue().rating) {
                    max = e.getValue().rating;
                }
            }
        }

        for (Entry<Meter, Info> entry : stats.entrySet()) {
            Meter m = entry.getKey();

            for (Entry<Integer, CellInfo> e : entry.getValue().ratingsByNumberOfFoots.entrySet()) {
                if (e.getValue().rating == max) {
                    Set<Integer> set = result.get(m);
                    if (set == null) {
                        set = new HashSet<Integer>();
                        result.put(m,set);
                    }
                    set.add(e.getKey());
                }
            }
        }

        return result;
    }

    public Double getUnstressed(Meter key, Integer integer) {
        CellInfo ci = getCellInfo(key, integer);
        if (ci == null)
            return null;

        return ci.unstressed;
    }

    public Double getOverstressed(Meter key, Integer integer) {
        CellInfo ci = getCellInfo(key, integer);
        if (ci == null)
            return null;

        return ci.overstressed;
    }

    private CellInfo getCellInfo(Meter key, Integer integer) {
        Info info = stats.get(key);

        if (info == null)
            return null;

        CellInfo ci = info.ratingsByNumberOfFoots.get(integer);

        if (ci == null)
            return null;
        return ci;
    }

}


text:
/**
 * asset-model file for ndp-video-spa on 27-Apr-16.
 */

define('assets-asset-model', ['jquery', 'knockout'], function ($, ko) {
    Date = window.Date;
    var wait = window.$PAGE_WAIT,
        _console = window.$page.console.getInstance('Asset Model');

    //TODO
    //Identify Media Type
    //pull thumbnails

    function AssetModel(asset, playlistid, index) {
        this.json = asset;
        this.index = index || 0;

        var data = asset.video || asset.videos || asset.availableAssets,
            self = this;

        this.id = data.guid || null;
        this.mpxid = data.mpxId;
        this.feedUrl = null;
        this.playlistid = playlistid || (data.video_playlists[0]).playlist_id || null;
        this.title = data.title;
        this.description = asset.summary;
        this.canonical = data.canonicalUrl || false;

        this.image = data.thumbnail || false;
        this.thumbnail = _resizeThumbnail(data.thumbnail) || null;
        if (location.protocol == 'https:') {
          this.image = this.image.replace('http','https');
          this.thumbnail = this.thumbnail.replace('http','https');
        }
        this.source = asset.externalSource || null;
        this.islive = (data.videoType === "Non Broadcast Live Video");
        this.hascaption = data.hasCaption || false;

        this.url = null;
        this.caption = false;

        this.format = this.getFormat(data.videoAssets);
        this.type = this.captionType(data);
        this.bitrate = 0;
    }

    AssetModel.prototype = Object.create({
        constructor: AssetModel
    }, {
        timestamp: {value: Date.now()}
        , mapMPXModel: {
            value: mapMPXModel,
            enumerable: true
        }
        , captionType: {
            value: captionType
        }
        , getFormat: {
            value: getFormat
        }
        , resizeThumbnail: {
            value: _resizeThumbnail
        }
        , video: {
            get: function () {
                return this.json.video
                    || this.json.videos
                    || this.json.availableAssets;
            }
        }
    });

    return AssetModel;

    function mapMPXModel(MPXMediaAssetModel) {
        if (!(MPXMediaAssetModel instanceof Function)) return;
        if (this.mpxMediaAsset instanceof MPXMediaAssetModel)
            return this.mpxMediaAsset;

        this.mpxMediaAsset = new MPXMediaAssetModel(this.video);

        var data = {
            url: this.mpxMediaAsset.url
        };
        if (this.mpxMediaAsset.getVideoData instanceof Function) {
            data = this.mpxMediaAsset.getVideoData();
        }
        this.caption = (data.cc || false);
        this.hascaption = !!(this.caption) || this.hascaption;
        this.url = data.url;

        return this.mpxMediaAsset;
    }

    function captionType(asset) {
        var captionType = "none";
        if (asset.captionLinks && asset.captionLinks['web-vtt']) {
            if (asset.captionLinks['web-vtt'].indexOf('snappy') > 0) {
                captionType = "snappy";
            } else {
                captionType = "nbc";
            }
        } else {
            captionType = this.format;
        }
        return captionType;
    }

    function getFormat(rawArray) {
        var once = false,
            lln = false,
            live = false;

        var i = rawArray.length,
            format = null,
            asset = null,
            bitRate = null;

        while (i--) {
            asset = rawArray[i];
            if (!asset) return format;
            bitRate = parseInt(asset.bitRate, 10);

            if (asset.format === "MPEG4") {
                if (bitRate === 0) {
                    once = true;
                } else {
                    lln = 'llnHigh_llnLow';
                }
            } else if (asset.format === "F4M" || asset.format === "M3U") {
                live = 'live';
            }
        }

        if (live) {
            format = live
        } else if (lln) {
            format = 'llnHigh_llnLow'
        } else if (asset.assetType === "FireTV-Once") {
            format = 'fireTV'
        } else {
            format = 'once'
        }

        return format;
    }

    function _resizeThumbnail(src, width) {
        if (!src)return src;
        var tail = src.substr(src.lastIndexOf('.'));
        var url = !width ? '.thumb-m' : '.nbcnews-video-reststate-' + width;
        src = src.replace(tail, url + tail);
        src = src.replace(/\/i\//, "\/j\/");
        return src;
    }

});


text:
function joinUrlWithQuery(url, query) {
    if (!query || !Object.keys(query).length) {
        return url;
    }
    var joiner = (url.indexOf('?') > -1) ? '&' : '?';
    return url + joiner + serializeObject(query);
}
exports.joinUrlWithQuery = joinUrlWithQuery;
function serializeObject(obj) {
    return Object.keys(obj).map(function (key) {
        return key + '=' + encodeURIComponent(obj[key]);
    }).join('&');
}
exports.serializeObject = serializeObject;


text:
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements. See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership. The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License. You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.stratos</groupId>
        <artifactId>stratos-components-parent</artifactId>
        <version>4.1.5-SNAPSHOT</version>
    </parent>

    <artifactId>org.apache.stratos.custom.handlers</artifactId>
    <packaging>bundle</packaging>
    <name>Apache Stratos - Custom Handlers</name>
    <description>Custom Handlers</description>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.user.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.user.api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.base</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.identity.oauth</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.core.services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.utils</artifactId>
        </dependency>

        <!-- Misc -->
        <dependency>
            <groupId>commons-lang.wso2</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>opensaml.wso2</groupId>
            <artifactId>opensaml2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.nimbusds.wso2</groupId>
            <artifactId>nimbus-jose-jwt</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>
                            ${project.artifactId}
                        </Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Private-Package>org.apache.stratos.custom.handlers.internal.*</Private-Package>
                        <Export-Package>
                            !org.apache.stratos.custom.handlers.internal.*,
                            org.apache.stratos.custom.handlers.*
                        </Export-Package>
                        <Import-Package>
                            org.wso2.carbon.core.*;version="${carbon.platform.imp.pkg.version.range}",
                            org.wso2.carbon.base.*;version="${carbon.base.imp.pkg.version.range}",
                            org.wso2.carbon.user.core.*;version="${carbon.platform.imp.pkg.version.range}",
                            org.wso2.carbon.utils.*;version="${carbon.platform.imp.pkg.version.range}",
                            org.wso2.carbon.identity.oauth2.*;version="${identity.oauth2.imp.pkg.version.range}",
                            org.wso2.carbon.identity.oauth.*;version="${identity.oauth2.imp.pkg.version.range}",
                            org.wso2.carbon.user.api.*;version="${carbon.user.api.imp.pkg.version.range}",

                            org.apache.commons.logging.*; version="${commons.logging.imp.pkg.version.range}",
                            org.apache.commons.lang.*;version="${commons.lang.imp.pkg.version.range}",
                            org.apache.commons.lang3.*;version="${commons.lang3.imp.pkg.version.range}",
                            org.opensaml.*;version="${opensaml2.imp.pkg.version.range}",
                            com.nimbusds.jose.*;version="${nimbus.jose.jwt.imp.pkg.version.range}",
                            com.nimbusds.jwt.*;version="${nimbus.jose.jwt.imp.pkg.version.range}",
                            *;resolution:=optional,
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package main

import (
	"github.com/flimzy/jsblob"
	"github.com/gopherjs/gopherjs/js"
	"github.com/gopherjs/jquery"
)

func downloadLogic() {
	jQuery("#downloadButton").On(jquery.CLICK, func() {
		go func() {
			setStatus("Compiling...", "bg-info")

			var err error
			data, _, err := compileCode()
			if err != nil {
				setStatus(err.Error(), "bg-danger")
				return
			}

			buffer := js.NewArrayBuffer(data)
			blob := jsblob.New([]interface{}{buffer}, jsblob.Options{Type: "application/octet-string"})

			link := js.Global.Get("document").Call("createElement", "a")
			link.Set("href", js.Global.Get("window").Get("URL").Call("createObjectURL", blob))

			link.Set("download", "fram.bin")
			link.Call("click")

			setStatus("Successfully created fram.bin", "bg-success")
		}()
	})
}


text:
package org.apereo.cas.adaptors.trusted.web.flow;

import org.apereo.cas.adaptors.trusted.authentication.principal.RemoteRequestPrincipalAttributesExtractor;
import org.apereo.cas.authentication.adaptive.AdaptiveAuthenticationPolicy;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.web.flow.resolver.CasDelegatingWebflowEventResolver;
import org.apereo.cas.web.flow.resolver.CasWebflowEventResolver;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This is {@link PrincipalFromRequestHeaderNonInteractiveCredentialsAction}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Slf4j
public class PrincipalFromRequestHeaderNonInteractiveCredentialsAction extends BasePrincipalFromNonInteractiveCredentialsAction {
    private static final int DEFAULT_SIZE = 20;
    private final String remotePrincipalHeader;

    public PrincipalFromRequestHeaderNonInteractiveCredentialsAction(final CasDelegatingWebflowEventResolver initialAuthenticationAttemptWebflowEventResolver,
                                                                     final CasWebflowEventResolver serviceTicketRequestWebflowEventResolver,
                                                                     final AdaptiveAuthenticationPolicy adaptiveAuthenticationPolicy,
                                                                     final PrincipalFactory principalFactory,
                                                                     final RemoteRequestPrincipalAttributesExtractor extractor,
                                                                     final String remotePrincipalHeader) {
        super(initialAuthenticationAttemptWebflowEventResolver, serviceTicketRequestWebflowEventResolver,
            adaptiveAuthenticationPolicy, principalFactory, extractor);
        this.remotePrincipalHeader = remotePrincipalHeader;
    }

    @Override
    public String getRemotePrincipalId(final HttpServletRequest request) {
        val principal = request.getUserPrincipal();
        if (principal != null) {
            LOGGER.debug("Principal [{}] found in request", principal.getName());
            return principal.getName();
        }
        val remoteUser = request.getRemoteUser();
        if (StringUtils.isNotBlank(remoteUser)) {
            LOGGER.debug("Remote user [{}] found in HttpServletRequest", remoteUser);
            return remoteUser;
        }

        if (StringUtils.isNotBlank(this.remotePrincipalHeader)) {
            val headers = getAllRequestHeaderValues(request);
            LOGGER.debug("Available request headers are [{}]. Locating first header value for [{}]", headers, this.remotePrincipalHeader);
            if (headers.containsKey(this.remotePrincipalHeader)) {
                val header = headers.get(this.remotePrincipalHeader).get(0);
                LOGGER.debug("Remote user [{}] found in [{}] header", header, this.remotePrincipalHeader);
                return header;
            }
        }
        LOGGER.debug("No remote user [{}] could be found", remoteUser);
        return null;
    }

    @SuppressWarnings("JdkObsolete")
    private static Map<String, List<String>> getAllRequestHeaderValues(final HttpServletRequest request) {
        val headers = new HashMap<String, List<String>>(DEFAULT_SIZE);
        val names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            val name = (String) names.nextElement();
            val values = request.getHeaders(name);
            if (values != null) {
                val listValues = new ArrayList<String>(DEFAULT_SIZE);
                while (values.hasMoreElements()) {
                    val value = (String) values.nextElement();
                    listValues.add(value);
                }
                headers.put(name, listValues);
            }
        }
        return headers;
    }
}


text:
package org.jboss.weld.tests.contexts.conversation.event.enterprise;

import jakarta.enterprise.context.ConversationScoped;
import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.context.Destroyed;
import jakarta.enterprise.event.Observes;

import org.jboss.weld.test.util.ActionSequence;

@Dependent
public class ObserverWeb2 {

    void conversationDestroyed(@Observes @Destroyed(ConversationScoped.class) Object event) {
        ActionSequence.addAction(ObserverWeb2.class.getName());
    }

}