text:
#include "wangle/channel/Handler.h"
#include <wangle/bootstrap/ServerBootstrap.h>
#include <wangle/channel/broadcast/BroadcastPool.h>
#include <wangle/channel/broadcast/test/Mocks.h>

using namespace wangle;
using namespace folly;
using namespace testing;

class BroadcastPoolTest : public Test {
 public:
  void SetUp() override {
    addr = std::make_shared<SocketAddress>();
    serverPool = std::make_shared<StrictMock<MockServerPool>>(addr);

    pipelineFactory =
        std::make_shared<StrictMock<MockBroadcastPipelineFactory>>();
    pool = folly::make_unique<BroadcastPool<int, std::string>>(serverPool,
                                                               pipelineFactory);

    startServer();
  }

  void TearDown() override {
    Mock::VerifyAndClear(serverPool.get());
    Mock::VerifyAndClear(pipelineFactory.get());

    serverPool.reset();
    addr.reset();
    pipelineFactory.reset();
    pool.reset();

    stopServer();
  }

 protected:
  class ServerPipelineFactory : public PipelineFactory<DefaultPipeline> {
   public:
    DefaultPipeline::Ptr newPipeline(
        std::shared_ptr<AsyncTransportWrapper> sock) override {
      auto pipeline = DefaultPipeline::create();
      pipeline->addBack(new BytesToBytesHandler());
      pipeline->finalize();
      return pipeline;
    }
  };

  void startServer() {
    server = folly::make_unique<ServerBootstrap<DefaultPipeline>>();
    server->childPipeline(std::make_shared<ServerPipelineFactory>());
    server->bind(0);
    server->getSockets()[0]->getAddress(addr.get());
  }

  void stopServer() {
    server.reset();
  }

  std::unique_ptr<BroadcastPool<int, std::string>> pool;
  std::shared_ptr<StrictMock<MockServerPool>> serverPool;
  std::shared_ptr<StrictMock<MockBroadcastPipelineFactory>> pipelineFactory;
  NiceMock<MockSubscriber<int, std::string>> subscriber;
  std::unique_ptr<ServerBootstrap<DefaultPipeline>> server;
  std::shared_ptr<SocketAddress> addr;
};

TEST_F(BroadcastPoolTest, BasicConnect) {
  // Test simple calls to getHandler()
  std::string routingData1 = "url1";
  std::string routingData2 = "url2";
  BroadcastHandler<int, std::string>* handler1 = nullptr;
  BroadcastHandler<int, std::string>* handler2 = nullptr;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  // No broadcast available for routingData1. Test that a new connection
  // is established and handler created.
  EXPECT_FALSE(pool->isBroadcasting(routingData1));
  pool->getHandler(routingData1)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1 = h;
        handler1->subscribe(&subscriber);
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);
  base->loopOnce(); // Do async connect
  EXPECT_TRUE(handler1 != nullptr);
  EXPECT_TRUE(pool->isBroadcasting(routingData1));

  // Broadcast available for routingData1. Test that the same handler
  // is returned.
  pool->getHandler(routingData1)
      .then([&](BroadcastHandler<int, std::string>* h) {
        EXPECT_TRUE(h == handler1);
      })
      .wait();
  EXPECT_TRUE(pool->isBroadcasting(routingData1));

  // Close the handler. This will delete the pipeline and the broadcast.
  handler1->readEOF(handler1->getContext());
  EXPECT_FALSE(pool->isBroadcasting(routingData1));

  // routingData1 doesn't have an available broadcast now. Test that a
  // new connection is established again and handler created.
  handler1 = nullptr;
  pool->getHandler(routingData1)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1 = h;
        handler1->subscribe(&subscriber);
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);
  base->loopOnce(); // Do async connect
  EXPECT_TRUE(handler1 != nullptr);
  EXPECT_TRUE(pool->isBroadcasting(routingData1));

  // Cleanup
  handler1->readEOF(handler1->getContext());

  // Test that a new connection is established for routingData2 with
  // a new handler created
  EXPECT_FALSE(pool->isBroadcasting(routingData2));
  pool->getHandler(routingData2)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler2 = h;
        handler2->subscribe(&subscriber);
      });
  EXPECT_TRUE(handler2 == nullptr);
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url2")).Times(1);
  base->loopOnce(); // Do async connect
  EXPECT_TRUE(handler2 != nullptr);
  EXPECT_TRUE(handler2 != handler1);
  EXPECT_TRUE(pool->isBroadcasting(routingData2));

  // Cleanup
  handler2->readEOF(handler2->getContext());
}

TEST_F(BroadcastPoolTest, OutstandingConnect) {
  // Test with multiple getHandler() calls for the same routing data
  // when a connect request is in flight
  std::string routingData = "url1";
  BroadcastHandler<int, std::string>* handler1 = nullptr;
  BroadcastHandler<int, std::string>* handler2 = nullptr;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  // No broadcast available for routingData. Kick off a connect request.
  EXPECT_FALSE(pool->isBroadcasting(routingData));
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1 = h;
        handler1->subscribe(&subscriber);
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Invoke getHandler() for the same routing data when a connect request
  // is outstanding
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler2 = h;
        handler2->subscribe(&subscriber);
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_TRUE(handler2 == nullptr);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);

  base->loopOnce(); // Do async connect

  // Verify that both promises are fulfilled
  EXPECT_TRUE(handler1 != nullptr);
  EXPECT_TRUE(handler2 != nullptr);
  EXPECT_TRUE(handler1 == handler2);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Invoke getHandler() again to test if the same handler is returned
  // from the existing connection
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        EXPECT_TRUE(h == handler1);
      })
      .wait();
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Cleanup
  handler1->readEOF(handler1->getContext());
}

TEST_F(BroadcastPoolTest, ConnectError) {
  // Test when an exception occurs during connect request
  std::string routingData = "url1";
  BroadcastHandler<int, std::string>* handler1 = nullptr;
  BroadcastHandler<int, std::string>* handler2 = nullptr;
  bool handler1Error = false;
  bool handler2Error = false;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  // Stop the server to inject connect failure
  stopServer();

  // No broadcast available for routingData. Kick off a connect request.
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1 = h;
      })
      .onError([&] (const std::exception& ex) {
        handler1Error = true;
        EXPECT_FALSE(pool->isBroadcasting(routingData));
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_FALSE(handler1Error);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Invoke getHandler() again while the connect request is in flight
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler2 = h;
      })
      .onError([&] (const std::exception& ex) {
        handler2Error = true;
        EXPECT_FALSE(pool->isBroadcasting(routingData));
      });
  EXPECT_TRUE(handler2 == nullptr);
  EXPECT_FALSE(handler2Error);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  base->loopOnce(); // Do async connect

  // Verify that the exception is set on both promises
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_TRUE(handler2 == nullptr);
  EXPECT_TRUE(handler1Error);
  EXPECT_TRUE(handler2Error);

  // The broadcast should have been deleted now
  EXPECT_FALSE(pool->isBroadcasting(routingData));

  // Start the server now. Connect requests should succeed.
  startServer();
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1 = h;
        handler1->subscribe(&subscriber);
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);
  base->loopOnce(); // Do async connect
  EXPECT_TRUE(handler1 != nullptr);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Cleanup
  handler1->readEOF(handler1->getContext());
}

TEST_F(BroadcastPoolTest, ConnectErrorServerPool) {
  // Test when an error occurs in ServerPool when trying to kick off
  // a connect request
  std::string routingData = "url1";
  BroadcastHandler<int, std::string>* handler1 = nullptr;
  BroadcastHandler<int, std::string>* handler2 = nullptr;
  bool handler1Error = false;
  bool handler2Error = false;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  // Inject a ServerPool error
  serverPool->failConnect();
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1 = h;
      })
      .onError([&] (const std::exception& ex) {
        handler1Error = true;
        EXPECT_FALSE(pool->isBroadcasting(routingData));
      });
  EXPECT_TRUE(handler1 == nullptr);
  EXPECT_TRUE(handler1Error);
  EXPECT_FALSE(pool->isBroadcasting(routingData));
}

TEST_F(BroadcastPoolTest, RoutingDataException) {
  // Test when an exception occurs while setting routing data on
  // the pipeline after the socket connect succeeds.
  std::string routingData = "url";
  BroadcastHandler<int, std::string>* handler = nullptr;
  bool handlerError = false;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  EXPECT_FALSE(pool->isBroadcasting(routingData));
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler = h;
      })
      .onError([&] (const std::exception& ex) {
        handlerError = true;
        EXPECT_FALSE(pool->isBroadcasting(routingData));
      });
  EXPECT_TRUE(handler == nullptr);
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url"))
      .WillOnce(Throw(std::exception()));
  base->loopOnce(); // Do async connect
  EXPECT_TRUE(handler == nullptr);
  EXPECT_TRUE(handlerError);
  EXPECT_FALSE(pool->isBroadcasting(routingData));
}

TEST_F(BroadcastPoolTest, HandlerEOFPoolDeletion) {
  // Test against use-after-free on BroadcastManager when the pool
  // is deleted before the handler
  std::string routingData = "url1";
  BroadcastHandler<int, std::string>* handler = nullptr;
  DefaultPipeline* pipeline = nullptr;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  // Dispatch a connect request and create a handler
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler = h;
        handler->subscribe(&subscriber);
        pipeline = dynamic_cast<DefaultPipeline*>(
            handler->getContext()->getPipeline());
      });
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);
  base->loopOnce(); // Do async connect
  EXPECT_TRUE(pool->isBroadcasting(routingData));
  EXPECT_TRUE(handler != nullptr);
  EXPECT_TRUE(pipeline != nullptr);

  EXPECT_CALL(subscriber, onCompleted()).Times(1);

  // This will also delete the pipeline and the handler
  pipeline->readEOF();
  EXPECT_FALSE(pool->isBroadcasting(routingData));
}

TEST_F(BroadcastPoolTest, SubscriberDeletionBeforeConnect) {
  // Test when the caller goes away before connect request returns
  // resulting in a new BroadcastHandler without any subscribers
  std::string routingData = "url1";
  BroadcastHandler<int, std::string>* handler = nullptr;
  bool handler1Connected = false;
  bool handler2Connected = false;
  auto base = EventBaseManager::get()->getEventBase();

  InSequence dummy;

  // No broadcast available for routingData. Kick off a connect request.
  EXPECT_FALSE(pool->isBroadcasting(routingData));
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1Connected = true;
        // Do not subscribe to the handler. This will simulate
        // the caller going away before we get here.
      });
  EXPECT_FALSE(handler1Connected);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Invoke getHandler() for the same routing data when a connect request
  // is outstanding
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler2Connected = true;
        // Do not subscribe to the handler.
      });
  EXPECT_FALSE(handler2Connected);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);

  base->loopOnce(); // Do async connect

  // Verify that both promises are fulfilled, but the broadcast is
  // deleted from the pool because no subscriber was added.
  EXPECT_TRUE(handler1Connected);
  EXPECT_TRUE(handler2Connected);
  EXPECT_FALSE(pool->isBroadcasting(routingData));

  // Test test same scenario but with one subscriber going away
  // sooner, but another subscriber being added to the handler.
  handler1Connected = false;
  handler2Connected = false;
  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler1Connected = true;
        // Do not subscribe to the handler. This will simulate
        // the caller going away before we get here.
      });
  EXPECT_FALSE(handler1Connected);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  pool->getHandler(routingData)
      .then([&](BroadcastHandler<int, std::string>* h) {
        handler2Connected = true;
        // Subscriber to the handler. The handler should stick around now.
        handler = h;
        handler->subscribe(&subscriber);
      });
  EXPECT_FALSE(handler2Connected);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  EXPECT_CALL(*pipelineFactory, setRoutingData(_, "url1")).Times(1);

  base->loopOnce(); // Do async connect

  // Verify that both promises are fulfilled, but the broadcast is
  // deleted from the pool because no subscriber was added.
  EXPECT_TRUE(handler1Connected);
  EXPECT_TRUE(handler2Connected);
  EXPECT_TRUE(pool->isBroadcasting(routingData));

  // Cleanup
  handler->readEOF(handler->getContext());
}

TEST_F(BroadcastPoolTest, ThreadLocalPool) {
  // Test that thread-local broadcast pool works correctly
  MockObservingPipelineFactory factory1(serverPool, pipelineFactory);
  MockObservingPipelineFactory factory2(serverPool, pipelineFactory);
  BroadcastHandler<int, std::string>* broadcastHandler = nullptr;
  const std::string kUrl = "url";

  InSequence dummy;

  // There should be no broadcast available for this routing data
  EXPECT_FALSE(factory1.broadcastPool()->isBroadcasting(kUrl));
  EXPECT_FALSE(factory2.broadcastPool()->isBroadcasting(kUrl));

  // Test creating a new broadcast
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, kUrl))
      .WillOnce(Invoke([&](DefaultPipeline* pipeline, const std::string&) {
        broadcastHandler = pipelineFactory->getBroadcastHandler(pipeline);
      }));
  auto pipeline1 = factory1.newPipeline(nullptr, kUrl, nullptr, nullptr);
  pipeline1->transportActive();
  EventBaseManager::get()->getEventBase()->loopOnce();
  EXPECT_TRUE(factory1.broadcastPool()->isBroadcasting(kUrl));
  EXPECT_FALSE(factory2.broadcastPool()->isBroadcasting(kUrl));

  // Test broadcast with the same routing data in the same thread. No
  // new broadcast handler should be created.
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, _)).Times(0);
  auto pipeline2 = factory1.newPipeline(nullptr, kUrl, nullptr, nullptr);
  pipeline2->transportActive();
  EXPECT_TRUE(factory1.broadcastPool()->isBroadcasting(kUrl));
  EXPECT_FALSE(factory2.broadcastPool()->isBroadcasting(kUrl));

  // Test creating a broadcast with the same routing data but in a
  // different thread. Should return a different broadcast handler.
  std::thread([&] {
    // There should be no broadcast available for this routing data since we
    // are on a different thread.
    EXPECT_FALSE(factory1.broadcastPool()->isBroadcasting(kUrl));
    EXPECT_FALSE(factory2.broadcastPool()->isBroadcasting(kUrl));

    EXPECT_CALL(*pipelineFactory, setRoutingData(_, kUrl))
        .WillOnce(Invoke([&](DefaultPipeline* pipeline, const std::string&) {
          EXPECT_NE(pipelineFactory->getBroadcastHandler(pipeline),
                    broadcastHandler);
        }));
    auto pipeline3 = factory1.newPipeline(nullptr, kUrl, nullptr, nullptr);
    pipeline3->transportActive();
    EventBaseManager::get()->getEventBase()->loopOnce();
    EXPECT_TRUE(factory1.broadcastPool()->isBroadcasting(kUrl));
    EXPECT_FALSE(factory2.broadcastPool()->isBroadcasting(kUrl));

    // Cleanup
    pipeline3->readEOF();
  }).join();

  // Test creating a broadcast with the same routing data but using a
  // different ObservingPipelineFactory. Should return a different broadcast
  // handler since a different thread-local BroadcastPool is used.
  EXPECT_CALL(*pipelineFactory, setRoutingData(_, kUrl))
      .WillOnce(Invoke([&](DefaultPipeline* pipeline, const std::string&) {
        EXPECT_NE(pipelineFactory->getBroadcastHandler(pipeline),
                  broadcastHandler);
      }));
  auto pipeline4 = factory2.newPipeline(nullptr, kUrl, nullptr, nullptr);
  pipeline4->transportActive();
  EventBaseManager::get()->getEventBase()->loopOnce();
  EXPECT_TRUE(factory2.broadcastPool()->isBroadcasting(kUrl));

  // Cleanup
  pipeline1->readEOF();
  pipeline2->readEOF();
  pipeline4->readEOF();
}


text:
package grpc

import (
	"context"
	"crypto/tls"

	"go-micro.dev/v4/client"
	"google.golang.org/grpc"
	"google.golang.org/grpc/encoding"
)

var (
	// DefaultPoolMaxStreams maximum streams on a connectioin
	// (20)
	DefaultPoolMaxStreams = 20

	// DefaultPoolMaxIdle maximum idle conns of a pool
	// (50)
	DefaultPoolMaxIdle = 50

	// DefaultMaxRecvMsgSize maximum message that client can receive
	// (4 MB).
	DefaultMaxRecvMsgSize = 1024 * 1024 * 4

	// DefaultMaxSendMsgSize maximum message that client can send
	// (4 MB).
	DefaultMaxSendMsgSize = 1024 * 1024 * 4
)

type poolMaxStreams struct{}
type poolMaxIdle struct{}
type codecsKey struct{}
type tlsAuth struct{}
type maxRecvMsgSizeKey struct{}
type maxSendMsgSizeKey struct{}
type grpcDialOptions struct{}
type grpcCallOptions struct{}

// maximum streams on a connectioin
func PoolMaxStreams(n int) client.Option {
	return func(o *client.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, poolMaxStreams{}, n)
	}
}

// maximum idle conns of a pool
func PoolMaxIdle(d int) client.Option {
	return func(o *client.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, poolMaxIdle{}, d)
	}
}

// gRPC Codec to be used to encode/decode requests for a given content type
func Codec(contentType string, c encoding.Codec) client.Option {
	return func(o *client.Options) {
		codecs := make(map[string]encoding.Codec)
		if o.Context == nil {
			o.Context = context.Background()
		}
		if v := o.Context.Value(codecsKey{}); v != nil {
			codecs = v.(map[string]encoding.Codec)
		}
		codecs[contentType] = c
		o.Context = context.WithValue(o.Context, codecsKey{}, codecs)
	}
}

// AuthTLS should be used to setup a secure authentication using TLS
func AuthTLS(t *tls.Config) client.Option {
	return func(o *client.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, tlsAuth{}, t)
	}
}

//
// MaxRecvMsgSize set the maximum size of message that client can receive.
//
func MaxRecvMsgSize(s int) client.Option {
	return func(o *client.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, maxRecvMsgSizeKey{}, s)
	}
}

//
// MaxSendMsgSize set the maximum size of message that client can send.
//
func MaxSendMsgSize(s int) client.Option {
	return func(o *client.Options) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, maxSendMsgSizeKey{}, s)
	}
}

//
// DialOptions to be used to configure gRPC dial options
//
func DialOptions(opts ...grpc.DialOption) client.CallOption {
	return func(o *client.CallOptions) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, grpcDialOptions{}, opts)
	}
}

//
// CallOptions to be used to configure gRPC call options
//
func CallOptions(opts ...grpc.CallOption) client.CallOption {
	return func(o *client.CallOptions) {
		if o.Context == nil {
			o.Context = context.Background()
		}
		o.Context = context.WithValue(o.Context, grpcCallOptions{}, opts)
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Etu\Module\CovoitBundle\Form;

use Doctrine\ORM\EntityRepository;
use Etu\Core\CoreBundle\Form\DatePickerType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\Form\FormBuilderInterface;

class SearchType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->setMethod('get')
            ->add('startCity', EntityType::class, [
                'label' => 'covoit.search.start_city',
                'required' => false,
                'class' => 'EtuCoreBundle:City',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c')->orderBy('c.name', 'ASC');
                },
            ])
            ->add('endCity', EntityType::class, [
                'label' => 'covoit.search.end_city',
                'required' => false,
                'class' => 'EtuCoreBundle:City',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c')->orderBy('c.name', 'ASC');
                },
            ])
            ->add('date', DatePickerType::class, ['label' => 'covoit.search.date', 'required' => false])
            ->add('dateBeforeAfter', CheckboxType::class, ['label' => 'covoit.search.date_before_after', 'required' => false])
            ->add('priceMax', null, ['label' => 'covoit.search.price_max', 'required' => false])
            ->add('placesLeft', IntegerType::class, ['label' => 'covoit.search.places_left', 'required' => false])
            ->add('hourMin', TimeType::class, ['label' => 'covoit.search.hour_min', 'minutes' => range(0, 55, 5), 'required' => false])
            ->add('hourMax', TimeType::class, ['label' => 'covoit.search.hour_max', 'minutes' => range(0, 55, 5), 'required' => false])
            ->add('keywords', TextType::class, ['label' => 'covoit.search.keywords', 'required' => false])
            ->add('olds', CheckboxType::class, ['label' => 'covoit.search.olds', 'required' => false]);
    }
}


text:
import traceback

import six
import web

from nailgun.api.v1.handlers.base import BaseHandler
from nailgun.api.v1.handlers.base import content
from nailgun.api.v1.handlers.base import SingleHandler
from nailgun.api.v1.validators.openstack_config import OpenstackConfigValidator
from nailgun.errors import errors
from nailgun.logger import logger
from nailgun import objects
from nailgun.task.manager import OpenstackConfigTaskManager

class OpenstackConfigCollectionHandler(BaseHandler):

    validator = OpenstackConfigValidator

    @content
    def GET(self):
        """Returns list of filtered config objects.

        :http: * 200 (OK)
               * 400 (Invalid query specified)
        :return: List of config objects in JSON format.
        """
        data = self.checked_data(
            self.validator.validate_query, data=web.input())
        return objects.OpenstackConfigCollection.to_json(
            objects.OpenstackConfigCollection.filter_by(None, **data))

    @content
    def POST(self):
        """Creates new config object.

        If config object with specified parameters exists, it is replaced
        with a new config object. Previous object is marked as inactive.
        It can be retrieved to track the history of configuration changes.

        :http: * 201 (Object successfully created)
               * 400 (Invalid query specified)
               * 404 (Object dependencies not found)
        :reutrn: New config object in JSON format.
        """
        data = self.checked_data()
        obj = objects.OpenstackConfig.create(data)
        raise self.http(201, objects.OpenstackConfig.to_json(obj))

class OpenstackConfigHandler(SingleHandler):

    single = objects.OpenstackConfig
    validator = OpenstackConfigValidator

    @content
    def PUT(self, obj_id):
        """Update an existing configuration is not allowed

        :http: * 405 (Method not allowed)
        """
        raise self.http(405)

    @content
    def DELETE(self, obj_id):
        """:returns: Empty string

        :http: * 204 (object successfully deleted)
               * 400 (object is already deleted)
               * 404 (object not found in db)
        """
        obj = self.get_object_or_404(
            self.single,
            obj_id
        )

        self.checked_data(
            self.validator.validate_delete,
            instance=obj
        )

        try:
            self.single.disable(obj)
        except errors.CannotUpdate as exc:
            raise self.http(400, exc.message)

        raise self.http(204)

class OpenstackConfigExecuteHandler(BaseHandler):

    validator = OpenstackConfigValidator
    task_manager = OpenstackConfigTaskManager

    @content
    def PUT(self):
        """Executes update tasks for specified resources.

        :http: * 200 (OK)
               * 202 (Accepted)
               * 400 (Invalid data)
               * 404 (Object dependencies not found)
        """
        filters = self.checked_data(self.validator.validate_execute)

        cluster = self.get_object_or_404(
            objects.Cluster, filters['cluster_id'])

        # Execute upload task for nodes
        task_manager = self.task_manager(cluster_id=cluster.id)
        try:
            task = task_manager.execute(filters)
        except Exception as exc:
            logger.warn(
                u'Cannot execute %s task nodes: %s',
                self.task_manager.__name__, traceback.format_exc())
            raise self.http(400, six.text_type(exc))

        self.raise_task(task)


text:
====================
Client API Reference
====================

Currently, the Kurento project provides implementations of the :doc:`/features/kurento_protocol` for two programming languages: *Java* and *JavaScript*.

In the future, additional Kurento Clients can be created, exposing the same kind of modularity in other languages such as Python, C/C++, PHP, etc.

Java Client
===========

**Kurento Java Client** is a Java SE layer which consumes the Kurento API and exposes its capabilities through a simple-to-use interface based on Java POJOs representing Media Elements and Media Pipelines. Using the Kurento Java Client only requires adding the appropriate dependency to a *Maven* project or to download the corresponding *jar* into the application's *Java Classpath*.

* **Reference**: `Kurento Client JavaDoc <../_static/client-javadoc/index.html>`__.

JavaScript Client
=================

**Kurento JavaScript Client** is a JavaScript layer which consumes the Kurento API and exposes its capabilities to JavaScript developers. It allow to build *Node.js* and browser-based applications.

* **Reference**: `Kurento Client JsDoc <../_static/client-jsdoc/index.html>`__.

Kurento Js Utils
================

`kurento-utils-js <https://github.com/Kurento/kurento-utils-js>`__ is a browser library that can be used to simplify creation and handling of `RTCPeerConnection <https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection>`__ objects, to control the browser's `WebRTC API <https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API>`__.

.. warning::

   This library is not actively maintained. It was written to simplify the :doc:`Kurento Tutorials </user/tutorials>` and has several shortcomings for more advanced uses.

   For real-world applications we recommend to **avoid using this library**  and instead to write your JavaScript code directly against the browser's WebRTC API.

* **Reference**: `kurento-utils-js JsDoc <../_static/utils-jsdoc/index.html>`__.


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**_previous_id** | **integer** |  | [optional] [default to null]
**_before_id** | **integer** |  | [optional] [default to null]
**contacts** | **array[integer]** |  | [optional] [default to null]
**tags** | **array[integer]** |  | [optional] [default to null]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
package db

import (
	"testing"
	"time"

	"github.com/stretchr/testify/suite"
)

type StateTestSuite struct {
	suite.Suite
}

func TestStateTestSuite(t *testing.T) {
	suite.Run(t, new(StateTestSuite))
}

func (s *StateTestSuite) TestElapsedTime() {
	t := new(Task)
	s.Equal(t.ElapsedTime(), time.Duration(0))

	t.Start()
	s.True(t.ElapsedTime() > time.Duration(0))

	t.End()
	s.Equal(t.ElapsedTime(), t.EndTime.Sub(*t.StartTime))
}


text:
class CustomTab < ApplicationRecord
  belongs_to :team
  has_many :custom_filters, dependent: :destroy

  validates :heading, presence: true
end


text:
package com.hazelcast.simulator.utils;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.lang.management.ManagementFactory;

public final class NativeUtils {

    private static final Logger LOGGER = Logger.getLogger(NativeUtils.class);

    private NativeUtils() {
    }

    public static String execute(String command) {
        return new BashCommand(command).execute();
    }

    public static String execute(String command, boolean throwException) {
        return new BashCommand(command)
                .setThrowsException(throwException)
                .execute();
    }

    public static void kill(int pid) {
        LOGGER.info("Sending -9 signal to PID " + pid);
        try {
            Runtime.getRuntime().exec("/bin/kill -9 " + pid + " >/dev/null");
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * http://stackoverflow.com/questions/35842/how-can-a-java-program-get-its-own-process-id
     *
     * @return the PID of this JVM or <tt>-1</tt> if not PID was retrieved
     */
    public static int getPID() {
        Integer pid = getPidFromManagementBean();
        if (pid != null) {
            return pid;
        }
        pid = getPidViaReflection();
        if (pid != null) {
            return pid;
        }
        return -1;
    }

    static Integer getPidFromManagementBean() {
        String name = ManagementFactory.getRuntimeMXBean().getName();
        return getPidFromBeanString(name);
    }

    static Integer getPidFromBeanString(String name) {
        int indexOf = name.indexOf('@');
        if (indexOf == -1) {
            return null;
        }
        String pidString = name.substring(0, indexOf);
        try {
            return Integer.parseInt(pidString);
        } catch (NumberFormatException e) {
            LOGGER.warn(e);
            return null;
        }
    }

    static Integer getPidViaReflection() {
        try {
            java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
            java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
            jvm.setAccessible(true);
            sun.management.VMManagement management = (sun.management.VMManagement) jvm.get(runtime);
            java.lang.reflect.Method pidMethod = management.getClass().getDeclaredMethod("getProcessId");
            pidMethod.setAccessible(true);

            return (Integer) pidMethod.invoke(management);
        } catch (Exception e) {
            LOGGER.warn(e);
            return null;
        }
    }
}


text:
package integration

import (
	"testing"
	wyc "github.com/voidshard/wysteria/client"
)

func TestDeleteResource(t *testing.T) {
	// arrange
	client := newClient(t)
	defer client.Close()

	collection, err := client.CreateCollection(randomString())
	if err != nil {
		t.Skip(err)
	}

	item, err := collection.CreateItem("foo", "bar")
	if err != nil {
		t.Skip(err)
	}

	version, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	resource, err := version.AddResource("a","b", "c")
	if err != nil {
		t.Error(err)
	}

	// act
	err = resource.Delete()
	if err != nil {
		t.Error(err)
	}

	found, err := client.Search(wyc.Id(resource.Id())).FindResources()
	if err != nil {
		t.Error(err)
	}

	// assert
	if len(found) != 0 {
		t.Error("Expected not to find anything, found", len(found), "resource(s)")
	}

}

func TestResourceGetParent(t *testing.T) {
	// arrange
	client := newClient(t)
	defer client.Close()

	collection, err := client.CreateCollection(randomString())
	if err != nil {
		t.Skip(err)
	}

	item, err := collection.CreateItem("foo", "bar")
	if err != nil {
		t.Skip(err)
	}

	version, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	resource, err := version.AddResource("a", "b", "c")
	if err != nil {
		t.Error(err)
	}

	// act
	parent, err := resource.Parent()
	if err != nil {
		t.Error(err)
	}

	// assert
	if parent.Id() != version.Id() {
		t.Error("Expected version with id", version.Id(), "got", parent.Id())
	}
}

func TestResourceSetFacets(t *testing.T) {
	// arrange
	client := newClient(t)
	defer client.Close()

	collection, err := client.CreateCollection(randomString())
	if err != nil {
		t.Skip(err)
	}

	item, err := collection.CreateItem("foo", "bar")
	if err != nil {
		t.Skip(err)
	}

	version, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	resource, err := version.AddResource("a", "b", "c")
	if err != nil {
		t.Error(err)
	}

	cases := []struct{
		Facets map[string]string
	} {
		{map[string]string{"a": "b"}},
		{ map[string]string{"a": "b", "q": "iuhuifawd"}},
		{ map[string]string{"foobar": "/oiaow./awd/adw"}},
		{ map[string]string{"foobar": "/daw./awd/adw", "zee": "moo"}},
	}

	expected := map[string]string{}

	// act
	for i, tst := range cases {
		for k, v := range tst.Facets {
			expected[k] = v
		}

		err = resource.SetFacets(tst.Facets)
		if err != nil {
			t.Error(i, err)
		}

		tmp, err := client.Search(wyc.Id(resource.Id())).FindResources(wyc.Limit(2))
		if err != nil {
			t.Error(i, err)
		}
		if len(tmp) != 1 {
			t.Error(i, "Expected 1 resource with id", resource.Id(), "got", len(tmp))
		}
		remote := tmp[0]

		//  assert
		if !facetsContain(tst.Facets, resource.Facets()) {
			t.Error(i, "Expected", resource.Facets(), "to contain", tst.Facets)
		}

		if !facetsContain(tst.Facets, remote.Facets()) {
			t.Error(i, "[remote] Expected", remote.Facets(), "to contain", tst.Facets)
		}
	}
}

func TestCreateResourceFailsWithDuplicateSettings(t *testing.T) {
	// arrange
	client := newClient(t)
	defer client.Close()

	collection, err := client.CreateCollection(randomString())
	if err != nil {
		t.Skip(err)
	}

	item, err := collection.CreateItem("foo", "bar")
	if err != nil {
		t.Skip(err)
	}

	version1, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	version2, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	rname := "name"
	rtype := "type"
	rloc := "location"

	// act & assert
	_, err = version1.AddResource(rname, rtype, rloc)
	if err != nil {
		t.Error(err)
	}

	_, err = version1.AddResource(rname, rtype, rloc)
	if err == nil {
		t.Error("Expected duplicate resource fail", version1.Id(), rname, rtype, rloc)
	}

	_, err = version2.AddResource(rname, rtype, rloc)
	if err != nil {
		t.Error(err)
	}
}

func TestClientResource(t *testing.T) {
	// arrange
	client := newClient(t)
	defer client.Close()

	collection, err := client.CreateCollection(randomString())
	if err != nil {
		t.Skip(err)
	}

	item, err := collection.CreateItem("TestClientResource", "TestClientResource")
	if err != nil {
		t.Skip(err)
	}

	version, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	result, err := version.AddResource("TestClientResource", "TestClientResource", "TestClientResource")
	if err != nil {
		t.Error(err)
	}

	// act
	remote, err := client.Resource(result.Uri())
	if err != nil {
		t.Error(err)
	}

	// assert
	if remote == nil {
		t.Error("did not find desired object by uri")
	}

	if remote.Uri() != result.Uri() || remote.Id() != result.Id() {
		t.Error("expected", result, "got", remote)
	}
}

func TestCreateResource(t *testing.T) {
	// arrange
	client := newClient(t)
	defer client.Close()

	collection, err := client.CreateCollection(randomString())
	if err != nil {
		t.Skip(err)
	}

	item, err := collection.CreateItem("foo", "bar")
	if err != nil {
		t.Skip(err)
	}

	version, err := item.CreateVersion()
	if err != nil {
		t.Skip(err)
	}

	cases := []struct{
		Name string
		Type string
		Location string
		Facets map[string]string
	} {
		{"foo", "img", "/path/to/image", map[string]string{"a": "b"}},
		{"bar", "xml", "/path/to/xml.xml", map[string]string{"a": "b", "q": "iuhuifawd"}},
		{"baz", "uuid", "8964829374hhludhoi3whr8w7r", map[string]string{"foobar": "/oiaow./awd/adw"}},
		{"moo", "xxx", ">//?o@^#)(^@(#^^%!@$/", map[string]string{}},
		{"moo", "boo", ">dawd@$/", nil},
	}

	for i, tst := range cases {
		// act
		resource, err := version.AddResource(tst.Name, tst.Type, tst.Location, wyc.Facets(tst.Facets))
		if err != nil {
			t.Error(i, err)
		}

		found, err := version.Resources(wyc.Id(resource.Id()))
		if err != nil {
			t.Error(i, err)
		}
		if len(found) != 1 {
			t.Error(i, "Expected to find 1 resource, found", len(found))
		}
		remote := found[0]

		allResources, err := version.Resources()
		if err != nil {
			t.Error(i, err)
		}

		// assert
		if len(allResources) != i + 1 {
			t.Error(i, "Expected", i + 1, "get", len(allResources))
		}

		if resource.Id() == "" {
			t.Error(i, "Expected Id to be set")
		}
		if resource.Uri() == "" {
			t.Error(i, "Expected non empty Uri field")
		}
		if resource.ParentId() != version.Id() {
			t.Error(i, "Expected ParentId to be", version.Id(), "got", resource.ParentId())
		}
		if resource.Name() != tst.Name {
			t.Error(i, "Expected", tst.Name, "got", resource.Name())
		}
		if resource.Type() != tst.Type {
			t.Error(i, "Expected", tst.Type, "got", resource.Type())
		}
		if resource.Location() != tst.Location {
			t.Error(i, "Expected", tst.Location, "got", resource.Location())
		}
		if !facetsContain(tst.Facets, resource.Facets()) {
			t.Error(i, "Expected", tst.Facets, "got", resource.Facets())
		}

		if remote.Id() == "" {
			t.Error(i, "[remote] Expected Id to be set")
		}
		if remote.Uri() == "" {
			t.Error(i, "Expected non empty Uri field")
		}
		if remote.ParentId() != version.Id() {
			t.Error(i, "[remote] Expected ParentId to be", version.Id(), "got", remote.ParentId())
		}
		if remote.Name() != tst.Name {
			t.Error(i, "[remote] Expected", tst.Name, "got", remote.Name())
		}
		if remote.Type() != tst.Type {
			t.Error(i, "[remote] Expected", tst.Type, "got", remote.Type())
		}
		if remote.Location() != tst.Location {
			t.Error(i, "[remote] Expected", tst.Location, "got", remote.Location())
		}
		if !facetsContain(tst.Facets, remote.Facets()) {
			t.Error(i, "[remote] Expected", tst.Facets, "got", remote.Facets())
		}
	}
}


text:
package io.netty.buffer;

import io.netty.util.ResourceLeakTracker;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayDeque;
import java.util.Queue;

import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

public class SimpleLeakAwareCompositeByteBufTest extends WrappedCompositeByteBufTest {

    private final Class<? extends ByteBuf> clazz = leakClass();
    private final Queue<NoopResourceLeakTracker<ByteBuf>> trackers = new ArrayDeque<NoopResourceLeakTracker<ByteBuf>>();

    @Override
    protected final WrappedCompositeByteBuf wrap(CompositeByteBuf buffer) {
        NoopResourceLeakTracker<ByteBuf> tracker = new NoopResourceLeakTracker<ByteBuf>();
        WrappedCompositeByteBuf leakAwareBuf = wrap(buffer, tracker);
        trackers.add(tracker);
        return leakAwareBuf;
    }

    protected SimpleLeakAwareCompositeByteBuf wrap(CompositeByteBuf buffer, ResourceLeakTracker<ByteBuf> tracker) {
        return new SimpleLeakAwareCompositeByteBuf(buffer, tracker);
    }

    @Before
    @Override
    public void init() {
        super.init();
        trackers.clear();
    }

    @After
    @Override
    public void dispose() {
        super.dispose();

        for (;;) {
            NoopResourceLeakTracker<ByteBuf> tracker = trackers.poll();

            if (tracker == null) {
                break;
            }
            assertTrue(tracker.get());
        }
    }

    protected Class<? extends ByteBuf> leakClass() {
        return SimpleLeakAwareByteBuf.class;
    }

   @Test
    public void testWrapSlice() {
        assertWrapped(newBuffer(8).slice());
    }

    @Test
    public void testWrapSlice2() {
        assertWrapped(newBuffer(8).slice(0, 1));
    }

    @Test
    public void testWrapReadSlice() {
        assertWrapped(newBuffer(8).readSlice(1));
    }

    @Test
    public void testWrapDuplicate() {
        assertWrapped(newBuffer(8).duplicate());
    }

    protected final void assertWrapped(ByteBuf buf) {
        try {
            assertSame(clazz, buf.getClass());
        } finally {
            buf.release();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using FreeBird.Infrastructure.Utilities.Threading;
using FreeBird.Infrastructure.Utilities;

namespace FreeBird.Infrastructure.Caching
{

	public static class ICacheManagerExtensions
	{
		public static T Get<T>(this ICacheManager cacheManager, string key)
		{
			return cacheManager.Get<T>(key, () => { return default(T); });
		}
	}

    public partial class CacheManager<TCache> : ICacheManager where TCache : ICache
    {
		private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
		private readonly ICache _cache;

        public IEnumerable<KeyValuePair<string, object>> Entries
        {
            get
            {
                return _cache.Entries;
            }
        }

        public CacheManager(Func<Type, ICache> fn)
        {
            this._cache = fn(typeof(TCache));
        }

        public T Get<T>(string key, Func<T> acquirer, int? cacheTime = null)
        {
			Guard.ArgumentNotNull(() => key);

			if (_cache.Contains(key))
			{
				return (T)_cache.Get(key);
			}
			else
			{
				using (EnterReadLock())
				{
					if (!_cache.Contains(key))
					{
						var value = acquirer();
						this.Set(key, value, cacheTime);

						return value;
					}
				}

				return (T)_cache.Get(key);
			}
        }

        public void Set(string key, object value, int? cacheTime = null)
		{
			Guard.ArgumentNotNull(() => key);

			if (value == null)
				return;

			using (EnterWriteLock())
			{
				_cache.Set(key, value, cacheTime);
			}
		}

        public bool Contains(string key)
        {
			Guard.ArgumentNotNull(() => key);

			return _cache.Contains(key);
        }

        public void Remove(string key)
        {
			Guard.ArgumentNotNull(() => key);

			using (EnterWriteLock())
			{
				_cache.Remove(key);
			}
        }

        public void RemoveByPattern(string pattern)
        {
			Guard.ArgumentNotNull(() => pattern);

			var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var keysToRemove = new List<String>();

            foreach (var item in _cache.Entries)
            {
                if (regex.IsMatch(item.Key))
                {
                    keysToRemove.Add(item.Key);
                }
            }

			using (EnterWriteLock())
			{
				foreach (string key in keysToRemove)
				{
					_cache.Remove(key);
				}
			}
        }

        public void Clear()
        {
            var keysToRemove = new List<string>();
            foreach (var item in _cache.Entries)
            {
                keysToRemove.Add(item.Key);
            }

			using (EnterWriteLock())
			{
				foreach (string key in keysToRemove)
				{
					_cache.Remove(key);
				}
			}
        }

		private IDisposable EnterReadLock()
		{
			return _cache.IsSingleton ? _rwLock.GetUpgradeableReadLock() : ActionDisposable.Empty;
		}

		public IDisposable EnterWriteLock()
		{
			return _cache.IsSingleton ? _rwLock.GetWriteLock() : ActionDisposable.Empty;
		}

	}
}


text:
@interface BKZoomView ()
{
    float oldX, oldY;
    BOOL dragging;
}
@property (nonatomic, strong) UIView *parentView;
@property (nonatomic, assign) CGFloat zoomScale;
@end

@implementation BKZoomView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        [self setBackgroundColor:[UIColor clearColor]];
        [self setClipsToBounds:YES];

        _zoomScale = 2.0;
        [self setDragingEnabled:YES];

        UIPanGestureRecognizer* pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
        [self addGestureRecognizer:pgr];

    }
    return self;
}

// This will be called every time 'addSubview:<BKZoomView>' gets called
- (void)willMoveToSuperview:(UIView *)newSuperview
{
    _parentView = newSuperview;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code

    // Set the corrext area we want to zoom in to
    CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextTranslateCTM(context, (self.frame.size.width / 2), (self.frame.size.height / 2));
	CGContextScaleCTM(context, _zoomScale, _zoomScale);
	CGContextTranslateCTM(context, -(self.frame.origin.x) - (self.frame.size.width / 2), -(self.frame.origin.y) - (self.frame.size.height / 2));

    [self setHidden:YES];
    //
	[_parentView.layer.superlayer renderInContext:context];
    [self setHidden:NO];
}

#pragma mark - Private

- (void)setZoomScale:(CGFloat)scale
{
    // We need to call setNeedsDisplay so that the zoom scale can be changed automatically

    _zoomScale = scale;
    [self setNeedsDisplay];
}

- (void)setDragingEnabled:(BOOL)enabled
{
    // This will ensure that if there is noch dragging we can also touch through this view

    [self setUserInteractionEnabled:enabled];
}

#pragma mark - UIPanGestureRecognizer

- (void)handlePan:(UIPanGestureRecognizer*)pgr;
{
    // Here we handle the dragging of the zoom view

    if (pgr.state == UIGestureRecognizerStateChanged)
    {
        CGPoint center = pgr.view.center;
        CGPoint translation = [pgr translationInView:pgr.view];
        center = CGPointMake(center.x + translation.x,
                             center.y + translation.y);
        pgr.view.center = center;
        [pgr setTranslation:CGPointZero inView:pgr.view];
        [self setNeedsDisplay];
    }
}

@end


text:
<html>
<script type="text/javascript">
    function sayHello() {
        alert("Hello")
    }

    function alertMessage(message) {
        alert(message)
    }

    function toastMessage(message) {
        window.control.toastMessage(message)
    }

    function sumToJava(number1, number2){
       window.control.onSumResult(number1 + number2)
    }
</script>
Java-Javascript Interaction In Android
</html>


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Skysail Server</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="keywords" content="">
    <meta name="generator" content="JBake">

    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/asciidoctor.css" rel="stylesheet">
    <link href="../css/base.css" rel="stylesheet">
    <link href="../css/prettify.css" rel="stylesheet">

    <link rel="shortcut icon" href="../favicon.ico">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          JBake

Home

About

Code

Subscribe

              Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Tag: asciidoc

October 2013

17 - Fourth Post

September 2013

26 - Third Post

© 2011 - 2015 | Mixed with Bootstrap v3.1.1 | Baked with JBake v2.4.0


text:
<?php

namespace PhpPdg\AstBridge\Parser;

use PhpParser\Node;
use PhpParser\Parser;

class WrappedParser implements FileParserInterface {
	private $string_parser;

	public function __construct(Parser $string_parser) {
		$this->string_parser = $string_parser;
	}

	public function parse($filename) {
		if (file_exists($filename) === false) {
			throw new \InvalidArgumentException("No such file: `$filename`");
		}
		return $this->string_parser->parse(file_get_contents($filename));
	}

	public function getErrors() {
		return $this->string_parser->getErrors();
	}
}


text:
package alien4cloud.tosca.parser.impl.advanced;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import alien4cloud.tosca.parser.impl.base.BaseParserFactory;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.nodes.Node;

import alien4cloud.tosca.parser.INodeParser;
import alien4cloud.tosca.parser.ParsingContextExecution;
import alien4cloud.tosca.parser.impl.base.ListParser;
import alien4cloud.tosca.parser.impl.base.ScalarParser;

@Component
public class StringListParser implements INodeParser<List<String>> {
    @Resource
    private BaseParserFactory baseParserFactory;
    @Resource
    private ScalarParser scalarParser;

    private ListParser<String> listParser;

    @PostConstruct
    public void init() {
        listParser = baseParserFactory.getListParser(scalarParser, "string");
    }

    @Override
    public List<String> parse(Node node, ParsingContextExecution context) {
        return (List<String>) listParser.parse(node, context);
    }

}


text:
var grunt = require('grunt');
var utils = require('../tasks/modules/utils');
var _ = require('lodash');
function testFile(test, path, whitespaceDifferencesOK) {
    if (whitespaceDifferencesOK === void 0) { whitespaceDifferencesOK = false; }
    var actualFileName = 'test/' + path, expectedFileName = 'test/expected/' + path;
    var actual = grunt.file.read(actualFileName);
    var expected = grunt.file.read(expectedFileName);
    if (whitespaceDifferencesOK) {
        actual = actual.replace(/\s/g, '');
        expected = expected.replace(/\s/g, '');
    }
    test.equal(expected, actual, "Actual did not match expected.  Run this to compare:" +
        (grunt.util.linefeed + "kdiff3 \"" + actualFileName + "\" \"" + expectedFileName + "\""));
}
function assertFileDoesNotExist(test, path) {
    var exists = grunt.file.exists(path);
    test.equal(false, exists, 'Expected this file to not exist: ' + path);
}
function testExpectedFile(test, path, whitespaceDifferencesOK) {
    if (whitespaceDifferencesOK === void 0) { whitespaceDifferencesOK = false; }
    var actualFileName = path.replace('\\expected', '').replace('/expected', ''), expectedFileName = path;
    var actual = grunt.file.read(actualFileName);
    var expected = grunt.file.read(expectedFileName);
    if (whitespaceDifferencesOK) {
        actual = actual.replace(/\s/g, '');
        expected = expected.replace(/\s/g, '');
    }
    test.equal(expected, actual, "Actual did not match expected.  Run this to compare:" +
        (grunt.util.linefeed + "kdiff3 \"" + actualFileName + "\" \"" + expectedFileName + "\""));
}
function testDirectory(test, folder, whitespaceDifferencesOK) {
    if (whitespaceDifferencesOK === void 0) { whitespaceDifferencesOK = false; }
    var files = utils.getFiles(('test/expected/' + folder));
    _.forEach(files, function (expected) {
        testExpectedFile(test, expected, whitespaceDifferencesOK);
    });
}
exports.tests = {
    setUp: function (callback) {
        callback();
    },
    tearDown: function (callback) {
        callback();
    },
    simple: function (test) {
        testFile(test, 'simple/js/zoo.js', true);
        testFile(test, 'simple/js/zoo.d.ts');
        test.done();
    },
    abtest: function (test) {
        testFile(test, 'abtest/reference.ts');
        testFile(test, 'abtest/out.js', true);
        test.done();
    },
    amdloader: function (test) {
        testDirectory(test, 'amdloader');
        test.done();
    },
    templateCache: function (test) {
        testDirectory(test, 'templateCache');
        test.done();
    },
    html2ts: function (test) {
        testDirectory(test, 'html');
        testDirectory(test, 'htmlTemplate');
        test.done();
    },
    index: function (test) {
        testDirectory(test, 'index');
        test.done();
    },
    transform: function (test) {
        testDirectory(test, 'transform', true);
        test.done();
    },
    referencesTransform: function (test) {
        testDirectory(test, 'references-transform');
        test.done();
    },
    customcompiler: function (test) {
        testDirectory(test, 'customcompiler');
        test.done();
    },
    fail: function (test) {
        testDirectory(test, 'fail'); // tested to make sure transformers still run for failing task
        test.done();
    },
    es6: function (test) {
        testDirectory(test, 'es6');
        test.done();
    },
    noEmitOnError: function (test) {
        testDirectory(test, 'noEmitOnError');
        assertFileDoesNotExist(test, 'test/noEmitOnError/testNoEmitOnError_true.js');
        test.done();
    },
    preserveConstEnums: function (test) {
        testDirectory(test, 'preserveConstEnums');
        test.done();
    },
    suppressImplicitAnyIndexErrors: function (test) {
        testDirectory(test, 'suppressImplicitAnyIndexErrors');
        assertFileDoesNotExist(test, 'test/suppressImplicitAnyIndexErrors/test_suppressImplicitAnyIndexError_false.js');
        test.done();
    },
    varReplacedTest: function (test) {
        testDirectory(test, 'varreplacedtest');
        test.done();
    },
    vsproj_test_ignoreSettings: function (test) {
        testDirectory(test, 'vsproj/ignoreSettings');
        test.done();
    },
    files_ObjectFormat: function (test) {
        testDirectory(test, 'files_ObjectFormat', true);
        test.done();
    },
    out_and_outdir_with_spaces: function (test) {
        testDirectory(test, 'out with spaces');
        test.done();
    },
    htmlExternal: function (test) {
        testDirectory(test, 'htmlExternal');
        test.done();
    }
};
//# sourceMappingURL=test.js.map


text:
package de.tum.in.niedermr.ta.core.analysis.mutation.returnvalues;

import static org.junit.Assert.assertEquals;

/** Test {@link VoidReturnValueGenerator}. */
public class VoidReturnValueGeneratorTest extends AbstractReturnValueGeneratorTest<ClassWithMethodsForMutation> {

	/** Constructor. */
	public VoidReturnValueGeneratorTest() {
		super(ClassWithMethodsForMutation.class, new VoidReturnValueGenerator());
	}

	/** {@inheritDoc} */
	@Override
	protected void verifyModification(Class<?> mutatedClass, Object instanceOfMutatedClass,
			ClassWithMethodsForMutation instanceOfOriginalClass) throws ReflectiveOperationException {
		assertEquals("no mutation expected", instanceOfOriginalClass.getStringValue(),
				mutatedClass.getMethod("getStringValue").invoke(instanceOfMutatedClass));
		assertEquals("no mutation expected", instanceOfOriginalClass.getIntValue(),
				mutatedClass.getMethod("getIntValue").invoke(instanceOfMutatedClass));

		// no exception expected
		mutatedClass.getMethod("voidMethod").invoke(instanceOfMutatedClass);
	}
}


text:
require 'mspec/runner/formatters/base'

class HtmlFormatter < BaseFormatter
  def register
    super
    MSpec.register :start, self
    MSpec.register :enter, self
    MSpec.register :leave, self
  end

  def start
    print <<-EOH
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

<title>Spec Output For #{RUBY_ENGINE} (#{RUBY_VERSION})</title>

EOH
  end

  def enter(describe)
    print "

#{describe}
\n
\n"
  end

  def leave
    print "
\n
\n"
  end

  def exception(exception)
    super(exception)
    outcome = exception.failure? ? "FAILED" : "ERROR"
    print %[
- #{exception.it} (]
    print %[#{outcome} - #{@count})
\n]
  end

  def after(state = nil)
    super(state)
    print %[
- #{state.it}
\n] unless exception?
  end

  def finish
    success = @exceptions.empty?
    unless success
      print "
\n"
      print %[
]
      count = 0
      @exceptions.each do |exc|
        outcome = exc.failure? ? "FAILED" : "ERROR"
        print %[\n

#{escape(exc.description)} #{outcome}
\n
]
        print escape(exc.message)
        print "
\n
\n"
        print escape(exc.backtrace)
        print "
\n
\n"
      end
      print "
\n"
    end
    print %[
#{@timer.format}
\n]
    print %[
#{@tally.format}
\n]
    print "\n\n"
  end

  def escape(string)
    string.gsub("&", " ").gsub("<", "<").gsub(">", ">")
  end
end


text:
/*
 * ----------------------------------------
 *           Json Upgrading and
 *        Persistence Architecture
 * ----------------------------------------
 *          Produced by Dan Grew
 *                 2016
 * ----------------------------------------
 */
package uk.dangrew.jupa.json.write.poc.string;

/** Simple data object for testing.**/
public final class Project {

   String projectName;
   String fullProjectName;
   String vcs;

   /** Blank constructor. */
   Project() {}

   /**
    * Constructs a new {@link Project}.
    * @param projectName the name of the project.
    * @param fullProjectName the full name of the project.
    * @param vcs the vcs.
    */
   Project( String projectName, String fullProjectName, String vcs ) {
      this.projectName = projectName;
      this.fullProjectName = fullProjectName;
      this.vcs = vcs;
   }//End Constructor

}//End Class


text:
<?xml version="1.0" encoding="UTF-8"?>
<document id="DDI-DrugBank.d383">
    <sentence id="DDI-DrugBank.d383.s0" text="No information provided"/>
</document>


text:
/*
  Place all the styles related to the matching controller here.
  They will automatically be included in application.css.
*/

#calendar{
	width: 220px;
}

#calendar p{
	margin: 0;
	margin-top: 5px;
	margin-left: 3px;
	font-size: 11px;
}

#calendar a{
	color: #86C555;
	font-weight: bold;
	font-size: 10px;
	text-decoration: none;
}

#calendar .change_months {
	width: 220px;
	height: 20px;
	text-align: center;
}

#calendar div.change_month_circle{
	color: #BDBDBD;
	width: 15px;
	height: 15px;
	line-height: 15px;
	font-size: 13px;
	margin-top: 3px;
	float: left;
	text-align: center;
}

#calendar div.change_month_circle:first-child{
	margin-left: 10px;
}

#calendar .change_months a{
	color: white;
	font-size: 14px;
}

#calendar .month{
	background: ;
	margin: 0;
	margin-left: 4px;
	width: 210px;
	max-height: 140px;
	position: relative;
}

#calendar .month .week-header{
	background: ;
	list-style: none;
	margin: 0px;
	width: 210px;
	height: 20px;
	margin-bottom: 1px;
	text-align: center;
	text-indent: 0px;
	padding: 0;
}

#calendar .month .week-header .day-header{
	background: none;
	color: ;
	width: 28px;
	margin-right: 1px;
	height: 20px;
	float: left;
	border: 0px;
	text-align: center;
	text-indent: 0px;
}
#calendar .month .week-header .day-header p{
	line-height: 20px;
	padding: 0px;
	margin: 0px !important;
	font-weight: bold;
	font-size: 14px !important;
}
#calendar .month .week {
	background: none;
	list-style: none;
	margin: 0px;
	width: 210px;
	height: 18px;
	margin-bottom: 1px;
	font-size: 11px;
	text-align: center;
	text-indent: 0px;
	padding: 0;
}
#calendar .month .week .not-day{
	background: none;
	width: 28px;
	margin-right: 1px;
	height: 18px;
	float: left;
	border: 0px;
	color: #AAAAAA;
	text-align: center;
	text-indent: 0px;
}
#calendar .month .week .not-day p{
	margin: 0 !important;
	line-height: 18px !important;
	font-size: 13px !important;
}
#calendar .month .week .day, #calendar .month .week li{
	background: none;
	width: 28px;
	margin-right: 1px;
	height: 18px;
	float: left;
	border: 0px;
	text-align: center;
	text-indent: 0px;
	cursor: auto;
}
#calendar .month .week-header .day-header div, #calendar .month .week .day div, #calendar .month .week .not-day div{
	margin-left: 0px;
	margin-right: 0px;

	position: relative;
	background: ;
	text-align: center;
}
#calendar .month .week .day p{
	margin: 0 !important;
	line-height: 18px !important;
	font-size: 13px !important;
}
#calendar .month #calendar_event{
	margin-left: 0px;
	margin-top: 0px;
	font-size: 13px;
	font-weight: bold;
	line-height: 18px;
	height: 18px;
	width: 20px;
	position: ;
	left: 4px;
	text-align: center;
	background: none;
}
#calendar .month #calendar_event div{
	height: 16px;
	width: 20px;
	margin-left: 3px;
	line-height: 16px;
}
#calendar .month .week #calendar_event #today{
	background: #CCCCCC !important;
	color: white !important;
	border: 1px solid #000000;
	height: 16px;
	line-height: 16px;
}
#calendar .month .week #today{
	background: white !important;
	color: #000000 !important;
	border: 1px solid #000000;
	height: 16px;
	width: 20px;
	margin-right: 1px;
	line-height: 16px;
	font-weight: bold;
}


text:
from model.country import Country
from model.geozone import Geozone

class GeozoneHelper:

    geozone_cache = None
    country_cache = None

    def __init__(self, app):
        self.app = app

    def get_country(self):
        if self.country_cache is None:
            self.country_cache = []
            for element in self.app.wd.find_elements_by_class_name("row"):
                cells = element.find_elements_by_tag_name("td")
                country = cells[2].text.encode('utf-8')
                self.country_cache.append(Country(name=country))
            return list(self.country_cache)

    def get_zone_list_for_country(self, name_country):
        zone_list = []
        self.app.wd.find_element_by_link_text("%s" % name_country).click()
        for element in self.app.wd.find_elements_by_xpath("//table[@id='table-zones']/tbody/tr[not(@*)]"):
            options = element.find_elements_by_xpath("td[3]/select/option")
            for option in options:
                if option.get_attribute('selected'):
                    zone = option.get_attribute('text').encode('utf-8')
                    zone_list.append(Geozone(name=zone))
        self.app.navigation.open_geozones_page()
        return zone_list


text:
<!doctype html>

  <meta charset="utf-8">
  <title>My AngularJS App</title>
  <link rel="stylesheet" href="css/app.css"/>

bills

add new

  <link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css">


text:
use common::{SourceLocationKey, WithLocation};
use fixture_tests::Fixture;
use graphql_ir::{
    build, Argument, ConstantValue, Directive, ExecutableDefinition, FragmentDefinition,
    OperationDefinition, Value,
};
use graphql_syntax::parse_executable;
use interner::Intern;
use relay_codegen::{build_request_params, print_fragment, print_request, JsModuleFormat};
use relay_test_schema::TEST_SCHEMA;

pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> {
    let ast = parse_executable(
        fixture.content,
        SourceLocationKey::standalone(fixture.file_name),
    )
    .unwrap();
    let program = build(&TEST_SCHEMA, &ast.definitions);
    program
        .map(|definitions| {
            definitions
                .iter()
                .map(|def| match def {
                    ExecutableDefinition::Operation(operation) => {
                        let operation = OperationDefinition {
                            directives: vec![Directive {
                                name: WithLocation::new(
                                    operation.name.location,
                                    "__metadata".intern(),
                                ),
                                arguments: vec![Argument {
                                    name: WithLocation::new(
                                        operation.name.location,
                                        "metadataKey".intern(),
                                    ),
                                    value: WithLocation::new(
                                        operation.name.location,
                                        Value::Constant(ConstantValue::String(
                                            "Hello world!".intern(),
                                        )),
                                    ),
                                }],
                            }],
                            ..operation.clone()
                        };

                        let operation_fragment = FragmentDefinition {
                            name: operation.name,
                            variable_definitions: operation.variable_definitions.clone(),
                            selections: operation.selections.clone(),
                            used_global_variables: Default::default(),
                            directives: operation.directives.clone(),
                            type_condition: operation.type_,
                        };
                        let request_parameters = build_request_params(&operation);
                        print_request(
                            &TEST_SCHEMA,
                            &operation,
                            &operation_fragment,
                            request_parameters,
                            JsModuleFormat::Haste,
                        )
                    }
                    ExecutableDefinition::Fragment(fragment) => {
                        print_fragment(&TEST_SCHEMA, fragment, JsModuleFormat::Haste)
                    }
                })
                .collect::<Vec<_>>()
                .join("\n\n")
        })
        .map_err(|errors| {
            errors
                .into_iter()
                .map(|error| format!("{:?}", error))
                .collect::<Vec<_>>()
                .join("\n\n")
        })
}


text:
<?php

class Controller_Transmission extends Core_Controller
{
	/**
	 * Set some controller defaults.
	 *
	 * @access public
	 */
	public function init() {
		// Set the layout
		$this->setLayout('ingame');

		// Load language file
		Core_Language::load('navigation-private');

	}

	/**
	 * Show a list of the transmissions in a countries inbound.
	 *
	 * @access public
	 */
	public function indexAction() {
		// Language declaration
		Core_Language::load('page-transmission-inbound');
		$lang = Core_Language::getLanguage();

		// Set some default variables
		$this->view->addVariable('title', $lang['transmission-title']);

		// Get the transmission
		$this->view->addVariable(
			'transmissions',
			new Model_Transmission_List(array('country' => $this->view->getVariable('country')))
		);
	}

	/**
	 * Read a transmission.
	 *
	 * @access public
	 */
	public function readAction() {
		// Get the country and transmission
		$country      = $this->view->getVariable('country');
		$transmission = new Model_Transmission_Instance($_GET['id']);

		// Is this transmission for this country?
		if ($country->getInfo('country_id') != $transmission->getInfo('transmission_to_country_id')) {
			// No, forward onto the index
			$this->forward('index');
		}

		// Has the user not read this transmission before?
		if ($transmission->getInfo('transmission_read') == null) {
			$transmissionUpdate = new Model_Transmission_Update();
			$transmissionUpdate->read($transmission->getInfo('transmission_id'));
		}

		// Language declaration
		Core_Language::load('page-transmission-read');
		$lang = Core_Language::getLanguage();

		// Put some variables into the view
		$this->view->addVariable('title', $lang['transmission-title']);
		$this->view->addVariable('transmission', $transmission);
		$this->view->addVariable(
			'transmissionFromCountry',
			new Model_Country_Instance($transmission->getInfo('transmission_from_country_id'))
		);
	}

	/**
	 * Send a transmission to another country.
	 *
	 * @access public
	 */
	public function createAction() {
		// Language declaration
		Core_Language::load('page-transmission-create');
		$lang = Core_Language::getLanguage();

		// Set some default variables
		$this->view->addVariable('title', $lang['transmission-title']);
		$this->view->addVariable('transmissionSendNotice', '');

		// Has the user submitted the form?
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			// Try and send the transmission
			try {
				// Create new transmission
				$transmission = new Model_Transmission_Create();
				$transmission->create(
					$this->view->getVariable('country'),
					$_POST['country_x_coord'],
					$_POST['country_y_coord'],
					$_POST['country_z_coord'],
					$_POST['transmission_subject'],
					$_POST['transmission_message']
				);
			} catch (Exception $e) {
				// Something went wrong
				$this->view->addVariable(
					'transmissionSendNotice',
					$this->view->notice(array(
						'status' => 'error',
						'title'  => $lang['error-title'],
						'body'   => $lang[$e->getMessage()]
					))
				);

				// Render the page now, no need to continue
				$this->view->render();
			}

			// Transmission was sent successfully
			$this->view->addVariable(
				'transmissionSendNotice',
				$this->view->notice(array(
					'status' => 'success',
					'title'  => $lang['success-title'],
					'body'   => $lang['transmission-success-sent']
				))
			);
		}
	}
}


text:
namespace Jwc.Experiment.Idioms
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using Ploeh.AutoFixture.Idioms;
    using Ploeh.AutoFixture.Xunit;
    using global::Xunit;
    using global::Xunit.Extensions;

    public class CompositeIdiomaticAssertionTest
    {
        [Theory, TestData]
        public void SutHasCorrectGuardClauses(
            GuardClauseAssertion assertion)
        {
            var members = new IdiomaticMembers(
                typeof(CompositeIdiomaticAssertion),
                MemberKinds.Constructor);

            foreach (var member in members)
                assertion.Verify(member);
        }

        [Theory, TestData]
        public void SutIsIdiomaticAssertion(CompositeIdiomaticAssertion sut)
        {
            Assert.IsAssignableFrom<IIdiomaticAssertion>(sut);
        }

        [Theory, TestData]
        public void AssertionsIsCorrectWhenInitializedWithIEnumerable(
            [Frozen] IEnumerable<IIdiomaticAssertion> assertions,
            [FavorEnumerables] CompositeIdiomaticAssertion sut)
        {
            var actual = sut.Assertions;
            Assert.Equal(assertions, actual);
        }

        [Theory, TestData]
        public void AssertionsIsCorrectWhenInitializedWithArray(
            [Frozen] IIdiomaticAssertion[] assertions,
            [FavorArrays] CompositeIdiomaticAssertion sut)
        {
            var actual = sut.Assertions;
            Assert.Equal(assertions, actual);
        }

        [Theory, TestData]
        public void VerifyAssemblyCorrectlyVerifies(
            CompositeIdiomaticAssertion sut,
            Assembly assembly)
        {
            sut.Verify(assembly);
            foreach (var assertion in sut.Assertions)
                assertion.ToMock().Verify(x => x.Verify(assembly));
        }

        [Theory, TestData]
        public void VerifyTypeCorrectlyVerifies(
            CompositeIdiomaticAssertion sut,
            Type type)
        {
            sut.Verify(type);
            foreach (var assertion in sut.Assertions)
                assertion.ToMock().Verify(x => x.Verify(type));
        }

        [Theory, TestData]
        public void VerifyMemberCorrectlyVerifies(
            CompositeIdiomaticAssertion sut,
            MemberInfo member)
        {
            sut.Verify(member);
            foreach (var assertion in sut.Assertions)
                assertion.ToMock().Verify(x => x.Verify(member));
        }
    }
}


text:
package org.gradoop.storage.common.api;

import org.gradoop.common.model.api.entities.EPGMEdge;
import org.gradoop.common.model.api.entities.EPGMGraphHead;
import org.gradoop.common.model.api.entities.EPGMVertex;

import javax.annotation.Nonnull;
import java.io.Closeable;
import java.io.IOException;

/**
 * Definition of graph store input.
 * A graph input instance provide a set of writing methods for EPGM elements.
 */
public interface EPGMGraphInput extends Closeable {

  /**
   * Writes the given graph data into the graph store.
   *
   * @param graphData graph data to write
   * @throws IOException if writing the {@link EPGMGraphHead} fails
   */
  void writeGraphHead(@Nonnull EPGMGraphHead graphData) throws IOException;

  /**
   * Writes the given vertex data into the graph store.
   *
   * @param vertexData vertex data to write
   * @throws IOException if writing the {@link EPGMVertex} fails
   */
  void writeVertex(@Nonnull EPGMVertex vertexData) throws IOException;

  /**
   * Writes the given edge data into the graph store.
   *
   * @param edgeData edge data to write
   * @throws IOException if writing the {@link EPGMEdge} fails
   */
  void writeEdge(@Nonnull EPGMEdge edgeData) throws IOException;

  /**
   * Setting this value to true, forces the store implementation to flush the
   * write buffers after every write.
   *
   * @param autoFlush true to enable auto flush, false to disable
   */
  void setAutoFlush(boolean autoFlush);

  /**
   * Flushes all buffered writes to the store.
   *
   * @throws IOException if flushing changes to the store fails
   */
  void flush() throws IOException;

}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.yy.studyapp.common.dto.order;

import java.math.BigDecimal;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.yy.studyapp.core.xml.JaxbHelper;
import static org.junit.Assert.*;

/**
 *
 * @author yyi
 */
public class OrderDtoToXmlTest {

    public OrderDtoToXmlTest() {
    }

    @Test
    public void test1() {
        OrderDto orderDto = new OrderDto();
        orderDto.setAccountId("01-222222-22");
        orderDto.setInstrumentCode("LLS");
        orderDto.setLot(new BigDecimal("10.00"));

        JaxbHelper helper = new JaxbHelper("org.yy.studyapp.common.dto.order");
        String xml = helper.toXmlString(orderDto);
        System.out.println(xml);
        OrderDto another = (OrderDto) helper.fromXmlString(xml);
        System.out.println(another.toString());
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }
    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //
    // @Test
    // public void hello() {}
}


text:
cask "avira-antivirus" do
  version :latest
  sha256 :no_check

  url "https://install.avira-update.com/package/wks_avira/osx/int/pecl/Avira_Antivirus.pkg",
      verified: "install.avira-update.com/"
  name "Avira Antivirus"
  desc "Antivirus and VPN software"
  homepage "https://www.avira.com/en/free-antivirus-mac/"

  depends_on macos: ">= :el_capitan"

  pkg "Avira_Antivirus.pkg"

  uninstall script:  {
    executable: "/Applications/Utilities/Avira-Uninstall.app/Contents/MacOS/Avira-Uninstall",
    sudo:       true,
  },
            pkgutil: "com.avira.pkg.AviraMacSecurity"

  zap trash: "~/Library/Saved Application State/com.avira.controlcenter.savedState"
end


text:
namespace netpp {

struct AcceptOperation : public BaseOperation {
  BaseSocket& peer;
  Address& peer_addr;
  AcceptHandler handler{};

  AcceptOperation(int e, BaseSocket& s, Address& addr, const AcceptHandler& h)
    : BaseOperation(OPER_ACCEPT, e), peer(s), peer_addr(addr), handler(h) {
  }

  AcceptOperation(int e, BaseSocket& s, Address& addr, AcceptHandler&& h)
    : BaseOperation(OPER_ACCEPT, e)
    , peer(s), peer_addr(addr), handler(std::move(h)) {
  }
};

struct ConnectOperation : public BaseOperation {
  ConnectHandler handler{};

  ConnectOperation(int e, const ConnectHandler& h)
    : BaseOperation(OPER_CONNECT, e), handler(h) {
  }

  ConnectOperation(int e, ConnectHandler&& h)
    : BaseOperation(OPER_CONNECT, e), handler(std::move(h)) {
  }
};

struct ReadOperation : public BaseOperation {
  const MutableBuffer& mbuf;
  std::size_t nread{};
  ReadHandler handler{};

  ReadOperation(int e, const MutableBuffer& buf, const ReadHandler& h)
    : BaseOperation(OPER_READ, e), mbuf(buf), handler(h) {
  }

  ReadOperation(int e, const MutableBuffer& buf, ReadHandler&& h)
    : BaseOperation(OPER_READ, e), mbuf(buf), handler(std::move(h)) {
  }
};

struct ReadSomeOperation : public BaseOperation {
  const MutableBuffer& mbuf;
  ReadHandler handler{};

  ReadSomeOperation(int e, const MutableBuffer& buf, const ReadHandler& h)
    : BaseOperation(OPER_READ_SOME, e), mbuf(buf), handler(h) {
  }

  ReadSomeOperation(int e, const MutableBuffer& buf, ReadHandler&& h)
    : BaseOperation(OPER_READ_SOME, e), mbuf(buf), handler(std::move(h)) {
  }
};

struct WriteOperation : public BaseOperation {
  const ConstBuffer& cbuf;
  std::size_t nwrote{};
  WriteHandler handler{};

  WriteOperation(int e, const ConstBuffer& buf, const WriteHandler& h)
    : BaseOperation(OPER_WRITE, e), cbuf(buf), handler(h) {
  }

  WriteOperation(int e, const ConstBuffer& buf, WriteHandler&& h)
    : BaseOperation(OPER_WRITE, e), cbuf(buf), handler(std::move(h)) {
  }
};

struct WriteSomeOperation : public BaseOperation {
  const ConstBuffer& cbuf;
  WriteHandler handler{};

  WriteSomeOperation(int e, const ConstBuffer& buf, const WriteHandler& h)
    : BaseOperation(OPER_WRITE_SOME, e), cbuf(buf), handler(h) {
  }

  WriteSomeOperation(int e, const ConstBuffer& buf, WriteHandler&& h)
    : BaseOperation(OPER_WRITE_SOME, e), cbuf(buf), handler(std::move(h)) {
  }
};

struct ReadFromOperation : public BaseOperation {
  const MutableBuffer& mbuf;
  const Address& peer_addr;
  ReadHandler handler{};

  ReadFromOperation(int e,
      const MutableBuffer& buf, const Address& addr, const ReadHandler& h)
    : BaseOperation(OPER_READFROM, e), mbuf(buf), peer_addr(addr), handler(h) {
  }

  ReadFromOperation(int e,
      const MutableBuffer& buf, const Address& addr, ReadHandler&& h)
    : BaseOperation(OPER_READFROM, e)
    , mbuf(buf), peer_addr(addr), handler(std::move(h)) {
  }
};

struct WriteToOperation : public BaseOperation {
  const ConstBuffer& cbuf;
  const Address& peer_addr;
  WriteHandler handler{};

  WriteToOperation(int e,
      const ConstBuffer& buf, const Address& addr, const WriteHandler& h)
    : BaseOperation(OPER_WRITETO, e), cbuf(buf), peer_addr(addr), handler(h) {
  }

  WriteToOperation(int e,
      const ConstBuffer& buf, const Address& addr, WriteHandler&& h)
    : BaseOperation(OPER_WRITETO, e)
    , cbuf(buf), peer_addr(addr), handler(std::move(h)) {
  }
};

bool SocketService::add_operation(socket_t sockfd, BaseOperation* oper) {
  if (operations_.find(sockfd) == operations_.end())
    operations_[sockfd] = OperationDict();

  auto event = oper->get_events();
  if (operations_[sockfd].find(event) == operations_[sockfd].end()) {
    pollfds_.push_back(PollFd(sockfd, event));
    operations_[sockfd][event] = oper;
    return true;
  }

  return false;
}

bool SocketService::set_non_blocking(
    socket_t sockfd, bool mode, std::error_code& ec) {
  return socket::set_non_blocking(sockfd, mode, ec);
}

int SocketService::set_option(socket_t sockfd, int level, int optname,
      const void* optval, std::size_t optlen, std::error_code& ec) {
  return socket::set_option(sockfd, level, optname, optval, optlen, ec);
}

int SocketService::get_option(socket_t sockfd, int level, int optname,
      void* optval, std::size_t* optlen, std::error_code& ec) {
  return socket::get_option(sockfd, level, optname, optval, optlen, ec);
}

socket_t SocketService::open(
    int family, int socket_type, int protocol, std::error_code& ec) {
  return socket::open(family, socket_type, protocol, ec);
}

void SocketService::close(socket_t sockfd, std::error_code& ec) {
  socket::close(sockfd, ec);
}

void SocketService::shutdown(socket_t sockfd, int how, std::error_code& ec) {
  socket::shutdown(sockfd, how, ec);
}

void SocketService::bind(
    socket_t sockfd, const Address& addr, std::error_code& ec) {
  socket::bind(sockfd, addr.get_address(), ec);
}

void SocketService::listen(socket_t sockfd, std::error_code& ec) {
  socket::listen(sockfd, ec);
}

socket_t SocketService::accept(socket_t sockfd,
    Address* peer_addr, bool non_blocking, std::error_code& ec) {
  return socket::sync_accept(sockfd,
      peer_addr ? peer_addr->get_address() : nullptr, non_blocking, ec);
}

void SocketService::async_accept(socket_t sockfd,
    BaseSocket& peer, Address& peer_addr, const AcceptHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new AcceptOperation(POLLIN, peer, peer_addr, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_accept(socket_t sockfd,
    BaseSocket& peer, Address& peer_addr, AcceptHandler&& handler) {
  // sockfd should be non-blocking
  auto* oper = new AcceptOperation(POLLIN, peer, peer_addr, std::move(handler));
  add_operation(sockfd, oper);
}

void SocketService::connect(
    socket_t sockfd, const Address& addr, std::error_code& ec) {
  socket::sync_connect(sockfd, addr.get_address(), ec);
}

void SocketService::async_connect(
    socket_t sockfd, const Address& addr, const ConnectHandler& handler) {
  // sockfd should be non-blocking
  std::error_code ec;
  socket::connect(sockfd, addr.get_address(), ec);
  if (!ec) {
    handler(ec);
  }
  else {
    if (ec.value() != error::IN_PROGRESS && ec.value() != error::WOULD_BLOCK) {
      handler(ec);
    }
    else {
      auto* oper = new ConnectOperation(POLLIN, handler);
      add_operation(sockfd, oper);
    }
  }
}

void SocketService::async_connect(
    socket_t sockfd, const Address& addr, ConnectHandler&& handler) {
  // sockfd should be non-blocking
  std::error_code ec;
  socket::connect(sockfd, addr.get_address(), ec);
  if (!ec) {
    handler(ec);
  }
  else {
    if (ec.value() != error::IN_PROGRESS && ec.value() != error::WOULD_BLOCK) {
      handler(ec);
    }
    else {
      auto* oper = new ConnectOperation(POLLIN, std::move(handler));
      add_operation(sockfd, oper);
    }
  }
}

std::size_t SocketService::read(socket_t sockfd,
    const MutableBuffer& buf, bool non_blocking, std::error_code& ec) {
  auto all_empty = buf.size() == 0;
  std::size_t nread{};
  for (;;) {
    auto n = socket::sync_read(sockfd,
        buf.size() - nread, reinterpret_cast<char*>(buf.data()) + nread,
        non_blocking, all_empty, ec);
    if (!ec) {
      nread += n;
      if (nread >= buf.size())
        break;
    }
    else {
      break;
    }
  }
  return nread;
}

std::size_t SocketService::read(socket_t sockfd,
    const NullBuffer&, bool non_blocking, std::error_code& ec) {
  return socket::poll_read(sockfd, non_blocking, -1, ec);
}

std::size_t SocketService::read_some(socket_t sockfd,
    const MutableBuffer& buf, bool non_blocking, std::error_code& ec) {
  auto all_empty = buf.size() == 0;
  return socket::sync_read(sockfd,
      buf.size(), buf.data(), non_blocking, all_empty, ec);
}

std::size_t SocketService::read_some(socket_t sockfd,
    const NullBuffer&, bool non_blocking, std::error_code& ec) {
  return socket::poll_read(sockfd, non_blocking, -1, ec);
}

void SocketService::async_read(
    socket_t sockfd, const MutableBuffer& buf, const ReadHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new ReadOperation(POLLIN, buf, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_read(
    socket_t sockfd, const MutableBuffer& buf, ReadHandler&& handler) {
  // sockfd should be non-blocking
  auto* oper = new ReadOperation(POLLIN, buf, std::move(handler));
  add_operation(sockfd, oper);
}

void SocketService::async_read_some(
    socket_t sockfd, const MutableBuffer& buf, const ReadHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new ReadSomeOperation(POLLIN, buf, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_read_some(
    socket_t sockfd, const MutableBuffer& buf, ReadHandler&& handler) {
  // sockfd should be non-blocking
  auto* oper = new ReadSomeOperation(POLLIN, buf, std::move(handler));
  add_operation(sockfd, oper);
}

std::size_t SocketService::write(socket_t sockfd,
    const ConstBuffer& buf, bool non_blocking, std::error_code& ec) {
  auto all_empty = buf.size() == 0;
  std::size_t nwrote{};
  for (;;) {
    auto n = socket::sync_write(sockfd,
        reinterpret_cast<const char*>(buf.data()) + nwrote,
        buf.size() - nwrote, non_blocking, all_empty, ec);
    if (!ec) {
      nwrote += n;
      if (nwrote >= buf.size())
        break;
    }
    else {
      break;
    }
  }
  return nwrote;
}

std::size_t SocketService::write(socket_t sockfd,
      const NullBuffer&, bool non_blocking, std::error_code& ec) {
  return socket::poll_write(sockfd, non_blocking, -1, ec);
}

std::size_t SocketService::write_some(socket_t sockfd,
    const ConstBuffer& buf, bool non_blocking, std::error_code& ec) {
  auto all_empty = buf.size() == 0;
  return socket::sync_write(sockfd,
      buf.data(), buf.size(), non_blocking, all_empty, ec);
}

std::size_t SocketService::write_some(socket_t sockfd,
    const NullBuffer&, bool non_blocking, std::error_code& ec) {
  return socket::poll_write(sockfd, non_blocking, -1, ec);
}

void SocketService::async_write(
    socket_t sockfd, const ConstBuffer& buf, const WriteHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new WriteOperation(POLLOUT, buf, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_write(
    socket_t sockfd, const ConstBuffer& buf, WriteHandler&& handler) {
  // sockfd should be non-blocking
  auto* oper = new WriteOperation(POLLOUT, buf, std::move(handler));
  add_operation(sockfd, oper);
}

void SocketService::async_write_some(
    socket_t sockfd, const ConstBuffer& buf, const WriteHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new WriteSomeOperation(POLLOUT, buf, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_write_some(
    socket_t sockfd, const ConstBuffer& buf, WriteHandler&& handler) {
  // sockfd should be non-blocking
  auto* oper = new WriteSomeOperation(POLLOUT, buf, std::move(handler));
  add_operation(sockfd, oper);
}

std::size_t SocketService::read_from(socket_t sockfd, const MutableBuffer& buf,
    Address& peer_addr, bool non_blocking, std::error_code& ec) {
  return socket::sync_read_from(sockfd,
      buf.size(), buf.data(), peer_addr.get_address(), non_blocking, ec);
}

std::size_t SocketService::read_from(socket_t sockfd,
      const NullBuffer&, Address&, bool non_blocking, std::error_code& ec) {
  socket::poll_read(sockfd, non_blocking, -1, ec);
  return 0;
}

void SocketService::async_read_from(socket_t sockfd,
    const MutableBuffer& buf, Address& peer_addr, const ReadHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new ReadFromOperation(POLLIN, buf, peer_addr, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_read_from(socket_t sockfd,
    const MutableBuffer& buf, Address& peer_addr, ReadHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new ReadFromOperation(
      POLLIN, buf, peer_addr, std::move(handler));
  add_operation(sockfd, oper);
}

std::size_t SocketService::write_to(socket_t sockfd, const ConstBuffer& buf,
    const Address& peer_addr, bool non_blocking, std::error_code& ec) {
  return socket::sync_write_to(sockfd,
      buf.data(), buf.size(), peer_addr.get_address(), non_blocking, ec);
}

std::size_t SocketService::write_to(socket_t sockfd,
    const NullBuffer&, const Address&, bool non_blocking, std::error_code& ec) {
  socket::poll_write(sockfd, non_blocking, -1, ec);
  return 0;
}

void SocketService::async_write_to(socket_t sockfd, const ConstBuffer& buf,
    const Address& peer_addr, const WriteHandler& handler) {
  // sockfd should be non-blocking
  auto* oper = new WriteToOperation(POLLOUT, buf, peer_addr, handler);
  add_operation(sockfd, oper);
}

void SocketService::async_write_to(socket_t sockfd,
    const ConstBuffer& buf, const Address& peer_addr, WriteHandler&& handler) {
  // sockfd should be non-blocking
  auto* oper = new WriteToOperation(
      POLLOUT, buf, peer_addr, std::move(handler));
  add_operation(sockfd, oper);
}

bool SocketService::handle_operation(socket_t sockfd, int event) {
  auto oper_dict_iter = operations_.find(sockfd);
  if (oper_dict_iter == operations_.end())
    return false;

  auto& oper_dict = operations_[sockfd];
  auto oper_iter = oper_dict.find(event);
  bool need_remove{true};
  if (oper_iter != oper_dict.end()) {
    auto* oper = oper_iter->second;
    if (oper != nullptr) {
      std::error_code ec;
      switch (oper->get_type()) {
      case BaseOperation::OPER_ACCEPT:
        {
          auto* aop = reinterpret_cast<AcceptOperation*>(oper);
          auto fd = socket::accept(sockfd, aop->peer_addr.get_address(), ec);
          aop->peer.attach_fd(fd);
          aop->handler(ec);
          delete aop;
        } break;
      case BaseOperation::OPER_CONNECT:
        {
          auto* cop = reinterpret_cast<ConnectOperation*>(oper);
          cop->handler(ec);
          delete cop;
        } break;
      case BaseOperation::OPER_READ:
        {
          auto* rop = reinterpret_cast<ReadOperation*>(oper);
          auto off = rop->nread;
          auto n = socket::read(sockfd, rop->mbuf.size() - off,
              reinterpret_cast<char*>(rop->mbuf.data()) + off, ec);
          if (!ec)
            rop->nread += n;
          if ((!ec && rop->nread >= rop->mbuf.size()) || ec) {
            rop->handler(ec, rop->nread);
            delete rop;
          }
          else {
            need_remove = false;
          }
        } break;
      case BaseOperation::OPER_READ_SOME:
        {
          auto* rop = reinterpret_cast<ReadSomeOperation*>(oper);
          auto n = socket::read(sockfd, rop->mbuf.size(), rop->mbuf.data(), ec);
          rop->handler(ec, n);
          delete rop;
        } break;
      case BaseOperation::OPER_WRITE:
        {
          auto* wop = reinterpret_cast<WriteOperation*>(oper);
          auto off = wop->nwrote;
          auto n = socket::write(sockfd,
              reinterpret_cast<const char*>(wop->cbuf.data()) + off,
              wop->cbuf.size() - off, ec);
          if (!ec)
            wop->nwrote += n;
          if ((!ec && wop->nwrote >= wop->cbuf.size()) || ec) {
            wop->handler(ec, wop->nwrote);
            delete wop;
          }
          else {
            need_remove = false;
          }
        } break;
      case BaseOperation::OPER_WRITE_SOME:
        {
          auto* wop = reinterpret_cast<WriteSomeOperation*>(oper);
          auto n = socket::write(sockfd,
              wop->cbuf.data(), wop->cbuf.size(), ec);
          wop->handler(ec, n);
          delete wop;
        } break;
      case BaseOperation::OPER_READFROM:
        {
          auto* rop = reinterpret_cast<ReadFromOperation*>(oper);
          auto n = socket::read_from(sockfd,
              rop->mbuf.size(), rop->mbuf.data(),
              (void*)rop->peer_addr.get_address(),
              ec, rop->peer_addr.get_family() == AF_INET6);
          rop->handler(ec, n);
          delete rop;
        } break;
      case BaseOperation::OPER_WRITETO:
        {
          auto* wop = reinterpret_cast<WriteToOperation*>(oper);
          auto n = socket::write_to(sockfd,
              wop->cbuf.data(), wop->cbuf.size(),
              wop->peer_addr.get_address(), ec);
          wop->handler(ec, n);
          delete wop;
        } break;
      }
    }
    if (need_remove)
      oper_dict.erase(oper_iter);
  }
  if (oper_dict.empty())
    operations_.erase(oper_dict_iter);

  return need_remove;
}

void SocketService::handle_error(socket_t sockfd) {
  auto oper_dict_iter = operations_.find(sockfd);
  if (oper_dict_iter == operations_.end())
    return;

  auto& oper_dict = operations_[sockfd];
  for (auto& it : oper_dict) {
    std::error_code ec = make_error(get_errno());
    auto* oper = it.second;
    switch (oper->get_type()) {
    case BaseOperation::OPER_ACCEPT:
      {
        auto* aop = reinterpret_cast<AcceptOperation*>(oper);
        aop->handler(ec);
        delete aop;
      } break;
    case BaseOperation::OPER_CONNECT:
      {
        auto* cop = reinterpret_cast<ConnectOperation*>(oper);
        cop->handler(ec);
        delete cop;
      } break;
    case BaseOperation::OPER_READ:
      {
        auto* rop = reinterpret_cast<ReadOperation*>(oper);
        rop->handler(ec, rop->nread);
        delete rop;
      } break;
    case BaseOperation::OPER_READ_SOME:
      {
        auto* rop = reinterpret_cast<ReadSomeOperation*>(oper);
        rop->handler(ec, 0);
        delete rop;
      } break;
    case BaseOperation::OPER_WRITE:
      {
        auto* wop = reinterpret_cast<WriteOperation*>(oper);
        wop->handler(ec, wop->nwrote);
        delete wop;
      } break;
    case BaseOperation::OPER_WRITE_SOME:
      {
        auto* wop = reinterpret_cast<WriteSomeOperation*>(oper);
        wop->handler(ec, 0);
        delete wop;
      } break;
    case BaseOperation::OPER_READFROM:
      {
        auto* rop = reinterpret_cast<ReadFromOperation*>(oper);
        rop->handler(ec, 0);
        delete rop;
      } break;
    case BaseOperation::OPER_WRITETO:
      {
        auto* wop = reinterpret_cast<WriteToOperation*>(oper);
        wop->handler(ec, 0);
        delete wop;
      } break;
    }
  }
  operations_.erase(oper_dict_iter);
}

void SocketService::run(void) {
  while (running_) {
    auto n = netpp::poll(&*pollfds_.begin(),
        static_cast<int>(pollfds_.size()), kPollTimeout);
    if (n <= 0)
      continue;

    std::vector<PollFd> active_fds;
    for (auto it = pollfds_.begin(); it != pollfds_.end();) {
      if (n-- <= 0)
        break;

      auto revents = it->revents;
      if (revents > 0) {
        active_fds.push_back(*it);
        pollfds_.erase(it++);
      }
      else {
        ++it;
      }
    }

    for (auto& fd : active_fds) {
        bool need_remove{true};
        auto revents = fd.revents;
        if ((revents & POLLHUP) && !(revents & POLLIN))  {
          // TODO: need solve close-functor
        }
        if (revents & (POLLERR | POLLNVAL)) // solve error-functor
          handle_error(fd.fd);
        if (revents & (POLLIN | POLLPRI | POLLHUP))
          need_remove = handle_operation(fd.fd, POLLIN);
        if (revents & POLLOUT)
          need_remove = handle_operation(fd.fd, POLLOUT);

        if (!need_remove)
          pollfds_.push_back(fd);
    }

    if (pollfds_.size() == 0 && operations_.size() == 0)
      running_ = false;
  }
}

void SocketService::stop(void) {
  running_ = false;
}

}


text:
<?php

require_once(dirname(__FILE__) . "/../autoload.inc.php");
class RP_MsParam extends RODSPacket
{
    public function __construct($label = '', RODSPacket $inOutStruct = null,
                                RP_BinBytesBuf $BinBytesBuf_PI = null)
    {
        if (!isset($BinBytesBuf_PI)) $BinBytesBuf_PI = new RP_BinBytesBuf();
        if (!isset($inOutStruct)) $inOutStruct = new RODSPacket();

        $packlets = array("label" => $label, "type" => $inOutStruct->type,
            $inOutStruct->type => $inOutStruct, "BinBytesBuf_PI" => $BinBytesBuf_PI);
        parent::__construct("MsParam_PI", $packlets);
    }

    // need to overwrite it's parent function here, since $inOutStruct->type
    // can be undefined, when it's parent packet class was defined.
    public function fromSXE(SimpleXMLElement $sxe)
    {
        if (!isset($this->packlets))
            return;

        $this->packlets["label"] = (string)$sxe->label;
        $this->packlets["type"] = (string)$sxe->type;

        $typename = $this->packlets["type"]; //type of the expected packet
        if (substr($typename, -3, 3) != "_PI") {
            throw new RODSException("RP_MsParam::fromSXE " .
                    "The XML node's type is unexpected: '$typename' " .
                    " expecting some thing like xxx_PI",
                "SYS_PACK_INSTRUCT_FORMAT_ERR");
        }
        $rp_classname = "RP_" . substr($typename, 0, strlen($typename) - 3);
        $inOutStruct = new $rp_classname();
        $inOutStruct->fromSXE($sxe->$typename);
        $this->packlets["$typename"] = $inOutStruct;

        $this->packlets['BinBytesBuf_PI'] = new RP_BinBytesBuf();
        $this->packlets['BinBytesBuf_PI']->fromSXE($sxe->BinBytesBuf_PI);
    }

}


text:
def c_location_bs(options = {})
  @o = FactoryGirl.build_stubbed(:location, options)
end

def c_location_cr(options = {})
  FactoryGirl.create(:location, options)
end

def c_location_numeric_field_bs(options = {})
  @o = FactoryGirl.build_stubbed(:location_numeric_field, options)
end

def c_location_numeric_field_cr(options = {})
  @o = FactoryGirl.create(:location_numeric_field, options)
end

def c_person_bs(options = {})
  @o = FactoryGirl.build_stubbed(:person, options)
end

def c_person_cr(options = {})
  FactoryGirl.create(:person, options)
end

def c_person_string_field_bs(options = {})
  @o = FactoryGirl.build_stubbed(:person_string_field, options)
end

def c_person_string_field_cr(options = {})
  FactoryGirl.create(:person_string_field, options)
end


text:
/* eslint max-params: [2, 8] */
define([
  'i18n!nls/messages',
  'i18n!nls/enduser',
  'i18n!nls/homepage',
  'i18n!nls/shared',
  'i18n!nls/selfservice',
  'i18n!nls/country'
], function (messages, enduser, homepage, shared, selfservice, country) {
  return {
    messages: messages,
    enduser: enduser,
    homepage: homepage,
    shared: shared,
    selfservice: selfservice,
    country: country
  };
});


text:
module GeneratedTest where
import Haskore.Basic.Duration((%+))
import Haskore.Music
import Haskore.Melody.Standard
import Haskore.Music.GeneralMIDI as MidiMusic
import Haskore.Interface.MIDI.Render as Render

main = Render.fileFromGeneralMIDIMusic "hello.midi" song

song = MidiMusic.fromStdMelody MidiMusic.AcousticGrandPiano $ chord
  [changeTempo (2 %+ 3) (line [c 1 (1 %+ 23) na, rest (1 %+ 23)]),
   transpose 3 (line [c 1 qn na, qnr]),
   changeTempo (2 %+ 3) (c 1 (1 %+ 23) na),
   transpose (- 3) (c 1 qn na), changeTempo (7 %+ 1) (rest (1 %+ 23)),
   transpose 4 qnr]