text:
"""Tests for the aggregates admin api."""

from webob import exc

from nova.api.openstack.compute.plugins.v3 import aggregates
from nova import exception
from nova import test
from nova.tests.api.openstack import fakes
from nova.tests import matchers

AGGREGATE_LIST = [
        {"name": "aggregate1", "id": "1", "availability_zone": "nova1"},
        {"name": "aggregate2", "id": "2", "availability_zone": "nova1"},
        {"name": "aggregate3", "id": "3", "availability_zone": "nova2"},
        {"name": "aggregate1", "id": "4", "availability_zone": "nova1"}]
AGGREGATE = {"name": "aggregate1",
                  "id": "1",
                  "availability_zone": "nova1",
                  "metadata": {"foo": "bar"},
                  "hosts": ["host1, host2"]}

class AggregateTestCase(test.NoDBTestCase):
    """Test Case for aggregates admin api."""

    def setUp(self):
        super(AggregateTestCase, self).setUp()
        self.controller = aggregates.AggregateController()
        self.req = fakes.HTTPRequest.blank('/v3/os-aggregates',
                                           use_admin_context=True)
        self.user_req = fakes.HTTPRequest.blank('/v3/os-aggregates')
        self.context = self.req.environ['nova.context']

    def test_index(self):
        def stub_list_aggregates(context):
            if context is None:
                raise Exception()
            return AGGREGATE_LIST
        self.stubs.Set(self.controller.api, 'get_aggregate_list',
                       stub_list_aggregates)

        result = self.controller.index(self.req)

        self.assertEqual(AGGREGATE_LIST, result["aggregates"])

    def test_index_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.index,
                          self.user_req)

    def test_create(self):
        def stub_create_aggregate(context, name, availability_zone):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("test", name, "name")
            self.assertEqual("nova1", availability_zone, "availability_zone")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        result = self.controller.create(self.req, {"aggregate":
                                          {"name": "test",
                                           "availability_zone": "nova1"}})
        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_create_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.create, self.user_req,
                          {"aggregate":
                              {"name": "test",
                               "availability_zone": "nova1"}})

    def test_create_with_duplicate_aggregate_name(self):
        def stub_create_aggregate(context, name, availability_zone):
            raise exception.AggregateNameExists(aggregate_name=name)
        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        self.assertRaises(exc.HTTPConflict, self.controller.create,
                          self.req, {"aggregate":
                                     {"name": "test",
                                      "availability_zone": "nova1"}})

    def test_create_with_incorrect_availability_zone(self):
        def stub_create_aggregate(context, name, availability_zone):
            raise exception.InvalidAggregateAction(action='create_aggregate',
                                                   aggregate_id="'N/A'",
                                                   reason='invalid zone')

        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.create,
                          self.req, {"aggregate":
                                     {"name": "test",
                                      "availability_zone": "nova_bad"}})

    def test_create_with_no_aggregate(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller.create,
                          self.req, {"foo":
                                     {"name": "test",
                                      "availability_zone": "nova1"}})

    def test_create_with_no_name(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller.create,
                          self.req, {"aggregate":
                                     {"availability_zone": "nova1"}})

    def test_create_with_no_availability_zone(self):
        def stub_create_aggregate(context, name, availability_zone):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("test", name, "name")
            self.assertEqual(None, availability_zone, "availability_zone")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "create_aggregate",
                       stub_create_aggregate)

        result = self.controller.create(self.req,
                                        {"aggregate": {"name": "test"}})
        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_create_with_null_name(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller.create,
                          self.req, {"aggregate":
                                     {"name": "",
                                      "availability_zone": "nova1"}})

    def test_create_with_name_too_long(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller.create,
                          self.req, {"aggregate":
                                     {"name": "x" * 256,
                                      "availability_zone": "nova1"}})

    def test_show(self):
        def stub_get_aggregate(context, id):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", id, "id")
            return AGGREGATE
        self.stubs.Set(self.controller.api, 'get_aggregate',
                       stub_get_aggregate)

        aggregate = self.controller.show(self.req, "1")

        self.assertEqual(AGGREGATE, aggregate["aggregate"])

    def test_show_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.show,
                          self.user_req, "1")

    def test_show_with_invalid_id(self):
        def stub_get_aggregate(context, id):
            raise exception.AggregateNotFound(aggregate_id=2)

        self.stubs.Set(self.controller.api, 'get_aggregate',
                       stub_get_aggregate)

        self.assertRaises(exc.HTTPNotFound,
                          self.controller.show, self.req, "2")

    def test_update(self):
        body = {"aggregate": {"name": "new_name",
                              "availability_zone": "nova1"}}

        def stub_update_aggregate(context, aggregate, values):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertEqual(body["aggregate"], values, "values")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        result = self.controller.update(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_update_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.update,
                          self.user_req, "1", body={})

    def test_update_with_only_name(self):
        body = {"aggregate": {"name": "new_name"}}

        def stub_update_aggregate(context, aggregate, values):
            return AGGREGATE
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        result = self.controller.update(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_update_with_only_availability_zone(self):
        body = {"aggregate": {"availability_zone": "nova1"}}

        def stub_update_aggregate(context, aggregate, values):
            return AGGREGATE
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)
        result = self.controller.update(self.req, "1", body=body)
        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_update_with_no_updates(self):
        test_metadata = {"aggregate": {}}
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
            self.req, "2", body=test_metadata)

    def test_update_with_wrong_updates(self):
        test_metadata = {"aggregate": {"status": "disable",
                                       "foo": "bar"}}
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_null_name(self):
        test_metadata = {"aggregate": {"name": ""}}
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_name_too_long(self):
        test_metadata = {"aggregate": {"name": "x" * 256}}
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
                          self.req, "2", body=test_metadata)

    def test_update_with_bad_aggregate(self):
        test_metadata = {"aggregate": {"name": "test_name"}}

        def stub_update_aggregate(context, aggregate, metadata):
            raise exception.AggregateNotFound(aggregate_id=2)
        self.stubs.Set(self.controller.api, "update_aggregate",
                       stub_update_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller.update,
                self.req, "2", body=test_metadata)

    def test_update_with_invalid_request(self):
        test_metadata = {"aggregate": 1}
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
            self.req, "2", body=test_metadata)

    def test_add_host(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertEqual("host1", host, "host")
            return AGGREGATE
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        aggregate = self.controller._add_host(self.req, "1",
                                           body={"add_host": {"host":
                                                              "host1"}})

        self.assertEqual(aggregate["aggregate"], AGGREGATE)
        self.assertEqual(self.controller._add_host.wsgi_code, 202)

    def test_add_host_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller._add_host,
                          self.user_req, "1",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_already_added_host(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise exception.AggregateHostExists(aggregate_id=aggregate,
                                                host=host)
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        self.assertRaises(exc.HTTPConflict, self.controller._add_host,
                          self.req, "1",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_bad_aggregate(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller._add_host,
                          self.req, "bogus_aggregate",
                          body={"add_host": {"host": "host1"}})

    def test_add_host_with_bad_host(self):
        def stub_add_host_to_aggregate(context, aggregate, host):
            raise exception.ComputeHostNotFound(host=host)
        self.stubs.Set(self.controller.api, "add_host_to_aggregate",
                       stub_add_host_to_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller._add_host,
                          self.req, "1",
                          body={"add_host": {"host": "bogus_host"}})

    def test_add_host_with_missing_host(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller._add_host,
                self.req, "1", body={"add_host": {}})

    def test_add_host_with_invalid_request(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller._add_host,
                self.req, "1", body={"add_host": 1})

    def test_add_host_with_non_string(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller._add_host,
                self.req, "1", body={"add_host": {"host": 1}})

    def test_remove_host(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertEqual("host1", host, "host")
            stub_remove_host_from_aggregate.called = True
            return {}
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)
        self.controller._remove_host(self.req, "1",
                               body={"remove_host": {"host": "host1"}})

        self.assertTrue(stub_remove_host_from_aggregate.called)
        self.assertEqual(self.controller._remove_host.wsgi_code, 202)

    def test_remove_host_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller._remove_host,
                          self.user_req, "1",
                          body={"remove_host": {"host": "host1"}})

    def test_remove_host_with_host_not_in_aggregate(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            raise exception.AggregateHostNotFound(aggregate_id=aggregate,
                                                  host=host)
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller._remove_host,
                          self.req, "1",
                          body={"remove_host": {"host": "host1"}})

    def test_remove_host_with_bad_host(self):
        def stub_remove_host_from_aggregate(context, aggregate, host):
            raise exception.ComputeHostNotFound(host=host)
        self.stubs.Set(self.controller.api,
                       "remove_host_from_aggregate",
                       stub_remove_host_from_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller._remove_host,
                self.req, "1", body={"remove_host": {"host": "bogushost"}})

    def test_remove_host_with_invalid_request(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller._remove_host,
                self.req, "1", body={"remove_host": 1})

    def test_remove_host_with_missing_host(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller._remove_host,
                self.req, "1", body={"remove_host": {}})

    def test_remove_host_with_missing_host(self):
        self.assertRaises(exc.HTTPBadRequest, self.controller._remove_host,
                self.req, "1", body={"remove_host": {"host": 1}})

    def test_set_metadata(self):
        body = {"set_metadata": {"metadata": {"foo": "bar"}}}

        def stub_update_aggregate(context, aggregate, values):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            self.assertThat(body["set_metadata"]['metadata'],
                            matchers.DictMatches(values))
            return AGGREGATE
        self.stubs.Set(self.controller.api,
                       "update_aggregate_metadata",
                       stub_update_aggregate)

        result = self.controller._set_metadata(self.req, "1", body=body)

        self.assertEqual(AGGREGATE, result["aggregate"])

    def test_set_metadata_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller._set_metadata,
                          self.user_req, "1",
                          body={"set_metadata": {"metadata":
                                                    {"foo": "bar"}}})

    def test_set_metadata_with_bad_aggregate(self):
        body = {"set_metadata": {"metadata": {"foo": "bar"}}}

        def stub_update_aggregate(context, aggregate, metadata):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api,
                       "update_aggregate_metadata",
                       stub_update_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller._set_metadata,
                self.req, "bad_aggregate", body=body)

    def test_set_metadata_with_missing_metadata(self):
        body = {"set_metadata": {}}
        self.assertRaises(exc.HTTPBadRequest, self.controller._set_metadata,
                          self.req, "1", body=body)

    def test_set_metadata_with_invalid_request(self):
        body = {"set_metadata": 1}
        self.assertRaises(exc.HTTPBadRequest, self.controller._set_metadata,
                          self.req, "1", body=body)

    def test_set_metadata_without_dict(self):
        body = {"set_metadata": {'metadata': 1}}
        self.assertRaises(exc.HTTPBadRequest, self.controller._set_metadata,
                          self.req, "1", body=body)

    def test_delete_aggregate(self):
        def stub_delete_aggregate(context, aggregate):
            self.assertEqual(context, self.context, "context")
            self.assertEqual("1", aggregate, "aggregate")
            stub_delete_aggregate.called = True
        self.stubs.Set(self.controller.api, "delete_aggregate",
                       stub_delete_aggregate)

        self.controller.delete(self.req, "1")
        self.assertTrue(stub_delete_aggregate.called)

    def test_delete_aggregate_no_admin(self):
        self.assertRaises(exception.PolicyNotAuthorized,
                          self.controller.delete,
                          self.user_req, "1")

    def test_delete_aggregate_with_bad_aggregate(self):
        def stub_delete_aggregate(context, aggregate):
            raise exception.AggregateNotFound(aggregate_id=aggregate)
        self.stubs.Set(self.controller.api, "delete_aggregate",
                       stub_delete_aggregate)

        self.assertRaises(exc.HTTPNotFound, self.controller.delete,
                self.req, "bogus_aggregate")


text:
class Instance::AsArray::ForName < Array
  attr_reader :results
  NO_YEAR = ''

  def initialize(name)
    @results = []
    @already_shown = []
    sorted_instances(name.instances.includes([{reference: :author}, :instance_type])).each do |instance|
      if instance.standalone?
        show_standalone_instance(instance)
      else
        show_relationship_instance(name, instance)
      end
    end
  end

  def debug(s)
    Rails.logger.debug("Instance::AsArray::ForName: #{s}")
  end

  def sorted_instances(instances)
    instances.sort do |i1, i2|
      sort_fields(i1) <=> sort_fields(i2)
    end
  end

  def sort_fields(instance)
    [instance.reference.year || instance.reference.try('parent').try('year') || NO_YEAR,
     instance.instance_type.primaries_first,
     instance.reference.iso_publication_date || instance.reference.try('parent').try('iso_publication_date') || NO_YEAR,
     instance.reference.author.try("name") || "x"]
  end

  def show_standalone_instance(instance)
    debug("show_standalone_instance #{instance.id}")
    standalone_instance_records(instance).each do |one_instance|
      one_instance.show_primary_instance_type = true
      one_instance.consider_apc = true
      @results.push(one_instance)
    end
  end

  # Work on a single standalone instance starts here.
  # - display the instance as part of a concept
  # - find all child instances using the cited_by_id column
  #   (all instances that say they are cited by the standalone instance)
  #   - display these relationship instances as cited_by the standalone instance
  def standalone_instance_records(instance)
    debug("show_standalone_instance_records #{instance.id}")
    results = [instance.display_as_part_of_concept]
    records_cited_by_standalone(instance)
      .each do |cited_by_original_instance|
        cited_by_original_instance.expanded_instance_type =
          cited_by_original_instance.instance_type.name
        cited_by_original_instance.display_as = "instance-is-cited-by"
        results.push(cited_by_original_instance)
      end
    results
  end

  def records_cited_by_standalone(instance)
    debug("records_cited_by_standalone for instance #{instance.id}")
    Instance.joins(:instance_type, :name, :reference)
            .includes(:instance_type)
            .where(cited_by_id: instance.id)
            .in_nested_instance_type_order
            .order("reference.iso_publication_date,lower(name.full_name)")
  end

  def show_relationship_instance(name, instance)
    citing_instance = instance.this_is_cited_by
    return if @already_shown.include?(citing_instance.id)
    relationship_instance_records(name, citing_instance).each do |element|
      element.consider_apc = false
      @results.push(element)
    end
    @already_shown.push(citing_instance.id)
  end

  # NSL-536: If instance name is not the subject name then
  # do not show the instance type.
  def relationship_instance_records(name, instance)
    results = [instance.display_as_citing_instance_within_name_search]
    records_cited_by_relationship(instance)
      .each do |cited_by_original_instance|
      next unless cited_by_original_instance.name.id == name.id
      cited_by_original_instance.expanded_instance_type =
        cited_by_original_instance.instance_type.name
      results.push(with_display_as(cited_by_original_instance))
    end
    results
  end

  def with_display_as(instance)
    debug("with_display_as for instance #{instance.id}")
    if instance.misapplied?
      instance.display_as = "cited-by-relationship-instance"
    else
      instance.display_as = "cited-by-relationship-instance-name-only"
    end
    instance
  end

  def records_cited_by_relationship(instance)
    debug("records_cited_by_relationship for instance #{instance.id}")
    Instance.joins(:instance_type)
            .where(cited_by_id: instance.id)
            .in_nested_instance_type_order
  end
end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.juddi.samples;

import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.wsdl.Definition;
import javax.wsdl.PortType;
import javax.xml.namespace.QName;

import org.apache.juddi.jaxb.PrintUDDI;
import org.apache.juddi.v3.client.config.UDDIClerk;
import org.apache.juddi.v3.client.config.UDDIClient;
import org.apache.juddi.v3.client.mapping.URLLocalizerDefaultImpl;
import org.apache.juddi.v3.client.mapping.wsdl.ReadWSDL;
import org.apache.juddi.v3.client.mapping.wsdl.WSDL2UDDI;
import org.apache.juddi.v3.client.transport.Transport;
import org.uddi.api_v3.AuthToken;
import org.uddi.api_v3.BusinessDetail;
import org.uddi.api_v3.BusinessEntity;
import org.uddi.api_v3.BusinessServices;
import org.uddi.api_v3.GetAuthToken;
import org.uddi.api_v3.Name;
import org.uddi.api_v3.SaveBusiness;
import org.uddi.api_v3.SaveService;
import org.uddi.api_v3.SaveTModel;
import org.uddi.api_v3.TModel;
import org.uddi.v3_service.UDDIPublicationPortType;
import org.uddi.v3_service.UDDISecurityPortType;

/**
 * This class shows how to perform a WSDL2UDDI import manually. More
 * specifically, this is WSDL2UDDI without using annotations.
 *
 * @author Alex O'Ree
 */
public class WsdlImport {

        private Properties properties = new Properties();
        private String wsdlURL = null;
        private UDDISecurityPortType security = null;
        private UDDIPublicationPortType publish = null;

        public static void main(String[] args) throws Exception {
                new WsdlImport().fire("http://svn.apache.org/repos/asf/juddi/trunk/uddi-ws/src/main/resources/juddi_api_v1.wsdl", null, null, null);
        }

        public void fire(String pathOrURL, String businessKey, String token, Transport transport) throws Exception {

                if (transport == null) {
                        // create a manager and read the config in the archive;
                        // you can use your config file name
                        UDDIClient clerkManager = new UDDIClient("META-INF/simple-publish-uddi.xml");
                        transport = clerkManager.getTransport();
                }
                // Now you create a reference to the UDDI API
                security = transport.getUDDISecurityService();
                publish = transport.getUDDIPublishService();

                if (token == null) {
                        //step one, get a token
                        GetAuthToken getAuthTokenRoot = new GetAuthToken();
                        getAuthTokenRoot.setUserID("uddi");
                        getAuthTokenRoot.setCred("uddi");

                        // Making API call that retrieves the authentication token for the 'root' user.
                        AuthToken rootAuthToken = security.getAuthToken(getAuthTokenRoot);
                        token = rootAuthToken.getAuthInfo();
                }

                //step two, identify the key used for all your stuff
                //you must have a key generator created already
                //here, we are assuming that you don't have one
                //NOTE: these are some of the publically available WSDLs that were used to test WSDL2UDDI
                //URL url = new URL("http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL");
                //http://www.bccs.uni.no/~pve002/wsdls/ebi-mafft.wsdl");
                //http://www.webservicex.net/GenericNAICS.asmx?WSDL");
                //http://www.webservicex.net/stockquote.asmx?WSDL");
                //http://www.webservicex.com/globalweather.asmx?WSDL");
                //http://graphical.weather.gov/xml/SOAP_server/ndfdXMLserver.php?wsdl");
                String domain = "localhost";
                int port = 80;
                if (pathOrURL.startsWith("http")) {
                        URL url = new URL(pathOrURL);
                        domain = url.getHost();
                        port = url.getPort();
                        if (port == -1) {
                                if (pathOrURL.startsWith("https://")) {
                                        port = 443;
                                }
                                if (pathOrURL.startsWith("http://")) {
                                        port = 80;
                                }

                        }
                }

                TModel keygen = UDDIClerk.createKeyGenator("uddi:" + domain + ":keygenerator", domain, "en");
                //save the keygen
                SaveTModel stm = new SaveTModel();
                stm.setAuthInfo(token);
                stm.getTModel().add(keygen);
                System.out.println("Saving key gen " + keygen.getTModelKey());
                publish.saveTModel(stm);
                System.out.println("Saved!");

                //step three, we have two options
                //1) import the wsdl's services into a brand new business
                //2) import the wsdl's services into an existing business
                //in either case, we're going to have to parse the WSDL
                ReadWSDL rw = new ReadWSDL();
                Definition wsdlDefinition = null;
                if (pathOrURL.startsWith("http")) {
                        wsdlDefinition = rw.readWSDL(new URL(pathOrURL));
                } else {
                        wsdlDefinition = rw.readWSDL(pathOrURL);
                }

                if (wsdlDefinition == null) {
                        System.out.println("There was an error parsing the WSDL!");
                        return;
                }
                properties.put("keyDomain", domain);
                properties.put("businessName", domain);
                properties.put("serverName", domain);
                properties.put("serverPort", port);
                wsdlURL = wsdlDefinition.getDocumentBaseURI();
                WSDL2UDDI wsdl2UDDI = new WSDL2UDDI(null, new URLLocalizerDefaultImpl(), properties);
                BusinessServices businessServices = wsdl2UDDI.createBusinessServices(wsdlDefinition);
                @SuppressWarnings("unchecked")
                Map<QName, PortType> portTypes = (Map<QName, PortType>) wsdlDefinition.getAllPortTypes();
                Set<TModel> portTypeTModels = wsdl2UDDI.createWSDLPortTypeTModels(wsdlURL, portTypes);
                Map allBindings = wsdlDefinition.getAllBindings();
                Set<TModel> createWSDLBindingTModels = wsdl2UDDI.createWSDLBindingTModels(wsdlURL, allBindings);
                //When parsing a WSDL, there's really two things going on
                //1) convert a bunch of stuff (the portTypes) to tModels
                //2) convert the service definition to a BusinessService

                //Since the service depends on the tModel, we have to save the tModels first
                stm = new SaveTModel();
                stm.setAuthInfo(token);

                TModel[] tmodels = portTypeTModels.toArray(new TModel[0]);
                for (int i = 0; i < tmodels.length; i++) {
                        stm.getTModel().add(tmodels[i]);
                }

                tmodels = createWSDLBindingTModels.toArray(new TModel[0]);
                for (int i = 0; i < tmodels.length; i++) {
                        stm.getTModel().add(tmodels[i]);
                }

                //important, you'll need to save your new tModels first, or else saving the business/service may fail
                System.out.println(new PrintUDDI<SaveTModel>().print(stm));
                System.out.println("Saving " + stm.getTModel().size() + " tModels");
                publish.saveTModel(stm);
                System.out.println("Saved!");

                if (businessKey == null || businessKey.length() == 0) {
                        SaveBusiness sb = new SaveBusiness();
                        sb.setAuthInfo(token);
                        BusinessEntity be = new BusinessEntity();
                        be.setBusinessKey(businessServices.getBusinessService().get(0).getBusinessKey());
                        be.getName().add(new Name());
                        be.getName().get(0).setValue(domain);
                        be.getName().get(0).setLang("en");
                        sb.getBusinessEntity().add(be);
                        BusinessDetail saveBusiness = publish.saveBusiness(sb);
                        businessKey = saveBusiness.getBusinessEntity().get(0).getBusinessKey();
                        System.out.println("new business created key= " + businessKey);
                }

                //finaly, we're ready to save all of the services defined in the WSDL
                //again, we're creating a new business, if you have one already, look it up using the Inquiry getBusinessDetails
                SaveService ss = new SaveService();
                ss.setAuthInfo(token);
                for (int i = 0; i < businessServices.getBusinessService().size(); i++) {
                        businessServices.getBusinessService().get(i).setBusinessKey(businessKey);
                        ss.getBusinessService().add(businessServices.getBusinessService().get(i));

                }

                System.out.println("Here's our new service(s): " + new PrintUDDI<SaveService>().print(ss));

                publish.saveService(ss);
                System.out.println("Saved!");

                //and we're done
                //Be sure to report any problems to the jUDDI JIRA bug tracker at
                //https://issues.apache.org/jira/browse/JUDDI
        }
}


text:
<?php

// $Id$

require_once('../../../../boot.inc.php');
boot('my_site_adm');

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/forms/_ci/ci_article/ci_article_form_ajax_ctrl.class.php');

session_start();

global $_MODULES_REGISTER;
$user_auth_config = $_MODULES_REGISTER->get_module_config('admin_user_auth');

$f_ajax_ctrl = new CI_Article_Form_Ajax_Ctrl($WSC->get_tpl_dir().'modules/tangra_cms/forms/ci_article_form.tpl', $user_auth_config);
$context = new Web_Context();
$SITE->run_other($f_ajax_ctrl, $context);


text:
using System;
using Xunit;

namespace Popsql.Tests
{
	public class SqlBinaryExpressionTests
	{
		[Fact]
		public void Ctor_WithNullLeftOperand_ThrowsArgumentNull()
		{
			Assert.Throws<ArgumentNullException>(() => new SqlBinaryExpression(null, SqlBinaryOperator.Equal, (SqlConstant)5));
		}

		[Fact]
		public void Ctor_WithNullRightOperand_ThrowsArgumentNull()
		{
			Assert.Throws<ArgumentNullException>(() => new SqlBinaryExpression((SqlConstant)5, SqlBinaryOperator.Equal, null));
		}

		[Fact]
		public void Ctor_WithLeftAndRightOperand_SetsPropertyValues()
		{
			var left = new SqlConstant(5);
			var @operator = SqlBinaryOperator.Equal;
			var right = new SqlConstant(1);
			var expression = new SqlBinaryExpression(left, @operator, right);

			Assert.NotNull(expression.Left);
			Assert.Same(left, expression.Left);
			Assert.Equal(@operator, expression.Operator);
			Assert.NotNull(expression.Right);
			Assert.Same(right, expression.Right);
		}

		[Fact]
		public void ExpressionType_ReturnsBinary()
		{
			var expression = new SqlBinaryExpression((SqlConstant)1, SqlBinaryOperator.Equal, (SqlConstant)1);
			Assert.Equal(SqlExpressionType.Binary, expression.ExpressionType);
		}
	}
}


text:
from neutron.common import exceptions as n_exc
from neutron.core_extensions import base
from neutron.db import api as db_api
from neutron import manager
from neutron.objects.qos import policy as policy_object
from neutron.plugins.common import constants as plugin_constants
from neutron.services.qos import qos_consts

class QosCoreResourceExtension(base.CoreResourceExtension):

    @property
    def plugin_loaded(self):
        if not hasattr(self, '_plugin_loaded'):
            service_plugins = manager.NeutronManager.get_service_plugins()
            self._plugin_loaded = plugin_constants.QOS in service_plugins
        return self._plugin_loaded

    def _get_policy_obj(self, context, policy_id):
        obj = policy_object.QosPolicy.get_object(context, id=policy_id)
        if obj is None:
            raise n_exc.QosPolicyNotFound(policy_id=policy_id)
        return obj

    def _check_policy_change_permission(self, context, old_policy):
        """An existing policy can be modified only if one of the following is
        true:

              the policy's tenant is the context's tenant
              the policy is shared with the tenant

        Using is_accessible expresses these conditions.
        """
        if not (policy_object.QosPolicy.is_accessible(context, old_policy)):
            raise n_exc.PolicyRemoveAuthorizationError(policy_id=old_policy.id)

    def _update_port_policy(self, context, port, port_changes):
        old_policy = policy_object.QosPolicy.get_port_policy(
            context.elevated(), port['id'])
        if old_policy:
            self._check_policy_change_permission(context, old_policy)
            old_policy.detach_port(port['id'])

        qos_policy_id = port_changes.get(qos_consts.QOS_POLICY_ID)
        if qos_policy_id is not None:
            policy = self._get_policy_obj(context, qos_policy_id)
            policy.attach_port(port['id'])
        port[qos_consts.QOS_POLICY_ID] = qos_policy_id

    def _update_network_policy(self, context, network, network_changes):
        old_policy = policy_object.QosPolicy.get_network_policy(
            context.elevated(), network['id'])
        if old_policy:
            self._check_policy_change_permission(context, old_policy)
            old_policy.detach_network(network['id'])

        qos_policy_id = network_changes.get(qos_consts.QOS_POLICY_ID)
        if qos_policy_id is not None:
            policy = self._get_policy_obj(context, qos_policy_id)
            policy.attach_network(network['id'])
        network[qos_consts.QOS_POLICY_ID] = qos_policy_id

    def _exec(self, method_name, context, kwargs):
        with db_api.autonested_transaction(context.session):
            return getattr(self, method_name)(context=context, **kwargs)

    def process_fields(self, context, resource_type,
                       requested_resource, actual_resource):
        if (qos_consts.QOS_POLICY_ID in requested_resource and
            self.plugin_loaded):
            self._exec('_update_%s_policy' % resource_type, context,
                       {resource_type: actual_resource,
                        "%s_changes" % resource_type: requested_resource})

    def extract_fields(self, resource_type, resource):
        if not self.plugin_loaded:
            return {}

        binding = resource['qos_policy_binding']
        qos_policy_id = binding['policy_id'] if binding else None
        return {qos_consts.QOS_POLICY_ID: qos_policy_id}


text: This directory contains the C API of the valid number system.


text:
package org.neo4j.jdbc.bolt.impl;

import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.jdbc.Neo4jDatabaseMetaData;
import org.neo4j.jdbc.Neo4jResultSet;
import org.neo4j.jdbc.bolt.*;
import org.neo4j.jdbc.impl.Neo4jConnectionImpl;
import org.neo4j.jdbc.utils.Neo4jInvocationHandler;
import org.neo4j.jdbc.utils.TimeLimitedCodeBlock;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author AgileLARUS
 * @since 3.0.0
 */
public class BoltNeo4jConnectionImpl extends Neo4jConnectionImpl implements BoltNeo4jConnection {

	private Session     session;
	private Transaction transaction;
	private boolean autoCommit = true;

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

	/**
	 * Constructor with Session and Properties.
	 *
	 * @param session    Bolt Session
	 * @param properties Driver properties
	 * @param url        Url used for this connection
	 */
	public BoltNeo4jConnectionImpl(Session session, Properties properties, String url) {
		super(properties, url, BoltNeo4jResultSet.DEFAULT_HOLDABILITY);
		this.session = session;
	}

	/**
	 * Constructor with Session.
	 *
	 * @param session Bolt Session
	 */
	public BoltNeo4jConnectionImpl(Session session) {
		this(session, new Properties(), "");
	}

	public static BoltNeo4jConnection newInstance(Session session, Properties info, String url) {
		BoltNeo4jConnection boltConnection = new BoltNeo4jConnectionImpl(session, info, url);
		return (BoltNeo4jConnection) Proxy
				.newProxyInstance(BoltNeo4jConnectionImpl.class.getClassLoader(), new Class[] { Connection.class, BoltNeo4jConnection.class },
						new Neo4jInvocationHandler(boltConnection, BoltNeo4jConnectionImpl.hasDebug(info)));
	}

	/**
	 * Getter for transaction.
	 *
	 * @return the transaction
	 */
	@Override public Transaction getTransaction() {
		return this.transaction;
	}

	/**
	 * Getter for session.
	 *
	 * @return the internal session
	 */
	@Override public Session getSession() {
		return this.session;
	}

	@Override public Neo4jDatabaseMetaData getMetaData() throws SQLException {
		return new BoltNeo4jDatabaseMetaData(this);
	}

	/*------------------------------*/
	/*       Commit, rollback       */
	/*------------------------------*/

	@Override public void setAutoCommit(boolean autoCommit) throws SQLException {
		if (this.autoCommit != autoCommit) {
			if (this.transaction != null && !this.autoCommit) {
				this.commit();
				this.transaction.close();
			}

			if (this.autoCommit) {
				//Simply restart the transaction
				this.transaction = this.session.beginTransaction();
			}

			this.autoCommit = autoCommit;
		}
	}

	@Override public boolean getAutoCommit() throws SQLException {
		this.checkClosed();
		return autoCommit;
	}

	@Override public void commit() throws SQLException {
		this.checkClosed();
		this.checkAutoCommit();
		if (this.transaction == null) {
			throw new SQLException("The transaction is null");
		}
		this.transaction.success();
		this.transaction.close();
		this.transaction = this.session.beginTransaction();
	}

	@Override public void rollback() throws SQLException {
		this.checkClosed();
		this.checkAutoCommit();
		if (this.transaction == null) {
			throw new SQLException("The transaction is null");
		}
		this.transaction.failure();
	}

	/*------------------------------*/
	/*       Create Statement       */
	/*------------------------------*/

	@Override public Statement createStatement() throws SQLException {
		if (this.transaction == null && !this.autoCommit) {
			this.transaction = this.session.beginTransaction();
		}
		return createStatement(Neo4jResultSet.TYPE_FORWARD_ONLY, Neo4jResultSet.CONCUR_READ_ONLY, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);
	}

	@Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
		return createStatement(resultSetType, resultSetConcurrency, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);
	}

	@Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
		this.checkClosed();
		this.checkTypeParams(resultSetType);
		this.checkConcurrencyParams(resultSetConcurrency);
		this.checkHoldabilityParams(resultSetHoldability);
		return BoltNeo4jStatement.newInstance(false, this, resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	/*-------------------------------*/
	/*       Prepare Statement       */
	/*-------------------------------*/

	@Override public PreparedStatement prepareStatement(String sql) throws SQLException {
		return prepareStatement(nativeSQL(sql), Neo4jResultSet.TYPE_FORWARD_ONLY, Neo4jResultSet.CONCUR_READ_ONLY, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);
	}

	@Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
		return prepareStatement(nativeSQL(sql), resultSetType, resultSetConcurrency, Neo4jResultSet.CLOSE_CURSORS_AT_COMMIT);
	}

	@Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
		this.checkClosed();
		this.checkTypeParams(resultSetType);
		this.checkConcurrencyParams(resultSetConcurrency);
		this.checkHoldabilityParams(resultSetHoldability);
		return BoltNeo4jPreparedStatement.newInstance(false, this, nativeSQL(sql), resultSetType, resultSetConcurrency, resultSetHoldability);
	}

	/*-------------------*/
	/*       Close       */
	/*-------------------*/

	@Override public boolean isClosed() throws SQLException {
		return !this.session.isOpen();
	}

	@Override public void close() throws SQLException {
		try {
			if (!this.isClosed()) {
				session.close();
			}
		} catch (Exception e) {
			throw new SQLException("A database access error has occurred: " + e.getMessage());
		}
	}

	/*-------------------*/
	/*      isValid      */
	/*-------------------*/
	@Override public boolean isValid(int timeout) throws SQLException {
		if (timeout < 0) {
			throw new SQLException("Timeout can't be less than zero");
		}
		if (this.isClosed()) {
			return false;
		}

		Runnable r = new Runnable() {
			@Override public void run() {
				Session s = getSession();
				Transaction tr = getTransaction();
				if (tr != null && tr.isOpen()) {
					tr.run(FASTEST_STATEMENT);
				} else {
					s.run(FASTEST_STATEMENT);
				}
			}
		};

		try {
			TimeLimitedCodeBlock.runWithTimeout(r, timeout, TimeUnit.SECONDS);
		} catch (Exception e) { // also timeout
			LOGGER.log(Level.FINEST, "Catch exception totally fine", e);
			return false;
		}

		return true;
	}

}


text:
package com.bird.shen.hotweather.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.bird.shen.hotweather.model.City;
import com.bird.shen.hotweather.model.Country;
import com.bird.shen.hotweather.model.Province;

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

/**
 * Create a database ,name is HotWeatherDB
 */
public class HotWeatherDB {

          // define a name of database

          public   static  final  String DB_NAME = "hot_weather";

          // the version of database

          public   static  final  int  VERSION = 1 ;

          private  static  HotWeatherDB  hotWeatherDB ;

          private SQLiteDatabase  db;

          // Privatization construction method

          private HotWeatherDB(Context context) {

                    HotWeatherOpenHelper dbHelper = new HotWeatherOpenHelper(context,DB_NAME,null,VERSION);

                    db = dbHelper.getWritableDatabase();  // Write tables to database.

          }

          // get HotWeatherDB instance

          public synchronized  static  HotWeatherDB  getInstance(Context context){

                    if (hotWeatherDB == null){

                              hotWeatherDB = new HotWeatherDB(context);

                    }

                    return hotWeatherDB;

          }

           //  make the Province instance deposit into HotWeatherDB

          public void saveProvince(Province province){

                    if (province != null){

                              ContentValues  values = new ContentValues();

                              values.put("province_name",province.getProvinceName());
                              values.put("province_code",province.getProvincecode());

                              db.insert("Province",null,values); // the firse parame is table`s name
                    }

          }

     // read the Province information from the database

          public List<Province> loadProvinces(){

                    List<Province> list = new ArrayList<Province>();

                    Cursor cursor = db.query("Province",null,null,null,null,null,null); //the database`s query sentence has 7 parames ,first is table`s name

                    if (cursor.moveToFirst()){

                              do {
                                        Province province = new Province();
                                        province.setId(cursor.getInt(cursor.getColumnIndex("id")));
                                        province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
                                        province.setProvincecode(cursor.getString(cursor.getColumnIndex("province_code")));
                                        list.add(province);

                              }while (cursor.moveToNext());

                    }

                    if (cursor != null){

                              cursor.close();
                    }

                    return list;

          }

          // make the City instance deposit into datebase

          public  void  saveCities(City city){

                    ContentValues values = new ContentValues();

                    values.put("city_name",city.getCityName());
                    values.put("city_code",city.getCityCode());
                    values.put("province_id",city.getProvinceId());

                    db.insert("City",null,values);

          }

          // read the Province information from the database

          public  List<City> loadcities(int provinceId){

                    List<City> list = new ArrayList<City>();

                    Cursor cursor = db.query("City",null,"province_id = ?",new String[]{String.valueOf(provinceId)},null,null,null);

                    // the first is table`s name , the third is lookup culumn , the Fourth is values of culumns

                    if (cursor.moveToFirst()){

                              do {

                                        City city = new City();

                                        city.setId(cursor.getInt(cursor.getColumnIndex("id")));
                                        city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
                                        city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
                                        city.setProvinceId(provinceId);

                                        list.add(city);

                              }while (cursor.moveToNext());

                    }

                    if (cursor != null){

                              cursor.close();
                    }

                    return  list;
          }

          // make the country instance deposit into database

           public  void  saveCountry(Country country){

                     ContentValues values = new ContentValues();

                     values.put("country_name",country.getCountryName());
                     values.put("country_code",country.getCountryCode());
                     values.put("city_id",country.getCityId());

                     db.insert("Country",null,values);
           }

          // read the Country information from the database

          public  List<Country> loadCountries(int cityId){

                    List<Country> list = new ArrayList<Country>();

                    Cursor cursor = db.query("Country",null,"city_id = ?",new String[]{String.valueOf(cityId)},null,null,null);

                    if (cursor.moveToFirst()){

                              do {

                                        Country country = new Country();

                                        country.setId(cursor.getInt(cursor.getColumnIndex("id")));
                                        country.setCountryName(cursor.getString(cursor.getColumnIndex("country_name")));
                                        country.setCountryCode(cursor.getString(cursor.getColumnIndex("country_code")));
                                        country.setCityId(cityId);

                                        list.add(country);
                              }while (cursor.moveToNext());

                    }

                    if (cursor != null){

                              cursor.close();
                    }

                    return  list;
          }

}


text:
using namespace eosio;

void payloadless::doit() {
   print("Im a payloadless action");
}


text:
var chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.config.includeStack = true;
chai.use(chaiAsPromised);
var expect = chai.expect;
chai.should();

// Connect to Cassandra.
var Castor = require('../castor-client');
var db = new Castor('localhost', 'castortest');

describe('Collections', function() {
  it('can be read', function() {
    return db.get('collections')
      .filter('id', 1)
    .then(function(rows) {
      if (!rows.valid()) {
        throw Error('Row not found');
      }
      return rows.current();
    }).then(function(row) {
      expect(row.test_list).to.deep.equal(['Alice', 'Bob']);
      expect(row.test_set.sort()).to.deep.equal(['Alice', 'Bob']);
      expect(row.test_map).to.deep.equal({Alice: 10, Bob: 20});
    });
  });

  it('can be set', function() {
    return db.set('collections')
      .field('id', 2)
      .field('test_list', ['Alice', 'Bob', 'Chris'])
      .field('test_set', ['Alice', 'Bob', 'Chris'])
      .field('test_map', {first: 1, second: 2})
    .then(function() {
      return db.get('collections')
        .filter('id', 2)
        .execute();
    }).then(function(rows) {
      if (!rows.valid()) {
        throw Error('Row not found');
      }
      return rows.current();
    }).then(function(row) {
      expect(row.test_list).to.deep.equal(['Alice', 'Bob', 'Chris']);
      expect(row.test_set.sort()).to.deep.equal(['Alice', 'Bob', 'Chris']);
      expect(row.test_map).to.deep.equal({first: 1, second: 2});
    });
  });

  it('cannot accept strings for list', function() {
    db.set('collections')
      .field('id', 3)
      .field('test_list', 'test')
      .execute().should.be.rejected;
  });

  it('cannot accept arrays for maps', function() {
    db.set('collections')
      .field('id', 3)
      .field('test_map', ['first', 'second'])
      .execute().should.be.rejected;
  });

  it('cannot accept strings for maps', function() {
    db.set('collections')
      .field('id', 3)
      .field('test_map', 'test')
      .execute().should.be.rejected;
  });

  it('cannot accept strings for set', function() {
    db.set('collections')
      .field('id', 3)
      .field('test_set', 'test')
      .execute().should.be.rejected;
  });
});


text:
<?php

class Braintree_Payments_Block_Adminhtml_Form_Field_Countrycreditcard
    extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract
{
    protected $_countryRenderer = null;
    protected $_ccTypesRenderer = null;

    /**
     * Returns renderer for country element
     *
     * @return Braintree_Payments_Block_Adminhtml_Form_Field_Countries
     */
    protected function _getCountryRenderer()
    {
        if (!$this->_countryRenderer) {
            $this->_countryRenderer = $this->getLayout()->createBlock(
                'braintree_payments/adminhtml_form_field_countries',
                '',
                array('is_render_to_js_template' => true)
            );
        }
        return $this->_countryRenderer;
    }

    /**
     * Returns renderer for country element
     *
     * @return Braintree_Payments_Block_Adminhtml_Form_Field_Countries
     */
    protected function _getCcTypesRenderer()
    {
        if (!$this->_ccTypesRenderer) {
            $this->_ccTypesRenderer = $this->getLayout()->createBlock(
                'braintree_payments/adminhtml_form_field_cctypes',
                '',
                array('is_render_to_js_template' => true)
            );
        }
        return $this->_ccTypesRenderer;
    }

    /**
     * Prepare to render
     */
    protected function _prepareToRender()
    {
        $this->addColumn(
            'country_id',
            array(
                'label'     => Mage::helper('braintree_payments')->__('Country'),
                'renderer'  => $this->_getCountryRenderer(),
            )
        );
        $this->addColumn(
            'cc_types',
            array(
                'label' => Mage::helper('braintree_payments')->__('Allowed Credit Card Types'),
                'renderer'  => $this->_getCcTypesRenderer(),
            )
        );
        $this->_addAfter = false;
        $this->_addButtonLabel = Mage::helper('braintree_payments')->__('Add Rule');
    }

    /**
     * Prepare existing row data object
     *
     * @param Varien_Object
     */
    protected function _prepareArrayRow(Varien_Object $row)
    {
        $data = $row->getData();
        $country = isset($data['_id']) ? $data['_id'] : false;
        if ($country) {
            unset($data['_id']);
            $row->setData(
                'option_extra_attr_' . $this->_getCountryRenderer()->calcOptionHash($country), 'selected="selected"'
            );

            foreach ($data as $cardType) {
                $row->setData(
                    'option_extra_attr_' . $this->_getCcTypesRenderer()->calcOptionHash($cardType),
                    'selected="selected"'
                );
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>The cloudi_service_http_elli application</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Modules

cloudi_http_elli_handler

cloudi_service_http_elli


text:
.. ref-commands:

==================
Commands Reference
==================

pypushwoosh.command
-------------------

.. automodule:: pypushwoosh.command
    :members:
    :undoc-members:


text:
from tests.isolated_testcase import IsolatedTestCase

class CoalaLowercaseTest(IsolatedTestCase):

    def test_coala_lowercase(self):
        self.assertCommand('what is Coala?',
                           'coala is always written with a lower case c')

    def test_cep(self):
        self.assertCommand('what is a CEP?',
                           'cEP is always written with a lower case c')


text:
//
//  unicode/version.h
//
//  Author:     Sophia Lee
//  Created:    2017. 06. 22. 16:02
//  Copyright (c) 2017 Sophia Lee. All rights reserved.
//

/// \file
/// \brief  Version information of Unicode.
#ifndef _SESHAT_UNICODE_VERSION_H
#define _SESHAT_UNICODE_VERSION_H

#include <cstdint>

namespace seshat {
namespace unicode {

/// \brief  Struct for containing version information.
///
/// Lexicographical comparison is used for comparing operations.
struct Version {
    uint8_t major;
    uint8_t minor;
    uint8_t update;
};

/// \brief  Unicode major version.
constexpr uint8_t UnicodeVersionMajor = 10;
/// \brief  Unicode minor version.
constexpr uint8_t UnicodeVersionMinor = 0;
/// \brief  Unicode update version.
constexpr uint8_t UnicodeVersionUpdate = 0;

/// \brief  Unicode version that Seshat currently using.
constexpr Version UnicodeVersion = {
    UnicodeVersionMajor,
    UnicodeVersionMinor,
    UnicodeVersionUpdate
};

// Do not use the below macro constants since these are not intended
// to use currently.
// It could be deprecated in future version.
#define UNICODE_VERSION_MAJOR 10
#define UNICODE_VERSION_MINOR 0
#define UNICODE_VERSION_UPDATE 0
namespace emoji {
    /// \brief  Emoji major version.
    constexpr uint8_t EmojiVersionMajor = 5;
    /// \brief  Emoji minor version.
    constexpr uint8_t EmojiVersionMinor = 0;

    /// \brief  Emoji version that Seshat currently using.
    ///
    /// The update version is always 0 since there is no update version in
    /// Emoji specification.
    constexpr Version EmojiVersion = {
        EmojiVersionMajor,
        EmojiVersionMinor,
        0 // Not used
    };
} // namespace emoji

// Comparison operators for struct Version.
// Operations are defined as constexpr so can be used compile time assertion.
constexpr bool operator==(const Version& lhs, const Version& rhs)
{
    return (lhs.major == rhs.major &&
        lhs.minor == rhs.minor && lhs.update == rhs.update);
}

constexpr bool operator!=(const Version& lhs, const Version& rhs)
{
    return !(lhs == rhs);
}

constexpr bool operator<(const Version& lhs, const Version& rhs)
{
    return (lhs.major < rhs.major) ? true :
        ((lhs.major == rhs.major && lhs.minor < rhs.minor) ? true :
        ((lhs.minor == rhs.minor && lhs.update < rhs.update) ? true : false));
}

constexpr bool operator>(const Version& lhs, const Version& rhs)
{
    return ((lhs != rhs) && !(lhs < rhs));
}

constexpr bool operator<=(const Version& lhs, const Version& rhs)
{
    return (lhs < rhs || lhs == rhs);
}

constexpr bool operator>=(const Version& lhs, const Version& rhs)
{
    return (lhs > rhs || lhs == rhs);
}

} // namespace unicode

using unicode::Version;

} // namespace seshat

#endif /* _SESHAT_UNICODE_VERSION_H */


text:
package gov.nist.csd.pm.application.workflow.creator;

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import gov.nist.csd.pm.common.action.PMKit;

import javax.swing.*;

/**
 * Created by IntelliJ IDEA.
 * User: R McHugh
 * Date: 7/27/11
 * Time: 12:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class CreatorModule extends AbstractModule {
    @Override
    protected void configure() {
         bind(Action.class).annotatedWith(Names.named(CreatorKit.SUBMIT_WORKFLOW_ACTION_ID)).to(SubmitWorkflowAction.class);
         bind(PMKit.class).to(CreatorKit.class);
    }
}


text:
<?php

/**
 * This file is part of the FOSCommentBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace FOS\CommentBundle\FormFactory;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormFactoryInterface;

/**
 * CommentForm factory class.
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Tim Nagel <tim@nagel.com.au>
 */
class CommentFormFactory implements CommentFormFactoryInterface
{
    /**
     * @var FormFactoryInterface
     */
    protected $formFactory;

    /**
     * @var string
     */
    protected $type;

    /**
     * @var string
     */
    protected $name;

    /**
     * Constructor.
     *
     * @param FormFactoryInterface $formFactory
     * @param string               $type
     * @param string               $name
     */
    public function __construct(FormFactoryInterface $formFactory, $type, $name)
    {
        $this->formFactory = $formFactory;
        $this->type        = $type;
        $this->name        = $name;
    }

    /**
     * Creates a new form.
     *
     * @return FormInterface
     */
    public function createForm()
    {
        $builder = $this->formFactory->createNamedBuilder($this->name, $this->type);

        return $builder->getForm();
    }
}


text:
package be.peopleware.jsf_II.convert;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * Converter for {@link Class}. The value must be the FQCN of the class.
 *
 * To activate this, the following entry has to appear in faces-config.xml:
 *

 * <converter>
 *   <converter-for-class>java.lang.Class</converter-for-class>
 *   <converter-class>be.peopleware.jsf_I.convert.ClassConverter</converter-class>
 * </converter>
 *

 *
 * @author Wim Lambrechts
 * @author René Clerckx
 * @author Jan Dockx
 * @author Peopleware n.v.
 *
 * @todo (jand) Toryt
 */
public class ClassConverter implements Converter {

  /*
*/
  //------------------------------------------------------------------
  /** {@value} */
  public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$
  /** {@value} */
  public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$
  /** {@value} */
  public static final String CVS_STATE = "$State$"; //$NON-NLS-1$
  /** {@value} */
  public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$
  /*
*/

  /**
   * @return (value != null) ? Class.forName(value) : null;
   * @throws ConverterException
   *         ; the class with FQCN value could not be loaded.
   */
  public Object getAsObject(FacesContext context, UIComponent component, String value)
      throws ConverterException {
    if (value == null) {
      return null;
    }
    else {
      try {
        return Class.forName(value);
      }
      catch (Throwable e) {
        throw new ConverterException("class with name " + value + "could not be loaded");
      }
    }
  }

  public final static String EMPTY = "";

  /**
   * @return (value != null) ? value.getName() : EMPTY;
   * @throws ConverterException
   *         ! value instanceof Class
   */
  public String getAsString(FacesContext context, UIComponent component, Object value)
      throws ConverterException {
    if (value == null) {
      return EMPTY;
    }
    if (! (value instanceof Class)) {
      throw new ConverterException("value is not a Class");
    }
    return ((Class)value).getName();
  }

}


text:
import java.util.Arrays;
import java.util.Base64;
import static java.lang.System.out;

class Base64Java {

    final static int STR_SIZE = 131072;
    final static int TRIES = 8192;

    final static Base64.Decoder dec = Base64.getDecoder();
    final static Base64.Encoder enc = Base64.getEncoder();

    private static void notify(final String msg) {
        try (final var socket = new java.net.Socket("localhost", 9001);
             final var out = socket.getOutputStream()) {
            out.write(msg.getBytes("UTF-8"));
        } catch (java.io.IOException e) {
            // standalone usage
        }
    }

    public static void main(String[] args){
        for (final var fixture: new String[][]{
                {"hello", "aGVsbG8="}, {"world", "d29ybGQ="}
            }) {
            final var src = fixture[0];
            final var dst = fixture[1];
            final var encoded = enc.encodeToString(src.getBytes());
            if (!encoded.equals(dst)) {
                System.err.printf("%s != %s\n", encoded, dst);
                System.exit(1);
            }
            final var decoded = new String(dec.decode(dst));
            if (!decoded.equals(src)) {
                System.err.printf("%s != %s\n", decoded, src);
                System.exit(1);
            }
        }

        final var str = new byte[STR_SIZE];
        Arrays.fill(str, (byte)'a');
        final var str2 = enc.encodeToString(str);
        final var encoded = str2.getBytes();
        final var b_arr = dec.decode(encoded);

        notify("Java\t" + ProcessHandle.current().pid());

        var s_encoded = 0;
        final var t = System.nanoTime();
        for (var i = 0 ; i < TRIES ; i++) {
            s_encoded += enc.encodeToString(str).length();
        }
        final var t_encoded = (System.nanoTime() - t) / 1e9;

        var s_decoded = 0;
        final var t1 = System.nanoTime();
        for (var i = 0 ; i < TRIES ; i++) {
            s_decoded += dec.decode(encoded).length;
        }
        final var t_decoded = (System.nanoTime() - t1) / 1e9;

        notify("stop");

        out.println(
            String.format(
                "encode %s... to %s...: %d, %.2f",
                new String(Arrays.copyOf(str, 4)),
                str2.substring(0, 4),
                s_encoded, t_encoded));

        out.println(
            String.format("decode %s... to %s...: %d, %.2f",
                          str2.substring(0, 4),
                          new String(Arrays.copyOf(b_arr, 4)),
                          s_decoded, t_decoded));
        out.println("overall time: " + (t_encoded + t_decoded) + "s");
    }
}


text:
.PHONY: build_for_testing
build_for_testing:
	python setup.py build_ext --inplace

.PHONY: clean
clean:
	rm -f zigzag/*.so
	rm -f zigzag/*.c
	rm -f zigzag/*.html

.PHONY: test
test:
	python setup.py nosetests

.PHONY: test_with_coverage
test_with_coverage:
	CYTHON_DEBUG=1 coverage run setup.py nosetests

.PHONY: coverage
coverage: clean test_with_coverage
	coverage html -i
	open htmlcov/index.html

.PHONY: profile
profile: clean test_with_coverage
	cython --annotate-coverage coverage.xml zigzag/*.pyx
	open zigzag

.PHONY: analyze
analyze: clean test_with_coverage
	coverage html -i
	cython --annotate-coverage coverage.xml zigzag/*.pyx
	open htmlcov/index.html
	open zigzag

.PHONY: docs
docs: build_for_testing
	cd docs && sphinx-apidoc -f -o source ../zigzag
	$(MAKE) -C docs html

.PHONY: gh-pages
gh-pages: ensure_clean docs
	git checkout gh-pages
	cp -r docs/build/html/* ./
	git add .
	@-git commit -m 'Update documentation'  # Don't fail if no changes.
	git checkout master

.PHONY: ensure_clean
ensure_clean:
ifeq ($(shell git status | grep "working directory clean"), )
	$(error Commit changes before generating docs)
endif


text:
<?php
declare(strict_types=1);
namespace Ivory\Exception;

use Ivory\Lang\Sql\SqlState;

/**
 * Exception thrown upon errors on querying the database.
 *
 * The exception message contains the primary error message. To get the SQL State code, use {@link getSqlStateCode()}
 * method. To recognize SQLSTATE codes, {@link \Ivory\Result\SqlState} constants might be helpful. Alternatively,
 * {@link StatementException::getSqlState()} may be used to get an {@link SqlState} object.
 *
 * Besides the primary message and SQLSTATE code, the exception holds the error message detail, error hint, and all the
 * other error diagnostic fields except those referring to PostgreSQL source code (those referred to by the PHP
 * `PGSQL_DIAG_SOURCE_*` constants).
 *
 * This class is expected to be sub-classed by custom exception classes. *Any such subclasses are required to have the
 * same constructor arguments as this class, and are required to pass these arguments to the constructor of this class.*
 * See {@link StatementExceptionFactory} and its usages - either the global
 * {@link \Ivory\Ivory::getStatementExceptionFactory()} or the local
 * {@link \Ivory\Connection::getStatementExceptionFactory()} - for details on using custom statement exceptions.
 */
class StatementException extends \RuntimeException
{
    private $query;
    private $errorFields = [];

    /**
     * @param resource $resultHandler a PostgreSQL query result resource
     * @param string $query the statement, as sent by the client, which caused the error
     */
    public function __construct($resultHandler, string $query)
    {
        $message = self::inferMessage($resultHandler);

        parent::__construct($message); // NOTE: SQL state code (string) cannot be used as the exception code (int)

        $this->query = $query;

        $fields = [
            PGSQL_DIAG_SQLSTATE,
            PGSQL_DIAG_SEVERITY,
            PGSQL_DIAG_MESSAGE_DETAIL,
            PGSQL_DIAG_MESSAGE_HINT,
            PGSQL_DIAG_STATEMENT_POSITION,
            PGSQL_DIAG_INTERNAL_QUERY,
            PGSQL_DIAG_INTERNAL_POSITION,
            PGSQL_DIAG_CONTEXT,
        ];
        if (PHP_VERSION_ID >= 70300) {
            /** @noinspection PhpUndefinedConstantInspection */
            $fields[] = PGSQL_DIAG_SEVERITY_NONLOCALIZED;
        }
        foreach ($fields as $f) {
            $this->errorFields[$f] = pg_result_error_field($resultHandler, $f);
        }
    }

    private static function inferMessage($resultHandler): string
    {
        $message = pg_result_error_field($resultHandler, PGSQL_DIAG_MESSAGE_PRIMARY);
        if (strlen($message) > 0) {
            return $message;
        }

        switch (pg_result_status($resultHandler)) {
            case PGSQL_EMPTY_QUERY:
                return 'Empty query';
            case PGSQL_BAD_RESPONSE:
                return "The server's response was not understood";
            case PGSQL_NONFATAL_ERROR:
                return 'Non-fatal error';
            case PGSQL_FATAL_ERROR:
                return 'Fatal error';
            default:
                return 'Unknown error';
        }
    }

    final public function getSqlStateCode(): string
    {
        return $this->errorFields[PGSQL_DIAG_SQLSTATE];
    }

    final public function getSqlState(): SqlState
    {
        return SqlState::fromCode($this->getSqlStateCode());
    }

    /**
     * Returns the localized severity of the error.
     *
     * @return string one of <tt>ERROR</tt>, <tt>FATAL</tt>, or <tt>PANIC</tt> (for errors), or <tt>WARNING</tt>,
     *                  <tt>NOTICE</tt>, <tt>DEBUG</tt>, <tt>INFO</tt>, or <tt>LOG</tt> (in a notice message), or a
     *                  localized translation of one of these
     */
    final public function getSeverity(): string
    {
        return $this->errorFields[PGSQL_DIAG_SEVERITY];
    }

    /**
     * Returns the nonlocalized severity of the error.
     *
     * @since PostgreSQL 9.6
     * @since PHP 7.3
     * @return string one of <tt>ERROR</tt>, <tt>FATAL</tt>, or <tt>PANIC</tt> (for errors), or <tt>WARNING</tt>,
     *                  <tt>NOTICE</tt>, <tt>DEBUG</tt>, <tt>INFO</tt>, or <tt>LOG</tt> (in a notice message);
     * @throws UnsupportedException if used in PHP < 7.3 or PostgreSQL < 9.6 as such older versions do not support the
     *                              nonlocalized severity
     */
    final public function getNonlocalizedSeverity(): string
    {
        if (PHP_VERSION_ID < 70300) {
            throw new UnsupportedException('Nonlocalized severity is only supported on PHP >= 7.3');
        }
        /** @noinspection PhpUndefinedConstantInspection */
        if (!isset($this->errorFields[PGSQL_DIAG_SEVERITY_NONLOCALIZED])) {
            throw new UnsupportedException('Nonlocalized severity is only supported on PostgreSQL >= 9.6');
        }
        /** @noinspection PhpUndefinedConstantInspection */
        return $this->errorFields[PGSQL_DIAG_SEVERITY_NONLOCALIZED];
    }

    /**
     * @return string|null the detailed message, if any
     */
    final public function getMessageDetail(): ?string
    {
        return $this->errorFields[PGSQL_DIAG_MESSAGE_DETAIL];
    }

    /**
     * @return string|null the message hint, if any
     */
    final public function getMessageHint(): ?string
    {
        return $this->errorFields[PGSQL_DIAG_MESSAGE_HINT];
    }

    /**
     * @return string the original statement, as sent by the client, which caused the error
     */
    final public function getQuery(): string
    {
        return $this->query;
    }

    /**
     * @return int|null position of the error within the original statement, returned by {@link getQuery()};
     *                  one-based, measured in characters (not bytes)
     */
    final public function getStatementPosition(): ?int
    {
        if (isset($this->errorFields[PGSQL_DIAG_STATEMENT_POSITION])) {
            return (int)$this->errorFields[PGSQL_DIAG_STATEMENT_POSITION];
        } else {
            return null;
        }
    }

    /**
     * @return string|null the text of the internally-generated query which actually caused the error (if any);
     *                     e.g., a query issued from within a PostgreSQL function
     */
    final public function getInternalQuery(): ?string
    {
        return $this->errorFields[PGSQL_DIAG_INTERNAL_QUERY];
    }

    /**
     * @return int|null position of the error within the {@link getInternalQuery() internally-generated query} which
     *                    actually caused the error (if any);
     *                  one-based, measured in characters (not bytes)
     */
    final public function getInternalPosition(): ?int
    {
        if (isset($this->errorFields[PGSQL_DIAG_INTERNAL_POSITION])) {
            return (int)$this->errorFields[PGSQL_DIAG_INTERNAL_POSITION];
        } else {
            return null;
        }
    }

    /**
     * @return string|null the PostgreSQL context of the error; e.g., the stack trace of functions and internal queries
     */
    final public function getContext(): ?string
    {
        return $this->errorFields[PGSQL_DIAG_CONTEXT];
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/api/servicecontrol/v1/metric_value.proto

namespace Google\Cloud\ServiceControl\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Represents a single metric value.
 *
 * Generated from protobuf message google.api.servicecontrol.v1.MetricValue
 */
class MetricValue extends \Google\Protobuf\Internal\Message
{
    /**
     * The labels describing the metric value.
     * See comments on [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] for
     * the overriding relationship.
     * Note that this map must not contain monitored resource labels.
     *
     * Generated from protobuf field map<string, string> labels = 1;
     */
    private $labels;
    /**
     * The start of the time period over which this metric value's measurement
     * applies. The time period has different semantics for different metric
     * types (cumulative, delta, and gauge). See the metric definition
     * documentation in the service configuration for details. If not specified,
     * [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] will be used.
     *
     * Generated from protobuf field .google.protobuf.Timestamp start_time = 2;
     */
    private $start_time = null;
    /**
     * The end of the time period over which this metric value's measurement
     * applies.  If not specified,
     * [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] will be used.
     *
     * Generated from protobuf field .google.protobuf.Timestamp end_time = 3;
     */
    private $end_time = null;
    protected $value;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type array|\Google\Protobuf\Internal\MapField $labels
     *           The labels describing the metric value.
     *           See comments on [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] for
     *           the overriding relationship.
     *           Note that this map must not contain monitored resource labels.
     *     @type \Google\Protobuf\Timestamp $start_time
     *           The start of the time period over which this metric value's measurement
     *           applies. The time period has different semantics for different metric
     *           types (cumulative, delta, and gauge). See the metric definition
     *           documentation in the service configuration for details. If not specified,
     *           [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] will be used.
     *     @type \Google\Protobuf\Timestamp $end_time
     *           The end of the time period over which this metric value's measurement
     *           applies.  If not specified,
     *           [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] will be used.
     *     @type bool $bool_value
     *           A boolean value.
     *     @type int|string $int64_value
     *           A signed 64-bit integer value.
     *     @type float $double_value
     *           A double precision floating point value.
     *     @type string $string_value
     *           A text string value.
     *     @type \Google\Cloud\ServiceControl\V1\Distribution $distribution_value
     *           A distribution value.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Api\Servicecontrol\V1\MetricValue::initOnce();
        parent::__construct($data);
    }

    /**
     * The labels describing the metric value.
     * See comments on [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] for
     * the overriding relationship.
     * Note that this map must not contain monitored resource labels.
     *
     * Generated from protobuf field map<string, string> labels = 1;
     * @return \Google\Protobuf\Internal\MapField
     */
    public function getLabels()
    {
        return $this->labels;
    }

    /**
     * The labels describing the metric value.
     * See comments on [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] for
     * the overriding relationship.
     * Note that this map must not contain monitored resource labels.
     *
     * Generated from protobuf field map<string, string> labels = 1;
     * @param array|\Google\Protobuf\Internal\MapField $var
     * @return $this
     */
    public function setLabels($var)
    {
        $arr = GPBUtil::checkMapField($var, \Google\Protobuf\Internal\GPBType::STRING, \Google\Protobuf\Internal\GPBType::STRING);
        $this->labels = $arr;

        return $this;
    }

    /**
     * The start of the time period over which this metric value's measurement
     * applies. The time period has different semantics for different metric
     * types (cumulative, delta, and gauge). See the metric definition
     * documentation in the service configuration for details. If not specified,
     * [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] will be used.
     *
     * Generated from protobuf field .google.protobuf.Timestamp start_time = 2;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getStartTime()
    {
        return $this->start_time;
    }

    public function hasStartTime()
    {
        return isset($this->start_time);
    }

    public function clearStartTime()
    {
        unset($this->start_time);
    }

    /**
     * The start of the time period over which this metric value's measurement
     * applies. The time period has different semantics for different metric
     * types (cumulative, delta, and gauge). See the metric definition
     * documentation in the service configuration for details. If not specified,
     * [google.api.servicecontrol.v1.Operation.start_time][google.api.servicecontrol.v1.Operation.start_time] will be used.
     *
     * Generated from protobuf field .google.protobuf.Timestamp start_time = 2;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setStartTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->start_time = $var;

        return $this;
    }

    /**
     * The end of the time period over which this metric value's measurement
     * applies.  If not specified,
     * [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] will be used.
     *
     * Generated from protobuf field .google.protobuf.Timestamp end_time = 3;
     * @return \Google\Protobuf\Timestamp|null
     */
    public function getEndTime()
    {
        return $this->end_time;
    }

    public function hasEndTime()
    {
        return isset($this->end_time);
    }

    public function clearEndTime()
    {
        unset($this->end_time);
    }

    /**
     * The end of the time period over which this metric value's measurement
     * applies.  If not specified,
     * [google.api.servicecontrol.v1.Operation.end_time][google.api.servicecontrol.v1.Operation.end_time] will be used.
     *
     * Generated from protobuf field .google.protobuf.Timestamp end_time = 3;
     * @param \Google\Protobuf\Timestamp $var
     * @return $this
     */
    public function setEndTime($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\Timestamp::class);
        $this->end_time = $var;

        return $this;
    }

    /**
     * A boolean value.
     *
     * Generated from protobuf field bool bool_value = 4;
     * @return bool
     */
    public function getBoolValue()
    {
        return $this->readOneof(4);
    }

    public function hasBoolValue()
    {
        return $this->hasOneof(4);
    }

    /**
     * A boolean value.
     *
     * Generated from protobuf field bool bool_value = 4;
     * @param bool $var
     * @return $this
     */
    public function setBoolValue($var)
    {
        GPBUtil::checkBool($var);
        $this->writeOneof(4, $var);

        return $this;
    }

    /**
     * A signed 64-bit integer value.
     *
     * Generated from protobuf field int64 int64_value = 5;
     * @return int|string
     */
    public function getInt64Value()
    {
        return $this->readOneof(5);
    }

    public function hasInt64Value()
    {
        return $this->hasOneof(5);
    }

    /**
     * A signed 64-bit integer value.
     *
     * Generated from protobuf field int64 int64_value = 5;
     * @param int|string $var
     * @return $this
     */
    public function setInt64Value($var)
    {
        GPBUtil::checkInt64($var);
        $this->writeOneof(5, $var);

        return $this;
    }

    /**
     * A double precision floating point value.
     *
     * Generated from protobuf field double double_value = 6;
     * @return float
     */
    public function getDoubleValue()
    {
        return $this->readOneof(6);
    }

    public function hasDoubleValue()
    {
        return $this->hasOneof(6);
    }

    /**
     * A double precision floating point value.
     *
     * Generated from protobuf field double double_value = 6;
     * @param float $var
     * @return $this
     */
    public function setDoubleValue($var)
    {
        GPBUtil::checkDouble($var);
        $this->writeOneof(6, $var);

        return $this;
    }

    /**
     * A text string value.
     *
     * Generated from protobuf field string string_value = 7;
     * @return string
     */
    public function getStringValue()
    {
        return $this->readOneof(7);
    }

    public function hasStringValue()
    {
        return $this->hasOneof(7);
    }

    /**
     * A text string value.
     *
     * Generated from protobuf field string string_value = 7;
     * @param string $var
     * @return $this
     */
    public function setStringValue($var)
    {
        GPBUtil::checkString($var, True);
        $this->writeOneof(7, $var);

        return $this;
    }

    /**
     * A distribution value.
     *
     * Generated from protobuf field .google.api.servicecontrol.v1.Distribution distribution_value = 8;
     * @return \Google\Cloud\ServiceControl\V1\Distribution|null
     */
    public function getDistributionValue()
    {
        return $this->readOneof(8);
    }

    public function hasDistributionValue()
    {
        return $this->hasOneof(8);
    }

    /**
     * A distribution value.
     *
     * Generated from protobuf field .google.api.servicecontrol.v1.Distribution distribution_value = 8;
     * @param \Google\Cloud\ServiceControl\V1\Distribution $var
     * @return $this
     */
    public function setDistributionValue($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\ServiceControl\V1\Distribution::class);
        $this->writeOneof(8, $var);

        return $this;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->whichOneof("value");
    }

}


text:
Some code that I use to crawl the web at scale with Poltergeist and
PhantomJS (cf. [stretched.io](https://github.com/jonstokes/stretched.io)). Uses a bunch of code from the venerable [anemone gem](https://github.com/chriskite/anemone). Released in the spirit of jolly cooperation.

## Installation

Add this line to your application's Gemfile:

    gem 'sunbro'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install sunbro

## Usage

I use sunbro to crawl the web at scale via Sidekiq on EC2. I've found
that web scraping with capybara/poltergeist + phantomjs is a giant pain
on JRuby (for various reasons that you'll encounter once you try it),
and this gem is basically my collection of fixes that makes it actually
work. And it works pretty well; I use in production to crawl
230 sites and counting.

Here's an example of a worker that looks something like what you might find in my code:

```ruby
class CrawlerWorker

  def perform(opts)
    @connection = Sunbro::Connection.new
    return unless @links = opts[:links]

    links.each do |link|
      next unless page = @connection.get_page(link)
      puts "Page #{page.url} returned code #{page.code} with body size #{page.body.size}"
    end

  ensure
    @connection.close
  end

end
```

The above uses `net-http` to fetch connections, and it pools
them. This is all you need most of the time. However, if you're scraping
a page that is AJAX-heavy, that's where you'll get the most out of sunbro.
To use phantomjs to scrape a page, you'll want to call `connection.render_page(link)`.
This renders the JS on the page, but doesn't download any images.

The one option to either `get_page` or `render_page` is
`:force_format`, can be one of `:html`, `:xml`, or `:auto`. If the
option is set to `:html`, then `Nokogiri::HTML` will be used to parse
`page.body`; if it's set to `:xml`, then `Nokogiri::XML` is used. If
it's set to `:auto` or `nil`, `Nokogiri.parse` is called.

## Configuration

You can configure a few options in a `config/initializers/sunbro.rb`
file, as follows:

```ruby
Sunbro::Settings.configure do |config|
  config.user_agent = ENV['USER_AGENT_STRING1']
  config.phantomjs_user_agent = ENV['USER_AGENT_STRING2']
  config.page_format = :auto
end
```

## PhantomJS zombie process monkey patch

I use the following monkey patch for PhantomJS, because it has zombie
process issues when it comes to JRuby. This monkey patch kills some minor
PhantomJS functionality that I don't use, and you can read more about
what it does and why, in [this blog post](http://jonstokes.com/2014/07/07/monkey-patching-poltergeist-for-web-scraping-with-jruby/).

I put this in `config/initializers/phantomjs.rb`

```ruby
require "capybara"
require "capybara/poltergeist"
require "capybara/poltergeist/utility"

module Capybara::Poltergeist
  Client.class_eval do
    def start
      @pid = Process.spawn(*command.map(&:to_s), pgroup: true)
      ObjectSpace.define_finalizer(self, self.class.process_killer(@pid))
    end

    def stop
      if pid
        kill_phantomjs
        ObjectSpace.undefine_finalizer(self)
      end
    end
  end
end
```

## Next steps

Right now, this is more of a bag of code than a bona fide user-friendly
gem. One next step would be to add some configuration options for PhantomJS
that get passed via `render_page` to poltergeist and then on to the
command line. Another would be to use `net-http-persistent`, which is
actually included here as a dependency but isn't yet used.

## Contributing

1. Fork it ( http://github.com/<my-github-username>/sunbro/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
namespace search
{
namespace v2
{
class SearchQueryV2 : public Query
{
public:
  SearchQueryV2(Index & index, CategoriesHolder const & categories,
                vector<Suggest> const & suggests, storage::CountryInfoGetter const & infoGetter);

  // my::Cancellable overrides:
  void Reset() override;
  void Cancel() override;

  // Query overrides:
  void Search(Results & results, size_t limit) override;
  void SearchViewportPoints(Results & results) override;
  void ClearCaches() override;

protected:
  Geocoder m_geocoder;
};
}  // namespace v2
}  // namespace search


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<body bgcolor="white">
Plug-in renderers for the {@link org.jfree.chart.plot.CategoryPlot} class.
</body>
</html>


text:
<?php

namespace Pho\Lib\Graph;

class EventsTest extends TestCase
{
    public function testNodeAdded() {
        $node_ref = null;
        $num_ref = 0;
        $this->graph->on("node.added", function($node) use (&$node_ref) {
                $node_ref = $node;
        });
        $this->graph->on("modified", function() use (&$num_ref) {
                $num_ref++;
        });
        $this->assertEquals(0, $num_ref);
        $node = new Node($this->graph);
        $this->assertEquals($node->id(), $node_ref->id());
        $this->assertEquals(1, $num_ref);
    }

    public function testNodeQuietSet() {
        $num_ref = 0;
        $node = new Node($this->graph);
        $node->on("modified", function() use (&$num_ref) {
                $num_ref++;
        });
        $this->assertEquals(0, $num_ref);
        $node->attributes()->key1 = "value";
        $this->assertEquals(1, $num_ref);
        $this->assertEquals("value", $node->attributes()->key1);
        $node->attributes()->quietSet("key2", "value");
        $this->assertEquals(1, $num_ref);
        $this->assertEquals("value", $node->attributes()->key2);
        $node->attributes()->key3 = "value";
        $this->assertEquals(2, $num_ref);
        $this->assertEquals("value", $node->attributes()->key3);
    }

    public function testEdgeCreated() {
        $ref = 0;
        $node1 = new Node($this->graph);
        $node1->on("edge.created", function() use (&$ref) {
                $this->assertTrue(true);
                $ref++;
        });
        $node2 = new Node($this->graph);
        $this->assertEquals(0, $ref);
        $edge = new Edge($node1, $node2);
        //eval(\Psy\sh());
        $this->assertEquals(1, $ref);
    } // Edge.php

    public function testEdgeCreatedWithObject() {
        $ref = "";
        $node1 = new Node($this->graph);
        $node1->on("edge.created", function($edge) use (&$ref) {
                $ref = (string) $edge->id();
        });
        $node2 = new Node($this->graph);
        $edge = new Edge($node1, $node2);
        $this->assertEquals($ref, (string) $edge->id());
    } // Edge.php

    public function testEdgeConnectedWithObject() {
        $ref1 = "";
        $ref2 = "";
        $node1 = new Node($this->graph);
        $node2 = new Node($this->graph);
        $node2->on("edge.connected", function($edge) use (&$ref2) {
                $ref2 = (string) $edge->id();
        });
        $edge = new Edge($node1, $node2);
        $this->assertEquals($ref2, (string) $edge->id());
    } // Edge.php

    public function testEdgeConnected() {
        $ref1 = 0;
        $ref2 = 0;
        $node1 = new Node($this->graph);
        $node2 = new Node($this->graph);
        $node1->on("edge.created", function() use (&$ref1) {
                $this->assertTrue(true);
                $ref1++;
        });
        $node2->on("edge.connected", function() use (&$ref2) {
                $this->assertTrue(true);
                $ref2++;
        });

        $edge = new Edge($node1);
        $this->assertEquals(1, $ref1);
        $this->assertEquals(0, $ref2);
        $this->assertTrue($edge->orphan());
        $edge->connect($node2);
        $this->assertEquals(1, $ref1);
        $this->assertEquals(1, $ref2);
    } // Edge.php

    public function testNodeModified() {
        $ref = 0;
        $node = new Node($this->graph);
        $node->on("modified", function() use (&$ref) {
                $this->assertTrue(true);
                $ref++;
        });
        $node->attributes()->color = "red";
        $this->assertEquals(1, $ref);
    } // EntityTrait.php

    public function testEdgeModified() {
        $ref_node = $ref_edge = 0;
        $node = new Node($this->graph);
        $edge = new Edge($node);
        $node->on("modified", function() use (&$ref_node) {
            $this->assertTrue(true);
            $ref_node++;
        });
        $edge->on("modified", function() use (&$ref_edge, $edge) {
                $this->assertTrue(true);
                $ref_edge++;
        });
        $edge->attributes()->color = "blue";
        $this->assertEquals(0, $ref_node);
        $this->assertEquals(1, $ref_edge);
    } // EntityTrait.php

    public function testNodeDeleting() {
        $ref = $ref2 = 0;
        $node = new Node($this->graph);
        $node->on("deleting", function() use (&$ref) {
                $this->assertTrue(true);
                $ref++;
        });
        $this->graph->on("modified", function() use (&$ref2) {
            $ref2++;
        });
        $node->destroy();
        $this->assertEquals(1, $ref);
        $this->assertEquals(1, $ref2);
    } // Node
}