text:
<?php

namespace FOS\ElasticaBundle\Tests\Doctrine;

use Elastica\Bulk\ResponseSet;
use Elastica\Response;

class AbstractProviderTest extends \PHPUnit_Framework_TestCase
{
    private $objectClass;
    private $objectManager;
    private $objectPersister;
    private $options;
    private $managerRegistry;
    private $indexable;

    public function setUp()
    {
        if (!interface_exists('Doctrine\Common\Persistence\ManagerRegistry')) {
            $this->markTestSkipped('Doctrine Common is not available.');
        }

        $this->objectClass = 'objectClass';
        $this->options = array('debug_logging' => true, 'indexName' => 'index', 'typeName' => 'type');

        $this->objectPersister = $this->getMockObjectPersister();
        $this->managerRegistry = $this->getMockManagerRegistry();
        $this->objectManager = $this->getMockObjectManager();
        $this->indexable = $this->getMockIndexable();

        $this->managerRegistry->expects($this->any())
            ->method('getManagerForClass')
            ->with($this->objectClass)
            ->will($this->returnValue($this->objectManager));
    }

    /**
     * @dataProvider providePopulateIterations
     */
    public function testPopulateIterations($nbObjects, $objectsByIteration, $batchSize)
    {
        $this->options['batch_size'] = $batchSize;

        $provider = $this->getMockAbstractProvider();

        $queryBuilder = new \stdClass();

        $provider->expects($this->once())
            ->method('createQueryBuilder')
            ->will($this->returnValue($queryBuilder));

        $provider->expects($this->once())
            ->method('countObjects')
            ->with($queryBuilder)
            ->will($this->returnValue($nbObjects));

        $this->indexable->expects($this->any())
            ->method('isObjectIndexable')
            ->with('index', 'type', $this->anything())
            ->will($this->returnValue(true));

        $providerInvocationOffset = 2;

        foreach ($objectsByIteration as $i => $objects) {
            $offset = $objects[0] - 1;

            $provider->expects($this->at($providerInvocationOffset + $i))
                ->method('fetchSlice')
                ->with($queryBuilder, $batchSize, $offset)
                ->will($this->returnValue($objects));

            $this->objectManager->expects($this->at($i))
                ->method('clear');
        }

        $this->objectPersister->expects($this->exactly(count($objectsByIteration)))
            ->method('insertMany');

        $provider->populate();
    }

    public function providePopulateIterations()
    {
        return array(
            array(
                100,
                array(range(1,100)),
                100,
            ),
            array(
                105,
                array(range(1, 50), range(51, 100), range(101, 105)),
                50,
            ),
        );
    }

    public function testPopulateShouldNotClearObjectManager()
    {
        $nbObjects = 1;
        $objects = array(1);
        $this->options['clear_object_manager'] = false;

        $provider = $this->getMockAbstractProvider();

        $provider->expects($this->any())
            ->method('countObjects')
            ->will($this->returnValue($nbObjects));

        $provider->expects($this->any())
            ->method('fetchSlice')
            ->will($this->returnValue($objects));

        $this->indexable->expects($this->any())
            ->method('isObjectIndexable')
            ->with('index', 'type', $this->anything())
            ->will($this->returnValue(true));

        $this->objectManager->expects($this->never())
            ->method('clear');

        $provider->populate();
    }

    public function testPopulateShouldClearObjectManagerForFilteredBatch()
    {
        $nbObjects = 1;
        $objects = array(1);

        $provider = $this->getMockAbstractProvider();

        $provider->expects($this->any())
            ->method('countObjects')
            ->will($this->returnValue($nbObjects));

        $provider->expects($this->any())
            ->method('fetchSlice')
            ->will($this->returnValue($objects));

        $this->indexable->expects($this->any())
            ->method('isObjectIndexable')
            ->with('index', 'type', $this->anything())
            ->will($this->returnValue(false));

        $this->objectManager->expects($this->once())
            ->method('clear');

        $provider->populate();
    }

    public function testPopulateInvokesLoggerClosure()
    {
        $nbObjects = 1;
        $objects = array(1);

        $provider = $this->getMockAbstractProvider();

        $provider->expects($this->any())
            ->method('countObjects')
            ->will($this->returnValue($nbObjects));

        $provider->expects($this->any())
            ->method('fetchSlice')
            ->will($this->returnValue($objects));

        $this->indexable->expects($this->any())
            ->method('isObjectIndexable')
            ->with('index', 'type', $this->anything())
            ->will($this->returnValue(true));

        $loggerClosureInvoked = false;
        $loggerClosure = function () use (&$loggerClosureInvoked) {
            $loggerClosureInvoked = true;
        };

        $provider->populate();
        $this->assertFalse($loggerClosureInvoked);

        $provider->populate($loggerClosure);
        $this->assertTrue($loggerClosureInvoked);
    }

    public function testPopulateNotStopOnError()
    {
        $nbObjects = 1;
        $objects = array(1);

        $provider = $this->getMockAbstractProvider();

        $provider->expects($this->any())
            ->method('countObjects')
            ->will($this->returnValue($nbObjects));

        $provider->expects($this->any())
            ->method('fetchSlice')
            ->will($this->returnValue($objects));

        $this->indexable->expects($this->any())
            ->method('isObjectIndexable')
            ->with('index', 'type', $this->anything())
            ->will($this->returnValue(true));

        $this->objectPersister->expects($this->any())
            ->method('insertMany')
            ->will($this->throwException($this->getMockBulkResponseException()));

        $this->setExpectedException('Elastica\Exception\Bulk\ResponseException');

        $provider->populate(null, array('ignore-errors' => false));
    }

    public function testPopulateRunsIndexCallable()
    {
        $nbObjects = 2;
        $objects = array(1, 2);

        $provider = $this->getMockAbstractProvider();
        $provider->expects($this->any())
            ->method('countObjects')
            ->will($this->returnValue($nbObjects));
        $provider->expects($this->any())
            ->method('fetchSlice')
            ->will($this->returnValue($objects));

        $this->indexable->expects($this->at(0))
            ->method('isObjectIndexable')
            ->with('index', 'type', 1)
            ->will($this->returnValue(false));
        $this->indexable->expects($this->at(1))
            ->method('isObjectIndexable')
            ->with('index', 'type', 2)
            ->will($this->returnValue(true));

        $this->objectPersister->expects($this->once())
            ->method('insertMany')
            ->with(array(1 => 2));

        $provider->populate();
    }

    /**
     * @return \FOS\ElasticaBundle\Doctrine\AbstractProvider|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockAbstractProvider()
    {
        return $this->getMockForAbstractClass('FOS\ElasticaBundle\Doctrine\AbstractProvider', array(
            $this->objectPersister,
            $this->indexable,
            $this->objectClass,
            $this->options,
            $this->managerRegistry,
        ));
    }

    /**
     * @return \Elastica\Exception\Bulk\ResponseException
     */
    private function getMockBulkResponseException()
    {
        return $this->getMock('Elastica\Exception\Bulk\ResponseException', null, array(
            new ResponseSet(new Response(array()), array())
        ));
    }

    /**
     * @return \Doctrine\Common\Persistence\ManagerRegistry|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockManagerRegistry()
    {
        return $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
    }

    /**
     * @return ObjectManager|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockObjectManager()
    {
        return $this->getMock(__NAMESPACE__ . '\ObjectManager');
    }

    /**
     * @return \FOS\ElasticaBundle\Persister\ObjectPersisterInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockObjectPersister()
    {
        return $this->getMock('FOS\ElasticaBundle\Persister\ObjectPersisterInterface');
    }

    /**
     * @return \FOS\ElasticaBundle\Provider\IndexableInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockIndexable()
    {
        return $this->getMock('FOS\ElasticaBundle\Provider\IndexableInterface');
    }
}

/**
 * Doctrine\Common\Persistence\ObjectManager does not include a clear() method
 * in its interface, so create a new interface for mocking.
 */
interface ObjectManager
{
    function clear();
}


text:
package com.google.cloud.vision.v1.samples;

// [START vision_v1_generated_productsearchclient_listproductsinproductset_paged_async]
import com.google.cloud.vision.v1.ListProductsInProductSetRequest;
import com.google.cloud.vision.v1.ListProductsInProductSetResponse;
import com.google.cloud.vision.v1.Product;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ProductSetName;
import com.google.common.base.Strings;

public class AsyncListProductsInProductSetPaged {

  public static void main(String[] args) throws Exception {
    asyncListProductsInProductSetPaged();
  }

  public static void asyncListProductsInProductSetPaged() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (ProductSearchClient productSearchClient = ProductSearchClient.create()) {
      ListProductsInProductSetRequest request =
          ListProductsInProductSetRequest.newBuilder()
              .setName(ProductSetName.of("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]").toString())
              .setPageSize(883849137)
              .setPageToken("pageToken873572522")
              .build();
      while (true) {
        ListProductsInProductSetResponse response =
            productSearchClient.listProductsInProductSetCallable().call(request);
        for (Product element : response.getProductsList()) {
          // doThingsWith(element);
        }
        String nextPageToken = response.getNextPageToken();
        if (!Strings.isNullOrEmpty(nextPageToken)) {
          request = request.toBuilder().setPageToken(nextPageToken).build();
        } else {
          break;
        }
      }
    }
  }
}
// [END vision_v1_generated_productsearchclient_listproductsinproductset_paged_async]

redpajama_set_name: RedPajamaGithub


text:
if(NOT(DEFINED PFUNIT_ROOT))
    find_path(PFUNIT_ROOT NAMES lib/libpfunit.a)
endif()

# Look for pFUnit headers
find_path(PFUNIT_INCLUDE_DIRS_INC
    NAMES TestUtil.F90
    HINTS ${PFUNIT_ROOT}/include
          $ENV{PFUNIT_ROOT}/include
)
set(PFUNIT_DRIVER "${PFUNIT_INCLUDE_DIRS_INC}/driver.F90")
find_path(PFUNIT_INCLUDE_DIRS_MOD
    NAMES test_mod.mod
    HINTS ${PFUNIT_ROOT}/mod
          $ENV{PFUNIT_ROOT}/mod
)
message( STATUS "ROOT: ${PFUNIT_ROOT}" )
set( PFUNIT_INCLUDE_DIRS "${PFUNIT_INCLUDE_DIRS_INC}" "${PFUNIT_INCLUDE_DIRS_MOD}" )

# Look for lib
find_library(PFUNIT_LIBRARIES NAMES pfunit HINTS ${PFUNIT_ROOT}/lib)

# Look for bin dir
find_path(PFUNIT_BIN_DIR
    NAMES pFUnitParser.py
    HINTS ${PFUNIT_ROOT}/bin
          $ENV{PFUNIT_ROOT}/bin
)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PFUNIT DEFAULT_MSG
    PFUNIT_INCLUDE_DIRS_INC
    PFUNIT_INCLUDE_DIRS_MOD
    PFUNIT_LIBRARIES
    PFUNIT_BIN_DIR)

if(PFUNIT_FOUND)
    message(STATUS "pFUnit found at ${PFUNIT_ROOT}")
else()
    # If the package was required we abort the process
    if(${PFUNIT_FIND_REQUIRED})
        message(FATAL_ERROR "Could NOT find pFUnit. (Try setting PFUNIT_ROOT in the env)")
    endif(${PFUNIT_FIND_REQUIRED})
endif()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <title>Monitor Module — DroidPot 1.0 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="DroidPot 1.0 documentation" href="index.html" />
    <link rel="next" title="Profiles Module" href="profiles.html" />
    <link rel="prev" title="Welcome to DroidPot's documentation!" href="index.html" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">

Monitor Module¶

Related Topics

Documentation overview

Previous: Welcome to DroidPot’s documentation!

Next: Profiles Module

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      ©2015, Tan RongShun.

      |
      Powered by Sphinx 1.3.1
      & Alabaster 0.7.6

      |
      Page source


text:
package org.eclipse.jetty.spdy;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import org.eclipse.jetty.npn.NextProtoNego;
import org.eclipse.jetty.spdy.api.Session;
import org.eclipse.jetty.spdy.api.server.ServerSessionFrameListener;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
import org.junit.Test;

public class SSLEngineLeakTest extends AbstractTest
{
    @Override
    protected SPDYServerConnector newSPDYServerConnector(ServerSessionFrameListener listener)
    {
        SslContextFactory sslContextFactory = newSslContextFactory();
        return new SPDYServerConnector(listener, sslContextFactory);
    }

    @Override
    protected SPDYClient.Factory newSPDYClientFactory(Executor threadPool)
    {
        SslContextFactory sslContextFactory = newSslContextFactory();
        return new SPDYClient.Factory(threadPool, sslContextFactory);
    }

    @Test
    public void testSSLEngineLeak() throws Exception
    {
        System.gc();
        Thread.sleep(1000);

        Field field = NextProtoNego.class.getDeclaredField("objects");
        field.setAccessible(true);
        Map<Object, NextProtoNego.Provider> objects = (Map<Object, NextProtoNego.Provider>)field.get(null);
        int initialSize = objects.size();

        avoidStackLocalVariables();
        // Allow the close to arrive to the server and the selector to process it
        Thread.sleep(1000);

        // Perform GC to be sure that the WeakHashMap is cleared
        System.gc();
        Thread.sleep(1000);

        // Check that the WeakHashMap is empty
        Assert.assertEquals(initialSize, objects.size());
    }

    private void avoidStackLocalVariables() throws Exception
    {
        Session session = startClient(startServer(null), null);
        session.goAway().get(5, TimeUnit.SECONDS);
    }
}


text:
PCs in this age have very powerful computation power. Thus, Base 10 `AB - CD = EF, EF + GH = PPP` is too easy to compute the result. That's why someone even said that brute-force is also be accepted.

Let's try more complicated scenario, all alphabats repersent a single value (in base) & distinct. It will be easier to see the significant performance difference of each approach.

#### Advance
Base 16 `AB - CD = EF, EF + GH = PPP` (Width = 2)

Base 22 `AB - CD = EF, EF + GH = PPP` (Width = 2)

Base 28 `AB - CD = EF, EF + GH = PPP` (Width = 2)

Base 34 `AB - CD = EF, EF + GH = PPP` (Width = 2)

Base 17 `ABCD - EFGH = IJKL, IJKL + MNOP = QQQQQ` (Width = 4)

Base 21 `ABCD - EFGH = IJKL, IJKL + MNOP = QQQQQ` (Width = 4)

Base 25 `ABCD - EFGH = IJKL, IJKL + MNOP = QQQQQ` (Width = 4)

Base 29 `ABCD - EFGH = IJKL, IJKL + MNOP = QQQQQ` (Width = 4)

...

** You must solve at least 2 of them **

All suggestions are welcome. Just modify this file and PR


text:
static const void *YJBarButtonItemAssociatedTargetKey = &YJBarButtonItemAssociatedTargetKey;

__attribute__((visibility("hidden")))
@interface _YJBarButtonItemTarget : NSObject
@property (nonatomic, copy) void(^actionHandler)(UIBarButtonItem *);
- (instancetype)initWithActionHandler:(void(^)(UIBarButtonItem *barButtonItem))actionHandler;
- (void)invokeActionFromBarButtonItem:(UIBarButtonItem *)barButtonItem;
@end

@implementation _YJBarButtonItemTarget

- (instancetype)initWithActionHandler:(void (^)(UIBarButtonItem *))actionHandler {
    self = [super init];
    if (self) _actionHandler = [actionHandler copy];
    return self;
}

- (void)invokeActionFromBarButtonItem:(UIBarButtonItem *)barButtonItem {
    if (self.actionHandler) self.actionHandler(barButtonItem);
}

#if YJ_DEBUG
- (void)dealloc {
    NSLog(@"%@ dealloc", self.class);
}
#endif

@end

@interface UIBarButtonItem ()
@property (nonatomic, strong) _YJBarButtonItemTarget *yj_target;
@end

@implementation UIBarButtonItem (YJBlockBased)

- (void)setYj_target:(_YJBarButtonItemTarget *)yj_target {
    objc_setAssociatedObject(self, YJBarButtonItemAssociatedTargetKey, yj_target, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (_YJBarButtonItemTarget *)yj_target {
    return objc_getAssociatedObject(self, YJBarButtonItemAssociatedTargetKey);
}

- (instancetype)initWithImage:(nullable UIImage *)image
                        style:(UIBarButtonItemStyle)style
                actionHandler:(nullable void(^)(UIBarButtonItem *sender))actionHandler {
    self.yj_target = [[_YJBarButtonItemTarget alloc] initWithActionHandler:actionHandler];
    return [self initWithImage:image style:style target:self.yj_target action:@selector(invokeActionFromBarButtonItem:)];
}

- (instancetype)initWithImage:(nullable UIImage *)image
          landscapeImagePhone:(nullable UIImage *)landscapeImagePhone
                        style:(UIBarButtonItemStyle)style
                actionHandler:(nullable void(^)(UIBarButtonItem *sender))actionHandler {
    self.yj_target = [[_YJBarButtonItemTarget alloc] initWithActionHandler:actionHandler];
    return [self initWithImage:image landscapeImagePhone:landscapeImagePhone style:style target:self.yj_target action:@selector(invokeActionFromBarButtonItem:)];
}

- (instancetype)initWithTitle:(nullable NSString *)title
                        style:(UIBarButtonItemStyle)style
                  actionHandler:(nullable void(^)(UIBarButtonItem *sender))actionHandler {
    self.yj_target = [[_YJBarButtonItemTarget alloc] initWithActionHandler:actionHandler];
    return [self initWithTitle:title style:style target:self.yj_target action:@selector(invokeActionFromBarButtonItem:)];
}

- (instancetype)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem
                              actionHandler:(nullable void(^)(UIBarButtonItem *sender))actionHandler {
    self.yj_target = [[_YJBarButtonItemTarget alloc] initWithActionHandler:actionHandler];
    return [self initWithBarButtonSystemItem:systemItem target:self.yj_target action:@selector(invokeActionFromBarButtonItem:)];
}

- (void)setActionHandler:(nullable YJBarButtonItemActionHandler)actionHandler {
    self.yj_target = [[_YJBarButtonItemTarget alloc] initWithActionHandler:actionHandler];
}

- (nullable YJBarButtonItemActionHandler)actionHandler {
    return self.yj_target.actionHandler;
}

@end


text:
/*
 * UserSettings store
 *
 */

import { types as T, getParent } from 'mobx-state-tree'

import { markStates } from '@/utils/mobx'

const UserSettings = T.model('UserSettings', {})
  .views((self) => ({
    get root() {
      return getParent(self)
    },
    get curTheme() {
      return self.root.theme.curTheme
    },
    get accountInfo() {
      return self.root.accountInfo
    },
    get isSelfViewing() {
      return self.root.viewing.isSelfViewing
    },
  }))
  .actions((self) => ({
    changeTheme(name) {
      self.root.changeTheme(name)
    },
    updateC11N(option) {
      self.root.updateC11N(option)
    },
    sponsorHepler() {
      self.root.sponsorHepler()
    },
    mark(sobj) {
      markStates(sobj, self)
    },
  }))

export default UserSettings


text:
package org.osc.core.broker.service.tasks.conformance.openstack.securitygroup;

import java.util.Set;

import javax.persistence.EntityManager;

import org.osc.core.broker.job.lock.LockObjectReference;
import org.osc.core.broker.model.entities.appliance.DistributedApplianceInstance;
import org.osc.core.broker.model.entities.appliance.VirtualSystem;
import org.osc.core.broker.model.entities.virtualization.SecurityGroupInterface;
import org.osc.core.broker.model.entities.virtualization.openstack.VMPort;
import org.osc.core.broker.model.plugin.ApiFactoryService;
import org.osc.core.broker.model.sdn.NetworkElementImpl;
import org.osc.core.broker.service.tasks.TransactionalTask;
import org.slf4j.LoggerFactory;
import org.osc.sdk.controller.DefaultInspectionPort;
import org.osc.sdk.controller.DefaultNetworkPort;
import org.osc.sdk.controller.FailurePolicyType;
import org.osc.sdk.controller.TagEncapsulationType;
import org.osc.sdk.controller.api.SdnRedirectionApi;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;

/**
 * This gets called from VmPortHookCheckTask and is tied to a specifc sgi. This should only be called in case of an
 * sdn controller which does NOT support portgroups and SFC.
 */
@Component(service = VmPortHookCreateTask.class)
public class VmPortHookCreateTask extends TransactionalTask {

    private final Logger log = LoggerFactory.getLogger(VmPortHookCreateTask.class);

    @Reference
    private ApiFactoryService apiFactoryService;

    private String vmName;
    private String serviceName;
    private VMPort vmPort;
    private DistributedApplianceInstance dai;
    private SecurityGroupInterface securityGroupInterface;

    public VmPortHookCreateTask create(VMPort vmPort, SecurityGroupInterface securityGroupInterface,
            DistributedApplianceInstance daiToRedirectTo) {
        VmPortHookCreateTask task = new VmPortHookCreateTask();
        task.vmPort = vmPort;
        task.dai = daiToRedirectTo;
        task.securityGroupInterface = securityGroupInterface;
        task.serviceName = securityGroupInterface.getVirtualSystem().getDistributedAppliance().getName();
        task.vmName = vmPort.getVm() != null ? vmPort.getVm().getName() : vmPort.getSubnet().getName();
        task.apiFactoryService = this.apiFactoryService;
        task.dbConnectionManager = this.dbConnectionManager;
        task.txBroadcastUtil = this.txBroadcastUtil;

        return task;
    }

    @Override
    public void executeTransaction(EntityManager em) throws Exception {
        this.vmPort = em.find(VMPort.class, this.vmPort.getId());
        this.dai = em.find(DistributedApplianceInstance.class, this.dai.getId());
        this.securityGroupInterface = em.find(SecurityGroupInterface.class,
                this.securityGroupInterface.getId());
        VirtualSystem vs = this.dai.getVirtualSystem();

        this.log.info(String.format("Creating Inspection Hooks for Security Group Member VM '%s' for service '%s'",
                this.vmName, this.serviceName));
        SdnRedirectionApi controller = this.apiFactoryService.createNetworkRedirectionApi(this.dai);

        try {
            DefaultNetworkPort ingressPort = new DefaultNetworkPort(
                    this.dai.getInspectionOsIngressPortId(),
                    this.dai.getInspectionIngressMacAddress());
            DefaultNetworkPort egressPort = new DefaultNetworkPort(
                    this.dai.getInspectionOsEgressPortId(),
                    this.dai.getInspectionEgressMacAddress());

            TagEncapsulationType encapsulationType = vs.getEncapsulationType() != null
                    ? TagEncapsulationType.valueOf(vs.getEncapsulationType().name()) : null;
            controller.installInspectionHook(new NetworkElementImpl(this.vmPort),
                    new DefaultInspectionPort(ingressPort, egressPort, null), this.securityGroupInterface.getTagValue(),
                    encapsulationType, this.securityGroupInterface.getOrder(),
                    FailurePolicyType.valueOf(this.securityGroupInterface.getFailurePolicyType().name()));
        } finally {
            controller.close();
        }
    }

    @Override
    public String getName() {
        return String.format(
                "Creating Inspection Hooks for Security Group Member VM '%s' to Service '%s' (DAI '%s', MAC: %s)",
                this.vmName, this.serviceName, this.dai.getName(), this.dai.getInspectionIngressMacAddress());
    }

    @Override
    public Set<LockObjectReference> getObjects() {
        return LockObjectReference.getObjectReferences(this.dai);
    }

}


text:
/*
 * Description:
 *     rpc engine implementation
 *
 * Revision history:
 *     Mar., 2015, @imzhenyu (Zhenyu Guo), first version
 *     xxxx-xx-xx, author, fix bug about xxx
 */

# ifdef _WIN32
# include <WinSock2.h>
# else
# include <sys/socket.h>
# include <netdb.h>
# include <ifaddrs.h>
# include <netinet/in.h>
# include <arpa/inet.h>
# endif

# include "rpc_engine.h"
# include "service_engine.h"
# include "group_address.h"
# include <dsn/internal/perf_counters.h>
# include <dsn/internal/factory_store.h>
# include <dsn/internal/task_queue.h>
# include <dsn/cpp/serialization.h>
# include <set>

# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "rpc.engine"

namespace dsn {

    DEFINE_TASK_CODE(LPC_RPC_TIMEOUT, TASK_PRIORITY_COMMON, THREAD_POOL_DEFAULT)

    class rpc_timeout_task : public task, public transient_object
    {
    public:
        rpc_timeout_task(rpc_client_matcher* matcher, uint64_t id, service_node* node)
            : task(LPC_RPC_TIMEOUT, nullptr, nullptr, 0, node)
        {
            _matcher = matcher;
            _id = id;
        }

        virtual void exec()
        {
            _matcher->on_rpc_timeout(_id);
        }

    private:
        // use the following if the matcher is per rpc session
        // rpc_client_matcher_ptr _matcher;

        rpc_client_matcher* _matcher;
        uint64_t            _id;
    };

    rpc_client_matcher::~rpc_client_matcher()
    {
        for (int i = 0; i < MATCHER_BUCKET_NR; i++)
        {
            dassert(_requests[i].size() == 0, "all rpc entries must be removed before the matcher ends");
        }
    }

    bool rpc_client_matcher::on_recv_reply(network* net, uint64_t key, message_ex* reply, int delay_ms)
    {
        rpc_response_task* call;
        task* timeout_task;
        int bucket_index = key % MATCHER_BUCKET_NR;

        {
            utils::auto_lock< ::dsn::utils::ex_lock_nr_spin> l(_requests_lock[bucket_index]);
            auto it = _requests[bucket_index].find(key);
            if (it != _requests[bucket_index].end())
            {
                call = it->second.resp_task;
                timeout_task = it->second.timeout_task;
                timeout_task->add_ref(); // released below in the same function
                _requests[bucket_index].erase(it);
            }
            else
            {
                if (reply)
                {
                    dassert(reply->get_count() == 0,
                        "reply should not be referenced by anybody so far");
                    delete reply;
                }
                return false;
            }
        }

        dbg_dassert(call != nullptr, "rpc response task cannot be empty");
        if (timeout_task != task::get_current_task())
        {
            timeout_task->cancel(false); // no need to wait
        }
        timeout_task->release_ref(); // added above in the same function

        // if rpc is early terminated with empty reply
        if (nullptr == reply)
        {
            call->set_delay(delay_ms);
            // TODO(qinzuoyan): maybe set err as ERR_NETWORK_FAILURE to differ with ERR_TIMEOUT
            call->enqueue(ERR_TIMEOUT, reply);
            call->release_ref(); // added in on_call
            return true;
        }

        // normal reply
        auto err = reply->error();
        auto req = call->get_request();
        auto sp = task_spec::get(req->local_rpc_code);

        // if this is pure client (no server port assigned), we can only do fake forwarding,
        // in this case, the server will return ERR_FORWARD_TO_OTHERS
        if (err == ERR_FORWARD_TO_OTHERS)
        {
            rpc_address addr;
            ::unmarshall((dsn_message_t)reply, addr);

            // TODO(qinzuoyan): handle the case of forwarding to itself where addr == req->to_address.

            // server address side effect
            switch (req->server_address.type())
            {
            case HOST_TYPE_GROUP:
                switch (sp->grpc_mode)
                {
                case GRPC_TO_LEADER:
                    if (req->server_address.group_address()->is_update_leader_on_rpc_forward())
                    {
                        req->server_address.group_address()->set_leader(addr);
                    }
                    break;
                case GRPC_TO_ANY:
                case GRPC_TO_ALL:
                    break;
                }
                break;
            case HOST_TYPE_URI:
                dassert(false, "not implemented");
                break;
            }

            // do fake forwarding, reset request_id
            // TODO(qinzuoyan): reset timeout to new value
            _engine->call_ip(addr, req, call, true);

            dassert(reply->get_count() == 0,
                "reply should not be referenced by anybody so far");
            delete reply;
        }
        else
        {
            // server address side effect
            if (reply->header->context.u.is_forwarded)
            {
                switch (req->server_address.type())
                {
                case HOST_TYPE_GROUP:
                    switch (sp->grpc_mode)
                    {
                    case GRPC_TO_LEADER:
                        if (err == ERR_OK && req->server_address.group_address()->is_update_leader_on_rpc_forward())
                        {
                            req->server_address.group_address()->set_leader(reply->header->from_address);
                        }
                        break;
                    case GRPC_TO_ANY:
                    case GRPC_TO_ALL:
                        break;
                    }
                    break;
                case HOST_TYPE_URI:
                    dassert(false, "not implemented");
                    break;
                }
            }

            // injector
            if (sp->on_rpc_response_enqueue.execute(call, true))
            {
                call->set_delay(delay_ms);

                if (ERR_OK == err)
                    call->enqueue(err, reply);
                else
                {
                    call->enqueue(err, nullptr);

                    // because (1) initially, the ref count is zero
                    //         (2) upper apps may call add_ref already
                    call->add_ref();
                    call->release_ref();
                }
            }

            // release the task when necessary
            else
            {
                ddebug("rpc reply %s is dropped (fault inject), rpc_id = %016llx",
                    reply->header->rpc_name,
                    reply->header->rpc_id
                    );

                // call network failure model
                net->inject_drop_message(reply, false);

                dassert(reply->get_count() == 0,
                    "reply should not be referenced by anybody so far");
                delete reply;

                // because (1) initially, the ref count is zero
                //         (2) upper apps may call add_ref already
                call->add_ref();
                call->release_ref();
            }
        }

        call->release_ref(); // added in on_call
        return true;
    }

    void rpc_client_matcher::on_rpc_timeout(uint64_t key)
    {
        rpc_response_task* call;
        int bucket_index = key % MATCHER_BUCKET_NR;
        uint64_t timeout_ts_ms;
        bool resend = false;

        {
            utils::auto_lock< ::dsn::utils::ex_lock_nr_spin> l(_requests_lock[bucket_index]);
            auto it = _requests[bucket_index].find(key);
            if (it != _requests[bucket_index].end())
            {
                timeout_ts_ms = it->second.timeout_ts_ms;
                call = it->second.resp_task;
                if (timeout_ts_ms == 0)
                {
                    _requests[bucket_index].erase(it);
                }

                // resend is enabled
                else
                {
                    // do it in next check so we can do expensive things
                    // outside of the lock

                    // call may be eliminated from this container and deleted after its execution
                    // we therefore add_ref here
                    call->add_ref();  // released after re-send
                    resend = true;
                }
            }
            else
            {
                return;
            }
        }

        dbg_dassert(call != nullptr,
            "rpc response task is missing for rpc request %" PRIu64, key);

        // if timeout
        if (!resend)
        {
            call->enqueue(ERR_TIMEOUT, nullptr);
            call->release_ref(); // added in on_call
            return;
        }

        // prepare resend context and check again
        uint64_t now_ts_ms = dsn_now_ms();

        // resend when timeout is not yet, and the call is not cancelled
        // TODO: time overflow
        resend = (now_ts_ms < timeout_ts_ms && call->state() == TASK_STATE_READY);

        // TODO: memory pool for this task
        task* new_timeout_task = resend ? new rpc_timeout_task(this, key, call->node()) : nullptr;

        {
            utils::auto_lock< ::dsn::utils::ex_lock_nr_spin> l(_requests_lock[bucket_index]);
            auto it = _requests[bucket_index].find(key);
            if (it != _requests[bucket_index].end())
            {
                // timeout
                if (!resend)
                {
                    _requests[bucket_index].erase(it);
                }

                // resend
                else
                {
                    // reset timeout task
                    it->second.timeout_task = new_timeout_task;
                }
            }

            // response is received
            else
            {
                resend = false;
            }
        }

        if (resend)
        {
            auto req = call->get_request();
            dinfo("resend reqeust message for rpc %" PRIx64 ", key = %" PRIu64,
                req->header->rpc_id, key);

            // resend without handling rpc_matcher, use the same request_id
            _engine->call_ip(req->to_address, req, nullptr);

            // use rest of the timeout to resend once only
            new_timeout_task->set_delay(static_cast<int>(timeout_ts_ms - now_ts_ms));
            new_timeout_task->enqueue();
        }
        else
        {
            if (new_timeout_task)
            {
                delete new_timeout_task;
            }
        }

        call->release_ref(); // added inside the first check of resend
    }

    void rpc_client_matcher::on_call(message_ex* request, rpc_response_task* call)
    {
        task* timeout_task;
        message_header& hdr = *request->header;
        int bucket_index = hdr.id % MATCHER_BUCKET_NR;
        auto sp = task_spec::get(request->local_rpc_code);
        int timeout_ms = hdr.client.timeout_ms;
        uint64_t timeout_ts_ms = 0;

        // reset timeout when resend is enabled
        if (sp->rpc_request_resend_timeout_milliseconds > 0 &&
            timeout_ms > sp->rpc_request_resend_timeout_milliseconds
            )
        {
            timeout_ts_ms = dsn_now_ms() + timeout_ms; // non-zero for resend
            timeout_ms = sp->rpc_request_resend_timeout_milliseconds;
        }

        dbg_dassert(call != nullptr, "rpc response task cannot be empty");
        timeout_task = (new rpc_timeout_task(this, hdr.id, call->node()));

        {
            utils::auto_lock< ::dsn::utils::ex_lock_nr_spin> l(_requests_lock[bucket_index]);
            auto pr = _requests[bucket_index].emplace(hdr.id, match_entry { call, timeout_task, timeout_ts_ms });
            dassert (pr.second, "the message is already on the fly!!!");
        }

        timeout_task->set_delay(timeout_ms);
        timeout_task->enqueue();

        call->add_ref(); // released in on_rpc_timeout or on_recv_reply
    }

    //----------------------------------------------------------------------------------------------
    rpc_server_dispatcher::rpc_server_dispatcher()
    {
        _vhandlers.resize(dsn_task_code_max() + 1);
        for (auto& h : _vhandlers)
        {
            h = new std::pair<rpc_handler_info*, utils::rw_lock_nr>();
            h->first = nullptr;
        }
    }

    bool rpc_server_dispatcher::register_rpc_handler(rpc_handler_info* handler)
    {
        auto name = std::string(dsn_task_code_to_string(handler->code));

        utils::auto_write_lock l(_handlers_lock);
        auto it = _handlers.find(name);
        auto it2 = _handlers.find(handler->name);
        if (it == _handlers.end() && it2 == _handlers.end())
        {
            _handlers[name] = handler;
            _handlers[handler->name] = handler;

            {
                utils::auto_write_lock l(_vhandlers[handler->code]->second);
                _vhandlers[handler->code]->first = handler;
            }
            return true;
        }
        else
        {
            dassert(false, "rpc registration confliction for '%s'", name.c_str());
            return false;
        }
    }

    rpc_handler_info* rpc_server_dispatcher::unregister_rpc_handler(dsn_task_code_t rpc_code)
    {
        rpc_handler_info* ret;
        {
            utils::auto_write_lock l(_handlers_lock);
            auto it = _handlers.find(dsn_task_code_to_string(rpc_code));
            if (it == _handlers.end())
                return nullptr;

            ret = it->second;
            std::string name = it->second->name;
            _handlers.erase(it);
            _handlers.erase(name);

            {
                utils::auto_write_lock l(_vhandlers[rpc_code]->second);
                _vhandlers[rpc_code]->first = nullptr;
            }
        }

        ret->unregister();
        return ret;
    }

    rpc_request_task* rpc_server_dispatcher::on_request(message_ex* msg, service_node* node)
    {
        rpc_handler_info* handler = nullptr;
        auto binary_hash = msg->header->rpc_name_fast.local_hash;
        if (binary_hash == message_ex::s_local_hash && binary_hash != 0)
        {
            msg->local_rpc_code = msg->header->rpc_name_fast.local_rpc_id;

            {
                utils::auto_read_lock l(_vhandlers[msg->local_rpc_code]->second);
                handler = _vhandlers[msg->local_rpc_code]->first;
                if (nullptr != handler)
                {
                    handler->add_ref();
                }
            }
        }
        else
        {
            utils::auto_read_lock l(_handlers_lock);
            auto it = _handlers.find(msg->header->rpc_name);
            if (it != _handlers.end())
            {
                msg->local_rpc_code = it->second->code;
                handler = it->second;
                handler->add_ref();
            }
        }

        return handler ? new rpc_request_task(msg, handler, node) : nullptr;
    }

    //----------------------------------------------------------------------------------------------
    /*static*/ bool rpc_engine::_message_crc_required;

    rpc_engine::rpc_engine(configuration_ptr config, service_node* node)
        : _config(config), _node(node), _rpc_matcher(this)
    {
        dassert (_node != nullptr, "");
        dassert (_config != nullptr, "");

        _is_running = false;
        _message_crc_required = config->get_value<bool>(
            "network", "message_crc_required", false,
            "whether crc is enabled for network messages");
    }

    //
    // management routines
    //
    network* rpc_engine::create_network(
        const network_server_config& netcs,
        bool client_only,
        io_modifer& ctx
        )
    {
        const service_spec& spec = service_engine::fast_instance().spec();
        auto net = utils::factory_store<network>::create(
            netcs.factory_name.c_str(), ::dsn::PROVIDER_TYPE_MAIN, this, nullptr);
        net->reset_parser(netcs.hdr_format, netcs.message_buffer_block_size);

        for (auto it = spec.network_aspects.begin();
            it != spec.network_aspects.end();
            it++)
        {
            net = utils::factory_store<network>::create(it->c_str(), ::dsn::PROVIDER_TYPE_ASPECT, this, net);
        }

        // start the net
        error_code ret = net->start(netcs.channel, netcs.port + ctx.port_shift_value, client_only, ctx);
        if (ret == ERR_OK)
        {
            return net;
        }
        else
        {
            // mem leak, don't care as it halts the program
            dassert(false, "create network failed, error_code: %s", ret.to_string());
            return nullptr;
        }
    }

    error_code rpc_engine::start(
        const service_app_spec& aspec,
        io_modifer& ctx
        )
    {
        if (_is_running)
        {
            return ERR_SERVICE_ALREADY_RUNNING;
        }

        // local cache for shared networks with same provider and message format and port
        std::map<std::string, network*> named_nets; // factory##fmt##port -> net

        // start client networks
        _client_nets.resize(network_header_format::max_value() + 1);

        // for each format
        for (int i = 0; i <= network_header_format::max_value(); i++)
        {
            std::vector<network*>& pnet = _client_nets[i];
            pnet.resize(rpc_channel::max_value() + 1);

            // for each channel
            for (int j = 0; j <= rpc_channel::max_value(); j++)
            {
                rpc_channel c = rpc_channel(rpc_channel::to_string(j));
                std::string factory;
                int blk_size;

                auto it1 = aspec.network_client_confs.find(c);
                if (it1 != aspec.network_client_confs.end())
                {
                    factory = it1->second.factory_name;
                    blk_size = it1->second.message_buffer_block_size;
                }
                else
                {
                    dwarn("network client for channel %s not registered, assuming not used further", c.to_string());
                    continue;
                }

                network_server_config cs(aspec.id, c);

                cs.factory_name = factory;
                cs.message_buffer_block_size = blk_size;
                cs.hdr_format = network_header_format(network_header_format::to_string(i));

                auto net = create_network(cs, true, ctx);
                if (!net) return ERR_NETWORK_INIT_FAILED;
                pnet[j] = net;

                if (ctx.queue)
                {
                    ddebug("[%s.%s] network client started at port %u, channel = %s, fmt = %s ...",
                        node()->name(),
                        ctx.queue->get_name().c_str(),
                        (uint32_t)(cs.port + ctx.port_shift_value),
                        cs.channel.to_string(),
                        cs.hdr_format.to_string()
                        );
                }
                else
                {
                    ddebug("[%s] network client started at port %u, channel = %s, fmt = %s ...",
                        node()->name(),
                        (uint32_t)(cs.port + ctx.port_shift_value),
                        cs.channel.to_string(),
                        cs.hdr_format.to_string()
                        );
                }
            }
        }

        // start server networks
        for (auto& sp : aspec.network_server_confs)
        {
            int port = sp.second.port;

            std::vector<network*>* pnets;
            auto it = _server_nets.find(port);

            if (it == _server_nets.end())
            {
                std::vector<network*> nets;
                auto pr = _server_nets.insert(std::map<int, std::vector<network*>>::value_type(port, nets));
                pnets = &pr.first->second;
                pnets->resize(rpc_channel::max_value() + 1);
            }
            else
            {
                pnets = &it->second;
            }

            auto net = create_network(sp.second, false, ctx);
            if (net == nullptr)
            {
                return ERR_NETWORK_INIT_FAILED;
            }

            (*pnets)[sp.second.channel] = net;

            if (ctx.queue)
            {
                dwarn("[%s.%s] network server started at port %u, channel = %s, fmt = %s ...",
                    node()->name(),
                    ctx.queue->get_name().c_str(),
                    (uint32_t)(port + ctx.port_shift_value),
                    sp.second.channel.to_string(),
                    sp.second.hdr_format.to_string()
                    );
            }
            else
            {
                dwarn("[%s] network server started at port %u, channel = %s, fmt = %s ...",
                    node()->name(),
                    (uint32_t)(port + ctx.port_shift_value),
                    sp.second.channel.to_string(),
                    sp.second.hdr_format.to_string()
                    );
            }
        }

        _local_primary_address = _client_nets[0][0]->address();
        _local_primary_address.c_addr_ptr()->u.v4.port = aspec.ports.size() > 0 ? *aspec.ports.begin() : aspec.id + ctx.port_shift_value;

        ddebug("=== service_node=[%s], primary_address=[%s] ===",
            _node->name(), _local_primary_address.to_string());

        _is_running = true;
        return ERR_OK;
    }

    bool rpc_engine::register_rpc_handler(rpc_handler_info* handler, uint64_t vnid)
    {
        if (0 == vnid)
        {
            return _rpc_dispatcher.register_rpc_handler(handler);
        }
        else
        {
            utils::auto_write_lock l(_vnodes_lock);
            auto it = _vnodes.find(vnid);
            if (it == _vnodes.end())
            {
                auto dispatcher = new rpc_server_dispatcher();
                return _vnodes.insert(
                    std::unordered_map<uint64_t, rpc_server_dispatcher* >::value_type(vnid, dispatcher))
                    .first->second->register_rpc_handler(handler);
            }
            else
            {
                return it->second->register_rpc_handler(handler);
            }
        }
    }

    rpc_handler_info* rpc_engine::unregister_rpc_handler(dsn_task_code_t rpc_code, uint64_t vnid)
    {
        if (0 == vnid)
        {
            return _rpc_dispatcher.unregister_rpc_handler(rpc_code);
        }
        else
        {
            utils::auto_write_lock l(_vnodes_lock);
            auto it = _vnodes.find(vnid);
            if (it == _vnodes.end())
            {
                return nullptr;
            }
            else
            {
                auto r = it->second->unregister_rpc_handler(rpc_code);
                if (0 == it->second->handler_count())
                {
                    delete it->second;
                    _vnodes.erase(it);
                }
                return r;
            }
        }
    }

    void rpc_engine::on_recv_request(network* net, message_ex* msg, int delay_ms)
    {
        rpc_request_task* tsk;
        if (msg->header->vnid == 0)
        {
            tsk = _rpc_dispatcher.on_request(msg, _node);
        }
        else
        {
            utils::auto_read_lock l(_vnodes_lock);
            auto it = _vnodes.find(msg->header->vnid);
            if (it != _vnodes.end())
            {
                tsk = it->second->on_request(msg, _node);
            }
            else
            {
                tsk = nullptr;
            }
        }

        if (tsk == nullptr)
        {
            dwarn(
                "recv unknown message with type %s from %s, rpc_id = %016llx",
                msg->header->rpc_name,
                msg->header->from_address.to_string(),
                msg->header->rpc_id
                );

            dassert(msg->get_count() == 0,
                "request should not be referenced by anybody so far");
            delete msg;
            return;
        }

        // injector
        if (tsk->spec().on_rpc_request_enqueue.execute(tsk, true))
        {
            tsk->set_delay(delay_ms);
            tsk->enqueue();
        }

        // release the task when necessary
        else
        {
            ddebug("rpc request %s is dropped (fault inject), rpc_id = %016llx",
                msg->header->rpc_name,
                msg->header->rpc_id
                );

            // call network failure model
            net->inject_drop_message(msg, false);

            // because (1) initially, the ref count is zero
            //         (2) upper apps may call add_ref already
            tsk->add_ref();
            tsk->release_ref();
        }
    }

    void rpc_engine::call(message_ex* request, rpc_response_task* call)
    {
        auto sp = task_spec::get(request->local_rpc_code);
        auto& hdr = *request->header;

        hdr.from_address = primary_address();
        hdr.rpc_id = dsn_random64(
            std::numeric_limits<decltype(hdr.rpc_id)>::min(),
            std::numeric_limits<decltype(hdr.rpc_id)>::max()
            );
        request->seal(_message_crc_required);

        switch (request->server_address.type())
        {
        case HOST_TYPE_IPV4:
            call_ip(request->server_address, request, call);
            break;
        case HOST_TYPE_URI:
            dassert(false, "uri as host support is to be implemented");
            break;
        case HOST_TYPE_GROUP:
            switch (sp->grpc_mode)
            {
            case GRPC_TO_LEADER:
                // TODO: auto-changed leader
                call_ip(request->server_address.group_address()->possible_leader(), request, call);
                break;
            case GRPC_TO_ANY:
                // TODO: performance optimization
                call_ip(request->server_address.group_address()->random_member(), request, call);
                break;
            case GRPC_TO_ALL:
                dassert(false, "to be implemented");
                break;
            default:
                dassert(false, "invalid group rpc mode %d", (int)(sp->grpc_mode));
            }
            break;
        default:
            dassert(false, "invalid target address type %d", (int)request->server_address.type());
            break;
        }
        return;
    }

    void rpc_engine::call_ip(rpc_address addr, message_ex* request, rpc_response_task* call, bool reset_request_id, bool set_forwarded)
    {
        dbg_dassert(addr.type() == HOST_TYPE_IPV4, "only IPV4 is now supported");
        dbg_dassert(addr.port() > MAX_CLIENT_PORT, "only server address can be called");
        dassert(!request->header->from_address.is_invalid(), "from address must be set before call call_ip");

        while (!request->dl.is_alone())
        {
            dwarn("msg request %s (%" PRIx64 ") is in sending queue, try to pick out ...",
                request->header->rpc_name,
                request->header->rpc_id
                );
            auto s = request->io_session;
            if (s.get() != nullptr)
            {
                s->cancel(request);
            }
        }

        request->to_address = addr;

        auto sp = task_spec::get(request->local_rpc_code);
        auto& hdr = *request->header;
        auto& named_nets = _client_nets[sp->rpc_call_header_format];
        network* net = named_nets[sp->rpc_call_channel];

        dassert(nullptr != net, "network not present for rpc channel '%s' with format '%s' used by rpc %s",
            sp->rpc_call_channel.to_string(),
            sp->rpc_call_header_format.to_string(),
            hdr.rpc_name
            );

        bool need_seal = false;
        if (reset_request_id)
        {
            hdr.id = message_ex::new_id();
            need_seal = true;
        }
        if (set_forwarded && request->header->context.u.is_forwarded == false)
        {
            request->header->context.u.is_forwarded = true;
            need_seal = true;
        }
        if (need_seal)
        {
            request->seal(_message_crc_required);
        }

        // join point and possible fault injection
        if (!sp->on_rpc_call.execute(task::get_current_task(), request, call, true))
        {
            ddebug("rpc request %s is dropped (fault inject), rpc_id = %016llx",
                request->header->rpc_name,
                request->header->rpc_id
                );

            // call network failure model
            net->inject_drop_message(request, true);

            if (call != nullptr)
            {
                call->set_delay(hdr.client.timeout_ms);
                call->enqueue(ERR_TIMEOUT, nullptr);
            }
            else
            {
                // as ref_count for request may be zero
                request->add_ref();
                request->release_ref();
            }

            return;
        }

        if (call != nullptr)
        {
            _rpc_matcher.on_call(request, call);
        }

        net->send_message(request);
    }

    void rpc_engine::reply(message_ex* response, error_code err)
    {
        response->header->server.error = err;
        response->seal(_message_crc_required);

        auto sp = task_spec::get(response->local_rpc_code);
        bool no_fail = sp->on_rpc_reply.execute(task::get_current_task(), response, true);

        auto s = response->io_session.get();

        // connetion oriented network, we have bound session
        if (s != nullptr)
        {
            // not forwarded
            if (!response->header->context.u.is_forwarded)
            {
                if (no_fail)
                {
                    s->send_message(response);
                }
                else
                {
                    s->net().inject_drop_message(response, true);
                }
            }

            // request is forwarded, we cannot use the original rpc session
            else
            {
                dbg_dassert(response->to_address.port() > MAX_CLIENT_PORT,
                    "target address must have named port in this case");

                auto sp = task_spec::get(response->local_rpc_code);
                auto& hdr = *response->header;
                auto& named_nets = _client_nets[sp->rpc_call_header_format];
                network* net = named_nets[sp->rpc_call_channel];

                dassert(nullptr != net, "network not present for rpc channel '%s' with format '%s' used by rpc %s",
                    sp->rpc_call_channel.to_string(),
                    sp->rpc_call_header_format.to_string(),
                    hdr.rpc_name
                    );

                if (no_fail)
                {
                    net->send_message(response);
                }
                else
                {
                    net->inject_drop_message(response, true);
                }
            }
        }

        // not connetion oriented network, we always use the named network to send msgs
        else
        {
            dbg_dassert(response->to_address.port() > MAX_CLIENT_PORT,
                "target address must have named port in this case");

            auto sp = task_spec::get(response->local_rpc_code);
            auto &net = _server_nets[response->header->from_address.port()][sp->rpc_call_channel];
            if (no_fail)
            {
                net->send_message(response);
            }
            else
            {
                net->inject_drop_message(response, true);
            }
        }

        if (!no_fail)
        {
            // because (1) initially, the ref count is zero
            //         (2) upper apps may call add_ref already
            response->add_ref();
            response->release_ref();
        }
    }

    void rpc_engine::forward(message_ex * request, rpc_address address)
    {
        dassert(request->header->context.u.is_request, "only rpc request can be forwarded");

        // msg is from pure client (no server port assigned)
        // in this case, we have no way to directly post a message
        // to it but reusing the current server connection
        // we therefore cannot really do the forwarding but fake it
        if (request->header->from_address.port() <= MAX_CLIENT_PORT)
        {
            auto resp = request->create_response();
            ::marshall(resp, address);
            ::dsn::task::get_current_rpc()->reply(resp, ::dsn::ERR_FORWARD_TO_OTHERS);
        }

        // do real forwarding, not reset request_id, but set forwarded flag
        // TODO(qinzuoyan): reply to client if forwarding failed for non-timeout reason (such as connection denied).
        else
        {
            auto copied_request = request->copy_and_prepare_send();
            call_ip(address, copied_request, nullptr, false, true);
        }
    }
}


text:
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/me.tatarka/bindingcollectionadapter/badge.svg?style=flat)](https://maven-badges.herokuapp.com/maven-central/me.tatarka/bindingcollectionadapter)

Easy way to bind collections to listviews and recyclerviews with the new [Android Data Binding framework](https://developer.android.com/tools/data-binding/guide.html).

## Download

```groovy
compile 'me.tatarka:bindingcollectionadapter:0.8'
```

## Usage

You need to provied your items and an `ItemView` to bind to the layout. You should use an
`ObservableList` to automaticaly update your view based on list changes. However, you can
use any `Collection` if you don't need that functionality.

```java
public class ViewModel {
  public final ObservableList<String> items = new ObservableArrayList<>();
  public final ItemView itemView = ItemView.of(BR.item, R.layout.item);
}
```

Then bind it to the collection view with `app:items` and `app:itemView`. There are also some
convience factories to attach a `LayoutManager` to a `RecyclerView` with `app:layoutManager`.

```xml
<!-- layout.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
      <variable name="viewModel" type="com.example.ViewModel"/>
      <import type="me.tatarka.bindingcollectionadapter.LayoutManagers" />
    </data>

    <ListView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"/>

    <android.support.v7.widget.RecyclerView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:layoutManager="@{LayoutManagers.linear()}"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"/>

    <android.support.v4.view.ViewPager
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:items="@{viewModel.items}"
      app:itemView="@{viewModel.itemView}"/>
</layout>
```

In your item layout, the collection item will be bound to the variable with the
name you passed into the `ItemView`

```xml
<!-- item.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
      <variable name="item" type="String"/>
    </data>

    <TextView
      android:id="@+id/text"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="@{item}"/>
</layout>
```

## Multiple View Types

You can use multiple view types by using a `ItemViewSelector` instead. You can still bind
it to the view with `app:itemView`.

```java
public final ItemViewSelector<String> itemView = new BaseItemViewSelector<String>() {
    @Override
    public void select(ItemView itemView, int position, String item) {
        itemView.set(BR.item, position == 0 ? R.layout.item_header : R.layout.item);
    }

    // This is only needed if you are using a BindingListViewAdapter
    @Override
    public int viewTypeCount() {
      return 2;
    }
};
```

Note that `select` is called many times so you should not do any complex processing in there. If you don't need to bind an item at a specific position (a static footer for example) you can use `ItemView.BINDING_VARIABLE_NONE` as the binding varibale.

## Additonal Adapter Configuration

### BindingListViewAdapter

You can set a callback to give an id for each item in the list with

```java
adapter.setItemIds(new BindingListViewAdapter.ItemIds<T>() {
    @Override
    public long getItemId(int position, T item) {
        return // Calculate item id.
    }
});
```
or by defining `app:itemIds="@{itemIds}"` in the `ListView` in your layout file.

Setting this will make `hasStableIds` return true which can increase performace of data changes.

You can also define a different dropdown view layout by setting

```java
itemView.setLayoutRes(BindingListViewAdapter.DROP_DOWN_LAYOUT, R.layout.item_dropdown);
```

### BindingViewPagerAdapter

You can set a callback to give a page title for each item in the list with

```java
adapter.setPageTitles(new PageTitles<T>() {
    @Override
    public CharSequence getPageTitle(int position, T item) {
        return "Page Title";
    }
});
```
or by defining `app:pageTitles="@{pageTitles}"` in the `ViewPager` in your layout file.

## Directly manipulationg views

Data binding is awesome and all, but you may run into a case where you simply need to manipulate the views directly. You can do this without throwing away the whole of databinding by subclassing an exisiting `BindingCollectionAdapter`. You can then bind `adapter` in your layout to your subclass's class name to have it use that instead. Instead of overriding the nomral adapter methods, you should override `onCreateBinding()` or `onBindBinding()` and call `super` allowing you to run code before and after those events and get access to the item view's binding.

```java
public class MyRecyclerViewAdapter<T> extends BindingRecyclerViewAdapter<T> {
    public LoggingRecyclerViewAdapter(@NonNull ItemView itemView) {
        super(itemView);
    }

    public LoggingRecyclerViewAdapter(@NonNull ItemViewSelector<T> selector) {
        super(selector);
    }

    @Override
    public ViewDataBinding onCreateBinding(LayoutInflater inflater, @LayoutRes int layoutId, ViewGroup viewGroup) {
        ViewDataBinding binding = super.onCreateBinding(inflater, layoutId, viewGroup);
        Log.d(TAG, "created binding: " + binding);
        return binding;
    }

    @Override
    public void onBindBinding(ViewDataBinding binding, int bindingVariable, @LayoutRes int layoutRes, int position, T item) {
        super.onBindBinding(binding, bindingVariable, layoutRes, position, item);
        Log.d(TAG, "bound binding: " + binding + " at position: " + position);
    }
}
```

```xml
<android.support.v7.widget.RecyclerView
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layoutManager="{@LayoutManagers.linear()}"
  app:items="@{viewModel.items}"
  app:itemView="@{viewModel.itemView}"
  app:adapter='@{"com.example.MyRecyclerViewAdapter"}'/>
```

## Known Issues

### Cannot Resolve the libraries `@BindingAdapter`'s

This is likely because you are using the [android-apt](https://bitbucket.org/hvisser/android-apt) plugin which [broke](https://bitbucket.org/hvisser/android-apt/issues/45/breaks-declaring-bindingadapter-in-a) this in previous versions. Update to `1.6+` to fix it.

## License

    Copyright 2015 Evan Tatarka

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense
import keras

# the four different states of the XOR gate
training_data = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], "float32")

# the four expected results in the same order
target_data = np.array([[0], [1], [1], [0]], "float32")

# 2 - 16 - 1
model = Sequential()
model.add(Dense(16, input_dim=2, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

sgd = keras.optimizers.SGD(lr=0.1)

model.compile(loss='mean_squared_error',
              optimizer=sgd,
              metrics=['binary_accuracy'])

model.fit(training_data, target_data, nb_epoch=500, verbose=1)
print(model.predict(training_data).round())


text:
#include "AttrID.h"

// Standard and system DB attributes

namespace Attr
{
	DeclareInt(rowid);
	DeclareInt(ID);
	DeclareStrID(GUID);
}

#endif


text:
package geneticSolver;

import genefighter.Fighter;
import genefighter.FighterUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Trevor on 11/22/2016.
 */
public class NaturalSelection {

    private static Long fitnessThreshold;
    private static Long populationCount;

    public static Population naturallySelectNewGeneration(Population currentGeneration){
        populationCount = currentGeneration.getPopulationCount();
        Population newGeneration = new Population(populationCount);

        System.out.print("victories in generation: " + fitnessThreshold + "\n");

        killUnfitPopulation(currentGeneration);
        breedNewGeneration(currentGeneration, newGeneration);
        mutateNewGeneration(newGeneration);

        resetFitnessThreshold();
        return newGeneration;
    }

    public static void resetFitnessThreshold() {
        fitnessThreshold = 0L;
    }

    private static void mutateNewGeneration(Population newGeneration) {
        for (Fighter populationMember: newGeneration.getPopulationGroup()) {
            Boolean willTypeMutate = (Math.random() * 10) >= 8.5;  //10% + 5% for 1/3 chance that mutate arrives at same result
            Boolean willAttackMutate = (Math.random() * 10) >= 8.99; //10% + .1% for the 1/100 chance that mutate arrives at same result

            if (willTypeMutate) {
                FighterUtils.generateRandomType(populationMember);
            }
            if (willAttackMutate) {
                FighterUtils.generateRandomAttackAndHealth(populationMember);
            }

        }

    }

    private static void breedNewGeneration(Population currentGeneration, Population newGeneration) {
        List<Fighter> newPopulation = new ArrayList<Fighter>();

        for (Fighter populationMember: currentGeneration.getPopulationGroup()) {
            Fighter randomBiasedChild = GenerateChildByAlphaParentBiasedGeneticCrossover(populationMember, currentGeneration.getRandomPopulationMember());
            Fighter parentBiasedChild = GenerateChildByRandomSinglePointGeneticCrossover(populationMember, currentGeneration.getRandomPopulationMember());
            newPopulation.add(randomBiasedChild);
            newPopulation.add(parentBiasedChild);
        }
        newGeneration.setPopulationGroup(newPopulation);
    }

    private static Fighter GenerateChildByAlphaParentBiasedGeneticCrossover(Fighter alphaParent, Fighter betaParent) {
        Fighter child = new Fighter();
        Double attack = (alphaParent.getAttack() * .75) + (betaParent.getAttack() *.25);
        child.setGeneType(alphaParent.getGeneType());
        child.setAttack(attack);
        child.setHealth(FighterUtils.calculateHealthBasedOnAttack(attack));
        return child;
    }

    private static Fighter GenerateChildByRandomSinglePointGeneticCrossover(Fighter alphaParent, Fighter betaParent) {
        Fighter child = new Fighter();
        Double attack = (alphaParent.getAttack() * .5) + (betaParent.getAttack() *.5);
        Boolean isTypeOfAlphaParent = Math.random() < 0.5;
        if(isTypeOfAlphaParent) {
            child.setGeneType(alphaParent.getGeneType());
        } else {
            child.setGeneType(betaParent.getGeneType());
        }
        child.setAttack(attack);
        child.setHealth(FighterUtils.calculateHealthBasedOnAttack(attack));
        return child;
    }

    private static void killUnfitPopulation(Population currentGeneration){
        Iterator<Fighter> populationIterator = currentGeneration.getPopulationGroup().iterator();

        while (populationIterator.hasNext()) {
            Fighter populationMember = populationIterator.next();
            if(populationMember.getFitness() < (fitnessThreshold / populationCount)){
                populationIterator.remove();
            }
        }
    }

    public static void addVictories(Long additionalVictories){fitnessThreshold += additionalVictories;}

}


text:
[![Build Status](https://travis-ci.org/grpc/grpc-java.svg?branch=master)](https://travis-ci.org/grpc/grpc-java)

gRPC-Java - An RPC library and framework
========================================

gRPC-Java works with JDK 6. TLS usage typically requires using Java 8, or Play
Services Dynamic Security Provider on Android. Please see the [Security
Readme](SECURITY.md).

Download
--------

Download [the JAR][]. Or for Maven, add to your `pom.xml`:
```xml
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-all</artifactId>
  <version>0.7.1</version>
</dependency>
```

Or for Gradle, add to your dependencies:
```gradle
compile 'io.grpc:grpc-all:0.7.1'
```

[the JAR]: https://search.maven.org/remote_content?g=io.grpc&a=grpc-all&v=0.7.1

Development snapshots are available in [Sonatypes's snapshot
repository](https://oss.sonatype.org/content/repositories/snapshots/).

For protobuf-based codegen integrated with the Maven build system, you can use
[maven-protoc-plugin][]:
```xml
<pluginRepositories>
  <pluginRepository>
    <releases>
      <updatePolicy>never</updatePolicy>
    </releases>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <id>central</id>
    <name>Central Repository</name>
    <url>https://repo.maven.apache.org/maven2</url>
  </pluginRepository>
  <pluginRepository>
    <id>protoc-plugin</id>
    <url>https://dl.bintray.com/sergei-ivanov/maven/</url>
  </pluginRepository>
</pluginRepositories>
<build>
  <extensions>
    <extension>
      <groupId>kr.motd.maven</groupId>
      <artifactId>os-maven-plugin</artifactId>
      <version>1.2.3.Final</version>
    </extension>
  </extensions>
  <plugins>
    <plugin>
      <groupId>com.google.protobuf.tools</groupId>
      <artifactId>maven-protoc-plugin</artifactId>
      <version>0.4.2</version>
      <configuration>
        <!--
          The version of protoc must match protobuf-java. If you don't depend on
          protobuf-java directly, you will be transitively depending on the
          protobuf-java version that grpc depends on.
        -->
        <protocArtifact>com.google.protobuf:protoc:3.0.0-alpha-2:exe:${os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:0.7.1:exe:${os.detected.classifier}</pluginArtifact>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>compile-custom</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>
```

[maven-protoc-plugin]: http://sergei-ivanov.github.io/maven-protoc-plugin/

For protobuf-based codegen integrated with the Gradle build system, you can use
[protobuf-gradle-plugin][]:
```gradle
apply plugin: 'java'
apply plugin: 'com.google.protobuf'

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.google.protobuf:protobuf-gradle-plugin:0.6.1'
  }
}

protobuf {
  protoc {
    // The version of protoc must match protobuf-java. If you don't depend on
    // protobuf-java directly, you will be transitively depending on the
    // protobuf-java version that grpc depends on.
    artifact = "com.google.protobuf:protoc:3.0.0-alpha-2"
  }
  plugins {
    grpc {
      artifact = 'io.grpc:protoc-gen-grpc-java:0.7.1'
    }
  }
  generateProtoTasks {
    all()*.plugins {
      grpc {}
    }
  }
}
```

[protobuf-gradle-plugin]: https://github.com/google/protobuf-gradle-plugin

How to Build
------------
This section is only necessary if you are making changes to gRPC-Java.

Building requires JDK 8, as our tests use TLS.

grpc-java has a C++ code generation plugin for protoc. Since many Java
developers don't have C compilers installed and don't need to modify the
codegen, the build can skip it. To skip, create the file
`<project-root>/gradle.properties` and add `skipCodegen=true`.

Then, to build, run:
```
$ ./gradlew build
```

To install the artifacts to your Maven local repository for use in your own
project, run:
```
$ ./gradlew install
```

How to Build Code Generation Plugin
-----------------------------------
This section is only necessary if you are making changes to the code
generation. Most users only need to use `skipCodegen=true` as discussed above.

### Build Protobuf
The codegen plugin is C++ code and requires protobuf 3.0.0-alpha-3.1.

For Linux, Mac and MinGW:
```
$ git clone https://github.com/google/protobuf.git
$ cd protobuf
$ git checkout v3.0.0-alpha-3.1
$ ./autogen.sh
$ ./configure
$ make
$ make check
$ sudo make install
```

If you are comfortable with C++ compilation and autotools, you can specify a
``--prefix`` for Protobuf and use ``-I`` in ``CXXFLAGS``, ``-L`` in
``LDFLAGS``, ``LD_LIBRARY_PATH``, and ``PATH`` to reference it. The
environment variables will be used when building grpc-java.

Protobuf installs to ``/usr/local`` by default.

For Visual C++, please refer to the [Protobuf README](https://github.com/google/protobuf/blob/master/vsprojects/readme.txt)
for how to compile Protobuf.

#### Linux and MinGW
If ``/usr/local/lib`` is not in your library search path, you can add it by running:
```
$ sudo sh -c 'echo /usr/local/lib >> /etc/ld.so.conf'
$ sudo ldconfig
```

#### Mac
Some versions of Mac OS X (e.g., 10.10) doesn't have ``/usr/local`` in the
default search paths for header files and libraries. It will fail the build of
the codegen. To work around this, you will need to set environment variables:
```
$ export CXXFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib"
```

### Notes for Visual C++

When building on Windows and VC++, you need to specify project properties for
Gradle to find protobuf:
```
.\gradlew install ^
    -PvcProtobufInclude=C:\path\to\protobuf-3.0.0-alpha-3.1\src ^
    -PvcProtobufLibs=C:\path\to\protobuf-3.0.0-alpha-3.1\vsprojects\Release
```

Since specifying those properties every build is bothersome, you can instead
create ``<project-root>\gradle.properties`` with contents like:
```
vcProtobufInclude=C:\\path\\to\\protobuf-3.0.0-alpha-3.1\\src
vcProtobufLibs=C:\\path\\to\\protobuf-3.0.0-alpha-3.1\\vsprojects\\Release
```

The build script will build the codegen for the same architecture as the Java
runtime installed on your system. If you are using 64-bit JVM, the codegen will
be compiled for 64-bit, that means you must have compiled Protobuf in 64-bit.

### Notes for MinGW on Windows
If you have both MinGW and VC++ installed on Windows, VC++ will be used by
default. To override this default and use MinGW, add ``-PvcDisable=true``
to your Gradle command line or add ``vcDisable=true`` to your
``<project-root>\gradle.properties``.

### Notes for unsupported operating systems
The build script pulls pre-compiled ``protoc`` from Maven Central by default.
We have built ``protoc`` binaries for popular systems, but they may not work
for your system. If ``protoc`` cannot be downloaded or would not run, you can
use the one that has been built by your own, by adding this property to
``<project-root>/gradle.properties``:
```
protoc=/path/to/protoc
```

Navigating Around the Source
----------------------------

Heres a quick readers guide to the code to help folks get started. At a high
level there are three distinct layers to the library: __Stub__, __Channel__ &
__Transport__.

### Stub

The Stub layer is what is exposed to most developers and provides type-safe
bindings to whatever datamodel/IDL/interface you are adapting. gRPC comes with
a [plugin](https://github.com/google/grpc-java/blob/master/compiler) to the
protocol-buffers compiler that generates Stub interfaces out of `.proto` files,
but bindings to other datamodel/IDL should be trivial to add and are welcome.

#### Key Interfaces

[Stream Observer](https://github.com/google/grpc-java/blob/master/stub/src/main/java/io/grpc/stub/StreamObserver.java)

### Channel

The Channel layer is an abstraction over Transport handling that is suitable for
interception/decoration and exposes more behavior to the application than the
Stub layer. It is intended to be easy for application frameworks to use this
layer to address cross-cutting concerns such as logging, monitoring, auth etc.
Flow-control is also exposed at this layer to allow more sophisticated
applications to interact with it directly.

#### Common

* [Metadata - headers & trailers](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/Metadata.java)
* [Status - error code namespace & handling](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/Status.java)

#### Client
* [Channel - client side binding](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/Channel.java)
* [Client Call](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/ClientCall.java)
* [Client Interceptor](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/ClientInterceptor.java)

#### Server
* [Server call handler - analog to Channel on server](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/ServerCallHandler.java)
* [Server Call](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/ServerCall.java)

### Transport

The Transport layer does the heavy lifting of putting & taking bytes off the
wire. The interfaces to it are abstract just enough to allow plugging in of
different implementations. Transports are modeled as `Stream` factories. The
variation in interface between a server Stream and a client Stream exists to
codify their differing semantics for cancellation and error reporting.

Note the transport layer API is considered internal to gRPC and has weaker API
guarantees than the core API under package `io.grpc`.

gRPC comes with tree Transport implementations:

1. The [Netty-based](https://github.com/google/grpc-java/blob/master/netty)
   transport is the main transport implementation based on
   [Netty](http://netty.io). It is for both the client and the server.
2. The [OkHttp-based](https://github.com/google/grpc-java/blob/master/okhttp)
   transport is a lightweight transport based on
   [OkHttp](http://square.github.io/okhttp/). It is mainly for use on Android
   and is for clinet only.
3. The
   [inprocess](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/inprocess)
   transport is for when a server is in the same process as the client. It is
   useful for testing.

#### Common

* [Stream](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/Stream.java)
* [Stream Listener](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/StreamListener.java)

#### Client

* [Client Stream](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/ClientStream.java)
* [Client Stream Listener](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/ClientStreamListener.java)

#### Server

* [Server Stream](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/ServerStream.java)
* [Server Stream Listener](https://github.com/google/grpc-java/blob/master/core/src/main/java/io/grpc/transport/ServerStreamListener.java)

### Examples

Tests showing how these layers are composed to execute calls using protobuf
messages can be found here
https://github.com/google/grpc-java/tree/master/interop-testing/src/main/java/io/grpc/testing/integration


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="update_app_model_prepare">准备下载 %s</string>
    <string name="update_app_model_progress">正在下载 %1$d%2$s</string>
    <string name="update_app_model_success">下载成功(点击安装)</string>
    <string name="update_app_model_error">下载失败(点击浏览器下载)</string>
</resources>


text:
export * from './modules/timeSpanNavigator/actions';
export * from './modules/logs/actions';


text:
var selectedHistory;

function showError(message) {
    document.getElementById("error").style.display = "block";
    document.getElementById("errorMessage").textContent = message;
}

function resetError() {
    document.getElementById("errorMessage").textContent = "";
    document.getElementById("error").style.display = "none";
}

/**
 * Saves given content to file sync
 * @param content String content to publish
 */
function sendClipboard() {
    var content = document.getElementById("clipboard").textContent;
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
        backgroundPage.saveClipboard(content, function(error) {
            if (error) {
                showError("Error syncing clipboard");
            } else {
                resetError();
                showHistory();
            }
        });
    })
}

/**
 * Retrieves and shows clipboard content
 * @param callback Callback function to accept retrieved content
 */
function showClientClipboard() {
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
       backgroundPage.getClientClipboard(function(content) {
           populateClipboardUI(content);
       });
    });
}

/**
 * Populate clipboard content in Clipboard tab
 * @param value Value to populate
 */
function populateClipboardUI(value) {
    document.getElementById('clipboard').textContent = value;
    document.getElementById('sync').style.display = "block";
    resetError();
}

/**
 * Retrieves and shows clipboard history
 */
function showHistory() {
    console.log("showHistory called");
    var ul = document.getElementById("historyList");
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
        backgroundPage.loadHistory(function(history) {
            console.log("after background loadHistory");
            console.log(history);
            if (history.length <= 0) {
                document.getElementById("noHistory").style.display = "block";
                document.getElementById("history").style.display = "none";
            } else {
                document.getElementById("noHistory").style.display = "none";
                document.getElementById("history").style.display = "block";
                ul.innerHTML = '';
                for (var i = 0; i < history.length; i++) {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(history[i].c));
                    if (i == history.length - 1) {
                        li.classList.add('current');
                    }
                    ul.appendChild(li);
                }
            }
            loadCarousel();
        });
    });
}

/**
 * Clear history
 * @param callback
 */
function clearHistory(callback) {
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
        backgroundPage.clearClipboard(function() {
            callback();
        });
    })
}

/**
 * Sets up history carousel and functions
 */
function loadCarousel() {
    var carousel = document.getElementById("carousel");
    var prev = document.getElementById("prev");
    var next = document.getElementById("next");
    var items = carousel.querySelectorAll('.content li');
    var counter = 0;
    var amount = items.length;
    var current = items[0];
    for (var i = 0; i < amount; ++i) {
        if (items[i].classList.contains('current')) {
            current = items[i];
            counter = i;
            break;
        }
    }
    function navigate(direction) {
        current && current.classList.remove('current');
        counter += direction;
        if (counter <= 0) {
            counter = 0;
            prev.disabled = true;
        } else {
            prev.disabled = false;
        }
        if (counter >= amount - 1) {
            counter = amount - 1;
            next.disabled = true;
        } else {
            next.disabled = false;
        }
        current = items[counter];
        if (current) {
            current.classList.add('current');
            selectedHistory = current.textContent;
        }
    }
    next.addEventListener('click', function(ev) {
        navigate(1);
    });
    prev.addEventListener('click', function(ev) {
        navigate(-1);
    });
    if (current) {
        current.classList.add('current');
        selectedHistory = current.textContent;
    }
    navigate(0);
}

/**
 * Perfom initialization once popup is loaded
 */
document.addEventListener('DOMContentLoaded', function() {
    // Add submit listener to clipboard sync
    document.getElementById("clipboardForm").addEventListener("submit", function(event) {
        event.preventDefault();
        sendClipboard();
    });
    // Add submit listener to history copy
    document.getElementById("historyForm").addEventListener("submit", function(event) {
        event.preventDefault();
        chrome.runtime.getBackgroundPage(function(backgroundPage) {
            backgroundPage.copyToClipboard(selectedHistory);
            populateClipboardUI(selectedHistory);
        });
    });
    // Add click listener to history tab
    document.getElementById("historyTabLink").addEventListener("click", function(event) {
       showHistory();
    });
    // Add click listener to help links
    var helpLinks = document.querySelectorAll(".help");
    for (var i = 0; i < helpLinks.length; i++) {
        helpLinks[i].addEventListener("click", function(event) {
            event.preventDefault();
            chrome.tabs.create({url: "http://synclip-app.com#support"});
        });
    }
    // Add click listener to clear history
    document.getElementById("clearHistoryLink").addEventListener("click", function(event) {
        event.preventDefault();
        clearHistory(function() {
            showHistory();
        });
    });
    // Prevent buttons from keeping focus
    var buttons = document.getElementsByClassName("btn");
    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("mousedown", function(event) {
            event.preventDefault();
        })
    }
    // Populate content
    showClientClipboard();
    showHistory();
    // Reset error message
    resetError();
});

/**
 * Repopulate clipboard element on new copy
 */
document.addEventListener('copy', function() {
    var selected = window.getSelection().toString();
    populateClipboardUI(selected);
});


text:
class TyneCore::ApplicationController < ApplicationController
  private
  def load_user
    @user = TyneAuth::User.find_by_username(params[:user])

    add_breadcrumb @user.username, main_app.overview_path(:user => params[:user])
  end

  def load_project
    @project = TyneCore::Project.joins(:user).where(:key => params[:key]).where(:tyne_auth_users => {:username => params[:user]  }).first

    add_breadcrumb @project.name, main_app.backlog_path(:user => params[:user], :key => params[:key])
  end

  def load_issue
    @issue = @project.issues.find_by_number(params[:id])

    add_breadcrumb @issue.key, main_app.issue_path(:user => params[:user], :key => params[:key], :id => params[:id])
  end

  def is_admin_area?
    false
  end
  helper_method :is_admin_area?

  def require_owner
    redirect_to main_app.root_path unless is_owner?
  end

  def is_owner?
    return false unless @project
    @project.owners.map { |x| x.user }.include? current_user
  end
  helper_method :is_owner?

  def is_collaborator?
    return false unless @project

    users = @project.workers.uniq { |x| x.user_id }.map { |x| x.user }
    users.include?(current_user)
  end
  helper_method :is_collaborator?

  def ensure_can_collaborate
    redirect_to main_app.root_path unless is_collaborator?
  end
end


text:
.class public final Landroid/bluetooth/le/TruncatedFilter;
.super Ljava/lang/Object;
.source "TruncatedFilter.java"

# instance fields
.field private final mFilter:Landroid/bluetooth/le/ScanFilter;

.field private final mStorageDescriptors:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/le/ResultStorageDescriptor;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>(Landroid/bluetooth/le/ScanFilter;Ljava/util/List;)V
    .locals 0
    .param p1, "filter"    # Landroid/bluetooth/le/ScanFilter;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/bluetooth/le/ScanFilter;",
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/le/ResultStorageDescriptor;",
            ">;)V"
        }
    .end annotation

    .prologue
    .line 41
    .local p2, "storageDescriptors":Ljava/util/List;, "Ljava/util/List<Landroid/bluetooth/le/ResultStorageDescriptor;>;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 42
    iput-object p1, p0, Landroid/bluetooth/le/TruncatedFilter;->mFilter:Landroid/bluetooth/le/ScanFilter;

    .line 43
    iput-object p2, p0, Landroid/bluetooth/le/TruncatedFilter;->mStorageDescriptors:Ljava/util/List;

    .line 44
    return-void
.end method

# virtual methods
.method public getFilter()Landroid/bluetooth/le/ScanFilter;
    .locals 1

    .prologue
    .line 50
    iget-object v0, p0, Landroid/bluetooth/le/TruncatedFilter;->mFilter:Landroid/bluetooth/le/ScanFilter;

    return-object v0
.end method

.method public getStorageDescriptors()Ljava/util/List;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/le/ResultStorageDescriptor;",
            ">;"
        }
    .end annotation

    .prologue
    .line 57
    iget-object v0, p0, Landroid/bluetooth/le/TruncatedFilter;->mStorageDescriptors:Ljava/util/List;

    return-object v0
.end method


text:
<mvc:View
	controllerName="sap.m.sample.InputSuggestionsCustomFilter.C"
	xmlns:l="sap.ui.layout"
	xmlns:core="sap.ui.core"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns="sap.m">
	<l:VerticalLayout
		class="sapUiContentPadding"
		width="100%">
		<l:content>
			<Label text="Product" labelFor="productInput"/>
			<Input
				id="productInput"
				type="Text"
				placeholder="Enter Product ..."
				showSuggestion="true"
				suggestionItems="{/ProductCollection}" >
				<suggestionItems>
					<core:Item text="{Name}" />
				</suggestionItems>
			</Input>
		</l:content>
	</l:VerticalLayout>
</mvc:View>


text:
Various scripts, sources and notes that I took while learning some language, framework or at online classes.

Vários scripts, fontes e notas tomadas ao aprender uma linguagem, framework ou em aulas online.


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0046_auto_20170411_2253'),
    ]

    operations = [
        migrations.AddField(
            model_name='patient',
            name='esas_alert',
            field=models.IntegerField(default=7),
        ),
    ]


text:
layout: post
microblog: true
category: photo
date: '2016-10-02T12:12:05'
title: ""
slug: '16100212121205'
location: 'Mr. Taka Ramen'
mf-photo:
  - https://cdn.ericalba.com/blog-images/_ig-photos/photos/201610/14c9bfd4aed15ba8db6efb5976ffb937.jpg
---
Spicy Miso Ramen: Chicken and Bonito Fish Broth, Wavy Flat Flour Noodles, Spicy Paste and Oil, Sliced Pork Belly, Ground Pork, Scallions, Bean Sprouts, Soft Boiled Egg, Chives and Cilantro.

Yum 🍜

<img src="https://cdn.ericalba.com/blog-images/_ig-photos/photos/201610/14c9bfd4aed15ba8db6efb5976ffb937.jpg" />


text: From https://github.com/mbostock/d3/wiki


text:
This package is a part of the [`localsync`](https://npmjs.com/package/localsync) monorepo.

- Core utils / TypeScript types for `localsync`.

See [https://github.com/noderaider/localsync] for usage information.


text:
"""Endpoints messages for the Chrome Experience Sampling backend.

These classes define the messages received and sent by the endpoints.
"""

from protorpc import message_types
from protorpc import messages

package = 'ChromeExperienceSampling'

class ResponseMessage(messages.Message):
  question = messages.StringField(1, required=True)
  answer = messages.StringField(2, required=True)

class SurveyMessage(messages.Message):
  survey_type = messages.StringField(1, required=True)
  participant_id = messages.StringField(2, required=True)
  date_taken = message_types.DateTimeField(3, required=True)
  responses = messages.MessageField(ResponseMessage, 4, repeated=True)


text:
<?php
// from https://github.com/krues8dr/SpeedyDelivery/blob/master/speedydelivery.php
// collects tinyletter archive
// released originally under Apache Licence https://github.com/krues8dr/SpeedyDelivery/blob/master/LICENSE
$user = filter_input(INPUT_GET, 'user', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$baseurl ="https://jobs.sgul.ac.uk";
$url = "https://jobs.sgul.ac.uk/vacancies.aspx?cat=-1";
$html_orig = file_get_contents($url);
$html = trim($html_orig);

function main($html)
{
	global $baseurl;
	if ($html)
	{
		$dom = new DOMDocument;
		$dom->preserveWhiteSpace = FALSE;
		$dom->loadHTML($html);
		$xpath = new DomXpath($dom);

		$container =  $xpath->query('//*[@id="maincontentcenter"]')->item(0);
		$entries = $xpath->query('//*[@style="margin-left:15px;"]/ul',$container);

		$jobs = array();
		foreach ($entries as $entry)
		{
			$department = $entry->previousSibling->previousSibling->nodeValue;
			$li = $xpath->query('li',$entry);

			foreach ($li as $job)
			{
				$this_job = array();
				$this_job['department'] = $department;

				$a = $xpath->query('a',$job);
				$href = $a->item(0)->getAttribute('href');
				$title = $a->item(0)->nodeValue;
				$this_job['title'] = $title;
				$this_job['url'] = $baseurl."/".$href;

				$details = jobDetails($this_job['url']);

				$jobs[] = $this_job;

			}
		}
	}

	print_r($jobs);
}

function jobDetails($link)
{
	$details = array();

	return $details();
}

main($html);
?>