text:
// @(#)$Id: IteratorAbstractAdapter.java,v 1.2 2005/07/07 21:03:04 leavens Exp $

// Copyright (C) 2005 Iowa State University
//
// This file is part of the runtime library of the Java Modeling Language.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2.1,
// of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with JML; see the file LesserGPL.txt.  If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301  USA.

package org.jmlspecs.jmlunit.strategies;

import java.util.Iterator;
import java.util.NoSuchElementException;

/** Make a java.util.Iterator into an IndefiniteIterator.
 * @author Gary T. Leavens
 */
public abstract class IteratorAbstractAdapter implements IndefiniteIterator {

    /** The underlying iterator */
    private /*@ spec_public non_null @*/ Iterator iter;

    /** Initialize this indefinite iterator to iterate over the
     * elements that iter iterates over. */
    /*@ public normal_behavior
      @   requires iter != null;
      @   assignable this.iter, objectState;
      @   ensures (* this.iter is a clone of iter *);
      @*/
    public IteratorAbstractAdapter(Iterator iter) {
        this.iter = cloneIterator(iter);
        if (iter.hasNext()) {
            item = iter.next();
        } else {
            atEnd = true;
        }
    }

    private boolean atEnd = false; //@ in objectState;
    private Object item;  //@ in objectState;

    // doc comment and specification inherited
    public boolean atEnd() {
        return atEnd;
    }

    // doc comment and specification inherited
    public /*@ pure @*/ Object get() {
        return item;
    }

    // doc comment and specification inherited
    public void advance() {
        if (!atEnd && iter.hasNext()) {
            item = iter.next();
        } else {
            atEnd = true;
        }
    }

    /** Return a clone of this iterator adapter, which contains a
     * clone of the underlying iterator. This has to be done by
     * subclasses. */
    public abstract Object clone();

    /** Return a clone of the argument iterator */
    /*@ protected normal_behavior
      @   assignable \nothing;
      @   ensures \result != null && (* result is a clone of iter *);
      @*/
    protected abstract Iterator cloneIterator(Iterator iter);
}


text:
//background.cpp

#include "stdafx.h"
#include "goodies.h"
#include "background.h"

namespace mongo {

    BackgroundJob *BackgroundJob::grab = 0;
    mongo::mutex BackgroundJob::mutex;

    /* static */
    void BackgroundJob::thr() {
        assert( grab );
        BackgroundJob *us = grab;
        assert( us->state == NotStarted );
        us->state = Running;
        grab = 0;
        us->run();
        us->state = Done;
        if ( us->deleteSelf )
            delete us;
    }

    BackgroundJob& BackgroundJob::go() {
        scoped_lock bl(mutex);
        assert( grab == 0 );
        grab = this;
        boost::thread t(thr);
        while ( grab )
            sleepmillis(2);
        return *this;
    }

    bool BackgroundJob::wait(int msMax) {
        assert( state != NotStarted );
        int ms = 1;
        Date_t start = jsTime();
        while ( state != Done ) {
            sleepmillis(ms);
            if ( ms < 1000 )
                ms = ms * 2;
            if ( msMax && ( int( jsTime() - start ) > msMax) )
                return false;
        }
        return true;
    }

} // namespace mongo

redpajama_set_name: RedPajamaGithub


text:
import unittest
import json
import pandas as pd
from bdgenomics.mango.io.readers import read_vcf
import bdgenomics.mango.pileup as pileup
from bdgenomics.mango.pileup.track import *
from bdgenomics.mango.io.test import IOTestCase

class VCFFileTest(IOTestCase):
    global filename
    filename = "genodata.v3.vcf"

    def test_required_columns(self):
        dataframe = read_vcf(self.exampleFile(filename))
        VCF_HEADER = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT']
        dataframe_columns = list(dataframe.columns)
        for name in VCF_HEADER:
            assert(name in dataframe_columns)

    def test_column_type(self):
        dataframe = read_vcf(self.exampleFile(filename))
        VCF_HEADER = ['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT']
        def enforce_type(item, type_x):
            assert(type(item) == type_x)

        for head in VCF_HEADER:
            current_type = str
            if (head == 'POS'):
                current_type = "<class 'numpy.int64'>";
            elif (head == 'QUAL'):
                current_type = "<class 'numpy.float64'>";
            result = [enforce_type, list(dataframe[head])]

    def test_to_json(self):
        dataframe = read_vcf(self.exampleFile(filename))

        def is_valid_json(string):
            try:
                json_object = json.loads(string)
            except ValueError:
                return False
            return True

        assert(type(dataframe._mango_to_json) == str)
        assert(is_valid_json(dataframe._mango_to_json) == True)

    def test_visualization(self):
        dataframe = read_vcf(self.exampleFile(filename))

        assert(dataframe._pileup_visualization == "variantJson")
        tracks=[Track(viz="variants", label="my variants", source=pileup.sources.DataFrameSource(dataframe))]
        reads = pileup.PileupViewer(chrom="chr22",start=10436,stop=10564, reference="hg19", tracks=tracks)
        assert(str(type(reads)) == '<class \'bdgenomics.mango.pileup.pileupViewer.PileupViewer\'>')
        assert(reads.chrom == 'chr22')

    # Run tests
if __name__ == '__main__':
    unittest.main()


text:
/* The rest of this file contains styles related to the mechanics of
   the editor. You probably shouldn't touch them. */

.CodeMirror {
  position: relative;
  overflow: hidden;
  background: white;
}

.CodeMirror-scroll {
  overflow: scroll !important; /* Things will break if this is overridden */
  /* 30px is the magic margin used to hide the element's real scrollbars */
  /* See overflow: hidden in .CodeMirror */
  margin-bottom: -30px; margin-right: -30px;
  padding-bottom: 30px;
  height: 100%;
  outline: none; /* Prevent dragging from highlighting the element */
  position: relative;
}
.CodeMirror-sizer {
  position: relative;
  border-right: 30px solid transparent;
}

/* The fake, visible scrollbars. Used to force redraw during scrolling
   before actual scrolling happens, thus preventing shaking and
   flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
  position: absolute;
  z-index: 6;
  display: none;
}
.CodeMirror-vscrollbar {
  right: 0; top: 0;
  overflow-x: hidden;
  overflow-y: scroll;
}
.CodeMirror-hscrollbar {
  bottom: 0; left: 0;
  overflow-y: hidden;
  overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
  right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
  left: 0; bottom: 0;
}

.CodeMirror-gutters {
  position: absolute; left: 0; top: 0;
  min-height: 100%;
  z-index: 3;
}
.CodeMirror-gutter {
  white-space: normal;
  height: 100%;
  display: inline-block;
  vertical-align: top;
  margin-bottom: -30px;
}
.CodeMirror-gutter-wrapper {
  position: absolute;
  z-index: 4;
  background: none !important;
  border: none !important;
}
.CodeMirror-gutter-background {
  position: absolute;
  top: 0; bottom: 0;
  z-index: 4;
}
.CodeMirror-gutter-elt {
  position: absolute;
  cursor: default;
  z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }

.CodeMirror-lines {
  cursor: text;
  min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre {
  /* Reset some styles that the rest of the page might have set */
  -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
  border-width: 0;
  background: transparent;
  font-family: inherit;
  font-size: inherit;
  margin: 0;
  white-space: pre;
  word-wrap: normal;
  line-height: inherit;
  color: inherit;
  z-index: 2;
  position: relative;
  overflow: visible;
  -webkit-tap-highlight-color: transparent;
  -webkit-font-variant-ligatures: contextual;
  font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre {
  word-wrap: break-word;
  white-space: pre-wrap;
  word-break: normal;
}

.CodeMirror-linebackground {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 0;
}

.CodeMirror-linewidget {
  position: relative;
  z-index: 2;
  padding: 0.1px; /* Force widget margins to stay inside of the container */
}

.CodeMirror-widget {}

.CodeMirror-rtl pre { direction: rtl; }

.CodeMirror-code {
  outline: none;
}

/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
  -moz-box-sizing: content-box;
  box-sizing: content-box;
}

.CodeMirror-measure {
  position: absolute;
  width: 100%;
  height: 0;
  overflow: hidden;
  visibility: hidden;
}

.CodeMirror-cursor {
  position: absolute;
  pointer-events: none;
}
.CodeMirror-measure pre { position: static; }

div.CodeMirror-cursors {
  visibility: hidden;
  position: relative;
  z-index: 3;
}
div.CodeMirror-dragcursors {
  visibility: visible;
}

.CodeMirror-focused div.CodeMirror-cursors {
  visibility: visible;
}

.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }

.cm-searching {
  background-color: #ffa;
  background-color: rgba(255, 255, 0, .4);
}

/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }

@media print {
  /* Hide the cursor when printing */
  .CodeMirror div.CodeMirror-cursors {
    visibility: hidden;
  }
}

/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }

/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }


text:
package com.zhao.album;

import java.io.Serializable;

/**
 * @author: zzp
 * @since: 2015-06-16
 */
public class SingleImageModel implements Serializable{
    public String path;
    public boolean isPicked;
    public long date;
    public long id;
    public SingleImageModel(String path, boolean isPicked, long date, long id){
        this.path = path;
        this.isPicked = isPicked;
        this.date = date;
        this.id = id;
    }
    public SingleImageModel(){

    }
    public boolean isThisImage(String path){
        return this.path.equalsIgnoreCase(path);
    }
}


text:
namespace base {

// Gets and sets the job object used for creating new child processes,
// and looking them up by their process IDs.
// zx::job::default_job() will be returned if no job is explicitly set here.
// Only valid handles may be passed to SetDefaultJob().
BASE_EXPORT zx::unowned_job GetDefaultJob();
BASE_EXPORT void SetDefaultJob(zx::job job);

// Replaces the current default job (if any) with the specified zx::job, and
// restores the original default job when going out-of-scope.
// Note that replacing the default job is not thread-safe!
class BASE_EXPORT ScopedDefaultJobForTest {
 public:
  ScopedDefaultJobForTest(zx::job new_default_job);
  ~ScopedDefaultJobForTest();

 private:
  zx::job old_default_job_;
  DISALLOW_COPY_AND_ASSIGN(ScopedDefaultJobForTest);
};

}  // namespace base

#endif  // BASE_FUCHSIA_DEFAULT_JOB_H_


text:
{#
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
 #
 # http://www.apache.org/licenses/LICENSE-2.0
 #
 # Unless required by applicable law or agreed to in writing, software
 # distributed under the License is distributed on an "AS IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-#}
{% extends "email/_base/body.html" %}

{% set site = request.registry.settings["site.name"] %}

{% block content %}

  {% trans organization_name=organization_name, project_name=project_name, site=site %}The {{ site }} project "{{ project_name }}" has been added to the "{{ organization_name }}" organization.{% endtrans %}

  {% trans email_address="admin@pypi.org", site=site %}If this was a mistake, you can email {{ email_address }} to communicate with the {{ site }} administrators.{% endtrans %}

{% endblock %}

{% block reason %}
{% trans %}You are receiving this because you are an owner of the project or the organization.{% endtrans %}
{% endblock %}


text:
package iam

import (
	SDK "github.com/aws/aws-sdk-go/service/iam"
)

// PolicyEntity contains Entity's id and name.
// Entity is User, Group or Role.
type PolicyEntity struct {
	Type EntityType
	ID   string
	Name string
}

// NewPolicyEntityList creates []PolicyEntity from *SDK.ListEntitiesForPolicyOutput.
func NewPolicyEntityList(o *SDK.ListEntitiesForPolicyOutput) []PolicyEntity {
	maxSize := len(o.PolicyUsers) + len(o.PolicyGroups) + len(o.PolicyRoles)
	list := make([]PolicyEntity, 0, maxSize)

	for _, e := range o.PolicyUsers {
		list = append(list, PolicyEntity{
			Type: NewEntityTypeUser(),
			ID:   *e.UserId,
			Name: *e.UserName,
		})
	}

	for _, e := range o.PolicyGroups {
		list = append(list, PolicyEntity{
			Type: NewEntityTypeGroup(),
			ID:   *e.GroupId,
			Name: *e.GroupName,
		})
	}

	for _, e := range o.PolicyRoles {
		list = append(list, PolicyEntity{
			Type: NewEntityTypeRole(),
			ID:   *e.RoleId,
			Name: *e.RoleName,
		})
	}
	return list
}

// IsUser checks this entity is user or not.
func (e PolicyEntity) IsUser() bool {
	return e.Type == entityTypeUser
}

// IsGroup checks this entity is group or not.
func (e PolicyEntity) IsGroup() bool {
	return e.Type == entityTypeGroup
}

// IsRole checks this entity is role or not.
func (e PolicyEntity) IsRole() bool {
	return e.Type == entityTypeRole
}

// EntityType represents entity's type.
type EntityType string

const (
	entityTypeUser  = "user"
	entityTypeGroup = "group"
	entityTypeRole  = "role"
)

// NewEntityTypeUser returns user's EntityType.
func NewEntityTypeUser() EntityType {
	return EntityType(entityTypeUser)
}

// NewEntityTypeGroup returns group's EntityType.
func NewEntityTypeGroup() EntityType {
	return EntityType(entityTypeGroup)
}

// NewEntityTypeRole returns role's EntityType.
func NewEntityTypeRole() EntityType {
	return EntityType(entityTypeRole)
}


text:
//
//  JXBaseAnimate.h
//  demo
//
//  Created by andy on 2/27/15.
//  Copyright (c) 2015 NationSky. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface JXBaseAnimate : NSObject

/**
 *  滚动动画
 *
 *  @param imageViews    图片
 *  @param contentOffset 滚动偏移量
 */
- (void)animateWithImageViews:(NSArray *)imageViews
      scrollViewContentOffset:(CGFloat)contentOffsetX;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popup_window_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginBottom="@dimen/popup_window_margin_bottom"
        android:layout_marginEnd="@dimen/popup_window_margin_right"
        android:layout_marginLeft="@dimen/popup_window_margin_left"
        android:layout_marginRight="@dimen/popup_window_margin_right"
        android:layout_marginStart="@dimen/popup_window_margin_left"
        android:background="@drawable/popup_window_background"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/popup_window_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/popup_window_bg_top_selector"
            android:gravity="center"
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:text="Title"
            android:textColor="@color/popup_window_title_color"
            android:textSize="18sp" />

        <View
            android:id="@+id/popup_window_divider"
            android:layout_width="match_parent"
            android:layout_height="0.5dp"
            android:background="@color/divider_color" />

        <TextView
            android:id="@+id/popup_window_msg"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:padding="10dp"
            android:text="Message"
            android:textColor="@color/popup_window_text_color"
            android:textSize="12sp" />

        <LinearLayout
            android:id="@+id/popup_window_buttons"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical" />
    </LinearLayout>
</RelativeLayout>


text:
#include "ipc/settings_client.h"

#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "ipc/constants.h"
#include "ipc/message_types.h"
#include "ipc/message_util.h"
#include "ipc/mock_component.h"
#include "ipc/mock_component_host.h"
#include "ipc/protos/ipc.pb.h"
#include "ipc/test_util.h"
#include "ipc/testing.h"

namespace {

using namespace ipc;

static bool ProtoMessageEqual(const ::google::protobuf::MessageLite& a,
                              const ::google::protobuf::MessageLite& b) {
  return a.SerializePartialAsString() == b.SerializePartialAsString();
}

// Messages an input method can produce.
const uint32 kIMEProduceMessages[] = {
  MSG_REGISTER_COMPONENT,
  MSG_DEREGISTER_COMPONENT,
  MSG_SET_COMMAND_LIST,
  MSG_UPDATE_COMMANDS,
  MSG_ADD_HOTKEY_LIST,
  MSG_REMOVE_HOTKEY_LIST,
  MSG_CHECK_HOTKEY_CONFLICT,
  MSG_ACTIVATE_HOTKEY_LIST,
  MSG_DEACTIVATE_HOTKEY_LIST,
  MSG_ATTACH_TO_INPUT_CONTEXT,
  MSG_QUERY_INPUT_CONTEXT,
  MSG_REQUEST_CONSUMER,
  MSG_SET_COMPOSITION,
  MSG_INSERT_TEXT,
  MSG_SET_CANDIDATE_LIST,
};

// Messages an input method can consume.
const uint32 kIMEConsumeMessages[] = {
  MSG_ATTACH_TO_INPUT_CONTEXT,
  MSG_DETACHED_FROM_INPUT_CONTEXT,
  MSG_INPUT_CONTEXT_GOT_FOCUS,
  MSG_INPUT_CONTEXT_LOST_FOCUS,
  MSG_PROCESS_KEY_EVENT,
  MSG_CANCEL_COMPOSITION,
  MSG_COMPLETE_COMPOSITION,
  MSG_CANDIDATE_LIST_SHOWN,
  MSG_CANDIDATE_LIST_HIDDEN,
  MSG_CANDIDATE_LIST_PAGE_DOWN,
  MSG_CANDIDATE_LIST_PAGE_UP,
  MSG_CANDIDATE_LIST_SCROLL_TO,
  MSG_CANDIDATE_LIST_PAGE_RESIZE,
  MSG_SELECT_CANDIDATE,
  MSG_UPDATE_INPUT_CARET,
};

// A mock input method component with a SettingsClient sub component.
class IMEComponent : public MockComponent,
                     public SettingsClient::Delegate {
 public:
  explicit IMEComponent() : MockComponent("IME1") {
    settings_client_ = new SettingsClient(this, this);
  }

  virtual void GetInfo(proto::ComponentInfo* info) OVERRIDE {
    SetupComponentInfo("", "Mock Input Method", "",
                       kIMEProduceMessages, arraysize(kIMEProduceMessages),
                       kIMEConsumeMessages, arraysize(kIMEConsumeMessages),
                       info);
    GetSubComponentsInfo(info);
    MockComponent::GetInfo(info);
  }

  // Overridden from Component.
  virtual void Handle(proto::Message* message) OVERRIDE {
    if (!HandleMessageBySubComponents(message))
      delete message;
  }

  SettingsClient* GetSettingsClient() const {
    return settings_client_;
  }

  // Overridden from SettingsClient::Delegate.
  virtual void OnValueChanged(const std::string& key,
                              const proto::VariableArray& array) OVERRIDE {
    DCHECK(!key.empty());
    changed_key_ = key;
  }

  std::string changed_key() {
    return changed_key_;
  }

 private:
  std::string changed_key_;
  SettingsClient* settings_client_;
  DISALLOW_COPY_AND_ASSIGN(IMEComponent);
};

class SettingsClientTest : public ::testing::Test {
 protected:
  SettingsClientTest() {
    settings_client_ = ime_.GetSettingsClient();
    keys_[0] = "key1";
    keys_[1] = "key2";
    keys_[2] = "key3";
    keys_[3] = "key4";
    values_[0].set_type(proto::Variable::STRING);
    values_[0].set_string(keys_[0]);
    values_[1].set_type(proto::Variable::BOOLEAN);
    values_[1].set_boolean(true);
    values_[2].set_type(proto::Variable::NONE);
    values_[3].set_type(proto::Variable::INTEGER);
    values_[3].set_integer(1);
  }

  virtual ~SettingsClientTest() {}

  // Sets up an ipc communication environment. An IME mock component accesses
  // the settings through the ipc layer.
  virtual void SetUp() {
    host_.AddComponent(&ime_);
  }

  virtual void TearDown() {
    host_.RemoveComponent(&ime_);
  }

  proto::Message* NewMessage(uint32 type, bool need_reply) {
    return ipc::NewMessage(type,
                           ime_.id(),
                           kComponentDefault,
                           kInputContextNone,
                           false);
  }

  proto::Message* NewReplyMessage(uint32 type) {
    proto::Message* message = NewMessage(type, false);
    message->set_reply_mode(proto::Message::IS_REPLY);
    return message;
  }

  proto::Message* NewErrorReplyMessage(uint32 type) {
    proto::Message* message = NewReplyMessage(type);
    message->mutable_payload()->mutable_error()->set_code(
        proto::Error::INVALID_PAYLOAD);
    message->mutable_payload()->mutable_error()->set_message("INVALID_PAYLOAD");
    return message;
  }

  void CheckMessage(const scoped_ptr<proto::Message>& mptr, uint32 type,
                    proto::Message::ReplyMode reply_mode) {
    ASSERT_TRUE(mptr.get());
    ASSERT_EQ(type, mptr->type());
    ASSERT_EQ(reply_mode, mptr->reply_mode());
    ASSERT_EQ(ime_.id(), mptr->source());
    ASSERT_EQ(kComponentDefault, mptr->target());
    ASSERT_EQ(kInputContextNone, mptr->icid());
  }

  SettingsClient* settings_client_;
  MockComponentHost host_;
  IMEComponent ime_;
  std::string keys_[4];
  proto::Variable values_[4];
};

typedef SettingsClient::KeyList KeyList;
typedef SettingsClient::ResultList ResultList;

TEST_F(SettingsClientTest, HandleTest) {
  scoped_ptr<proto::Message> mptr;
  std::string key = "key";
  proto::Variable value;
  value.set_type(proto::Variable::STRING);
  value.set_string(key);
  mptr.reset(ipc::NewMessage(MSG_SETTINGS_CHANGED,
                             kComponentDefault,
                             ime_.id(),
                             kInputContextNone,
                             true));
  mptr->mutable_payload()->add_string(key);
  mptr->mutable_payload()->add_variable()->CopyFrom(value);
  host_.HandleMessage(mptr.release());
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_CHANGED,
                                       proto::Message::IS_REPLY));
  EXPECT_EQ(mptr->payload().boolean_size(), 1);
  EXPECT_EQ(mptr->payload().boolean(0), true);
  // Checks if OnValueChanged was called.
  EXPECT_EQ(ime_.changed_key(), key);
}

TEST_F(SettingsClientTest, SetValuesTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  KeyList key_list;
  proto::VariableArray array;
  ResultList results;

  // SetValues with successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  for (int i = 0; i < 3; ++i) {
    key_list.push_back(keys_[i]);
    array.add_variable()->CopyFrom(values_[i]);
    reply_mptr->mutable_payload()->add_boolean(true);
  }
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->SetValues(key_list, array, &results));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_SET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 3);
  EXPECT_EQ(mptr->payload().variable_size(), 3);
  EXPECT_EQ(results.size(), 3);
  for (int i = 0; i < 3; ++i) {
    EXPECT_EQ(keys_[i], mptr->payload().string(i));
    EXPECT_TRUE(ProtoMessageEqual(values_[i], mptr->payload().variable(i)));
    EXPECT_TRUE(results[i]);
  }
  // SetValues with error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_SET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetValues(key_list, array, &results));
  host_.PopOutgoingMessage();

  // SetValues with key_list.size() != array.size(), no message sent.
  key_list.push_back(keys_[3]);
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_SET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetValues(key_list, array, &results));

  // SetValues with empty key list, return false without reply.
  key_list.clear();
  ASSERT_FALSE(settings_client_->SetValues(key_list, array, &results));
}

TEST_F(SettingsClientTest, GetValuesTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  KeyList key_list;
  proto::VariableArray array;

  // GetValues with successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_GET_VALUES));
  for (int i = 0; i < 3; ++i) {
    key_list.push_back(keys_[i]);
    reply_mptr->mutable_payload()->add_string(keys_[i]);
    reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[i]);
  }
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->GetValues(key_list, &array));
  EXPECT_EQ(3, array.variable_size());
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_GET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 3);
  for (int i = 0; i < 3; i++) {
    EXPECT_EQ(keys_[i], mptr->payload().string(i));
    EXPECT_TRUE(ProtoMessageEqual(values_[i], array.variable(i)));
  }

  // GetValues with error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_GET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->GetValues(key_list, &array));
  host_.PopOutgoingMessage();

  // GetValues with empty key list. False is returned without message sent.
  key_list.clear();
  ASSERT_FALSE(settings_client_->GetValues(key_list, &array));
}

TEST_F(SettingsClientTest, SetValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;

  // SetValue with successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->SetValue(keys_[0], values_[0]));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_SET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().variable_size(), 1);
  EXPECT_EQ(keys_[0], mptr->payload().string(0));
  EXPECT_TRUE(ProtoMessageEqual(values_[0], mptr->payload().variable(0)));

  // SetValue with empty key. False is returned.
  std::string empty_key;
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(false);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetValue(empty_key, values_[0]));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, GetValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  proto::Variable reply_value;

  // GetValue with successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_GET_VALUES));
  reply_mptr->mutable_payload()->add_string(keys_[0]);
  reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[0]);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->GetValue(keys_[0], &reply_value));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_GET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(keys_[0], mptr->payload().string(0));
  EXPECT_TRUE(ProtoMessageEqual(values_[0], reply_value));
}

TEST_F(SettingsClientTest, SetArrayValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  proto::VariableArray array;

  // SetArrayValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_ARRAY_VALUE));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  array.clear_variable();
  array.add_variable()->CopyFrom(values_[0]);
  array.add_variable()->CopyFrom(values_[2]);
  ASSERT_TRUE(settings_client_->SetArrayValue(keys_[0], array));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_SET_ARRAY_VALUE,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().variable_size(), 2);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_TRUE(ProtoMessageEqual(mptr->payload().variable(0), values_[0]));
  EXPECT_TRUE(ProtoMessageEqual(mptr->payload().variable(1), values_[2]));

  // SetArrayValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_SET_ARRAY_VALUE));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetArrayValue(keys_[0], array));
  host_.PopOutgoingMessage();

  // SetArrayValue with an empty key. False is replyed.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(false);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetArrayValue(keys_[0], array));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, GetArrayValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  proto::VariableArray array;

  // GetArrayValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_GET_ARRAY_VALUE));
  reply_mptr->mutable_payload()->add_string(keys_[0]);
  reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[0]);
  reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[1]);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->GetArrayValue(keys_[0], &array));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_GET_ARRAY_VALUE,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(array.variable_size(), 2);
  EXPECT_TRUE(ProtoMessageEqual(array.variable(0), values_[0]));
  EXPECT_TRUE(ProtoMessageEqual(array.variable(1), values_[1]));

  // GetArrayValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_GET_ARRAY_VALUE));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->GetArrayValue(keys_[0], &array));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, AddChangeObserverTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  KeyList key_list;

  // AddChangeObserverForKeys with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_ADD_CHANGE_OBSERVER));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  key_list.clear();
  key_list.push_back(keys_[0]);
  key_list.push_back(keys_[1]);
  ASSERT_TRUE(settings_client_->AddChangeObserverForKeys(key_list));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_ADD_CHANGE_OBSERVER,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 2);
  EXPECT_EQ(keys_[0], mptr->payload().string(0));
  EXPECT_EQ(keys_[1], mptr->payload().string(1));

  // AddChangeObserverForKeys with an empty key_list. False is replyed without
  // message sent.
  key_list.clear();
  ASSERT_FALSE(settings_client_->AddChangeObserverForKeys(key_list));

  // AddChangeObserver with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_ADD_CHANGE_OBSERVER));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->AddChangeObserver(keys_[0]));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_ADD_CHANGE_OBSERVER,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(keys_[0], mptr->payload().string(0));
}

TEST_F(SettingsClientTest, RemoveChangeObserverTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  KeyList key_list;

  // RemoveChangeObserverForKeys with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_REMOVE_CHANGE_OBSERVER));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  key_list.clear();
  key_list.push_back(keys_[0]);
  key_list.push_back(keys_[1]);
  ASSERT_TRUE(settings_client_->RemoveChangeObserverForKeys(key_list));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(
      CheckMessage(mptr, MSG_SETTINGS_REMOVE_CHANGE_OBSERVER,
                   proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 2);
  EXPECT_EQ(keys_[0], mptr->payload().string(0));
  EXPECT_EQ(keys_[1], mptr->payload().string(1));

  // RemoveChangeObserverForKeys with an empty key_list. False is returned
  // without message sent.
  key_list.clear();
  ASSERT_FALSE(settings_client_->RemoveChangeObserverForKeys(key_list));

  // RemoveChangeObserver with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_REMOVE_CHANGE_OBSERVER));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->RemoveChangeObserver(keys_[0]));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(
      CheckMessage(mptr, MSG_SETTINGS_REMOVE_CHANGE_OBSERVER,
                   proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(keys_[0], mptr->payload().string(0));
}

TEST_F(SettingsClientTest, SetIntegerValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;

  // SetIntegerValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->SetIntegerValue(keys_[0],
                                                values_[3].integer()));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_SET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().variable_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(mptr->payload().variable(0).type(), proto::Variable::INTEGER);
  EXPECT_EQ(mptr->payload().variable(0).integer(), values_[3].integer());

  // SetIntegerValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_SET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetIntegerValue(keys_[0],
                                                 values_[3].integer()));
  host_.PopOutgoingMessage();

  // SetIntegerValue with a false reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(false);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetIntegerValue(keys_[0],
                                                 values_[3].integer()));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, GetIntegerValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  int64 int_value;

  // GetIntegerValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_GET_VALUES));
  reply_mptr->mutable_payload()->add_string(keys_[0]);
  reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[3]);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->GetIntegerValue(keys_[0], &int_value));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_GET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(int_value, values_[3].integer());

  // GetIntegerValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_GET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->GetIntegerValue(keys_[0], &int_value));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, SetStringValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;

  // SetStringValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->SetStringValue(keys_[0], values_[0].string()));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_SET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().variable_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(mptr->payload().variable(0).type(), proto::Variable::STRING);
  EXPECT_EQ(mptr->payload().variable(0).string(), values_[0].string());

  // SetStringValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_SET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetStringValue(keys_[0], values_[0].string()));
  host_.PopOutgoingMessage();

  // SetStringValue with a false reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(false);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetStringValue(keys_[0], values_[0].string()));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, GetStringValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  string string_value;

  // GetStringValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_GET_VALUES));
  reply_mptr->mutable_payload()->add_string(keys_[0]);
  reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[0]);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->GetStringValue(keys_[0], &string_value));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_GET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(string_value, values_[0].string());

  // GetStringValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_GET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->GetStringValue(keys_[0], &string_value));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, SetBooleanValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  // SetBooleanValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(true);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->SetBooleanValue(keys_[0],
                                                values_[1].boolean()));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_SET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().variable_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(mptr->payload().variable(0).type(), proto::Variable::BOOLEAN);
  EXPECT_EQ(mptr->payload().variable(0).boolean(), values_[1].boolean());

  // SetBooleanValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_SET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetBooleanValue(keys_[0],
                                                 values_[1].boolean()));
  host_.PopOutgoingMessage();

  // SetBooleanValue with a false reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_SET_VALUES));
  reply_mptr->mutable_payload()->add_boolean(false);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->SetBooleanValue(keys_[0],
                                                 values_[1].boolean()));
  host_.PopOutgoingMessage();
}

TEST_F(SettingsClientTest, GetBooleanValueTest) {
  scoped_ptr<proto::Message> mptr;
  scoped_ptr<proto::Message> reply_mptr;
  bool boolean_value;

  // GetBooleanValue with a successful reply.
  reply_mptr.reset(NewReplyMessage(MSG_SETTINGS_GET_VALUES));
  reply_mptr->mutable_payload()->add_string(keys_[0]);
  reply_mptr->mutable_payload()->add_variable()->CopyFrom(values_[1]);
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_TRUE(settings_client_->GetBooleanValue(keys_[0], &boolean_value));
  mptr.reset(host_.PopOutgoingMessage());
  ASSERT_NO_FATAL_FAILURE(CheckMessage(mptr, MSG_SETTINGS_GET_VALUES,
                                       proto::Message::NEED_REPLY));
  EXPECT_EQ(mptr->payload().string_size(), 1);
  EXPECT_EQ(mptr->payload().string(0), keys_[0]);
  EXPECT_EQ(boolean_value, values_[1].boolean());

  // GetIntegerValue with an error reply.
  reply_mptr.reset(NewErrorReplyMessage(MSG_SETTINGS_GET_VALUES));
  host_.SetNextReplyMessage(reply_mptr.release());
  ASSERT_FALSE(settings_client_->GetBooleanValue(keys_[0], &boolean_value));
  host_.PopOutgoingMessage();
}

}  // namespace


text:
<?php

namespace Antares\Extension;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Antares\Contracts\Extension\RouteGenerator as RouteGeneratorContract;

class RouteGenerator implements RouteGeneratorContract
{

    /**
     * Request instance.
     *
     * @var Request
     */
    protected $request;

    /**
     * Domain name.
     *
     * @var string
     */
    protected $domain;

    /**
     * Handles path.
     *
     * @var string
     */
    protected $prefix;

    /**
     * Base URL.
     *
     * @var string
     */
    protected $baseUrl = '';

    /**
     * Base URL prefix.
     *
     * @var string
     */
    protected $basePrefix = null;

    /**
     * Construct a new instance.
     *
     * @param  string  $handles
     * @param  \Illuminate\Http\Request  $request
     */
    public function __construct($handles = null, Request $request)
    {
        $this->request = $request;
        $this->setBaseUrl($this->request->root());
        if ($handles === null || !Str::startsWith($handles, ['//', 'http://', 'https://'])) {
            $this->prefix = $handles;
        } else {
            $handles      = substr(str_replace(['http://', 'https://'], '//', $handles), 2);
            $fragments    = explode('/', $handles, 2);
            $this->domain = array_shift($fragments);
            $this->prefix = array_shift($fragments);
        }
        !is_null($this->prefix) || $this->prefix = '/';
    }

    /**
     * Get route domain.
     *
     * @param  bool  $forceBase
     *
     * @return string
     */
    public function domain($forceBase = false)
    {
        $pattern = $this->domain;

        if ($pattern === null && $forceBase === true) {
            $pattern = $this->baseUrl;
        } elseif (Str::contains($pattern, '{{domain}}')) {
            $pattern = str_replace('{{domain}}', $this->baseUrl, $pattern);
        }

        return $pattern;
    }

    /**
     * Determine if the current request URI matches a pattern.
     *
     * @param  string  $pattern
     *
     * @return bool
     */
    public function is($pattern)
    {
        $path   = $this->path();
        $prefix = $this->prefix();

        foreach (func_get_args() as $_pattern) {
            $_pattern = ($_pattern === '*' ? "{$prefix}*" : "{$prefix}/{$_pattern}");
            $_pattern = trim($_pattern, '/');

            empty($_pattern) && $_pattern = '/';

            if (Str::is($_pattern, $path)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Get the current path info for the request.
     *
     * @return string
     */
    public function path()
    {
        $pattern = trim($this->request->path(), '/');

        return $pattern === '' ? '/' : $pattern;
    }

    /**
     * Get route prefix.
     *
     * @param  bool  $forceBase
     *
     * @return string
     */
    public function prefix($forceBase = false)
    {
        if (!is_string($this->prefix)) {
            return '/';
        }
        $pattern = trim($this->prefix, '/');

        if ($this->domain === null && $forceBase === true) {
            $pattern = trim($this->basePrefix, '/') . "/{$pattern}";
            $pattern = trim($pattern, '/');
        }
        empty($pattern) && $pattern = '/';
        return $pattern;
    }

    /**
     * Get route root.
     *
     * @return string
     */
    public function root()
    {
        $http   = ($this->request->secure() ? 'https' : 'http');
        $domain = trim($this->domain(true), '/');
        $prefix = $this->prefix(true);

        return trim("{$http}://{$domain}/{$prefix}", '/');
    }

    /**
     * Set base URL.
     *
     * @param  string  $root
     *
     * @return $this
     */
    public function setBaseUrl($root)
    {
        $baseUrl = str_replace(['https://', 'http://'], '', $root);
        $base    = explode('/', $baseUrl, 2);

        if (count($base) > 1) {
            $this->basePrefix = array_pop($base);
        }

        $this->baseUrl = array_shift($base);

        return $this;
    }

    /**
     * Get route to.
     *
     * @param  string  $to
     *
     * @return string
     */
    public function to($to)
    {
        $root    = $this->root();
        $to      = trim($to, '/');
        $pattern = trim("{$root}/{$to}", '/');

        return $pattern !== '/' ? $pattern : '';
    }

    /**
     * Magic method to parse as string.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->prefix();
    }

    /**
     * Member prefix setter
     *
     * @param string $prefix
     * @return RouteGenerator
     */
    public function setPrefix($prefix = null)
    {
        $this->prefix = ($prefix === null) ? 'member' : $prefix;

        return $this;
    }

    /**
     * Sets user level as prefix in route
     *
     * @return RouteGenerator
     */
    public function setAreaPrefix()
    {
        if (auth()->guest()) {
            return $this;
        }

        $this->prefix = app('antares.areas')->getUserArea();
        return $this;
    }

}


text:
from django import forms
from django.forms import widgets
from gonzo.hunt import models

class SubmissionForm(forms.ModelForm):
    class Meta:
        model = models.Submission
        fields = ['photo','latitude','longitude','via']
        widgets = {
            'latitude': widgets.HiddenInput(),
            'longitude': widgets.HiddenInput(),
            'via': widgets.HiddenInput(attrs={'value':'Web'})
        }

class CommentForm(forms.ModelForm):
    class Meta:
        model = models.Comment
        fields = ['text']


text:
@interface LottieLoaderViewManager : RCTViewManager

@end


text:
package ingress

import (
	"context"
	"os"
	"testing"

	corev1 "k8s.io/api/core/v1"

	"knative.dev/net-contour/pkg/reconciler/contour/config"
	fakenetworkingclient "knative.dev/networking/pkg/client/injection/client/fake"
	duckv1 "knative.dev/pkg/apis/duck/v1"
	fakekubeclient "knative.dev/pkg/client/injection/kube/client/fake"

	ktesting "k8s.io/client-go/testing"
	ingressreconciler "knative.dev/networking/pkg/client/injection/reconciler/networking/v1alpha1/ingress"
	"knative.dev/pkg/configmap"
	"knative.dev/pkg/controller"
	"knative.dev/pkg/logging"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/intstr"
	. "knative.dev/async-component/pkg/reconciler/testing"
	networkpkg "knative.dev/networking/pkg"

	network "knative.dev/pkg/network"

	"knative.dev/networking/pkg/apis/networking"
	"knative.dev/networking/pkg/apis/networking/v1alpha1"
	netv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1"
	. "knative.dev/pkg/reconciler/testing"
)

type testConfigStore struct {
	config *config.Config
}

const (
	defaultNamespace       = "default"
	testingName            = "testing"
	testingAlwaysAsyncName = "testing-always"
	knativeTesting         = "knative-testing"
	exampleHost            = "example.com"
	testHost               = "test.com"
	serviceName            = "servicename"
)

var statusReady = v1alpha1.IngressStatus{
	PublicLoadBalancer: &v1alpha1.LoadBalancerStatus{
		Ingress: []v1alpha1.LoadBalancerIngressStatus{
			{DomainInternal: publicLBDomain},
		},
	},
	PrivateLoadBalancer: &v1alpha1.LoadBalancerStatus{
		Ingress: []v1alpha1.LoadBalancerIngressStatus{
			{DomainInternal: privateLBDomain},
		},
	},
	Status: duckv1.Status{
		Conditions: duckv1.Conditions{{
			Type:   v1alpha1.IngressConditionLoadBalancerReady,
			Status: corev1.ConditionTrue,
		}, {
			Type:   v1alpha1.IngressConditionNetworkConfigured,
			Status: corev1.ConditionTrue,
		}, {
			Type:   v1alpha1.IngressConditionReady,
			Status: corev1.ConditionTrue,
		}},
	},
}

var statusUnknown = v1alpha1.IngressStatus{
	Status: duckv1.Status{
		Conditions: duckv1.Conditions{{
			Type:   v1alpha1.IngressConditionLoadBalancerReady,
			Status: corev1.ConditionUnknown,
		}, {
			Type:   v1alpha1.IngressConditionNetworkConfigured,
			Status: corev1.ConditionUnknown,
		}, {
			Type:   v1alpha1.IngressConditionReady,
			Status: corev1.ConditionUnknown,
		}},
	},
}

var ingWithAsyncAnnotation = ingress(defaultNamespace, testingName, statusReady,
	withAnnotations(map[string]string{
		networking.IngressClassAnnotationKey: asyncIngressClassName,
	}))
var ingAlwaysAsync = ingress(defaultNamespace, testingAlwaysAsyncName, statusReady,
	withAnnotations(map[string]string{
		networking.IngressClassAnnotationKey: asyncIngressClassName,
		AsyncModeAnnotationKey:               asyncAlwaysMode,
	}),
)
var ingSometimesAsync = ingress(defaultNamespace, testingName, statusReady,
	withAnnotations(map[string]string{
		networking.IngressClassAnnotationKey: asyncIngressClassName,
		AsyncModeAnnotationKey:               asyncConditionalMode,
	}),
)
var ingInvalidModeAnnotation = ingress(defaultNamespace, testingName, statusReady,
	withAnnotations(map[string]string{
		networking.IngressClassAnnotationKey: asyncIngressClassName,
		AsyncModeAnnotationKey:               "invalid.mode.annotation.value",
	}),
)

var alwaysAsyncPaths = []netv1alpha1.HTTPIngressPath{{
	Headers: map[string]v1alpha1.HeaderMatch{preferHeaderField: {Exact: preferSyncValue}},
	Splits: []netv1alpha1.IngressBackendSplit{{
		IngressBackend: v1alpha1.IngressBackend{
			ServiceName:      serviceName,
			ServiceNamespace: defaultNamespace,
			ServicePort:      intstr.FromInt(80),
		},
		Percent:       int(100),
		AppendHeaders: map[string]string{"K-Original-Host": testHost},
	}},
},
	{
		RewriteHost: network.GetServiceHostname(producerServiceName, knativeTesting),
		Splits: []netv1alpha1.IngressBackendSplit{{
			Percent: 100,
			IngressBackend: netv1alpha1.IngressBackend{
				ServiceNamespace: defaultNamespace,
				ServiceName:      testingAlwaysAsyncName + asyncSuffix,
				ServicePort:      intstr.FromInt(80),
			},
		}},
		AppendHeaders: map[string]string{asyncOriginalHostHeader: network.GetServiceHostname(testingAlwaysAsyncName, defaultNamespace)},
	},
}

var conditionalAsyncPaths = []netv1alpha1.HTTPIngressPath{{
	RewriteHost: network.GetServiceHostname(producerServiceName, knativeTesting),
	Headers:     map[string]v1alpha1.HeaderMatch{preferHeaderField: {Exact: preferAsyncValue}},
	Splits: []netv1alpha1.IngressBackendSplit{{
		IngressBackend: v1alpha1.IngressBackend{
			ServiceName:      testingName + asyncSuffix,
			ServiceNamespace: defaultNamespace,
			ServicePort:      intstr.FromInt(80),
		},
		Percent: int(100),
	}},
	AppendHeaders: map[string]string{
		asyncOriginalHostHeader: network.GetServiceHostname(testingName, defaultNamespace),
	}},
	{Splits: []netv1alpha1.IngressBackendSplit{{
		Percent: 100,
		AppendHeaders: map[string]string{
			networkpkg.OriginalHostHeader: testHost,
		},
		IngressBackend: netv1alpha1.IngressBackend{
			ServiceNamespace: defaultNamespace,
			ServiceName:      serviceName,
			ServicePort:      intstr.FromInt(80),
		}},
	}},
}
var createdIng = ingressWithPaths(defaultNamespace, testingName, statusUnknown, conditionalAsyncPaths)
var createdIngWithAsyncAlways = ingressWithPaths(defaultNamespace, testingAlwaysAsyncName, statusUnknown, alwaysAsyncPaths)
var createdIngWithIstio = ingressWithIstio(defaultNamespace, testingName, statusUnknown, conditionalAsyncPaths)
var createdUnknownLBIng = ingressWithUnknownLB(defaultNamespace, testingName, statusUnknown, conditionalAsyncPaths)

func TestReconcile(t *testing.T) {
	createdIng.Status.InitializeConditions()
	changedService := service(defaultNamespace, testingName)
	changedService.Spec.ExternalName = "changed"
	table := TableTest{{
		Name: "skip ingress not matching class key",
		Objects: []runtime.Object{
			ingress("testing", "testing", statusReady, withAnnotations(
				map[string]string{networking.IngressClassAnnotationKey: "fake-class-annotation"})),
		}}, {
		Name: "create new ingress with async annotation",
		Key:  "default/testing",
		Objects: []runtime.Object{
			ingWithAsyncAnnotation,
		},
		WantCreates: []runtime.Object{
			createdIng,
			service(defaultNamespace, testingName),
		}}, {
		Name: "test service update",
		Key:  "default/testing",
		Objects: []runtime.Object{
			ingWithAsyncAnnotation,
			changedService,
		},
		WantCreates: []runtime.Object{
			createdIng,
		},
		WantUpdates: []ktesting.UpdateActionImpl{{
			Object: service(defaultNamespace, testingName),
		}}}, {
		Name: "create new ingress with async annotation and sometimes mode value",
		Key:  "default/testing",
		Objects: []runtime.Object{
			ingSometimesAsync,
		},
		WantCreates: []runtime.Object{
			createdIng,
			service(defaultNamespace, testingName),
		}}, {
		Name: "create new ingress with async annotation and always mode value",
		Key:  "default/testing-always",
		Objects: []runtime.Object{
			ingAlwaysAsync,
		},
		WantCreates: []runtime.Object{
			createdIngWithAsyncAlways,
			service(defaultNamespace, testingAlwaysAsyncName),
		}}, {
		Name: "create new ingress with async annotation and invalid mode value",
		Key:  "default/testing",
		Objects: []runtime.Object{
			ingInvalidModeAnnotation,
		},
		WantErr: true,
		WantEvents: []string{
			Eventf(corev1.EventTypeWarning, "InternalError", "Invalid value for key async.knative.dev/mode: "),
		}},
	}

	table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler {
		r := &Reconciler{
			netclient:     fakenetworkingclient.Get(ctx),
			ingressLister: listers.GetIngressLister(),
			serviceLister: listers.GetK8sServiceLister(),
			kubeclient:    fakekubeclient.Get(ctx),
		}
		return ingressreconciler.NewReconciler(ctx, logging.FromContext(ctx), fakenetworkingclient.Get(ctx),
			listers.GetIngressLister(), controller.GetEventRecorder(ctx), r, asyncIngressClassName, controller.Options{})
	}))
}

func TestIstioIngress(t *testing.T) {
	createdIng.Status.InitializeConditions()
	changedService := service(defaultNamespace, testingName)
	changedService.Spec.ExternalName = "changed"
	defaultIngressClassName := os.Getenv("INGRESS_CLASS_NAME")
	table := TableTest{{
		Name: "create new ingress with istio",
		Key:  "default/testing",
		Objects: []runtime.Object{
			ingSometimesAsync,
		},
		Ctx: context.WithValue(context.Background(), "ingressClass", "istio.ingress.networking.knative.dev"),
		WantCreates: []runtime.Object{
			createdIngWithIstio,
			service(defaultNamespace, testingName),
		}},
	}
	// Restores the ingress class to the default after the kourier test
	// TODO refactor to inject this value in context
	os.Setenv("INGRESS_CLASS_NAME", defaultIngressClassName)

	table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler {
		os.Setenv("INGRESS_CLASS_NAME", "istio.ingress.networking.knative.dev")
		r := &Reconciler{
			netclient:     fakenetworkingclient.Get(ctx),
			ingressLister: listers.GetIngressLister(),
			serviceLister: listers.GetK8sServiceLister(),
			kubeclient:    fakekubeclient.Get(ctx),
		}
		return ingressreconciler.NewReconciler(ctx, logging.FromContext(ctx), fakenetworkingclient.Get(ctx),
			listers.GetIngressLister(), controller.GetEventRecorder(ctx), r, asyncIngressClassName, controller.Options{})
	}))
}

// Make sure we allow custom ingress with default LB domain
func TestUnknownLBIngress(t *testing.T) {
	createdIng.Status.InitializeConditions()
	changedService := service(defaultNamespace, testingName)
	changedService.Spec.ExternalName = "changed"
	defaultIngressClassName := os.Getenv("INGRESS_CLASS_NAME")
	table := TableTest{{
		Name: "create new unrecognized ingress",
		Key:  "default/testing",
		Objects: []runtime.Object{
			ingSometimesAsync,
		},
		Ctx: context.WithValue(context.Background(), "ingressClass", "fake.ingress.networking.knative.dev"),
		WantCreates: []runtime.Object{
			createdIng,
			service(defaultNamespace, testingName),
		}},
	}

	os.Setenv("INGRESS_CLASS_NAME", defaultIngressClassName)

	table.Test(t, MakeFactory(func(ctx context.Context, listers *Listers, cmw configmap.Watcher) controller.Reconciler {
		os.Setenv("INGRESS_CLASS_NAME", "fake.ingress.networking.knative.dev")
		r := &Reconciler{
			netclient:     fakenetworkingclient.Get(ctx),
			ingressLister: listers.GetIngressLister(),
			serviceLister: listers.GetK8sServiceLister(),
			kubeclient:    fakekubeclient.Get(ctx),
		}
		return ingressreconciler.NewReconciler(ctx, logging.FromContext(ctx), fakenetworkingclient.Get(ctx),
			listers.GetIngressLister(), controller.GetEventRecorder(ctx), r, asyncIngressClassName, controller.Options{})
	}))
}

type ingressCreationOption func(ing *v1alpha1.Ingress)

func ingress(namespace, name string, status v1alpha1.IngressStatus, opt ...ingressCreationOption) *v1alpha1.Ingress {
	ing := &netv1alpha1.Ingress{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name,
			Namespace: namespace,
		},
		Spec: netv1alpha1.IngressSpec{
			Rules: []netv1alpha1.IngressRule{{
				Hosts:      []string{exampleHost},
				Visibility: netv1alpha1.IngressVisibilityExternalIP,
				HTTP: &netv1alpha1.HTTPIngressRuleValue{
					Paths: []netv1alpha1.HTTPIngressPath{{
						Splits: []netv1alpha1.IngressBackendSplit{{
							Percent: 100,
							AppendHeaders: map[string]string{
								networkpkg.OriginalHostHeader: testHost,
							},
							IngressBackend: netv1alpha1.IngressBackend{
								ServiceName:      serviceName,
								ServiceNamespace: namespace,
								ServicePort:      intstr.FromInt(80),
							},
						}},
					}},
				},
			}},
		},
		Status: status,
	}
	for _, o := range opt {
		o(ing)
	}
	return ing
}

func withAnnotations(ans map[string]string) ingressCreationOption {
	return func(ing *v1alpha1.Ingress) {
		ing.Annotations = ans
	}
}

func ingressWithPaths(namespace, name string, status v1alpha1.IngressStatus, paths []netv1alpha1.HTTPIngressPath) *v1alpha1.Ingress {
	return &netv1alpha1.Ingress{
		ObjectMeta: metav1.ObjectMeta{
			Name:        name + newSuffix,
			Namespace:   namespace,
			Annotations: map[string]string{networking.IngressClassAnnotationKey: "kourier.ingress.networking.knative.dev"},
		},
		Spec: netv1alpha1.IngressSpec{
			Rules: []netv1alpha1.IngressRule{{
				Hosts:      []string{exampleHost},
				Visibility: netv1alpha1.IngressVisibilityExternalIP,
				HTTP: &netv1alpha1.HTTPIngressRuleValue{
					Paths: paths,
				},
			}},
		},
		Status: status,
	}
}

func ingressWithIstio(namespace, name string, status v1alpha1.IngressStatus, paths []netv1alpha1.HTTPIngressPath) *v1alpha1.Ingress {
	return &netv1alpha1.Ingress{
		ObjectMeta: metav1.ObjectMeta{
			Name:        name + newSuffix,
			Namespace:   namespace,
			Annotations: map[string]string{networking.IngressClassAnnotationKey: networkpkg.IstioIngressClassName},
		},
		Spec: netv1alpha1.IngressSpec{
			Rules: []netv1alpha1.IngressRule{{
				Hosts:      []string{exampleHost},
				Visibility: netv1alpha1.IngressVisibilityExternalIP,
				HTTP: &netv1alpha1.HTTPIngressRuleValue{
					Paths: paths,
				},
			}},
		},
		Status: status,
	}
}

func ingressWithUnknownLB(namespace, name string, status v1alpha1.IngressStatus, paths []netv1alpha1.HTTPIngressPath) *v1alpha1.Ingress {
	return &netv1alpha1.Ingress{
		ObjectMeta: metav1.ObjectMeta{
			Name:        name + newSuffix,
			Namespace:   namespace,
			Annotations: map[string]string{networking.IngressClassAnnotationKey: "fake.ingress.networking.knative.dev"},
		},
		Spec: netv1alpha1.IngressSpec{
			Rules: []netv1alpha1.IngressRule{{
				Hosts:      []string{exampleHost},
				Visibility: netv1alpha1.IngressVisibilityExternalIP,
				HTTP: &netv1alpha1.HTTPIngressRuleValue{
					Paths: paths,
				},
			}},
		},
		Status: status,
	}
}

func service(namespace, name string) *corev1.Service {
	selector := make(map[string]string)
	selector["app"] = producerServiceName
	svc := &corev1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      name + asyncSuffix,
			Namespace: namespace,
		},
		Spec: corev1.ServiceSpec{
			Type:         "ExternalName",
			ExternalName: network.GetServiceHostname(producerServiceName, knativeTesting),
			Ports: []corev1.ServicePort{{
				Name:       networking.ServicePortName(networking.ProtocolHTTP1),
				Protocol:   corev1.ProtocolTCP,
				Port:       int32(networking.ServicePort(networking.ProtocolHTTP1)),
				TargetPort: intstr.FromInt(80),
			}},
			Selector:        selector,
			SessionAffinity: "None",
		},
	}
	return svc
}


text:
layout: post
comments: true
title: "Revision control source text lines"
---

When writing a document in a formatted syntax (e.g. Latex or Markdown) with revision control (e.g. git or svn), it is better to avoid (1) artificial line breaks in the middle of the sentences and (2) putting an entire paragraph in one line.

I usually keep one full sentence at one line, such as:

A variety of applications such as virtual reality and immersive cinema require high image quality, low rendering latency, and consistent depth cues.

4D light field displays support focus accommodation, but are more costly to render than 2D images, resulting in higher latency.

The human visual system can resolve higher spatial frequencies in the fovea than in the periphery.

This property has been harnessed by recent 2D foveated rendering methods to reduce computation cost while maintaining perceptual quality.

Inspired by this, we present foveated 4D light fields by investigating their effects on 3D depth perception.

Based on our psychophysical experiments and theoretical analysis on visual and display bandwidths, we formulate a content-adaptive importance model in the 4D ray space.

We verify our method by building a prototype light field display that can render only 16%-30% rays without compromising perceptual quality.

If I violate (1) above and break lines in the middle of the sentences, it could confuse automatic spell checkers such as MS Word:

A variety of applications such as virtual reality

and immersive cinema require high image quality, low

rendering latency, and consistent depth cues. 4D light

field displays support focus accommodation, but are more

costly to render than 2D images, resulting in higher

latency. The human visual system can resolve higher spatial

frequencies in the fovea than in the periphery. This property

has been harnessed by recent 2D foveated rendering methods

to reduce computation cost while maintaining perceptual

quality. Inspired by this, we present foveated 4D light

fields by investigating their effects on 3D depth perception.

Based on our psychophysical experiments and theoretical

analysis on visual and display bandwidths, we formulate a

content-adaptive importance model in the 4D ray space. We

verify our method by building a prototype light field

display that can render only 16%-30% rays without compromising

perceptual quality.

If I violate (2) above and put all sentences in one line, it could confuse line-based revision tools such as git or svn.
For example, if we just change one word, git/svn will think you change the entire paragraph, making it very hard to see the actual difference:

A variety of applications such as virtual reality and immersive cinema require high image quality, low rendering latency, and consistent depth cues. 4D light field displays support focus accommodation, but are more costly to render than 2D images, resulting in higher latency. The human visual system can resolve higher spatial frequencies in the fovea than in the periphery. This property has been harnessed by recent 2D foveated rendering methods to reduce computation cost while maintaining perceptual quality. Inspired by this, we present foveated 4D light fields by investigating their effects on 3D depth perception. Based on our psychophysical experiments and theoretical analysis on visual and display bandwidths, we formulate a content-adaptive importance model in the 4D ray space. We verify our method by building a prototype light field display that can render only 16%-30% rays without compromising perceptual quality.


text:
{{login.loginError}}

Kirjautuminen

    <form id="login_form" ng-submit="login.login()">

            <input required id="email_block" type="email" name="email" placeholder="Sähköpostiosoite" ng-model="login.user.email">

Sähköposti tai salasana väärin #

            <input required id="password_block" name="password" type="{{login.input.type}}" placeholder="Salasana" ng-model="login.user.password">

Sähköposti tai salasana väärin #

                            Salasanan näyttö

            Unohditko salasanan?

            <button type="submit" class="submit_button">Kirjaudu</button>

    </form>


text:
/****************************************************************************/
/**
 *  @file   Directory.h
 *  @author Naohisa Sakamoto
 */
/****************************************************************************/
#pragma once
#include <string>
#include <iostream>
#include <algorithm>
#include <functional>
#include <kvs/FileList>
#include <kvs/Deprecated>

namespace kvs
{

/*==========================================================================*/
/**
 *  Directory class
 */
/*==========================================================================*/
class Directory
{
public:
    static std::string Separator();
    static std::string Absolute( const std::string& directory_path );
    static bool Exists( const std::string& directory_path );
    static bool Make( const std::string& directory_path );
    static bool Remove( const std::string& directory_path );
    static bool Change( const std::string& directory_path );
    static std::string RootPath();
    static std::string HomePath();
    static std::string TempPath();
    static std::string CurrentPath();
    static Directory Root() { return Directory( RootPath() ); }
    static Directory Home() { return Directory( HomePath() ); }
    static Directory Temp() { return Directory( TempPath() ); }
    static Directory Current() { return Directory( CurrentPath() ); }

private:
    std::string m_path = ""; ///< directory path (ex. "/tmp/abc/")
    std::string m_name = ""; ///< directory name (ex. "abc")

public:
    Directory() = default;
    explicit Directory( const std::string& path ) { this->parse( path ); }
    virtual ~Directory() = default;

    std::string path( bool absolute = false ) const;
    std::string name() const { return m_name; }
    kvs::FileList fileList( const bool sort = true ) const;
    bool isDirectory() const { return this->exists(); }
    bool exists() const { return Exists( m_path ); }
    bool parse( const std::string& direcotry_path );

public:
    KVS_DEPRECATED( bool isExisted() const ) { return this->exists(); }
    KVS_DEPRECATED( std::string directoryPath( bool abs = false ) const ) { return this->path( abs ); }
    KVS_DEPRECATED( std::string directoryName() const ) { return this->name(); }
};

} // end of namespace kvs


text:
<?php
namespace Czim\JsonApi\Test;

use Czim\JsonApi\Providers\JsonApiServiceProvider;
use Illuminate\Foundation\Application;

abstract class TestCase extends \Orchestra\Testbench\TestCase
{
    /**
     * Define environment setup.
     *
     * @param Application $app
     */
    protected function getEnvironmentSetUp($app): void
    {
        $app->register(JsonApiServiceProvider::class);

        $app->singleton(
            \Illuminate\Contracts\Debug\ExceptionHandler::class,
            \Czim\JsonApi\Test\Helpers\Exceptions\Handler::class
        );

        // Setup default database to use sqlite :memory:
        $app['config']->set('database.default', 'testbench');
        $app['config']->set('database.connections.testbench', [
            'driver'   => 'sqlite',
            'database' => ':memory:',
            'prefix'   => '',
        ]);
    }
}


text:
import hashlib
import hmac
from time import time

from ._compat import to_bytes, to_unicode

def eval_url(url):
    if callable(url):
        url = url()
    return url

def test_hasher(hasher):
    hasher.encrypt('test', rounds=hasher.min_rounds)

def to36(number):
    assert int(number) >= 0, 'Must be a positive integer'
    alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    base36 = ''
    while number:
        number, i = divmod(number, 36)
        base36 = alphabet[i] + base36

    return base36 or alphabet[0]

def from36(snumber):
    snumber = snumber.upper()
    return int(snumber, 36)

def get_hash_extract(hash):
    if not hash:
        return u''
    half = hash.rsplit('$', 1)[0]
    return half[-10:]

def get_uhmac(user, secret):
    """Make an unique identifier for the user (stored in the session),
    so it can stay logged between requests.

    By hashing a snippet of the current password hash salt, it makes possible
    to automatically logout from all other devices just by changing
    (or refreshing) the password.
    """
    secret = to_bytes(secret)
    key = '|'.join([
        hashlib.sha1(secret).hexdigest(),
        str(user.id),
        get_hash_extract(user.password),
    ])
    key = key.encode('utf8', 'ignore')
    mac = hmac.new(key, msg=None, digestmod=hashlib.sha512)
    mac = mac.hexdigest()[:50]
    uhmac = '{0}${1}'.format(user.id, mac)
    return uhmac

def get_token(user, secret, timestamp=None):
    """Make a timestamped one-time-use token that can be used to
    identifying the user.

    By hashing the `last_sign_in` attribute and a snippet of the current
    password hash salt, it produces a token that will be invalidated as soon
    as the user log in again or the is changed.

    A hash of the user ID is used, so the HMAC part of the token is always
    unique for each user.

    It also hash a secret key, so without access to the source code,
    fake tokens cannot be generated even if the database is compromised.
    """
    timestamp = int(timestamp or time())
    secret = to_bytes(secret)
    key = '|'.join([
        hashlib.sha1(secret).hexdigest(),
        str(user.id),
        get_hash_extract(user.password),
        str(getattr(user, 'last_sign_in', 0)),
        str(timestamp),
    ])
    key = key.encode('utf8', 'ignore')
    mac = hmac.new(key, msg=None, digestmod=hashlib.sha512)
    mac = mac.hexdigest()[:50]
    token = '{0}${1}${2}'.format(user.id, to36(timestamp), mac)
    return token

def split_uhmac(uhmac):
    uid, mac = uhmac.split('$', 1)
    return uid

def split_token(token):
    uid, t36, mac = token.split('$', 2)
    return from36(t36), uid

class LazyUser(object):
    """Acts as a proxy for the current user.  Forwards all operations to
    the proxied user.  The only operations not supported for forwarding
    are right handed operands and any kind of assignment.
    """
    __slots__ = ('__auth', '__storage', '__dict__')

    def __init__(self, auth, storage, user_name='user'):
        object.__setattr__(self, '_LazyUser__auth', auth)
        object.__setattr__(self, '_LazyUser__storage', storage)
        object.__setattr__(self, '_LazyUser__user_name', user_name)
        setattr(storage, user_name, self)

    def __get_user(self):
        """Return the real user object.
        """
        storage = object.__getattribute__(self, '_LazyUser__storage')
        user = getattr(self.__auth, 'get_user')()
        setattr(storage, self.__user_name, user)
        return user

    @property
    def __dict__(self):
        return self.__get_user().__dict__

    @property
    def __doc__(self):
        return self.__get_user().__doc__

    def __repr__(self):
        return repr(self.__get_user())

    def __bool__(self):
        user = self.__get_user()
        return user is not None

    __nonzero__ = __bool__

    def __str__(self):
        return str(self.__get_user())

    def __unicode__(self):
        return to_unicode(self.__get_user())

    def __dir__(self):
        return dir(self.__get_user())

    def __getattr__(self, name):
        return getattr(self.__get_user(), name)

    def __setattr__(self, name, value):
        setattr(self.__get_user(), name, value)

    def __delattr__(self, name):
        delattr(self.__get_user(), name)

    def __hash__(self):
        return hash(self.__get_user())

    def __call__(self, *args, **kwargs):
        return self.__get_user()(*args, **kwargs)

    def __eq__(self, other):
        return self.__get_user() == other

    def __ne__(self, other):
        return self.__get_user() != other

    def __setitem__(self, key, value):
        self.__get_user()[key] = value

    def __delitem__(self, key):
        del self.__get_user()[key]

    def __lt__(self, other):
        return self.__get_user() < other

    def __le__(self, other):
        return self.__get_user() <= other

    def __gt__(self, other):
        return self.__get_user() > other

    def __ge__(self, other):
        return self.__get_user() >= other

    def __getitem__(self, i):
        return self.__get_user()[i]

    def __iter__(self):
        return iter(self.__get_user())

    def __contains__(self, i):
        return i in self.__get_user()

    def __add__(self, other):
        return self.__get_user() + other

    def __sub__(self, other):
        return self.__get_user() - other

    def __mul__(self, other):
        return self.__get_user() * other

    def __floordiv__(self, other):
        return self.__get_user() // other

    def __mod__(self, other):
        return self.__get_user() % other

    def __divmod__(self, other):
        return self.__get_user().__divmod__(other)

    def __pow__(self, other):
        return self.__get_user() ** other

    def __lshift__(self, other):
        return self.__get_user() << other

    def __rshift__(self, other):
        return self.__get_user() >> other

    def __and__(self, other):
        return self.__get_user() & other

    def __xor__(self, other):
        return self.__get_user() ^ other

    def __or__(self, other):
        return self.__get_user() | other

    def __div__(self, other):
        return self.__get_user().__div__(other)

    def __truediv__(self, other):
        return self.__get_user().__truediv__(other)

    def __neg__(self):
        return -(self.__get_user())

    def __pos__(self):
        return +(self.__get_user())

    def __abs__(self):
        return abs(self.__get_user())

    def __len__(self):
        return len(self.__get_user())

    def __invert__(self):
        return ~(self.__get_user())

    def __complex__(self):
        return complex(self.__get_user())

    def __int__(self):
        return int(self.__get_user())

    def __float__(self):
        return float(self.__get_user())

    def __enter__(self):
        return self.__get_user().__enter__()

    def __exit__(self, *args, **kwargs):
        return self.__get_user().__exit__(*args, **kwargs)


text:
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;

namespace System.Net.Sockets
{
    // The System.Net.Sockets.TcpClient class provide TCP services at a higher level
    // of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
    // is used to create a Client connection to a remote host.
    public class TcpClient : IDisposable
    {
        private AddressFamily _family;
        private Socket _clientSocket;
        private NetworkStream _dataStream;
        private bool _cleanedUp;
        private bool _active;

        // Initializes a new instance of the System.Net.Sockets.TcpClient class.
        public TcpClient() : this(AddressFamily.InterNetwork)
        {
        }

        // Initializes a new instance of the System.Net.Sockets.TcpClient class.
        public TcpClient(AddressFamily family)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, family);

            // Validate parameter
            if (family != AddressFamily.InterNetwork &&
                family != AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family));
            }

            _family = family;
            InitializeClientSocket();

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Initializes a new instance of the System.Net.Sockets.TcpClient class with the specified end point.
        public TcpClient(IPEndPoint localEP)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, localEP);

            if (localEP == null)
            {
                throw new ArgumentNullException(nameof(localEP));
            }

            _family = localEP.AddressFamily; // set before calling CreateSocket
            InitializeClientSocket();
            _clientSocket.Bind(localEP);

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Initializes a new instance of the System.Net.Sockets.TcpClient class and connects to the specified port on
        // the specified host.
        public TcpClient(string hostname, int port)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, hostname);

            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            try
            {
                Connect(hostname, port);
            }
            catch
            {
                _clientSocket?.Close();
                throw;
            }

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Used by TcpListener.Accept().
        internal TcpClient(Socket acceptedSocket)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, acceptedSocket);

            _clientSocket = acceptedSocket;
            _active = true;

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Used by the class to indicate that a connection has been made.
        protected bool Active
        {
            get { return _active; }
            set { _active = value; }
        }

        public int Available => _clientSocket?.Available ?? 0;

        // Used by the class to provide the underlying network socket.
        public Socket Client
        {
            get { return _clientSocket; }
            set { _clientSocket = value; }
        }

        public bool Connected => _clientSocket?.Connected ?? false;

        public bool ExclusiveAddressUse
        {
            get { return _clientSocket?.ExclusiveAddressUse ?? false; }
            set
            {
                if (_clientSocket != null)
                {
                    _clientSocket.ExclusiveAddressUse = value;
                }
            }
        }

        // Connects the Client to the specified port on the specified host.
        public void Connect(string hostname, int port)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, hostname);

            if (_cleanedUp)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            // Check for already connected and throw here. This check
            // is not required in the other connect methods as they
            // will throw from WinSock. Here, the situation is more
            // complex since we have to resolve a hostname so it's
            // easier to simply block the request up front.
            if (_active)
            {
                throw new SocketException((int)SocketError.IsConnected);
            }

            // IPv6: We need to process each of the addresses returned from
            //       DNS when trying to connect. Use of AddressList[0] is
            //       bad form.
            IPAddress[] addresses = Dns.GetHostAddresses(hostname);
            ExceptionDispatchInfo lastex = null;

            try
            {
                foreach (IPAddress address in addresses)
                {
                    Socket tmpSocket = null;
                    try
                    {
                        if (_clientSocket == null)
                        {
                            // We came via the <hostname,port> constructor. Set the address family appropriately,
                            // create the socket and try to connect.
                            Debug.Assert(address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6);
                            if ((address.AddressFamily == AddressFamily.InterNetwork && Socket.OSSupportsIPv4) || Socket.OSSupportsIPv6)
                            {
                                tmpSocket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                                tmpSocket.Connect(address, port);
                                _clientSocket = tmpSocket;
                                tmpSocket = null;
                            }

                            _family = address.AddressFamily;
                            _active = true;
                            break;
                        }
                        else if (address.AddressFamily == _family)
                        {
                            // Only use addresses with a matching family
                            Connect(new IPEndPoint(address, port));
                            _active = true;
                            break;
                        }
                    }
                    catch (Exception ex) when (!(ex is OutOfMemoryException))
                    {
                        if (tmpSocket != null)
                        {
                            tmpSocket.Dispose();
                            tmpSocket = null;
                        }
                        lastex = ExceptionDispatchInfo.Capture(ex);
                    }
                }
            }
            finally
            {
                if (!_active)
                {
                    // The connect failed - rethrow the last error we had
                    lastex?.Throw();
                    throw new SocketException((int)SocketError.NotConnected);
                }
            }

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Connects the Client to the specified port on the specified host.
        public void Connect(IPAddress address, int port)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);

            if (_cleanedUp)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }
            if (!TcpValidationHelpers.ValidatePortNumber(port))
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            IPEndPoint remoteEP = new IPEndPoint(address, port);
            Connect(remoteEP);

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Connect the Client to the specified end point.
        public void Connect(IPEndPoint remoteEP)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, remoteEP);

            if (_cleanedUp)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            if (remoteEP == null)
            {
                throw new ArgumentNullException(nameof(remoteEP));
            }

            Client.Connect(remoteEP);
            _active = true;

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        public void Connect(IPAddress[] ipAddresses, int port)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, ipAddresses);

            Client.Connect(ipAddresses, port);
            _active = true;

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        public Task ConnectAsync(IPAddress address, int port) =>
            Task.Factory.FromAsync(
                (targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
                asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
                address, port, state: this);

        public Task ConnectAsync(string host, int port) =>
            Task.Factory.FromAsync(
                (targetHost, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetHost, targetPort, callback, state),
                asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
                host, port, state: this);

        public Task ConnectAsync(IPAddress[] addresses, int port) =>
            Task.Factory.FromAsync(
                (targetAddresses, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddresses, targetPort, callback, state),
                asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
                addresses, port, state: this);

        public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, address);

            IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
            return result;
        }

        public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, (string)host);

            IAsyncResult result = Client.BeginConnect(host, port, requestCallback, state);

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
            return result;
        }

        public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, addresses);

            IAsyncResult result = Client.BeginConnect(addresses, port, requestCallback, state);

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
            return result;
        }

        public void EndConnect(IAsyncResult asyncResult)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult);

            Socket s = Client;
            if (s == null)
            {
                // Dispose nulls out the client socket field.
                throw new ObjectDisposedException(GetType().Name);
            }

            s.EndConnect(asyncResult);
            _active = true;

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        // Returns the stream used to read and write data to the remote host.
        public NetworkStream GetStream()
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);

            if (_cleanedUp)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }
            if (!Connected)
            {
                throw new InvalidOperationException(SR.net_notconnected);
            }

            if (_dataStream == null)
            {
                _dataStream = new NetworkStream(Client, true);
            }

            if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _dataStream);
            return _dataStream;
        }

        public void Close() => Dispose();

        // Disposes the Tcp connection.
        protected virtual void Dispose(bool disposing)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);

            if (_cleanedUp)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
                return;
            }

            if (disposing)
            {
                IDisposable dataStream = _dataStream;
                if (dataStream != null)
                {
                    dataStream.Dispose();
                }
                else
                {
                    // If the NetworkStream wasn't created, the Socket might
                    // still be there and needs to be closed. In the case in which
                    // we are bound to a local IPEndPoint this will remove the
                    // binding and free up the IPEndPoint for later uses.
                    Socket chkClientSocket = _clientSocket;
                    if (chkClientSocket != null)
                    {
                        try
                        {
                            chkClientSocket.InternalShutdown(SocketShutdown.Both);
                        }
                        finally
                        {
                            chkClientSocket.Close();
                            _clientSocket = null;
                        }
                    }
                }

                GC.SuppressFinalize(this);
            }

            _cleanedUp = true;
            if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
        }

        public void Dispose() => Dispose(true);

        ~TcpClient()
        {
#if DEBUG
            DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
            {
#endif
                Dispose(false);
#if DEBUG
            }
#endif
        }

        // Gets or sets the size of the receive buffer in bytes.
        public int ReceiveBufferSize
        {
            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); }
            set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); }
        }

        // Gets or sets the size of the send buffer in bytes.
        public int SendBufferSize
        {
            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer); }
            set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value); }
        }

        // Gets or sets the receive time out value of the connection in milliseconds.
        public int ReceiveTimeout
        {
            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); }
            set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); }
        }

        // Gets or sets the send time out value of the connection in milliseconds.
        public int SendTimeout
        {
            get { return (int)Client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout); }
            set { Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); }
        }

        // Gets or sets the value of the connection's linger option.
        public LingerOption LingerState
        {
            get { return Client.LingerState; }
            set { Client.LingerState = value; }
        }

        // Enables or disables delay when send or receive buffers are full.
        public bool NoDelay
        {
            get { return Client.NoDelay; }
            set { Client.NoDelay = value; }
        }

        private void InitializeClientSocket()
        {
            Debug.Assert(_clientSocket == null);
            _clientSocket = new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
        }
    }
}