text:
<?php
//  AcmlmBoard XD - User account registration page
//  Access: any, but meant for guests.
$crumbs = new PipeMenu();
$crumbs->add(new PipeMenuLinkEntry(__("Register"), "register"));
makeBreadcrumbs($crumbs);
$title = __("Register");

if($loguserid)
    Kill(__("You already have an account"));

if(Settings::get("registration"))
    Kill(__("Account registrations are disabled"));

#StopForumSpam protection goes here

function validateSex($sex)
{
	if($sex == 0) return 0;
	if($sex == 1) return 1;
	if($sex == 2) return 2;
	return 2;
}
if(isset($_POST['name']))
{
	$name = trim($_POST['name']);
	$cname = str_replace(" ","", strtolower($name));
	$rUsers = Query("select name, displayname from {users}");
	while($user = Fetch($rUsers))
	{
		$uname = trim(str_replace(" ", "", strtolower($user['name'])));
		if($uname == $cname)
			break;
		$uname = trim(str_replace(" ", "", strtolower($user['displayname'])));
		if($uname == $cname)
			break;
	}
	$ipKnown = FetchResult("select COUNT(*) from {users} where lastip={0}", $_SERVER['REMOTE_ADDR']);
	//This makes testing faster.
	if($_SERVER['REMOTE_ADDR'] == "127.0.0.1")
		$ipKnown = 0;
	if($uname == $cname)
		$err = __("This user name is already taken. Please choose another.");
	else if($name == "" || $cname == "")
		$err = __("The user name must not be empty. Please choose one.");
    else if (Settings::get("forcemail") && !$email)
        $err = __("You must specify an e-mail address");
	else if(strpos($name, ";") !== false)
		$err = __("The user name cannot contain semicolons.");
	elseif($ipKnown >= 3)
		$err = __("You already have an account.");
	else if ($_POST['pass'] !== $_POST['pass2'])
		$err = __("The passwords you entered don't match.");
    else if(strlen($_POST['pass']) < 8)
		$err = __("Your password must be at least eight characters long.");

	/*if(!$err) #Enable this only if you're using the StopForumSpam addition
	{
		$reasons = array();
		if(IsTorExitPoint()) {
			$reasons[] = 'tor';
		}
		$s = new StopForumSpam($stopForumSpamKey);
		if($s->is_spammer(array('email' => $_POST['email'], 'ip' => $_SERVER['REMOTE_ADDR'] ))) {
			$reasons[] = 'sfs';
		}
		if(count($reasons)) {
			$reason = implode(',', $reasons);
			$bucket = "regfail"; include("lib/pluginloader.php");
			$err = 'An unknown error occured, please try again.';
		}
	}*/
	if($err)
	{
		Alert($err);
	}
	else
	{
		$newsalt = Shake();
		$sha = doHash($_POST['pass'].$salt.$newsalt);
		$sex = validateSex($_POST["sex"]);
		$rUsers = Query("insert into {users} (name, password, pss, regdate, lastactivity, lastip, email, sex, theme) values ({0}, {1}, {2}, {3}, {3}, {4}, {5}, {6}, {7})", $_POST['name'], $sha, $newsalt, time(), $_SERVER['REMOTE_ADDR'], $_POST['email'], $sex, Settings::get("defaultTheme"));
		$uid = insertId();
		if($uid == 1)
			Query("update {users} set powerlevel = 4 where id = 1");
		logAction('register', array('user' => $uid));
		$user = Fetch(Query("select * from {users} where id={0}", $uid));
		$user["rawpass"] = $_POST["pass"];
		$bucket = "newuser"; include("lib/pluginloader.php");
		$sessionID = Shake();
		setcookie("logsession", $sessionID, 0, $boardroot, "", false, true);
		Query("INSERT INTO {sessions} (id, user, autoexpire) VALUES ({0}, {1}, {2})", doHash($sessionID.$salt), $user["id"], 0);
		redirectAction("board");
	}
}
$sexes = array(__("Male"), __("Female"), __("N/A"));
$name = "";
if(isset($_POST["name"]))
	$name = htmlspecialchars($_POST["name"]);
$email = "";
if(isset($_POST["email"]))
	$email = htmlspecialchars($_POST["email"]);
$sex = 2;
if(isset($_POST["sex"]))
	$sex = validateSex($_POST["sex"]);
//TODO: Kill dumb echo -.-
echo "

<form action=\"".actionLink("register")."\" method=\"post\">

				".__("Register")."

				".__("User name")."

				<input type=\"text\" id=\"un\" name=\"name\" value=\"$name\" maxlength=\"20\" style=\"width: 98%;\"  class=\"required\" />

				".__("Password")."

				<input type=\"password\" id=\"pw\" name=\"pass\" size=\"13\" maxlength=\"32\" class=\"required\" /> / ".__("Repeat:")." <input type=\"password\" id=\"pw2\" name=\"pass2\" size=\"13\" maxlength=\"32\" class=\"required\" />

				".__("Email address")."

				<input type=\"email\" id=\"email\" name=\"email\" value=\"$email\" style=\"width: 98%;\" maxlength=\"60\" />

				".__("Sex")."

				".MakeOptions("sex",$sex,$sexes)."

";
echo "

				<input type=\"submit\" name=\"action\" value=\"".__("Register")."\"/>

				".__("Specifying an email address is not exactly a hard requirement, but it will allow you to reset your password should you forget it. By default, your email is not shown.")."

</form>";

function MakeOptions($fieldName, $checkedIndex, $choicesList) {
	$checks[$checkedIndex] = " checked=\"checked\"";
	foreach($choicesList as $key=>$val)
		$result .= format("

						<input type=\"radio\" name=\"{1}\" value=\"{0}\"{2} />
						{3}
					", $key, $fieldName, $checks[$key], $val);
	return $result;
}


text:
package com.siso.app.ui;

import com.easemob.EMCallBack;
import com.siso.app.common.Constants;
import com.siso.app.ui.common.BaseFragment;
import com.siso.app.utils.AccountInfoUtils;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

public class SettingFragment extends BaseFragment implements OnClickListener {

	private static final String TAG = "SettingFragment";

	private View mView;
	private RelativeLayout setAccount;
	private RelativeLayout feedback;
	private RelativeLayout aboutus;
	private Button loginoutBtn;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mView = (View) inflater.inflate(R.layout.fragment_setting, null);
		initView();
		return mView;
	}

	private void initView() {
		setAccount = (RelativeLayout) mView.findViewById(R.id.setting_account);
		loginoutBtn = (Button)mView.findViewById(R.id.loginOut);
		feedback = (RelativeLayout) mView.findViewById(R.id.feedback);
		aboutus = (RelativeLayout) mView.findViewById(R.id.aboutus);

		setAccount.setOnClickListener(this);
		loginoutBtn.setOnClickListener(this);
		feedback.setOnClickListener(this);
		aboutus.setOnClickListener(this);
		if(MyApplication.userInfo==null){
			loginoutBtn.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.setting_account:
			if (Constants.ISLOGIN) startActivity(new Intent(getActivity(),AccountSetting.class));
			else showButtomToast("亲,你还没登录~");
			break;
		case R.id.loginOut:
			loadingProgressDialog.show();
			MyApplication.getInstance().logout(new EMCallBack() {

				@Override
				public void onSuccess() {
					getActivity().runOnUiThread(new Runnable() {
						public void run() {
							loadingProgressDialog.dismiss();
							AccountInfoUtils.loginOut(getActivity());
							showButtomToast(getStringByRId(R.string.loginout_success));
							Intent intent = new Intent(getActivity(),ChooseSchoolActivity.class);
							intent.putExtra("isFirst", true);
							startActivity(intent);
							getActivity().finish();
						}
					});
				}

				@Override
				public void onProgress(int progress, String status) {
					loadingProgressDialog.setMessage(getString(R.string.loginouting));
				}

				@Override
				public void onError(int code, String message) {

				}
			});
			break;
		case R.id.feedback:
			startActivity(new Intent(getActivity(),FeedbackActivity.class));
			break;
		case R.id.aboutus:
			startActivity(new Intent(getActivity(),AboutActivity.class));
			break;
		default:
			break;
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
`td-chart-x-axis` and `td-chart-y-axis` elements generate an axis inside a `td-chart`. Its the equivalent of creating a JS xAxis/yAxis object in echarts.

## API Summary

#### Inputs

- config?: any
  - Sets the JS config object if you choose to not use the property inputs.
  - Note: [config] input properties will override input values

There are also lots of property inputs like:

- id?: string
  - It can be used to refer the component in option or API.
- name?: string
  - Location of axis name.
- type?: 'value' | 'category' | 'time' | 'log'
  - Type of axis
- min?: number
  - The minimun value of axis.
- max?: number
  - The maximum value of axis.

And so many more.. for more info on xAxis [click here](https://echarts.apache.org/en/option.html#xAxis) and yAxis [click here](https://echarts.apache.org/en/option.html#yAxis)

## Setup

Import the [CovalentBaseEchartsModule] in your NgModule:

```typescript
import { CovalentBaseEchartsModule } from '@covalent/echarts/base';
@NgModule({
  imports: [
    CovalentBaseEchartsModule,
    ...
  ],
  ...
})
export class MyModule {}
```

## Usage

Basic Tooltip Example:

```html
<td-chart>
  <td-chart-x-axis
    [show]="true"
    [type]="'category'"
    [data]="['Electronics', 'Toys', 'Grocery', 'Appliances', 'Automotive', 'Sports']"
  >
  </td-chart-x-axis>
  <td-chart-y-axis [show]="true" [type]="'value'"> </td-chart-y-axis>
</td-chart>
```


text:
package cn.cug.laboratory.service.impl;

import cn.cug.laboratory.service.BaseService;

/**
 * @autor shixing
 * @since 1.0.0
 */

public class BaseServiceImpl<T> implements BaseService<T>{

    @Override
    public void insertSelective(T record) {

    }

    @Override
    public void deleteByPrimaryKey(Integer id) {

    }

    @Override
    public int updateByPrimaryKeySelective(T record) {
        return 0;
    }

    @Override
    public T selectByPrimaryKey(String id) {
        return null;
    }
}


text:
.extension-alert {
	position: absolute;
	z-index: 10000;

	width: 100%;

	text-align: center;

	color: #8a6d3b;
	border-width: thin;
	border-style: solid;
	border-color: #faebcc;
	background-color: #fcf8e3;
}

.extension-alert > button {
	margin: 2px 12px;
	padding: 2px 10px;

	color: white;
	border-radius: 8px;
	background: #c18a17;
}

.extension-alert > button:hover {
	background: #dea123;
}

.extension-alert > .icon-cancel {
	float: right;
}

.extension-configuration {
	position: absolute;
	z-index: 10000;
	top: 0;
	left: 0;

	width: 100%;
	height: 100%;

	text-align: center;

	background-color: rgba(0, 0, 0, 0.4);
}

.extension-configuration > .configuration-text {
	position: relative;

	width: 50%;
	margin: 0 auto;
	margin-top: 10%;
	padding: 30px;

	border-radius: 5px;
	background-color: white;
	box-shadow: 0 15px 50px rgba(0, 0, 0, 0.7);
}

.extension-configuration > .configuration-text .configuration-title {
	margin-bottom: 20px;

	font-size: medium;
	font-weight: bold;
}

.extension-configuration > .configuration-text img {
	display: block;

	margin-right: auto;
	margin-left: auto;
	padding: 10px;
}

.extension-configuration > .configuration-text > ul {
	text-align: left;
}

.extension-configuration > .configuration-text > button {
	padding: 10px;

	color: white;
	border-radius: 7px;
	background: #13679a;
}

.extension-configuration > .configuration-text > button:hover {
	background: #115d8b;
}

.popup-warning {
	position: relative;
	z-index: 10000;
	top: -25px;
	left: -20px;

	float: right;

	width: 250px;

	text-align: center;
}

.popup-warning > .popup-warning-text {
	position: relative;

	width: 100%;
	margin: 0 auto;
	margin-top: 20%;
	padding: 30px;

	border-radius: 5px;
	background-color: white;
	box-shadow: 0 15px 50px rgba(0, 0, 0, 0.7);
}

.popup-warning > .popup-warning-text > img {
	display: block;
	float: left;

	margin-right: auto;
	margin-left: auto;
	padding: 10px;
}

.popup-warning::after,
.popup-warning::before {
	position: absolute;
	z-index: 10000;
	top: 0%;
	left: 20%;

	width: 0;
	height: 0;

	content: " ";
	pointer-events: none;

	border: solid transparent;
}

.popup-warning::before {
	margin-left: -30px;

	border-width: 30px;
	border-bottom-color: white;
}


text:
package eecs2030.lab6;

/**
 * This class is incomplete - implemented sufficiently only to enable Circle
 * objects to be added and queried from a list.
 *
 *
 * For other types of comparisons (equality, compareTo etc, a more complete version is necessary)
 *
 * @author
 *
 */
public class Circle {

	private int x;
	private int y;

	private int radius;

	public Circle() {

		this(0,0,1);

	}

	public Circle(int x, int y, int radius) {

		this.x = x;
		this.y = y;

		this.radius = radius;

	}

	public int getX() {
		return this.x;
	}

	public int getY() {
		return this.y;
	}
	public int getRad() {
		return this.radius;
	}

}


text:
set -e

export DEBIAN_FRONTEND=noninteractive

if [ "$EUID" -ne 0 ]
then
    echo "You must run the install script as root!"
    exit
fi

cd director/

# Install conductor-agent dependencies
apt-get install -y lxc
pip3 install -U pip
pip3 install -U Flask gunicorn dnspython

# Set up Debian virtual machine template
mkdir -p /var/conductor/debian/rootfs/
mkdir -p /usr/local/var/lib/lxc/
cp conductor/vm_config /var/conductor/debian/config
cp conductor/vm_create /var/conductor/debian/create

# Install Debian on the rootfs
if [ -z "$(ls -A /var/conductor/debian/rootfs)" ]; then
    debootstrap --include=openssh-server stable /var/conductor/debian/rootfs https://deb.debian.org/debian/
fi

supervisorctl start conductoragent


text: Define the URL to get the Chuck Norris Facts. Example: http://api.icndb.com/jokes/random/


text:
package org.jbpm.test.persistence.objects;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Patient implements Serializable{
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;
    @OneToOne(optional=true, mappedBy="patient")
    private MedicalRecord record;
    @Temporal(TemporalType.TIMESTAMP)
    private Date nextAppointment;

    public Patient() {
    }

    public Patient(String name) {
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getNextAppointment() {
        return nextAppointment;
    }

    public void setNextAppointment(Date nextAppointment) {
        this.nextAppointment = nextAppointment;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public MedicalRecord getRecord() {
        return record;
    }

    public void setRecord(MedicalRecord record) {
        this.record = record;
    }

    @Override
    public String toString() {
        return "Patient{" + "id=" + id + ", name=" + name + ", record=" + record + ", nextAppointment=" + nextAppointment + '}';
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Patient other = (Patient) obj;
        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if (this.record != other.record && (this.record == null || !this.record.equals(other.record))) {
            return false;
        }
        if (this.nextAppointment != other.nextAppointment && (this.nextAppointment == null || !this.nextAppointment.equals(other.nextAppointment))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0);
        hash = 47 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 47 * hash + (this.record != null ? this.record.hashCode() : 0);
        hash = 47 * hash + (this.nextAppointment != null ? this.nextAppointment.hashCode() : 0);
        return hash;
    }

}


text:
var customInterpolationApp = angular.module('customInterpolationApp', []);

customInterpolationApp.config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('[[');
  $interpolateProvider.endSymbol(']]');
});


text:
package utility

import (
	"encoding/hex"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
	"time"

	. "github.com/smartystreets/goconvey/convey"
)

// Test that Check(e) exits
// this is how you test fails
func TestCheck(t *testing.T) {
	err := errors.New("test check function")

	if os.Getenv("CRASHED") == "1" {
		Check(err)
		return
	}

	cmd := exec.Command(os.Args[0], "-test.run=TestCheck")
	cmd.Env = append(os.Environ(), "CRASHED=1")
	err = cmd.Run()
	if e, ok := err.(*exec.ExitError); ok && !e.Success() {
		return
	}
	t.Fatalf("process ran with err %v, want exit status 1", err)
}

func TestSliceIndex(t *testing.T) {
	Convey("Slice index", t, func() {
		Convey("should return element position in slice", func() {

			xs := []int{2, 4, 6, 8}
			ys := []string{"C", "B", "K", "A"}

			index, err := SliceIndex(len(xs), func(i int) bool { return xs[i] == 5 })
			So(index, ShouldEqual, -1)
			So(err, ShouldNotBeNil)

			index, err = SliceIndex(len(xs), func(i int) bool { return xs[i] == 6 })
			So(index, ShouldEqual, 2)
			So(err, ShouldBeNil)

			index, err = SliceIndex(len(ys), func(i int) bool { return ys[i] == "Z" })
			So(index, ShouldEqual, -1)
			So(err, ShouldNotBeNil)

			index, err = SliceIndex(len(ys), func(i int) bool { return ys[i] == "A" })
			So(index, ShouldEqual, 3)
			So(err, ShouldBeNil)
		})
	})
}

func TestRoundFloat64(t *testing.T) {
	Convey("Round a float64 to x decimal places", t, func() {
		Convey("should return a valid rounded float64", func() {

			// define input and expected result
			type testdata struct {
				number float64
				places int
				result float64
			}

			// define test data
			var tests = []testdata{
				{27865428945.7825346789253, 2, 27865428945.78},
				{27865428945.7825346789253, 6, 27865428945.782535},
				{27865428945.7825346789253, 1, 27865428945.8},
				{0.7825346789253, 4, 0.7825},
				{0.782549000, 4, 0.7825},
				{-0.78255000, 4, -0.7826},
				{0.0, 0, 0},
			}

			// run tests
			for _, test := range tests {
				result := RoundFloat64(test.number, test.places)
				fmt.Printf("\n       %f, %f ", result, test.result)
				match := Float64Equal(result, test.result)
				So(match, ShouldEqual, true)
			}
		})
	})
}

func TestRoundDuration(t *testing.T) {
	Convey("Round a time.Duration", t, func() {
		Convey("should return a valid rounded duration", func() {

			// define input and expected result
			type testdata struct {
				period  time.Duration
				roundTo time.Duration
				result  time.Duration
			}

			// define test data
			var tests = []testdata{
				{500 * time.Millisecond, time.Second, 1 * time.Second},
				{499 * time.Millisecond, time.Second, 0 * time.Second},
				{500 * time.Millisecond, 0 * time.Second, 500 * time.Millisecond},
				{-500 * time.Millisecond, time.Second, -1 * time.Second},
			}

			// run tests
			for _, test := range tests {
				result := RoundDuration(test.period, test.roundTo)
				fmt.Printf("\n       %v, %v ", result, test.result)
				So(result, ShouldEqual, test.result)
			}
		})
	})
}

func TestFloat64Equal(t *testing.T) {
	Convey("compare float64 values", t, func() {
		Convey("should return equivalent `true` if values match", func() {

			// define input and expected result
			type testdata struct {
				valueOne float64
				valueTwo float64
				result   bool
			}

			// NOTE epsilon = 0.00000001

			// define test data
			var tests = []testdata{
				{0.0, 0.0, true},
				{0.0, 0.1, false},
				{0.0, 0.000000009, true},
				{0.0, 0.00000001, false}, //epsilon
				{0.0, 0.00000099, false},
				{435.9, 435.89999999, true},
			}

			// run tests
			for _, test := range tests {
				result := Float64Equal(test.valueOne, test.valueTwo)
				fmt.Printf("\n       %v, %v ", result, test.result)
				So(result, ShouldEqual, test.result)
			}
		})
	})
}

func TestMakeFileName(t *testing.T) {
	Convey("Making a new filename", t, func() {
		Convey("should return a unique filename with extension .ach", func() {
			filename := MakeFileName(".ach", "test/")
			ext := filepath.Ext(filename)
			So(filename, ShouldNotEqual, "")
			So(ext, ShouldEqual, ".ach")
		})
	})
}

func TestGetLocalIP(t *testing.T) {
	Convey("Function GetLocalIP", t, func() {
		Convey("Should return the local IP address", func() {
			result, err := GetLocalIP()
			So(result, ShouldNotEqual, "")
			So(err, ShouldEqual, nil)
		})
	})
}

func TestPadding(t *testing.T) {

	Convey("if string to be padded is longer than length (l)", t, func() {
		Convey("it should return an error", func() {
			res, err := Padding("abc", 1, "right", " ")
			So(res, ShouldEqual, "")
			So(err, ShouldNotBeNil)
			So(err.Error(), ShouldEqual, "string is too long")
		})
	})

	Convey("if justified is not \"right\" or \"left\"", t, func() {
		Convey("it should return an error", func() {
			res, err := Padding("abc", 10, "hello", " ")
			So(res, ShouldEqual, "")
			So(err, ShouldNotBeNil)
			So(err.Error(), ShouldEqual, "justification must be either right or left")
		})
	})

	Convey("if Padding character is longer than 1 character", t, func() {
		Convey("it should return an error", func() {
			res, err := Padding("abc", 10, "right", "12")
			So(res, ShouldEqual, "")
			So(err, ShouldNotBeNil)
			So(err.Error(), ShouldEqual, "padding must be only one character")
		})
	})

	Convey("if string is \"abc\" and length is 10, and justification is \"left\"", t, func() {
		Convey("it should return \"abc       \"", func() {
			res, err := Padding("abc", 10, "left", " ")
			So(res, ShouldEqual, "abc       ")
			So(err, ShouldBeNil)
		})
	})

	Convey("if string is \"abc\" and length is 10, and justification is \"right\"", t, func() {
		Convey("it should return \"       abc\"", func() {
			res, err := Padding("abc", 10, "right", " ")
			So(res, ShouldEqual, "       abc")
			So(err, ShouldBeNil)
		})
	})

	Convey("if string is \"abc\", length is 10, justification is \"right\" and Padding character is \"0\"", t, func() {
		Convey("it should return \"0000000abc\"", func() {
			res, err := Padding("abc", 10, "right", "0")
			So(res, ShouldEqual, "0000000abc")
			So(res, ShouldNotEqual, "       abc")
			So(err, ShouldBeNil)
		})
	})

}

func TestCalcSettlementDate(t *testing.T) {
	Convey("Calculate settement date", t, func() {
		Convey("should return a valid settlement date", func() {

			const timeFormat = "060102"

			// Make a map of bank holidays
			var bankHolidayMap = make(map[string]bool)

			var holidayList = []string{
				"160704",
				"160904",
				"161009",
				"161110",
				"160722", // Friday holiday
			}

			for _, holiday := range holidayList {
				bankHolidayMap[holiday] = true
			}

			// define input date and expected result
			type testpair struct {
				date   string
				result string
			}

			// define test data
			var tests = []testpair{
				{"160629", "160630"}, // regular weekday
				{"160630", "160701"}, // Thursday
				{"160701", "160705"}, // weekend & *holiday
				{"160708", "160711"}, // Friday
				{"160709", "160711"}, // Saturday
				{"160710", "160711"}, // Sunday
				{"160704", "160705"}, // *holiday
				{"160721", "160725"}, // *holiday falls on Friday
			}

			// run tests
			for _, testData := range tests {
				testDate, _ := time.Parse(timeFormat, testData.date)
				result := CalcSettlementDate(testDate, bankHolidayMap)
				So(result.Format(timeFormat), ShouldEqual, testData.result)
			}
		})
	})
}

func TestGenRandomString(t *testing.T) {
	Convey("Generate a hexadecimal random string", t, func() {
		Convey("should return a valid hexadecimal string of length l", func() {

			// define input and expected result
			type testdata struct {
				length int
				result int
			}

			// define test data.  Hexadecimal
			// result is double the length
			var tests = []testdata{
				{0, 0}, // err test
				{1, 2},
				{2, 4},
				{20, 40},
				{-1, 0}, // err test
			}

			// run tests
			for _, test := range tests {
				result := GenRandomString(test.length)
				// make sure it's hex (we can decode it)
				_, err := hex.DecodeString(result)
				So(err, ShouldBeNil)
				So(len(result), ShouldEqual, test.result)
			}
		})
	})
}


text:
package me.shuza.rxformvalidation;

import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import com.jakewharton.rxbinding2.widget.RxTextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.subscribers.DisposableSubscriber;

public class MainActivity extends AppCompatActivity {
    @BindView(R.id.etFirstName)
    EditText etFirstName;

    @BindView(R.id.etLastName)
    EditText etLastName;

    @BindView(R.id.etEmail)
    EditText etEmail;

    @BindView(R.id.btnSubmit)
    Button btnSubmit;

    private String TAG = this.getClass().getSimpleName();

    private DisposableSubscriber<Boolean> disposableSubscriber = null;
    private Flowable<CharSequence> firstNameChangeObservable;
    private Flowable<CharSequence> lastNameChangeObservable;
    private Flowable<CharSequence> emailChangeObservable;
    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        unbinder = ButterKnife.bind(this);

        firstNameChangeObservable = RxTextView.textChanges(etFirstName).skip(1).toFlowable(BackpressureStrategy.LATEST);
        lastNameChangeObservable = RxTextView.textChanges(etLastName).skip(1).toFlowable(BackpressureStrategy.LATEST);
        emailChangeObservable = RxTextView.textChanges(etEmail).skip(1).toFlowable(BackpressureStrategy.LATEST);

        combineLatestEvents();
    }

    private void combineLatestEvents() {
        disposableSubscriber = new DisposableSubscriber<Boolean>() {
            @Override
            public void onNext(Boolean isValidForm) {
                if (isValidForm) {
                    btnSubmit.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
                } else {
                    btnSubmit.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.gray));
                }
            }

            @Override
            public void onError(Throwable t) {
                Log.d(TAG, "onError       ==/   " + t.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "onComplete       ==/    called");
            }
        };

        Flowable.combineLatest(firstNameChangeObservable, lastNameChangeObservable, emailChangeObservable,
                (firstName, lastName, email) -> {
                    boolean isValidFirstName = firstName != null && firstName.length() > 3;
                    if (!isValidFirstName) {
                        etFirstName.setError("Invalid first name");
                    }

                    boolean isValidLastName = lastName != null && lastName.length() > 3;
                    if (!isValidLastName) {
                        etLastName.setError("Invalid last name");
                    }

                    boolean isValidEmail = email != null && Validator.isValidEmailAddress(String.valueOf(email));
                    if (!isValidEmail) {
                        etEmail.setError("Invalid email addess");
                    }

                    return isValidFirstName && isValidLastName && isValidEmail;
                })
                .subscribe(disposableSubscriber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        disposableSubscriber.dispose();
    }
}


text:
/*global console*/
var SelectView = require('../ampersand-select-view');
var FormView = require('ampersand-form-view');

var Model = require('ampersand-state').extend({
    props: {
        id: 'string',
        title: 'string'
    }
});
var Collection = require('ampersand-collection').extend({
    model: Model
});

var collection1 = new Collection([
    { id: 'foo', title: 'Foo Option' },
    { id: 'bar', title: 'Bar Option' },
    { id: 'baz', title: 'Baz Option' }
]);

var BaseView = FormView.extend({
    fields: function () {
        return [
            new SelectView({
                name: 'one.1',
                parent: this,
                options: ['a', 'b', 'c'],
                unselectedText: 'please choose one'
            }),
            new SelectView({
                name: 'one.2',
                parent: this,
                options: ['a', 'b', 'c'],
                unselectedText: 'please choose one'
            }),
            new SelectView({
                name: 'one.3',
                parent: this,
                options: ['a', 'b', 'c'],
                value: 'c',
                unselectedText: 'please choose one'
            }),

            new SelectView({
                name: 'two.1',
                parent: this,
                options: [ ['a', 'Option A'], ['b', 'Option B'], ['c', 'Option C'] ],
                unselectedText: 'please choose one'
            }),
            new SelectView({
                name: 'two.2',
                parent: this,
                options: [ ['a', 'Option A'], ['b', 'Option B'], ['c', 'Option C'] ],
                value: 'b',
                unselectedText: 'please choose one'
            }),

            new SelectView({
                name: 'three.1',
                parent: this,
                options: collection1,
                value: collection1.at(2),
                idAttribute: 'id',
                textAttribute: 'title',
                unselectedText: 'please choose one'
            }),

            new SelectView({
                name: 'three.1',
                parent: this,
                options: collection1,
                value: collection1.at(2),
                idAttribute: 'id',
                textAttribute: 'title',
                yieldModel: false
            }),

            new SelectView({
                name: 'select-only',
                parent: this,
                options: ['a', 'b', 'c'],
                template: '<select></select>'
            })
        ];
    }
});

document.addEventListener('DOMContentLoaded', function () {
    var baseView = new BaseView({el: document.body });
    baseView.on('all', function (name, field) {
        console.log('Got event', name, field.value, field.valid);
    });
    baseView.render();

    //cycle a field
    var i = 0;
    var field = baseView.getField('one.3');
    var options = [null].concat(field.options);

    setInterval(function () {
        i = (i + 1) % (field.options.length + 1);

        baseView.getField('one.3').setValue(options[i]);
    }, 1000);

    //Add options to a collection field
    setInterval(function () {
        collection1.add({ id: new Date().toString(), title: new Date().toString() });
    }, 1000);
});


text:
Before we begin, make sure you have a version `>= 7.6` of [Node.js](https://nodejs.org/) installed.

## Locally

Installing locally is what we recommend for most projects. This makes it easier to upgrade projects individually when breaking changes are introduced.

###### Using npm

```bash
$ npm i claypot
```

###### Using yarn

```bash
$ yarn add claypot
```

### Globally

Claypot also provides a powerful Command Line Interface (CLI) for Claypot monitors managment. Installing globally is also we recommend for using CLI.

###### Using npm

```bash
$ npm i -g claypot
```

###### Using yarn

```bash
$ yarn global add claypot
```


text:
package com.twinone.locker.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class NetworkStateReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("", "INTENT RECEIVED: " + intent.getAction());
		// processConnectivityEvent(intent, context);
	}

	// private String unescapeSsid(String ssid) {
	// if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
	// ssid = ssid.substring(1, ssid.length() - 1);
	// }
	// return ssid;
	// }

	// Old method, do not use.

	// private static final void processConnectivityEvent(Intent intent, Context
	// c) {
	// String a = WifiManager.NETWORK_STATE_CHANGED_ACTION;
	// SharedPreferences sp = c.getSharedPreferences("beta",
	// Context.MODE_PRIVATE);
	// // TODO bug here
	// final boolean should = sp.getBoolean(
	// c.getString(R.string.pref_key_temp_wifi_unlock_state), false);
	// if (!should)
	// return;
	//
	// String savedSSID = sp.getString(
	// c.getString(R.string.pref_key_temp_wifi_ssid), "");
	// NetworkInfo ni = (NetworkInfo) intent
	// .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
	//
	// if (ni.isConnected()) {
	// switch (ni.getType()) {
	// case ConnectivityManager.TYPE_WIFI:
	// WifiManager wm = (WifiManager) c
	// .getSystemService(Context.WIFI_SERVICE);
	// WifiInfo wi = wm.getConnectionInfo();
	// String ssid = wi.getSSID();
	//
	// Log.d("RECEIVER", "SSID: " + ssid + " saved: " + savedSSID);
	// if (ssid != null && ssid.length() != 0) {
	// // 4.2+ have quotes, remove them if it has!
	// if (ssid.equals(savedSSID)) {
	// Log.d("RECEIVER", "Stopping service, ssid matched");
	// Intent i = new Intent(c, AppLockService.class);
	// c.stopService(i);
	// }
	// }
	// break;
	// }
	// }
	// }

}


text:
package main

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/user"
	"reflect"
	"runtime"
	"strings"

	"github.com/google/gapid/core/fault"
	"github.com/google/gapid/core/os/file"
)

type enum interface {
	Options() []string
	String() string
	Set(string) bool
}

type Flavor string

func (Flavor) Options() []string { return []string{"release", "debug"} }
func (f Flavor) String() string  { return string(f) }
func (f *Flavor) Set(v string) bool {
	for _, o := range f.Options() {
		if o == v {
			*f = Flavor(o)
			return true
		}
	}
	return false
}

// Config is the structure that holds all the configuration settings.
type Config struct {
	Flavor         Flavor    `desc:"Build flavor"`
	OutRoot        file.Path `desc:"Build output directory"`
	JavaHome       file.Path `desc:"Path to JDK root"`
	AndroidSDKRoot file.Path `desc:"Path to Android SDK"`
	AndroidNDKRoot file.Path `desc:"Path to Android NDK"`
	CMakePath      file.Path `desc:"Path to CMake executable"`
	NinjaPath      file.Path `desc:"Path to ninja executable"`
	PythonPath     file.Path `desc:"Path to python executable"`
	MSYS2Path      file.Path `desc:"Path to msys2 root" os:"windows"`
	ArmLinuxGapii  bool      `desc:"Build additional gapii for armlinux"`
}

func defaults() Config {
	u, _ := user.Current()
	cfg := Config{}
	cfg.Flavor = "release"
	cfg.OutRoot = file.Abs(u.HomeDir).Join("gapid")
	cfg.JavaHome = file.Abs(os.Getenv("JAVA_HOME"))
	cfg.AndroidSDKRoot = file.Abs(os.Getenv("ANDROID_HOME"))
	cfg.AndroidNDKRoot = file.Abs(os.Getenv("ANDROID_NDK_ROOT"))
	cfg.CMakePath, _ = file.FindExecutable("cmake")
	cfg.NinjaPath, _ = file.FindExecutable("ninja")
	cfg.PythonPath, _ = file.FindExecutable("python")
	return cfg
}

func (cfg Config) out() file.Path         { return cfg.OutRoot.Join(cfg.Flavor.String()) }
func (cfg Config) bin() file.Path         { return cfg.out().Join("bin") }
func (cfg Config) pkg() file.Path         { return cfg.out().Join("pkg") }
func (cfg Config) versionFile() file.Path { return cfg.out().Join("do-version.txt") }
func (cfg Config) cacheFile() file.Path   { return cfg.out().Join("CMakeCache.txt") }

func (cfg Config) loadBuildVersion() (int, int) {
	data, err := ioutil.ReadFile(cfg.versionFile().System())
	if err != nil {
		return 0, 0
	}
	var major, minor int
	fmt.Sscanf(string(data), "%d.%d", &major, &minor)
	return major, minor
}

func (cfg Config) storeBuildVersion() {
	str := fmt.Sprintf("%d.%d", versionMajor, versionMinor)
	ioutil.WriteFile(cfg.versionFile().System(), []byte(str), 0666)
}

func readConfig() (Config, bool) {
	def := defaults()
	data, err := ioutil.ReadFile(cfgPath)
	if err != nil {
		return def, false
	}
	cfg := def
	if err := json.Unmarshal(data, &cfg); err != nil {
		return def, false
	}
	return cfg, true
}

func writeConfig(cfg Config) {
	data, err := json.MarshalIndent(cfg, "", "    ")
	if err != nil {
		panic(err)
	}
	if err := ioutil.WriteFile(cfgPath, data, 0666); err != nil {
		panic(err)
	}
}

func fetchValidConfig(ctx context.Context, options ConfigOptions) Config {
	cfg, found := readConfig()
	if options.Reset {
		cfg = defaults()
	}
	if !found || options.Interactive {
		cfg = interactiveConfig(ctx, cfg, options)
	}
	for {
		err := validateConfig(ctx, cfg)
		if err == nil {
			return cfg
		}
		fmt.Printf("Configuration is not valid: %v\n", err)
		cfg = interactiveConfig(ctx, cfg, options)
	}
}

func validateConfig(ctx context.Context, cfg Config) error {
	for _, test := range []struct {
		name string
		path file.Path
	}{
		{"cmake", cfg.CMakePath},
		{"ninja", cfg.NinjaPath},
		{"python", cfg.PythonPath},
	} {
		if !test.path.Exists() {
			return fault.Const("Could not find " + test.name)
		}
		if test.path.IsDir() {
			return fault.Const("The provided " + test.name + " is a directory,\nplease provide the path to the " + test.name + " executable")
		}
	}
	return nil
}

func interactiveStructConfig(ctx context.Context, v reflect.Value, options ConfigOptions) {
	t := v.Type()
	for i, c := 0, t.NumField(); i < c; i++ {
		f, t := v.Field(i), t.Field(i)
		desc := t.Tag.Get("desc")
		if desc == "" {
			desc = t.Name
		}
		os := t.Tag.Get("os")
		if os != "" && os != runtime.GOOS {
			continue
		}
		v := f.Addr().Interface()
		switch v := v.(type) {
		case enum:
			options := v.Options()
			fmt.Printf(" • %s. One of: %v [Default: %v]\n", desc, strings.Join(options, ", "), v)
			if in := readLine(); in != "" {
				if !v.Set(in) {
					fmt.Printf("Must be one of: %v\n", strings.Join(options, ", "))
					i--
					continue
				}
			}
		case *string:
			fmt.Printf(" • %s [Default: %q]\n", desc, *v)
			if in := readLine(); in != "" {
				*v = in
			}
		case *bool:
			fmt.Printf(" • %s [Default: %v]\n", desc, *v)
			if in := readLine(); in != "" {
				if val, ok := parseBool(in); !ok {
					fmt.Printf("Must be yes/true or no/false\n")
					i--
					continue
				} else {
					*v = val
				}
			}
		case *file.Path:
			fmt.Printf(" • %s [Default: %v]\n", desc, v.System())
			if in := readLine(); in != "" {
				*v = file.Abs(in)
			}
		default:
			if t.Type.Kind() == reflect.Interface {
				if !f.IsNil() {
					interactiveStructConfig(ctx, f.Elem(), options)
				}
				continue
			}
			panic(fmt.Sprintf("Unknown type %T in config struct", v))
		}
	}
}

func interactiveConfig(ctx context.Context, cfg Config, options ConfigOptions) Config {
	v := reflect.ValueOf(&cfg).Elem()
	interactiveStructConfig(ctx, v, options)
	writeConfig(cfg)
	return cfg
}

func readLine() string {
	r := bufio.NewReader(os.Stdin)
	l, _ := r.ReadString('\n')
	return strings.Trim(l, "\n\r")
}

func parseBool(str string) (val, ok bool) {
	switch strings.ToLower(str) {
	case "yes", "y", "true":
		return true, true
	case "no", "n", "false":
		return false, true
	}
	return false, false
}


text:
<?php

namespace Kunstmaan\PagePartBundle\Form;

use Kunstmaan\AdminBundle\Form\WysiwygType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * TextPagePartAdminType.
 */
class TextPagePartAdminType extends AbstractType
{
    /**
     * @param \Symfony\Component\Form\FormBuilderInterface $builder
     * @param array                                        $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('content', WysiwygType::class, [
            'label' => 'pagepart.text.content',
            'required' => false,
        ]);
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return 'kunstmaan_pagepartbundle_textpageparttype';
    }

    /**
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Kunstmaan\PagePartBundle\Entity\TextPagePart',
        ]);
    }
}


text:
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="style.css">
        <link rel="shortcut icon" href="assets\medhacks_cross.png">

Fake message

View Pitches

                <input class="inputText short-center invisible" type="text" id="new-title" placeholder="View Pitches" maxlength="20">

                <button class="corner-button save-button"></button>
                <button class="corner-button load-button"></button>
                <form action="add.html">
                    <button class="corner-button add-button" type="submit"></button>
                </form>

Save your favorites

#community

#openscience

#patientsafety

Favorites

All Pitches


text:
package com.facebook.buck.artifact_cache;

import com.facebook.buck.artifact_cache.thrift.ArtifactMetadata;
import com.facebook.buck.artifact_cache.thrift.BuckCacheDeleteRequest;
import com.facebook.buck.artifact_cache.thrift.BuckCacheDeleteResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheFetchRequest;
import com.facebook.buck.artifact_cache.thrift.BuckCacheFetchResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheMultiContainsRequest;
import com.facebook.buck.artifact_cache.thrift.BuckCacheMultiContainsResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheMultiFetchRequest;
import com.facebook.buck.artifact_cache.thrift.BuckCacheMultiFetchResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheRequest;
import com.facebook.buck.artifact_cache.thrift.BuckCacheRequestType;
import com.facebook.buck.artifact_cache.thrift.BuckCacheResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheStoreRequest;
import com.facebook.buck.artifact_cache.thrift.ContainsResult;
import com.facebook.buck.artifact_cache.thrift.FetchResultType;
import com.facebook.buck.artifact_cache.thrift.PayloadInfo;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.io.file.LazyPath;
import com.facebook.buck.log.Logger;
import com.facebook.buck.slb.HttpResponse;
import com.facebook.buck.slb.ThriftProtocol;
import com.facebook.buck.slb.ThriftUtil;
import com.facebook.buck.util.RichStream;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * This is the Thrift protocol for the cache. The underlying channel is still HTTP but the payload
 * is Thrift. To learn a bit more about the protocol please look at ThriftArtifactCacheProtocol.
 */
public class ThriftArtifactCache extends AbstractNetworkCache {
  static final Logger LOG = Logger.get(ThriftArtifactCache.class);

  public static final MediaType HYBRID_THRIFT_STREAM_CONTENT_TYPE =
      MediaType.parse("application/x-hybrid-thrift-binary");
  public static final String PROTOCOL_HEADER = "X-Thrift-Protocol";
  public static final ThriftProtocol PROTOCOL = ThriftProtocol.COMPACT;

  private final String hybridThriftEndpoint;
  private final boolean distributedBuildModeEnabled;
  private final BuildId buildId;
  private final int multiFetchLimit;
  private final int concurrencyLevel;

  public ThriftArtifactCache(
      NetworkCacheArgs args,
      String hybridThriftEndpoint,
      boolean distributedBuildModeEnabled,
      BuildId buildId,
      int multiFetchLimit,
      int concurrencyLevel) {
    super(args);
    this.buildId = buildId;
    this.multiFetchLimit = multiFetchLimit;
    this.concurrencyLevel = concurrencyLevel;
    this.hybridThriftEndpoint = hybridThriftEndpoint;
    this.distributedBuildModeEnabled = distributedBuildModeEnabled;
  }

  @Override
  protected FetchResult fetchImpl(RuleKey ruleKey, LazyPath output) throws IOException {
    FetchResult.Builder resultBuilder = FetchResult.builder();

    BuckCacheFetchRequest fetchRequest = new BuckCacheFetchRequest();
    com.facebook.buck.artifact_cache.thrift.RuleKey thriftRuleKey =
        new com.facebook.buck.artifact_cache.thrift.RuleKey();
    thriftRuleKey.setHashString(ruleKey.getHashCode().toString());
    fetchRequest.setRuleKey(thriftRuleKey);
    fetchRequest.setRepository(getRepository());
    fetchRequest.setScheduleType(scheduleType);
    fetchRequest.setDistributedBuildModeEnabled(distributedBuildModeEnabled);

    BuckCacheRequest cacheRequest = newCacheRequest();
    cacheRequest.setType(BuckCacheRequestType.FETCH);
    cacheRequest.setFetchRequest(fetchRequest);

    LOG.verbose("Will fetch key %s", thriftRuleKey);

    ThriftArtifactCacheProtocol.Request request =
        ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest);
    Request.Builder builder = toOkHttpRequest(request);
    try (HttpResponse httpResponse = fetchClient.makeRequest(hybridThriftEndpoint, builder)) {
      if (httpResponse.statusCode() != 200) {
        String message =
            String.format(
                "Failed to fetch cache artifact with HTTP status code [%d:%s] "
                    + " to url [%s] for rule key [%s].",
                httpResponse.statusCode(),
                httpResponse.statusMessage(),
                httpResponse.requestUrl(),
                ruleKey.toString());
        LOG.warn(message);
        return resultBuilder
            .setCacheResult(CacheResult.error(getName(), getMode(), message))
            .build();
      }

      try (ThriftArtifactCacheProtocol.Response response =
          ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
        resultBuilder.setResponseSizeBytes(httpResponse.contentLength());

        BuckCacheResponse cacheResponse = response.getThriftData();
        if (!cacheResponse.isWasSuccessful()) {
          LOG.warn("Request was unsuccessful: %s", cacheResponse.getErrorMessage());
          return resultBuilder
              .setCacheResult(
                  CacheResult.error(getName(), getMode(), cacheResponse.getErrorMessage()))
              .build();
        }

        BuckCacheFetchResponse fetchResponse = cacheResponse.getFetchResponse();

        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Debug info for cache fetch request: request=[%s] response=[%s]",
              ThriftUtil.thriftToDebugJson(cacheRequest),
              ThriftUtil.thriftToDebugJson(cacheResponse));
        }

        if (!fetchResponse.isArtifactExists()) {
          LOG.verbose("Artifact did not exist.");
          return resultBuilder.setCacheResult(CacheResult.miss()).build();
        }

        LOG.verbose("Got artifact.  Attempting to read payload.");
        Path tmp = createTempFileForDownload();
        ThriftArtifactCacheProtocol.Response.ReadPayloadInfo readResult;
        try (OutputStream tmpFile = getProjectFilesystem().newFileOutputStream(tmp)) {
          try {
            readResult = response.readPayload(tmpFile);
          } catch (IOException e) {
            LOG.debug(e, "encountered an exception while receiving the payload for %s", ruleKey);
            throw e;
          }
          LOG.verbose("Successfully read payload: %d bytes.", readResult.getBytesRead());
        }

        if (!fetchResponse.isSetMetadata()) {
          String msg =
              String.format(
                  "ArtifactMetadata section is missing in the response. response=[%s]",
                  ThriftUtil.thriftToDebugJson(fetchResponse));
          return resultBuilder.setCacheResult(CacheResult.error(getName(), getMode(), msg)).build();
        }
        ArtifactMetadata metadata = fetchResponse.getMetadata();
        if (LOG.isVerboseEnabled()) {
          LOG.verbose(
              String.format(
                  "Fetched artifact with rule key [%s] contains the following metadata: [%s].",
                  ruleKey, ThriftUtil.thriftToDebugJson(metadata)));
        }

        if (!metadata.isSetRuleKeys()) {
          return resultBuilder
              .setCacheResult(
                  CacheResult.error(
                      getName(), getMode(), "Rule key section in the metadata is not set."))
              .build();
        }
        ImmutableSet<RuleKey> associatedRuleKeys = null;
        try {
          associatedRuleKeys = toImmutableSet(metadata.getRuleKeys());
        } catch (IllegalArgumentException e) {
          String msg =
              String.format(
                  "Exception parsing the rule keys in the metadata section [%s] with exception [%s].",
                  ThriftUtil.thriftToDebugJson(metadata), e.toString());
          return resultBuilder.setCacheResult(CacheResult.error(getName(), getMode(), msg)).build();
        }

        resultBuilder
            .setBuildTarget(Optional.ofNullable(metadata.getBuildTarget()))
            .setAssociatedRuleKeys(associatedRuleKeys)
            .setArtifactSizeBytes(readResult.getBytesRead());
        if (!metadata.isSetArtifactPayloadMd5()) {
          String msg = "Fetched artifact is missing the MD5 hash.";
          LOG.warn(msg);
        } else {
          resultBuilder.setArtifactContentHash(metadata.getArtifactPayloadMd5());
          if (!readResult
              .getMd5Hash()
              .equals(fetchResponse.getMetadata().getArtifactPayloadMd5())) {
            String msg =
                String.format(
                    "The artifact fetched from cache is corrupted. ExpectedMD5=[%s] ActualMD5=[%s]",
                    fetchResponse.getMetadata().getArtifactPayloadMd5(), readResult.getMd5Hash());
            LOG.warn(msg);
            return resultBuilder
                .setCacheResult(CacheResult.error(getName(), getMode(), msg))
                .build();
          }
        }

        // This makes sure we don't have 'half downloaded files' in the dir cache.
        getProjectFilesystem().move(tmp, output.get(), StandardCopyOption.REPLACE_EXISTING);
        return resultBuilder
            .setCacheResult(
                CacheResult.hit(
                    getName(),
                    getMode(),
                    ImmutableMap.copyOf(fetchResponse.getMetadata().getMetadata()),
                    readResult.getBytesRead()))
            .build();
      }
    }
  }

  private BuckCacheRequest newCacheRequest() {
    BuckCacheRequest buckCacheRequest = new BuckCacheRequest();
    buckCacheRequest.setBuckBuildId(buildId.toString());
    return buckCacheRequest;
  }

  private void processContainsResult(
      RuleKey ruleKey, ContainsResult containsResult, MultiContainsResult.Builder resultBuilder) {
    switch (containsResult.resultType) {
      case CONTAINS:
        resultBuilder.putCacheResults(ruleKey, CacheResult.contains(getName(), getMode()));
        break;
      case DOES_NOT_CONTAIN:
        resultBuilder.putCacheResults(ruleKey, CacheResult.miss());
        break;
      case UNKNOWN_DUE_TO_TRANSIENT_ERRORS:
        resultBuilder.putCacheResults(
            ruleKey,
            CacheResult.error(
                getName(),
                getMode(),
                String.format(
                    "Multi-contains request reported transient errors in some backing stores for "
                        + "rule key [%s]. Artifact may still be present.",
                    ruleKey.toString())));
        break;
    }
  }

  private MultiContainsResult processMultiContainsHttpResponse(
      HttpResponse httpResponse, List<RuleKey> ruleKeys) throws IOException {
    MultiContainsResult.Builder resultBuilder = MultiContainsResult.builder();

    if (httpResponse.statusCode() != 200) {
      LOG.warn(
          String.format(
              "Failed to multi-contains request for [%d] cache artifacts "
                  + "with HTTP status code [%d:%s] to url [%s].",
              ruleKeys.size(),
              httpResponse.statusCode(),
              httpResponse.statusMessage(),
              httpResponse.requestUrl()));

      Function<RuleKey, CacheResult> genErrorResult =
          ruleKey ->
              CacheResult.error(
                  getName(),
                  getMode(),
                  String.format(
                      "Failed to check cache artifact (via multi-contains request) "
                          + "with HTTP status code [%d:%s] to url [%s] for rule key [%s].",
                      httpResponse.statusCode(),
                      httpResponse.statusMessage(),
                      httpResponse.requestUrl(),
                      ruleKey.toString()));

      return resultBuilder.setCacheResults(Maps.toMap(ruleKeys, genErrorResult::apply)).build();
    }

    try (ThriftArtifactCacheProtocol.Response response =
        ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
      resultBuilder.setResponseSizeBytes(httpResponse.contentLength());

      BuckCacheResponse cacheResponse = response.getThriftData();
      if (!cacheResponse.isWasSuccessful()) {
        LOG.warn("Request was unsuccessful: %s", cacheResponse.getErrorMessage());
        Function<RuleKey, CacheResult> genErrorResult =
            k -> CacheResult.error(getName(), getMode(), cacheResponse.getErrorMessage());
        return resultBuilder.setCacheResults(Maps.toMap(ruleKeys, genErrorResult::apply)).build();
      }

      BuckCacheMultiContainsResponse containsResponse = cacheResponse.getMultiContainsResponse();

      Preconditions.checkState(
          containsResponse.results.size() == ruleKeys.size(),
          "Bad response from server. MultiContains Response does not have the "
              + "same number of results as the MultiContains Request.");

      for (int i = 0; i < containsResponse.results.size(); ++i) {
        processContainsResult(ruleKeys.get(i), containsResponse.results.get(i), resultBuilder);
      }
      return resultBuilder.build();
    }
  }

  @Override
  protected MultiContainsResult multiContainsImpl(ImmutableSet<RuleKey> uniqueRuleKeys)
      throws IOException {
    List<RuleKey> ruleKeys = Lists.newArrayList(uniqueRuleKeys);

    BuckCacheMultiContainsRequest containsRequest = new BuckCacheMultiContainsRequest();
    containsRequest.setRuleKeys(new ArrayList<>(ruleKeys.size()));

    for (RuleKey ruleKey : ruleKeys) {
      com.facebook.buck.artifact_cache.thrift.RuleKey thriftRuleKey =
          new com.facebook.buck.artifact_cache.thrift.RuleKey();
      thriftRuleKey.setHashString(ruleKey.getHashCode().toString());
      containsRequest.addToRuleKeys(thriftRuleKey);
    }

    LOG.verbose(
        "Will check (multi-contains) for keys [%s]",
        Joiner.on(",").join(containsRequest.getRuleKeys()));

    containsRequest.setRepository(getRepository());
    containsRequest.setScheduleType(scheduleType);
    containsRequest.setDistributedBuildModeEnabled(distributedBuildModeEnabled);

    BuckCacheRequest cacheRequest = newCacheRequest();
    cacheRequest.setType(BuckCacheRequestType.CONTAINS);
    cacheRequest.setMultiContainsRequest(containsRequest);

    ThriftArtifactCacheProtocol.Request request =
        ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest);
    Request.Builder builder = toOkHttpRequest(request);
    try (HttpResponse httpResponse = fetchClient.makeRequest(hybridThriftEndpoint, builder)) {
      MultiContainsResult result = processMultiContainsHttpResponse(httpResponse, ruleKeys);
      LOG.verbose(
          "(%d out of %d) artifacts exist in cache.",
          result.getCacheResults().values().stream().filter(r -> r.getType().isSuccess()).count(),
          ruleKeys.size());
      return result;
    }
  }

  @Override
  protected int getMultiFetchBatchSize(int pendingRequestsSize) {
    if (concurrencyLevel > 0)
      return Math.min(multiFetchLimit, 1 + pendingRequestsSize / concurrencyLevel);
    return 0;
  }

  @Override
  protected MultiFetchResult multiFetchImpl(Iterable<FetchRequest> requests) throws IOException {
    ImmutableList<RuleKey> keys =
        RichStream.from(requests)
            .map(FetchRequest::getRuleKey)
            .collect(ImmutableList.toImmutableList());
    ImmutableList<LazyPath> outputs =
        RichStream.from(requests)
            .map(FetchRequest::getOutput)
            .collect(ImmutableList.toImmutableList());
    Preconditions.checkState(keys.size() == outputs.size());
    String joinedKeys = Joiner.on(", ").join(keys);
    LOG.verbose("Will fetch keys <%s>", joinedKeys);

    BuckCacheRequest cacheRequest = createMultiFetchRequest(keys);
    try (HttpResponse httpResponse =
        fetchClient.makeRequest(
            hybridThriftEndpoint,
            toOkHttpRequest(ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest)))) {
      return MultiFetchResult.of(
          processMultiFetchResponse(keys, outputs, cacheRequest, joinedKeys, httpResponse));
    }
  }

  com.facebook.buck.artifact_cache.thrift.RuleKey toThriftRuleKey(RuleKey ruleKey) {
    com.facebook.buck.artifact_cache.thrift.RuleKey thriftRuleKey =
        new com.facebook.buck.artifact_cache.thrift.RuleKey();
    thriftRuleKey.setHashString(ruleKey.getHashCode().toString());
    return thriftRuleKey;
  }

  private BuckCacheRequest createMultiFetchRequest(ImmutableList<RuleKey> keys) {
    BuckCacheMultiFetchRequest multiFetchRequest = new BuckCacheMultiFetchRequest();
    multiFetchRequest.setRepository(getRepository());
    multiFetchRequest.setScheduleType(scheduleType);
    multiFetchRequest.setDistributedBuildModeEnabled(distributedBuildModeEnabled);
    keys.forEach(k -> multiFetchRequest.addToRuleKeys(toThriftRuleKey(k)));

    BuckCacheRequest cacheRequest = newCacheRequest();
    cacheRequest.setType(BuckCacheRequestType.MULTI_FETCH);
    cacheRequest.setMultiFetchRequest(multiFetchRequest);
    return cacheRequest;
  }

  private Iterable<FetchResult> processMultiFetchResponse(
      ImmutableList<RuleKey> keys,
      ImmutableList<LazyPath> outputs,
      BuckCacheRequest cacheRequest,
      String joinedKeys,
      HttpResponse httpResponse)
      throws IOException {

    if (httpResponse.statusCode() != 200) {
      String message =
          String.format(
              "Failed to fetch cache artifact with HTTP status code [%d:%s] "
                  + " to url [%s] for rule keys [%s].",
              httpResponse.statusCode(),
              httpResponse.statusMessage(),
              httpResponse.requestUrl(),
              joinedKeys);
      LOG.warn(message);
      CacheResult cacheResult = CacheResult.error(getName(), getMode(), message);
      return keys.stream().map(k -> FetchResult.builder().setCacheResult(cacheResult).build())
          ::iterator;
    }

    try (ThriftArtifactCacheProtocol.Response response =
        ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
      return convertMultiFetchResponseToFetchResults(
                  keys, outputs, cacheRequest, httpResponse, response)
              .stream()
              .map(b -> b.build())
          ::iterator;
    }
  }

  private ImmutableList<FetchResult.Builder> convertMultiFetchResponseToFetchResults(
      ImmutableList<RuleKey> keys,
      ImmutableList<LazyPath> outputs,
      BuckCacheRequest cacheRequest,
      HttpResponse httpResponse,
      ThriftArtifactCacheProtocol.Response response)
      throws IOException {
    long responseSizeBytes = httpResponse.contentLength();
    ImmutableList<FetchResult.Builder> resultsBuilders =
        keys.stream().map(k -> FetchResult.builder()).collect(ImmutableList.toImmutableList());

    BuckCacheResponse cacheResponse = response.getThriftData();
    resultsBuilders.forEach(b -> b.setResponseSizeBytes(responseSizeBytes));

    if (!cacheResponse.isWasSuccessful()) {
      String message = cacheResponse.getErrorMessage();
      LOG.warn("Request was unsuccessful: %s", message);
      resultsBuilders.forEach(
          b -> b.setCacheResult(CacheResult.error(getName(), getMode(), message)));
      return resultsBuilders;
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(
          "Debug info for cache multiFetch request: request=[%s] response=[%s]",
          ThriftUtil.thriftToDebugJson(cacheRequest), ThriftUtil.thriftToDebugJson(cacheResponse));
    }

    BuckCacheMultiFetchResponse multiFetchResponse = cacheResponse.getMultiFetchResponse();
    if (multiFetchResponse.getResultsSize() != keys.size()) {
      String message =
          String.format(
              "Response had incorrect results size expected=%d actual=%d",
              keys.size(), multiFetchResponse.getResultsSize());
      LOG.warn(message);
      resultsBuilders.forEach(
          b -> b.setCacheResult(CacheResult.error(getName(), getMode(), message)));
      return resultsBuilders;
    }

    for (int i = 0; i < keys.size(); i++) {
      RuleKey ruleKey = keys.get(i);
      com.facebook.buck.artifact_cache.thrift.FetchResult fetchResponse =
          multiFetchResponse.getResults().get(i);
      FetchResult.Builder builder = resultsBuilders.get(i);
      LOG.verbose("Handling result for key %s", ruleKey);

      convertSingleMultiFetchResult(
          fetchResponse, ruleKey, new PayloadReader(response), outputs.get(i), builder);
    }
    return resultsBuilders;
  }

  private void convertSingleMultiFetchResult(
      com.facebook.buck.artifact_cache.thrift.FetchResult fetchResponse,
      RuleKey ruleKey,
      PayloadReader payloadReader,
      LazyPath output,
      FetchResult.Builder builder)
      throws IOException {
    FetchResultType resultType = fetchResponse.getResultType();
    switch (resultType) {
      case UNKNOWN:
      case ERROR:
        builder.setCacheResult(
            CacheResult.error(
                getName(), getMode(), String.format("Got bad result of type %s", resultType)));
        return;
      case MISS:
        LOG.verbose("Artifact did not exist.");
        builder.setCacheResult(CacheResult.miss());
        return;
      case CONTAINS:
        LOG.verbose("Got CONTAINS result.");
        builder.setCacheResult(CacheResult.skipped());
        return;
      case SKIPPED:
        LOG.verbose("Got SKIPPED result.");
        builder.setCacheResult(CacheResult.skipped());
        return;
      case HIT:
        // Handled below.
        break;
    }

    if (resultType != FetchResultType.HIT) {
      String message = String.format("Got unexpected result type: %s", resultType);
      LOG.verbose(message);
      // We need to throw an exception in this case. We don't know if this result type has a
      // payload or not and so we could start assigning payloads to incorrect results.
      // TODO(cjhopman): Do we have to the same for the UNKNOWN case above?
      throw new IOException(message);
    }

    LOG.verbose("Got artifact.  Attempting to read payload.");
    Path tmp = createTempFileForDownload();

    // Always read payload even if information is missing to ensure that we associate payloads
    // with the correct result.
    @SuppressWarnings("PMD.PrematureDeclaration")
    ThriftArtifactCacheProtocol.Response.ReadPayloadInfo readResult =
        payloadReader.readNextPayload(tmp, ruleKey);

    if (!fetchResponse.isSetMetadata()) {
      String msg =
          String.format(
              "ArtifactMetadata section is missing in the response. response=[%s]",
              ThriftUtil.thriftToDebugJson(fetchResponse));
      LOG.verbose(msg);
      builder.setCacheResult(CacheResult.error(getName(), getMode(), msg));
      return;
    }

    ArtifactMetadata metadata = fetchResponse.getMetadata();
    if (LOG.isVerboseEnabled()) {
      LOG.verbose(
          String.format(
              "Fetched artifact with rule key [%s] contains the following metadata: [%s].",
              ruleKey, ThriftUtil.thriftToDebugJson(metadata)));
    }

    if (!metadata.isSetRuleKeys()) {
      String msg = "Rule key section in the metadata is not set.";
      LOG.verbose(msg);
      builder.setCacheResult(CacheResult.error(getName(), getMode(), msg));
      return;
    }

    ImmutableSet<RuleKey> associatedRuleKeys;
    try {
      associatedRuleKeys = toImmutableSet(metadata.getRuleKeys());
    } catch (IllegalArgumentException e) {
      String msg =
          String.format(
              "Exception parsing the rule keys in the metadata section [%s] with exception [%s].",
              ThriftUtil.thriftToDebugJson(metadata), e.toString());
      LOG.verbose(msg);
      builder.setCacheResult(CacheResult.error(getName(), getMode(), msg));
      return;
    }

    builder
        .setBuildTarget(Optional.ofNullable(metadata.getBuildTarget()))
        .setAssociatedRuleKeys(associatedRuleKeys)
        .setArtifactSizeBytes(readResult.getBytesRead());

    // Unlike fetch(), multiFetch() requires that the md5 be set. This is to provide extra
    // protection against assigning a payload to the incorrect request.
    if (!metadata.isSetArtifactPayloadMd5()) {
      throw new IOException(
          String.format(
              "Metadata for rulekey %s does not contain a payload md5. "
                  + "Rejecting entire multiFetch result.",
              ruleKey));
    }

    builder.setArtifactContentHash(metadata.getArtifactPayloadMd5());
    if (!readResult.getMd5Hash().equals(fetchResponse.getMetadata().getArtifactPayloadMd5())) {
      String msg =
          String.format(
              "The artifact fetched from cache is corrupted. ExpectedMD5=[%s] ActualMD5=[%s]",
              fetchResponse.getMetadata().getArtifactPayloadMd5(), readResult.getMd5Hash());
      LOG.warn(msg);
      builder.setCacheResult(CacheResult.error(getName(), getMode(), msg));
      return;
    }

    // This makes sure we don't have 'half downloaded files' in the dir cache.
    getProjectFilesystem().move(tmp, output.get(), StandardCopyOption.REPLACE_EXISTING);
    builder.setCacheResult(
        CacheResult.hit(
            getName(),
            getMode(),
            ImmutableMap.copyOf(fetchResponse.getMetadata().getMetadata()),
            readResult.getBytesRead()));
  }

  private static ImmutableSet<RuleKey> toImmutableSet(
      List<com.facebook.buck.artifact_cache.thrift.RuleKey> ruleKeys) {
    return ImmutableSet.copyOf(
        Iterables.transform(ruleKeys, input -> new RuleKey(input.getHashString())));
  }

  @Override
  protected StoreResult storeImpl(ArtifactInfo info, Path file) throws IOException {
    StoreResult.Builder resultBuilder = StoreResult.builder();
    ByteSource artifact =
        new ByteSource() {
          @Override
          public InputStream openStream() throws IOException {
            return getProjectFilesystem().newFileInputStream(file);
          }
        };

    BuckCacheStoreRequest storeRequest = new BuckCacheStoreRequest();
    ArtifactMetadata artifactMetadata =
        infoToMetadata(info, artifact, getRepository(), scheduleType, distributedBuildModeEnabled);
    storeRequest.setMetadata(artifactMetadata);
    PayloadInfo payloadInfo = new PayloadInfo();
    long artifactSizeBytes = artifact.size();
    payloadInfo.setSizeBytes(artifactSizeBytes);
    BuckCacheRequest cacheRequest = newCacheRequest();
    cacheRequest.addToPayloads(payloadInfo);
    cacheRequest.setType(BuckCacheRequestType.STORE);
    cacheRequest.setStoreRequest(storeRequest);

    if (LOG.isVerboseEnabled()) {
      LOG.verbose(
          String.format(
              "Storing artifact with metadata: [%s].",
              ThriftUtil.thriftToDebugJson(artifactMetadata)));
    }

    ThriftArtifactCacheProtocol.Request request =
        ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest, artifact);
    Request.Builder builder = toOkHttpRequest(request);
    resultBuilder.setRequestSizeBytes(request.getRequestLengthBytes());
    try (HttpResponse httpResponse = storeClient.makeRequest(hybridThriftEndpoint, builder)) {
      if (httpResponse.statusCode() != 200) {
        throw new IOException(
            String.format(
                "Failed to store cache artifact with HTTP status code [%d:%s] "
                    + " to url [%s] for build target [%s] that has size [%d] bytes.",
                httpResponse.statusCode(),
                httpResponse.statusMessage(),
                httpResponse.requestUrl(),
                info.getBuildTarget().orElse(null),
                artifactSizeBytes));
      }

      try (ThriftArtifactCacheProtocol.Response response =
          ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
        BuckCacheResponse cacheResponse = response.getThriftData();
        if (!cacheResponse.isWasSuccessful()) {
          reportFailureWithFormatKey(
              "Failed to store artifact with thriftErrorMessage=[%s] "
                  + "url=[%s] artifactSizeBytes=[%d]",
              response.getThriftData().getErrorMessage(),
              httpResponse.requestUrl(),
              artifactSizeBytes);
        }

        resultBuilder.setArtifactContentHash(storeRequest.getMetadata().artifactPayloadMd5);
        resultBuilder.setWasStoreSuccessful(cacheResponse.isWasSuccessful());

        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Debug info for cache store request: artifactMetadata=[%s] response=[%s]",
              ThriftUtil.thriftToDebugJson(artifactMetadata),
              ThriftUtil.thriftToDebugJson(cacheResponse));
        }
      }
    }
    return resultBuilder.build();
  }

  private Path createTempFileForDownload() throws IOException {
    getProjectFilesystem().mkdirs(getProjectFilesystem().getBuckPaths().getScratchDir());
    return getProjectFilesystem()
        .createTempFile(
            getProjectFilesystem().getBuckPaths().getScratchDir(), "buckcache_artifact", ".tmp");
  }

  private static ArtifactMetadata infoToMetadata(
      ArtifactInfo info,
      ByteSource file,
      String repository,
      String scheduleType,
      boolean distributedBuildModeEnabled)
      throws IOException {
    ArtifactMetadata metadata = new ArtifactMetadata();
    if (info.getBuildTarget().isPresent()) {
      metadata.setBuildTarget(info.getBuildTarget().get().toString());
    }

    metadata.setRuleKeys(
        ImmutableList.copyOf(
            Iterables.transform(
                info.getRuleKeys(),
                input -> {
                  com.facebook.buck.artifact_cache.thrift.RuleKey ruleKey =
                      new com.facebook.buck.artifact_cache.thrift.RuleKey();
                  ruleKey.setHashString(input.getHashCode().toString());
                  return ruleKey;
                })));

    metadata.setMetadata(info.getMetadata());
    metadata.setArtifactPayloadMd5(ThriftArtifactCacheProtocol.computeMd5Hash(file));
    metadata.setRepository(repository);
    metadata.setScheduleType(scheduleType);
    metadata.setDistributedBuildModeEnabled(distributedBuildModeEnabled);

    return metadata;
  }

  private static Request.Builder toOkHttpRequest(ThriftArtifactCacheProtocol.Request request) {
    Request.Builder builder =
        new Request.Builder().addHeader(PROTOCOL_HEADER, PROTOCOL.toString().toLowerCase());
    builder.post(
        new RequestBody() {
          @Override
          public MediaType contentType() {
            return HYBRID_THRIFT_STREAM_CONTENT_TYPE;
          }

          @Override
          public long contentLength() {
            return request.getRequestLengthBytes();
          }

          @Override
          public void writeTo(BufferedSink bufferedSink) throws IOException {
            request.writeAndClose(bufferedSink.outputStream());
          }
        });

    return builder;
  }

  @Override
  protected CacheDeleteResult deleteImpl(List<RuleKey> ruleKeys) throws IOException {
    List<com.facebook.buck.artifact_cache.thrift.RuleKey> ruleKeysThrift =
        ruleKeys
            .stream()
            .map(
                r ->
                    new com.facebook.buck.artifact_cache.thrift.RuleKey()
                        .setHashString(r.toString()))
            .collect(Collectors.toList());

    BuckCacheDeleteRequest deleteRequest = new BuckCacheDeleteRequest();
    deleteRequest.setDistributedBuildModeEnabledIsSet(distributedBuildModeEnabled);
    deleteRequest.setRepository(getRepository());
    deleteRequest.setRuleKeys(ruleKeysThrift);
    deleteRequest.setScheduleType(scheduleType);
    BuckCacheRequest cacheRequest = newCacheRequest();
    cacheRequest.setType(BuckCacheRequestType.DELETE_REQUEST);
    cacheRequest.setDeleteRequest(deleteRequest);

    if (LOG.isVerboseEnabled()) {
      LOG.verbose(String.format("Deleting rule keys: [%s].", ruleKeys));
    }

    ThriftArtifactCacheProtocol.Request request =
        ThriftArtifactCacheProtocol.createRequest(PROTOCOL, cacheRequest);
    Request.Builder builder = toOkHttpRequest(request);
    try (HttpResponse httpResponse = storeClient.makeRequest(hybridThriftEndpoint, builder)) {
      if (httpResponse.statusCode() != 200) {
        throw new IOException(
            String.format(
                "Failed to delete cache artifacts with HTTP status code [%d:%s] " + " to url [%s].",
                httpResponse.statusCode(),
                httpResponse.statusMessage(),
                httpResponse.requestUrl()));
      }

      try (ThriftArtifactCacheProtocol.Response response =
          ThriftArtifactCacheProtocol.parseResponse(PROTOCOL, httpResponse.getBody())) {
        BuckCacheResponse cacheResponse = response.getThriftData();
        if (!cacheResponse.isWasSuccessful()) {
          throw new IOException(
              String.format(
                  "Failed to store artifact with thriftErrorMessage=[%s] " + "url=[%s]",
                  response.getThriftData().getErrorMessage(), httpResponse.requestUrl()));
        }
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Debug info for cache delete request: ruleKeys=[%s] response=[%s]",
              ruleKeys, ThriftUtil.thriftToDebugJson(cacheResponse));
        }

        BuckCacheDeleteResponse deleteResponse = cacheResponse.deleteResponse;
        if (deleteResponse == null) {
          throw new IOException("Got response without deleteResponse object");
        }

        String storesCommaSeparated;
        if (deleteResponse.debugInfo != null
            && deleteResponse.debugInfo.storesDeletedFrom != null) {
          storesCommaSeparated = String.join(", ", deleteResponse.debugInfo.storesDeletedFrom);
        } else {
          storesCommaSeparated = "";
        }

        String cacheName =
            ThriftArtifactCache.class.getSimpleName() + "[" + storesCommaSeparated + "]";
        ImmutableList<String> cacheNames = ImmutableList.of(cacheName);
        return CacheDeleteResult.builder().setCacheNames(cacheNames).build();
      }
    }
  }

  private class PayloadReader {
    private ThriftArtifactCacheProtocol.Response response;

    private PayloadReader(ThriftArtifactCacheProtocol.Response response) {
      this.response = response;
    }

    ThriftArtifactCacheProtocol.Response.ReadPayloadInfo readNextPayload(Path path, RuleKey ruleKey)
        throws IOException {
      try (OutputStream tmpFile = getProjectFilesystem().newFileOutputStream(path)) {
        ThriftArtifactCacheProtocol.Response.ReadPayloadInfo result;
        try {
          result = response.readPayload(tmpFile);
        } catch (IOException e) {
          LOG.debug(e, "Encountered an exception while receiving the payload for %s", ruleKey);
          throw e;
        }
        LOG.verbose("Successfully read payload: %d bytes.", result.getBytesRead());
        return result;
      }
    }
  }
}


text:
<?php

namespace ZendTest\Service\Nirvanix\Context;

use Zend\Service\Nirvanix\Context\Imfs as ImfsContext,
    ZendTest\Service\Nirvanix\FunctionalTestCase;

/**
 * @see        Zend\Service\Nirvanix\Context\Imfs
 * @category   Zend
 * @package    Zend_Service_Nirvanix
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Service
 * @group      Zend_Service_Nirvanix
 */
class ImfsTest extends FunctionalTestCase
{
    public function testInheritsFromNirvanixBase()
    {
        $imfs = new ImfsContext();
        $this->assertInstanceOf('Zend\Service\Nirvanix\Context\Base', $imfs);
    }

    // putContents()

    public function testPutContents()
    {
        $imfs = $this->nirvanix->getService('IMFS');

        // response for call to GetStorageNode
        $this->httpAdapter->addResponse(
           $this->makeNirvanixResponse(
                array('ResponseCode'   => '0',
                      'GetStorageNode' => '<UploadHost>node1.nirvanix.com</UploadHost>
                                           <UploadToken>bar</UploadToken>'))
        );

        $imfs->putContents('/foo', 'contents for foo');
    }

    // getContents()

    public function testGetContents()
    {
        $imfs = $this->nirvanix->getService('IMFS');

        // response for call to GetOptimalUrlss
        $this->httpAdapter->addResponse(
           $this->makeNirvanixResponse(
                array('ResponseCode' => '0',
                      'Download' => '<DownloadURL>http://get-it-here</DownloadURL>'))
        );

        // response for file download
        $this->httpAdapter->addResponse(
            $this->makeHttpResponseFrom('contents for foo')
        );

        $actual   = $imfs->getContents('/foo.txt');
        $expected = $this->httpClient->getResponse()->getBody();
        $this->assertEquals($expected, $actual);
    }

    // unlink()

    public function testUnlink()
    {
        $imfs = $this->nirvanix->getService('IMFS');

        // response for call to DeleteFiles
        $this->httpAdapter->addResponse(
            $this->makeNirvanixResponse(array('ResponseCode' => '0'))
        );

        $imfs->unlink('foo');
    }

    /**
     * @issue ZF-6860
     */
    public function testDestinationPathFormatSentToServiceAsParameterUsesUnixConvention()
    {
        $imfs = $this->nirvanix->getService('IMFS');
        $this->httpAdapter->addResponse(
           $this->makeNirvanixResponse(
                array('ResponseCode'   => '0',
                      'GetStorageNode' => '<UploadHost>node1.nirvanix.com</UploadHost>
                                           <UploadToken>bar</UploadToken>'))
        );
        // little unix cheat to force a backslash into the IFS path
        $imfs->putContents('.\foo/bar', 'contents for foo');
        $this->assertContains('./foo', $imfs->getHttpClient()->getLastRawRequest());
    }

}


text:
package idea.analyzesystem.hover.pinnedsection;

/**
 * Created by idea on 2017/1/20.
 */
public interface OnPinnedSectionListener<T> {

    void onPinnedSectionItem(T result);

    void onPinnedSectionNext(T result);
}


text:
using System;

namespace OpenSage.Gui.Apt.ActionScript.Library
{
    class ASString : BuiltinClass
    {
        string _value;

        public ASString(string value) : base()
        {
            _value = value;

            //list of builtin functions
            _builtinFunctions.Add("substr", substr);

            // list of builtin variables
            _builtinVariablesGet.Add("length", () => Value.FromInteger(_value.Length));
        }

        private Value substr(Value[] args)
        {
            if (args.Length == 1)
            {
                return Value.FromString(_value.Substring(args[0].ToInteger()));
            }
            else if (args.Length == 2)
            {
                return Value.FromString(_value.Substring(args[0].ToInteger(), args[1].ToInteger()));
            }
            else
            {
                throw new InvalidOperationException("Argument count invalid!");
            }
        }
    }
}


text:
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> {
    __weak IBOutlet DTParallaxTableView *_tableView;
    __weak IBOutlet UIView *tabbar;
}

@end


text:
package cgeo.geocaching;

import cgeo.geocaching.databinding.StatusBinding;
import cgeo.geocaching.network.StatusUpdater;
import cgeo.geocaching.network.StatusUpdater.Status;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.Log;

import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import io.reactivex.rxjava3.disposables.CompositeDisposable;

public class StatusFragment extends Fragment {

    private final CompositeDisposable statusSubscription = new CompositeDisposable();
    private StatusBinding binding;

    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        binding = StatusBinding.inflate(getLayoutInflater(), container, false);
        final ViewGroup statusGroup = binding.getRoot();
        statusSubscription.add(AndroidRxUtils.bindFragment(this, StatusUpdater.LATEST_STATUS)
                .subscribe(status -> {
                    if (status == Status.NO_STATUS) {
                        statusGroup.setVisibility(View.GONE);
                        return;
                    }

                    final Resources res = getResources();
                    final String packageName = getActivity().getPackageName();

                    if (status.icon != null) {
                        final int iconId = res.getIdentifier(status.icon, "drawable", packageName);
                        if (iconId != 0) {
                            binding.statusIcon.setImageResource(iconId);
                            binding.statusIcon.setVisibility(View.VISIBLE);
                        } else {
                            Log.w("StatusHandler: could not find icon corresponding to @drawable/" + status.icon);
                            binding.statusIcon.setVisibility(View.GONE);
                        }
                    } else {
                        binding.statusIcon.setVisibility(View.GONE);
                    }

                    String message = status.message;
                    if (status.messageId != null) {
                        final int messageId = res.getIdentifier(status.messageId, "string", packageName);
                        if (messageId != 0) {
                            message = res.getString(messageId);
                        }
                    }

                    binding.statusMessage.setText(message);
                    statusGroup.setVisibility(View.VISIBLE);

                    if (status.url != null) {
                        statusGroup.setOnClickListener(v -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(status.url)))); // don't use ShareUtils here. E.g. we want to redirect directly to PlayStore even if "use WebView" is set
                    } else {
                        statusGroup.setClickable(false);
                    }
                }));
        return statusGroup;
    }

    @Override
    public void onDestroyView() {
        statusSubscription.clear();
        super.onDestroyView();
    }

}