text:
using System;
using NUnit.Framework;
using TagLib;
using TagLib.IFD;
using TagLib.IFD.Entries;
using TagLib.IFD.Tags;
using TagLib.Jpeg;
using TagLib.Xmp;

namespace TagLib.Tests.Images
{
	[TestFixture]
	public class JpegNikon2Test
	{
		private static string sample_file = "samples/sample_nikon2.jpg";
		private static string tmp_file = "samples/tmpwrite_nikon2.jpg";

		private TagTypes contained_types = TagTypes.TiffIFD | TagTypes.XMP;

		private File file;

		[TestFixtureSetUp]
		public void Init () {
			file = File.Create (sample_file);
		}

		[Test]
		public void JpegRead () {
			CheckTags (file);
		}

		[Test]
		public void ExifRead () {
			CheckExif (file);
		}

		[Test]
		public void MakernoteRead () {
			CheckMakerNote (file);
		}

		[Test]
		public void XMPRead () {
			CheckXMP (file);
		}

		[Test]
		public void PropertiesRead () {
			CheckProperties (file);
		}

		[Test]
		public void Rewrite () {
			File tmp = Utils.CreateTmpFile (sample_file, tmp_file);
			tmp.Save ();

			tmp = File.Create (tmp_file);

			CheckTags (tmp);
			CheckExif (tmp);
			CheckMakerNote (tmp);
			CheckXMP (tmp);
			CheckProperties(tmp);
		}

		[Test]
		public void AddExif ()
		{
			AddImageMetadataTests.AddExifTest (sample_file, tmp_file, true);
		}

		[Test]
		public void AddGPS ()
		{
			AddImageMetadataTests.AddGPSTest (sample_file, tmp_file, true);
		}

		[Test]
		public void AddXMP1 ()
		{
			AddImageMetadataTests.AddXMPTest1 (sample_file, tmp_file, true);
		}

		[Test]
		public void AddXMP2 ()
		{
			AddImageMetadataTests.AddXMPTest2 (sample_file, tmp_file, true);
		}

		public void CheckTags (File file) {
			Assert.IsTrue (file is Jpeg.File, "not a Jpeg file");

			Assert.AreEqual (contained_types, file.TagTypes);
			Assert.AreEqual (contained_types, file.TagTypesOnDisk);
		}

		public void CheckExif (File file) {
			var tag = file.GetTag (TagTypes.TiffIFD) as IFDTag;

			Assert.IsNotNull (tag, "tag");

			var exif_ifd = tag.Structure.GetEntry(0, IFDEntryTag.ExifIFD) as SubIFDEntry;
			Assert.IsNotNull (exif_ifd, "Exif IFD");

			Assert.AreEqual ("NIKON CORPORATION", tag.Make);
			Assert.AreEqual ("NIKON D70s", tag.Model);
			Assert.AreEqual (null, tag.ISOSpeedRatings, "ISOSpeedRatings");
			Assert.AreEqual (1.0d/180.0d, tag.ExposureTime);
			Assert.AreEqual (6.7d, tag.FNumber);
			Assert.AreEqual (50.0d, tag.FocalLength);
			Assert.AreEqual (new DateTime (2007, 01, 01, 12, 19, 34), tag.DateTime);
			Assert.AreEqual (new DateTime (2007, 01, 01, 13, 19, 34), tag.DateTimeDigitized);
			Assert.AreEqual (new DateTime (2007, 01, 01, 12, 19, 34), tag.DateTimeOriginal);
		}

		public void CheckMakerNote (File file) {
			IFDTag tag = file.GetTag (TagTypes.TiffIFD) as IFDTag;
			Assert.IsNotNull (tag, "tag");

			var makernote_ifd =
				tag.ExifIFD.GetEntry (0, (ushort) ExifEntryTag.MakerNote) as MakernoteIFDEntry;

			Assert.IsNotNull (makernote_ifd, "makernote ifd");
			Assert.AreEqual (MakernoteType.Nikon3, makernote_ifd.MakernoteType);

			var structure = makernote_ifd.Structure;
			Assert.IsNotNull (structure, "structure");
			{
				var entry = structure.GetEntry (0, 0x01) as UndefinedIFDEntry;
				Assert.IsNotNull (entry);
				ByteVector read_bytes = entry.Data;
				ByteVector expected_bytes = new ByteVector (new byte [] {48, 50, 49, 48});

				Assert.AreEqual (expected_bytes.Count, read_bytes.Count);
				for (int i = 0; i < expected_bytes.Count; i++)
					Assert.AreEqual (expected_bytes[i], read_bytes[i]);
			}
			{
				var entry = structure.GetEntry (0, 0x04) as StringIFDEntry;
				Assert.IsNotNull (entry, "entry 0x04");
				Assert.AreEqual ("FINE   ", entry.Value);
			}
			{
				var entry = structure.GetEntry (0, 0x08) as StringIFDEntry;
				Assert.IsNotNull (entry, "entry 0x08");
				Assert.AreEqual ("NORMAL      ", entry.Value);
			}
			{
				var entry = structure.GetEntry (0, 0x92) as SShortIFDEntry;
				Assert.IsNotNull (entry, "entry 0x92");
				Assert.AreEqual (0, entry.Value);
			}
			{
				var entry = structure.GetEntry (0, 0x9A) as RationalArrayIFDEntry;
				Assert.IsNotNull (entry, "entry 0x9A");
				var values = entry.Values;

				Assert.IsNotNull (values, "values of entry 0x9A");
				Assert.AreEqual (2, values.Length);
				Assert.AreEqual (78.0d/10.0d, (double) values[0]);
				Assert.AreEqual (78.0d/10.0d, (double) values[1]);
			}
		}

		public void CheckXMP (File file)
		{
			string [] keywords = new string[] {
				"Nikon D70s",
				"Food",
				"2007",
				"2006",
				"Neujahr",
				"Sylvester"
			};

			var tag = file.GetTag (TagTypes.XMP) as XmpTag;

			Assert.IsNotNull (tag, "tag");

			Assert.AreEqual (keywords, tag.Keywords);
		}

		public void CheckProperties (File file)
		{
			Assert.AreEqual (3008, file.Properties.PhotoWidth);
			Assert.AreEqual (2000, file.Properties.PhotoHeight);
			Assert.AreEqual (96, file.Properties.PhotoQuality);
		}
	}
}


text:
#include "api/dtls_transport_interface.h"

namespace webrtc {

DtlsTransportInformation::DtlsTransportInformation()
    : state_(DtlsTransportState::kNew) {}

DtlsTransportInformation::DtlsTransportInformation(DtlsTransportState state)
    : state_(state) {}

DtlsTransportInformation::DtlsTransportInformation(
    DtlsTransportState state,
    absl::optional<int> tls_version,
    absl::optional<int> ssl_cipher_suite,
    absl::optional<int> srtp_cipher_suite,
    std::unique_ptr<rtc::SSLCertChain> remote_ssl_certificates)
    : state_(state),
      tls_version_(tls_version),
      ssl_cipher_suite_(ssl_cipher_suite),
      srtp_cipher_suite_(srtp_cipher_suite),
      remote_ssl_certificates_(std::move(remote_ssl_certificates)) {}

DtlsTransportInformation::DtlsTransportInformation(
    const DtlsTransportInformation& c)
    : state_(c.state()),
      tls_version_(c.tls_version_),
      ssl_cipher_suite_(c.ssl_cipher_suite_),
      srtp_cipher_suite_(c.srtp_cipher_suite_),
      remote_ssl_certificates_(c.remote_ssl_certificates()
                                   ? c.remote_ssl_certificates()->Clone()
                                   : nullptr) {}

DtlsTransportInformation& DtlsTransportInformation::operator=(
    const DtlsTransportInformation& c) {
  state_ = c.state();
  tls_version_ = c.tls_version_;
  ssl_cipher_suite_ = c.ssl_cipher_suite_;
  srtp_cipher_suite_ = c.srtp_cipher_suite_;
  remote_ssl_certificates_ = c.remote_ssl_certificates()
                                 ? c.remote_ssl_certificates()->Clone()
                                 : nullptr;
  return *this;
}

}  // namespace webrtc

redpajama_set_name: RedPajamaGithub


text:
namespace Xamurais.Cfdv33
{
    /// <comentarios/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
    [System.SerializableAttribute()]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.sat.gob.mx/cfd/3")]
    public partial class ComprobanteComplemento
    {

        private System.Xml.XmlElement[] anyField;

        /// <comentarios/>
        [System.Xml.Serialization.XmlAnyElementAttribute()]
        public System.Xml.XmlElement[] Any
        {
            get
            {
                return this.anyField;
            }
            set
            {
                this.anyField = value;
            }
        }
    }
}


text:
package org.scalajars.web.lib.oauth

import scalaz._, Scalaz._
import play.scalaz.json._

case class GithubUser(
  login: String,
  email: String,
  avatar_url: String,
  name: String
)

object GithubUser {
  implicit def GithubUserReadz = readz4("login", "email", "avatar_url", "name")(GithubUser.apply)
}

case class GithubOAuth2(clientId: String, clientSecret: String) extends OAuth2[GithubUser] {
  def oauthSignInUrl = "https://github.com/login/oauth/authorize"
  def oauthAccessTokenUrl = "https://github.com/login/oauth/access_token"
  def oauthUserInfoUrl = "https://api.github.com/user"

  def loadUser(body: String) = fromJsonString[GithubUser](body).toOption
}


text:
local Background = Object:subclass('Background')

-- Images
local images = {
  love.graphics.newImage("assets/images/background-layer-1.png"),
  love.graphics.newImage("assets/images/background-layer-2.png"),
  love.graphics.newImage("assets/images/background-layer-3.png")
}

function Background:initialize(camera)
  self.layers = {}

  -- Vitesse de déplacement du décalage de l'arrière-plan
  self.speed = 0.5

  if camera then
    self.camera = camera
  else
    self.camera = false
  end

  -- Angle du mouvement automatique (rotation)
  self.mvt = 0

  -- Vitesse et distance du mouvement automatique
  self.mvtDistance = 100 -- pixels
  self.mvtSpeed = 0.2 -- [0;1]

  for i, image in pairs(images) do
    table.insert(self.layers, image)
  end
end

-- Affichage du fond d'écran
function Background:draw()

  love.graphics.setColor(7, 9, 15, 255)
  local bx, by = self.camera:worldCoords(0, 0)
  love.graphics.rectangle('fill', bx, by, syst.width, syst.height)
  love.graphics.setColor(255, 255, 255, 255)

  local n = table.getn(self.layers)
  -- Fond mobile

  for l, layer in pairs(self.layers) do
    local w, h = layer:getWidth(), layer:getHeight()
    local tx, ty = math.floor(self.camera.x / w), math.floor(self.camera.y / h)
    local x, y =
      (self.camera.x + math.cos(self.mvt) * self.mvtDistance) / (l + 1) * self.speed % w,
      (self.camera.y + math.sin(self.mvt) * self.mvtDistance) / (l + 1) * self.speed % h

    for ix = -3, 2 do
      for iy = -3, 2 do
        love.graphics.draw(layer,
          (tx + ix) * w + x,
          (ty + iy) * h + y)
      end
    end
  end --]]--

  --[[ Fond immobile

  for l, layer in pairs(self.layers) do
    local w, h = layer:getWidth(), layer:getHeight()
    local tx, ty = math.floor(self.camera.x / w), math.floor(self.camera.y / h)

    for ix = -2, 1 do
      for iy = -2, 1 do
        love.graphics.draw(layer, (tx + ix) * w, (ty + iy) * h, self.angle)
      end
    end
  end --]]--
end

-- Mise à jour du fond d'écran
function Background:update(dt)

  -- Lent déplacement du fond
  self.mvt = (self.mvt + dt * self.mvtSpeed) % (math.pi * 2)
end

return Background


text:
require 'fileutils'
require 'liberty_buildpack/util'
require 'liberty_buildpack/util/application_cache'
require 'liberty_buildpack/util/format_duration'

module LibertyBuildpack::Util

  # Downloads a given item using the application cache.
  #
  # @param [LibertyBuildpack::Util::TokenizedVersion] version the version of the item
  # @param [String] uri the URI of the item
  # @param [String] description a description of the item
  # @param [String] jar_name the filename of the item
  # @param [String] target_directory the path of the directory into which to download the item
  def self.download(version, uri, description, jar_name, target_directory)

    download_start_time = Time.now
    print "-----> Downloading #{description} #{version} from #{uri} "

    LibertyBuildpack::Util::ApplicationCache.new.get(uri) do |file| # TODO: Use global cache #50175265
      FileUtils.cp(file.path, File.join(target_directory, jar_name))
      puts "(#{(Time.now - download_start_time).duration})"
    end

  end

end


text:
using System;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Serialization;

namespace Content.Shared.GameObjects.Components
{
    public class SharedVaporComponent : Component
    {
        public override string Name => "Vapor";
    }

    [Serializable, NetSerializable]
    public enum VaporVisuals
    {
        Rotation,
        Color,
        State,
    }
}


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\widgets\Select2;
use yii\helpers\ArrayHelper;
use kartik\widgets\SwitchInput;
use backend\models\Reference;

/* @var $this yii\web\View */
/* @var $model backend\models\Program */
/* @var $form yii\widgets\ActiveForm */

$disabled = false;

if(!$model->isNewRecord){
	$program_revision = (int) \backend\models\ProgramHistory::getRevision($model->id);
	$countTraining = \backend\models\Training::find()
		->joinWith(['activity','program'])
		->where([
			'program_id'=>$model->id,
			'program_revision'=> $program_revision,
			'activity.status' => [2], // Status Ready
		])
		->count();
	if($countTraining>0) $disabled = true;
}
?>

    <?php $form = ActiveForm::begin(); ?>
	<?= $form->errorSummary($model) ?>
    <?php //$form->field($model, 'number')->textInput(['maxlength' => 15]) ?>

	<?php
	$data = ArrayHelper::map(
		\backend\models\Reference::find()
			->select(['id','value', 'CONCAT(name," => ",value) as name_value'])
			->where(['type'=>'program_code'])
			->orderBy(['sort'=> SORT_ASC])
			->asArray()
			->all(),
			'value', 'name_value'
	);

	/* Aku wrap ke tag row, biar konsisten. Yang hours, days, dan test pake wrap, masak yg lain engga :) */
	echo '
';
		echo '
';
			echo $form->field($model, 'number')->widget(Select2::classname(), [
				'data' => $data,
				'options' => [
					'placeholder' => 'Pilih kode program ...',
					'disabled'=>$disabled,
				],
				'pluginOptions' => [
					'allowClear' => true
				],
			])->label('Kode');
		echo '
';
	echo '
';
	?>

    		<?= $form->field($model, 'name')->textInput(['maxlength' => 255,'disabled'=>$disabled,])->label('Nama Program'); ?>

			<?php
			$data = ['1'=>'Dasar','2'=>'Lanjutan','3'=>'Menengah','4'=>'Tinggi'];
			echo $form->field($model, 'category')->widget(Select2::classname(), [
				'data' => $data,
				'options' => [
					'placeholder' => 'Pilih kategori program ...',
				],
				'pluginOptions' => [
					'allowClear' => true,
				],
			])
			->label('Kategori');
			?>

			<?= $form->field($model, 'stage')->textInput(['maxlength' => 255])->label('Rumpun') ?>

			<?= $form->field($model, 'hours')->textInput(['maxlength' => 5,'disabled'=>$disabled])->label('JP'); ?>

			<?= $form->field($model, 'days')->textInput(['disabled'=>$disabled])->label('Hari'); ?>

			<?= $form->field($model, 'test')->widget(SwitchInput::classname(), [
				'options'=>[
					'disabled'=>$disabled
				],
				'pluginOptions' => [
					'onText' => 'Ya',
					'offText' => 'Tidak',
				]
			])
			->label('Ujian?') ?>

    		<?= $form->field($model, 'note')->textInput(['maxlength' => 255])->label('Catatan'); ?>

	<?php if(!$model->isNewRecord){ ?>
		<?php
		$permit = \Yii::$app->user->can('pusdiklat-planning-1');
		if($permit){
			$form->field($model, 'status')->widget(SwitchInput::classname(), [
				'options' => [
					'placeholder' => 'Tentukan status...',
				],
				'pluginOptions' => [
					'onText' => 'Tampil',
					'offText' => 'Sembunyi',
				]
			]);
		}
		?>
		<?php
		if($countTraining>0){
			echo "

Program ini telah digunakan oleh diklat

";
		}
		?>
	<?php } ?>

        <?= Html::submitButton($model->isNewRecord ? ''.Yii::t('app', 'SYSTEM_BUTTON_CREATE') : ''.Yii::t('app', 'SYSTEM_BUTTON_UPDATE'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>

	<?php $this->registerCss('label{display:block !important;}'); ?>


text:
package com.raidzero.teamcitydownloader.global;

import android.content.Context;

import com.raidzero.teamcitydownloader.data.DownloadRequest;
import com.raidzero.teamcitydownloader.tasks.DownloadTask;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by raidzero on 12/4/14.
 */
public class DownloadHelper {
    private static final String tag = "DownloadHelper";
    private Context mContext;
    private int mNotificationId = 0;
    private boolean mDownloadInProgress = false;

    // map of files downloaded under a notification id
    private HashMap<Integer, ArrayList<String>> mNotifiedFiles;

    // link a request URL to a task
    private HashMap<String, DownloadTask> mDownloadTaskMap;

    // list of current requests
    private ArrayList<DownloadRequest> mCurrentRequests;

    public DownloadHelper(Context context) {
        mContext = context;
        mNotifiedFiles = new HashMap<Integer, ArrayList<String>>();
        mDownloadTaskMap = new HashMap<String, DownloadTask>();
        mCurrentRequests = new ArrayList<DownloadRequest>();
    }

    public void addtoCurrentRequests(DownloadRequest request) {
        if (!isRequestInProgress(request)) {
            mCurrentRequests.add(request);
        }
    }

    public void removeFromCurrentRequests(DownloadRequest request) {
        if (isRequestInProgress(request)) {
            mCurrentRequests.remove(request);
        }
    }

    public void clearCurrentRequests() {
        mCurrentRequests.clear();
        mNotifiedFiles.clear();
    }

    public int getNumCurrentRequests() {
        return mCurrentRequests.size();
    }

    public DownloadRequest getRequestForFile(String fileName) {
        for (DownloadRequest r : mCurrentRequests) {
            if (r.fileName.equals(fileName)) {
                return r;
            }
        }

        return null;
    }

    public boolean isRequestInProgress(DownloadRequest request) {
        for (DownloadRequest r : mCurrentRequests) {
            if (r.url.equals(request.url)) {
                return true;
            }
        }

        return false;
    }

    public int getNextNotificationId() {
        return ++mNotificationId;
    }

    public int getNotificationId() {
        return mNotificationId;
    }

    public void addToNotifiedFiles(int notificationId, String fileName) {
        if (mNotifiedFiles.get(notificationId) == null) {
            mNotifiedFiles.put(notificationId, new ArrayList<String>());
        }

        mNotifiedFiles.get(notificationId).add(fileName);
    }

    public void removeFromNotifiedFiles(int notificationId, String fileName) {
        if (mNotifiedFiles != null) {
            if (mNotifiedFiles.containsKey(notificationId)) {
                if (mNotifiedFiles.get(notificationId).contains(fileName)) {
                    mNotifiedFiles.get(notificationId).remove(fileName);
                }
            }
        }
    }

    public boolean shouldBoldFile(String fileName, int notificationId) {
        if (mNotifiedFiles != null) {
            if (mNotifiedFiles.containsKey(notificationId)) {
                for (String f : mNotifiedFiles.get(notificationId)) {
                    if (fileName.equals(f)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public void markFileSeen(String file, int notificationId) {
        if (mNotifiedFiles != null) {
            if (mNotifiedFiles.containsKey(notificationId)) {
                if (mNotifiedFiles.get(notificationId).contains(file)) {
                    mNotifiedFiles.get(notificationId).remove(file);
                }
            }
        }
    }

    public String getNotifiedFilesString(int notificationId) {
        ArrayList<String> files = mNotifiedFiles.get(notificationId);
        String rtn = "";

        for (String s : files) {
            rtn += s + "\n";
        }

        return rtn;
    }

    public void setIsDownloading(boolean downloading) {
        mDownloadInProgress = downloading;
    }

    public boolean isDownloadInProgress() {
        return mDownloadInProgress;
    }

    public void addDownloadTaskToMap(DownloadRequest request, DownloadTask task) {
        mDownloadTaskMap.put(request.url, task);
    }

    public String getNotificationContent() {
        String rtn = "";
        for (DownloadRequest r : mCurrentRequests) {
            rtn += r.fileName + "\n";
        }

        return rtn;
    }

    public boolean isFileDownloading(String fileName) {
        if (mCurrentRequests != null) {
            for (DownloadRequest r : mCurrentRequests) {
                if (fileName.equals(r.fileName)) {
                    return true;
                }
            }
        }

        return false;
    }

    public void cancelDownload(String fileName) {
        DownloadRequest request = getRequestForFile(fileName);
        if (request != null) {
            DownloadTask task = mDownloadTaskMap.get(request.url);
            task.cancel(true);
            removeFromNotifiedFiles(request.notificationId, request.fileName);
        }
    }

    public void cancelDownload(String fileName, boolean showToast) {
        DownloadRequest request = getRequestForFile(fileName);
        if (request != null) {
            DownloadTask task = mDownloadTaskMap.get(request.url);
            task.showToast(showToast);
            task.cancel(true);
        }
    }
}


text:
cp ../../Bin/blue.png $1.app/Contents/Resources
cp ../../Bin/purple.png $1.app/Contents/Resources
cp ../../Bin/background2.jpg $1.app/Contents/Resources


text:
<?php

namespace Smalot\Gitlab\Webhook\Event;

use Smalot\Gitlab\Webhook\Model\ModelBase;
use Symfony\Component\EventDispatcher\Event;

/**
 * Class EventBase
 * @package Smalot\Gitlab\Webhook\Event
 */
abstract class EventBase extends Event
{
    /**
     * @var string
     */
    protected $eventName;

    /**
     * @var string
     */
    protected $payload;

    /**
     * @var ModelBase
     */
    protected $model;

    /**
     * EventBase constructor.
     * @param string $eventName
     * @param string $payload
     */
    public function __construct($eventName, $payload)
    {
        $this->eventName = $eventName;
        $this->payload = $payload;

        $payload = json_decode($this->payload, true);
        $className = $this->getClassModel();
        $this->model = new $className($payload);
    }

    /**
     * @return string
     */
    public function getEventName()
    {
        return $this->eventName;
    }

    /**
     * @return string
     */
    public function getPayload()
    {
        return $this->payload;
    }

    /**
     * @return ModelBase
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * @return string
     */
    abstract protected function getClassModel();
}


text:
package org.bgp4j.net.packets;

import org.bgp4j.net.BGPv4Constants;

/**
 * @author Rainer Bieniek (Rainer.Bieniek@web.de)
 *
 */
public abstract class CeaseNotificationPacket extends NotificationPacket {

	public static final int SUBCODE_UNSPECIFIC = 0;
	public static final int SUBCODE_MAXIMUM_NUMBER_OF_PREFIXES_REACHED = 1;
	public static final int SUBCODE_ADMINSTRATIVE_SHUTDOWN = 2;
	public static final int SUBCODE_PEER_DECONFIGURED = 3;
	public static final int SUBCODE_ADMINSTRATIVE_RESET = 4;
	public static final int SUBCODE_CONNECTION_REJECTED = 5;
	public static final int SUBCODE_OTHER_CONFIGURATION_CHANGE = 6;
	public static final int SUBCODE_CONNECTION_COLLISION_RESOLUTION = 7;
	public static final int SUBCODE_OUT_OF_RESOURCES = 8;

	/**
	 * @param errorCode
	 * @param errorSubcode
	 */
	protected CeaseNotificationPacket(int subcode) {
		super(BGPv4Constants.BGP_ERROR_CODE_CEASE, subcode);
	}

}


text:
RSpec.describe Liebre::Actor::Consumer do

  let(:chan)    { double 'chan' }
  let(:declare) { double 'declare' }
  let(:handler) { double 'handler' }

  let :spec do
    {:exchange => {:name => "foo"},
     :queue    => {:name => "bar"},
     :bind     => {:fake => "bind_config"}}
  end

  let(:logger) { double 'logger', :info => nil, :error => nil }

  let :context do
    double 'context', :chan    => chan,
                      :declare => declare,
                      :name    => "foo",
                      :handler => handler,
                      :spec    => spec,
                      :logger  => logger
  end

  subject { described_class.new(context) }

  let(:queue)    { double 'queue' }
  let(:exchange) { double 'exchange' }

  let(:dead_queue)    { double 'dead_queue' }
  let(:dead_exchange) { double 'dead_exchange' }

  let(:dead_letter_opts) do
    {:arguments => {"x-dead-letter-exchange" => "bar-error"}}
  end

  before do
    allow(subject).to receive(:async).and_return(subject)

    allow(declare).to receive(:queue).
      with(:name => "bar", :opts => dead_letter_opts).and_return(queue)

    allow(declare).to receive(:exchange).
      with(:name => "foo").and_return(exchange)

    allow(declare).to receive(:queue).
      with(:name => "bar-error", :opts => {}).and_return(dead_queue)

    allow(declare).to receive(:exchange).
      with(:name => "bar-error", :type => "fanout", :opts => {}).and_return(dead_exchange)

    allow(declare).to receive(:bind).
      with(queue, exchange, :fake => "bind_config")

    allow(declare).to receive(:bind).
      with(dead_queue, dead_exchange)
  end

  let(:info)    { double 'info' }
  let(:meta)    { double 'meta' }
  let(:payload) { "some_data" }

  describe '#start' do
    it 'declares and binds queue and exchange, and subscribes to the queue' do
      expect(declare).to receive(:queue).
        with(:name => "bar", :opts => dead_letter_opts).and_return(queue)

      expect(declare).to receive(:exchange).
        with(:name => "foo").and_return(exchange)

      expect(declare).to receive(:bind).
        with(queue, exchange, :fake => "bind_config")

      expect(declare).to receive(:queue).
        with(:name => "bar-error", :opts => {}).and_return(dead_queue)

      expect(declare).to receive(:exchange).
        with(:name => "bar-error", :type => "fanout", :opts => {}).and_return(dead_exchange)

      expect(declare).to receive(:bind).
        with(dead_queue, dead_exchange)

      subscription_block = nil
      expect(queue).to receive(:subscribe) do |opts, &block|
        expect(opts).to eq :block => false, :manual_ack => true
        subscription_block = block
      end

      subject.start

      expect(subject).to receive(:consume).
        with(info, meta, payload)

      subscription_block.(info, meta, payload)
    end
  end

  describe '#clean' do
    it 'deletes all queues and exchanges' do
      expect(queue        ).to receive(:delete)
      expect(exchange     ).to receive(:delete)
      expect(dead_queue   ).to receive(:delete)
      expect(dead_exchange).to receive(:delete)

      subject.clean
    end
  end

  describe '#consume' do
    context 'on success' do
      it 'runs the handler with a callbacks object' do
        callback = nil
        expect(handler).to receive :call do |given_payload, given_meta, given_callback|
          expect(given_payload).to eq payload
          expect(given_meta   ).to eq meta

          callback = given_callback
        end

        subject.consume(info, meta, payload)

        expect(subject).to receive(:ack).with(info, {})
        callback.ack()

        expect(subject).to receive(:nack).with(info, {})
        callback.nack()

        expect(subject).to receive(:reject).with(info, :requeue => true)
        callback.reject(:requeue => true)
      end
    end

    context 'on handler failure' do
      let(:error) { double 'error' }

      it 'calls failed on the consumer' do
        error_block = nil
        expect(handler).to receive :call do |payload, meta, callback, &block|
          error_block = block
        end

        subject.consume(info, meta, payload)

        expect(subject).to receive(:failed).
          with(info, error)

        error_block.(error)
      end
    end
  end

  describe '#ack, #nack, #reject and #failed' do
    let(:error) { double 'error', :message => "foo", :backtrace => [] }

    it 'delegates to the queue' do
      expect(queue).to receive(:ack).with(info, {})
      subject.ack(info)

      expect(queue).to receive(:nack).with(info, {})
      subject.nack(info)

      expect(queue).to receive(:reject).with(info, :requeue => true)
      subject.reject(info, :requeue => true)

      expect(queue).to receive(:reject).with(info, {})
      subject.failed(info, error)
    end
  end

end


text:
require 'rom/support/configurable'
require 'rom/gateway'

module ROM
  # Core gateway configuration interface
  #
  # @api public
  class Environment
    include Configurable

    attr_reader :gateways, :gateways_map

    # @api public
    def initialize(*args)
      @gateways = {}
      @gateways_map = {}

      configure_gateways(*args) unless args.empty?
    end

    private

    def configure_gateways(*args)
      normalized_gateway_args = normalize_gateway_args(*args)
      normalized_gateways = normalize_gateways(normalized_gateway_args)

      @gateways, @gateways_map = normalized_gateways.values_at(:gateways, :map)

      normalized_gateway_args.each_with_object(config) do |(name, gateway_config), config|
        options = gateway_config.is_a?(Array) && gateway_config.last
        load_config(config.gateways[name], options) if options.is_a?(Hash)
      end
    end

    # @api private
    def normalize_gateway_args(*args)
      args.first.is_a?(Hash) ? args.first : {default: args}
    end

    # Build gateways using the setup interface
    #
    # @api private
    def normalize_gateways(gateways_config)
      gateways_config.each_with_object({map: {}, gateways: {}}) do |(name, spec), hash|
        identifier, *args = Array(spec)

        if identifier.is_a?(Gateway)
          gateway = identifier
        else
          gateway = Gateway.setup(identifier, *(args.flatten))
          hash[:map][gateway] = identifier
        end

        hash[:gateways][name] = gateway
      end
    end

    # @api private
    def load_config(config, hash)
      hash.each do |key, value|
        if value.is_a?(Hash)
          load_config(config[key], value)
        else
          config.send("#{key}=", value)
        end
      end
    end
  end
end


text:
package leap.web;

import java.util.concurrent.CopyOnWriteArrayList;

import leap.core.web.RequestBase;
import leap.lang.Args;
import leap.lang.collection.ListEnumerable;

public class DefaultFilterMappings extends ListEnumerable<FilterMapping> implements FilterMappings {

	public DefaultFilterMappings() {
	    super(new CopyOnWriteArrayList<FilterMapping>());
    }

	@Override
    public FilterMappings add(FilterMapping m) {
		Args.notNull(m,"filter mapping");
		l.add(m);
	    return this;
    }

	@Override
    public FilterMappings addAll(Iterable<FilterMapping> i) {
		if(null != i){
			for(FilterMapping m : i){
				add(m);
			}
		}
	    return this;
    }

	@Override
    public FilterMappings add(String path, Filter filter) {
		return add(new DefaultFilterMapping(path, filter));
    }

	@Override
    public FilterMappings add(Filter filter) {
		Args.notNull(filter, "filter");
	    return add(new AllFilterMapping(filter));
    }

	public static final class AllFilterMapping implements FilterMapping {

		private final Filter filter;

		public AllFilterMapping(Filter filter) {
			this.filter = filter;
		}

		@Override
        public boolean matches(RequestBase request) {
	        return true;
        }

		@Override
        public Filter getFilter() {
	        return filter;
        }

	}
}


text:
using System;
using Deltatre.Timeline.Core.Drawing;

namespace Deltatre.Timeline.Core.Interfaces
{
	public interface IDockable : IDrawable
	{
		DockType Type { get; }
		int Space { get; }
		bool IsOverlay { get; }
	}
}


text:
package Moose.commands;

import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import Moose.OI;
import Moose.RobotMap;
import Moose.subsystems.DriveTrain;
import Moose.subsystems.Elevator;
import Moose.subsystems.Lights;
import Moose.subsystems.Shooter;

public abstract class CommandBase extends Command {

    public static OI oi;
    public static DriveTrain drive;
    public static Shooter shooter;
    public static Elevator elevator;
    public static Lights lights;

    public static void init() {

        drive = new DriveTrain(RobotMap.frontLeftMotor, RobotMap.frontRightMotor ,RobotMap.backLeftMotor,RobotMap.backRightMotor,
                               0, RobotMap.encoderLeftA,RobotMap.encoderLeftB,RobotMap.encoderRightA,RobotMap.encoderRightB);
        shooter = new Shooter(RobotMap.shooterMotor,RobotMap.shooterEncoder);
        elevator = new Elevator(RobotMap.liftMotor,RobotMap.LiftTop,RobotMap.LiftBottom, RobotMap.LiftMiddle,RobotMap.LiftEncoderA,RobotMap.LiftEncoderB,0);
        lights = new Lights(RobotMap.redLight,RobotMap.whiteLight, RobotMap.BlueLight, RobotMap.greenLight);
        oi = new OI();
        //SmartDashboard.putData(drive);
    }

    public CommandBase(String name) {
        super(name);
    }

    public CommandBase() {
        super();
    }
}


text:
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <nan.h>
#include <unistd.h>
#include <string>
#include <map>
#include <exception>
#include <exiv2/image.hpp>
#include <exiv2/exif.hpp>
#include <exiv2/preview.hpp>

using namespace node;
using namespace v8;

// Create a map of strings for passing them back and forth between the V8 and
// worker threads.
typedef std::map<std::string, std::string> tag_map_t;

class Exiv2Worker : public NanAsyncWorker {
 public:
  Exiv2Worker(NanCallback *callback, const std::string fileName)
    : NanAsyncWorker(callback), fileName(fileName) {}
  ~Exiv2Worker() {}

 protected:
  const std::string fileName;
  std::string exifException;
};

// - - -

class GetTagsWorker : public Exiv2Worker {
 public:
  GetTagsWorker(NanCallback *callback, const std::string fileName)
    : Exiv2Worker(callback, fileName) {}
  ~GetTagsWorker() {}

  // Should become protected...
  tag_map_t tags;

  // Executed inside the worker-thread. Not safe to access V8, or V8 data
  // structures here.
  void Execute () {
    try {
      Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fileName);
      assert(image.get() != 0);
      image->readMetadata();

      Exiv2::ExifData &exifData = image->exifData();
      if (exifData.empty() == false) {
        Exiv2::ExifData::const_iterator end = exifData.end();
        for (Exiv2::ExifData::const_iterator i = exifData.begin(); i != end; ++i) {
          tags.insert(std::pair<std::string, std::string> (i->key(), i->value().toString()));
        }
      }

      Exiv2::IptcData &iptcData = image->iptcData();
      if (iptcData.empty() == false) {
        Exiv2::IptcData::const_iterator end = iptcData.end();
        for (Exiv2::IptcData::const_iterator i = iptcData.begin(); i != end; ++i) {
          tags.insert(std::pair<std::string, std::string> (i->key(), i->value().toString()));
        }
      }

      Exiv2::XmpData &xmpData = image->xmpData();
      if (xmpData.empty() == false) {
        Exiv2::XmpData::const_iterator end = xmpData.end();
        for (Exiv2::XmpData::const_iterator i = xmpData.begin(); i != end; ++i) {
          tags.insert(std::pair<std::string, std::string> (i->key(), i->value().toString()));
        }
      }
    } catch (std::exception& e) {
      exifException.append(e.what());
    }
  }

  // This function will be run inside the main event loop so it is safe to use
  // V8 again.
  void HandleOKCallback () {
    NanScope();

    Local<Value> argv[2] = { NanNull(), NanNull() };

    if (!exifException.empty()){
      argv[0] = NanNew<String>(exifException.c_str());
    } else if (!tags.empty()) {
      Local<Object> hash = NanNew<Object>();
      // Copy the tags out.
      for (tag_map_t::iterator i = tags.begin(); i != tags.end(); ++i) {
        hash->Set(NanNew<String>(i->first.c_str()), NanNew<String>(i->second.c_str()));
      }
      argv[1] = hash;
    }

    // Pass the argv array object to our callback function.
    callback->Call(2, argv);
  };
};

NAN_METHOD(GetImageTags) {
  NanScope();

  /* Usage arguments */
  if (args.Length() <= 1 || !args[1]->IsFunction())
    return NanThrowTypeError("Usage: <filename> <callback function>");

  NanCallback *callback = new NanCallback(args[1].As<Function>());
  std::string filename = std::string(*NanUtf8String(args[0]));

  NanAsyncQueueWorker(new GetTagsWorker(callback, filename));
  NanReturnUndefined();
}

// - - -

class SetTagsWorker : public Exiv2Worker {
 public:
  SetTagsWorker(NanCallback *callback, const std::string fileName)
    : Exiv2Worker(callback, fileName) {}
  ~SetTagsWorker() {}

  // Should become protected...
  tag_map_t tags;

  // Executed inside the worker-thread. Not safe to access V8, or V8 data
  // structures here.
  void Execute () {
    try {
      Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fileName);
      assert(image.get() != 0);

      image->readMetadata();
      Exiv2::ExifData &exifData = image->exifData();
      Exiv2::IptcData &iptcData = image->iptcData();
      Exiv2::XmpData &xmpData = image->xmpData();

      // Assign the tags.
      for (tag_map_t::iterator i = tags.begin(); i != tags.end(); ++i) {
        if (i->first.compare(0, 5, "Exif.") == 0) {
          exifData[i->first].setValue(i->second);
        } else if (i->first.compare(0, 5, "Iptc.") == 0) {
          iptcData[i->first].setValue(i->second);
        } else if (i->first.compare(0, 4, "Xmp.") == 0) {
          xmpData[i->first].setValue(i->second);
        } else {
          //std::cerr << "skipping unknown tag " << i->first << std::endl;
        }
      }

      // Write the tag data the image file.
      image->setExifData(exifData);
      image->setIptcData(iptcData);
      image->setXmpData(xmpData);
      image->writeMetadata();
    } catch (std::exception& e) {
      exifException.append(e.what());
    }
  }

  // This function will be run inside the main event loop so it is safe to use
  // V8 again.
  void HandleOKCallback () {
    NanScope();

    // Create an argument array for any errors.
    Local<Value> argv[1] = { NanNull() };
    if (!exifException.empty()) {
      argv[0] = NanNew<String>(exifException.c_str());
    }

    // Pass the argv array object to our callback function.
    callback->Call(1, argv);
  };
};

NAN_METHOD(SetImageTags) {
  NanScope();

  /* Usage arguments */
  if (args.Length() <= 2 || !args[2]->IsFunction())
    return NanThrowTypeError("Usage: <filename> <tags> <callback function>");

  NanCallback *callback = new NanCallback(args[2].As<Function>());
  std::string filename = std::string(*NanUtf8String(args[0]));

  SetTagsWorker *worker = new SetTagsWorker(callback, filename);

  Local<Object> tags = Local<Object>::Cast(args[1]);
  Local<Array> keys = tags->GetPropertyNames();
  for (unsigned i = 0; i < keys->Length(); i++) {
    Handle<v8::Value> key = keys->Get(i);
    worker->tags.insert(std::pair<std::string, std::string> (
      *NanUtf8String(key),
      *NanUtf8String(tags->Get(key)))
    );
  }

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

// - - -

class DeleteTagsWorker : public Exiv2Worker {
 public:
  DeleteTagsWorker(NanCallback *callback, const std::string fileName)
    : Exiv2Worker(callback, fileName) {}
  ~DeleteTagsWorker() {}

  // Should become protected...
  std::vector<std::string> tags;

  // Executed inside the worker-thread. Not safe to access V8, or V8 data
  // structures here.
  void Execute () {
    try {
      Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fileName);
      assert(image.get() != 0);

      image->readMetadata();
      Exiv2::ExifData &exifData = image->exifData();
      Exiv2::IptcData &iptcData = image->iptcData();
      Exiv2::XmpData &xmpData = image->xmpData();

      // Erase the tags.
      for (std::vector<std::string>::iterator i = tags.begin(); i != tags.end(); ++i) {
        if (i->compare(0, 5, "Exif.") == 0) {
          Exiv2::ExifKey *k = new Exiv2::ExifKey(*i);
          exifData.erase(exifData.findKey(*k));
          delete k;
        } else if (i->compare(0, 5, "Iptc.") == 0) {
          Exiv2::IptcKey *k = new Exiv2::IptcKey(*i);
          iptcData.erase(iptcData.findKey(*k));
          delete k;
        } else if (i->compare(0, 4, "Xmp.") == 0) {
          Exiv2::XmpKey *k = new Exiv2::XmpKey(*i);
          xmpData.erase(xmpData.findKey(*k));
          delete k;
        } else {
          //std::cerr << "skipping unknown tag " << i << std::endl;
        }
      }

      // Write the tag data the image file.
      image->setExifData(exifData);
      image->setIptcData(iptcData);
      image->setXmpData(xmpData);
      image->writeMetadata();
    } catch (std::exception& e) {
      exifException.append(e.what());
    }
  }

  // This function will be run inside the main event loop so it is safe to use
  // V8 again.
  void HandleOKCallback () {
    NanScope();

    // Create an argument array for any errors.
    Local<Value> argv[1] = { NanNull() };
    if (!exifException.empty()) {
      argv[0] = NanNew<String>(exifException.c_str());
    }

    // Pass the argv array object to our callback function.
    callback->Call(1, argv);
  };
};

NAN_METHOD(DeleteImageTags) {
  NanScope();

  /* Usage arguments */
  if (args.Length() <= 2 || !args[2]->IsFunction())
    return NanThrowTypeError("Usage: <filename> <tags> <callback function>");

  NanCallback *callback = new NanCallback(args[2].As<Function>());
  std::string filename = std::string(*NanUtf8String(args[0]));

  DeleteTagsWorker *worker = new DeleteTagsWorker(callback, filename);

  Local<Array> keys = Local<Array>::Cast(args[1]);
  for (unsigned i = 0; i < keys->Length(); i++) {
    Handle<v8::Value> key = keys->Get(i);
    worker->tags.push_back(*NanUtf8String(key));
  }

  NanAsyncQueueWorker(worker);
  NanReturnUndefined();
}

// - - -

class GetPreviewsWorker : public Exiv2Worker {
 public:
  GetPreviewsWorker(NanCallback *callback, const std::string fileName)
    : Exiv2Worker(callback, fileName) {}
  ~GetPreviewsWorker() {}

  // Executed inside the worker-thread. Not safe to access V8, or V8 data
  // structures here.
  void Execute () {
    try {
      Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(fileName);
      assert(image.get() != 0);
      image->readMetadata();

      Exiv2::PreviewManager manager(*image);
      Exiv2::PreviewPropertiesList list = manager.getPreviewProperties();

      // Make sure we're not reusing a baton with memory allocated.
      for (Exiv2::PreviewPropertiesList::iterator pos = list.begin(); pos != list.end(); pos++) {
        Exiv2::PreviewImage image = manager.getPreviewImage(*pos);

        previews.push_back(Preview(pos->mimeType_, pos->height_,
          pos->width_, (char*) image.pData(), pos->size_));
      }
    } catch (std::exception& e) {
      exifException.append(e.what());
    }
  }

  // This function will be run inside the main event loop so it is safe to use
  // V8 again.
  void HandleOKCallback () {
    NanScope();

    Local<Value> argv[2] = { NanNull(), NanNull() };
    if (!exifException.empty()){
      argv[0] = NanNew<String>(exifException.c_str());
    } else {
      // Convert the data into V8 values.
      Local<Array> array = NanNew<Array>(previews.size());
      for (size_t i = 0; i < previews.size(); ++i) {
        Local<Object> preview = NanNew<Object>();
        preview->Set(NanNew<String>("mimeType"), NanNew<String>(previews[i].mimeType.c_str()));
        preview->Set(NanNew<String>("height"), NanNew<Number>(previews[i].height));
        preview->Set(NanNew<String>("width"), NanNew<Number>(previews[i].width));
        preview->Set(NanNew<String>("data"), NanNewBufferHandle(previews[i].data, previews[i].size));

        array->Set(i, preview);
      }
      argv[1] = array;
    }

    // Pass the argv array object to our callback function.
    callback->Call(2, argv);
  };

 protected:

  // Holds a preview image when we copy it from the worker to V8.
  struct Preview {
    Preview(const Preview &p)
      : mimeType(p.mimeType), height(p.height), width(p.width), size(p.size)
    {
      data = new char[size];
      memcpy(data, p.data, size);
    }
    Preview(std::string type_, uint32_t height_, uint32_t width_, const char *data_, size_t size_)
      : mimeType(type_), height(height_), width(width_), size(size_)
    {
      data = new char[size];
      memcpy(data, data_, size);
    }
    ~Preview() {
      delete[] data;
    }

    std::string mimeType;
    uint32_t height;
    uint32_t width;
    size_t size;
    char* data;
  };

  std::vector<Preview> previews;
};

NAN_METHOD(GetImagePreviews) {
  NanScope();

  /* Usage arguments */
  if (args.Length() <= 1 || !args[1]->IsFunction())
    return NanThrowTypeError("Usage: <filename> <callback function>");

  NanCallback *callback = new NanCallback(args[1].As<Function>());
  std::string filename = std::string(*NanUtf8String(args[0]));

  NanAsyncQueueWorker(new GetPreviewsWorker(callback, filename));
  NanReturnUndefined();
}

// - - -

void InitAll(Handle<Object> target) {
  target->Set(NanNew<String>("getImageTags"), NanNew<FunctionTemplate>(GetImageTags)->GetFunction());
  target->Set(NanNew<String>("setImageTags"), NanNew<FunctionTemplate>(SetImageTags)->GetFunction());
  target->Set(NanNew<String>("deleteImageTags"), NanNew<FunctionTemplate>(DeleteImageTags)->GetFunction());
  target->Set(NanNew<String>("getImagePreviews"), NanNew<FunctionTemplate>(GetImagePreviews)->GetFunction());
}
NODE_MODULE(exiv2, InitAll)


text:
@interface AmountViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *serviceCharge;
@property (weak, nonatomic) IBOutlet UITextField *tip;
@property (weak, nonatomic) IBOutlet UITextField *discount;
@property (weak, nonatomic) IBOutlet UISegmentedControl *splitType;
@property (weak, nonatomic) IBOutlet UITextField *totalBill;
@property (weak, nonatomic) IBOutlet UITextView *definition;
@property (strong, nonatomic) NSString* type;
@property (strong, nonatomic) AppDelegate* ad;
- (IBAction)nextViewController:(id)sender;
- (IBAction)changeSplitter:(id)sender;
- (IBAction)textFieldShouldReturn:(UITextField *)textField;
@end


text:
package org.elasticsearch.xpack.eql.action;

import org.elasticsearch.Version;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.search.fetch.subphase.FieldAndFormat;
import org.elasticsearch.xpack.eql.AbstractBWCSerializationTestCase;
import org.junit.Before;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.Collections.emptyMap;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
import static org.elasticsearch.xpack.ql.TestUtils.randomRuntimeMappings;

public class EqlSearchRequestTests extends AbstractBWCSerializationTestCase<EqlSearchRequest> {

    // TODO: possibly add mutations
    static String defaultTestFilter = "{\n" +
        "   \"match\" : {\n" +
        "       \"foo\": \"bar\"\n" +
        "   }" +
        "}";

    static String defaultTestIndex = "endgame-*";

    @Before
    public void setup() {
    }

    @Override
    protected NamedWriteableRegistry getNamedWriteableRegistry() {
        SearchModule searchModule = new SearchModule(Settings.EMPTY, Collections.emptyList());
        return new NamedWriteableRegistry(searchModule.getNamedWriteables());
    }

    @Override
    protected NamedXContentRegistry xContentRegistry() {
        SearchModule searchModule = new SearchModule(Settings.EMPTY, Collections.emptyList());
        return new NamedXContentRegistry(searchModule.getNamedXContents());
    }

    @Override
    protected EqlSearchRequest createTestInstance() {
        try {
            List<FieldAndFormat> randomFetchFields = new ArrayList<>();
            int fetchFieldsCount = randomIntBetween(0, 5);
            for (int j = 0; j < fetchFieldsCount; j++) {
                randomFetchFields.add(new FieldAndFormat(randomAlphaOfLength(10), randomAlphaOfLength(10)));
            }
            if (randomFetchFields.isEmpty()) {
                randomFetchFields = null;
            }
            QueryBuilder filter = parseFilter(defaultTestFilter);
            return new EqlSearchRequest()
                .indices(defaultTestIndex)
                .filter(filter)
                .timestampField(randomAlphaOfLength(10))
                .eventCategoryField(randomAlphaOfLength(10))
                .fetchSize(randomIntBetween(1, 50))
                .size(randomInt(50))
                .query(randomAlphaOfLength(10))
                .fetchFields(randomFetchFields)
                .runtimeMappings(randomRuntimeMappings());
        } catch (IOException ex) {
            assertNotNull("unexpected IOException " + ex.getCause().getMessage(), ex);
        }
        return null;
    }

    protected QueryBuilder parseFilter(String filter) throws IOException {
        XContentParser parser = createParser(JsonXContent.jsonXContent, filter);
        return parseFilter(parser);
    }

    protected QueryBuilder parseFilter(XContentParser parser) throws IOException {
        QueryBuilder parseInnerQueryBuilder = parseInnerQueryBuilder(parser);
        assertNull(parser.nextToken());
        return parseInnerQueryBuilder;
    }

    @Override
    protected Writeable.Reader<EqlSearchRequest> instanceReader() {
        return EqlSearchRequest::new;
    }

    @Override
    protected EqlSearchRequest doParseInstance(XContentParser parser) {
        return EqlSearchRequest.fromXContent(parser).indices(defaultTestIndex);
    }

    @Override
    protected EqlSearchRequest mutateInstanceForVersion(EqlSearchRequest instance, Version version) {
        EqlSearchRequest mutatedInstance = new EqlSearchRequest();
        mutatedInstance.indices(instance.indices());
        mutatedInstance.indicesOptions(instance.indicesOptions());
        mutatedInstance.filter(instance.filter());
        mutatedInstance.timestampField(instance.timestampField());
        mutatedInstance.tiebreakerField(instance.tiebreakerField());
        mutatedInstance.eventCategoryField(instance.eventCategoryField());
        mutatedInstance.size(instance.size());
        mutatedInstance.fetchSize(instance.fetchSize());
        mutatedInstance.query(instance.query());
        mutatedInstance.waitForCompletionTimeout(instance.waitForCompletionTimeout());
        mutatedInstance.keepAlive(instance.keepAlive());
        mutatedInstance.keepOnCompletion(instance.keepOnCompletion());
        mutatedInstance.fetchFields(version.onOrAfter(Version.V_7_13_0) ? instance.fetchFields() : null);
        mutatedInstance.runtimeMappings(version.onOrAfter(Version.V_7_13_0) ? instance.runtimeMappings() : emptyMap());

        return mutatedInstance;
    }
}


text:
"""Read and write Data Matrix barcodes from Python 2 and 3."""

__version__ = '0.1.10'


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" android:padding="10dp">
    <!-- you can use any color you want-->
    <solid android:color="#E45925"/>
    <corners
            android:bottomRightRadius="10dp"
            android:bottomLeftRadius="10dp"
            android:topLeftRadius="10dp"
            android:topRightRadius="10dp"/>
    <stroke android:color="@color/rounded_shape_stroke" android:width="1dp" />
</shape>


text:
[![Bower version](https://badge.fury.io/bo/tock.svg)](http://badge.fury.io/bo/tock)

A javscript timer/countdown clock.

[View Demo](http://deviouschimp.co.uk/misc/tock)

Based on an idea by James Edwards:
http://sitepoint.com/creating-accurate-timers-in-javascript/

 > Note: I have renamed the repo from Tock to tock. Sorry for any inconvenience.

# Readme Contents #

 * [What's so good about it?](#whats-so-good-about-it)
 * [When would I use it?](#when-would-i-use-it)
 * [How do I use it?](#how-do-i-use-it)
 * [Options](#options)
 * [Callbacks](#callbacks)
 * [Methods](#methods)
 * [License](#license)

# What's so good about it? #

* Pure Javascript - no dependencies
* Self-correcting time based on the system clock - won't go out of time unlike clocks based solely on setInterval or setTimeout (see the link above).
* It can be used to count up from 0:00 or down from a given time.
* It can call a callback function every tick (10 milliseconds) and (for countdown clocks) when the clock reaches 0:00.
* It's about as accurate a clock as you can get with Javascript.

# When would I use it? #

 * Countdown counters, e.g. "site will launch in..."
 * Timers
 * Accurate timing of any repeated action

# How do I use it? #

Tock.js works behind the scenes - it doesn't alter anything on screen - so here I'll show how to make a stop-watch that updates in real-time on screen.

### 1) Make some html to show the clock. ###

      <button id="start">Start</button>
      <button id="stop">Stop</button>
      <input id="clock" value="10:00">
      <script> // javascripts... </script>

### 2) Instantiate a Tock ###

Now we write some Javascript. First we'll create a new instance of Tock and assign it to a variable called *timer*.

    var timer = new Tock();

This will give you a clock that will count up from 00:00 when the start() method is called. The stop() and reset() methods can also be used.

For more control we can pass in some options. *Note that all options are... optional.*

    var timer = new Tock({
      countdown: true,
      interval: 10,
      callback: someCallbackFunction,
      complete: someCompleteFunction
    });

[See available options below](#options)

### 2) Add some controls ###

You'll need some way of controlling your clock. Let's set up some buttons *(using jQuery for example)*.

    $('#start').on('click', function() {
	    timer.start($('#clock').val());
	});

Note that we get the time from the clock input and pass it to the start function as the start time.

    $('#stop').on('click', function() {
	    timer.stop();
	});

If you're not using a countdown clock you can make a reset button, too.

    $('#reset').on('click', function() {
	    timer.reset();
	});

You could also create a reset button if you *are* using a countdown clock, but that's beyond the scope of this walkthrough. The tools are there. Do with them what you can. After this next section you're on your own. Good luck. We're all counting on you.

# Options #

  * **countdown** *boolean*  Default: false. If true, the clock will count down from a given time, otherwise it will count up from 0:00.
  * **interval** *integer* Default: 10. How often, in milliseconds, that the clock will tick.
  * **callback** *function* Default: null (see below)
  * **complete** *function* Default: null (see below)

# Callbacks #

The callback option is a function that will be called once every `interval` milliseconds.

Here we'll use the `lap()` method to get the current clock time (in milliseconds). We'll then pass that through `msToTime()` to format it nicely before displaying it in the `input` field.

    callback: function () {
        var current_time = timer.msToTime(timer.lap());
        $('#clock').val(current_time);
    }

As we are have set `countdown` to `true` we can also pass in a function to call once the countdown reaches zero.

    complete: function () {
        alert("Time's up!");
    }

# Methods #

 * start(time)
   * *time* is only needed if using countdown clock.
      Should be an integer in milliseconds.
 * stop()
   * Stops the clock.
 * pause()
   * Stop the clock if it's running, continue clock if paused.
 * reset()
   * Restart times to zero. Countdown clocks still need a duration to be passed to `start()` after `reset()` is called.
 * lap()
   * Returns elapsed time in milliseconds.
 * msToTime(ms)
   * Note: this is rudimentary - won't handle > 1 hour
 * timeToMS(time)
   Time should be a string of form:
   * "MM:SS"
   * "MM:SS:ms"
   * "yyyy-mm-dd HH:MM:SS.ms"

# License #

MIT License.


text:
package net.kaczmarzyk.spring.data.jpa.domain;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * @author Tomasz Kaczmarzyk
 */
interface FakeSpecWrapper<T> {

	void initializeFakes(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);
}


text:
layout: post
title: Week 5 - When all is said and done
---

"What I've done"?
---
The whole week was a blur until Thursday when I finally submitted all projects for my 3 CS classes. SWE's IDB definitely took a significant amount of time, since there were a lot of requirements to fulfill.

On Friday, after bumping into professor Downing in the elevator and having a brief conversation on competitive programming (CP), I decided to compete in the weekly contest. Retiring from CP for years definitely had its hold on me, especially when it comes to reading long problems and implementing bug-free solutions. I was really disappointed in the sense that I misread one of the problems and spent quite a lot of time debugging another (very) easy problem. However, it was still a lucky day that I secured the 3rd place and won the raffle prize at the end.

What's in my way?
---

The amount of material to digest from my Information Retrieval (IR) and Artificial Intelligence (AI) classes. It just came to my realization that the difficulty of those classes increases pretty quickly over a short span of time while I haven't studied as much as I should have.

I'm also having interviews with some companies that often ask very hard questions. Due to the fact that I dedicated most of my week to school work but not much interview prep, I'm pretty worried that I'm just going to blow up those interviews.

Plan for next week
---

Pick up some React to prepare for the upcoming phases of the IDB project, re-study IR/AI concepts and get a head start on the assignments. Most importantly, practice for the interviews as much as I can.

My experience of the class
---

While learning about the different nuances of Python (and programming languages in general) is pretty intriguing, I'd love to see more of Software Engineering concepts and practices being taught in the class since they are what I initially signed up for. The materials for this class are easy to learn, despite being tricky sometimes.

While I was able to pull off the project before the deadline, there were a lot of trials and errors in between since the project description was demanding yet super vague. I felt like lots of time could be saved if there were a high-level guideline of what steps are to be done.

For example, nowhere in the project description required Python 3 to be used,  so our team went with Python 2.7 at first because it deploys much faster on Google App Engine. However, only a few days before the deadline we saw a comment on Piazza stating the project must be written in Python 3, so we had to start everything all over again. That was a very frustrating experience since we could as well missed that Piazza comment and our 1st project grade will surely suffer.

Tips of the week
---
If you are a UT student who often walks home late at night, I'd highly recommend using [Lyft SURE Ride program](https://blog.lyft.com/posts/ut-safe-rides) as an alternative. You can get home safe, sweat-free between 11PM-4AM every day with the FREE rides provided.


text:
@interface CCLogSystem ()

@property (nonatomic, strong) CCLogController *logController;

@property (nonatomic, strong) NSObject <CCFileOutputRedirectionController> *redirectionController;

@end

@implementation CCLogSystem

+ (CCLogSystem *)defaultLogSystem
{
    static dispatch_once_t onceToken;
    static CCLogSystem *_defaultLogConfigure;
    dispatch_once(&onceToken, ^{
        _defaultLogConfigure = [[self alloc] init];
    });
    return _defaultLogConfigure;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.logController = [[CCLogController alloc] init];
    }
    return self;
}

+ (void)setupDefaultLogConfigure
{
    [self setupLogConfigureWithExceedingTotalLogSize:DEFAULT_EXCEEDING_TOTAL_LOG_SIZE logType:CCLogTypeCCLOG];
}

+ (void)setupLogConfigureWithExceedingTotalLogSize:(unsigned long long)toalLogSize logType:(CCLogType)logType
{
    CCLogSystem *logConfigure = [CCLogSystem defaultLogSystem];

    [logConfigure.logController removeOldLogsExceedingTotalSize:toalLogSize savingAtLeast:10];

    if (!logConfigure.redirectionController) {
        if ([CCLogController forceConsoleLog]) {
            logConfigure.redirectionController = [[CCTeeController alloc] init];
        } else {
            logConfigure.redirectionController = [[CCSimpleFileOutputRedirectionController alloc] init];
        }
        [logConfigure.logController startCapturingLogsWithRedirectionController:logConfigure.redirectionController logType:logType];
        [logConfigure.redirectionController startRecordLog];
    }
}

+ (void)activeDeveloperUI
{
    CCLogViewController *logViewController = [[CCLogViewController alloc] init];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:logViewController];

    UIApplication *application = [UIApplication sharedApplication];
    [application.windows enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKeyWindow]) {
            UIWindow *keyWindow = obj;
            if (keyWindow.rootViewController) {
                [keyWindow.rootViewController presentViewController:navigationController animated:YES completion:NULL];
            }
        }
    }];
}

+ (NSArray *)availableLogs
{
    if ([CCLogSystem defaultLogSystem].logController) {
        return [CCLogSystem defaultLogSystem].logController.availableLogs;
    } else {
        return nil;
    }
}

@end


text:
Chọn
			TK nợ
			Tiền {{ngMasterData.ma_nt}}	 Tiền VND

				<input type='checkbox' ng-model='r.sel'/>

{{r.ten_tk_no}}

				{{r.tk_no}}

				{{r.tien_nt|number:2}}

				{{r.tien|number:0}}

0'>
			Tổng cộng:
			{{ngMasterData.t_tien_nt|number:0}}
			{{ngMasterData.t_tien|number:0}}

			<button class='btn btn-sm btn-primary'  ng-click="addDetail()">Mới</button>
			<button class='btn btn-sm btn-danger' ng-click="deleteRow(ngMasterData.details)" ng-disabled="isNotRowSelected(ngMasterData.details)">Xóa</button>


text:
from django.conf.urls import url
from django.contrib.auth import views as auth_views

from . import views

from fichas.views import FichaList, FichaDetail, FichaSearchView, download_file

app_name = 'fichas'

urlpatterns = [
    url(r'^$', FichaSearchView.as_view(), name='search'),
    url(r'^media/(?P<name>[\w\.]+)$', download_file, name='media'),
    url(r'^search/$', FichaList.as_view(), name='ficha-list'),
    url(r'^(?P<pk>[0-9]+)/$', FichaDetail.as_view(), name='ficha-detail'),

]


text: $HADOOP_PREFIX/bin/yarn --config $HADOOP_CONF_DIR resourcemanager


text: java -jar lib/standalone/jruby-complete.jar src/watir_robot_gui.rb


text:
import { Injectable } from "@angular/core"
import { RequestOptions, Headers, Http, Response } from "@angular/http"

import { Observable } from "rxjs/Observable"

import { Invoice } from "./invoice.model"

@Injectable()
export class InvoicesService {

  private invoicesUrl = "api/invoices"
  private options = new RequestOptions({ headers: new Headers({ "Content-Type": "application/json" }) })

  constructor(private http: Http) {}

  getInvoices(): Observable<Invoice[]> {
    return this.http.get(this.invoicesUrl)
      .map(this.extractData)
      .catch(this.handleError)
  }

  getInvoice(id: string): Observable<Invoice> {
    return this.http.get(`${this.invoicesUrl}/${id}`)
      .map(this.extractData)
      .catch(this.handleError)
  }

  createInvoice(invoice: Invoice): Observable<Invoice> {
    return this.http.post(this.invoicesUrl, JSON.stringify(invoice), this.options)
      .map(this.extractData)
      .catch(this.handleError)
  }

  updateInvoice(invoice: Invoice): Observable<Invoice> {
    return this.http.put(`${this.invoicesUrl}/${invoice._id}`, JSON.stringify(invoice), this.options)
      .map(this.extractData)
      .catch(this.handleError)
  }

  deleteInvoice(invoice: Invoice): Observable<Invoice> {
    return this.http.delete(`${this.invoicesUrl}/${invoice._id}`)
      .map(this.extractData)
      .catch(this.handleError)
  }

  private extractData(response: Response): Observable<any> {
    return response.json() || {}
  }

  private handleError(error: any): Observable<any> {
    return Observable.throw(error)
  }

}


text:
{% comment %}
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.
{% endcomment %}

      {{ post.title }}
      ∞

    {% capture discard %}
      {% for c in site.data.contributors %}
        {% if c.apacheId == post.author %}
          {% assign author_name = c.name %}
          {% if c.homepage %}
            {% assign homepage = c.homepage %}
          {% else %}
            {% capture homepage %}http://github.com/{{ c.githubId }}{% endcapture %}
          {% endif %}
          {% if c.avatar %}
            {% assign avatar = c.avatar %}
          {% else %}
            {% capture avatar %}http://github.com/{{ c.githubId }}.png{% endcapture %}
          {% endif %}
        {% endif %}
      {% endfor %}
    {% endcapture %}{% assign discard = nil %}

      Published

        {{ post.date | date_to_string }}

      By
      {{ author_name }} ({{ post.author }})

    {{ post.content }}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  <meta name="description" content="Javadoc API documentation for TrAP API." />

<link rel="shortcut icon" type="image/x-icon" href="../../../../../favicon.ico" />
<title>

  IPUtil

| TrAP API

</title>
<link href="../../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />

      TrAP API

          <form accept-charset="utf-8" class="gsc-search-box"
                onsubmit="return submit_search()">

                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../../../')"
                      onkeyup="return search_changed(event, false, '../../../../../')" />

                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />

          </form>

<nobr>
                Package Index |
                Class Index</nobr>

  com.ericsson.research.trap

  com.ericsson.research.trap.auth

  com.ericsson.research.trap.delegates

  com.ericsson.research.trap.examples

  com.ericsson.research.trap.spi

  com.ericsson.research.trap.spi.queues

  com.ericsson.research.trap.utils

Interfaces

Callback<T>

Callback.SingleArgumentCallback<T>

Configuration

Future

Classes

Base64

Block

ByteConverter

ConditionalBlock

HexConverter

HexDump

IPUtil

Lock

LRUCache<K, V>

PackageScanner

SSLUtil

SSLUtil.SSLMaterial

StringUtil

ThreadPool

UID

UUID

<nobr>
            Package Index |
            Class Index</nobr>

Summary:

  Methods

  | Inherited Methods

| [Expand All]

    public

    abstract
    class

IPUtil

    extends Object

        java.lang.Object

               ↳

        com.ericsson.research.trap.utils.IPUtil

Class Overview

A collection of checks for IP addresses. These utilities provide convenience
 methods not covered by the Java API.

Summary

Public Methods

        <nobr>

            static

            String</nobr>

        <nobr>
        getAddressForURI(InetAddress address)</nobr>

Gets a URI-safe address of an InetAddress.

        <nobr>

            static

            InetAddress[]</nobr>

        <nobr>
        getPublicAddresses()</nobr>

Gets an array of the publicly accesisble IP addresses of the JVM.

        <nobr>

            static

            boolean</nobr>

        <nobr>
        isLocal(InetAddress address)</nobr>

Checks whether an InetAddress is a local (=virtual address space).

  [Expand]

Inherited Methods

From class

  java.lang.Object

        <nobr>

            Object</nobr>

        <nobr>
        clone()</nobr>

        <nobr>

            boolean</nobr>

        <nobr>
        equals(Object arg0)</nobr>

        <nobr>

            void</nobr>

        <nobr>
        finalize()</nobr>

        <nobr>

            final

            Class<?></nobr>

        <nobr>
        getClass()</nobr>

        <nobr>

            int</nobr>

        <nobr>
        hashCode()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        notify()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        notifyAll()</nobr>

        <nobr>

            String</nobr>

        <nobr>
        toString()</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long arg0, int arg1)</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait(long arg0)</nobr>

        <nobr>

            final

            void</nobr>

        <nobr>
        wait()</nobr>

Public Methods

        public
        static

        String

      getAddressForURI
      (InetAddress address)

Gets a URI-safe address of an InetAddress. For example, returns
 127.0.0.1 for localhost in IPv4, and [::1] for
 localhost in IPv6.

Parameters

          address
          The address to convert

Returns

A string representation of the address that is safe to insert
         into a URI.

        public
        static

        InetAddress[]

      getPublicAddresses
      ()

Gets an array of the publicly accesisble IP addresses of the JVM.

Returns

an array of the publicly accesisble IP addresses of the JVM.

        public
        static

        boolean

      isLocal
      (InetAddress address)

Checks whether an InetAddress is a local (=virtual address space). For
 example, 127.0.0.1 returns true, while 8.8.8.8 returns false.

Parameters

          address
          The address to verify.

Returns

true if the address is defined in an address space that is
         routable from the Internet, false otherwise.

Generated by Doclava.


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class UnifiedProcedureStepState extends AbstractTag
{

    protected $Id = '0074,1000';

    protected $Name = 'UnifiedProcedureStepState';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Unified Procedure Step State';
}


text:
using Ds3.Helpers;
using Ds3.Models;
using Ds3Client.Api;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;

namespace Ds3Client.Commands.Api
{
    [Cmdlet(VerbsCommunications.Read, DS3Nouns.Object)]
    public class ReadObjectCommand : BaseApiCommand
    {
        private const string ToLocalFileParamSet = "ToLocalFileParamSet";
        private const string ToLocalFolderParamSet = "ToLocalFolderParamSet";

        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
        public string BucketName { get; set; }

        [Alias(new string[] { "Name" })]
        [Parameter(Position = 1, ParameterSetName = ToLocalFileParamSet, ValueFromPipelineByPropertyName = true, Mandatory = true)]
        public string Key { get; set; }

        [Parameter(Position = 2, ParameterSetName = ToLocalFileParamSet, Mandatory = true)]
        public string File { get; set; }

        [Alias(new string[] { "Directory" })]
        [Parameter(ParameterSetName = ToLocalFolderParamSet, Mandatory = true)]
        public string Folder { get; set; }

        protected override void ProcessRecord()
        {
            switch (this.ParameterSetName)
            {
                case ToLocalFileParamSet: WriteToLocalFile(); break;
                case ToLocalFolderParamSet: WriteToLocalFolder(); break;
                default: throw new ApiException(Resources.InvalidParameterSetException);
            }
        }

        private void WriteToLocalFile()
        {
            var file = Path.GetFullPath(Path.Combine(this.SessionState.Path.CurrentFileSystemLocation.Path, File));
            if (System.IO.File.Exists(file))
            {
                throw new ApiException(Resources.FileAlreadyExistsException, file);
            }

            new Ds3ClientHelpers(CreateClient())
                .StartReadJob(this.BucketName, new[] { new Ds3Object(this.Key, null) })
                .Transfer(key => System.IO.File.OpenWrite(file));
        }

        private void WriteToLocalFolder()
        {
            var folder = Path.GetFullPath(Path.Combine(this.SessionState.Path.CurrentFileSystemLocation.Path, Folder));
            if (Directory.Exists(folder))
            {
                throw new ApiException(Resources.DirectoryAlreadyExistsException, folder);
            }

            new Ds3ClientHelpers(CreateClient())
                .StartReadAllJob(BucketName)
                .Transfer(FileHelpers.BuildFileGetter(folder));
        }
    }
}