text:
namespace {

static const int kBindRetries = 10;
static const int kPortStart = 1024;
static const int kPortEnd = 65535;

}  // namespace net

namespace net {

void UDPSocketWin::ReadDelegate::OnObjectSignaled(HANDLE object) {
  DCHECK_EQ(object, socket_->read_overlapped_.hEvent);
  socket_->DidCompleteRead();
}

void UDPSocketWin::WriteDelegate::OnObjectSignaled(HANDLE object) {
  DCHECK_EQ(object, socket_->write_overlapped_.hEvent);
  socket_->DidCompleteWrite();
}

UDPSocketWin::UDPSocketWin(DatagramSocket::BindType bind_type,
                           const RandIntCallback& rand_int_cb,
                           net::NetLog* net_log,
                           const net::NetLog::Source& source)
    : socket_(INVALID_SOCKET),
      socket_options_(0),
      bind_type_(bind_type),
      rand_int_cb_(rand_int_cb),
      ALLOW_THIS_IN_INITIALIZER_LIST(read_delegate_(this)),
      ALLOW_THIS_IN_INITIALIZER_LIST(write_delegate_(this)),
      recv_from_address_(NULL),
      net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_UDP_SOCKET)) {
  EnsureWinsockInit();
  net_log_.BeginEvent(NetLog::TYPE_SOCKET_ALIVE,
                      source.ToEventParametersCallback());
  memset(&read_overlapped_, 0, sizeof(read_overlapped_));
  read_overlapped_.hEvent = WSACreateEvent();
  memset(&write_overlapped_, 0, sizeof(write_overlapped_));
  write_overlapped_.hEvent = WSACreateEvent();
  if (bind_type == DatagramSocket::RANDOM_BIND)
    DCHECK(!rand_int_cb.is_null());
}

UDPSocketWin::~UDPSocketWin() {
  Close();
  net_log_.EndEvent(NetLog::TYPE_SOCKET_ALIVE);
}

void UDPSocketWin::Close() {
  DCHECK(CalledOnValidThread());

  if (!is_connected())
    return;

  // Zero out any pending read/write callback state.
  read_callback_.Reset();
  recv_from_address_ = NULL;
  write_callback_.Reset();

  read_watcher_.StopWatching();
  write_watcher_.StopWatching();

  closesocket(socket_);
  socket_ = INVALID_SOCKET;
}

int UDPSocketWin::GetPeerAddress(IPEndPoint* address) const {
  DCHECK(CalledOnValidThread());
  DCHECK(address);
  if (!is_connected())
    return ERR_SOCKET_NOT_CONNECTED;

  // TODO(szym): Simplify. http://crbug.com/126152
  if (!remote_address_.get()) {
    SockaddrStorage storage;
    if (getpeername(socket_, storage.addr, &storage.addr_len))
      return MapSystemError(WSAGetLastError());
    scoped_ptr<IPEndPoint> address(new IPEndPoint());
    if (!address->FromSockAddr(storage.addr, storage.addr_len))
      return ERR_FAILED;
    remote_address_.reset(address.release());
  }

  *address = *remote_address_;
  return OK;
}

int UDPSocketWin::GetLocalAddress(IPEndPoint* address) const {
  DCHECK(CalledOnValidThread());
  DCHECK(address);
  if (!is_connected())
    return ERR_SOCKET_NOT_CONNECTED;

  // TODO(szym): Simplify. http://crbug.com/126152
  if (!local_address_.get()) {
    SockaddrStorage storage;
    if (getsockname(socket_, storage.addr, &storage.addr_len))
      return MapSystemError(WSAGetLastError());
    scoped_ptr<IPEndPoint> address(new IPEndPoint());
    if (!address->FromSockAddr(storage.addr, storage.addr_len))
      return ERR_FAILED;
    local_address_.reset(address.release());
  }

  *address = *local_address_;
  return OK;
}

int UDPSocketWin::Read(IOBuffer* buf,
                       int buf_len,
                       const CompletionCallback& callback) {
  return RecvFrom(buf, buf_len, NULL, callback);
}

int UDPSocketWin::RecvFrom(IOBuffer* buf,
                           int buf_len,
                           IPEndPoint* address,
                           const CompletionCallback& callback) {
  DCHECK(CalledOnValidThread());
  DCHECK_NE(INVALID_SOCKET, socket_);
  DCHECK(read_callback_.is_null());
  DCHECK(!recv_from_address_);
  DCHECK(!callback.is_null());  // Synchronous operation not supported.
  DCHECK_GT(buf_len, 0);

  int nread = InternalRecvFrom(buf, buf_len, address);
  if (nread != ERR_IO_PENDING)
    return nread;

  read_iobuffer_ = buf;
  read_callback_ = callback;
  recv_from_address_ = address;
  return ERR_IO_PENDING;
}

int UDPSocketWin::Write(IOBuffer* buf,
                        int buf_len,
                        const CompletionCallback& callback) {
  return SendToOrWrite(buf, buf_len, NULL, callback);
}

int UDPSocketWin::SendTo(IOBuffer* buf,
                         int buf_len,
                         const IPEndPoint& address,
                         const CompletionCallback& callback) {
  return SendToOrWrite(buf, buf_len, &address, callback);
}

int UDPSocketWin::SendToOrWrite(IOBuffer* buf,
                                int buf_len,
                                const IPEndPoint* address,
                                const CompletionCallback& callback) {
  DCHECK(CalledOnValidThread());
  DCHECK_NE(INVALID_SOCKET, socket_);
  DCHECK(write_callback_.is_null());
  DCHECK(!callback.is_null());  // Synchronous operation not supported.
  DCHECK_GT(buf_len, 0);
  DCHECK(!send_to_address_.get());

  int nwrite = InternalSendTo(buf, buf_len, address);
  if (nwrite != ERR_IO_PENDING)
    return nwrite;

  if (address)
    send_to_address_.reset(new IPEndPoint(*address));
  write_iobuffer_ = buf;
  write_callback_ = callback;
  return ERR_IO_PENDING;
}

int UDPSocketWin::Connect(const IPEndPoint& address) {
  net_log_.BeginEvent(NetLog::TYPE_UDP_CONNECT,
                      CreateNetLogUDPConnectCallback(&address));
  int rv = InternalConnect(address);
  net_log_.EndEventWithNetErrorCode(NetLog::TYPE_UDP_CONNECT, rv);
  return rv;
}

int UDPSocketWin::InternalConnect(const IPEndPoint& address) {
  DCHECK(!is_connected());
  DCHECK(!remote_address_.get());
  int rv = CreateSocket(address);
  if (rv < 0)
    return rv;

  if (bind_type_ == DatagramSocket::RANDOM_BIND)
    rv = RandomBind(address);
  // else connect() does the DatagramSocket::DEFAULT_BIND

  if (rv < 0)
    return rv;

  SockaddrStorage storage;
  if (!address.ToSockAddr(storage.addr, &storage.addr_len))
    return ERR_FAILED;

  rv = connect(socket_, storage.addr, storage.addr_len);
  if (rv < 0)
    return MapSystemError(WSAGetLastError());

  remote_address_.reset(new IPEndPoint(address));
  return rv;
}

int UDPSocketWin::Bind(const IPEndPoint& address) {
  DCHECK(!is_connected());
  int rv = CreateSocket(address);
  if (rv < 0)
    return rv;
  rv = SetSocketOptions();
  if (rv < 0)
    return rv;
  rv = DoBind(address);
  if (rv < 0)
    return rv;
  local_address_.reset();
  return rv;
}

int UDPSocketWin::CreateSocket(const IPEndPoint& address) {
  socket_ = WSASocket(address.GetFamily(), SOCK_DGRAM, IPPROTO_UDP, NULL, 0,
                      WSA_FLAG_OVERLAPPED);
  if (socket_ == INVALID_SOCKET)
    return MapSystemError(WSAGetLastError());
  return OK;
}

bool UDPSocketWin::SetReceiveBufferSize(int32 size) {
  DCHECK(CalledOnValidThread());
  int rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF,
                      reinterpret_cast<const char*>(&size), sizeof(size));
  DCHECK(!rv) << "Could not set socket receive buffer size: " << errno;
  return rv == 0;
}

bool UDPSocketWin::SetSendBufferSize(int32 size) {
  DCHECK(CalledOnValidThread());
  int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF,
                      reinterpret_cast<const char*>(&size), sizeof(size));
  DCHECK(!rv) << "Could not set socket send buffer size: " << errno;
  return rv == 0;
}

void UDPSocketWin::AllowAddressReuse() {
  DCHECK(CalledOnValidThread());
  DCHECK(!is_connected());

  socket_options_ |= SOCKET_OPTION_REUSE_ADDRESS;
}

void UDPSocketWin::AllowBroadcast() {
  DCHECK(CalledOnValidThread());
  DCHECK(!is_connected());

  socket_options_ |= SOCKET_OPTION_BROADCAST;
}

void UDPSocketWin::DoReadCallback(int rv) {
  DCHECK_NE(rv, ERR_IO_PENDING);
  DCHECK(!read_callback_.is_null());

  // since Run may result in Read being called, clear read_callback_ up front.
  CompletionCallback c = read_callback_;
  read_callback_.Reset();
  c.Run(rv);
}

void UDPSocketWin::DoWriteCallback(int rv) {
  DCHECK_NE(rv, ERR_IO_PENDING);
  DCHECK(!write_callback_.is_null());

  // since Run may result in Write being called, clear write_callback_ up front.
  CompletionCallback c = write_callback_;
  write_callback_.Reset();
  c.Run(rv);
}

void UDPSocketWin::DidCompleteRead() {
  DWORD num_bytes, flags;
  BOOL ok = WSAGetOverlappedResult(socket_, &read_overlapped_,
                                   &num_bytes, FALSE, &flags);
  WSAResetEvent(read_overlapped_.hEvent);
  int result = ok ? num_bytes : MapSystemError(WSAGetLastError());
  // Convert address.
  if (recv_from_address_ && result >= 0) {
    if (!ReceiveAddressToIPEndpoint(recv_from_address_))
      result = ERR_FAILED;
  }
  LogRead(result, read_iobuffer_->data());
  read_iobuffer_ = NULL;
  recv_from_address_ = NULL;
  DoReadCallback(result);
}

void UDPSocketWin::LogRead(int result, const char* bytes) const {
  if (result < 0) {
    net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_RECEIVE_ERROR, result);
    return;
  }

  if (net_log_.IsLoggingAllEvents()) {
    // Get address for logging, if |address| is NULL.
    IPEndPoint address;
    bool is_address_valid = ReceiveAddressToIPEndpoint(&address);
    net_log_.AddEvent(
        NetLog::TYPE_UDP_BYTES_RECEIVED,
        CreateNetLogUDPDataTranferCallback(
            result, bytes,
            is_address_valid ? &address : NULL));
  }

  base::StatsCounter read_bytes("udp.read_bytes");
  read_bytes.Add(result);
}

void UDPSocketWin::DidCompleteWrite() {
  DWORD num_bytes, flags;
  BOOL ok = WSAGetOverlappedResult(socket_, &write_overlapped_,
                                   &num_bytes, FALSE, &flags);
  WSAResetEvent(write_overlapped_.hEvent);
  int result = ok ? num_bytes : MapSystemError(WSAGetLastError());
  LogWrite(result, write_iobuffer_->data(), send_to_address_.get());

  send_to_address_.reset();
  write_iobuffer_ = NULL;
  DoWriteCallback(result);
}

void UDPSocketWin::LogWrite(int result,
                            const char* bytes,
                            const IPEndPoint* address) const {
  if (result < 0) {
    net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_SEND_ERROR, result);
    return;
  }

  if (net_log_.IsLoggingAllEvents()) {
    net_log_.AddEvent(
        NetLog::TYPE_UDP_BYTES_SENT,
        CreateNetLogUDPDataTranferCallback(result, bytes, address));
  }

  base::StatsCounter write_bytes("udp.write_bytes");
  write_bytes.Add(result);
}

int UDPSocketWin::InternalRecvFrom(IOBuffer* buf, int buf_len,
                                   IPEndPoint* address) {
  recv_addr_len_ = sizeof(recv_addr_storage_);
  struct sockaddr* addr =
      reinterpret_cast<struct sockaddr*>(&recv_addr_storage_);

  WSABUF read_buffer;
  read_buffer.buf = buf->data();
  read_buffer.len = buf_len;

  DWORD flags = 0;
  DWORD num;
  AssertEventNotSignaled(read_overlapped_.hEvent);
  int rv = WSARecvFrom(socket_, &read_buffer, 1, &num, &flags, addr,
                       &recv_addr_len_, &read_overlapped_, NULL);
  if (rv == 0) {
    if (ResetEventIfSignaled(read_overlapped_.hEvent)) {
      int result = num;
      // Convert address.
      if (address && result >= 0) {
        if (!ReceiveAddressToIPEndpoint(address))
          result = ERR_FAILED;
      }
      LogRead(result, buf->data());
      return result;
    }
  } else {
    int os_error = WSAGetLastError();
    if (os_error != WSA_IO_PENDING) {
      int result = MapSystemError(os_error);
      LogRead(result, NULL);
      return result;
    }
  }
  read_watcher_.StartWatching(read_overlapped_.hEvent, &read_delegate_);
  return ERR_IO_PENDING;
}

int UDPSocketWin::InternalSendTo(IOBuffer* buf, int buf_len,
                                 const IPEndPoint* address) {
  SockaddrStorage storage;
  struct sockaddr* addr = storage.addr;
  // Convert address.
  if (!address) {
    addr = NULL;
    storage.addr_len = 0;
  } else {
    if (!address->ToSockAddr(addr, &storage.addr_len)) {
      int result = ERR_FAILED;
      LogWrite(result, NULL, NULL);
      return result;
    }
  }

  WSABUF write_buffer;
  write_buffer.buf = buf->data();
  write_buffer.len = buf_len;

  DWORD flags = 0;
  DWORD num;
  AssertEventNotSignaled(write_overlapped_.hEvent);
  int rv = WSASendTo(socket_, &write_buffer, 1, &num, flags,
                     addr, storage.addr_len, &write_overlapped_, NULL);
  if (rv == 0) {
    if (ResetEventIfSignaled(write_overlapped_.hEvent)) {
      int result = num;
      LogWrite(result, buf->data(), address);
      return result;
    }
  } else {
    int os_error = WSAGetLastError();
    if (os_error != WSA_IO_PENDING) {
      int result = MapSystemError(os_error);
      LogWrite(result, NULL, NULL);
      return result;
    }
  }

  write_watcher_.StartWatching(write_overlapped_.hEvent, &write_delegate_);
  return ERR_IO_PENDING;
}

int UDPSocketWin::SetSocketOptions() {
  BOOL true_value = 1;
  if (socket_options_ & SOCKET_OPTION_REUSE_ADDRESS) {
    int rv = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
                        reinterpret_cast<const char*>(&true_value),
                        sizeof(true_value));
    if (rv < 0)
      return MapSystemError(errno);
  }
  if (socket_options_ & SOCKET_OPTION_BROADCAST) {
    int rv = setsockopt(socket_, SOL_SOCKET, SO_BROADCAST,
                        reinterpret_cast<const char*>(&true_value),
                        sizeof(true_value));
    if (rv < 0)
      return MapSystemError(errno);
  }
  return OK;
}

int UDPSocketWin::DoBind(const IPEndPoint& address) {
  SockaddrStorage storage;
  if (!address.ToSockAddr(storage.addr, &storage.addr_len))
    return ERR_UNEXPECTED;
  int rv = bind(socket_, storage.addr, storage.addr_len);
  return rv < 0 ? MapSystemError(WSAGetLastError()) : rv;
}

int UDPSocketWin::RandomBind(const IPEndPoint& address) {
  DCHECK(bind_type_ == DatagramSocket::RANDOM_BIND && !rand_int_cb_.is_null());

  // Construct IPAddressNumber of appropriate size (IPv4 or IPv6) of 0s.
  IPAddressNumber ip(address.address().size());

  for (int i = 0; i < kBindRetries; ++i) {
    int rv = DoBind(IPEndPoint(ip, rand_int_cb_.Run(kPortStart, kPortEnd)));
    if (rv == OK || rv != ERR_ADDRESS_IN_USE)
      return rv;
  }
  return DoBind(IPEndPoint(ip, 0));
}

bool UDPSocketWin::ReceiveAddressToIPEndpoint(IPEndPoint* address) const {
  const struct sockaddr* addr =
      reinterpret_cast<const struct sockaddr*>(&recv_addr_storage_);
  return address->FromSockAddr(addr, recv_addr_len_);
}

}  // namespace net


text:
@implementation HKHealthStore (ReactiveCocoa)

- (RACSignal *)rac_queryWithSampleType:(HKSampleType *)sampleType
                         predicate:(NSPredicate *)predicate
                             limit:(NSUInteger)limit
                   sortDescriptors:(NSArray *)sortDescriptors {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sampleType
                                                               predicate:predicate
                                                                   limit:limit
                                                         sortDescriptors:sortDescriptors
                                                          resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
            if (error) {
              [subscriber sendError:error];
            }
            for (id result in results) {
                [subscriber sendNext:result];
            }
            [subscriber sendCompleted];
        }];
        [self executeQuery:query];

        return (RACDisposable *)nil;
    }];
}

- (RACSignal *)rac_deleteObject:(HKObject *)object {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [self deleteObject:object withCompletion:^(BOOL success, NSError *error) {
            if (success) {
                [subscriber sendCompleted];
            } else {
                [subscriber sendError:error];
            }
        }];
        return (RACDisposable *)nil;
    }];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package me.yorkart.net.common.rpc;

import com.sun.xml.internal.ws.encoding.soap.SerializationException;
import org.apache.thrift.TBase;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

/**
 * Created by Yorkart on 16/9/8.
 * @link http://www.programcreek.com/java-api-examples/index.php?source_dir=amor-master/Test/de.modelrepository.test/res/in/T0004/voldemort/src/java/voldemort/serialization/thrift/ThriftSerializer.java
 */
public class ThriftSerializer<T extends TBase> implements Serializer<T> {

    private static final String ONLY_JAVA_CLIENTS_SUPPORTED = "Only Java clients are supported currently, so the format of the schema-info should be: <schema-info>java=com.xyz.Foo,protocol=binary</schema-info> where com.xyz.Foo is the fully qualified name of the message.";

    /**
     * Supported Thrift Protocols
     */
    static enum ThriftProtocol {
        BINARY,
        JSON,
        SIMPLE_JSON,
        UNKNOWN
    }

    private Class<T> messageClass;
    private ThriftProtocol protocol;

    public ThriftSerializer(Class<T> clazz) {
        this.messageClass = clazz;
        this.protocol = getThriftProtocol("binary");
    }

    @SuppressWarnings("unchecked")
    public ThriftSerializer(String schemaInfo) {
        String[] thriftInfo = parseSchemaInfo(schemaInfo);

        if(thriftInfo[1] == null || thriftInfo[1].length() == 0) {
            throw new IllegalArgumentException("Thrift protocol is missing from schema-info.");
        }
        this.protocol = getThriftProtocol(thriftInfo[1]);
        if(this.protocol == ThriftProtocol.UNKNOWN) {
            throw new IllegalArgumentException("Unknown Thrift protocol found in schema-info");
        }

        if(thriftInfo[0] == null || thriftInfo[0].length() == 0) {
            throw new IllegalArgumentException("Thrift generated class name is missing from schema-info.");
        }
        try {
            this.messageClass = (Class<T>) Class.forName(thriftInfo[0]);
            Object msgObj = messageClass.newInstance();
            if(!(msgObj instanceof TBase)) {
                throw new IllegalArgumentException(thriftInfo[0]
                        + " is not a subtype of com.facebook.thrift.TBase");
            }
        } catch(ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        } catch(SecurityException e) {
            throw new IllegalArgumentException(e);
        } catch(InstantiationException e) {
            throw new IllegalArgumentException(e);
        } catch(IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public byte[] toBytes(T object) {
        MemoryBuffer buffer = new MemoryBuffer();
        TProtocol protocol = createThriftProtocol(buffer);
        try {
            object.write(protocol);
        } catch(TException e) {
            throw new SerializationException(e);
        }
        return buffer.toByteArray();
    }

    public T toObject(byte[] bytes) {
        MemoryBuffer buffer = new MemoryBuffer();
        try {
            buffer.write(bytes);
        } catch(TTransportException e) {
            throw new SerializationException(e);
        }
        TProtocol protocol = createThriftProtocol(buffer);

        T msg = null;
        try {
            msg = messageClass.newInstance();
            msg.read(protocol);
        } catch(InstantiationException e) {
            throw new SerializationException(e);
        } catch(IllegalAccessException e) {
            throw new SerializationException(e);
        } catch(TException e) {
            throw new SerializationException(e);
        }

        return msg;
    }

    protected String[] parseSchemaInfo(String schemaInfo) {
        String[] thriftInfo = new String[2];

        String javaToken = null;
        String[] tokens = schemaInfo.split(";");
        for(int i = 0; i < tokens.length; i++) {
            if(tokens[i].trim().startsWith("java")) {
                javaToken = tokens[i];
                break;
            }
        }

        if(javaToken == null) {
            throw new IllegalArgumentException(ONLY_JAVA_CLIENTS_SUPPORTED);
        }

        tokens = javaToken.split(",");
        for(int i = 0; i < tokens.length; i++) {
            tokens[i] = tokens[i].trim();
            if(tokens[i].startsWith("java=")) {
                thriftInfo[0] = tokens[i].substring("java=".length());
            } else if(tokens[i].startsWith("protocol=")) {
                thriftInfo[1] = tokens[i].substring("protocol=".length());
            }
        }

        return thriftInfo;
    }

    protected ThriftProtocol getThriftProtocol(String protocolStr) {
        if(protocolStr.equalsIgnoreCase("binary")) {
            return ThriftProtocol.BINARY;
        } else if(protocolStr.equalsIgnoreCase("json")) {
            return ThriftProtocol.JSON;
        } else if(protocolStr.equalsIgnoreCase("simple-json")) {
            return ThriftProtocol.SIMPLE_JSON;
        } else {
            return ThriftProtocol.UNKNOWN;
        }
    }

    protected TProtocol createThriftProtocol(TTransport transport) {
        switch(this.protocol) {
            case BINARY:
                return new TBinaryProtocol(transport);
            case JSON:
                return new TJSONProtocol(transport);
            case SIMPLE_JSON:
                return new TSimpleJSONProtocol(transport);
            default:
                throw new IllegalArgumentException("Unknown Thrift Protocol.");
        }
    }
}


text:
@interface HKLSocketStubResponse : NSObject
<HKLSocketStubResponseChaining, NSCopying>

@property (nonatomic) NSData *data;         // expected incoming data
@property (nonatomic) NSString *dataString; // expected incoming data(UTF-8 string expression)

@property (nonatomic) NSData *responseData;         // outgoing response data
@property (nonatomic) NSString *responseDataString; // outgoing response data(UTF-8 string expression)

@property (nonatomic) NSTimeInterval processingTimeSeconds;

@property (nonatomic, copy) HKLSocketStubDataCheckBlock checkBlock;

@property (nonatomic) BOOL external;

- (instancetype)initWithSocketStubResponse:(HKLSocketStubResponse *)response;
@end


text:
package admin

import (
	"github.com/Unknwon/paginater"

	"github.com/gogits/gogs/models"
	"github.com/gogits/gogs/modules/base"
	"github.com/gogits/gogs/modules/middleware"
	"github.com/gogits/gogs/modules/setting"
)

const (
	REPOS base.TplName = "admin/repo/list"
)

func Repositories(ctx *middleware.Context) {
	ctx.Data["Title"] = ctx.Tr("admin.repositories")
	ctx.Data["PageIsAdmin"] = true
	ctx.Data["PageIsAdminRepositories"] = true

	total := models.CountRepositories()
	page := ctx.QueryInt("page")
	if page <= 1 {
		page = 1
	}
	ctx.Data["Page"] = paginater.New(int(total), setting.AdminRepoPagingNum, page, 5)

	repos, err := models.RepositoriesWithUsers(page, setting.AdminRepoPagingNum)
	if err != nil {
		ctx.Handle(500, "RepositoriesWithUsers", err)
		return
	}
	ctx.Data["Repos"] = repos

	ctx.Data["Total"] = total
	ctx.HTML(200, REPOS)
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor;

use Oro\Bundle\ApiBundle\Collection\IncludedEntityCollection;
use Oro\Bundle\ApiBundle\Processor\FormContext;

class FormContextTest extends \PHPUnit_Framework_TestCase
{
    /** @var FormContext */
    protected $context;

    protected function setUp()
    {
        $configProvider   = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\ConfigProvider')
            ->disableOriginalConstructor()
            ->getMock();
        $metadataProvider = $this->getMockBuilder('Oro\Bundle\ApiBundle\Provider\MetadataProvider')
            ->disableOriginalConstructor()
            ->getMock();

        $this->context = new FormContextStub($configProvider, $metadataProvider);
    }

    public function testRequestData()
    {
        $requestData = [];
        $this->context->setRequestData($requestData);
        $this->assertSame($requestData, $this->context->getRequestData());
    }

    public function testIncludedData()
    {
        $includedData = [];
        $this->context->setIncludedData($includedData);
        $this->assertSame($includedData, $this->context->getIncludedData());
    }

    public function testIncludedEntities()
    {
        $this->assertNull($this->context->getIncludedEntities());

        $includedEntities = $this->createMock(IncludedEntityCollection::class);
        $this->context->setIncludedEntities($includedEntities);
        $this->assertSame($includedEntities, $this->context->getIncludedEntities());

        $this->context->setIncludedEntities();
        $this->assertNull($this->context->getIncludedEntities());
    }

    public function testFormBuilder()
    {
        $formBuilder = $this->createMock('Symfony\Component\Form\FormBuilderInterface');

        $this->assertFalse($this->context->hasFormBuilder());
        $this->assertNull($this->context->getFormBuilder());

        $this->context->setFormBuilder($formBuilder);
        $this->assertTrue($this->context->hasFormBuilder());
        $this->assertSame($formBuilder, $this->context->getFormBuilder());

        $this->context->setFormBuilder();
        $this->assertFalse($this->context->hasFormBuilder());
        $this->assertNull($this->context->getFormBuilder());
    }

    public function testForm()
    {
        $form = $this->createMock('Symfony\Component\Form\FormInterface');

        $this->assertFalse($this->context->hasForm());
        $this->assertNull($this->context->getForm());

        $this->context->setForm($form);
        $this->assertTrue($this->context->hasForm());
        $this->assertSame($form, $this->context->getForm());

        $this->context->setForm();
        $this->assertFalse($this->context->hasForm());
        $this->assertNull($this->context->getForm());
    }
}


text:
hello-flask
===========

A sandbox for playing around with Flask.


text:
/**
 * \file TLVSharedMemoryInfoTestSuite.cpp
 * \date Apr 8, 2010
 * \author samael
 */

#include <cstring>
#include "TLVSharedMemoryInfoTestSuite.h"
#include "CTlvSharedMemoryInfo.h"
#include "CmlTLVTypes.h"
#include "CTlvUint32.h"
#include "CTlvString.h"
#include "CTlvBlock.h"
#include "WfeTLVTypes.h"

CPPUNIT_TEST_SUITE_REGISTRATION(TLVSharedMemoryInfoTestSuite);

using namespace wolf;
using namespace wolf;

void TLVSharedMemoryInfoTestSuite::testToTLVBlock()
{
	CTlvSharedMemoryInfo info("this is a piece of shared memory", 16992);
	ITlvBlock *blk = info.toTLVBlock();

	CPPUNIT_ASSERT_EQUAL((uint32_t)TLV_TYPE_SMINFO, blk->type());
	CPPUNIT_ASSERT_EQUAL((uint32_t)(strlen("this is a piece of shared memory") +
			ITlvBlock::szHeader + CTlvUint32::Size), blk->length());

	CSharedTlvBlock nameblk(blk->value());
	CSharedTlvBlock sizeblk(blk->value() + nameblk.plainSize());
	CPPUNIT_ASSERT_EQUAL((uint32_t)TLV_TYPE_STRING, nameblk.type());
	CPPUNIT_ASSERT_EQUAL((uint32_t)TLV_TYPE_UINT32, sizeblk.type());

	delete blk;
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping
>
    <class
        name="org.apache.ode.daohib.bpel.hobj.HScope"
        table="BPEL_SCOPE"
    >

        <id
            name="id"
            column="ID"
            type="java.lang.Long"
        >
            <generator class="org.apache.ode.daohib.NativeHiLoGenerator">
                <param name="sequence">hibernate_seqhilo</param>
                <param name="max_lo">99</param>
              <!--
                  To add non XDoclet generator parameters, create a file named
                  hibernate-generator-params-HScope.xml
                  containing the additional parameters and place it in your merge dir.
              -->
            </generator>
        </id>

        <set
            name="correlationSets"
            lazy="true"
            inverse="true"
            cascade="delete"
            sort="unsorted"
        >

            <key
                column="SCOPE_ID"
                  foreign-key="none"
            >
            </key>

            <one-to-many
                  class="org.apache.ode.daohib.bpel.hobj.HCorrelationSet"
            />

        </set>

        <many-to-one
            name="instance"
            class="org.apache.ode.daohib.bpel.hobj.HProcessInstance"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            foreign-key="none"
            column="PIID"
        />

        <many-to-one
            name="parentScope"
            class="org.apache.ode.daohib.bpel.hobj.HScope"
            cascade="none"
            outer-join="auto"
            update="true"
            insert="true"
            foreign-key="none"
            column="PARENT_SCOPE_ID"
        />

        <property
            name="state"
            type="java.lang.String"
            update="true"
            insert="true"
            column="STATE"
            not-null="true"
        />

        <property
            name="name"
            type="java.lang.String"
            update="true"
            insert="true"
            column="NAME"
            not-null="true"
        />

        <set
            name="variables"
            lazy="true"
            inverse="true"
            cascade="delete"
            sort="unsorted"
        >

            <key
                column="SCOPE_ID"
                  foreign-key="none"
            >
            </key>

            <one-to-many
                  class="org.apache.ode.daohib.bpel.hobj.HXmlData"
            />

        </set>

        <set
            name="partnerLinks"
            lazy="true"
            inverse="true"
            cascade="delete"
            sort="unsorted"
        >

            <key
                column="SCOPE"
                  foreign-key="none"
            >
            </key>

            <one-to-many
                  class="org.apache.ode.daohib.bpel.hobj.HPartnerLink"
            />

        </set>

        <property
            name="scopeModelId"
            type="int"
            update="true"
            insert="true"
            column="MODELID"
        />

        <property
            name="created"
            type="timestamp"
            update="true"
            insert="true"
            column="INSERT_TIME"
        />

        <property
            name="lock"
            type="int"
            update="true"
            insert="true"
            column="MLOCK"
            not-null="true"
        />

        <!--
            To add non XDoclet property mappings, create a file named
                hibernate-properties-HScope.xml
            containing the additional properties and place it in your merge dir.
        -->

    </class>

        <query name="SELECT_SCOPE_IDS_BY_INSTANCES"><![CDATA[
            select id from HScope as s where s.instance in (:instances)
        ]]></query>

</hibernate-mapping>


text:
var config = require('../config');
var path = require('path');

var env = process.env.NODE_ENV || "development";

var log4js = require('log4js');
log4js.configure({
  appenders: [
    { type: 'console' },
    { type: 'file', filename: path.join(config.log_dir, 'cheese.log'), category: 'cheese' }
  ]
});

var logger = log4js.getLogger('cheese');
logger.setLevel(config.debug && env !== 'test' ? 'DEBUG' : 'ERROR');

module.exports = logger;


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var _class = function () {
    function _class(name, source, type) {
        _classCallCheck(this, _class);

        this.active = true;

        this.name = name;
        this.source = source;
        this.type = type;
    }

    _createClass(_class, [{
        key: "$destroy",
        value: function $destroy() {
            this.active = false;
        }
    }, {
        key: "$transfor",
        value: function $transfor(wxevent) {
            var k = 0;
            for (k in wxevent) {
                this[k] = wxevent[k];
            }
        }
    }]);

    return _class;
}();

exports.default = _class;
//# sourceMappingURL=event.js.map


text:
export const REQUEST_LOCATION = 'REQUEST_LOCATION';
export const SET_LOCATION = 'SET_LOCATION';
export const REQUEST_WEATHER = 'REQUEST_WEATHER';
export const SET_WEATHER = 'SET_WEATHER';

function requestLocation() {
    return {
        type: REQUEST_LOCATION,
    }
}

export function getLocation() {
    return (dispatch) => {
        dispatch(requestLocation());
        /*if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position) => {
                dispatch(getWeather(position.coords.latitude, position.coords.longitude));
            });
            return;
        }*/
        fetch(`https://freegeoip.net/json/`)
            .then(response => response.json())
            .then(json => {
                dispatch(setLocation(json));
                dispatch(getWeather(json.latitude, json.longitude));
            }).catch(error => dispatch(setLocation(null)));
    };
}

export function setLocation(json) {
    return {
        type: SET_LOCATION,
        json
    };
}

function requestWeather(lat, lon) {
    return {
        type: REQUEST_WEATHER,
        lat,
        lon
    };
}

export function getWeather(lat, lon) {
    return (dispatch) => {
        dispatch(requestWeather(lat, lon));
        return fetch(`https://shielded-depths-35887.herokuapp.com/proxy/weather?lat=${lat}&lon=${lon}`)
            .then(response => response.json())
            .then(json => {
                dispatch(setWeather(json));
            }).catch(error => {
                console.log("Error: getWeather", error);
                dispatch(setWeather(null))
            });

    }
}

export function setWeather(json) {
    return {
        type: SET_WEATHER,
        json
    };
}


text:
#ifndef _ERL_UNICODE_H
#define _ERL_UNICODE_H

Uint erts_atom_to_string_length(Eterm atom);
Eterm erts_atom_to_string(Eterm **hpp, Eterm atom, Eterm tail);

#endif /* _ERL_UNICODE_H */


text:
pub const BCS_SIGNED_TRANSACTION: &str = "application/x.diem.signed_transaction+bcs";
pub const JSON: &str = "application/json";


text:
package de.mrapp.android.adapter;

import androidx.annotation.NonNull;
import android.widget.AbsListView;

import de.mrapp.android.adapter.list.ListAdapter;

/**
 * Defines the interface, an adapter, whose underlying data is managed as a list of arbitrary items,
 * which can not be selected, must implement. Such an adapter's purpose is to provide the underlying
 * data for visualization using a {@link AbsListView} widget.
 *
 * @param <DataType>
 *         The type of the adapter's underlying data
 * @author Michael Rapp
 * @since 0.5.0
 */
public interface NoChoiceListAdapter<DataType> extends ListAdapter<DataType> {

    /**
     * Returns the decorator, which allows to customize the appearance of the views, which are used
     * to visualize the items of the adapter.
     *
     * @return The decorator, which allows to customize the appearance of the views, which are used
     * to visualize the items of the adapter, as an instance of the type {@link ListDecorator}. The
     * decorator may not be null
     */
    ListDecorator<DataType> getDecorator();

    /**
     * Sets the decorator, which allows to customize the appearance of the views, which are used to
     * visualize the items of the adapter.
     *
     * @param decorator
     *         The decorator, which should be set, as an instance of the type {@link ListDecorator}.
     *         The decorator may not be null
     */

    void setDecorator(@NonNull ListDecorator<DataType> decorator);

    @Override
    NoChoiceListAdapter<DataType> clone() throws CloneNotSupportedException;

}


text:
//
//  ShareSDKUI.h
//  ShareSDKUI
//
//  Created by fenghj on 15/6/18.
//  Copyright (c) 2015年 mob. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ShareSDK+SSUI.h"
#import "SSUIShareActionSheetController.h"
#import "SSUIShareContentEditorViewController.h"

@interface ShareSDKUI : NSObject

/**
 *  创建分享菜单
 *
 *  @param items 分享菜单项
 *
 *  @return 分享菜单控制器
 */
+ (SSUIShareActionSheetController *)shareActionSheetWithItems:(NSArray *)items;

/**
 *  创建内容编辑视图
 *
 *  @param content          内容
 *  @param image            图片
 *  @param platformTypes    分享平台列表
 *
 *  @return 内容编辑视图控制器
 */
+ (SSUIShareContentEditorViewController *)contentEditorViewWithContent:(NSString *)content
                                                                 image:(SSDKImage *)image
                                                         platformTypes:(NSArray *)platformTypes;

@end


text:
<!doctype html>
<!--
WebXR page that only submits one frame.
-->
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="../resources/webxr_e2e.css">
  </head>
  <body>
    <canvas id="webgl-canvas"></canvas>
    <script src="../resources/webxr_e2e.js"></script>
    <script src="../resources/webxr_boilerplate.js"></script>
    <script src="../../../../../../third_party/blink/web_tests/resources/testharness.js"></script>
    <script>
      shouldSetBaseLayer = false;
      var frame_count = 0;
      var frame_expected = false;
      var delay_ended = false;
      onImmersiveXRFrameCallback = function() {
        assert_true(frame_expected);
        frame_count++;
        console.log('Got immersive frame number ' + frame_count);
      };

      function setBaseLayer() {
        let session = sessionInfos[sessionTypes.IMMERSIVE].session;
        session.updateRenderState({ baseLayer: new XRWebGLLayer(session, gl) });
        frame_expected = true;
      }

      function delayMilliseconds(waitTime) {
        delay_ended = false;
        window.setTimeout(() => { delay_ended = true }, waitTime);
      }
    </script>
  </body>
</html>


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Punktu interpolēšana

Šis rīks sniedz iespēju prognozēt vērtības jaunos izvietojumos, pamatojoties uz mērījumiem no punktu kolekcijas. Rīks izmanto punkta datus ar vērtībām katrā punktā un atgriež prognozēto vērtību rastru:

Gaisa kvalitātes uzraudzības apgabalā ir sensori, kas mēra piesārņojuma līmeni. Interpolēt punktus var izmantot, lai prognozētu piesārņojuma līmeni izvietojumos, kuros nav sensoru, piemēram, izvietojumos, kur atrodas riska grupas — skolas vai slimnīcas.

Prognozējiet smago metālu koncentrāciju ražā, pamatojoties uz paraugiem, kas iegūti no atsevišķiem augiem.

Prognozējiet augsnes barības vielu līmeņus (slāpeklis, fosfors, kālijs u.c.) un citus indikatorus (piemēram, elektrovadītspēju), lai izpētītu to relāciju ar ražas apjomu un noteiktu precīzu mēslojuma daudzumu katram izvietojumam laukā.

Meteoroloģiskais lietojums ietver temperatūru, lietavu un citu saistīto mainīgo prognozes (piemēram, skābā lietus).

Izvēlieties punkta slāni, kas satur vietas ar zināmām vērtībām

Punktu slānis, kas satur punktus, kuros ir noteiktas vērtības.

Izvēlēties lauku interpolēšanai

Izvēlieties lauku, kura vērtības vēlaties interpolēt. Laukam ir jābūt ciparu laukam.

Optimizēt

Izvēlieties savu iestatījumu ātruma un precizitātes attiecībai.

Precīzākas prognozes tiek aprēķinātas ilgāk. Šis parametrs izmaina noklusējuma vērtības vairākiem citiem rīka Punktu interpolēšana parametriem, lai optimizētu aprēķina ātrumu, rezultātu akurātumu vai līdzsvarotu abus rādītājus. Pēc noklusējuma rīks optimizē, lai panāktu līdzsvaru.

Pārveidot datus par parastu sadali

Izvēlieties, vai pārveidot datus par parastu sadali.

Interpolācija ir visprecīzākā datiem, kas atbilst parastai (zvana formas) sadalei. Ja jūsu datu sadalījums nav parasts, tie ir jāpārveido.

Lokālo modeļu lielums

Rīks Punktu interpolēšana darbojas, veidojot lokālus interpolācijas modeļus, kas tiek apvienoti, lai izveidotu galīgo prognožu karti. Šis parametrs nosaka, cik punkti tiks ietverti katrā lokālajā modelī. Mazākas vērtības padarīs rezultātus lokālākus un var atklāt maza mēroga efektus, tomēr tās var padarīt aprēķinus nestabilus. Lielākas vērtības būs stabilākas, tomēr tās var neuzrādīt dažus lokālus efektus.

Vērtības diapazons ir 30–500, tomēr tipiskas vērtības atrodas diapazonā 50–200.

Kaimiņu skaits

Prognozes tiek aprēķinātas, ņemot vērā kaimiņu punktus. Šis parametrs nosaka, cik punkti tiks izmantoti aprēķinos. Izmantojot lielu skaitu kaimiņu, parasti tiek iegūti precīzāki rezultāti, tomēr to aprēķins aizņem vairāk laika.

Šīs vērtības diapazons ir 1–64, tomēr tipiskas vērtības atrodas diapazonā 5–15.

Izvades šūnas lielums

Ievadiet izvades rastru šūnas lielumu un mērvienību.

Pieejamās mērvienības ir pēdas, jūdzes, metri un kilometri.

Izvades prognozes kļūda

Izvēlieties, vai vēlaties izveidot prognozēto vērtību standartkļūdu rastru.

Standartkļūdas ir noderīgas, jo sniedz informāciju par prognozēto vērtību uzticamību. Vienkāršs nosacījums ir tāds, ka patiesā vērtība 95 procentos gadījumu atradīsies starp divām prognozētās vērtības standartkļūdām. Piemēram, pieņemsim, ka jaunā izvietojumā tiek prognozēta vērtība 50 ar standartkļūdu 5. Tas nozīmē, ka šis rīks prognozē, ka patiesā vērtībā šajā izvietojumā ir 50, bet tā var būt arī augstāka vai zemāka, piemēram, 40 vai 60. Lai aprēķinātu šo saprātīgo vērtību diapazonu, reiziniet standartkļūdu ar 2, pieskaitiet šo vērtību prognozētajai vērtībai, lai iegūtu diapazona augšējo robežu, un atņemiet to no prognozētās vērtības, lai iegūtu diapazona apakšējo robežu.

Rezultātu slāņa nosaukums

Slāņa nosaukums, kas tiks izveidots sadaļā  Mans saturs un pievienots kartei. Noklusējuma nosaukums ir balstīts uz rīka nosaukumu un ievades slāņa nosaukumu. Ja slānis jau pastāv, jums tiks lūgts norādīt citu nosaukumu.

Lietojot  Saglabāt rezultātus nolaižamajā sarakstlodziņā, jūs varat norādīt nosaukumu mapē Mans saturs, kur tiks saglabāti rezultāti.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Package render
</TITLE>

<META NAME="date" CONTENT="2013-05-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
render

Packages that use render

gui.control

gui.menu

render

Classes in render used by gui.control

DisplayControl

          Trieda v sebe uklada konfiguraciu aktualneho renderu.

IRenderEvaluator

          Interface IRenderEvaluator

ISearchText

          Interface pre nastavenie vyhladavaneho textu

Classes in render used by gui.menu

DisplayControl

          Trieda v sebe uklada konfiguraciu aktualneho renderu.

Classes in render used by render

DisplayControl

          Trieda v sebe uklada konfiguraciu aktualneho renderu.

IRenderEvaluator

          Interface IRenderEvaluator

ISearchText

          Interface pre nastavenie vyhladavaneho textu

RenderThroughtQuadTree

          Render spolupracujuci s quad tree, upraveny pre lepsiu performance.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
#ifndef _CRC_h
#define _CRC_h

#include "MiniStdlib/cstdint.h"
 // for size_t
#include "MiniStdlib/cstddef.h"
#include "MiniStdlib/declspec.h"
#include "MiniStdlib/cstdbool.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef enum
{
	CRC_BitOrder_LSB_to_MSB,
	CRC_BitOrder_MSB_to_LSB
} CRC_BitOrder;

DLLEXPORT uint32_t CRC_init(bool in_invertBefore);

/*!
* Precondition: the function CRC_init() was called before.
*/
DLLEXPORT uint32_t CRC_update_LSB_to_MSB(uint32_t in_currentCRC, uint8_t in_currentByte);
DLLEXPORT uint32_t CRC_update_MSB_to_LSB(uint32_t in_currentCRC, uint8_t in_currentByte);

DLLEXPORT uint32_t CRC_terminate(uint32_t in_currentCRC, bool in_invertAfter);

/*!
* Precondition: the function CRC_init() was called before.
*/
DLLEXPORT uint32_t CRC_foldl_LSB_to_MSB(uint32_t in_currentCRC, void *in_pBuffer, size_t in_bufferSize);
DLLEXPORT uint32_t CRC_foldl_MSB_to_LSB(uint32_t in_currentCRC, void *in_pBuffer, size_t in_bufferSize);

DLLEXPORT uint32_t CRC_compute_LSB_to_MSB(void *in_pBuffer, size_t in_bufferSize,
	bool in_invertBefore, bool in_invertAfter);
DLLEXPORT uint32_t CRC_compute_MSB_to_LSB(void *in_pBuffer, size_t in_bufferSize,
	bool in_invertBefore, bool in_invertAfter);

/*!
 * The function CRC_stateUpdate is for using with fread_withState (IO/fread.h).
 * Precondition: the function CRC_init() was called before.
 */
DLLEXPORT void CRC_stateUpdate_update_LSB_to_MSB(void *in_pState, const void *in_pBuffer, size_t in_count);
DLLEXPORT void CRC_stateUpdate_update_MSB_to_LSB(void *in_pState, const void *in_pBuffer, size_t in_count);

#ifdef __cplusplus
}
#endif

#endif


text:
/*jslint node: true */
'use strict';

var paramUtil = require('../utils/paramUtil');
var _ = require('underscore');

describe('paramUtil', function() {
    describe('isInt', function() {
        it('return true if number is integer (true)', function() {
            expect(paramUtil.isInt(2.0)).toEqual(true);
        });

        it('return true if number is integer (false)', function() {
            expect(paramUtil.isInt(2.01)).toEqual(false);
        });
    });

    describe('isFloat', function() {
        it('return true if number is float (true)', function() {
            expect(paramUtil.isFloat(2.01)).toEqual(true);
        });

        it('return true if number is float (false)', function() {
            expect(paramUtil.isFloat(2.0)).toEqual(false);
        });
    });

    describe('returnObject', function() {
        it('returns an appropriate return object given an array', function() {
            var arrayItems = ['a', 'b', 3];
            var expectedResult = {
                data: {
                    items: [
                        'a',
                        'b',
                        3
                    ],
                    success: true
                }
            };
            var ro = new paramUtil.returnObject(arrayItems);
            expect(ro).toEqual(expectedResult);
        });
    });

    describe('convertArrayToRPCParameters', function() {
        it('return empty string because argument is undefined', function() {
            var parameter;
            var actualOutput = paramUtil.convertArrayToRPCParameters(parameter);
            expect(actualOutput).toEqual('');
        });

        it('return empty string because argument is not an array', function() {
            var parameter = 23;
            var actualOutput = paramUtil.convertArrayToRPCParameters(parameter);
            expect(actualOutput).toEqual('');
        });

        it('return empty string because array argument is empty', function() {
            var parameter = [];
            var actualOutput = paramUtil.convertArrayToRPCParameters(parameter);
            expect(actualOutput).toEqual('');
        });

        it('return RPC array without ^ because array argument has only one item', function() {
            var parameter = ['WT'];
            var actualOutput = paramUtil.convertArrayToRPCParameters(parameter);
            expect(actualOutput).toEqual('WT');
        });

        it('return RPC array given array argument with 3 elements', function() {
            var parameter = ['WT', 'HT', 'PO'];
            var actualOutput = paramUtil.convertArrayToRPCParameters(parameter);
            expect(actualOutput).toEqual('WT^HT^PO');
        });
    });

    describe('parseIntParam', function() {
        // test parsing
        it('returns parsed value when int is a positive number', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return '1';
                }
            }, 'myField')).toBe(1);
            expect(paramUtil.parseIntParam({
                param: function() {
                    return '1';
                }
            }, 'myField', 0, 0)).toBe(1);
        });
        it('returns parsed value when int is 0', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return '0';
                }
            }, 'myField')).toBe(0);
            expect(paramUtil.parseIntParam({
                param: function() {
                    return '0';
                }
            }, 'myField', -1, -1)).toBe(0);
        });
        it('returns parsed value when int is a negative number', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return '-1';
                }
            }, 'myField')).toBe(-1);
            expect(paramUtil.parseIntParam({
                param: function() {
                    return '-1';
                }
            }, 'myField', 0, 0)).toBe(-1);
        });

        // test default value handling
        it('returns default val when param is undefined', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return undefined;
                }
            }, 'myField', 7)).toBe(7);
            expect(paramUtil.parseIntParam({
                param: function() {
                    return undefined;
                }
            }, 'myField', 7, 0)).toBe(7);
        });
        it('returns default val when param is null', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return null;
                }
            }, 'myField', 7)).toBe(7);
            expect(paramUtil.parseIntParam({
                param: function() {
                    return null;
                }
            }, 'myField', 7, 0)).toBe(7);
        });
        it('returns NaN when param is undefined and no default val was specified', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return undefined;
                }
            }, 'myField')).toBe(undefined);
        });
        it('works correctly when the default val is explicitly undefined', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return undefined;
                }
            }, 'myField', undefined)).toBe(undefined);
        });

        // test error value handling
        it('returns error val when param is non-numeric', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return 'non-numeric value';
                }
            }, 'myField', 0, 7)).toBe(7);
        });
        it('returns NaN when param is non-numeric and no error val was specified', function() {
            var actualOutput = paramUtil.parseIntParam({
                param: function() {
                    return 'non-numeric value';
                }
            }, 'myField');
            expect(_.isNaN(actualOutput)).toBe(true);
        });
        it('works correctly when the error val is explicitly undefined', function() {
            expect(paramUtil.parseIntParam({
                param: function() {
                    return 'non-numeric value';
                }
            }, 'myField', 0, undefined)).toBe(undefined);
        });
    });
});


text:
#include "float_math.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "planetri.h"

// http://codesuppository.blogspot.com
//
// mailto: jratcliff@infiniplex.net
//
// http://www.amillionpixels.us
//

static inline float DistToPt(const float *p,const float *plane)
{
	float x = p[0];
	float y = p[1];
	float z = p[2];
	float d = x*plane[0] + y*plane[1] + z*plane[2] + plane[3];
	return d;
}

static PlaneTriResult getSidePlane(const float *p,const float *plane,float epsilon)
{

  float d = DistToPt(p,plane);

  if ( (d+epsilon) > 0 )
		return PTR_FRONT; // it is 'in front' within the provided epsilon value.

  return PTR_BACK;
}

static void add(const float *p,float *dest,unsigned int tstride,unsigned int &pcount)
{
  char *d = (char *) dest;
  d = d + pcount*tstride;
  dest = (float *) d;
  dest[0] = p[0];
  dest[1] = p[1];
  dest[2] = p[2];
  pcount++;
	assert( pcount <= 4 );
}

// assumes that the points are on opposite sides of the plane!
static void intersect(const float *p1,const float *p2,float *split,const float *plane)
{

  float dp1 = DistToPt(p1,plane);

  float dir[3];

  dir[0] = p2[0] - p1[0];
  dir[1] = p2[1] - p1[1];
  dir[2] = p2[2] - p1[2];

  float dot1 = dir[0]*plane[0] + dir[1]*plane[1] + dir[2]*plane[2];
  float dot2 = dp1 - plane[3];

  float    t = -(plane[3] + dot2 ) / dot1;

  split[0] = (dir[0]*t)+p1[0];
  split[1] = (dir[1]*t)+p1[1];
  split[2] = (dir[2]*t)+p1[2];

}

PlaneTriResult planeTriIntersection(const float *plane,    // the plane equation in Ax+By+Cz+D format
                                    const float *triangle, // the source triangle.
                                    unsigned int tstride,  // stride in bytes of the input and output triangles
                                    float        epsilon,  // the co-planer epsilon value.
                                    float       *front,    // the triangle in front of the
                                    unsigned int &fcount,  // number of vertices in the 'front' triangle
                                    float       *back,     // the triangle in back of the plane
                                    unsigned int &bcount) // the number of vertices in the 'back' triangle.
{
  fcount = 0;
  bcount = 0;

  const char *tsource = (const char *) triangle;

  // get the three vertices of the triangle.
  const float *p1     = (const float *) (tsource);
  const float *p2     = (const float *) (tsource+tstride);
  const float *p3     = (const float *) (tsource+tstride*2);

  PlaneTriResult r1   = getSidePlane(p1,plane,epsilon); // compute the side of the plane each vertex is on
  PlaneTriResult r2   = getSidePlane(p2,plane,epsilon);
  PlaneTriResult r3   = getSidePlane(p3,plane,epsilon);

  if ( r1 == r2 && r1 == r3 ) // if all three vertices are on the same side of the plane.
  {
    if ( r1 == PTR_FRONT ) // if all three are in front of the plane, then copy to the 'front' output triangle.
    {
      add(p1,front,tstride,fcount);
      add(p2,front,tstride,fcount);
      add(p3,front,tstride,fcount);
    }
    else
    {
      add(p1,back,tstride,bcount); // if all three are in 'abck' then copy to the 'back' output triangle.
      add(p2,back,tstride,bcount);
      add(p3,back,tstride,bcount);
    }
    return r1; // if all three points are on the same side of the plane return result
  }

  // ok.. we need to split the triangle at the plane.

  // First test ray segment P1 to P2
  if ( r1 == r2 ) // if these are both on the same side...
  {
    if ( r1 == PTR_FRONT )
    {
      add( p1, front, tstride, fcount );
      add( p2, front, tstride, fcount );
    }
    else
    {
      add( p1, back, tstride, bcount );
      add( p2, back, tstride, bcount );
    }
  }
  else
  {
    float split[3]; // split the point
    intersect(p1,p2,split,plane);

    if ( r1 == PTR_FRONT )
    {

      add(p1, front, tstride, fcount );
      add(split, front, tstride, fcount );

      add(split, back, tstride, bcount );
      add(p2, back, tstride, bcount );

    }
    else
    {
      add(p1, back, tstride, bcount );
      add(split, back, tstride, bcount );

      add(split, front, tstride, fcount );
      add(p2, front, tstride, fcount );
    }

  }

  // Next test ray segment P2 to P3
  if ( r2 == r3 ) // if these are both on the same side...
  {
    if ( r3 == PTR_FRONT )
    {
      add( p3, front, tstride, fcount );
    }
    else
    {
      add( p3, back, tstride, bcount );
    }
  }
  else
  {
    float split[3]; // split the point
    intersect(p2,p3,split,plane);

    if ( r3 == PTR_FRONT )
    {
      add(split, front, tstride, fcount );
      add(split, back, tstride, bcount );

      add(p3, front, tstride, fcount );
    }
    else
    {
      add(split, front, tstride, fcount );
      add(split, back, tstride, bcount );

      add(p3, back, tstride, bcount );
    }
  }

  // Next test ray segment P3 to P1
  if ( r3 != r1 ) // if these are both on the same side...
  {
    float split[3]; // split the point

    intersect(p3,p1,split,plane);

    if ( r1 == PTR_FRONT )
    {
      add(split, front, tstride, fcount );
      add(split, back, tstride, bcount );
    }
    else
    {
      add(split, front, tstride, fcount );
      add(split, back, tstride, bcount );
    }
  }

  return PTR_SPLIT;
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/safe_browsing/protocol_manager.h"

#include <utility>

#include "base/environment.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/rand_util.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/timer/timer.h"
#include "chrome/browser/safe_browsing/protocol_parser.h"
#include "chrome/common/env_vars.h"
#include "components/safe_browsing_db/util.h"
#include "components/variations/variations_associated_data.h"
#include "google_apis/google_api_keys.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"

using base::Time;
using base::TimeDelta;

namespace {

// UpdateResult indicates what happened with the primary and/or backup update
// requests. The ordering of the values must stay the same for UMA consistency,
// and is also ordered in this way to match ProtocolManager::BackupUpdateReason.
enum UpdateResult {
  UPDATE_RESULT_FAIL,
  UPDATE_RESULT_SUCCESS,
  UPDATE_RESULT_BACKUP_CONNECT_FAIL,
  UPDATE_RESULT_BACKUP_CONNECT_SUCCESS,
  UPDATE_RESULT_BACKUP_HTTP_FAIL,
  UPDATE_RESULT_BACKUP_HTTP_SUCCESS,
  UPDATE_RESULT_BACKUP_NETWORK_FAIL,
  UPDATE_RESULT_BACKUP_NETWORK_SUCCESS,
  UPDATE_RESULT_MAX,
  UPDATE_RESULT_BACKUP_START = UPDATE_RESULT_BACKUP_CONNECT_FAIL,
};

void RecordUpdateResult(UpdateResult result) {
  DCHECK(result >= 0 && result < UPDATE_RESULT_MAX);
  UMA_HISTOGRAM_ENUMERATION("SB2.UpdateResult", result, UPDATE_RESULT_MAX);
}

const char kSBUpdateFrequencyFinchExperiment[] = "SafeBrowsingUpdateFrequency";
const char kSBUpdateFrequencyFinchParam[] = "NextUpdateIntervalInMinutes";

// This will be used for experimenting on a small subset of the population to
// better estimate the benefit of updating the safe browsing hashes more
// frequently.
base::TimeDelta GetNextUpdateIntervalFromFinch() {
  std::string num_str = variations::GetVariationParamValue(
      kSBUpdateFrequencyFinchExperiment, kSBUpdateFrequencyFinchParam);
  int finch_next_update_interval_minutes = 0;
  if (!base::StringToInt(num_str, &finch_next_update_interval_minutes)) {
    finch_next_update_interval_minutes = 0;  // Defaults to 0.
  }
  return base::TimeDelta::FromMinutes(finch_next_update_interval_minutes);
}

}  // namespace

namespace safe_browsing {

// Minimum time, in seconds, from start up before we must issue an update query.
static const int kSbTimerStartIntervalSecMin = 60;

// Maximum time, in seconds, from start up before we must issue an update query.
static const int kSbTimerStartIntervalSecMax = 300;

// The maximum time, in seconds, to wait for a response to an update request.
static const int kSbMaxUpdateWaitSec = 30;

// Maximum back off multiplier.
static const size_t kSbMaxBackOff = 8;

const char kGetHashUmaResponseMetricName[] = "SB2.GetHashResponseOrErrorCode";
const char kGetChunkUmaResponseMetricName[] = "SB2.GetChunkResponseOrErrorCode";

// The default SBProtocolManagerFactory.
class SBProtocolManagerFactoryImpl : public SBProtocolManagerFactory {
 public:
  SBProtocolManagerFactoryImpl() {}
  ~SBProtocolManagerFactoryImpl() override {}
  SafeBrowsingProtocolManager* CreateProtocolManager(
      SafeBrowsingProtocolManagerDelegate* delegate,
      net::URLRequestContextGetter* request_context_getter,
      const SafeBrowsingProtocolConfig& config) override {
    return new SafeBrowsingProtocolManager(delegate, request_context_getter,
                                           config);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(SBProtocolManagerFactoryImpl);
};

// SafeBrowsingProtocolManager implementation ----------------------------------

// static
SBProtocolManagerFactory* SafeBrowsingProtocolManager::factory_ = NULL;

// static
SafeBrowsingProtocolManager* SafeBrowsingProtocolManager::Create(
    SafeBrowsingProtocolManagerDelegate* delegate,
    net::URLRequestContextGetter* request_context_getter,
    const SafeBrowsingProtocolConfig& config) {
  // TODO(cbentzel): Remove ScopedTracker below once crbug.com/483689 is fixed.
  tracked_objects::ScopedTracker tracking_profile(
      FROM_HERE_WITH_EXPLICIT_FUNCTION(
          "483689 SafeBrowsingProtocolManager::Create"));
  if (!factory_)
    factory_ = new SBProtocolManagerFactoryImpl();
  return factory_->CreateProtocolManager(delegate, request_context_getter,
                                         config);
}

SafeBrowsingProtocolManager::SafeBrowsingProtocolManager(
    SafeBrowsingProtocolManagerDelegate* delegate,
    net::URLRequestContextGetter* request_context_getter,
    const SafeBrowsingProtocolConfig& config)
    : delegate_(delegate),
      request_type_(NO_REQUEST),
      update_error_count_(0),
      gethash_error_count_(0),
      update_back_off_mult_(1),
      gethash_back_off_mult_(1),
      next_update_interval_(base::TimeDelta::FromSeconds(
          base::RandInt(kSbTimerStartIntervalSecMin,
                        kSbTimerStartIntervalSecMax))),
      chunk_pending_to_write_(false),
      version_(config.version),
      update_size_(0),
      client_name_(config.client_name),
      request_context_getter_(request_context_getter),
      url_prefix_(config.url_prefix),
      backup_update_reason_(BACKUP_UPDATE_REASON_MAX),
      disable_auto_update_(config.disable_auto_update),
      url_fetcher_id_(0) {
  DCHECK(!url_prefix_.empty());

  backup_url_prefixes_[BACKUP_UPDATE_REASON_CONNECT] =
      config.backup_connect_error_url_prefix;
  backup_url_prefixes_[BACKUP_UPDATE_REASON_HTTP] =
      config.backup_http_error_url_prefix;
  backup_url_prefixes_[BACKUP_UPDATE_REASON_NETWORK] =
      config.backup_network_error_url_prefix;

  // Set the backoff multiplier fuzz to a random value between 0 and 1.
  back_off_fuzz_ = static_cast<float>(base::RandDouble());
  if (version_.empty())
    version_ = SafeBrowsingProtocolManagerHelper::Version();
}

// static
void SafeBrowsingProtocolManager::RecordGetHashResult(bool is_download,
                                                      ResultType result_type) {
  if (is_download) {
    UMA_HISTOGRAM_ENUMERATION("SB2.GetHashResultDownload", result_type,
                              GET_HASH_RESULT_MAX);
  } else {
    UMA_HISTOGRAM_ENUMERATION("SB2.GetHashResult", result_type,
                              GET_HASH_RESULT_MAX);
  }
}

void SafeBrowsingProtocolManager::RecordHttpResponseOrErrorCode(
    const char* metric_name,
    const net::URLRequestStatus& status,
    int response_code) {
  UMA_HISTOGRAM_SPARSE_SLOWLY(
      metric_name, status.is_success() ? response_code : status.error());
}

bool SafeBrowsingProtocolManager::IsUpdateScheduled() const {
  return update_timer_.IsRunning();
}

SafeBrowsingProtocolManager::~SafeBrowsingProtocolManager() {
  // Delete in-progress SafeBrowsing requests.
  STLDeleteContainerPairFirstPointers(hash_requests_.begin(),
                                      hash_requests_.end());
  hash_requests_.clear();
}

// We can only have one update or chunk request outstanding, but there may be
// multiple GetHash requests pending since we don't want to serialize them and
// slow down the user.
void SafeBrowsingProtocolManager::GetFullHash(
    const std::vector<SBPrefix>& prefixes,
    FullHashCallback callback,
    bool is_download,
    bool is_extended_reporting) {
  DCHECK(CalledOnValidThread());
  // If we are in GetHash backoff, we need to check if we're past the next
  // allowed time. If we are, we can proceed with the request. If not, we are
  // required to return empty results (i.e. treat the page as safe).
  if (gethash_error_count_ && Time::Now() <= next_gethash_time_) {
    RecordGetHashResult(is_download, GET_HASH_BACKOFF_ERROR);
    std::vector<SBFullHashResult> full_hashes;
    callback.Run(full_hashes, base::TimeDelta());
    return;
  }
  GURL gethash_url = GetHashUrl(is_extended_reporting);
  net::URLFetcher* fetcher =
      net::URLFetcher::Create(url_fetcher_id_++, gethash_url,
                              net::URLFetcher::POST, this)
          .release();
  hash_requests_[fetcher] = FullHashDetails(callback, is_download);

  const std::string get_hash = FormatGetHash(prefixes);

  fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE);
  fetcher->SetRequestContext(request_context_getter_.get());
  fetcher->SetUploadData("text/plain", get_hash);
  fetcher->Start();
}

void SafeBrowsingProtocolManager::GetNextUpdate() {
  DCHECK(CalledOnValidThread());
  if (request_.get() || request_type_ != NO_REQUEST)
    return;

  IssueUpdateRequest();
}

// net::URLFetcherDelegate implementation ----------------------------------

// All SafeBrowsing request responses are handled here.
// TODO(paulg): Clarify with the SafeBrowsing team whether a failed parse of a
//              chunk should retry the download and parse of that chunk (and
//              what back off / how many times to try), and if that effects the
//              update back off. For now, a failed parse of the chunk means we
//              drop it. This isn't so bad because the next UPDATE_REQUEST we
//              do will report all the chunks we have. If that chunk is still
//              required, the SafeBrowsing servers will tell us to get it again.
void SafeBrowsingProtocolManager::OnURLFetchComplete(
    const net::URLFetcher* source) {
  DCHECK(CalledOnValidThread());
  scoped_ptr<const net::URLFetcher> fetcher;

  HashRequests::iterator it = hash_requests_.find(source);
  int response_code = source->GetResponseCode();
  net::URLRequestStatus status = source->GetStatus();

  if (it != hash_requests_.end()) {
    // GetHash response.
    // Reset the scoped pointer so the fetcher gets destroyed properly.
    fetcher.reset(it->first);
    RecordHttpResponseOrErrorCode(kGetHashUmaResponseMetricName, status,
                                  response_code);
    const FullHashDetails& details = it->second;
    std::vector<SBFullHashResult> full_hashes;
    base::TimeDelta cache_lifetime;
    if (status.is_success() && (response_code == net::HTTP_OK ||
                                response_code == net::HTTP_NO_CONTENT)) {
      // For tracking our GetHash false positive (net::HTTP_NO_CONTENT) rate,
      // compared to real (net::HTTP_OK) responses.
      if (response_code == net::HTTP_OK)
        RecordGetHashResult(details.is_download, GET_HASH_STATUS_200);
      else
        RecordGetHashResult(details.is_download, GET_HASH_STATUS_204);

      gethash_error_count_ = 0;
      gethash_back_off_mult_ = 1;
      std::string data;
      source->GetResponseAsString(&data);
      if (!ParseGetHash(data.data(), data.length(), &cache_lifetime,
                        &full_hashes)) {
        full_hashes.clear();
        RecordGetHashResult(details.is_download, GET_HASH_PARSE_ERROR);
        // TODO(cbentzel): Should cache_lifetime be set to 0 here? (See
        // http://crbug.com/360232.)
      }
    } else {
      HandleGetHashError(Time::Now());
      if (status.status() == net::URLRequestStatus::FAILED) {
        RecordGetHashResult(details.is_download, GET_HASH_NETWORK_ERROR);
        DVLOG(1) << "SafeBrowsing GetHash request for: " << source->GetURL()
                 << " failed with error: " << status.error();
      } else {
        RecordGetHashResult(details.is_download, GET_HASH_HTTP_ERROR);
        DVLOG(1) << "SafeBrowsing GetHash request for: " << source->GetURL()
                 << " failed with error: " << response_code;
      }
    }

    // Invoke the callback with full_hashes, even if there was a parse error or
    // an error response code (in which case full_hashes will be empty). The
    // caller can't be blocked indefinitely.
    details.callback.Run(full_hashes, cache_lifetime);

    hash_requests_.erase(it);
  } else {
    // Update or chunk response.
    RecordHttpResponseOrErrorCode(kGetChunkUmaResponseMetricName, status,
                                  response_code);
    fetcher.reset(request_.release());

    if (request_type_ == UPDATE_REQUEST ||
        request_type_ == BACKUP_UPDATE_REQUEST) {
      if (!fetcher.get()) {
        // We've timed out waiting for an update response, so we've cancelled
        // the update request and scheduled a new one. Ignore this response.
        return;
      }

      // Cancel the update response timeout now that we have the response.
      timeout_timer_.Stop();
    }

    if (status.is_success() && response_code == net::HTTP_OK) {
      // We have data from the SafeBrowsing service.
      std::string data;
      source->GetResponseAsString(&data);

      // TODO(shess): Cleanup the flow of this code so that |parsed_ok| can be
      // removed or omitted.
      const bool parsed_ok =
          HandleServiceResponse(source->GetURL(), data.data(), data.length());
      if (!parsed_ok) {
        DVLOG(1) << "SafeBrowsing request for: " << source->GetURL()
                 << " failed parse.";
        chunk_request_urls_.clear();
        if (request_type_ == UPDATE_REQUEST &&
            IssueBackupUpdateRequest(BACKUP_UPDATE_REASON_HTTP)) {
          return;
        }
        UpdateFinished(false);
      }

      switch (request_type_) {
        case CHUNK_REQUEST:
          if (parsed_ok) {
            chunk_request_urls_.pop_front();
            if (chunk_request_urls_.empty() && !chunk_pending_to_write_)
              UpdateFinished(true);
          }
          break;
        case UPDATE_REQUEST:
        case BACKUP_UPDATE_REQUEST:
          if (chunk_request_urls_.empty() && parsed_ok) {
            // We are up to date since the servers gave us nothing new, so we
            // are done with this update cycle.
            UpdateFinished(true);
          }
          break;
        case NO_REQUEST:
          // This can happen if HandleServiceResponse fails above.
          break;
        default:
          NOTREACHED();
          break;
      }
    } else {
      if (status.status() == net::URLRequestStatus::FAILED) {
        DVLOG(1) << "SafeBrowsing request for: " << source->GetURL()
                 << " failed with error: " << status.error();
      } else {
        DVLOG(1) << "SafeBrowsing request for: " << source->GetURL()
                 << " failed with error: " << response_code;
      }
      if (request_type_ == CHUNK_REQUEST) {
        // The SafeBrowsing service error, or very bad response code: back off.
        chunk_request_urls_.clear();
      } else if (request_type_ == UPDATE_REQUEST) {
        BackupUpdateReason backup_update_reason = BACKUP_UPDATE_REASON_MAX;
        if (status.is_success()) {
          backup_update_reason = BACKUP_UPDATE_REASON_HTTP;
        } else {
          switch (status.error()) {
            case net::ERR_INTERNET_DISCONNECTED:
            case net::ERR_NETWORK_CHANGED:
              backup_update_reason = BACKUP_UPDATE_REASON_NETWORK;
              break;
            default:
              backup_update_reason = BACKUP_UPDATE_REASON_CONNECT;
              break;
          }
        }
        if (backup_update_reason != BACKUP_UPDATE_REASON_MAX &&
            IssueBackupUpdateRequest(backup_update_reason)) {
          return;
        }
      }
      UpdateFinished(false);
    }

    // Get the next chunk if available.
    IssueChunkRequest();
  }
}

bool SafeBrowsingProtocolManager::HandleServiceResponse(const GURL& url,
                                                        const char* data,
                                                        size_t length) {
  DCHECK(CalledOnValidThread());

  switch (request_type_) {
    case UPDATE_REQUEST:
    case BACKUP_UPDATE_REQUEST: {
      size_t next_update_sec = 0;
      bool reset = false;
      scoped_ptr<std::vector<SBChunkDelete>> chunk_deletes(
          new std::vector<SBChunkDelete>);
      std::vector<ChunkUrl> chunk_urls;
      if (!ParseUpdate(data, length, &next_update_sec, &reset,
                       chunk_deletes.get(), &chunk_urls)) {
        return false;
      }

      // New time for the next update.
      base::TimeDelta finch_next_update_interval =
          GetNextUpdateIntervalFromFinch();
      if (finch_next_update_interval > base::TimeDelta()) {
        next_update_interval_ = finch_next_update_interval;
      } else {
        base::TimeDelta next_update_interval =
            base::TimeDelta::FromSeconds(next_update_sec);
        if (next_update_interval > base::TimeDelta()) {
          next_update_interval_ = next_update_interval;
        }
      }
      last_update_ = Time::Now();

      // New chunks to download.
      if (!chunk_urls.empty()) {
        UMA_HISTOGRAM_COUNTS("SB2.UpdateUrls", chunk_urls.size());
        for (size_t i = 0; i < chunk_urls.size(); ++i)
          chunk_request_urls_.push_back(chunk_urls[i]);
      }

      // Handle the case were the SafeBrowsing service tells us to dump our
      // database.
      if (reset) {
        delegate_->ResetDatabase();
        return true;
      }

      // Chunks to delete from our storage.
      if (!chunk_deletes->empty())
        delegate_->DeleteChunks(std::move(chunk_deletes));

      break;
    }
    case CHUNK_REQUEST: {
      UMA_HISTOGRAM_TIMES("SB2.ChunkRequest",
                          base::Time::Now() - chunk_request_start_);

      const ChunkUrl chunk_url = chunk_request_urls_.front();
      scoped_ptr<std::vector<scoped_ptr<SBChunkData>>> chunks(
          new std::vector<scoped_ptr<SBChunkData>>);
      UMA_HISTOGRAM_COUNTS("SB2.ChunkSize", length);
      update_size_ += length;
      if (!ParseChunk(data, length, chunks.get()))
        return false;

      // Chunks to add to storage.  Pass ownership of |chunks|.
      if (!chunks->empty()) {
        chunk_pending_to_write_ = true;
        delegate_->AddChunks(
            chunk_url.list_name, std::move(chunks),
            base::Bind(&SafeBrowsingProtocolManager::OnAddChunksComplete,
                       base::Unretained(this)));
      }

      break;
    }

    default:
      return false;
  }

  return true;
}

void SafeBrowsingProtocolManager::Initialize() {
  DCHECK(CalledOnValidThread());
  // TODO(cbentzel): Remove ScopedTracker below once crbug.com/483689 is fixed.
  tracked_objects::ScopedTracker tracking_profile(
      FROM_HERE_WITH_EXPLICIT_FUNCTION(
          "483689 SafeBrowsingProtocolManager::Initialize"));
  // Don't want to hit the safe browsing servers on build/chrome bots.
  scoped_ptr<base::Environment> env(base::Environment::Create());
  if (env->HasVar(env_vars::kHeadless))
    return;
  ScheduleNextUpdate(false /* no back off */);
}

void SafeBrowsingProtocolManager::ScheduleNextUpdate(bool back_off) {
  DCHECK(CalledOnValidThread());
  if (disable_auto_update_) {
    // Unschedule any current timer.
    update_timer_.Stop();
    return;
  }
  // Reschedule with the new update.
  base::TimeDelta next_update_interval = GetNextUpdateInterval(back_off);
  ForceScheduleNextUpdate(next_update_interval);
}

void SafeBrowsingProtocolManager::ForceScheduleNextUpdate(
    base::TimeDelta interval) {
  DCHECK(CalledOnValidThread());
  DCHECK(interval >= base::TimeDelta());
  // Unschedule any current timer.
  update_timer_.Stop();
  update_timer_.Start(FROM_HERE, interval, this,
                      &SafeBrowsingProtocolManager::GetNextUpdate);
}

// According to section 5 of the SafeBrowsing protocol specification, we must
// back off after a certain number of errors. We only change |next_update_sec_|
// when we receive a response from the SafeBrowsing service.
base::TimeDelta SafeBrowsingProtocolManager::GetNextUpdateInterval(
    bool back_off) {
  DCHECK(CalledOnValidThread());
  DCHECK(next_update_interval_ > base::TimeDelta());
  base::TimeDelta next = next_update_interval_;
  if (back_off) {
    next = GetNextBackOffInterval(&update_error_count_, &update_back_off_mult_);
  } else {
    // Successful response means error reset.
    update_error_count_ = 0;
    update_back_off_mult_ = 1;
  }
  return next;
}

base::TimeDelta SafeBrowsingProtocolManager::GetNextBackOffInterval(
    size_t* error_count,
    size_t* multiplier) const {
  DCHECK(CalledOnValidThread());
  DCHECK(multiplier && error_count);
  (*error_count)++;
  if (*error_count > 1 && *error_count < 6) {
    base::TimeDelta next =
        base::TimeDelta::FromMinutes(*multiplier * (1 + back_off_fuzz_) * 30);
    *multiplier *= 2;
    if (*multiplier > kSbMaxBackOff)
      *multiplier = kSbMaxBackOff;
    return next;
  }
  if (*error_count >= 6)
    return base::TimeDelta::FromHours(8);
  return base::TimeDelta::FromMinutes(1);
}

// This request requires getting a list of all the chunks for each list from the
// database asynchronously. The request will be issued when we're called back in
// OnGetChunksComplete.
// TODO(paulg): We should get this at start up and maintain a ChunkRange cache
//              to avoid hitting the database with each update request. On the
//              otherhand, this request will only occur ~20-30 minutes so there
//              isn't that much overhead. Measure!
void SafeBrowsingProtocolManager::IssueUpdateRequest() {
  DCHECK(CalledOnValidThread());
  request_type_ = UPDATE_REQUEST;
  delegate_->UpdateStarted();
  delegate_->GetChunks(
      base::Bind(&SafeBrowsingProtocolManager::OnGetChunksComplete,
                 base::Unretained(this)));
}

// The backup request can run immediately since the chunks have already been
// retrieved from the DB.
bool SafeBrowsingProtocolManager::IssueBackupUpdateRequest(
    BackupUpdateReason backup_update_reason) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(request_type_, UPDATE_REQUEST);
  DCHECK(backup_update_reason >= 0 &&
         backup_update_reason < BACKUP_UPDATE_REASON_MAX);
  if (backup_url_prefixes_[backup_update_reason].empty())
    return false;
  request_type_ = BACKUP_UPDATE_REQUEST;
  backup_update_reason_ = backup_update_reason;

  GURL backup_update_url = BackupUpdateUrl(backup_update_reason);
  request_ = net::URLFetcher::Create(url_fetcher_id_++, backup_update_url,
                                     net::URLFetcher::POST, this);
  request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
  request_->SetRequestContext(request_context_getter_.get());
  request_->SetUploadData("text/plain", update_list_data_);
  request_->Start();

  // Begin the update request timeout.
  timeout_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(kSbMaxUpdateWaitSec),
                       this,
                       &SafeBrowsingProtocolManager::UpdateResponseTimeout);

  return true;
}

void SafeBrowsingProtocolManager::IssueChunkRequest() {
  DCHECK(CalledOnValidThread());
  // We are only allowed to have one request outstanding at any time.  Also,
  // don't get the next url until the previous one has been written to disk so
  // that we don't use too much memory.
  if (request_.get() || chunk_request_urls_.empty() || chunk_pending_to_write_)
    return;

  ChunkUrl next_chunk = chunk_request_urls_.front();
  DCHECK(!next_chunk.url.empty());
  GURL chunk_url = NextChunkUrl(next_chunk.url);
  request_type_ = CHUNK_REQUEST;
  request_ = net::URLFetcher::Create(url_fetcher_id_++, chunk_url,
                                     net::URLFetcher::GET, this);
  request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
  request_->SetRequestContext(request_context_getter_.get());
  chunk_request_start_ = base::Time::Now();
  request_->Start();
}

void SafeBrowsingProtocolManager::OnGetChunksComplete(
    const std::vector<SBListChunkRanges>& lists,
    bool database_error,
    bool is_extended_reporting) {
  DCHECK(CalledOnValidThread());
  DCHECK_EQ(request_type_, UPDATE_REQUEST);
  DCHECK(update_list_data_.empty());
  if (database_error) {
    // The update was not successful, but don't back off.
    UpdateFinished(false, false);
    return;
  }

  // Format our stored chunks:
  bool found_malware = false;
  bool found_phishing = false;
  for (size_t i = 0; i < lists.size(); ++i) {
    update_list_data_.append(FormatList(lists[i]));
    if (lists[i].name == kPhishingList)
      found_phishing = true;

    if (lists[i].name == kMalwareList)
      found_malware = true;
  }

  // If we have an empty database, let the server know we want data for these
  // lists.
  // TODO(shess): These cases never happen because the database fills in the
  // lists in GetChunks().  Refactor the unit tests so that this code can be
  // removed.
  if (!found_phishing) {
    update_list_data_.append(FormatList(SBListChunkRanges(kPhishingList)));
  }
  if (!found_malware) {
    update_list_data_.append(FormatList(SBListChunkRanges(kMalwareList)));
  }

  // Large requests are (probably) a sign of database corruption.
  // Record stats to inform decisions about whether to automate
  // deletion of such databases.  http://crbug.com/120219
  UMA_HISTOGRAM_COUNTS("SB2.UpdateRequestSize", update_list_data_.size());

  GURL update_url = UpdateUrl(is_extended_reporting);
  request_ = net::URLFetcher::Create(url_fetcher_id_++, update_url,
                                     net::URLFetcher::POST, this);
  request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
  request_->SetRequestContext(request_context_getter_.get());
  request_->SetUploadData("text/plain", update_list_data_);
  request_->Start();

  // Begin the update request timeout.
  timeout_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(kSbMaxUpdateWaitSec),
                       this,
                       &SafeBrowsingProtocolManager::UpdateResponseTimeout);
}

// If we haven't heard back from the server with an update response, this method
// will run. Close the current update session and schedule another update.
void SafeBrowsingProtocolManager::UpdateResponseTimeout() {
  DCHECK(CalledOnValidThread());
  DCHECK(request_type_ == UPDATE_REQUEST ||
         request_type_ == BACKUP_UPDATE_REQUEST);
  request_.reset();
  if (request_type_ == UPDATE_REQUEST &&
      IssueBackupUpdateRequest(BACKUP_UPDATE_REASON_CONNECT)) {
    return;
  }
  UpdateFinished(false);
}

void SafeBrowsingProtocolManager::OnAddChunksComplete() {
  DCHECK(CalledOnValidThread());
  chunk_pending_to_write_ = false;

  if (chunk_request_urls_.empty()) {
    UMA_HISTOGRAM_LONG_TIMES("SB2.Update", Time::Now() - last_update_);
    UpdateFinished(true);
  } else {
    IssueChunkRequest();
  }
}

void SafeBrowsingProtocolManager::HandleGetHashError(const Time& now) {
  DCHECK(CalledOnValidThread());
  base::TimeDelta next =
      GetNextBackOffInterval(&gethash_error_count_, &gethash_back_off_mult_);
  next_gethash_time_ = now + next;
}

void SafeBrowsingProtocolManager::UpdateFinished(bool success) {
  UpdateFinished(success, !success);
}

void SafeBrowsingProtocolManager::UpdateFinished(bool success, bool back_off) {
  DCHECK(CalledOnValidThread());
  UMA_HISTOGRAM_COUNTS("SB2.UpdateSize", update_size_);
  update_size_ = 0;
  bool update_success = success || request_type_ == CHUNK_REQUEST;
  if (backup_update_reason_ == BACKUP_UPDATE_REASON_MAX) {
    RecordUpdateResult(update_success ? UPDATE_RESULT_SUCCESS
                                      : UPDATE_RESULT_FAIL);
  } else {
    UpdateResult update_result = static_cast<UpdateResult>(
        UPDATE_RESULT_BACKUP_START +
        (static_cast<int>(backup_update_reason_) * 2) + update_success);
    RecordUpdateResult(update_result);
  }
  backup_update_reason_ = BACKUP_UPDATE_REASON_MAX;
  request_type_ = NO_REQUEST;
  update_list_data_.clear();
  delegate_->UpdateFinished(success);
  ScheduleNextUpdate(back_off);
}

GURL SafeBrowsingProtocolManager::UpdateUrl(bool is_extended_reporting) const {
  std::string url = SafeBrowsingProtocolManagerHelper::ComposeUrl(
      url_prefix_, "downloads", client_name_, version_, additional_query_,
      is_extended_reporting);
  return GURL(url);
}

GURL SafeBrowsingProtocolManager::BackupUpdateUrl(
    BackupUpdateReason backup_update_reason) const {
  DCHECK(backup_update_reason >= 0 &&
         backup_update_reason < BACKUP_UPDATE_REASON_MAX);
  DCHECK(!backup_url_prefixes_[backup_update_reason].empty());
  std::string url = SafeBrowsingProtocolManagerHelper::ComposeUrl(
      backup_url_prefixes_[backup_update_reason], "downloads", client_name_,
      version_, additional_query_);
  return GURL(url);
}

GURL SafeBrowsingProtocolManager::GetHashUrl(bool is_extended_reporting) const {
  std::string url = SafeBrowsingProtocolManagerHelper::ComposeUrl(
      url_prefix_, "gethash", client_name_, version_, additional_query_,
      is_extended_reporting);
  return GURL(url);
}

GURL SafeBrowsingProtocolManager::NextChunkUrl(const std::string& url) const {
  DCHECK(CalledOnValidThread());
  std::string next_url;
  if (!base::StartsWith(url, "http://", base::CompareCase::INSENSITIVE_ASCII) &&
      !base::StartsWith(url, "https://",
                        base::CompareCase::INSENSITIVE_ASCII)) {
    // Use https if we updated via https, otherwise http (useful for testing).
    if (base::StartsWith(url_prefix_, "https://",
                         base::CompareCase::INSENSITIVE_ASCII))
      next_url.append("https://");
    else
      next_url.append("http://");
    next_url.append(url);
  } else {
    next_url = url;
  }
  if (!additional_query_.empty()) {
    if (next_url.find("?") != std::string::npos) {
      next_url.append("&");
    } else {
      next_url.append("?");
    }
    next_url.append(additional_query_);
  }
  return GURL(next_url);
}

SafeBrowsingProtocolManager::FullHashDetails::FullHashDetails()
    : callback(), is_download(false) {}

SafeBrowsingProtocolManager::FullHashDetails::FullHashDetails(
    FullHashCallback callback,
    bool is_download)
    : callback(callback), is_download(is_download) {}

SafeBrowsingProtocolManager::FullHashDetails::FullHashDetails(
    const FullHashDetails& other) = default;

SafeBrowsingProtocolManager::FullHashDetails::~FullHashDetails() {}

SafeBrowsingProtocolManagerDelegate::~SafeBrowsingProtocolManagerDelegate() {}

}  // namespace safe_browsing


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.hadoop.mapreduce.v2.app.job.JobStateInternal (hadoop-mapreduce-client-app 2.2.0 API)</title>
<meta name="date" content="2013-12-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.hadoop.mapreduce.v2.app.job.JobStateInternal

Packages that use JobStateInternal

Package
Description

org.apache.hadoop.mapreduce.v2.app

org.apache.hadoop.mapreduce.v2.app.job

org.apache.hadoop.mapreduce.v2.app.job.impl

Uses of JobStateInternal in org.apache.hadoop.mapreduce.v2.app

Methods in org.apache.hadoop.mapreduce.v2.app with parameters of type JobStateInternal

Modifier and Type
Method and Description

protected Job
MRAppMaster.createJob(org.apache.hadoop.conf.Configuration conf,
         JobStateInternal forcedState,
         String diagnostic)

Create and initialize (but don't start) a single job.

Uses of JobStateInternal in org.apache.hadoop.mapreduce.v2.app.job

Methods in org.apache.hadoop.mapreduce.v2.app.job that return JobStateInternal

Modifier and Type
Method and Description

static JobStateInternal
JobStateInternal.valueOf(String name)

Returns the enum constant of this type with the specified name.

static JobStateInternal[]
JobStateInternal.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Uses of JobStateInternal in org.apache.hadoop.mapreduce.v2.app.job.impl

Fields in org.apache.hadoop.mapreduce.v2.app.job.impl with type parameters of type JobStateInternal

Modifier and Type
Field and Description

protected static org.apache.hadoop.yarn.state.StateMachineFactory<JobImpl,JobStateInternal,JobEventType,JobEvent>
JobImpl.stateMachineFactory

Methods in org.apache.hadoop.mapreduce.v2.app.job.impl that return JobStateInternal

Modifier and Type
Method and Description

protected JobStateInternal
JobImpl.checkReadyForCommit()

JobStateInternal
JobImpl.getInternalState()

JobStateInternal
JobImpl.InitTransition.transition(JobImpl job,
          JobEvent event)

Note that this transition method is called directly (and synchronously)
 by MRAppMaster's init() method (i.e., no RPC, no thread-switching;
 just plain sequential call within AM context), so we can trigger
 modifications in AM state from here (at least, if AM is written that
 way; MR version is).

Methods in org.apache.hadoop.mapreduce.v2.app.job.impl that return types with arguments of type JobStateInternal

Modifier and Type
Method and Description

protected org.apache.hadoop.yarn.state.StateMachine<JobStateInternal,JobEventType,JobEvent>
JobImpl.getStateMachine()

Constructors in org.apache.hadoop.mapreduce.v2.app.job.impl with parameters of type JobStateInternal

Constructor and Description

<a href="../../../../../../../../org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.html#JobImpl(org.apache.hadoop.mapreduce.v2.api.records.JobId, org.apache.hadoop.yarn.api.records.ApplicationAttemptId, org.apache.hadoop.conf.Configuration, org.apache.hadoop.yarn.event.EventHandler, org.apache.hadoop.mapreduce.v2.app.TaskAttemptListener, org.apache.hadoop.mapreduce.security.token.JobTokenSecretManager, org.apache.hadoop.security.Credentials, org.apache.hadoop.yarn.util.Clock, java.util.Map, org.apache.hadoop.mapreduce.v2.app.metrics.MRAppMetrics, org.apache.hadoop.mapreduce.OutputCommitter, boolean, java.lang.String, long, java.util.List, org.apache.hadoop.mapreduce.v2.app.AppContext, org.apache.hadoop.mapreduce.v2.app.job.JobStateInternal, java.lang.String)">JobImpl(org.apache.hadoop.mapreduce.v2.api.records.JobId jobId,
       org.apache.hadoop.yarn.api.records.ApplicationAttemptId applicationAttemptId,
       org.apache.hadoop.conf.Configuration conf,
       org.apache.hadoop.yarn.event.EventHandler eventHandler,
       TaskAttemptListener taskAttemptListener,
       org.apache.hadoop.mapreduce.security.token.JobTokenSecretManager jobTokenSecretManager,
       org.apache.hadoop.security.Credentials jobCredentials,
       org.apache.hadoop.yarn.util.Clock clock,
       Map<org.apache.hadoop.mapreduce.v2.api.records.TaskId,org.apache.hadoop.mapreduce.jobhistory.JobHistoryParser.TaskInfo> completedTasksFromPreviousRun,
       MRAppMetrics metrics,
       org.apache.hadoop.mapreduce.OutputCommitter committer,
       boolean newApiCommitter,
       String userName,
       long appSubmitTime,
       List<org.apache.hadoop.mapreduce.v2.api.records.AMInfo> amInfos,
       AppContext appContext,
       JobStateInternal forcedState,
       String forcedDiagnostic)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Copyright © 2013 Apache Software Foundation. All Rights Reserved.


text:
#include <aws/iam/model/TagUserRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::IAM::Model;
using namespace Aws::Utils;

TagUserRequest::TagUserRequest() :
    m_userNameHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String TagUserRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=TagUser&";
  if(m_userNameHasBeenSet)
  {
    ss << "UserName=" << StringUtils::URLEncode(m_userName.c_str()) << "&";
  }

  if(m_tagsHasBeenSet)
  {
    unsigned tagsCount = 1;
    for(auto& item : m_tags)
    {
      item.OutputToStream(ss, "Tags.member.", tagsCount, "");
      tagsCount++;
    }
  }

  ss << "Version=2010-05-08";
  return ss.str();
}

void  TagUserRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
namespace atom {

namespace api {

class MenuMac : public Menu {
 protected:
  MenuMac();

  void Popup(Window* window) override;
  void PopupAt(Window* window, int x, int y) override;

  base::scoped_nsobject<AtomMenuController> menu_controller_;

 private:
  friend class Menu;

  static void SendActionToFirstResponder(const std::string& action);

  DISALLOW_COPY_AND_ASSIGN(MenuMac);
};

}  // namespace api

}  // namespace atom

#endif  // ATOM_BROWSER_API_ATOM_API_MENU_MAC_H_


text:
'use strict';

var _ = require('lodash'),
	Wolverine = require('wolverine');

module.exports = {
	defaultsDeep: _.partialRight(_.merge, function deep(value, other) {
		return _.merge(value, other, deep);
	}),
	jsFileRegex: /^\w+\.js$/i,
	Logger: new Wolverine(Wolverine.DEBUG, { printTime: false })
};


text:
using Nucleus.Base;
using Nucleus.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nucleus.Game
{
    /// <summary>
    /// Component which allows the element to which it is attached to perform critical hits
    /// </summary>
    public class CritHitter : Unique, IElementDataComponent
    {
        private double _BaseChance = 0.1;

        /// <summary>
        /// The base chance of this element performing a critical hit
        /// </summary>
        public double BaseChance
        {
            get { return _BaseChance; }
            set { ChangeProperty(ref _BaseChance, value); }
        }

        /// <summary>
        /// Determine the overall critical success chance
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public double CombinedCritChance(EffectContext context)
        {
            var chance = BaseChance;
            chance = context.Actor.Data.ApplyModifiers<double, ICritChanceModifier>(chance, (value, iModifier) => iModifier.ModifyCritChance(value, null, context));
            return chance;
        }

        /// <summary>
        /// Roll randomly to determine whether a critical success has been achieved
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool RollToCrit(EffectContext context)
        {
            return context.RNG.NextDouble() < CombinedCritChance(context);
        }
    }
}


text:
static void *groupContext = &groupContext;

@implementation UIButton (Connect)

- (void)setDelegate:(UIButton *)delegate
{
    NSArray *keys = @[@"enabled",@"selected",@"highlighted"];

    for (NSString *key in keys) {
        [delegate addSafeObserver:self
                       forKeyPath:key
                          options:NSKeyValueObservingOptionsWithoutPrior
                          context:groupContext];
    }
}

- (UIButton *)delegate
{
    return nil;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if (context == groupContext) {
        UIButton *button = (UIButton *)object;

        //不相同才跟進

        if (self.enabled != button.enabled)
            self.enabled = button.enabled;

        if (self.highlighted != button.highlighted)
            self.highlighted = button.highlighted;

        if (self.selected != button.highlighted ? NO : button.selected)
            self.selected = button.highlighted ? NO : button.selected;
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

@end